granttap-mcp 0.8.140 → 0.8.142

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.
@@ -5,6 +5,9 @@ Public entry point: [`index.ts`](index.ts).
5
5
  GrantTap reads native Codex `hooks/list` metadata to distinguish configuration,
6
6
  current-definition trust, and enabled state. Only the two exact user hooks
7
7
  installed by this runtime (`PreToolUse` and `PermissionRequest`) can be reviewed.
8
+ A hook an earlier runtime wrote through its launcher in the private version cache
9
+ still counts as this runtime's, because that launcher hands off to the selected
10
+ version; setup keeps it, so an automatic update does not void its Codex trust.
8
11
  Project, plugin, managed, ambiguous, or unrelated commands are never approved.
9
12
  Unsupported native APIs report unknown; configured hooks alone do not establish
10
13
  readiness or computer enforcement.
@@ -1,4 +1,4 @@
1
- import { ownedHookCommands } from "./projection";
1
+ import { ownedHookCommand } from "./projection";
2
2
 
3
3
  export function codexHookSet(config: string): { permission: boolean; policy: boolean } {
4
4
  type Event = "PermissionRequest" | "PreToolUse";
@@ -14,12 +14,12 @@ export function codexHookSet(config: string): { permission: boolean; policy: boo
14
14
  if (!event || !matcherAll || !inCommandHook || !commandType) return;
15
15
  if (event === "PermissionRequest"
16
16
  && timeout === 120
17
- && command === ownedHookCommands().permission) {
17
+ && ownedHookCommand(command, "permission")) {
18
18
  permission = true;
19
19
  }
20
20
  if (event === "PreToolUse"
21
21
  && timeout === 30
22
- && command === ownedHookCommands().policy) {
22
+ && ownedHookCommand(command, "policy")) {
23
23
  policy = true;
24
24
  }
25
25
  };
@@ -1,16 +1,24 @@
1
1
  import { dirname, join } from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { ProviderHook, type ProviderHook as Hook } from "../../../../packages/protocol/messages/provider-hooks";
4
+ import { configDir } from "../config/runtime/paths";
5
+ import { cachedHookLauncher, runtimeVersion } from "../runtime-updates/selection.mjs";
6
+
7
+ const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..");
4
8
 
5
9
  export function ownedHookCommands() {
6
- const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..");
7
10
  const base = `node "${join(root, "bin", "granttap-mcp.mjs")}" internal hook`;
8
11
  return { policy: `${base} codex-policy`, permission: `${base} codex` };
9
12
  }
10
13
 
14
+ /** This runtime's command, or an earlier runtime's cached launcher that hands off to it. */
15
+ export function ownedHookCommand(command: unknown, kind: "policy" | "permission"): boolean {
16
+ return command === ownedHookCommands()[kind] || cachedHookLauncher(command,
17
+ kind === "policy" ? "codex-policy" : "codex", join(configDir(), "runtime-updates"), runtimeVersion(root));
18
+ }
19
+
11
20
  /** Only the two exact user-config hooks installed by this runtime are reviewable. */
12
21
  export function projectCodexHooks(value: unknown): Hook[] {
13
- const commands = ownedHookCommands();
14
22
  const report = value as { data?: Array<{ hooks?: any[]; errors?: unknown[] }> } | null;
15
23
  const data = Array.isArray(report?.data) ? report.data : [];
16
24
  return (["PreToolUse", "PermissionRequest"] as const).map((event) => {
@@ -21,7 +29,7 @@ export function projectCodexHooks(value: unknown): Hook[] {
21
29
  const rows = Array.isArray(data[0]?.hooks) ? data[0]!.hooks! : [];
22
30
  const candidates = rows.filter((row) => row?.eventName === (event === "PreToolUse" ? "preToolUse" : "permissionRequest")
23
31
  && row.handlerType === "command" && row.source === "user" && row.isManaged === false
24
- && row.command === commands[event === "PreToolUse" ? "policy" : "permission"]
32
+ && ownedHookCommand(row.command, event === "PreToolUse" ? "policy" : "permission")
25
33
  && row.matcher === ".*" && row.timeoutSec === (event === "PreToolUse" ? 30 : 120));
26
34
  if (candidates.length !== 1) return missing;
27
35
  const row = candidates[0];
@@ -3,7 +3,8 @@
3
3
  `index.ts` exposes saved-declaration activation and platform-specific endpoint
4
4
  selection. The launcher preloads `activation-entry.ts` after registering tsx and
5
5
  before importing a hook, service or monitor. It performs no network access or
6
- Engine installation. The runtime supervisor verifies the selected executable
6
+ Engine installation. It first makes stderr errors non-fatal, so a full disk
7
+ behind a desktop client's MCP log loses log lines instead of the server. The runtime supervisor verifies the selected executable
7
8
  before launch. Windows endpoints are local owner-scoped named pipes; Unix
8
9
  endpoints retain the configured socket path.
9
10
 
@@ -1,3 +1,5 @@
1
1
  import { activateConfiguredEngine } from "./activation";
2
+ import { keepDiagnosticsNonFatal } from "./diagnostic-stream";
2
3
 
4
+ keepDiagnosticsNonFatal();
3
5
  activateConfiguredEngine();
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Diagnostics may never end the process that writes them.
3
+ *
4
+ * Desktop clients redirect an MCP server's stderr into a log file. When that
5
+ * disk fills, a write fails with ENOSPC and the stream emits `error`; with no
6
+ * listener Node turns it into an uncaught exception and the server disconnects
7
+ * mid-session. Losing the log line is the right trade.
8
+ */
9
+ export function keepDiagnosticsNonFatal(stream: NodeJS.WriteStream | NodeJS.WritableStream = process.stderr): void {
10
+ stream.on("error", () => {});
11
+ }
@@ -19,22 +19,23 @@ import { createHash } from "node:crypto";
19
19
  import { randomId } from "../../../../packages/core/crypto";
20
20
  import { approvalPresentation } from "./approval-presentation";
21
21
 
22
+ const HIGH = [
23
+ /\brm\s+-rf?\b/,
24
+ /\bsudo\b/,
25
+ /\bgit\s+push\b.*--force/,
26
+ /\bgit\s+reset\s+--hard\b/,
27
+ /\bcurl\b[^|]*\|\s*(sh|bash)\b/,
28
+ /\bnpm\s+publish\b/,
29
+ /\bdd\s+if=/,
30
+ /\b(drop|truncate)\s+table\b/,
31
+ /:\s*>\s*\//, // truncate a file
32
+ /\bchmod\s+-r\b/,
33
+ ];
34
+ const isHighRisk = (command: string): boolean => HIGH.some((re) => re.test(command.toLowerCase()));
35
+
22
36
  /** Heuristic risk tag so the watch can color/rank the request at a glance. */
23
37
  export function guessRisk(tool: string, command: string | undefined): Risk {
24
- const c = (command ?? "").toLowerCase();
25
- const HIGH = [
26
- /\brm\s+-rf?\b/,
27
- /\bsudo\b/,
28
- /\bgit\s+push\b.*--force/,
29
- /\bgit\s+reset\s+--hard\b/,
30
- /\bcurl\b[^|]*\|\s*(sh|bash)\b/,
31
- /\bnpm\s+publish\b/,
32
- /\bdd\s+if=/,
33
- /\b(drop|truncate)\s+table\b/,
34
- /:\s*>\s*\//, // truncate a file
35
- /\bchmod\s+-r\b/,
36
- ];
37
- if (HIGH.some((re) => re.test(c))) return "high";
38
+ if (isHighRisk(command ?? "")) return "high";
38
39
  const READONLY = ["Read", "Glob", "Grep", "NotebookRead", "WebFetch", "WebSearch"];
39
40
  if (READONLY.includes(tool)) return "low";
40
41
  return "medium";
@@ -170,10 +171,26 @@ export function decisionToCursorOutput(d: ApprovalDecision): unknown {
170
171
 
171
172
  // ------------------------------------------------------------------ helpers
172
173
 
174
+ /**
175
+ * The risky step of a chained command when an earlier, harmless step would
176
+ * otherwise fill the title. Long paths keep only their last part here; the full
177
+ * command stays in the request.
178
+ */
179
+ function riskyStep(command: string): string | undefined {
180
+ const steps = command.split(/&&|\|\||;|\n/).map((step) => step.replace(/\s+/g, " ").trim());
181
+ const index = steps.findIndex(isHighRisk);
182
+ if (index <= 0) return undefined;
183
+ return steps[index]!.split(" ").map((word) =>
184
+ word.length > 40 && word.includes("/") ? `…/${word.split("/").filter(Boolean).at(-1) ?? ""}` : word,
185
+ ).join(" ");
186
+ }
187
+
173
188
  function shortTitle(tool: string, command: string): string {
174
189
  if (command) {
175
190
  const oneLine = command.replace(/\s+/g, " ").trim();
176
- return oneLine.length > 80 ? oneLine.slice(0, 77) + "…" : oneLine;
191
+ const risky = riskyStep(command);
192
+ const title = risky ? `${risky} · ${oneLine}` : oneLine;
193
+ return title.length > 80 ? title.slice(0, 77) + "…" : title;
177
194
  }
178
195
  return tool;
179
196
  }
@@ -13,6 +13,7 @@ import {
13
13
  CLAUDE_MATCHERS,
14
14
  commandHasRoute,
15
15
  hookCommand,
16
+ hookCommandIsCurrent,
16
17
  codexHookSet,
17
18
  } from "./inspect";
18
19
 
@@ -62,7 +63,9 @@ export function installClaudeHook(): InstallResult {
62
63
  // The prompt hook rides along with the approval hook: what the chat could
63
64
  // not know by itself — background runs in it, the Mesh around it — is added
64
65
  // to each prompt. It never blocks; anything wrong, and it adds nothing.
65
- const promptHookChanged = [ensureClaudePromptHook(settings), ensureClaudeUsageStatusLine(settings, hookCommand("claude-statusline"))].some(Boolean);
66
+ const statusLine = hookCommandIsCurrent(settings.statusLine?.command, "claude-statusline")
67
+ ? settings.statusLine.command : hookCommand("claude-statusline");
68
+ const promptHookChanged = [ensureClaudePromptHook(settings), ensureClaudeUsageStatusLine(settings, statusLine)].some(Boolean);
66
69
  const entries: any[] = (((settings.hooks ??= {}).PreToolUse ??= []) as any[]);
67
70
  const currentCommand = hookCommand("claude");
68
71
  const presentEntry = entries.find((entry) =>
@@ -75,10 +78,10 @@ export function installClaudeHook(): InstallResult {
75
78
  );
76
79
  if (present && presentEntry) {
77
80
  const matcherChanged = repairClaudeMatcher(presentEntry);
78
- const commandChanged = present.command !== currentCommand;
81
+ const commandChanged = !hookCommandIsCurrent(present.command, "claude");
79
82
  if (!matcherChanged && !commandChanged && !promptHookChanged) return { status: "already", detail: path };
80
83
  backupOnce(path);
81
- present.command = currentCommand;
84
+ if (commandChanged) present.command = currentCommand;
82
85
  writeFileSync(path, JSON.stringify(settings, null, 2) + "\n");
83
86
  const detail = !matcherChanged && !commandChanged
84
87
  ? `${path}, GrantTap prompt hook added`
@@ -121,7 +124,7 @@ function ensureClaudePromptHook(settings: any): boolean {
121
124
  .flatMap((entry) => (Array.isArray(entry?.hooks) ? entry.hooks : []))
122
125
  .find((hook: any) => commandHasRoute(hook?.command, "claude-prompt"));
123
126
  if (present) {
124
- if (present.command === command) return false;
127
+ if (hookCommandIsCurrent(present.command, "claude-prompt")) return false;
125
128
  present.command = command;
126
129
  return true;
127
130
  }
@@ -175,6 +178,7 @@ export function installCodexHook(): InstallResult {
175
178
  if (!match) return line;
176
179
  for (const route of ["codex", "codex-policy"] as const) {
177
180
  if (!commandHasRoute(match[3], route)) continue;
181
+ if (hookCommandIsCurrent(match[3], route)) return line;
178
182
  const replacement = `${match[1]}'${hookCommand(route)}'`;
179
183
  if (replacement !== line) changed = true;
180
184
  return replacement;
@@ -267,7 +271,7 @@ export function installCursorHook(): InstallResult {
267
271
  ) => {
268
272
  const entries = document.hooks![event] ?? [];
269
273
  const expected = hookCommand(route);
270
- const current = entries.find((entry) => entry.command === expected);
274
+ const current = entries.find((entry) => hookCommandIsCurrent(entry.command, route));
271
275
  if (current) {
272
276
  if (current.timeout !== timeout) {
273
277
  current.timeout = timeout;
@@ -43,6 +43,7 @@ import { monitorPlistLooksInstalled } from "./monitor-helper";
43
43
  import { inspectLinuxService } from "./linux-service";
44
44
  import { codexHooksExplicitlyDisabled } from "./hooks";
45
45
  import { cachedCodexHooks, codexHookSet } from "../codex-hook-trust";
46
+ import { cachedHookLauncher, runtimeVersion } from "../runtime-updates/selection.mjs";
46
47
  import type { ProviderHook } from "../../../../packages/protocol/messages/provider-hooks";
47
48
  export { codexHookSet } from "../codex-hook-trust";
48
49
 
@@ -71,8 +72,14 @@ export function commandHasRoute(command: unknown, route: HookRoute): boolean {
71
72
  return new RegExp(`\\bhook\\s+${escaped}(?:\\s|[\"']|$)`).test(command);
72
73
  }
73
74
 
74
- function commandIsCurrentRoute(command: unknown, route: HookRoute): boolean {
75
- return typeof command === "string" && command.trim() === hookCommand(route);
75
+ /**
76
+ * This runtime's command, or an earlier runtime's launcher in the version cache,
77
+ * which hands off to this one. Keeping that command after an automatic update
78
+ * also keeps the trust Codex records for it.
79
+ */
80
+ export function hookCommandIsCurrent(command: unknown, route: HookRoute): boolean {
81
+ return typeof command === "string" && (command.trim() === hookCommand(route)
82
+ || cachedHookLauncher(command, route, join(configDir(), "runtime-updates"), runtimeVersion(repoRoot)));
76
83
  }
77
84
 
78
85
  export type InstallResult = { status: "installed" | "already" | "manual"; detail: string };
@@ -146,7 +153,7 @@ function claudeHookConfigured(): boolean {
146
153
  claudeMatcherCoversPolicy(entry.matcher)
147
154
  && (entry.hooks ?? []).some((hook) =>
148
155
  (hook as { type?: unknown }).type === "command"
149
- && commandIsCurrentRoute(hook.command, "claude"),
156
+ && hookCommandIsCurrent(hook.command, "claude"),
150
157
  ),
151
158
  );
152
159
  } catch {
@@ -186,7 +193,7 @@ export function inspectCursorIntegration(): CursorIntegrationStatus {
186
193
  const has = (event: string, route: HookRoute, timeout: number): boolean =>
187
194
  Array.isArray(parsed.hooks?.[event])
188
195
  && parsed.hooks![event]!.some((entry) =>
189
- commandIsCurrentRoute(entry.command, route)
196
+ hookCommandIsCurrent(entry.command, route)
190
197
  && entry.failClosed === false
191
198
  && (entry as { timeout?: unknown }).timeout === timeout,
192
199
  );
@@ -80,6 +80,10 @@ export function withCommandLines(rows: readonly ProcessRow[], commands: Readonly
80
80
  * Two listings: the executable path on its own, then the command line, joined
81
81
  * by pid — one listing cannot carry both once a path has a space in it.
82
82
  */
83
+ /**
84
+ * A listing that fails or times out is unknown, not empty: under heavy load an
85
+ * empty answer told the phone that every agent had stopped.
86
+ */
83
87
  export async function sampleProcessRows(): Promise<ProcessRow[]> {
84
88
  try {
85
89
  const [{ stdout: executables }, { stdout: commands }] = await Promise.all([
@@ -88,6 +92,7 @@ export async function sampleProcessRows(): Promise<ProcessRow[]> {
88
92
  ]);
89
93
  return withCommandLines(parsePsOutput(String(executables)), parsePidListing(String(commands)));
90
94
  } catch {
91
- return [];
95
+ // The execFile error carries every command line it read; none of them leaves here.
96
+ throw new Error("process listing unavailable");
92
97
  }
93
98
  }
@@ -137,22 +137,31 @@ export function createMachineLoadPublisher(dependencies: {
137
137
  const sampleDisk = dependencies.sampleDisk ?? createDiskUsageSampler().sample;
138
138
  const now = dependencies.now ?? Date.now;
139
139
  let loggedAt: number | undefined;
140
- let active: Promise<MachineLoad> | undefined;
140
+ let active: Promise<MachineLoad | undefined> | undefined;
141
+ const logDue = (): boolean => {
142
+ if (!dependencies.log || (loggedAt !== undefined && now() - loggedAt < LOAD_LOG_INTERVAL_MS)) return false;
143
+ loggedAt = now();
144
+ return true;
145
+ };
141
146
  return (
142
147
  client: LoadRelay,
143
148
  status: SessionsStatus,
144
149
  intervalMs: number,
145
- ): Promise<MachineLoad> => {
150
+ ): Promise<MachineLoad | undefined> => {
146
151
  if (active) return active;
147
152
  active = (async () => {
148
- const processes = await sampleProcesses();
153
+ let processes: Record<string, AgentProcessLoad>;
154
+ try {
155
+ processes = await sampleProcesses();
156
+ } catch {
157
+ // The phone keeps the previous report until its TTL; zeros would read as every agent stopping.
158
+ if (logDue()) dependencies.log?.("[load] process listing unavailable; the previous report stands");
159
+ return undefined;
160
+ }
149
161
  recordAgentLoad(processes, now(), agentLanes(status.sessions));
150
162
  const disk = sampleDisk(Object.keys(processes));
151
163
  const load = buildMachineLoad({ status, processes, self: sampleSelf(), disk });
152
- if (dependencies.log && (loggedAt === undefined || now() - loggedAt >= LOAD_LOG_INTERVAL_MS)) {
153
- loggedAt = now();
154
- dependencies.log(describeLoad(load));
155
- }
164
+ if (logDue()) dependencies.log?.(describeLoad(load));
156
165
  await client.send(load, "phone", { ttlMs: intervalMs * 3, reliable: false });
157
166
  return load;
158
167
  })().finally(() => {
@@ -49,11 +49,21 @@ function tryAcquireLock(input: {
49
49
  }): boolean {
50
50
  const { path, token, primary, read, write, expired, ownerIsPrimary, reportRefusal } = input;
51
51
  if (input.getLeader() && read() === token) {
52
- write();
52
+ // A renewal the disk refuses still leaves this token in the lease, and the
53
+ // phone needs this computer's sessions most while its disk is full.
54
+ try {
55
+ write();
56
+ } catch {
57
+ // The lease ages out normally if the disk stays full.
58
+ }
53
59
  return true;
54
60
  }
55
61
  input.setLeader(false);
56
- mkdirSync(configDir(), { recursive: true });
62
+ try {
63
+ mkdirSync(configDir(), { recursive: true });
64
+ } catch {
65
+ return false;
66
+ }
57
67
  for (let attempt = 0; attempt < 2; attempt += 1) {
58
68
  try {
59
69
  const fd = openSync(path, "wx", 0o600);
@@ -20,7 +20,13 @@ export function startPublishLoop(options: PublishLoopOptions): () => void {
20
20
  let timer: NodeJS.Timeout | undefined;
21
21
  const tick = async (): Promise<void> => {
22
22
  if (stopped) return;
23
- if (options.connected()) await options.publish();
23
+ // A failed publish must neither end the loop nor escape as an unhandled
24
+ // rejection: on a full disk one lease renewal once took the whole MCP server down.
25
+ try {
26
+ if (options.connected()) await options.publish();
27
+ } catch {
28
+ // The next tick retries.
29
+ }
24
30
  if (!stopped) timer = schedule(() => void tick(), options.intervalMs);
25
31
  };
26
32
  timer = schedule(() => void tick(), options.immediate ? 0 : options.intervalMs);
@@ -6,7 +6,10 @@ version directory under `~/.granttap/runtime-updates`, with lifecycle scripts
6
6
  disabled, Node engine checks enabled, and registry integrity verified. A failed
7
7
  installation leaves the running version in place.
8
8
 
9
- The stable launcher selects the verified version for future invocations. Owned
9
+ The stable launcher selects the verified version for future invocations.
10
+ Provider hooks keep the launcher path they were written with: `cachedHookLauncher`
11
+ treats an earlier cached launcher as current, so status stays ready and setup
12
+ leaves the hook (and the trust Codex keeps per command) alone after an update. Owned
10
13
  background services switch only after their current requests finish and no
11
14
  approval is pending. Existing provider processes and active stdio MCP calls keep
12
15
  running. A new service that cannot start restores the previous version; that
@@ -11,7 +11,10 @@ type Options={root:string;stateDirectory:string;manual?:boolean;now?:()=>number;
11
11
  idle:()=>boolean;install?:(release:Release,directory:string)=>Promise<void>;
12
12
  verify?:(root:string)=>Promise<void>;activate?:(root:string)=>void};
13
13
 
14
- /** Stage verified releases independently; activation waits until no request or decision is pending. */
14
+ /**
15
+ * Stage releases independently; verification and activation wait until no request or decision is pending.
16
+ * A phone-started run can keep the monitor busy for hours, and each check would otherwise start two Node processes.
17
+ */
15
18
  export async function checkForRuntimeUpdate(options:Options):Promise<string|undefined> {
16
19
  const allowed=()=>options.manual===true || automaticUpdatesAllowed(options.stateDirectory);
17
20
  if(!allowed())return;
@@ -28,7 +31,7 @@ export async function checkForRuntimeUpdate(options:Options):Promise<string|unde
28
31
  if(!validRuntime(candidate,options.stateDirectory,release.version)) {
29
32
  await (options.install??installRelease)(release,options.stateDirectory);
30
33
  }
31
- if(!allowed())return;
34
+ if(!options.idle() || !allowed())return;
32
35
  await (options.verify??verifyRelease)(candidate);
33
36
  if(!validRuntime(candidate,options.stateDirectory,release.version))throw Error('Runtime verification failed');
34
37
  if(!options.idle() || !allowed())return;
@@ -7,4 +7,5 @@ export function runtimeVersion(root:string):string;
7
7
  export function versionRoot(directory:string,version:string):string;
8
8
  export function validRuntime(root:string|undefined,directory:string,version:string|undefined):boolean;
9
9
  export function selectedRuntime(bundled:string,directory:string):string;
10
+ export function cachedHookLauncher(command:unknown,route:string,directory:string,current:string):boolean;
10
11
  export function rollbackRuntime(bundled:string,directory:string,failedRoot?:string):boolean;
@@ -34,6 +34,17 @@ export function selectedRuntime(bundled, directory) {
34
34
  return validRuntime(state.root,directory,state.version) && newerVersion(state.version,runtimeVersion(bundled))
35
35
  ? state.root : bundled;
36
36
  }
37
+ /**
38
+ * A provider hook written by an earlier runtime names that runtime's launcher in
39
+ * this cache. Each cached launcher hands off to the selection above, so the hook
40
+ * stays current after an update; one naming a newer, rolled-back release does not.
41
+ */
42
+ export function cachedHookLauncher(command, route, directory, current) {
43
+ const match=typeof command==='string' && command.trim().match(/^node "(.+)[\\/]bin[\\/]granttap-mcp\.mjs" internal hook (\S+)$/);
44
+ if(!match || match[2]!==route) return false;
45
+ try { const version=runtimeVersion(match[1]);
46
+ return validRuntime(match[1],directory,version) && !newerVersion(version,current); } catch { return false; }
47
+ }
37
48
  /** A new background service that exits during startup restores the last working selection. */
38
49
  export function rollbackRuntime(bundled, directory, failedRoot) {
39
50
  const state=readState(directory);
@@ -14,13 +14,13 @@ const beat = new BigInt64Array(buffer);
14
14
  const send = () => reportUrl ? sendPendingFaults(directory, reportUrl).catch(() => 0) : Promise.resolve(0);
15
15
  const within = (work, ms) => Promise.race([work, new Promise(resolve => setTimeout(resolve, ms))]);
16
16
 
17
- let lastCheck = Date.now(), graceUntil = 0, reported = false, busy = false;
17
+ let lastCheck = Date.now(), graceUntil = 0, reported = false, busy = false, killed = false;
18
18
  const record = (kind, stalledMs, action, restartsInWindow) => {
19
19
  rememberFault(directory, faultReport({ id: randomUUID(), kind, at: Date.now(), stalledMs, action, restartsInWindow, version }));
20
20
  };
21
21
 
22
22
  async function check() {
23
- if (busy) return;
23
+ if (busy || killed) return;
24
24
  busy = true;
25
25
  try {
26
26
  const now = Date.now(), last = Number(Atomics.load(beat, 0));
@@ -38,7 +38,12 @@ async function check() {
38
38
  record('event-loop-stall', now - last, budget.restart ? 'restart' : 'held', budget.restartsInWindow);
39
39
  reported = true;
40
40
  await within(send(), 5_000);
41
- if (budget.restart) process.kill(process.pid, 'SIGKILL');
41
+ if (budget.restart) {
42
+ // macOS can let this thread run briefly after the kill; under load a second
43
+ // check spent another restart on the same hang.
44
+ killed = true;
45
+ process.kill(process.pid, 'SIGKILL');
46
+ }
42
47
  } catch { /* A watchdog fault must never become the monitor's fault. */ }
43
48
  finally { busy = false; }
44
49
  }
@@ -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.140
13
+ npm install -g granttap-mcp@0.8.142
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.140\";\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.142\";\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.140";
10
+ const PACKAGE = "granttap-mcp@0.8.142";
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.140",
3
+ "version": "0.8.142",
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": {
@@ -103,7 +103,8 @@ export class RelayClient {
103
103
  resolve();
104
104
  this.connections.connected();
105
105
  });
106
- ws.on("message", (data: WebSocket.RawData) => void this.onRaw(data.toString()));
106
+ // One frame that fails to apply must not end the process; an unacknowledged one is redelivered.
107
+ ws.on("message", (data: WebSocket.RawData) => void this.onRaw(data.toString()).catch(() => {}));
107
108
  ws.on('unexpected-response', (_request, response) => {
108
109
  this.reconnect.defer(response.headers['retry-after']);
109
110
  response.resume(); ws.terminate();
@@ -56,7 +56,12 @@ export class RelayMessageAcceptance {
56
56
  const oldest = this.seen.values().next().value;
57
57
  if (oldest) this.seen.delete(oldest);
58
58
  }
59
- saveReplayFingerprints(this.path, this.seen);
59
+ try {
60
+ saveReplayFingerprints(this.path, this.seen);
61
+ } catch {
62
+ // On a full disk this once ended the monitor and the relay redelivered the
63
+ // message after the restart. The next save the disk accepts writes the whole set.
64
+ }
60
65
  }
61
66
 
62
67
  finish(fingerprint: string): void { this.processing.delete(fingerprint); }