granttap-mcp 0.8.175 → 0.8.177

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.
@@ -74,6 +74,8 @@ async function sendScopedPayload(input: {
74
74
  options: SendOptions;
75
75
  }): Promise<void> {
76
76
  const { client, payload, sessionId, purpose, to, options } = input;
77
+ // The relay already holds this exact state from this connection; the grant and the copy would only spend upload.
78
+ if (client.retainedUnchanged?.(payload, to, options.peerPublicKey)) return;
77
79
  const retained = retainedPayloadOptions(payload);
78
80
  const grantOptions = retained.stateKey ? {}
79
81
  : { stateKey: undefined, stateRevision: undefined, statePriority: undefined, stateGroup: undefined };
@@ -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.175
13
+ npm install -g granttap-mcp@0.8.177
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.175\";\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.177\";\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.175";
10
+ const PACKAGE = "granttap-mcp@0.8.177";
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.175",
3
+ "version": "0.8.177",
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": {
@@ -1,4 +1,5 @@
1
1
  import { retainedPayloadOptions } from "./retained-state";
2
+ import { RetainedStateLedger } from "./retained-state/ledger";
2
3
  /** Shared authenticated relay transport. See README.md for delivery and encryption boundaries. */
3
4
  import WebSocket from "ws";
4
5
  import { ManagedRelayLease, RelaySocketHealth, RelayReconnectBackoff, RelayConnectionNotifications, relayUpgradeHeaders } from "./socket-lifecycle";
@@ -38,6 +39,8 @@ export class RelayClient {
38
39
  private readonly refusalLoggedAt = new Map<string, number>();
39
40
  private readonly sessionKeys = new Map<string, string>();
40
41
  private readonly replay: RelayMessageAcceptance;
42
+ /** Read state this connection already handed to the relay, which replays it to joining phones. */
43
+ private readonly retainedSent = new RetainedStateLedger();
41
44
 
42
45
  constructor(
43
46
  private readonly cfg: PeerConfig,
@@ -91,6 +94,7 @@ export class RelayClient {
91
94
  ws.send(frame, error => error ? reject(error) : resolve());
92
95
  }));
93
96
  this.frames = frames;
97
+ this.retainedSent.forget();
94
98
  let opened = false, openedAt: number | undefined;
95
99
  const timer = setTimeout(() => {
96
100
  ws.terminate();
@@ -228,6 +232,8 @@ export class RelayClient {
228
232
  if (peerPublicKey !== this.cfg.peerPublicKey && !peers.includes(peerPublicKey)) {
229
233
  if (peers.length >= 16) throw new Error("controller device limit reached");
230
234
  this.cfg.extraPeerPublicKeys = [...peers, peerPublicKey];
235
+ // The relay holds no state for the new phone yet.
236
+ this.retainedSent.forget();
231
237
  }
232
238
  }
233
239
 
@@ -250,6 +256,15 @@ export class RelayClient {
250
256
  return this.sessionKeys.has(sessionId);
251
257
  }
252
258
 
259
+ /**
260
+ * True when a broadcast of this exact read state already reached the relay on
261
+ * this connection: the relay keeps it for every phone, so sending it again
262
+ * would only spend upload. A reply to one phone is never skipped.
263
+ */
264
+ retainedUnchanged(payload: Payload, to: Role | "all" = this.otherRole(), peerPublicKey?: string): boolean {
265
+ return this.retainedState && !peerPublicKey && this.retainedSent.unchanged(payload, to);
266
+ }
267
+
253
268
  /** Add an independent authenticated-encryption layer for one task. */
254
269
  async sendSession(
255
270
  payload: Payload,
@@ -259,6 +274,7 @@ export class RelayClient {
259
274
  ): Promise<void> {
260
275
  await this.send(sealSessionPayload(payload, sessionId, this.sessionKeys.get(sessionId)), to, { ...retainedPayloadOptions(payload), ...options,
261
276
  urgent: options.urgent === true || priorityControlPayload(payload.type) });
277
+ if (this.retainedState && !options.peerPublicKey) this.retainedSent.remember(payload, to);
262
278
  }
263
279
 
264
280
  /** Register before connect so only durable receivers advertise task-job support. */
@@ -16,6 +16,23 @@ The phone's queue is restored through the separate durable task-job API. Relay
16
16
  state caching does not execute commands or change provider policy. Older relays
17
17
  continue using live updates and the existing acknowledged mailbox.
18
18
 
19
+ `ledger.ts` remembers which read state each relay connection has already handed
20
+ over. A broadcast of that state again (`RelayClient.retainedUnchanged`) is
21
+ skipped together with its key grant: the relay keeps the copy and replays it to
22
+ joining phones. Without this the monitor resent every Mesh snapshot, plain and
23
+ enriched, and every chat head on each catalog refresh, sealed once for each
24
+ paired phone (92 projects and 17 phones on the owner's Mac): several megabytes
25
+ a second that queued its heartbeat and replies behind them.
26
+
27
+ A Mesh snapshot is compared without its observation times and with its model
28
+ list in a fixed order (`comparableMeshState`): every project carries the whole
29
+ model catalog, observed anew on each build, so otherwise every snapshot looked
30
+ new. Account usage is compared separately; a snapshot whose only news is usage
31
+ waits five minutes. The three latest copies of a state count as sent, so a Mesh
32
+ generation's plain and enriched copies are both recognised. A reply to one
33
+ phone is never skipped; a new connection and a newly added phone hand
34
+ everything over again.
35
+
19
36
  Tests live in `tests/` and run with the repository's test and release commands.
20
37
 
21
38
  GrantTap Commercial Source License; see the repository LICENSE.
@@ -0,0 +1,93 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { Payload } from '../../protocol/schema';
3
+ import { retainedPayloadOptions } from './index';
4
+
5
+ /** A Mesh snapshot whose only news is account usage waits this long, so usage reaches the phone a few times an hour. */
6
+ export const RETAINED_REFRESH_MS = 5 * 60_000;
7
+ /** A Mesh snapshot is published plain and then enriched; both are recognised as already sent. */
8
+ const RECENT_COPIES = 3;
9
+ /** Fields that say when something was looked at, not what it is. */
10
+ const OBSERVATION_KEYS = new Set(['generatedAt', 'observedAt']);
11
+
12
+ type Model = { provider: string; modelId: string; source?: string };
13
+ const isModel = (value: unknown): value is Model => !!value && typeof value === 'object'
14
+ && typeof (value as Model).provider === 'string' && typeof (value as Model).modelId === 'string';
15
+ const modelOrder = (model: Model) => `${model.provider}\0${model.modelId}\0${model.source ?? ''}`;
16
+
17
+ /**
18
+ * What a Mesh snapshot says, without when it was looked at. Every project's
19
+ * snapshot carries this computer's model catalog and account usage, observed
20
+ * anew and in no fixed order on each build. Compared as built, all 92 snapshots
21
+ * on the owner's Mac looked new on every refresh and went to all 17 phones again.
22
+ * Account usage is real news, but the same for every project: it is compared
23
+ * separately and sent at most every five minutes.
24
+ */
25
+ export function comparableMeshState(value: unknown, withUsage = false): unknown {
26
+ if (Array.isArray(value)) {
27
+ const items = value.map((item) => comparableMeshState(item, withUsage));
28
+ return items.length > 1 && items.every(isModel)
29
+ ? [...items].sort((left, right) => modelOrder(left).localeCompare(modelOrder(right))) : items;
30
+ }
31
+ if (!value || typeof value !== 'object') return value;
32
+ return Object.fromEntries(Object.entries(value)
33
+ .filter(([key]) => !OBSERVATION_KEYS.has(key) && (withUsage || key !== 'accountUsage'))
34
+ .map(([key, item]) => [key, comparableMeshState(item, withUsage)]));
35
+ }
36
+
37
+ /**
38
+ * The read state one relay connection has already handed over.
39
+ *
40
+ * The relay keeps the latest copy of each state for every phone and replays it
41
+ * when a phone joins, so giving it the same copy again only spends upload. The
42
+ * monitor republished every Mesh snapshot and every chat head on each catalog
43
+ * refresh, sealed once for each paired phone: on the owner's Mac 92 projects,
44
+ * 17 phones and several megabytes a second, with the computer's heartbeat and
45
+ * its replies queued behind them.
46
+ */
47
+ export class RetainedStateLedger {
48
+ private readonly sent = new Map<string, { same: string[]; usage: string[]; at: number }>();
49
+ private readonly digests = new WeakMap<object, { same: string; usage: string }>();
50
+
51
+ constructor(private readonly now: () => number = Date.now) {}
52
+
53
+ private slot(payload: Payload, recipient: string) {
54
+ const { stateKey } = retainedPayloadOptions(payload);
55
+ if (!stateKey) return undefined;
56
+ let digest = this.digests.get(payload);
57
+ if (!digest) {
58
+ const hash = (value: unknown) => createHash('sha256').update(JSON.stringify(value)).digest('hex');
59
+ digest = payload.type === 'mesh.snapshot'
60
+ ? { same: hash(comparableMeshState(payload)), usage: hash(comparableMeshState(payload, true)) }
61
+ : { same: hash(payload), usage: '' };
62
+ if (!digest.usage) digest.usage = digest.same;
63
+ this.digests.set(payload, digest);
64
+ }
65
+ return { key: `${stateKey}\0${recipient}`, ...digest };
66
+ }
67
+
68
+ /**
69
+ * True when the relay already holds this state from this connection. A copy
70
+ * whose only news is account usage counts as held for five minutes.
71
+ */
72
+ unchanged(payload: Payload, recipient: string): boolean {
73
+ const slot = this.slot(payload, recipient);
74
+ const entry = slot ? this.sent.get(slot.key) : undefined;
75
+ if (!slot || !entry || !entry.same.includes(slot.same)) return false;
76
+ return this.now() - entry.at < RETAINED_REFRESH_MS || entry.usage.includes(slot.usage);
77
+ }
78
+
79
+ /** Note a state the relay now holds. */
80
+ remember(payload: Payload, recipient: string): void {
81
+ const slot = this.slot(payload, recipient);
82
+ if (!slot) return;
83
+ const entry = this.sent.get(slot.key);
84
+ const keep = (list: string[] | undefined, digest: string) => [digest, ...(list ?? []).filter((item) => item !== digest)]
85
+ .slice(0, RECENT_COPIES);
86
+ this.sent.set(slot.key, { same: keep(entry?.same, slot.same), usage: keep(entry?.usage, slot.usage), at: this.now() });
87
+ }
88
+
89
+ /** A new connection or a new phone starts with nothing handed over. */
90
+ forget(): void {
91
+ this.sent.clear();
92
+ }
93
+ }