granttap-mcp 0.8.147 → 0.8.148

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.
package/README.md CHANGED
@@ -162,9 +162,10 @@ GrantTap reports the depth each provider actually exposes. Visibility does not
162
162
  imply deterministic remote blocking or full mobile continuation.
163
163
 
164
164
  The Mac app checks this runtime's local health endpoint without account login
165
- or QR scanning. A Mac App Store sandbox build then asks for explicit local
166
- access using the runtime's bounded PKCE consent flow; development builds retain
167
- private Unix IPC. Mac Settings can configure encrypted address discovery or
165
+ or QR scanning. Signed Mac builds, including local test builds, ask for explicit
166
+ local access using the runtime's bounded PKCE consent flow and authenticated
167
+ loopback desktop bridge. The MCP forwards bounded requests to its same-user
168
+ runtime IPC. Mac Settings can configure encrypted address discovery or
168
169
  install/start/stop the pinned personal relay. Runtime code remains outside the
169
170
  Apple sandbox. Mac purchase terms, optional Personal subscriptions and required
170
171
  TLS/VPN reachability are documented in the Apple client repository.
@@ -521,6 +522,10 @@ searched, and `--engine <path>` points at one that lives elsewhere; the binary
521
522
  is checksummed here, because that checksum is the only thing verified before it
522
523
  is launched. Without an engine the rollout stays off and setup says so, rather
523
524
  than leaving "Governance not reported" on the phone as the only symptom.
525
+ A paired monitor can prepare the pinned managed Engine in the background.
526
+ Inspect current readiness and coverage rather than assuming every missing
527
+ Engine requires a manual binary path; initial catalog delivery does not wait
528
+ for background preparation.
524
529
 
525
530
  The normal CLI surface is intentionally small:
526
531
 
@@ -697,11 +702,13 @@ The user-facing approval modes map to the existing runtime policy:
697
702
 
698
703
  | Personal UI | Runtime |
699
704
  | --- | --- |
700
- | Ask for risky actions | `except_push` |
701
- | Ask for every action | `ask` |
705
+ | Ask for approval | `ask` |
706
+ | Approve for me | `except_push` |
707
+ | Allow all actions | `full` |
702
708
  | Use agent defaults | no GrantTap gate for that task |
703
709
 
704
- Legacy custom levels remain compatible but are not part of the primary flow.
710
+ Custom levels remain compatible. Native provider restrictions and global deny
711
+ still apply; a selected mode is distinct from a confirmed policy receipt.
705
712
 
706
713
  ## Project Governance
707
714
 
@@ -10,8 +10,10 @@ The background monitor, MCP tool connection, desktop Task handoff, agent hooks
10
10
  and machine-role Mesh connections all use this entry point. Their leases renew
11
11
  on the existing socket; the provider conversation and task keys remain intact.
12
12
 
13
- Legacy free beta servers may not issue leases. Commercial relay mode requires
14
- a valid signed lease independently, including when a modified client omits it.
13
+ Missing account links and unavailable admission endpoints fail closed. An HTTP
14
+ 404 or 503 never becomes a free transport grant. Official TestFlight access is
15
+ issued by the account service from verified beta evidence. Commercial relay mode
16
+ also requires a valid signed lease independently of the client.
15
17
  Expiry/refund stops hosted delivery; local provider approval remains available,
16
18
  and history, pairing keys and pending decisions are retained.
17
19
 
