granttap-mcp 0.8.143 → 0.8.146

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,7 +5,7 @@ import { loadConfig, machineConfigPath } from '../config';
5
5
  import { observedComputerId } from '../mesh/identity/computer';
6
6
  import { clearComputerCache } from './cache';
7
7
  import { providerLogins } from './login';
8
- import { managementSnapshot, maintenanceIdle, restartProvider, restartRuntime, runtimeRoot, updateRuntime, updateProvider } from './maintenance';
8
+ import { managementSnapshot, maintenanceIdle, prepareRestart, restartProvider, restartRuntime, runtimeRoot, updateRuntime, updateProvider } from './maintenance';
9
9
 
10
10
  type Send = (result: DeviceManagementResult) => Promise<void>;
11
11
  type Entry = { fingerprint: string; result?: DeviceManagementResult; pending?: Promise<void>; at: number; ttl: number };
@@ -84,7 +84,7 @@ async function execute(request: DeviceManagementRequest, scope: string, computer
84
84
  message = await updateProvider(request.agent!);
85
85
  } else if (request.action === 'runtime-restart') {
86
86
  // The phone waits for a different runtimeEpoch, rather than treating this acknowledgement as a restart.
87
- if (!maintenanceIdle()) throw Error('Finish active requests and sign-in before restarting MCP.');
87
+ await prepareRestart(request.interruptActiveTasks === true);
88
88
  await send(result('waiting', 'Restart requested. Waiting for MCP to reconnect…'));
89
89
  restartRuntime(); return;
90
90
  }
@@ -16,7 +16,8 @@ import { binaryVersion } from '../tools/version';
16
16
  import { providerCommand, providerAuthentication, installedProvider, providerEnvironment } from './provider-command';
17
17
  import { computerCache } from './cache';
18
18
  import { providerLogins } from './login';
19
- import { ownedProviderProcesses, signalOwnedProcess } from '../reply/process';
19
+ import { ownedProviderProcesses } from '../reply/process';
20
+ import { prepareRuntimeRestart, stopOwnedChildren } from './runtime-restart';
20
21
  import { approvalsStatus } from '../approvals/state';
21
22
  import { inspectTool, updateTool } from '../tools/updater';
22
23
 
@@ -80,13 +81,20 @@ export async function updateRuntime(): Promise<string> {
80
81
  const candidate = await checkForRuntimeUpdate({ root: runtimeRoot, stateDirectory: join(configDir(), 'runtime-updates'),
81
82
  idle: maintenanceIdle, manual: true });
82
83
  return candidate ? 'MCP update verified and selected. Restart MCP to activate it.'
83
- : 'No newer published MCP is available, or activation is waiting for active work. The current MCP is retained.';
84
+ : 'No newer published MCP is available, or another update is still installing. The current MCP is retained.';
85
+ }
86
+
87
+ const ownedRuns = () => agents.flatMap(agent => ownedProviderProcesses(providerCommand(agent)));
88
+
89
+ /** Stops GrantTap's own runs only when the phone confirmed it; see `prepareRuntimeRestart`. */
90
+ export function prepareRestart(interrupt: boolean): Promise<void> {
91
+ return prepareRuntimeRestart({ supported: runtimeRestartSupported, signingIn: () => providerLogins.active(),
92
+ pendingDecisions: () => approvalsStatus().pending.length, activeRuns: ownedRuns, stop: stopOwnedChildren }, interrupt);
84
93
  }
85
94
 
86
95
  /** A detached, fixed command survives the monitor exiting. No phone-supplied command or path is executed. */
