granttap-mcp 0.8.134 → 0.8.135

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/README.md +7 -0
  2. package/SECURITY.md +5 -0
  3. package/apps/bridge/src/bin/runtime/monitor.ts +3 -0
  4. package/apps/bridge/src/device-management/maintenance.ts +19 -1
  5. package/apps/bridge/src/mesh/store/base.ts +7 -0
  6. package/apps/bridge/src/mesh/tasks/create-task.ts +7 -3
  7. package/apps/bridge/src/monitor/handlers/receipts.ts +10 -0
  8. package/apps/bridge/src/monitor/handlers/user-message.ts +1 -1
  9. package/apps/bridge/src/monitor/support/leadership.ts +13 -0
  10. package/apps/bridge/src/monitor/support/session-activity.ts +2 -2
  11. package/apps/bridge/src/runtime-watchdog/README.md +25 -0
  12. package/apps/bridge/src/runtime-watchdog/index.ts +34 -0
  13. package/apps/bridge/src/runtime-watchdog/policy.d.mts +12 -0
  14. package/apps/bridge/src/runtime-watchdog/policy.mjs +76 -0
  15. package/apps/bridge/src/runtime-watchdog/worker.mjs +48 -0
  16. package/apps/bridge/src/sessions/index.ts +10 -1
  17. package/apps/bridge/src/sessions/scan/claude/activity.ts +100 -64
  18. package/apps/bridge/src/sessions/scan/claude/parse.ts +118 -32
  19. package/apps/bridge/src/sessions/scan/claude/recorded-usage/index.ts +3 -2
  20. package/apps/bridge/src/sessions/scan/claude/scan.ts +2 -2
  21. package/apps/bridge/src/sessions/scan/claude/shared.ts +2 -0
  22. package/apps/bridge/src/task-dispatch/README.md +4 -0
  23. package/apps/bridge/src/task-dispatch/worker/monitor.ts +27 -5
  24. package/apps/bridge/src/task-dispatch/worker/readiness.ts +6 -0
  25. package/cursor-plugin/README.md +1 -1
  26. package/cursor-plugin/mcp.json +1 -1
  27. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  28. package/package.json +1 -1
  29. package/packages/core/task-dispatch/index.ts +6 -1
  30. package/packages/protocol/messages/interaction/index.ts +12 -0
  31. package/packages/protocol/schema.ts +2 -0
package/README.md CHANGED
@@ -856,6 +856,13 @@ The relay can retain recipient-encrypted catalogs, Mesh snapshots, capability us
856
856
 
857
857
  Tools & Skills matches recorded usage to the exact computer, provider and execution. Codex's native history projection supplies actual MCP invocation IDs, results and durations, including calls made through Code Mode. Claude Code uses observed tool-use, result and Skill records, aggregating MCP and skill calls before its recent-detail cache is trimmed. Execution summaries remain available when older call details fall outside the recent-event budget. Counts describe recorded evidence; installation and permission do not prove usage. Missing resource measurements remain unknown. See [native capability history](apps/bridge/src/sessions/native-capability-history/README.md).
858
858
 
859
+ ## Hang recovery
860
+
861
+ If the background monitor stops responding for two minutes, it records the fault and
862
+ restarts as a clean process, at most three times an hour. Past that it stays up and
863
+ only reports, so a recurring hang cannot become a restart loop. Sleep does not count.
864
+ See the [runtime watchdog](apps/bridge/src/runtime-watchdog/README.md).
865
+
859
866
  ## Automatic runtime updates
860
867
 
861
868
  Installed GrantTap background services check for stable MCP updates automatically.
package/SECURITY.md CHANGED
@@ -20,6 +20,11 @@ credential used for authenticated WebSocket and APNs registration.
20
20
  Provider credentials remain in each provider's own local authentication flow.
21
21
  GrantTap does not send them to the relay.
22
22
 
23
+ If the background monitor hangs, the [runtime watchdog](apps/bridge/src/runtime-watchdog/README.md)
24
+ sends the site a fault report holding only the fault kind, duration, restart count,
25
+ GrantTap and Node versions, platform and architecture. It never holds a prompt, path,
26
+ room, key or computer name. `GRANTTAP_DISABLE_FAULT_REPORTS=1` turns sending off.
27
+
23
28
  Installed Claude Code, Codex, and Cursor hooks deny direct agent tool calls
24
29
  that name GrantTap's local pairing, key, or policy files, including calls that
25
30
  would otherwise be auto-accepted or run in provider bypass mode. The denial
@@ -16,6 +16,7 @@ import { applyNetworkRoute } from "../../device-network/settings";
16
16
  import { startEndpointPublisher } from "../../device-network/directory";
17
17
  import { managedAdmissionOptions } from "../../managed-admission";
18
18
  import { publishStableNode } from "../../install/stable-node/index";
19
+ import { startRuntimeWatchdog } from "../../runtime-watchdog";
19
20
 
20
21
  import { startTaskDispatchMonitor } from "../../task-dispatch/worker/monitor";
21
22
  import { startTaskNetworkMonitor } from '../../task-network/runtime';
@@ -30,6 +31,7 @@ let stopTaskNetwork = () => {};
30
31
  let stopEngineRecovery = () => {};
31
32
  let stopRuntimeUpdates = () => {};
32
33
  let stopUpdateReadiness = () => {};
34
+ const stopWatchdog = startRuntimeWatchdog();
33
35
 
34
36
  publishStableNode();
35
37
 