@@ -10,16 +10,16 @@ export function managedAdmissionOptions(config: PeerConfig,
10
10
  return { connectionLeaseExpiresAt: () => expiresAt,
11
11
  upgradeHeaders: async (): Promise<Record<string, string>> => {
12
12
  const account = loadAccountLink();
13
- if (!account) return {};
13
+ if (!account) throw new Error("Sign in to your GrantTap account before connecting this computer.");
14
14
  const response = await request("https://granttap.com/api/account/machine/admission", {
15
15
  method: "POST", headers: { authorization: `Bearer ${account.machineToken}`,
16
16
  "content-type": "application/json", accept: "application/json" },
17
17
  body: JSON.stringify({ publicKey: config.myPublicKey, room: config.room }),
18
18
  signal: AbortSignal.timeout(8_000), redirect: "error",
19
19
  });
20
- // Legacy free-beta deployments predate admission. A commercial relay still
21
- // independently refuses every machine socket without a valid ticket.
22
- if (response.status === 404 || response.status === 503) return {};
20
+ if (response.status === 404 || response.status === 503) {
21
+ throw new Error("GrantTap account access could not be verified. Retry when the service is available.");
22
+ }
23
23
  if (!response.ok) throw new Error("Managed relay access or the computer limit must be renewed in GrantTap.");
24
24
  const body = await response.json() as { ticket?: unknown; expiresAt?: unknown };
25
25
  if (typeof body.ticket !== "string" || body.ticket.length > 2_048
@@ -104,7 +104,9 @@ async function monitorSnapshot(input: {
104
104
  type: "sessions.status",
105
105
  machine: computerDisplayName(),
106
106
  sessions: decorateSessions(sessions, subscriptions, inspection),
107
- history: historical ? decorateSessions(historical, subscriptions, inspection) : undefined,
107
+ // A finished chat's ring needs only its totals; the breakdown would grow every catalog.
108
+ history: historical ? decorateSessions(historical.map(({ contextUsage: _detail, ...session }) => session),
109
+ subscriptions, inspection) : undefined,
108
110
  tokensRecent,
109
111
  tokenWindowHours: TOKEN_WINDOW_HOURS,
110
112
  tokensAllTime: tokensRecent,
@@ -2,9 +2,11 @@
2
2
 
3
3
  `effective-action.ts` is the public implementation entry point for combining
4
4
  the private engine's Project decision with the existing provider/session flow.
5
- It resolves only already-known local Project state, uses one shared 50 ms IPC
6
- deadline, and falls back to the established GrantTap behavior when rollout is
7
- disabled or the engine cannot answer.
5
+ It resolves only already-known local Project state and uses the shared bounded
6
+ Engine policy IPC deadline (currently 2,000 ms). When Engine cannot answer for
7
+ a previously governed Project, policy asks rather than silently allowing the
8
+ action. A never-governed Project preserves the established GrantTap behavior.
9
+ This policy timeout is not a phone message delivery timer.
8
10
 
9
11
  `capability-fingerprint.ts` turns provider tool metadata into a bounded
10
12
  capability fingerprint. It never copies raw tool arguments, commands, secrets,
@@ -52,10 +52,21 @@ Claude Code exposes its picker metadata in the `initialize` control response
52
52
  `claude-models.ts` requests that metadata without a user message, tools, hooks,
53
53
  MCP servers or saved conversation. It preserves exact CLI values, versioned labels,
54
54
  order and supported effort levels. The Default row is represented by Automatic in
55
- the client. Account identity is discarded. A missing, failed or oversized response
56
- advertises no models. The shared cache refreshes successful metadata every ten
57
- minutes, failures after two, expires after fifteen, and never blocks catalog polling.
58
- Tests: [`tests/claude-models.test.ts`](tests/claude-models.test.ts).
55
+ the client. Account identity is discarded. Live rows win. While Claude Code is
56
+ installed (`GRANTTAP_CLAUDE_BIN`, `PATH`, the native installer or the Claude app's
57
+ copy) but the query has not answered, failed, timed out, overflowed or listed no
58
+ usable model, the catalog advertises the CLI's documented aliases (`opus`,
59
+ `sonnet`, `haiku`, `fable`, in that order), which the installed CLI resolves itself,
60
+ so the phone always has a list. Their descriptions are the phone's localization
61
+ keys. A Mac without Claude Code advertises no Claude rows and starts nothing.
62
+ The query may take 30 s: by hand it answered in 2–7 s on an idle Mac, and the
63
+ monitor runs several Claude Code processes beside it. Each new failure reason,
64
+ with the end of the CLI's stderr, is written once to the process's stderr (the
65
+ monitor log) as `[granttap] Claude Code model list unavailable, …`. The shared
66
+ cache refreshes successful metadata every ten minutes, failures after two,
67
+ expires after fifteen, and never blocks catalog polling.
68
+ Tests: [`tests/claude-models.test.ts`](tests/claude-models.test.ts),
69
+ [`tests/claude-aliases.test.ts`](tests/claude-aliases.test.ts).
59
70
 
60
71
  Claude account invalidation uses an opaque digest of account, organization and
61
72
  model-entitlement fields, rather than the modification time of `.claude.json`.
@@ -4,7 +4,7 @@ import { homedir } from 'node:os';
4
4
  import { statSync } from 'node:fs';
5
5
  import { join } from 'node:path';
6
6
  import type { AdvertisedModel } from '../../../../packages/protocol/schema';
7
- import { resolveClaudeBinary } from '../providers/claude-bin';
7
+ import { installedClaudeBinary } from '../providers/claude-bin';
8
8
  import { claudeAccountScope } from './claude-account-scope';
9
9
 
10
10
  const ID = /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,159}$/;
@@ -29,35 +29,66 @@ export function projectClaudeModels(value: unknown, endpointId: string, now: num
29
29
  });
30
30
  }
31
31
 
32
- /** No prompt, saved session, hooks, MCP children or tools. Never persists the account payload. */
32
+ /**
33
+ * `--model` documents these aliases, and the installed CLI resolves each to a
34
+ * concrete version, so none is invented here. The descriptions are the phone's
35
+ * own localization keys.
36
+ */
37
+ const ALIASES: ReadonlyArray<{ modelId: string; label: string; description: string }> = [
38
+ { modelId: 'opus', label: 'Opus', description: 'Latest Opus alias · complex reasoning tasks.' },
39
+ { modelId: 'sonnet', label: 'Sonnet', description: 'Latest Sonnet alias · everyday coding tasks.' },
40
+ { modelId: 'haiku', label: 'Haiku', description: 'Latest Haiku alias · fast, efficient simple tasks.' },
41
+ { modelId: 'fable', label: 'Fable',
42
+ description: 'Fable alias · hardest and longest-running tasks. May require usage credits.' },
43
+ ];
44
+
45
+ function claudeAliasRows(endpointId: string, now: number): AdvertisedModel[] {
46
+ return ALIASES.map((alias, priority) => ({ ...alias, provider: 'claude' as const, endpointId,
47
+ observedAt: now, source: 'advertised' as const, priority }));
48
+ }
49
+
50
+ export type ClaudeModelQuery = { timeoutMs?: number; cwd?: string; env?: NodeJS.ProcessEnv;
51
+ onFailure?: (reason: string) => void };
52
+
53
+ /**
54
+ * No prompt, saved session, hooks, MCP children or tools. Never persists the account payload.
55
+ * Startup took 2–7 s by hand on an idle Mac; a busy monitor runs several CLIs beside it.
56
+ */
33
57
  export async function readClaudeModels(binary: string, endpointId: string,
34
- options: { timeoutMs?: number; cwd?: string; env?: NodeJS.ProcessEnv } = {}): Promise<AdvertisedModel[]> {
58
+ options: ClaudeModelQuery = {}): Promise<AdvertisedModel[]> {
35
59
  return new Promise(resolve => {
60
+ const timeoutMs = options.timeoutMs ?? 30_000;
36
61
  const child = spawn(binary, ['--print', '--input-format', 'stream-json', '--output-format', 'stream-json',
37
62
  '--verbose', '--no-session-persistence', '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}',
38
63
  '--settings', '{"disableAllHooks":true}', '--tools', ''],
39
- { cwd: options.cwd ?? homedir(), env: options.env ?? process.env, stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
64
+ { cwd: options.cwd ?? homedir(), env: options.env ?? process.env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true });
40
65
  const lines = createInterface({ input: child.stdout });
41
- let bytes = 0, done = false;
42
- const stop = (rows: AdvertisedModel[] = []) => {
66
+ let bytes = 0, done = false, stderr = '';
67
+ const stop = (rows: AdvertisedModel[], failure: string) => {
43
68
  if (done) return;
44
69
  done = true; clearTimeout(timeout); lines.close(); child.stdin.destroy();
45
70
  child.kill('SIGTERM');
46
71
  const force = setTimeout(() => { child.kill('SIGKILL'); }, 1_000); force.unref();
47
72
  child.once('exit', () => clearTimeout(force));
73
+ const said = text(stderr.slice(-480));
74
+ if (!rows.length) options.onFailure?.(said ? `${failure}: ${said}` : failure);
48
75
  resolve(rows);
49
76
  };
50
- const timeout = setTimeout(() => stop(), options.timeoutMs ?? 10_000);
51
- child.on('error', () => stop()); child.on('exit', () => stop());
52
- child.stdin.on('error', () => stop());
53
- child.stdout.on('data', data => { bytes += data.length; if (bytes > 512_000) stop(); });
77
+ const timeout = setTimeout(() => stop([], `timed out after ${timeoutMs / 1000} s`), timeoutMs);
78
+ child.on('error', error => stop([], `could not start (${(error as NodeJS.ErrnoException).code ?? error.name})`));
79
+ // `close` follows the last stderr bytes, so the reason a CLI gave on its way out is kept.
80
+ child.on('close', (code, signal) => stop([], `exited with ${signal ?? `code ${code}`} before answering`));
81
+ child.stdin.on('error', () => stop([], 'closed its input before answering'));
82
+ child.stderr.on('data', data => { stderr = (stderr + data).slice(-4_000); });
83
+ child.stdout.on('data', data => { bytes += data.length; if (bytes > 512_000) stop([], 'answered with more than 512 KB'); });
54
84
  lines.on('line', line => {
55
85
  if (done || line.length > 512_000) return;
56
86
  try {
57
87
  const value = JSON.parse(line);
58
88
  if (value.type === 'control_response' && value.response?.request_id === 'granttap-model-catalog') {
59
- stop(value.response.subtype === 'success'
60
- ? projectClaudeModels(value.response.response?.models, endpointId, Date.now()) : []);
89
+ if (value.response.subtype !== 'success') {
90
+ stop([], `initialize failed (${text(value.response.error) ?? 'no reason given'})`);
91
+ } else stop(projectClaudeModels(value.response.response?.models, endpointId, Date.now()), 'listed no usable models');
61
92
  }
62
93
  } catch { /* A non-protocol line does not advertise models. */ }
63
94
  });
@@ -66,25 +97,38 @@ export async function readClaudeModels(binary: string, endpointId: string,
66
97
  });
67
98
  }
68
99
 
69
- let scope = '', report: AdvertisedModel[] = [], checkedAt = 0;
100
+ let scope = '', report: AdvertisedModel[] = [], checkedAt = 0, recorded = '';
70
101
  let pending: Promise<void> | undefined;
102
+ const stderrLog = (line: string) => { process.stderr.write(`[granttap] ${line}\n`); };
71
103
 
72
- /** Nonblocking, one bounded metadata process at a time, shared by all catalog readers. */
73
- export function cachedClaudeModels(endpointId: string, env = process.env): AdvertisedModel[] {
74
- const binary = resolveClaudeBinary(homedir(), env);
104
+ /**
105
+ * Nonblocking, one bounded metadata process at a time, shared by all catalog readers.
106
+ * Live picker rows win; an installed Claude Code without them still offers its aliases.
107
+ */
108
+ export function cachedClaudeModels(endpointId: string, env = process.env, home = homedir(),
109
+ log: (line: string) => void = stderrLog): AdvertisedModel[] {
110
+ const binary = installedClaudeBinary(home, env);
111
+ if (!binary) return [];
75
112
  const config = env.GRANTTAP_CLAUDE_DIR ?? env.NODVOX_CLAUDE_DIR ?? env.CLAUDE_CONFIG_DIR;
76
- const root = config ?? join(homedir(), '.claude');
113
+ const root = config ?? join(home, '.claude');
77
114
  const key = [endpointId, binary.path, binary.version, root,
78
- modified(join(root, '.credentials.json')), claudeAccountScope(config ? join(root, '.claude.json') : join(homedir(), '.claude.json')),
115
+ modified(join(root, '.credentials.json')), claudeAccountScope(config ? join(root, '.claude.json') : join(home, '.claude.json')),
79
116
  modified(join(root, 'settings.json')), modified(join(root, 'settings.local.json'))].join('\u001f');
80
117
  if (key !== scope) { scope = key; report = []; checkedAt = 0; }
81
- if (binary && !pending && Date.now() - checkedAt > (report.length ? 10 : 2) * 60_000) {
118
+ if (!pending && Date.now() - checkedAt > (report.length ? 10 : 2) * 60_000) {
82
119
  checkedAt = Date.now();
83
- pending = readClaudeModels(binary.path, endpointId, { env: config ? { ...env, CLAUDE_CONFIG_DIR: config } : env }).then(rows => {
84
- if (scope === key) report = rows;
85
- }).finally(() => { pending = undefined; });
120
+ const onFailure = (reason: string) => {
121
+ if (reason !== recorded) log(`Claude Code model list unavailable, offering its aliases: ${reason}`);
122
+ recorded = reason;
123
+ };
124
+ pending = readClaudeModels(binary.path, endpointId, { env: config ? { ...env, CLAUDE_CONFIG_DIR: config } : env, onFailure })
125
+ .then(rows => {
126
+ if (rows.length) recorded = '';
127
+ if (scope === key) report = rows;
128
+ }).finally(() => { pending = undefined; });
86
129
  }
87
- return report.filter(row => Date.now() - row.observedAt <= 15 * 60_000);
130
+ const live = report.filter(row => Date.now() - row.observedAt <= 15 * 60_000);
131
+ return live.length ? live : claudeAliasRows(endpointId, Date.now());
88
132
  }
89
133
 
90
134
  function modified(path: string): string {
@@ -87,6 +87,16 @@ export function installedClaudeBinaries(
87
87
  });
88
88
  }
89
89
 
90
+ /** The explicit override, else the newest installed; none when this Mac has no Claude Code. */
91
+ export function installedClaudeBinary(
92
+ home = homedir(),
93
+ env: NodeJS.ProcessEnv = process.env,
94
+ ): ClaudeBinary | undefined {
95
+ const override = env.GRANTTAP_CLAUDE_BIN ?? env.NODVOX_CLAUDE_BIN;
96
+ if (override) return versioned(override);
97
+ return installedClaudeBinaries(home, env)[0];
98
+ }
99
+
90
100
  /**
91
101
  * The Claude Code to run: the explicit override, else the newest installed,
92
102
  * else plain `claude` for PATH to resolve.
@@ -95,9 +105,7 @@ export function resolveClaudeBinary(
95
105
  home = homedir(),
96
106
  env: NodeJS.ProcessEnv = process.env,
97
107
  ): ClaudeBinary {
98
- const override = env.GRANTTAP_CLAUDE_BIN ?? env.NODVOX_CLAUDE_BIN;
99
- if (override) return versioned(override);
100
- return installedClaudeBinaries(home, env)[0] ?? { path: "claude" };
108
+ return installedClaudeBinary(home, env) ?? { path: "claude" };
101
109
  }
102
110
 
103
111
  /**
@@ -0,0 +1,25 @@
1
+ import type { ReplyResult } from "./payload/types";
2
+
3
+ /**
4
+ * Provider runs this runtime owns, keyed by the chat (or new-task key) they
5
+ * were queued under. Kept apart from delivery so the session catalog can ask
6
+ * whether a run is live without loading process control.
7
+ */
8
+ const inFlight = new Map<string, Promise<ReplyResult | null>>();
9
+
10
+ export function isDeliveryInFlight(sessionId: string): boolean { return inFlight.has(sessionId); }
11
+
12
+ /** Acknowledging a message does not finish the provider turn or permit a runtime handoff. */
13
+ export function hasPendingDeliveries(): boolean { return inFlight.size > 0; }
14
+
15
+ /** One run per key at a time; the key stays live until the provider process settles. */
16
+ export function queued(key: string, run: () => Promise<ReplyResult>): Promise<ReplyResult> {
17
+ const previous = inFlight.get(key) ?? Promise.resolve(null);
18
+ const next = previous.then(run);
19
+ const settled = next.finally(() => {
20
+ if (inFlight.get(key) === tracked) inFlight.delete(key);
21
+ });
22
+ const tracked = settled.catch(() => null);
23
+ inFlight.set(key, tracked);
24
+ return settled;
25
+ }
@@ -15,6 +15,7 @@ import { abortProcesses, runProcess } from "./process";
15
15
  import { routingPrompt } from "./payload/routing";
16
16
  import type { DeliveryOptions, ReplyResult } from "./payload/types";
17
17
  import { deliveryIntent } from './payload/identity';
18
+ import { queued } from "./in-flight";
18
19
  import {
19
20
  runCursorNew,
20
21
  runCursorResume,
@@ -23,6 +24,7 @@ import {
23
24
  } from "./process/provider-headless";
24
25
  export type { DeliveryOptions, ReplyResult } from "./payload/types";
25
26
  export { prunePreparedAttachments } from './payload/attachments';
27
+ export { hasPendingDeliveries, isDeliveryInFlight } from "./in-flight";
26
28
 
27
29
  export const GENERAL_WORKSPACE = "granttap:general";
28
30
 
@@ -33,18 +35,11 @@ export function resolveAgentWorkspace(cwd: string | undefined, agent: CodingAgen
33
35
  return path;
34
36
  }
35
37
 
36
- const inFlight = new Map<string, Promise<ReplyResult | null>>();
37
-
38
- export function isDeliveryInFlight(sessionId: string): boolean { return inFlight.has(sessionId); }
39
-
40
38
  /** New tasks are separate conversations: one long run must not hold back the next. */
41
39
  export function newTaskDeliveryKey(agent: string, operationKey?: string): string {
42
40
  return `__new_${agent}_task__${operationKey ? `:${operationKey}` : ''}`;
43
41
  }
44
42
 
45
- /** Acknowledging a message does not finish the provider turn or permit a runtime handoff. */
46
- export function hasPendingDeliveries(): boolean { return inFlight.size > 0; }
47
-
48
43
  /** Request a stop for owned processes; confirmation arrives only on process exit. */
49
44
  export function stopDeliveries(sessionId: string): number {
50
45
  try { localRoutingRequests().cancel(sessionId); } catch { /* The native stop still runs when storage is unavailable. */ }
@@ -167,17 +162,6 @@ export function createGrokSession(
167
162
  ));
168
163
  }
169
164
 
170
- function queued(key: string, run: () => Promise<ReplyResult>): Promise<ReplyResult> {
171
- const previous = inFlight.get(key) ?? Promise.resolve(null);
172
- const next = previous.then(run);
173
- const settled = next.finally(() => {
174
- if (inFlight.get(key) === tracked) inFlight.delete(key);
175
- });
176
- const tracked = settled.catch(() => null);
177
- inFlight.set(key, tracked);
178
- return settled;
179
- }
180
-
181
165
  function runDelivery(
182
166
  session: SessionInfo,
183
167
  text: string,
@@ -49,3 +49,11 @@ conversations remain on their independent refresh/request paths. A model
49
49
  end-turn record describes presentation; a CLI invocation may still own background
50
50
  work. Queue admission and runtime handoff keep the physical-invocation guard
51
51
  until that invocation returns its result.
52
+
53
+ A chat whose headless run this runtime started (`reply/in-flight.ts`, matched by
54
+ the chat or its transferred native session) is published as Working for as long
55
+ as that run executes. A long tool call can keep the transcript quiet for many
56
+ minutes, so the transcript-age rule alone would show Idle. Only Idle is
57
+ corrected: Waiting and the provider's own states stay as observed. Open chats
58
+ use the same rule, and their observation revision changes when the run starts
59
+ and ends. Tests: [`tests/freshness/owned-delivery.test.ts`](tests/freshness/owned-delivery.test.ts).
@@ -11,6 +11,7 @@ import {observeCodexTurn,codexTurnState,type CodexTurnClock} from '../sessions/s
11
11
  import {ts} from '../sessions/support/common';
12
12
  import {grokResumeActivity} from '../providers/grok-activity';
13
13
  import {cursorConversationSession} from '../sessions/cursor';
14
+ import {isDeliveryInFlight} from '../reply/in-flight';
14
15
 
15
16
  type NativeClock={revision:string;lastActivityAt:number;claude:ClaudeTurnClock;codex:CodexTurnClock};
16
17
  const clocks=new Map<string,NativeClock>();
@@ -18,13 +19,32 @@ export type SessionObservation={session:SessionInfo;revision:string};
18
19
 
19
20
  /** Discovery may have started before an open chat finished its turn. Recheck before publication. */
20
21
  export function refreshObservedCatalog(status: SessionsStatus): SessionsStatus {
21
- const refresh = (session: SessionInfo) => observeSessionExecution(session)?.session ?? session;
22
+ const refresh = (session: SessionInfo) => observeSessionExecution(session)?.session
23
+ ?? ownedRun(session, localTaskTransfers().nativeSession(session).sessionId);
22
24
  return {...status, sessions: status.sessions.map(refresh), history: status.history?.map(refresh)};
23
25
  }
24
26
 
25
27
  /** A known chat uses one bounded native tail, never discovery across unrelated projects. */
26
28
  export function observeSessionExecution(input:SessionInfo):SessionObservation|undefined {
27
29
  const native=localTaskTransfers().nativeSession(input);
30
+ const observed=observeNativeTail(input,native);
31
+ if(!observed)return;
32
+ const session=ownedRun(observed.session,native.sessionId);
33
+ // The revision moves when the run starts and ends, so an open chat republishes both times.
34
+ return session===observed.session?observed:{session,revision:`${observed.revision}:owned-run`};
35
+ }
36
+
37
+ /**
38
+ * A headless run this runtime started is still executing, however long its
39
+ * current tool call keeps the transcript quiet. Only Idle is corrected:
40
+ * Waiting and the provider's own Working stay as observed.
41
+ */
42
+ function ownedRun(session:SessionInfo,nativeId:string):SessionInfo {
43
+ if(session.state!=='idle')return session;
44
+ return isDeliveryInFlight(session.sessionId)||isDeliveryInFlight(nativeId)?{...session,state:'working'}:session;
45
+ }
46
+
47
+ function observeNativeTail(input:SessionInfo,native:SessionInfo):SessionObservation|undefined {
28
48
  if(native.agent==='cursor'){
29
49
  const current=cursorConversationSession(native.sessionId);
30
50
  return current?{session:{...input,state:current.state,lastActivityAt:current.lastActivityAt},revision:`${current.lastActivityAt}:${current.state}`}:undefined;
@@ -0,0 +1,45 @@
1
+ import type { SessionContextUsage } from "../../../../../packages/protocol/schema";
2
+
3
+ const count = (value: unknown): number | undefined =>
4
+ typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
5
+
6
+ /** What the provider said about the window itself; anything it did not say stays absent. */
7
+ export type ContextLimits = { windowTokens?: number; autoCompactAtTokens?: number };
8
+
9
+ function limits(value: ContextLimits | undefined): ContextLimits {
10
+ const windowTokens = count(value?.windowTokens) || undefined;
11
+ const autoCompactAtTokens = count(value?.autoCompactAtTokens) || undefined;
12
+ return { ...(windowTokens ? { windowTokens } : {}), ...(autoCompactAtTokens ? { autoCompactAtTokens } : {}) };
13
+ }
14
+
15
+ /** Codex's `token_count` event: the last request's input is the context it carried. */
16
+ export function codexContextReport(info: any, observedAt: number): SessionContextUsage | undefined {
17
+ const last = info?.last_token_usage;
18
+ const input = count(last?.input_tokens);
19
+ if (input == null || !(observedAt > 0)) return undefined;
20
+ const cached = Math.min(count(last?.cached_input_tokens) ?? 0, input);
21
+ const output = count(last?.output_tokens);
22
+ return { observedAt, source: "codex", usedTokens: input,
23
+ ...limits({ windowTokens: info?.model_context_window }),
24
+ ...(output != null ? { lastOutputTokens: output } : {}),
25
+ parts: [{ id: "cached-input", tokens: cached }, { id: "new-input", tokens: input - cached }] };
26
+ }
27
+
28
+ const CLAUDE_COUNTERS = ["input_tokens", "output_tokens", "cache_creation_input_tokens", "cache_read_input_tokens"];
29
+
30
+ /** A Claude assistant turn's `usage`: its prompt is what the conversation now holds. */
31
+ export function claudeContextReport(usage: any, observedAt: number, window?: ContextLimits): SessionContextUsage | undefined {
32
+ // One malformed counter rejects the row, as the session's token totals do.
33
+ if (CLAUDE_COUNTERS.some(key => usage?.[key] !== undefined && count(usage[key]) == null)) return undefined;
34
+ const input = count(usage?.input_tokens);
35
+ const written = count(usage?.cache_creation_input_tokens);
36
+ const read = count(usage?.cache_read_input_tokens);
37
+ if ((input == null && written == null && read == null) || !(observedAt > 0)) return undefined;
38
+ const parts = [{ id: "cache-read", tokens: read ?? 0 }, { id: "cache-write", tokens: written ?? 0 },
39
+ { id: "new-input", tokens: input ?? 0 }];
40
+ const used = parts.reduce((sum, part) => sum + part.tokens, 0);
41
+ if (!Number.isSafeInteger(used)) return undefined;
42
+ const output = count(usage?.output_tokens);
43
+ return { observedAt, source: "claude", usedTokens: used, ...limits(window),
44
+ ...(output != null ? { lastOutputTokens: output } : {}), parts };
45
+ }
@@ -5,6 +5,7 @@ import type { ChildThreadInfo, SessionInfo } from "../../../../../../packages/pr
5
5
  import { aggregateChildThreads, childTitle } from "../../support/child-threads";
6
6
  import { rememberCapabilityObservation } from "../../telemetry";
7
7
  import { observeClaudeTurn } from "./turn-state";
8
+ import { claudeContextReport } from "../../context-usage";
8
9
  import { LIVE_MS, safeParse, stateFor, ts } from "../../support/common";
9
10
  import { finishScan } from "../../cooperative-scan";
10
11
  import { claudeCapabilityUsage, createClaudeCapabilityCollector } from "./activity";
@@ -34,6 +35,7 @@ type ClaudeParseState = {
34
35
  tokensSession: number;
35
36
  tokensLastTurn: number;
36
37
  contextTokensUsed?: number;
38
+ contextUsage?: SessionInfo["contextUsage"];
37
39
  repositoryPaths: string[];
38
40
  changedPaths: string[];
39
41
  turnEnded: boolean;
@@ -95,6 +97,7 @@ function applyClaudeLine(d: any, state: ClaudeParseState): void {
95
97
  state.tokensLastTurn = spent;
96
98
  }
97
99
  state.contextTokensUsed = claudeContextUsage(usage) ?? state.contextTokensUsed;
100
+ if (d.isSidechain !== true) state.contextUsage = claudeContextReport(usage, ts(d.timestamp) ?? 0) ?? state.contextUsage;
98
101
  if (d.message?.model && !state.model) state.model = String(d.message.model);
99
102
  }
100
103
  if (d.message?.role === "assistant") {
@@ -273,6 +276,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
273
276
  tokensSession: state.tokensSession,
274
277
  tokensLastTurn: state.tokensLastTurn,
275
278
  contextTokensUsed: state.contextTokensUsed,
279
+ ...(state.contextUsage ? { contextUsage: state.contextUsage } : {}),
276
280
  };
277
281
  const actualChildPaths =
278
282
  state.sessionId === cachedSessionId ? childPaths : claudeChildLogPaths(file, state.sessionId);
@@ -68,6 +68,7 @@ function collectCodexRoots(candidates: CodexCandidate[]): {
68
68
  tokensLastTurn: 0,
69
69
  contextTokensUsed: latest.session.contextTokensUsed,
70
70
  contextWindow: latest.session.contextWindow,
71
+ ...(latest.session.contextUsage ? { contextUsage: latest.session.contextUsage } : {}),
71
72
  },
72
73
  observations: [],
73
74
  });
@@ -17,6 +17,7 @@ import { childTitle } from "../../support/child-threads";
17
17
  import { visibleUserText } from "../../support/activity-helpers";
18
18
  import { codexHeadRequest, isProvisionalPageTitle } from "../../support/codex-head";
19
19
  import { heartbeatDisplayText } from '../../host-heartbeat';
20
+ import { codexContextReport } from "../../context-usage";
20
21
 
21
22
  type CodexParseState = {
22
23
  sessionId: string;
@@ -36,6 +37,7 @@ type CodexParseState = {
36
37
  tokensLastTurn: number;
37
38
  contextTokensUsed?: number;
38
39
  contextWindow?: number;
40
+ contextUsage?: SessionInfo["contextUsage"];
39
41
  workdirs: string[];
40
42
  turn: CodexTurnClock;
41
43
  };
@@ -136,6 +138,7 @@ function applyCodexLine(d: any, state: CodexParseState): void {
136
138
  if (typeof input === "number" && Number.isFinite(input)) state.contextTokensUsed = input;
137
139
  const window = info.model_context_window;
138
140
  if (typeof window === "number" && Number.isFinite(window)) state.contextWindow = window;
141
+ state.contextUsage = codexContextReport(info, ts(d.timestamp) ?? 0) ?? state.contextUsage;
139
142
  }
140
143
  }
141
144
 
@@ -197,6 +200,7 @@ export function parseCodexFile(file: string): CodexCandidate | undefined {
197
200
  tokensLastTurn: state.tokensLastTurn,
198
201
  contextTokensUsed: state.contextTokensUsed,
199
202
  contextWindow: state.contextWindow,
203
+ ...(state.contextUsage ? { contextUsage: state.contextUsage } : {}),
200
204
  };
201
205
  const observations = codexCapabilityUsage(session, lines);
202
206
  const child = state.child;
@@ -64,6 +64,26 @@ export function desktopOperationTimeout(operation: unknown, input: unknown): num
64
64
  return 15_000;
65
65
  }
66
66
 
67
+ function sendDesktopResult(socket: Socket, requestId: string, result: unknown): void {
68
+ if (socket.destroyed) return;
69
+ try {
70
+ socket.end(encodeEngineFrame({
71
+ protocol_version: ENGINE_PROTOCOL_VERSION, request_id: requestId,
72
+ status: "ok", result,
73
+ }));
74
+ } catch {
75
+ try {
76
+ if (!socket.destroyed) socket.end(encodeEngineFrame({
77
+ protocol_version: ENGINE_PROTOCOL_VERSION, request_id: requestId,
78
+ status: "error", error: {
79
+ code: "ENGINE_RESPONSE_UNAVAILABLE",
80
+ message: "The local response could not be delivered.",
81
+ },
82
+ }));
83
+ } catch { socket.destroy(); }
84
+ }
85
+ }
86
+
67
87
  /** Same-user desktop channel; Task sends require an exact persisted execution link. */
68
88
  export async function startDesktopEngineBridge(options: {
69
89
  engineSocketPath?: string;
@@ -115,10 +135,7 @@ export async function startDesktopEngineBridge(options: {
115
135
  void read.then(
116
136
  (result) => {
117
137
  if (!result) { socket.destroy(); return; }
118
- if (!socket.destroyed) socket.end(encodeEngineFrame({
119
- protocol_version: ENGINE_PROTOCOL_VERSION, request_id: requestId,
120
- status: "ok", result,
121
- }));
138
+ sendDesktopResult(socket, requestId, result);
122
139
  },
123
140
  () => {
124
141
  if (!socket.destroyed) socket.end(encodeEngineFrame({
@@ -77,15 +77,42 @@ export function desktopFixtureSnapshot(
77
77
  });
78
78
  }
79
79
 
80
- /** Durable Mesh list; live Engine enrichment is requested for the selected Mesh only. */
81
- export function desktopMeshSnapshots(storePath = join(configDir(), "project-mesh.json")) {
80
+ /** Durable Mesh list; each page fits the shared 512 KiB Engine frame. */
81
+ export function desktopMeshSnapshots(
82
+ input: unknown = undefined, storePath = join(configDir(), "project-mesh.json")
83
+ ) {
84
+ const query = input == null ? {} : input;
85
+ if (typeof query !== "object" || Array.isArray(query)) throw new Error("Invalid Mesh snapshot page");
86
+ const options = query as Record<string, unknown>;
87
+ const limit = options.limit == null ? 16 : Number(options.limit);
88
+ if (!Number.isInteger(limit) || limit < 1 || limit > 64) throw new Error("Invalid Mesh snapshot page");
89
+ const after = options.after_project_id;
90
+ if (after != null && (typeof after !== "string" || after.length > 128)) {
91
+ throw new Error("Invalid Mesh snapshot page");
92
+ }
93
+ const projects = desktopWorkspace(storePath)?.projects ?? [];
94
+ const start = after == null ? 0 : projects.findIndex((project) => project.project_id === after) + 1;
95
+ if (after != null && start === 0) throw new Error("Unknown Mesh snapshot cursor");
82
96
  const models = desktopModelCatalog();
83
- return {
84
- operation: "desktop.mesh_snapshots" as const,
85
- snapshots: (desktopWorkspace(storePath)?.projects ?? []).flatMap((project) =>
86
- desktopFixtureSnapshot({ project_id: project.project_id }, storePath) ?? [])
87
- .map((snapshot, index) => withDesktopModels(snapshot, models, index === 0)),
88
- };
97
+ const snapshots: NonNullable<ReturnType<typeof desktopFixtureSnapshot>>[] = [];
98
+ let index = start;
99
+ while (index < projects.length && snapshots.length < limit) {
100
+ const project = projects[index]!;
101
+ const snapshot = desktopFixtureSnapshot({ project_id: project.project_id }, storePath);
102
+ if (!snapshot) throw new Error("Mesh snapshot unavailable");
103
+ const candidate = withDesktopModels(snapshot, models, index === 0);
104
+ const page = { operation: "desktop.mesh_snapshots", snapshots: [...snapshots, candidate],
105
+ next_after_project_id: project.project_id };
106
+ // Keep room for the protocol envelope and the caller's request identifier.
107
+ if (Buffer.byteLength(JSON.stringify(page)) > 480 * 1_024) {
108
+ if (snapshots.length === 0) throw new Error("Mesh snapshot exceeds the frame budget");
109
+ break;
110
+ }
111
+ snapshots.push(candidate);
112
+ index += 1;
113
+ }
114
+ return { operation: "desktop.mesh_snapshots" as const, snapshots,
115
+ next_after_project_id: index < projects.length ? projects[index - 1]!.project_id : undefined };
89
116
  }
90
117
 
91
118
  /** Global Task index for the Mac's Now and Tasks views. */
@@ -57,7 +57,7 @@ export function desktopReadOperation(input: {
57
57
  return Promise.resolve(desktopInstalledSkills(queryInput, storePath));
58
58
  }
59
59
  if (operation === "desktop.mesh_snapshots") {
60
- return Promise.resolve(desktopMeshSnapshots(storePath));
60
+ return Promise.resolve(desktopMeshSnapshots(queryInput, storePath));
61
61
  }
62
62
  if (operation === "desktop.live_catalog") return activity.liveCatalog(storePath);
63
63
  if (operation === "desktop.task_capabilities") return activity.capabilities(queryInput, storePath);
@@ -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.147
13
+ npm install -g granttap-mcp@0.8.148
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.147\";\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.148\";\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.147";
10
+ const PACKAGE = "granttap-mcp@0.8.148";
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.147",
3
+ "version": "0.8.148",
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": {
@@ -0,0 +1,20 @@
1
+ import { z } from "zod";
2
+
3
+ /**
4
+ * How full a chat's context window is, as its provider last reported it. `parts` add up to
5
+ * `usedTokens`; their ids are stable and the phone names them. A window or auto-compact point
6
+ * the provider did not report stays absent rather than guessed.
7
+ */
8
+ export const SessionContextUsage = z.object({
9
+ observedAt: z.number().finite().positive(),
10
+ source: z.enum(["claude", "codex"]),
11
+ usedTokens: z.number().int().nonnegative(),
12
+ windowTokens: z.number().int().positive().optional(),
13
+ autoCompactAtTokens: z.number().int().positive().optional(),
14
+ lastOutputTokens: z.number().int().nonnegative().optional(),
15
+ parts: z.array(z.object({
16
+ id: z.string().min(1).max(40),
17
+ tokens: z.number().int().nonnegative(),
18
+ }).strict()).max(16),
19
+ }).strict();
20
+ export type SessionContextUsage = z.infer<typeof SessionContextUsage>;
@@ -3,6 +3,8 @@ import { TaskTransferNotice } from "../../task-transfer";
3
3
  import { z } from "zod";
4
4
  import { CodingAgent } from "../primitives";
5
5
  import { ActivityEntry, McpServerInfo, SkillInfo } from "../capabilities";
6
+ import { SessionContextUsage } from "./context";
7
+ export { SessionContextUsage } from "./context";
6
8
  import {
7
9
  AgentId,
8
10
  AutoAcceptLevel,
@@ -91,6 +93,7 @@ export const SessionInfo = z.object({
91
93
  tokensLastTurn: z.number(),
92
94
  contextTokensUsed: z.number().optional(),
93
95
  contextWindow: z.number().optional(),
96
+ contextUsage: SessionContextUsage.optional(),
94
97
  mcpServers: z.array(McpServerInfo).optional(),
95
98
  skills: z.array(SkillInfo).optional(),
96
99
  childThreads: z.array(ChildThreadInfo).max(32).optional(),