87
96
  export function restartRuntime(): void {
88
97
  if (!runtimeRestartSupported()) throw Error('Managed MCP services are not installed on this computer.');
89
- if (!maintenanceIdle()) throw Error('Finish active requests, decisions and sign-in before restarting MCP.');
90
98
  const domain = 'gui/' + process.getuid!();
91
99
  const script = `setTimeout(() => { const { spawnSync } = require('node:child_process');
92
100
  for (const label of ['com.granttap.mcp-http','com.granttap.monitor'])
@@ -101,12 +109,7 @@ export async function restartProvider(agent: CodingAgent, interrupt = false): Pr
101
109
  if (providerLogins.active()) throw Error('Finish sign-in before restarting a provider.');
102
110
  const children = ownedProviderProcesses(command);
103
111
  if (children.length && !interrupt) throw Error('This provider has active GrantTap requests. Confirm interruption before restarting.');
104
- await Promise.all(children.map(child => new Promise<void>(resolve => {
105
- const timer = setTimeout(() => { signalOwnedProcess(child, 'SIGKILL'); resolve(); }, 2_000);
106
- child.once('close', () => { clearTimeout(timer); resolve(); });
107
- (child as typeof child & { granttapStopped?: boolean }).granttapStopped = true;
108
- signalOwnedProcess(child, 'SIGTERM');
109
- })));
112
+ await stopOwnedChildren(children);
110
113
  await promisify(execFile)(command, ['--version'], { env: providerEnvironment(), timeout: 15_000, maxBuffer: 16_384 });
111
114
  return 'A fresh provider CLI started successfully. The next message starts a new GrantTap connection to it.';
112
115
  }
@@ -0,0 +1,44 @@
1
+ import type { ChildProcess } from 'node:child_process';
2
+ import { signalOwnedProcess } from '../reply/process';
3
+
4
+ /** What a phone-requested MCP restart has to know about this computer before launchd restarts it. */
5
+ export type RuntimeRestartHost = {
6
+ supported(): boolean;
7
+ signingIn(): boolean;
8
+ pendingDecisions(): number;
9
+ activeRuns(): ChildProcess[];
10
+ stop(children: ChildProcess[]): Promise<void>;
11
+ };
12
+
13
+ function plural(count: number, one: string, many: string): string {
14
+ return `${count} ${count === 1 ? one : many}`;
15
+ }
16
+
17
+ /**
18
+ * A restart is most needed when a run has hung, so open work no longer refuses it outright. The phone confirms
19
+ * the interruption; GrantTap's own detached provider runs are stopped first, otherwise they would outlive the
20
+ * monitor that owns their chats.
21
+ */
22
+ export async function prepareRuntimeRestart(host: RuntimeRestartHost, interrupt: boolean): Promise<void> {
23
+ if (!host.supported()) throw Error('Managed MCP services are not installed on this computer.');
24
+ if (host.signingIn()) throw Error('Finish sign-in before restarting MCP.');
25
+ const runs = host.activeRuns(), decisions = host.pendingDecisions();
26
+ if ((runs.length || decisions) && !interrupt) {
27
+ const open = [runs.length && plural(runs.length, 'GrantTap request', 'GrantTap requests'),
28
+ decisions && plural(decisions, 'decision', 'decisions')].filter(Boolean).join(' and ');
29
+ throw Error(`${open} ${runs.length + decisions === 1 ? 'is' : 'are'} still open on this computer. `
30
+ + 'Confirm interruption to stop them and restart MCP.');
31
+ }
32
+ if (runs.length) await host.stop(runs);
33
+ }
34
+
35
+ /** SIGTERM the run's process group, then SIGKILL whatever is still there once the grace period ends. */
36
+ export async function stopOwnedChildren(children: ChildProcess[], graceMs = 2_000): Promise<void> {
37
+ await Promise.all(children.map(child => new Promise<void>(resolve => {
38
+ if (child.exitCode != null || child.signalCode != null) { resolve(); return; }
39
+ const timer = setTimeout(() => { signalOwnedProcess(child, 'SIGKILL'); resolve(); }, graceMs);
40
+ child.once('exit', () => { clearTimeout(timer); resolve(); });
41
+ (child as typeof child & { granttapStopped?: boolean }).granttapStopped = true;
42
+ signalOwnedProcess(child, 'SIGTERM');
43
+ })));
44
+ }
@@ -39,8 +39,8 @@ export class RepositoryGraphJobs<T> {
39
39
  if (!this.admit(priority)) return undefined;
40
40
  if (!previous && this.entries.size >= this.capacity * 2) {
41
41
  const oldest = [...this.entries].find(([, entry]) => !entry.pending)?.[0];
42
- if (!oldest) return undefined;
43
- this.entries.delete(oldest);
42
+ if (oldest) this.entries.delete(oldest);
43
+ else if (priority !== Number.MAX_SAFE_INTEGER) return undefined;
44
44
  }
45
45
  this.entries.set(key, { value: previous?.value, retryAt: 0, pending: true, listeners: [],
46
46
  sourceFingerprint: source?.fingerprint });
@@ -81,7 +81,9 @@ export class RepositoryGraphJobs<T> {
81
81
  }
82
82
 
83
83
  private admit(priority: number): boolean {
84
- if (this.queue.length < this.capacity) return true;
84
+ // A person's build used to be refused once other builds filled the queue; its answer then
85
+ // came back empty and the phone read that as an unbound repository.
86
+ if (this.queue.length < this.capacity || priority === Number.MAX_SAFE_INTEGER) return true;
85
87
  const last = this.queue[this.queue.length - 1];
86
88
  if (!last || last.priority >= priority) return false;
87
89
  this.queue.pop();
@@ -2,6 +2,7 @@ import { retainedPayloadOptions } from "../../../../packages/core/retained-state
2
2
  import { existsSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { loadSessionKeys, persistedSessionKey } from "./session-key-store";
5
+ import { fitMeshSnapshot } from "../mesh/runtime/snapshot/fit";
5
6
  import { RelayClient, type SendOptions } from "../../../../packages/core/relay-client";
6
7
  import type {
7
8
  MeshClaimReleaseResult,
@@ -49,7 +50,8 @@ export async function sendMeshPayload(
49
50
  options: SendOptions = {},
50
51
  ): Promise<void> {
51
52
  const purpose = payload.type === "mesh.snapshot" ? "project" : "task";
52
- await sendScopedPayload({ client, payload, sessionId: payload.sessionId, purpose, to, options });
53
+ const fitted = payload.type === "mesh.snapshot" ? fitMeshSnapshot(payload) : payload;
54
+ await sendScopedPayload({ client, payload: fitted, sessionId: fitted.sessionId, purpose, to, options });
53
55
  }
54
56
 
55
57
  export async function sendProjectPayload(
@@ -68,12 +68,15 @@ export async function analyzeProjectGraphNow(
68
68
  const peers = relationships === undefined ? current.peers
69
69
  : mergeRelationshipPeers(current.peers, relationships);
70
70
  const observed = [...repositoryGraphs, ...failures];
71
- const reports = observed.length > 0 ? observed : [{
72
- projectId, repositoryId: current.project.canonicalRepositoryId,
73
- revision: "unverified", weavatrixVersion: "unknown",
74
- analysisStatus: "UNAVAILABLE" as const, analysisErrorCode: "REPOSITORY_NOT_BOUND",
71
+ const unavailable = (repositoryId: string, analysisErrorCode: string) => ({
72
+ projectId, repositoryId, revision: "unverified", weavatrixVersion: "unknown",
73
+ analysisStatus: "UNAVAILABLE" as const, analysisErrorCode,
75
74
  nodes: [], relations: [], totalNodes: 0, totalRelations: 0, truncated: false,
76
- }];
75
+ });
76
+ // "Not bound" is true only without bindings here; checkouts whose analysis did not come back are named.
77
+ const reports = observed.length > 0 ? observed : bindings.length > 0
78
+ ? [...new Set(bindings.map(binding => binding.repositoryId))].map(id => unavailable(id, "ANALYSIS_NOT_FINISHED"))
79
+ : [unavailable(current.project.canonicalRepositoryId, "REPOSITORY_NOT_BOUND")];
77
80
  const receipts = requestIds?.size ? requestIds : new Set<string | undefined>([undefined]);
78
81
  for (const id of receipts) {
79
82
  await dependencies.send(client, {
@@ -1,5 +1,5 @@
1
- import { realpathSync } from "node:fs";
2
- import { isAbsolute } from "node:path";
1
+ import { realpathSync, statSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
3
  import type { ProjectBindingSummary } from "../../../../../../packages/protocol/schema";
4
4
  import { inspectRepository, inspectRepositoryAsync, type RepositoryFacts } from "../../catalog";
5
5
 
@@ -29,7 +29,16 @@ export function matchesLocalCheckout(repositoryId: string, root: string): boolea
29
29
  catch { return false; }
30
30
  }
31
31
 
32
- /** Once admitted, one checkout contributes one graph to this Mesh. */
32
+ /** A linked worktree's `.git` is a file; the main checkout's is a directory. */
33
+ function mainCheckout(root: string): boolean {
34
+ try { return statSync(join(root, ".git")).isDirectory(); } catch { return false; }
35
+ }
36
+
37
+ /**
38
+ * Once admitted, one checkout of each repository contributes one graph to this Mesh. Every worktree and
39
+ * release copy a chat visited used to be parsed in full, queued ahead of the repository a person asked
40
+ * about; the main checkout now stands for its copies, and a local folder that no longer exists is skipped.
41
+ */
33
42
  export function graphAnalysisBindings(bindings: ProjectBindingSummary[], endpointId?: string,
34
43
  inspect: (path: string) => RepositoryFacts = inspectRepository): ProjectBindingSummary[] {
35
44
  const selected = new Map<string, ProjectBindingSummary>();
@@ -42,6 +51,7 @@ export function graphAnalysisBindings(bindings: ProjectBindingSummary[], endpoin
42
51
  if (binding.available && binding.localPathHint) {
43
52
  try { path = realpathSync(binding.localPathHint); } catch { /* Keep an unavailable checkout distinct. */ }
44
53
  }
54
+ if (!path && binding.available && binding.localPathHint && binding.repositoryId.startsWith("local:")) continue;
45
55
  if (path && !observations.has(path)) {
46
56
  let facts: RepositoryFacts | undefined;
47
57
  try {
@@ -56,10 +66,11 @@ export function graphAnalysisBindings(bindings: ProjectBindingSummary[], endpoin
56
66
  const facts = path ? observations.get(path) : undefined;
57
67
  const canonical = facts?.canonicalRepositoryId === binding.repositoryId;
58
68
  const scoped = facts && matchesLocalCheckout(binding.repositoryId, facts.root);
59
- const rank = canonical ? 3 : scoped ? 2 : binding.repositoryId.startsWith("local:") ? 0 : 1;
69
+ const identity = canonical ? 3 : scoped ? 2 : binding.repositoryId.startsWith("local:") ? 0 : 1;
70
+ const rank = identity * 2 + (facts && (canonical || scoped) && mainCheckout(facts.root) ? 1 : 0);
60
71
  const candidate = (canonical || scoped) && facts?.revision
61
72
  ? { ...binding, revision: facts.revision } : binding;
62
- const key = JSON.stringify([binding.endpointId, path ?? binding.repositoryId]);
73
+ const key = JSON.stringify([binding.endpointId, facts ? facts.canonicalRepositoryId : path ?? binding.repositoryId]);
63
74
  const previous = selected.get(key);
64
75
  if (!previous || rank > (ranks.get(key) ?? 0)) {
65
76
  selected.set(key, candidate);
@@ -0,0 +1,35 @@
1
+ import type { MeshSnapshot, ProjectRepositoryGraph } from "../../../../../../packages/protocol/schema";
2
+ import { fitRepositoryGraph } from "../../../engine/runtime/repository-graph/fit";
3
+
4
+ /**
5
+ * A snapshot is sealed twice, with the task key and then for transport, and each base64 layer adds a
6
+ * third; this plaintext budget keeps the sealed frame under the relay's 1.8 MB stored-message limit.
7
+ */
8
+ export const MESH_SNAPSHOT_BUDGET_BYTES = 900_000;
9
+
10
+ const size = (value: unknown) => Buffer.byteLength(JSON.stringify(value), "utf8");
11
+
12
+ function cut(graph: ProjectRepositoryGraph, maxBytes: number): ProjectRepositoryGraph {
13
+ return fitRepositoryGraph(graph, maxBytes)
14
+ ?? { ...graph, codeMap: undefined, nodes: [], relations: [], truncated: true };
15
+ }
16
+
17
+ /**
18
+ * Each repository graph is bounded on its own, so a Project bound to many checkouts outgrew the relay
19
+ * as a whole. Graphs are shrunk first, then repository details and graphs are left out; the Project,
20
+ * its tasks and its people are never cut here.
21
+ */
22
+ export function fitMeshSnapshot(snapshot: MeshSnapshot, maxBytes = MESH_SNAPSHOT_BUDGET_BYTES): MeshSnapshot {
23
+ if (size(snapshot) <= maxBytes) return snapshot;
24
+ const graphs = snapshot.repositoryGraphs ?? [];
25
+ let fitted = snapshot;
26
+ for (const perGraph of graphs.length ? [96, 48, 24, 12] : []) {
27
+ fitted = { ...fitted, repositoryGraphs: graphs.map(graph => ({ ...cut(graph, perGraph * 1_024), truncated: true })) };
28
+ if (size(fitted) <= maxBytes) return fitted;
29
+ }
30
+ if (fitted.repositoryDetails) {
31
+ fitted = { ...fitted, repositoryDetails: undefined };
32
+ if (size(fitted) <= maxBytes) return fitted;
33
+ }
34
+ return { ...fitted, repositoryGraphs: undefined, repositoryDetails: undefined };
35
+ }
@@ -5,7 +5,11 @@ import { readNativeCredential } from "./credentials";
5
5
  import { createNativeAccountUsageReader } from "./reader";
6
6
 
7
7
  let scope = "";
8
- let reader = createNativeAccountUsageReader({ credential: readNativeCredential });
8
+ const create = () => createNativeAccountUsageReader({ credential: readNativeCredential,
9
+ report: (provider, reason) => process.stderr.write(reason
10
+ ? `[granttap-mcp] ${provider} account limits unavailable: ${reason}\n`
11
+ : `[granttap-mcp] ${provider} account limits readable again\n`) });
12
+ let reader = create();
9
13
 
10
14
  export function mergeNativeUsage(direct: ProviderAccountUsage[], statusLine: ProviderAccountUsage[],
11
15
  now = Date.now()): ProviderAccountUsage[] {
@@ -24,7 +28,7 @@ export function cachedNativeAccountUsage(): ProviderAccountUsage[] {
24
28
  const env = process.env;
25
29
  const current = [homedir(), env.GRANTTAP_CLAUDE_DIR, env.NODVOX_CLAUDE_DIR, env.CLAUDE_CONFIG_DIR,
26
30
  env.GRANTTAP_GROK_DIR, env.XDG_CONFIG_HOME, env.APPDATA].join("\u001f");
27
- if (scope !== current) { scope = current; reader = createNativeAccountUsageReader({ credential: readNativeCredential }); }
31
+ if (scope !== current) { scope = current; reader = create(); }
28
32
  void reader.refresh();
29
33
  return mergeNativeUsage(reader.current(), readClaudeUsage());
30
34
  }
@@ -5,6 +5,8 @@ type Options = {
5
5
  credential: (provider: NativeUsageProvider) => Promise<string | undefined>;
6
6
  fetcher?: (url: string, init: RequestInit) => Promise<Response>;
7
7
  clock?: () => number;
8
+ /** Told when a signed-in account's limits become unreadable or readable again; never given a credential. */
9
+ report?: (provider: NativeUsageProvider, reason: string | undefined) => void;
8
10
  };
9
11
 
10
12
  const requests = {
@@ -37,11 +39,18 @@ export function createNativeAccountUsageReader(options: Options) {
37
39
  const reports = new Map<NativeUsageProvider, ProviderAccountUsage>();
38
40
  let pending: Promise<void> | undefined;
39
41
  let attemptedAt = -Infinity;
42
+ // Missing limits used to leave no trace; one line per change of reason keeps the log readable.
43
+ const reasons = new Map<NativeUsageProvider, string | undefined>();
44
+ const note = (provider: NativeUsageProvider, reason: string | undefined) => {
45
+ if (reasons.has(provider) ? reasons.get(provider) === reason : reason === undefined) return;
46
+ reasons.set(provider, reason);
47
+ options.report?.(provider, reason);
48
+ };
40
49
 
41
50
  async function update(provider: NativeUsageProvider): Promise<void> {
42
51
  try {
43
52
  const token = await options.credential(provider);
44
- if (!token) { reports.delete(provider); return; }
53
+ if (!token) { reports.delete(provider); reasons.delete(provider); return; }
45
54
  const request = requests[provider];
46
55
  const response = await fetcher(request.url, {
47
56
  method: request.method, redirect: "error", signal: AbortSignal.timeout(8_000),
@@ -62,7 +71,11 @@ export function createNativeAccountUsageReader(options: Options) {
62
71
  }
63
72
  if (report) reports.set(provider, report);
64
73
  else reports.delete(provider);
65
- } catch { reports.delete(provider); }
74
+ note(provider, report ? undefined : response.ok ? "unrecognized response" : `HTTP ${response.status}`);
75
+ } catch (error) {
76
+ reports.delete(provider);
77
+ note(provider, error instanceof Error ? error.name : "request failed");
78
+ }
66
79
  }
67
80
 
68
81
  return {
@@ -11,15 +11,24 @@ 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
+ /** An install killed mid-way (a reboot, a full disk) leaves its lock behind; ten minutes covers a real install. */
15
+ function removeStaleLock(lock:string,now:number):void {
16
+ try {if(now-statSync(lock).mtimeMs>10*60_000)unlinkSync(lock);} catch { /* no stale lock */ }
17
+ }
18
+
14
19
  /**
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.
20
+ * Stage releases independently; automatic verification and activation wait until no request or decision is
21
+ * pending. A phone-started run can keep the monitor busy for hours, and each check would otherwise start two
22
+ * Node processes. A phone's explicit update is one check, and a hung run is exactly what it may be replacing,
23
+ * so it verifies and selects at once; the selected version starts with the next MCP restart.
17
24
  */
18
25
  export async function checkForRuntimeUpdate(options:Options):Promise<string|undefined> {
19
26
  const allowed=()=>options.manual===true || automaticUpdatesAllowed(options.stateDirectory);
27
+ const ready=()=>(options.manual===true || options.idle()) && allowed();
20
28
  if(!allowed())return;
21
29
  mkdirSync(options.stateDirectory,{recursive:true,mode:0o700});
22
30
  const lock=join(options.stateDirectory,'install.lock');let fd:number;
31
+ removeStaleLock(lock,(options.now??Date.now)());
23
32
  try {fd=openSync(lock,'wx',0o600);} catch {return undefined;}
24
33
  try {
25
34
  const release=await (options.latest??latestRelease)();
@@ -31,10 +40,10 @@ export async function checkForRuntimeUpdate(options:Options):Promise<string|unde
31
40
  if(!validRuntime(candidate,options.stateDirectory,release.version)) {
32
41
  await (options.install??installRelease)(release,options.stateDirectory);
33
42
  }
34
- if(!options.idle() || !allowed())return;
43
+ if(!ready())return;
35
44
  await (options.verify??verifyRelease)(candidate);
36
45
  if(!validRuntime(candidate,options.stateDirectory,release.version))throw Error('Runtime verification failed');
37
- if(!options.idle() || !allowed())return;
46
+ if(!ready())return;
38
47
  saveState(options.stateDirectory,{root:candidate,version:release.version,
39
48
  previous:state.root?{root:state.root,version:state.version}:undefined});
40
49
  options.activate?.(candidate);return candidate;
@@ -52,8 +61,7 @@ export function runtimeUpdateLoop(options:LoopOptions):()=>void {
52
61
  if(stopped)return;
53
62
  try {
54
63
  if(!automaticUpdatesAllowed(options.directory)){lastCheck=0;return;}
55
- const lock=join(options.directory,'install.lock');
56
- try {if(now()-statSync(lock).mtimeMs>10*60_000)unlinkSync(lock);} catch { /* no stale lock */ }
64
+ removeStaleLock(join(options.directory,'install.lock'),now());
57
65
  if(now()-lastCheck>=4*60*60_000) {
58
66
  await (options.check??checkForRuntimeUpdate)({root:options.root,stateDirectory:options.directory,idle:options.idle,
59
67
  activate:()=>options.activate?.()});
@@ -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.143
13
+ npm install -g granttap-mcp@0.8.146
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.143\";\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.146\";\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.143";
10
+ const PACKAGE = "granttap-mcp@0.8.146";
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.143",
3
+ "version": "0.8.146",
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": {
@@ -120,6 +120,10 @@ export class RelayClient {
120
120
  this.socketHealth.stop(ws);
121
121
  this.admissionLease.stop(ws);
122
122
  if (this.ws === ws) { this.reconnect.closed(openedAt, code, reason.toString()); this.ws = undefined; }
123
+ // The relay names why it closed; without this a refusal loop looked like an idle, online computer.
124
+ if (opened && code !== 1000 && code !== 1001 && code !== 1005) {
125
+ process.stderr.write(`[relay] connection closed: ${code} ${reason.toString().slice(0, 80)}\n`);
126
+ }
123
127
  if (!opened) reject(new Error(`relay connection closed (${this.cfg.relayUrl})`));
124
128
  this.scheduleReconnect();
125
129
  });
@@ -39,9 +39,21 @@ export function sealEnvelope(
39
39
  nonce,
40
40
  box,
41
41
  };
42
- return JSON.stringify(envelope);
42
+ const frame = JSON.stringify(envelope);
43
+ if (envelope.deliveryId && to !== "all" && Buffer.byteLength(frame) > MAX_STORED_FRAME_BYTES) {
44
+ throw new Error(`relay frame of ${Buffer.byteLength(frame)} bytes exceeds the stored-message limit`);
45
+ }
46
+ return frame;
43
47
  }
44
48
 
49
+ /**
50
+ * The relay stores a frame that carries a `deliveryId` until the peer confirms it, and refuses one
51
+ * larger than this by closing the sender's socket with a cool-down. A computer whose Mesh snapshot
52
+ * outgrew it reconnected every few seconds and never stayed long enough to receive a phone message,
53
+ * so such a frame is refused here and the socket stays up.
54
+ */
55
+ export const MAX_STORED_FRAME_BYTES = 1_800_000;
56
+
45
57
  /** Apply the independent task encryption layer before transport encryption. */
46
58
  export function sealSessionPayload(payload: Payload, sessionId: string, key: string | undefined): Payload {
47
59
  if (!key) throw new Error(`no encryption key for task ${sessionId}`);