@@ -59,6 +61,7 @@ try {
59
61
  const stop = (): void => {
60
62
  if (stopping) return;
61
63
  stopping = true;
64
+ stopWatchdog();
62
65
  stopRuntimeUpdates();
63
66
  stopUpdateReadiness();
64
67
  stopEngineRecovery();
@@ -9,7 +9,8 @@ import type { CodingAgent, DeviceManagementSnapshot } from '../../../../packages
9
9
  import { configDir } from '../config/runtime/paths';
10
10
  import { observedComputerId } from '../mesh/identity/computer';
11
11
  import { automaticUpdatesAllowed } from '../runtime-updates/preferences/storage.mjs';
12
- import { readState, runtimeVersion } from '../runtime-updates/selection.mjs';
12
+ import { newerVersion, readState, runtimeVersion } from '../runtime-updates/selection.mjs';
13
+ import { latestRelease, trustedRelease } from '../runtime-updates/registry';
13
14
  import { checkForRuntimeUpdate } from '../runtime-updates';
14
15
  import { binaryVersion } from '../tools/version';
15
16
  import { providerCommand, providerAuthentication, installedProvider, providerEnvironment } from './provider-command';
@@ -39,6 +40,22 @@ export function maintenanceIdle(): boolean {
39
40
  && agents.every(agent => ownedProviderProcesses(providerCommand(agent)).length === 0);
40
41
  }
41
42
 
43
+ const RELEASE_CHECK_MS = 60 * 60_000;
44
+ let knownRelease: { at: number; version?: string } = { at: 0 };
45
+
46
+ /** The phone offers an update from this answer; a registry problem only hides the offer. */
47
+ async function availableRuntimeVersion(): Promise<string | undefined> {
48
+ if (Date.now() - knownRelease.at >= RELEASE_CHECK_MS) {
49
+ knownRelease = { at: Date.now(), version: knownRelease.version };
50
+ try {
51
+ const release = await latestRelease();
52
+ if (trustedRelease(release)) knownRelease.version = release.version;
53
+ } catch { /* Keep what was last known. */ }
54
+ }
55
+ const version = knownRelease.version;
56
+ return version && newerVersion(version, runtimeVersion(runtimeRoot)) ? version : undefined;
57
+ }
58
+
42
59
  export async function managementSnapshot(): Promise<DeviceManagementSnapshot> {
43
60
  const observedAt = Date.now();
44
61
  const directory = join(configDir(), 'runtime-updates');
@@ -52,6 +69,7 @@ export async function managementSnapshot(): Promise<DeviceManagementSnapshot> {
52
69
  }));
53
70
  return { computerId: observedComputerId(), computerName: hostname(), observedAt,
54
71
  runtimeVersion: runtimeVersion(runtimeRoot), runtimeEpoch, selectedRuntimeVersion: selected.version,
72
+ availableRuntimeVersion: await availableRuntimeVersion(),
55
73
  automaticUpdatesEnabled: automaticUpdatesAllowed(directory),
56
74
  runtimeUpdateSupported: runtimeRoot.includes('/node_modules/'), runtimeRestartSupported: runtimeRestartSupported(),
57
75
  cache: (await computerCache(runtimeRoot)).map(({ paths: _paths, ...category }) => category), providers };
@@ -227,6 +227,13 @@ export class MeshStoreBase {
227
227
  return bindingForEndpoint(this.state.bindings, repositoryId, endpointId);
228
228
  }
229
229
 
230
+ /** A folder this computer registered for a Project, whichever agent worked there. */
231
+ hasLocalBinding(projectId: string, localPath: string, endpointId: string): boolean {
232
+ this.sync();
233
+ return this.state.bindings.some((item) => item.projectId === projectId
234
+ && item.endpointId === endpointId && item.available && item.localPathHint === localPath);
235
+ }
236
+
230
237
  upsertTask(input: TaskValue): void {
231
238
  this.sync();
232
239
  const task = MeshTask.parse(input);
@@ -55,11 +55,15 @@ export function evaluateCreateTask(input: {
55
55
  now?: number;
56
56
  }): CreateTaskEvaluation {
57
57
  const endpoint = input.localEndpointId ?? computerId();
58
- const known = [...scanSessions().sessions, ...scanSessionHistory()].some((session) =>
59
- session.agent === input.agent && session.cwd === input.cwd);
58
+ const store = localMeshStore();
59
+ const requestedProjectId = input.projectId?.trim();
60
+ // The Mesh composer offers folders this computer registered for the Project.
61
+ // Its agent choice is free, so one that never ran there is not a stranger.
62
+ const known = (requestedProjectId && store.hasLocalBinding(requestedProjectId, input.cwd, endpoint))
63
+ || [...scanSessions().sessions, ...scanSessionHistory()].some((session) =>
64
+ session.agent === input.agent && session.cwd === input.cwd);
60
65
  if (!known) return { ok: false, reason: "unknown_workspace", detail: DETAILS.unknown_workspace };
61
66
  const repository = inspectRepository(input.cwd);
62
- const store = localMeshStore();
63
67
  const resolved = resolveCreateTaskProject({
64
68
  requestedProjectId: input.projectId,
65
69
  endpointBinding: store.bindingForEndpoint(repository.canonicalRepositoryId, endpoint),
@@ -31,6 +31,16 @@ export async function sendDeliveryReceipt(
31
31
  : client.send(payload, "phone", options)).catch(() => {});
32
32
  }
33
33
 
34
+ /** The message reached this computer. The relay repeats offers, so the caller sends this once. */
35
+ export async function sendDeliveryArrival(client: RelayClient, messageId: string, sessionId: string | undefined,
36
+ peerPublicKey: string | undefined): Promise<void> {
37
+ const payload = { type: "delivery.arrival" as const, messageId, sessionId: sessionId?.trim() || undefined, receivedAt: Date.now() };
38
+ const options = { ttlMs: 24 * 60 * 60_000, peerPublicKey };
39
+ await (sessionId && !peerPublicKey
40
+ ? sendSessionPayload(client, payload, sessionId, "phone", options)
41
+ : client.send(payload, "phone", options)).catch(() => {});
42
+ }
43
+
34
44
  export function agentEventForUserMessage(
35
45
  message: UserMessage,
36
46
  text: string,
@@ -91,7 +91,7 @@ async function startNewAgentTask(input: {
91
91
  let run: Promise<ReplyResult>;
92
92
  try {
93
93
  run = create(projectGuidancePrompt(admittedProjectId, message.text), requestedCwd, PHONE_RUN_LIMIT_MS, resolved.attachments,
94
- message.model, undefined, message.effort).catch(() => {
94
+ message.model, message.messageId, message.effort).catch(() => {
95
95
  input.origin?.registry.complete(input.origin.scope, { ok: true });
96
96
  return { ok: false, error: 'The provider task stopped unexpectedly.' } as ReplyResult;
97
97
  });
@@ -110,8 +110,21 @@ export function monitorLeadership(
110
110
  writeFileSync(path, token, { mode: 0o600 });
111
111
  };
112
112
 
113
+ /** A monitor that is gone cannot renew; its successor need not wait out the lease. */
114
+ const holderGone = (): boolean => {
115
+ const holder = Number(read()?.split(":", 1)[0]);
116
+ if (!Number.isSafeInteger(holder) || holder < 1) return false;
117
+ try {
118
+ process.kill(holder, 0);
119
+ return false;
120
+ } catch (error) {
121
+ return (error as NodeJS.ErrnoException).code === "ESRCH";
122
+ }
123
+ };
124
+
113
125
  /** A lease nobody renewed is free, whatever process now owns that id. */
114
126
  const expired = (): boolean => {
127
+ if (holderGone()) return true;
115
128
  try {
116
129
  return now() - statSync(path).mtimeMs > LEADERSHIP_TTL_MS;
117
130
  } catch {
@@ -1,5 +1,5 @@
1
1
  import type { SessionActivity, SessionInfo } from "../../../../../packages/protocol/schema";
2
- import { scanSessionActivity } from "../../sessions";
2
+ import { scanChildActivity, scanSessionActivity } from "../../sessions";
3
3
  import { readTranscriptHistory } from "../../transcript-history";
4
4
 
5
5
  type ActivityReader = (session: SessionInfo) => SessionActivity;
@@ -62,6 +62,6 @@ export const cachedSessionActivity = sessionActivityCache((session) => {
62
62
  const history = readTranscriptHistory(session);
63
63
  if (!history) return scanSessionActivity(session);
64
64
  if (!session.childThreads?.length) return history;
65
- const children = scanSessionActivity(session).entries.filter((entry) => entry.childThreadId);
65
+ const children = scanChildActivity(session);
66
66
  return { ...history, entries: [...history.entries, ...children].sort((a, b) => a.createdAt - b.createdAt) };
67
67
  });
@@ -0,0 +1,25 @@
1
+ # Runtime watchdog
2
+
3
+ [Monitor](../monitor/README.md) · [Runtime updates](../runtime-updates/README.md)
4
+
5
+ The monitor is one event loop. If it hangs, nothing inside it can notice. A worker
6
+ thread watches a heartbeat the loop writes every second. After 120 seconds without
7
+ one, it records a fault, tries to send it to the site, and kills the process so the
8
+ service manager starts a clean one.
9
+
10
+ Restarts are bounded: at most three per hour, counted in a file that survives them.
11
+ Past that the process stays up and only reports. Sleep is not a hang: a gap in the
12
+ watchdog's own timer starts a fresh grace period. A monitor started by hand reports
13
+ and is never killed, because nothing would bring it back.
14
+
15
+ A report holds only the fault kind, duration, action, restart count, GrantTap version,
16
+ Node version, platform and architecture. It never holds a prompt, path, room, key or
17
+ computer name. Unsent reports stay in `runtime-watchdog/pending-reports.json` in the
18
+ private configuration folder until the site confirms them.
19
+ `GRANTTAP_DISABLE_FAULT_REPORTS=1` turns sending off and keeps the local record.
20
+
21
+ Public entry: `startRuntimeWatchdog`. Tests hang a real process and check the kill,
22
+ the spent budget, the sent report and the sleep case.
23
+
24
+ License: this module is distributed under the GrantTap Commercial Source License
25
+ in the repository-root `LICENSE` file.
@@ -0,0 +1,34 @@
1
+ import { join } from 'node:path';
2
+ import { Worker } from 'node:worker_threads';
3
+ import { configDir } from '../config';
4
+
5
+ export const FAULT_REPORT_URL = 'https://granttap.com/api/runtime-faults';
6
+ const BEAT_MS = 1_000;
7
+
8
+ /** Starts the monitor's hang watchdog. Its failure to start never stops the monitor. */
9
+ export function startRuntimeWatchdog(options: { version?: string; restartAllowed?: boolean; reportUrl?: string;
10
+ directory?: string; stallMs?: number; checkMs?: number } = {}): () => void {
11
+ try {
12
+ const buffer = new SharedArrayBuffer(8);
13
+ const beat = new BigInt64Array(buffer);
14
+ const touch = () => { Atomics.store(beat, 0, BigInt(Date.now())); };
15
+ touch();
16
+ const timer = setInterval(touch, BEAT_MS);
17
+ timer.unref();
18
+ const reportsAllowed = process.env.GRANTTAP_DISABLE_FAULT_REPORTS !== '1';
19
+ const worker = new Worker(new URL('./worker.mjs', import.meta.url), {
20
+ execArgv: [],
21
+ workerData: { buffer, directory: options.directory ?? join(configDir(), 'runtime-watchdog'),
22
+ version: options.version ?? process.env.GRANTTAP_PACKAGE_VERSION ?? 'unknown',
23
+ reportUrl: reportsAllowed ? options.reportUrl ?? FAULT_REPORT_URL : undefined,
24
+ // Only a managed service comes back after the kill; a monitor started by hand just reports.
25
+ restartAllowed: options.restartAllowed ?? process.env.GRANTTAP_MONITOR_PRIMARY === '1',
26
+ ...(options.stallMs ? { stallMs: options.stallMs } : {}), ...(options.checkMs ? { checkMs: options.checkMs } : {}) },
27
+ });
28
+ worker.unref();
29
+ worker.on('error', () => { clearInterval(timer); });
30
+ return () => { clearInterval(timer); void worker.terminate(); };
31
+ } catch {
32
+ return () => {};
33
+ }
34
+ }
@@ -0,0 +1,12 @@
1
+ export const STALL_MS: number;
2
+ export const CHECK_MS: number;
3
+ export const RESTART_LIMIT: number;
4
+ export const RESTART_WINDOW_MS: number;
5
+ export function nextStep(input: { now: number; lastCheck: number; beat: number; graceUntil: number; reported: boolean;
6
+ stallMs?: number; checkMs?: number }): { graceUntil: number; stalled: boolean; recovered: boolean };
7
+ export function spendRestart(directory: string, now: number, limit?: number, windowMs?: number):
8
+ { restart: boolean; restartsInWindow: number };
9
+ export function faultReport(input: { id: string; kind: string; at: number; stalledMs: number; action: string;
10
+ restartsInWindow: number; version: string }): Record<string, unknown>;
11
+ export function rememberFault(directory: string, report: Record<string, unknown>): void;
12
+ export function sendPendingFaults(directory: string, url: string, request?: typeof fetch): Promise<number>;
@@ -0,0 +1,76 @@
1
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+
4
+ export const STALL_MS = 120_000;
5
+ export const CHECK_MS = 5_000;
6
+ export const RESTART_LIMIT = 3;
7
+ export const RESTART_WINDOW_MS = 60 * 60_000;
8
+ const PENDING_REPORT_LIMIT = 50;
9
+
10
+ function readJson(path, fallback) {
11
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return fallback; }
12
+ }
13
+
14
+ function writeJson(directory, name, value) {
15
+ mkdirSync(directory, { recursive: true, mode: 0o700 });
16
+ const path = join(directory, name), next = `${path}.${process.pid}.tmp`;
17
+ writeFileSync(next, JSON.stringify(value), { mode: 0o600 });
18
+ renameSync(next, path);
19
+ }
20
+
21
+ /** One step of the watchdog loop. A gap in its own timer means the computer slept, not a hang. */
22
+ export function nextStep(input) {
23
+ const { now, lastCheck, beat, graceUntil, reported, stallMs = STALL_MS, checkMs = CHECK_MS } = input;
24
+ const slept = now - lastCheck > checkMs * 3;
25
+ const grace = slept ? now + stallMs : graceUntil;
26
+ const stalled = now - beat >= stallMs && now >= grace;
27
+ return { graceUntil: grace, stalled, recovered: !stalled && reported && now - beat < stallMs };
28
+ }
29
+
30
+ /**
31
+ * The restart budget survives the restart it pays for. Once it is spent the
32
+ * process stays up and only reports, so a hang that returns after every start
33
+ * cannot become an endless restart.
34
+ */
35
+ export function spendRestart(directory, now, limit = RESTART_LIMIT, windowMs = RESTART_WINDOW_MS) {
36
+ const recent = readJson(join(directory, 'restarts.json'), [])
37
+ .filter(at => Number.isFinite(at) && now - at < windowMs && at <= now);
38
+ if (recent.length >= limit) return { restart: false, restartsInWindow: recent.length };
39
+ recent.push(now);
40
+ writeJson(directory, 'restarts.json', recent);
41
+ return { restart: true, restartsInWindow: recent.length };
42
+ }
43
+
44
+ /** Only these fields leave the computer: no prompt, path, room, key or computer name. */
45
+ export function faultReport(input) {
46
+ return { id: input.id, kind: input.kind, at: input.at, stalledMs: input.stalledMs, action: input.action,
47
+ restartsInWindow: input.restartsInWindow, version: input.version, node: process.versions.node,
48
+ platform: process.platform, arch: process.arch };
49
+ }
50
+
51
+ export function rememberFault(directory, report) {
52
+ const pending = readJson(join(directory, 'pending-reports.json'), []);
53
+ pending.push(report);
54
+ writeJson(directory, 'pending-reports.json', pending.slice(-PENDING_REPORT_LIMIT));
55
+ }
56
+
57
+ /** Reports wait on this computer until the site confirms them, so a hang offline is not lost. */
58
+ export async function sendPendingFaults(directory, url, request = fetch) {
59
+ const pending = readJson(join(directory, 'pending-reports.json'), []);
60
+ const delivered = new Set();
61
+ for (const report of pending) {
62
+ try {
63
+ const response = await request(url, { method: 'POST', redirect: 'error',
64
+ headers: { 'content-type': 'application/json' }, body: JSON.stringify(report),
65
+ signal: AbortSignal.timeout(5_000) });
66
+ // The site refused this report for good; it must not hold back the others.
67
+ if (response.status === 400) { delivered.add(report.id); continue; }
68
+ if (!response.ok) break;
69
+ delivered.add(report.id);
70
+ } catch { break; }
71
+ }
72
+ if (!delivered.size) return 0;
73
+ const current = readJson(join(directory, 'pending-reports.json'), []);
74
+ writeJson(directory, 'pending-reports.json', current.filter(report => !delivered.has(report.id)));
75
+ return delivered.size;
76
+ }
@@ -0,0 +1,48 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { workerData } from 'node:worker_threads';
3
+ import { CHECK_MS, STALL_MS, faultReport, nextStep, rememberFault, sendPendingFaults, spendRestart } from './policy.mjs';
4
+
5
+ /**
6
+ * This thread keeps its own event loop, so it still runs when the monitor's is
7
+ * stuck. A stuck loop cannot run a shutdown handler either, which is why the
8
+ * restart is a kill: the launcher exits with it and the service manager starts
9
+ * a clean process. Durable jobs are not replayed after that; an attempt that
10
+ * was running is reported as needing confirmation.
11
+ */
12
+ const { buffer, directory, version, reportUrl, restartAllowed, stallMs = STALL_MS, checkMs = CHECK_MS } = workerData;
13
+ const beat = new BigInt64Array(buffer);
14
+ const send = () => reportUrl ? sendPendingFaults(directory, reportUrl).catch(() => 0) : Promise.resolve(0);
15
+ const within = (work, ms) => Promise.race([work, new Promise(resolve => setTimeout(resolve, ms))]);
16
+
17
+ let lastCheck = Date.now(), graceUntil = 0, reported = false, busy = false;
18
+ const record = (kind, stalledMs, action, restartsInWindow) => {
19
+ rememberFault(directory, faultReport({ id: randomUUID(), kind, at: Date.now(), stalledMs, action, restartsInWindow, version }));
20
+ };
21
+
22
+ async function check() {
23
+ if (busy) return;
24
+ busy = true;
25
+ try {
26
+ const now = Date.now(), last = Number(Atomics.load(beat, 0));
27
+ const step = nextStep({ now, lastCheck, beat: last, graceUntil, reported, stallMs, checkMs });
28
+ lastCheck = now; graceUntil = step.graceUntil;
29
+ if (step.recovered) {
30
+ reported = false;
31
+ record('event-loop-recovered', 0, 'none', 0);
32
+ await send();
33
+ return;
34
+ }
35
+ if (!step.stalled) return;
36
+ const budget = restartAllowed ? spendRestart(directory, now) : { restart: false, restartsInWindow: 0 };
37
+ if (!budget.restart && reported) return;
38
+ record('event-loop-stall', now - last, budget.restart ? 'restart' : 'held', budget.restartsInWindow);
39
+ reported = true;
40
+ await within(send(), 5_000);
41
+ if (budget.restart) process.kill(process.pid, 'SIGKILL');
42
+ } catch { /* A watchdog fault must never become the monitor's fault. */ }
43
+ finally { busy = false; }
44
+ }
45
+
46
+ setInterval(() => void check(), checkMs);
47
+ void send();
48
+ setInterval(() => void send(), 60 * 60_000).unref();
@@ -31,6 +31,7 @@ import {
31
31
  } from "./cursor";
32
32
  import { grokCapabilityUsage } from "./scan/grok";
33
33
  import { activityForSession } from './session-activity';
34
+ import { localTaskTransfers } from "../task-transfer";
34
35
  export { MAX_THREAD_ENTRIES, scanThreadActivity } from './session-activity';
35
36
  import {
36
37
  limitCapabilityUsageEvents,
@@ -40,7 +41,7 @@ import {
40
41
  import { createCapabilityTotals } from "./support/capability-totals";
41
42
  import { createExecutionSummaries, budgetExecutionSummaries } from './telemetry/execution-summaries';
42
43
  import { readCodexCapabilityHistory, type NativeCapabilityEvidence } from './native-capability-history';
43
- import { recordedClaudeUsage } from './scan/claude';
44
+ import { claudeChildActivity, recordedClaudeUsage } from './scan/claude';
44
45
 
45
46
  export { MAX_ACTIVITY_ENTRIES, MAX_ACTIVITY_TEXT, TOKEN_WINDOW_HOURS };
46
47
  export { nativeTranscriptRoots, nativeTranscriptSource, restoreNativeTranscriptSource } from "./native-source";
@@ -78,6 +79,14 @@ export function pickActivityEntries(all: ActivityEntry[], limit: number): Activi
78
79
  return [...byId.values()].sort((a, b) => a.createdAt - b.createdAt);
79
80
  }
80
81
 
82
+ /** Subagent rows of a chat whose own transcript already has a bounded reader. */
83
+ export function scanChildActivity(input: SessionInfo): ActivityEntry[] {
84
+ const session = localTaskTransfers().nativeSession(input);
85
+ const entries = session.agent === "claude" ? claudeChildActivity(session)
86
+ : scanSessionActivity(input).entries;
87
+ return pickActivityEntries(entries.filter((entry) => entry.childThreadId), MAX_ACTIVITY_ENTRIES);
88
+ }
89
+
81
90
  export function scanSessionActivity(session: SessionInfo): SessionActivity {
82
91
  // A Project rule that refused something is part of what happened in this
83
92
  // chat, so it is shown there, beside the call it stopped.
@@ -59,6 +59,19 @@ export function claudeCapabilityUsage(
59
59
  lines = claudeLogLines(session.sessionId);
60
60
  }
61
61
  if (!lines) return [];
62
+ const collector = createClaudeCapabilityCollector(() => session, sourceThreadId);
63
+ for (const line of lines) {
64
+ const row = safeParse(line);
65
+ if (row) collector.add(row);
66
+ }
67
+ return collector.snapshot();
68
+ }
69
+
70
+ type CapabilitySessionContext = Pick<SessionInfo, "sessionId" | "lastActivityAt" | "cwd">;
71
+
72
+ /** Observes one transcript row at a time, so a growing log is never read twice. */
73
+ export function createClaudeCapabilityCollector(session: () => CapabilitySessionContext,
74
+ sourceThreadId?: string) {
62
75
  const pending = new Map<string, PendingCapabilityTool>();
63
76
  const out: CapabilityObservation[] = [];
64
77
  const recorder = createClaudeUsageRecorder();
@@ -66,72 +79,78 @@ export function claudeCapabilityUsage(
66
79
  recorder.remember(observation);
67
80
  rememberCapabilityObservation(out, observation);
68
81
  };
69
-
70
82
  let commandOrdinal = 0;
71
- for (const line of lines) {
72
- const row = safeParse(line);
73
- if (!row) continue;
74
- const rowAt = ts(row.timestamp);
75
- // A skill the person invoked as a slash command never becomes a tool call;
76
- // the host writes it as a user turn. It is a skill used all the same.
77
- const command = slashCommandSkill(row);
78
- if (command) {
79
- commandOrdinal += 1;
80
- remember({
81
- sourceId: `${sourceThreadId}:command:${typeof row.uuid === "string" ? row.uuid : commandOrdinal}`,
82
- sessionId: session.sessionId,
83
- toolName: `/${command}`,
84
- skill: command,
85
- createdAt: rowAt || session.lastActivityAt,
86
- outcome: "success",
87
- });
88
- continue;
89
- }
90
- if (!Array.isArray(row.message?.content)) continue;
91
- for (const block of row.message.content as any[]) {
92
- if (
93
- block?.type === "tool_use" &&
94
- typeof block.id === "string" &&
95
- typeof block.name === "string"
96
- ) {
97
- const item: PendingCapabilityTool = {
98
- sourceId: `${sourceThreadId}:${block.id}`,
99
- sessionId: session.sessionId,
100
- toolName: block.name,
101
- input: block.input,
102
- createdAt: rowAt || session.lastActivityAt,
103
- cwd: session.cwd ?? undefined,
104
- };
105
- for (const path of writtenPaths(item.toolName, item.input)) {
106
- recordObservedWrite(session.sessionId, path, item.createdAt);
83
+ return {
84
+ add(row: any): void {
85
+ const { sessionId, lastActivityAt, cwd } = session();
86
+ const source = sourceThreadId ?? sessionId;
87
+ const rowAt = ts(row.timestamp);
88
+ // A skill the person invoked as a slash command never becomes a tool call;
89
+ // the host writes it as a user turn. It is a skill used all the same.
90
+ const command = slashCommandSkill(row);
91
+ if (command) {
92
+ commandOrdinal += 1;
93
+ remember({
94
+ sourceId: `${source}:command:${typeof row.uuid === "string" ? row.uuid : commandOrdinal}`,
95
+ sessionId,
96
+ toolName: `/${command}`,
97
+ skill: command,
98
+ createdAt: rowAt || lastActivityAt,
99
+ outcome: "success",
100
+ });
101
+ return;
102
+ }
103
+ if (!Array.isArray(row.message?.content)) return;
104
+ for (const block of row.message.content as any[]) {
105
+ if (
106
+ block?.type === "tool_use" &&
107
+ typeof block.id === "string" &&
108
+ typeof block.name === "string"
109
+ ) {
110
+ const item: PendingCapabilityTool = {
111
+ sourceId: `${source}:${block.id}`,
112
+ sessionId,
113
+ toolName: block.name,
114
+ input: block.input,
115
+ createdAt: rowAt || lastActivityAt,
116
+ cwd: cwd ?? undefined,
117
+ };
118
+ for (const path of writtenPaths(item.toolName, item.input)) {
119
+ recordObservedWrite(sessionId, path, item.createdAt);
120
+ }
121
+ if (pendingCapabilityObservation(item)) {
122
+ rememberPendingCapabilityCall(pending, block.id, item);
123
+ }
124
+ continue;
107
125
  }
108
- if (pendingCapabilityObservation(item)) {
109
- rememberPendingCapabilityCall(pending, block.id, item);
126
+ if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") {
127
+ continue;
110
128
  }
111
- continue;
129
+ const item = pending.get(block.tool_use_id);
130
+ if (!item) continue;
131
+ const observation =
132
+ observeCapability(item, block.content, rowAt || item.createdAt, {
133
+ outcome: block.is_error === true ? "error" : "success",
134
+ errorClass: block.is_error === true ? "tool_result" : undefined,
135
+ }, "claude") ??
136
+ pendingCapabilityObservation(item);
137
+ if (observation) remember(observation);
138
+ pending.delete(block.tool_use_id);
112
139
  }
113
- if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") {
114
- continue;
140
+ },
141
+ /** Calls without a result yet are reported as pending; the collector keeps waiting for them. */
142
+ snapshot(): CapabilityObservation[] {
143
+ const result = [...out];
144
+ for (const item of pending.values()) {
145
+ const observation = pendingCapabilityObservation(item);
146
+ if (!observation) continue;
147
+ recorder.remember(observation);
148
+ rememberCapabilityObservation(result, observation);
115
149
  }
116
- const item = pending.get(block.tool_use_id);
117
- if (!item) continue;
118
- const observation =
119
- observeCapability(item, block.content, rowAt || item.createdAt, {
120
- outcome: block.is_error === true ? "error" : "success",
121
- errorClass: block.is_error === true ? "tool_result" : undefined,
122
- }, "claude") ??
123
- pendingCapabilityObservation(item);
124
- if (observation) remember(observation);
125
- pending.delete(block.tool_use_id);
126
- }
127
- }
128
-
129
- for (const item of pending.values()) {
130
- const observation = pendingCapabilityObservation(item);
131
- if (observation) remember(observation);
132
- }
133
- recorder.finish(out);
134
- return out;
150
+ recorder.finish(result, true);
151
+ return result;
152
+ },
153
+ };
135
154
  }
136
155
 
137
156
  /**
@@ -281,6 +300,26 @@ export function claudeActivity(session: SessionInfo): ActivityEntry[] {
281
300
  const out: ActivityEntry[] = [];
282
301
  const seen = new Set<string>();
283
302
  appendClaudeActivity({ out, seen, session, lines, observations });
303
+ appendClaudeChildActivity(session, out, seen, observations);
304
+ // V8 sort is stable: preserve transcript order when a provider stamps a
305
+ // whole batch with the same millisecond. Source ids are not chronological.
306
+ return out.sort((a, b) => a.createdAt - b.createdAt);
307
+ }
308
+
309
+ /**
310
+ * Nested threads only. A chat's own transcript can be 100 MB and has a bounded
311
+ * reader, so asking for its subagents must not read that transcript again.
312
+ */
313
+ export function claudeChildActivity(session: SessionInfo): ActivityEntry[] {
314
+ const file = claudeLogPathBySession.get(session.sessionId);
315
+ const known = file ? claudeSummaryCache.get(file)?.observations ?? [] : [];
316
+ const out: ActivityEntry[] = [];
317
+ appendClaudeChildActivity(session, out, new Set<string>(), new Map(known.map((item) => [item.sourceId, item])));
318
+ return out.sort((a, b) => a.createdAt - b.createdAt);
319
+ }
320
+
321
+ function appendClaudeChildActivity(session: SessionInfo, out: ActivityEntry[], seen: Set<string>,
322
+ observations: Map<string, CapabilityObservation>): void {
284
323
  const childById = new Map(session.childThreads?.map((child) => [child.threadId, child]));
285
324
  for (const path of claudeChildLogPathsBySession.get(session.sessionId) ?? []) {
286
325
  const childLines = readLines(path);
@@ -289,7 +328,4 @@ export function claudeActivity(session: SessionInfo): ActivityEntry[] {
289
328
  const child = childById.get(inferred.threadId) ?? inferred;
290
329
  appendClaudeActivity({ out, seen, session, lines: childLines, observations, child });
291
330
  }
292
- // V8 sort is stable: preserve transcript order when a provider stamps a
293
- // whole batch with the same millisecond. Source ids are not chronological.
294
- return out.sort((a, b) => a.createdAt - b.createdAt);
295
331
  }
@@ -1,12 +1,13 @@
1
- import { readFileSync, statSync } from "node:fs";
1
+ import { closeSync, openSync, readSync, statSync } from "node:fs";
2
2
  import { mergeRecordedClaudeUsage, recordedClaudeUsageIsCurrent } from './recorded-usage';
3
3
  import { basename } from "node:path";
4
4
  import type { ChildThreadInfo, SessionInfo } from "../../../../../../packages/protocol/schema";
5
5
  import { aggregateChildThreads, childTitle } from "../../support/child-threads";
6
6
  import { rememberCapabilityObservation } from "../../telemetry";
7
7
  import { observeClaudeTurn } from "./turn-state";
8
- import { safeParse, stateFor, ts } from "../../support/common";
9
- import { claudeCapabilityUsage } from "./activity";
8
+ import { LIVE_MS, safeParse, stateFor, ts } from "../../support/common";
9
+ import { finishScan } from "../../cooperative-scan";
10
+ import { claudeCapabilityUsage, createClaudeCapabilityCollector } from "./activity";
10
11
  import { claudeRepositoryPaths } from "./repository-observation";
11
12
  import { observedCheckoutRoot } from "../../support/repository-checkout";
12
13
  import {
@@ -99,11 +100,100 @@ function applyClaudeLine(d: any, state: ClaudeParseState): void {
99
100
  }
100
101
  }
101
102
 
102
- export function parseClaudeFile(file: string): {
103
- session: SessionInfo;
104
- tokensSession: number;
105
- childPaths: string[];
106
- } | undefined {
103
+ type ClaudeParseResult = { session: SessionInfo; tokensSession: number; childPaths: string[] } | undefined;
104
+
105
+ /** What was already read from one growing transcript. It holds summaries, never message text. */
106
+ export type ClaudeParseProgress = {
107
+ device: number;
108
+ inode: number;
109
+ offset: number;
110
+ /** The bytes before `offset`: a rewritten log must not be continued as if it had only grown. */
111
+ tail: Buffer;
112
+ state: ClaudeParseState;
113
+ capabilities: ReturnType<typeof createClaudeCapabilityCollector>;
114
+ children: Map<string, { fingerprint: string; summary: ChildThreadInfo; observations: ReturnType<typeof claudeCapabilityUsage> }>;
115
+ };
116
+
117
+ const READ_CHUNK_BYTES = 1024 * 1024;
118
+ const TAIL_BYTES = 256;
119
+
120
+ function newProgress(device: number, inode: number, fallbackSessionId: string): ClaudeParseProgress {
121
+ const state: ClaudeParseState = {
122
+ sessionId: "", startedAt: 0, lastActivityAt: 0, lastMessageAt: 0,
123
+ tokensSession: 0, tokensLastTurn: 0, repositoryPaths: [], turnEnded: false,
124
+ };
125
+ return { device, inode, offset: 0, tail: Buffer.alloc(0), state, children: new Map(),
126
+ capabilities: createClaudeCapabilityCollector(() => ({ sessionId: state.sessionId || fallbackSessionId,
127
+ lastActivityAt: state.lastActivityAt, cwd: state.cwd })) };
128
+ }
129
+
130
+ function continues(progress: ClaudeParseProgress | undefined, fd: number,
131
+ stat: { dev: number; ino: number; size: number }): progress is ClaudeParseProgress {
132
+ if (!progress || progress.device !== stat.dev || progress.inode !== stat.ino || stat.size < progress.offset) return false;
133
+ const tail = Buffer.alloc(progress.tail.length);
134
+ return readSync(fd, tail, 0, tail.length, progress.offset - tail.length) === tail.length && tail.equals(progress.tail);
135
+ }
136
+
137
+ function applyRow(line: string, progress: ClaudeParseProgress): boolean {
138
+ const row = line ? safeParse(line) : null;
139
+ if (!row) return false;
140
+ applyClaudeLine(row, progress.state);
141
+ progress.capabilities.add(row);
142
+ return true;
143
+ }
144
+
145
+ /** Reads only what was appended, in slices, so one long chat cannot hold the event loop. */
146
+ function* readAppended(fd: number, progress: ClaudeParseProgress, size: number): Generator<void> {
147
+ let carry = Buffer.alloc(0);
148
+ while (progress.offset + carry.length < size) {
149
+ const wanted = Math.min(READ_CHUNK_BYTES, size - progress.offset - carry.length);
150
+ const chunk = Buffer.allocUnsafe(wanted);
151
+ const count = readSync(fd, chunk, 0, wanted, progress.offset + carry.length);
152
+ if (count === 0) break;
153
+ const data = carry.length ? Buffer.concat([carry, chunk.subarray(0, count)]) : chunk.subarray(0, count);
154
+ const end = data.lastIndexOf(0x0a);
155
+ if (end < 0) { carry = data; continue; }
156
+ for (const line of data.toString("utf8", 0, end).split("\n")) applyRow(line, progress);
157
+ progress.offset += end + 1;
158
+ progress.tail = Buffer.from(data.subarray(Math.max(0, end + 1 - TAIL_BYTES), end + 1));
159
+ carry = data.subarray(end + 1);
160
+ yield;
161
+ }
162
+ // A complete last row without its newline counts; a row still being written waits.
163
+ if (carry.length && applyRow(carry.toString("utf8"), progress)) {
164
+ progress.offset += carry.length;
165
+ progress.tail = Buffer.from(carry.subarray(Math.max(0, carry.length - TAIL_BYTES)));
166
+ }
167
+ }
168
+
169
+ /** A subagent log is read again only when it changed, not whenever its parent chat did. */
170
+ function readChildren(paths: string[], ownSession: SessionInfo, progress: ClaudeParseProgress,
171
+ observations: ReturnType<typeof claudeCapabilityUsage>): ChildThreadInfo[] {
172
+ const childThreads: ChildThreadInfo[] = [];
173
+ for (const childPath of paths) {
174
+ const fingerprint = childLogsFingerprint([childPath]);
175
+ let known = progress.children.get(childPath);
176
+ if (known?.fingerprint !== fingerprint || !recordedClaudeUsageIsCurrent(known.observations)) {
177
+ const childLines = readLines(childPath);
178
+ if (!childLines) continue;
179
+ const child = claudeChildSummary(childPath, ownSession.sessionId, childLines);
180
+ known = { fingerprint, summary: child, observations: claudeCapabilityUsage(ownSession, childLines, child.threadId) };
181
+ progress.children.set(childPath, known);
182
+ }
183
+ childThreads.push(known.summary);
184
+ for (const observation of known.observations) {
185
+ rememberCapabilityObservation(observations, observation);
186
+ }
187
+ mergeRecordedClaudeUsage(observations, known.observations);
188
+ }
189
+ return childThreads;
190
+ }
191
+
192
+ export function parseClaudeFile(file: string): ClaudeParseResult {
193
+ return finishScan(parseClaudeFileSteps(file));
194
+ }
195
+
196
+ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParseResult> {
107
197
  let fileStat;
108
198
  try {
109
199
  fileStat = statSync(file);
@@ -134,22 +224,27 @@ export function parseClaudeFile(file: string): {
134
224
  };
135
225
  return { session, tokensSession: cached.tokensSession, childPaths };
136
226
  }
137
- let text: string;
227
+ // Taken out of the cache while in use: a parallel reader starts its own pass
228
+ // instead of applying the same rows to this one between our slices.
229
+ const resumable = cached?.progress as ClaudeParseProgress | undefined;
230
+ if (cached) cached.progress = undefined;
231
+ let progress: ClaudeParseProgress;
232
+ let fd: number;
138
233
  try {
139
- text = readFileSync(file, "utf8");
234
+ fd = openSync(file, "r");
140
235
  } catch {
141
236
  return undefined;
142
237
  }
143
- const lines = text.split("\n");
144
- const state: ClaudeParseState = {
145
- sessionId: "", startedAt: 0, lastActivityAt: 0, lastMessageAt: 0,
146
- tokensSession: 0, tokensLastTurn: 0, repositoryPaths: [], turnEnded: false,
147
- };
148
- for (const line of lines) {
149
- if (!line) continue;
150
- const d = safeParse(line);
151
- if (d) applyClaudeLine(d, state);
238
+ try {
239
+ progress = continues(resumable, fd, fileStat) ? resumable
240
+ : newProgress(fileStat.dev, fileStat.ino, basename(file, ".jsonl"));
241
+ yield* readAppended(fd, progress, fileStat.size);
242
+ } catch {
243
+ return undefined;
244
+ } finally {
245
+ closeSync(fd);
152
246
  }
247
+ const state = progress.state;
153
248
  if (!state.sessionId || !state.lastActivityAt) return undefined;
154
249
  const ownSession: SessionInfo = {
155
250
  sessionId: state.sessionId,
@@ -170,19 +265,8 @@ export function parseClaudeFile(file: string): {
170
265
  };
171
266
  const actualChildPaths =
172
267
  state.sessionId === cachedSessionId ? childPaths : claudeChildLogPaths(file, state.sessionId);
173
- const childThreads: ChildThreadInfo[] = [];
174
- const observations = claudeCapabilityUsage(ownSession, lines);
175
- for (const childPath of actualChildPaths) {
176
- const childLines = readLines(childPath);
177
- if (!childLines) continue;
178
- const child = claudeChildSummary(childPath, state.sessionId, childLines);
179
- childThreads.push(child);
180
- const childObservations = claudeCapabilityUsage(ownSession, childLines, child.threadId);
181
- for (const observation of childObservations) {
182
- rememberCapabilityObservation(observations, observation);
183
- }
184
- mergeRecordedClaudeUsage(observations, childObservations);
185
- }
268
+ const observations = progress.capabilities.snapshot();
269
+ const childThreads = readChildren(actualChildPaths, ownSession, progress, observations);
186
270
  const session = aggregateChildThreads(ownSession, childThreads);
187
271
  claudeSummaryCache.set(file, {
188
272
  mtimeMs: fileStat.mtimeMs,
@@ -192,6 +276,8 @@ export function parseClaudeFile(file: string): {
192
276
  tokensSession: session.tokensSession,
193
277
  observations,
194
278
  turnEnded: state.turnEnded,
279
+ // A chat that has gone quiet gives its memory back and is read again if it returns.
280
+ progress: Date.now() - state.lastActivityAt <= LIVE_MS ? progress : undefined,
195
281
  });
196
282
  return { session, tokensSession: session.tokensSession, childPaths: actualChildPaths };
197
283
  }
@@ -28,7 +28,8 @@ export function createClaudeUsageRecorder() {
28
28
  events.set(event.sourceId, event);
29
29
  while (events.size > 20000) events.delete(events.keys().next().value!);
30
30
  },
31
- finish(observations: CapabilityObservation[]) {
31
+ /** `retain` keeps the events for a transcript that will continue to grow. */
32
+ finish(observations: CapabilityObservation[], retain = false) {
32
33
  const summaries = createExecutionSummaries(), totals = createCapabilityTotals();
33
34
  const now = Date.now();
34
35
  let nextExpiry = Infinity;
@@ -41,7 +42,7 @@ export function createClaudeUsageRecorder() {
41
42
  }
42
43
  }
43
44
  recorded.set(observations, { summaries: summaries.rows(), totals: totals.rows(), nextExpiry });
44
- events.clear();
45
+ if (!retain) events.clear();
45
46
  },
46
47
  };
47
48
  }
@@ -5,7 +5,7 @@ import {
5
5
  claudeLogPathBySession,
6
6
  claudeSummaryCache,
7
7
  } from "./shared";
8
- import { parseClaudeFile } from "./parse";
8
+ import { parseClaudeFileSteps } from "./parse";
9
9
  import { recentLogs, claudeProjectsRoot, MAX_FILES, TOKEN_WINDOW_MS, type Scan } from "../../support/common";
10
10
  import type { SessionInfo } from "../../../../../../packages/protocol/schema";
11
11
 
@@ -29,7 +29,7 @@ function* scanClaudeCatalog(maxFiles: number): Generator<void, Scan> {
29
29
 
30
30
  for (const file of files) {
31
31
  yield;
32
- const parsed = parseClaudeFile(file);
32
+ const parsed = yield* parseClaudeFileSteps(file);
33
33
  if (!parsed || seenSessionIds.has(parsed.session.sessionId)) continue;
34
34
  seenSessionIds.add(parsed.session.sessionId);
35
35
  sources.push({ sessionId: parsed.session.sessionId, file, childPaths: parsed.childPaths });
@@ -53,6 +53,8 @@ export type CachedClaudeSummary = {
53
53
  observations: CapabilityObservation[];
54
54
  /** The chat's own last turn ended; recent writes no longer mean it is working. */
55
55
  turnEnded?: boolean;
56
+ /** Where a growing transcript was last read to; see `ClaudeParseProgress`. */
57
+ progress?: unknown;
56
58
  };
57
59
 
58
60
  export const claudeSummaryCache = new Map<string, CachedClaudeSummary>();
@@ -14,6 +14,10 @@ until expiry plus seven days. Restarting after an ambiguous submission requires
14
14
  of blindly replaying the prompt. Queued server cancellation wins over a stale
15
15
  local offer. Scheduling does not imply that the controller phone is online.
16
16
 
17
+ The first time a message reaches this computer, the phone gets a `delivery.arrival`,
18
+ so it can say the message is here and waiting its turn instead of still on the relay.
19
+ That is a type of its own: earlier apps read any other receipt status as a refusal.
20
+
17
21
  The native sender cancels an uploaded operation with DELETE directly, without
18
22
  waiting for a metadata GET. A claim conflict is reconciled by a subsequent read.
19
23
  An ambiguous upload is still reconciled using the same encrypted reservation;
@@ -5,11 +5,12 @@ import { isDeliveryInFlight, newTaskDeliveryKey } from '../../reply';
5
5
  import { publishedCatalog } from '../../session-catalog';
6
6
  import { handleUserMessage } from '../../monitor/handlers/user-message';
7
7
  import { handleTaskCreate } from '../../monitor/handlers/task-create';
8
+ import { sendDeliveryArrival } from '../../monitor/handlers/receipts';
8
9
  import { TaskDispatchInbox } from '../index';
9
10
  import { TaskDispatchWorker, type TaskJobRemote, type WorkerOptions } from './index';
10
11
  import { relayTaskJobRemote } from './remote';
11
12
  import { NativeTaskQueueSender } from '../sender';
12
- import { dispatchSessionObservation, queuedCatalogRefreshDue, taskDispatchReady } from './readiness';
13
+ import { dispatchSessionObservation, newTaskOperationKey, queuedCatalogRefreshDue, taskDispatchReady } from './readiness';
13
14
  import { localTaskOrigins, resolveTaskOriginJob } from '../../task-origins';
14
15
 
15
16
  /** Only the persistent monitor advertises durable submission capability. */
@@ -23,6 +24,7 @@ export function startTaskDispatchMonitor(input: {
23
24
  const resolve = (job: Parameters<typeof resolveTaskOriginJob>[1], peer: string) =>
24
25
  resolveTaskOriginJob(origins, job, input.config.room, peer);
25
26
  let stopped = false, reportedAt = 0, maintainedAt = 0, refreshedAt = 0;
27
+ const waitingSince = new Map<string, number>();
26
28
  const sender = new NativeTaskQueueSender({ root: join(configDir(), 'native-task-queue'), config: input.config });
27
29
  const peerAllowed = (peer: string) => peer === input.config.myPublicKey || input.peerAllowed(peer);
28
30
  const worker = new TaskDispatchWorker({ inbox, remote: input.remote ?? relayTaskJobRemote(input.config),
@@ -45,10 +47,18 @@ export function startTaskDispatchMonitor(input: {
45
47
  const session = [...(catalog?.sessions ?? []), ...(catalog?.history ?? [])]
46
48
  .find(item => item.sessionId === job.sessionId);
47
49
  const observation = { ...dispatchSessionObservation(session, catalog?.generatedAt),
48
- inFlight: isDeliveryInFlight(job.sessionId ?? newTaskDeliveryKey(job.operation.agent ?? 'codex',
49
- job.operation.type === 'project.task.create' ? job.operation.operationId : undefined)),
50
+ inFlight: isDeliveryInFlight(job.sessionId
51
+ ?? newTaskDeliveryKey(job.operation.agent ?? 'codex', newTaskOperationKey(job.operation))),
50
52
  paused: !!job.sessionId && isSessionPaused(job.sessionId) };
51
53
  const ready = taskDispatchReady(job, observation);
54
+ if (!ready) { if (!waitingSince.has(job.jobId)) waitingSince.set(job.jobId, Date.now()); }
55
+ else {
56
+ const waited = Date.now() - (waitingSince.get(job.jobId) ?? Date.now());
57
+ waitingSince.delete(job.jobId);
58
+ if (waited >= 30_000) {
59
+ process.stderr.write(`[monitor] A queued message waited ${Math.round(waited / 1000)} s for its chat to become free.\n`);
60
+ }
61
+ }
52
62
  if (!ready && queuedCatalogRefreshDue(job, observation, refreshedAt)) {
53
63
  refreshedAt = Date.now();
54
64
  void input.publish().catch(() => {});
@@ -70,7 +80,10 @@ export function startTaskDispatchMonitor(input: {
70
80
  if (Date.now() - reportedAt < 60_000) return;
71
81
  reportedAt = Date.now();
72
82
  // Storage and relay errors name a status or a path, never a prompt.
73
- const cause = error instanceof Error ? `${error.name}: ${error.message}`.slice(0, 200) : 'unknown';
83
+ // A failed fetch keeps its reason (DNS, TLS, connect timeout) in `cause`.
84
+ const reason = error instanceof Error && error.cause instanceof Error
85
+ ? ` [${(error.cause as NodeJS.ErrnoException).code ?? error.cause.name}]` : '';
86
+ const cause = error instanceof Error ? `${error.name}: ${error.message}${reason}`.slice(0, 200) : 'unknown';
74
87
  process.stderr.write(`[monitor] Durable task queue needs storage or relay recovery (${cause}). No prompt was replayed.\n`);
75
88
  };
76
89
  const tick = () => {
@@ -82,7 +95,16 @@ export function startTaskDispatchMonitor(input: {
82
95
  };
83
96
  const off = input.client.onTaskDispatch((job, peer) => {
84
97
  if (stopped || !input.isLeader() || !peerAllowed(peer)) return;
85
- try { if (inbox.stage(job, peer) !== 'conflict') tick(); }
98
+ try {
99
+ const staged = inbox.stage(job, peer);
100
+ if (staged === 'conflict') return;
101
+ // The relay repeats its offer until a claim. Only the first one is news.
102
+ if (staged !== 'existing' && job.operation.type === 'user.message' && job.operation.messageId) {
103
+ void sendDeliveryArrival(input.client, job.operation.messageId, job.operation.sessionId,
104
+ peer === input.config.myPublicKey ? undefined : peer);
105
+ }
106
+ tick();
107
+ }
86
108
  catch (error) { reportFailure(error); }
87
109
  });
88
110
  const interval = setInterval(tick, 2_000); interval.unref();
@@ -8,6 +8,12 @@ export function dispatchSessionObservation(session: SessionInfo | undefined, gen
8
8
  nativeState: fresh?.session.state };
9
9
  }
10
10
 
11
+ /** Each new task runs under its own operation, so a long run cannot hold back the next one. */
12
+ export function newTaskOperationKey(operation: TaskDispatch['operation']): string | undefined {
13
+ if (operation.type === 'project.task.create') return operation.operationId;
14
+ return operation.type === 'user.message' ? operation.messageId : undefined;
15
+ }
16
+
11
17
  /** Manual release bypasses busy state only. Pause, native admission and policy still win. */
12
18
  export function taskDispatchReady(job: TaskDispatch, observation: {
13
19
  session?: SessionInfo; generatedAt?: number; inFlight: boolean; paused: boolean;
@@ -10,7 +10,7 @@ keeps each phone response tied to the exact originating chat and prompt.
10
10
  Install the supported CLI on this computer, then run:
11
11
 
12
12
  ```bash
13
- npm install -g granttap-mcp@0.8.134
13
+ npm install -g granttap-mcp@0.8.135
14
14
  granttap setup
15
15
  granttap status
16
16
  ```
@@ -4,7 +4,7 @@
4
4
  "command": "node",
5
5
  "args": [
6
6
  "-e",
7
- "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.134\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
7
+ "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.135\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
8
8
  ]
9
9
  }
10
10
  }
@@ -7,7 +7,7 @@ const { spawn } = require("node:child_process");
7
7
  const { existsSync } = require("node:fs");
8
8
  const { delimiter, dirname, join } = require("node:path");
9
9
 
10
- const PACKAGE = "granttap-mcp@0.8.134";
10
+ const PACKAGE = "granttap-mcp@0.8.135";
11
11
  const dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === "1";
12
12
  const platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM
13
13
  ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "granttap-mcp",
3
- "version": "0.8.134",
3
+ "version": "0.8.135",
4
4
  "description": "Commercial computer runtime connecting local coding agents to GrantTap on Mac, iPhone, iPad and Apple Watch.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -4,6 +4,8 @@ import { publicKeyIdentifier } from '../ciphertext-recipient';
4
4
  import { openRelayMessage } from '../relay-inbound';
5
5
  import type { PeerConfig } from '../relay-client-types';
6
6
 
7
+ const CLOCK_SKEW_MS = 5 * 60_000;
8
+
7
9
  export type TaskDispatchListener = (job: TaskDispatch, peerPublicKey: string) => void | Promise<void>;
8
10
  const Offer = z.object({ type: z.literal('relay.task-job'), job: z.object({
9
11
  id: z.string(), state: z.literal('queued'), notBefore: z.number().int(),
@@ -30,7 +32,10 @@ export async function consumeTaskJobOffer(input: {
30
32
  const payload = opened.payload;
31
33
  if ((opened.peerPublicKey === localKey) !== (payload.origin === 'computer')) return;
32
34
  if (payload.jobId !== job.id || payload.notBefore !== job.notBefore
33
- || payload.expiresAt !== job.expiresAt || payload.notBefore > Date.now()) return;
35
+ || payload.expiresAt !== job.expiresAt) return;
36
+ // A sender's clock can run ahead. The worker holds the job until it is due;
37
+ // only a schedule far ahead can have come from something other than skew.
38
+ if (payload.notBefore > Date.now() + CLOCK_SKEW_MS) return;
34
39
  await Promise.all(input.listeners.map(async listener => {
35
40
  try { await listener(payload, opened.peerPublicKey); } catch { /* durable receipt remains queued */ }
36
41
  }));
@@ -113,6 +113,18 @@ export const DeliveryReceipt = z.object({
113
113
  });
114
114
  export type DeliveryReceipt = z.infer<typeof DeliveryReceipt>;
115
115
 
116
+ /**
117
+ * The computer holds a queued message durably, whatever its chat is doing. A type
118
+ * of its own: earlier apps read every receipt status except "accepted" as a refusal.
119
+ */
120
+ export const DeliveryArrival = z.object({
121
+ type: z.literal("delivery.arrival"),
122
+ messageId: z.string().min(1).max(180),
123
+ sessionId: z.string().nullish(),
124
+ receivedAt: z.number(),
125
+ });
126
+ export type DeliveryArrival = z.infer<typeof DeliveryArrival>;
127
+
116
128
  /** Reads the original operation; it cannot submit or resume a provider turn. */
117
129
  export const DeliveryReceiptQuery = z.object({
118
130
  type: z.literal('delivery.receipt.query'), messageId: z.string().min(1).max(180),
@@ -24,6 +24,7 @@ import {
24
24
  import { CapabilityUsageStatus } from "./messages/capabilities";
25
25
  import {
26
26
  AgentEvent,
27
+ DeliveryArrival,
27
28
  DeliveryReceipt,
28
29
  DeliveryReceiptQuery,
29
30
  MAX_ATTACHMENT_BASE64_CHARS,
@@ -139,6 +140,7 @@ export const Payload = z.union([
139
140
  TaskCreate,
140
141
  HostGrant,
141
142
  UserAttachmentUpload,
143
+ DeliveryArrival,
142
144
  DeliveryReceipt,
143
145
  DeliveryReceiptQuery,
144
146
  AgentEvent,