granttap-mcp 0.8.154 → 0.8.156

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.
@@ -44,7 +44,7 @@ try {
44
44
  replayPath: join(configDir(), `replay-${cfg.room}.json`),
45
45
  peerAllowed: controllerPeerGate(cfg),
46
46
  });
47
- monitor = startSessionMonitor(client, { primary: process.env.GRANTTAP_MONITOR_PRIMARY === "1" });
47
+ monitor = startSessionMonitor(client, { primary: process.env.GRANTTAP_MONITOR_PRIMARY === "1", config: cfg });
48
48
  stopTaskDispatch = startTaskDispatchMonitor({ config: cfg, client,
49
49
  isLeader: monitor.isLeader, peerAllowed: controllerPeerGate(cfg), publish: monitor.publish });
50
50
  stopTaskNetwork = startTaskNetworkMonitor({ config: cfg, client,
@@ -1,4 +1,5 @@
1
1
  import type { RelayClient } from "../../../../packages/core/relay-client";
2
+ import type { PeerConfig } from "../../../../packages/core/relay-client";
2
3
  import { startSessionMonitor as start } from "./support/runtime";
3
4
 
4
5
  export { HISTORY_PUBLISH_LIMIT, boundedCatalogHistory, publishSessionEvents } from "./handlers/catalog";
@@ -16,6 +17,6 @@ export { sweepAttachments, resolveMessageAttachments } from "./handlers/receipts
16
17
  export { handleUserMessage } from "./handlers/user-message";
17
18
  export type { SessionMonitor } from "./support/runtime";
18
19
 
19
- export function startSessionMonitor(client: RelayClient, options: { primary?: boolean } = {}) {
20
+ export function startSessionMonitor(client: RelayClient, options: { primary?: boolean; config?: PeerConfig } = {}) {
20
21
  return start(client, options);
21
22
  }
@@ -21,7 +21,7 @@ export const HEARTBEAT_INTERVAL_MS = Number(
21
21
  export async function publishHeartbeat(client: RelayClient): Promise<void> {
22
22
  await client.send(
23
23
  { type: "machine.heartbeat", machine: computerDisplayName(), createdAt: Date.now(), taskQueueImmediate: true,
24
- taskScheduleControls: true },
24
+ taskScheduleControls: true, taskActivityPreviews: true },
25
25
  "phone",
26
26
  { ttlMs: HEARTBEAT_INTERVAL_MS * 3, reliable: false },
27
27
  );
@@ -40,7 +40,7 @@ export const HELD_HEARTBEAT_TTL_MS = 60_000;
40
40
  export async function publishHeldHeartbeat(client: RelayClient): Promise<void> {
41
41
  await client.send(
42
42
  { type: "machine.heartbeat", machine: computerDisplayName(), createdAt: Date.now(), taskQueueImmediate: true,
43
- taskScheduleControls: true },
43
+ taskScheduleControls: true, taskActivityPreviews: true },
44
44
  "phone",
45
45
  { ttlMs: HELD_HEARTBEAT_TTL_MS, reliable: true },
46
46
  );
@@ -37,6 +37,8 @@ import { handleMonitorMessage } from "../handlers/inbound";
37
37
  import { decorateTaskOriginCatalog } from '../../task-origins';
38
38
  import { publishCodexQuestions } from '../../codex-questions';
39
39
  import { publishClaudeOpenQuestions } from '../../claude-open-questions';
40
+ import { startTaskActivities } from '../../task-activities';
41
+ import type { PeerConfig } from '../../../../../packages/core/relay-client';
40
42
 
41
43
  const HISTORY_INTERVAL_MS = 60_000;
42
44
  const resumedHeads = new WeakSet<RelayClient>();
@@ -176,7 +178,7 @@ async function publishMonitorTick(input: {
176
178
  * used by MCP tools. This keeps STDIO stdout clean and removes the old need for
177
179
  * a separate `granttap-mcp monitor` terminal process.
178
180
  */
179
- export function startSessionMonitor(client: RelayClient, options: { primary?: boolean } = {}): SessionMonitor {
181
+ export function startSessionMonitor(client: RelayClient, options: { primary?: boolean; config?: PeerConfig } = {}): SessionMonitor {
180
182
  const subscriptions = new Set<string>();
181
183
  const leadership = monitorLeadership(Date.now, undefined, () => client.isConnected, options.primary === true);
182
184
  restoreMonitorState(client);
@@ -186,6 +188,8 @@ export function startSessionMonitor(client: RelayClient, options: { primary?: bo
186
188
  let closed = false;
187
189
  const work = runtimeWorkTracker(() => hasPendingDeliveries() || approvalsStatus().pending.length > 0 || providerLogins.active() || deviceManagementWorkActive());
188
190
  const loadLoop = monitorLoadLoop(client, leadership);
191
+ const stopActivities = options.config ? startTaskActivities({config: options.config,
192
+ catalog: () => publishedCatalog(client), isLeader: () => !closed && client.isConnected && leadership.acquire()}) : () => {};
189
193
 
190
194
  const history = (force = false): Promise<SessionsStatus["sessions"]> => {
191
195
  if (historyRead) return historyRead;
@@ -256,6 +260,7 @@ export function startSessionMonitor(client: RelayClient, options: { primary?: bo
256
260
  canUpdate: work.idle,
257
261
  close: () => {
258
262
  closed = true;
263
+ stopActivities();
259
264
  offConnected?.();
260
265
  stopCatalog();
261
266
  stopCatalogHeads(client);
@@ -0,0 +1,20 @@
1
+ # Task activities
2
+
3
+ The public entry point is `index.ts`. A leader publishes an encrypted preview of
4
+ its existing root catalog to a phone-created Live Activity. It never scans a
5
+ provider or treats an idle execution as a completed Task. Project/Task identities
6
+ deduplicate executions; provider children remain inside their root conversation.
7
+
8
+ The phone enrolls an independent, expiring preview key encrypted to this computer.
9
+ Every publish revalidates its controller and activity scope. The relay receives
10
+ only ciphertext, opaque identities and delivery metadata. Privacy mode excludes
11
+ computer names and task text before encryption. Catalog freshness, not delivery
12
+ time, determines when the card becomes stale.
13
+
14
+ HTTP delivery has its own bounded, single-flight lane. An unavailable APNs route
15
+ does not block relay heartbeats or ordinary task delivery. Updates are coalesced
16
+ and the system may further limit Live Activity refreshes. Existing clients keep
17
+ their ordinary notifications.
18
+
19
+ This source is covered by the GrantTap Commercial Source License in `LICENSE.md`.
20
+ Third-party dependencies retain their own licenses and notices.
@@ -0,0 +1,13 @@
1
+ import { controllerPeerGate } from '../pairing/controllers';
2
+ import { TaskActivityPublisher, type ActivityPublisherOptions } from './publisher';
3
+ export { TaskActivityPublisher } from './publisher';
4
+ export { taskActivitySnapshot } from './presentation';
5
+ export { activitySubscription } from './subscription';
6
+
7
+ export function startTaskActivities(options: Omit<ActivityPublisherOptions, 'peerAllowed'>): () => void {
8
+ const publisher = new TaskActivityPublisher({...options, peerAllowed: controllerPeerGate(options.config)});
9
+ const timer = setInterval(() => void publisher.tick(), 15_000);
10
+ timer.unref();
11
+ void publisher.tick();
12
+ return () => { clearInterval(timer); publisher.close(); };
13
+ }
@@ -0,0 +1,34 @@
1
+ import { createHash } from 'node:crypto';
2
+ import type { SessionsStatus } from '../../../../packages/protocol/schema';
3
+
4
+ export type TaskActivitySnapshot = {version: 1; keyId: string; machine: string; taskCount: number;
5
+ generatedAt: number; rows: {id: string; title: string; preview: string; state: string; lastActivityAt: number}[]};
6
+
7
+ function text(value: string | undefined, bytes: number): string {
8
+ let result = '';
9
+ for (const point of (value ?? '').replace(/[\u0000-\u001f\u007f]/g, ' ').trim()) {
10
+ if (Buffer.byteLength(result + point) > bytes) break;
11
+ result += point;
12
+ }
13
+ return result;
14
+ }
15
+
16
+ /** The root catalog already owns child exclusion. Executions of one Task share one row. */
17
+ export function taskActivitySnapshot(catalog: SessionsStatus,
18
+ options: {keyId: string; previews: boolean}): TaskActivitySnapshot {
19
+ const tasks = new Map<string, SessionsStatus['sessions'][number]>();
20
+ for (const session of catalog.sessions) {
21
+ const key = session.projectId && session.taskId
22
+ ? `${session.projectId}\0${session.taskId}` : session.sessionId;
23
+ if ((tasks.get(key)?.lastActivityAt ?? -Infinity) < session.lastActivityAt) tasks.set(key, session);
24
+ }
25
+ const sorted = [...tasks].sort(([a, left], [b, right]) =>
26
+ right.lastActivityAt - left.lastActivityAt || a.localeCompare(b));
27
+ return {version: 1, keyId: options.keyId, machine: options.previews ? text(catalog.machine, 128) : 'GrantTap',
28
+ taskCount: tasks.size, generatedAt: catalog.generatedAt,
29
+ rows: options.previews ? sorted.slice(0, 2).map(([id, item]) => ({
30
+ id: createHash('sha256').update(id).digest('hex').slice(0, 24),
31
+ title: text(item.title, 128) || 'GrantTap', preview: text(item.summary, 256),
32
+ state: item.state, lastActivityAt: item.lastActivityAt,
33
+ })) : []};
34
+ }
@@ -0,0 +1,60 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import type { PeerConfig } from '../../../../packages/core/relay-client';
3
+ import type { SessionsStatus } from '../../../../packages/protocol/schema';
4
+ import { sealWithTransferKey } from '../../../../packages/core/crypto';
5
+ import { taskActivitySnapshot } from './presentation';
6
+ import { activitySubscription } from './subscription';
7
+ import { activityHTTP, type ActivityHTTP } from './transport';
8
+
9
+ export type ActivityPublisherOptions = {config: PeerConfig; catalog: () => SessionsStatus | null | undefined;
10
+ isLeader: () => boolean; peerAllowed: (key: string) => boolean; http?: ActivityHTTP; now?: () => number};
11
+
12
+ /** A separate single-flight lane consumes the published catalog; it never discovers providers. */
13
+ export class TaskActivityPublisher {
14
+ private pending?: Promise<void>;
15
+ private closed = false;
16
+ private readonly receipts = new Map<string, {fingerprint: string; sentAt: number}>();
17
+ private readonly http: ActivityHTTP;
18
+ constructor(private readonly options: ActivityPublisherOptions) { this.http = options.http ?? activityHTTP(options.config); }
19
+
20
+ tick(): Promise<void> {
21
+ if (this.pending) return this.pending;
22
+ this.pending = this.publish().catch(() => {}).finally(() => { this.pending = undefined; });
23
+ return this.pending;
24
+ }
25
+
26
+ close(): void { this.closed = true; this.receipts.clear(); }
27
+
28
+ private active(): boolean { return !this.closed && this.options.isLeader(); }
29
+
30
+ private async publish(): Promise<void> {
31
+ if (!this.active() || !this.options.config.pushAuth) return;
32
+ const now = (this.options.now ?? Date.now)();
33
+ const catalog = this.options.catalog();
34
+ if (!catalog || !Number.isFinite(catalog.generatedAt) || catalog.generatedAt > now + 30_000
35
+ || now - catalog.generatedAt > 90_000) return;
36
+ const result = await this.http('subscriptions') as {subscriptions?: unknown[]} | null;
37
+ if (!Array.isArray(result?.subscriptions) || result.subscriptions.length > 8) return;
38
+ const active = new Set<string>();
39
+ for (const record of result.subscriptions) {
40
+ if (!this.active()) return;
41
+ const subscription = activitySubscription(this.options.config, record, this.options.peerAllowed, now);
42
+ if (!subscription) continue;
43
+ active.add(subscription.activityId);
44
+ const snapshot = taskActivitySnapshot(catalog, subscription);
45
+ const fingerprint = createHash('sha256').update(JSON.stringify({...snapshot, generatedAt: 0})).digest('hex');
46
+ const prior = this.receipts.get(subscription.activityId);
47
+ if (prior && (now - prior.sentAt < 15_000
48
+ || prior.fingerprint === fingerprint && now - prior.sentAt < 60_000)) continue;
49
+ const event = snapshot.taskCount === 0 ? 'end' : 'update';
50
+ const contentState = sealWithTransferKey(snapshot, subscription.key);
51
+ if (!this.active() || !this.options.peerAllowed(subscription.peerPublicKey)) continue;
52
+ const delivered = await this.http('update', {activityId: subscription.activityId, deliveryId: randomUUID(),
53
+ event, staleDate: Math.floor((catalog.generatedAt + 90_000) / 1_000), contentState}) as
54
+ {accepted?: boolean; closed?: boolean} | null;
55
+ if (delivered?.accepted) this.receipts.set(subscription.activityId, {fingerprint, sentAt: now});
56
+ if (delivered?.closed) this.receipts.delete(subscription.activityId);
57
+ }
58
+ for (const id of this.receipts.keys()) if (!active.has(id)) this.receipts.delete(id);
59
+ }
60
+ }
@@ -0,0 +1,27 @@
1
+ import { z } from 'zod';
2
+ import type { PeerConfig } from '../../../../packages/core/relay-client';
3
+ import { openFromPeersWithIdentity } from '../../../../packages/core/crypto';
4
+
5
+ const subscription = z.object({version: z.literal(1), kind: z.literal('task.activity.subscription'),
6
+ room: z.string().min(1).max(180), activityId: z.string().regex(/^[A-Za-z0-9_-]{1,180}$/),
7
+ keyId: z.string().regex(/^[A-Za-z0-9_-]{1,80}$/), key: z.string().min(43).max(44),
8
+ expiresAt: z.number().int().positive(), previews: z.boolean()}).strict();
9
+ const route = z.object({activityId: z.string(), expiresAt: z.number(),
10
+ nonce: z.string().length(32), box: z.string().min(24).max(2048)}).strict();
11
+ export type ActivitySubscription = z.infer<typeof subscription> & {peerPublicKey: string};
12
+
13
+ export function activitySubscription(config: PeerConfig, input: unknown,
14
+ peerAllowed: (key: string) => boolean, now: number): ActivitySubscription | null {
15
+ const record = route.safeParse(input);
16
+ if (!record.success) return null;
17
+ const opened = openFromPeersWithIdentity(record.data.nonce, record.data.box, config.mySecretKey,
18
+ config.peerPublicKey, config.extraPeerPublicKeys);
19
+ if (!opened || !peerAllowed(opened.peerPublicKey)) return null;
20
+ const parsed = subscription.safeParse(opened.body);
21
+ if (!parsed.success) return null;
22
+ const value = parsed.data;
23
+ if (value.room !== config.room || value.activityId !== record.data.activityId
24
+ || value.expiresAt !== record.data.expiresAt || value.expiresAt <= now
25
+ || value.expiresAt > now + 8 * 60 * 60_000 || Buffer.from(value.key, 'base64url').length !== 32) return null;
26
+ return {...value, peerPublicKey: opened.peerPublicKey};
27
+ }
@@ -0,0 +1,27 @@
1
+ import type { PeerConfig } from '../../../../packages/core/relay-client';
2
+
3
+ export type ActivityHTTP = (path: 'subscriptions' | 'update', body?: unknown) => Promise<unknown>;
4
+
5
+ /** Never follow an HTTP redirect with the room credential. Responses and time are bounded. */
6
+ export function activityHTTP(config: PeerConfig, request: typeof fetch = fetch): ActivityHTTP {
7
+ return async (path, body) => {
8
+ if (!config.pushAuth) return null;
9
+ const url = new URL(config.relayUrl);
10
+ url.protocol = url.protocol === 'wss:' ? 'https:' : url.protocol === 'ws:' ? 'http:' : url.protocol;
11
+ if (!['https:', 'http:'].includes(url.protocol) || url.username || url.password) return null;
12
+ url.pathname = `/push/activity/${path}`;
13
+ url.search = new URLSearchParams({room: config.room}).toString(); url.hash = '';
14
+ const response = await request(url, {method: body === undefined ? 'GET' : 'POST', redirect: 'error',
15
+ headers: {Authorization: `Bearer ${config.pushAuth}`, 'Content-Type': 'application/json'},
16
+ signal: AbortSignal.timeout(8_000), body: body === undefined ? undefined : JSON.stringify(body)});
17
+ if (!response.ok || !response.body) return null;
18
+ const reader = response.body.getReader(); let bytes = 0; const chunks: Uint8Array[] = [];
19
+ while (true) {
20
+ const part = await reader.read(); if (part.done) break;
21
+ bytes += part.value.byteLength;
22
+ if (bytes > 24_000) { await reader.cancel(); return null; }
23
+ chunks.push(part.value);
24
+ }
25
+ return JSON.parse(Buffer.concat(chunks).toString('utf8')) as unknown;
26
+ };
27
+ }
@@ -64,7 +64,7 @@ export async function relay(): Promise<RelayClient | null> {
64
64
  recordPhoneSeen(phoneLastSeenAt, peerPublicKey);
65
65
  return false;
66
66
  });
67
- monitor = startSessionMonitor(client);
67
+ monitor = startSessionMonitor(client, {config});
68
68
  stopEndpointPublisher = startEndpointPublisher(config);
69
69
  }
70
70
  await client.connect();
@@ -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.154
13
+ npm install -g granttap-mcp@0.8.156
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.154\";\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.156\";\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.154";
10
+ const PACKAGE = "granttap-mcp@0.8.156";
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.154",
3
+ "version": "0.8.156",
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": {
@@ -12,6 +12,13 @@ Disconnect rejects the current write as well as queued frames. Catalog and
12
12
  history publishers can retry on the next connection even if the previous
13
13
  socket never calls its write-completion callback.
14
14
 
15
+ Supporting relays negotiate an ingress window and cumulative read receipts.
16
+ At most 64 frames then wait for relay reads, in addition to the existing pace.
17
+ Short TCP buffering or a slow relay cannot release several seconds of ordinary
18
+ traffic as one excessive burst. Controls retain queue priority and reconnecting
19
+ creates a new counter generation. Managed admission renewals use their separate
20
+ control lane. A read receipt proves no persistence, decryption or task delivery.
21
+
15
22
  Tests live in `tests/`; they include an actual WebSocket server with the relay's
16
23
  rate limit. A socket write is transport evidence, never an approval receipt.
17
24
 
@@ -17,9 +17,30 @@ export class OutboundFrameQueue {
17
17
  private closed = false;
18
18
  private timer?: NodeJS.Timeout;
19
19
  private nextAt = 0;
20
+ private ingressWindow?: number;
21
+ private sentFrames = 0;
22
+ private receivedFrames = 0;
20
23
 
21
24
  constructor(private readonly write: (frame: string) => Promise<void>, private readonly intervalMs = 6) {}
22
25
 
26
+ /** Read receipts bound TCP bursts; they never acknowledge application delivery. */
27
+ enableIngressWindow(window: number | undefined): void {
28
+ if (!Number.isSafeInteger(window) || window! < 16) return;
29
+ this.ingressWindow = Math.min(window!, 64);
30
+ this.schedule();
31
+ }
32
+
33
+ acknowledgeIngress(received: number): void {
34
+ if (this.ingressWindow === undefined || !Number.isSafeInteger(received)
35
+ || received <= this.receivedFrames || received > this.sentFrames) return;
36
+ this.receivedFrames = received;
37
+ this.schedule();
38
+ }
39
+
40
+ private get hasIngressCredit(): boolean {
41
+ return this.ingressWindow === undefined || this.sentFrames - this.receivedFrames < this.ingressWindow;
42
+ }
43
+
23
44
  send(frame: string, urgent = false): Promise<void> {
24
45
  if (this.closed) return Promise.reject(CLOSED());
25
46
  const bytes = Buffer.byteLength(frame);
@@ -45,18 +66,20 @@ export class OutboundFrameQueue {
45
66
  }
46
67
 
47
68
  private schedule(): void {
48
- if (this.closed || this.running || this.timer || (!this.controls.length && !this.snapshots.length)) return;
69
+ if (this.closed || this.running || this.timer || !this.hasIngressCredit
70
+ || (!this.controls.length && !this.snapshots.length)) return;
49
71
  this.timer = setTimeout(() => { this.timer = undefined; void this.pump(); },
50
72
  Math.max(0, this.nextAt - performance.now()));
51
73
  }
52
74
 
53
75
  private async pump(): Promise<void> {
54
- if (this.closed) return;
76
+ if (this.closed || !this.hasIngressCredit) return;
55
77
  const job = this.controls.shift() ?? this.snapshots.shift();
56
78
  if (!job) return;
57
79
  this.running = true;
58
80
  this.inFlight = job;
59
81
  this.bytes -= job.bytes;
82
+ this.sentFrames += 1;
60
83
  try {
61
84
  await this.write(job.frame);
62
85
  if (this.closed) throw CLOSED();
@@ -144,10 +144,16 @@ export class RelayClient {
144
144
  }
145
145
 
146
146
  private async onRaw(raw: string): Promise<void> {
147
- const control = parseRelayControl(raw) as { type?: string; recipientRouting?: boolean; retainedState?: boolean; retainedStateGroups?: boolean } | null;
147
+ const control = parseRelayControl(raw) as { type?: string; recipientRouting?: boolean; retainedState?: boolean;
148
+ retainedStateGroups?: boolean; ingressWindow?: number; received?: number } | null;
148
149
  if (control?.type === "relay.capabilities" && control.recipientRouting === true) {
149
150
  this.recipientRouting = true;
150
151
  this.retainedState = control.retainedState === true && control.retainedStateGroups === true;
152
+ this.frames?.enableIngressWindow(control.ingressWindow);
153
+ return;
154
+ }
155
+ if (control?.type === 'relay.ingress') {
156
+ if (typeof control.received === 'number') this.frames?.acknowledgeIngress(control.received);
151
157
  return;
152
158
  }
153
159
  if (control?.type === "relay.task-job") {
@@ -3,7 +3,7 @@ import { publicKeyIdentifier } from '../ciphertext-recipient';
3
3
 
4
4
  /** Bind optional mailbox routing to this endpoint's real encryption identity. */
5
5
  export function relayUpgradeHeaders(cfg: PeerConfig, admission: Record<string, string>, durableReceiver: boolean) {
6
- return { ...admission, 'X-GrantTap-Recipient-Routing': '1',
6
+ return { ...admission, 'X-GrantTap-Recipient-Routing': '1', 'X-GrantTap-Ingress-Flow': '1',
7
7
  'X-GrantTap-Recipient-Key-Id': publicKeyIdentifier(cfg.myPublicKey),
8
8
  ...(durableReceiver ? { 'X-GrantTap-Task-Dispatch': '1' } : {}),
9
9
  ...(cfg.pushAuth ? { Authorization: `Bearer ${cfg.pushAuth}` } : {}) };
@@ -121,6 +121,7 @@ export const MachineHeartbeat = z.object({
121
121
  createdAt: z.number().catch(() => Date.now()),
122
122
  taskQueueImmediate: z.boolean().optional(),
123
123
  taskScheduleControls: z.boolean().optional(),
124
+ taskActivityPreviews: z.boolean().optional(),
124
125
  });
125
126
  export type MachineHeartbeat = z.infer<typeof MachineHeartbeat>;
126
127