granttap-mcp 0.8.146 → 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 +13 -6
- package/apps/bridge/src/bin/runtime/monitor.ts +13 -4
- package/apps/bridge/src/engine/runtime/engine-projects.ts +3 -1
- package/apps/bridge/src/managed-admission/README.md +4 -2
- package/apps/bridge/src/managed-admission/index.ts +4 -4
- package/apps/bridge/src/mesh/runtime/graph/analysis.ts +15 -4
- package/apps/bridge/src/monitor/relay-link/index.ts +23 -0
- package/apps/bridge/src/monitor/support/runtime.ts +3 -1
- package/apps/bridge/src/policy/README.md +5 -3
- package/apps/bridge/src/provider-model-catalog/README.md +15 -4
- package/apps/bridge/src/provider-model-catalog/claude-models.ts +67 -23
- package/apps/bridge/src/providers/claude-bin.ts +11 -3
- package/apps/bridge/src/reply/in-flight.ts +25 -0
- package/apps/bridge/src/reply/index.ts +2 -18
- package/apps/bridge/src/session-catalog/README.md +8 -0
- package/apps/bridge/src/session-catalog/observed-state.ts +21 -1
- package/apps/bridge/src/sessions/context-usage/index.ts +45 -0
- package/apps/bridge/src/sessions/scan/claude/parse.ts +4 -0
- package/apps/bridge/src/sessions/scan/codex/assemble.ts +1 -0
- package/apps/bridge/src/sessions/scan/codex/parse.ts +4 -0
- package/apps/mcp/src/desktop/engine-bridge.ts +21 -4
- package/apps/mcp/src/desktop/mesh-project.ts +35 -8
- package/apps/mcp/src/desktop/operations/index.ts +1 -1
- package/apps/mcp/src/mcp-tools/connect/idle-release.ts +25 -0
- package/apps/mcp/src/mcp-tools/connect/relay.ts +6 -0
- package/cursor-plugin/README.md +1 -1
- package/cursor-plugin/mcp.json +1 -1
- package/cursor-plugin/stdio-bootstrap.cjs +1 -1
- package/package.json +1 -1
- package/packages/core/relay-client.ts +26 -1
- package/packages/core/socket-lifecycle/link-watch/index.ts +44 -0
- package/packages/protocol/messages/sessions/context.ts +20 -0
- package/packages/protocol/messages/sessions/index.ts +3 -0
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.
|
|
166
|
-
access using the runtime's bounded PKCE consent flow
|
|
167
|
-
|
|
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
|
|
701
|
-
|
|
|
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
|
-
|
|
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
|
|
|
@@ -20,6 +20,7 @@ import { startRuntimeWatchdog } from "../../runtime-watchdog";
|
|
|
20
20
|
|
|
21
21
|
import { startTaskDispatchMonitor } from "../../task-dispatch/worker/monitor";
|
|
22
22
|
import { startTaskNetworkMonitor } from '../../task-network/runtime';
|
|
23
|
+
import { claimLinkRestart } from '../../monitor/relay-link';
|
|
23
24
|
|
|
24
25
|
let client: RelayClient;
|
|
25
26
|
let monitor: ReturnType<typeof startSessionMonitor>;
|
|
@@ -58,7 +59,7 @@ try {
|
|
|
58
59
|
process.exit(1);
|
|
59
60
|
}
|
|
60
61
|
|
|
61
|
-
const stop = (): void => {
|
|
62
|
+
const stop = (exitCode = 0): void => {
|
|
62
63
|
if (stopping) return;
|
|
63
64
|
stopping = true;
|
|
64
65
|
stopWatchdog();
|
|
@@ -70,11 +71,19 @@ const stop = (): void => {
|
|
|
70
71
|
monitor.close();
|
|
71
72
|
stopEndpointPublisher();
|
|
72
73
|
client.close();
|
|
73
|
-
void engine.stop().finally(() => process.exit(
|
|
74
|
+
void engine.stop().finally(() => process.exit(exitCode));
|
|
74
75
|
};
|
|
75
76
|
|
|
76
|
-
process.on("SIGINT", stop);
|
|
77
|
-
process.on("SIGTERM", stop);
|
|
77
|
+
process.on("SIGINT", () => stop());
|
|
78
|
+
process.on("SIGTERM", () => stop());
|
|
79
|
+
// A monitor that cannot stay on the relay looks online on the phone while no message reaches it.
|
|
80
|
+
client.onLinkStuck(report => {
|
|
81
|
+
process.stderr.write(`[monitor] cannot stay on the relay: ${report.failures} failures in five minutes, last ${report.reason}\n`);
|
|
82
|
+
if (claimLinkRestart()) {
|
|
83
|
+
process.stderr.write("[monitor] restarting for a fresh relay link\n");
|
|
84
|
+
stop(75);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
78
87
|
|
|
79
88
|
stopEngineRecovery = startEngineRecovery({
|
|
80
89
|
prepare: prepareMonitorEngine,
|
|
@@ -33,6 +33,8 @@ const pendingBindingSyncs = new Map<string, Promise<boolean>>();
|
|
|
33
33
|
// The Apple Mesh envelope is 256KiB; leave room for Tasks, bindings and receipts.
|
|
34
34
|
const MAX_REPOSITORY_GRAPH_WIRE_BYTES = 192 * 1_024 - 128;
|
|
35
35
|
const MAX_SINGLE_GRAPH_WIRE_BYTES = 192 * 1_024;
|
|
36
|
+
/** A person asked for this build; a repository the size of pytorch did not finish in two minutes. */
|
|
37
|
+
const EXPLICIT_ANALYSIS_MS = 600_000;
|
|
36
38
|
const repositoryGraphJobs = new RepositoryGraphJobs<ProjectRepositoryGraph>(Date.now,120_000,300_000,32,
|
|
37
39
|
new RepositoryGraphCache(()=>join(configDir(),"repository-graph-cache")));
|
|
38
40
|
|
|
@@ -209,7 +211,7 @@ export async function projectRepositoryGraphs(
|
|
|
209
211
|
))
|
|
210
212
|
: await Promise.all(repositories.map((binding, index) => repositoryGraphJobs.refresh(
|
|
211
213
|
JSON.stringify([projectId, binding.repositoryId, binding.revision]),
|
|
212
|
-
() => analyzeRepositoryGraph(client, projectId, binding.repositoryId,
|
|
214
|
+
() => analyzeRepositoryGraph(client, projectId, binding.repositoryId, EXPLICIT_ANALYSIS_MS, binding.revision),
|
|
213
215
|
Number.MAX_SAFE_INTEGER, observations[index],
|
|
214
216
|
)));
|
|
215
217
|
return boundRepositoryGraphs(graphs.filter((item): item is ProjectRepositoryGraph => item != null));
|
|
@@ -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
|
-
|
|
14
|
-
|
|
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)
|
|
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
|
-
|
|
21
|
-
|
|
22
|
-
|
|
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
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
1
2
|
import { projectRelationshipPeers, mergeRelationshipPeers } from "../../../engine/runtime/project-relationships";
|
|
2
3
|
import type { RelayClient } from "../../../../../../packages/core/relay-client";
|
|
3
4
|
import type { MeshSnapshot } from "../../../../../../packages/protocol/schema";
|
|
@@ -58,7 +59,12 @@ export async function analyzeProjectGraphNow(
|
|
|
58
59
|
const rejected = new Set(failures.map(report => report.repositoryId));
|
|
59
60
|
const bindings = graphAnalysisBindings((current.bindings ?? [])
|
|
60
61
|
.filter(binding => !rejected.has(binding.repositoryId)), dependencies.endpoint?.());
|
|
61
|
-
|
|
62
|
+
// The Engine analyses Git checkouts only; the Project's own folder without one is named, not dropped.
|
|
63
|
+
const endpoint = dependencies.endpoint?.();
|
|
64
|
+
const own = (current.bindings ?? []).find(binding => binding.repositoryId === current.project.canonicalRepositoryId
|
|
65
|
+
&& (!endpoint || binding.endpointId === endpoint) && binding.available && binding.localPathHint
|
|
66
|
+
&& existsSync(binding.localPathHint) && !bindings.some(selected => selected.repositoryId === binding.repositoryId));
|
|
67
|
+
if (dependencies.endpoint && !bindings.length && !failures.length && !own && current.bindings?.length) return false;
|
|
62
68
|
const [backbone, repositoryGraphs, details] = await Promise.all([
|
|
63
69
|
dependencies.backbone(projectId),
|
|
64
70
|
dependencies.graphs(projectId, bindings, { background: false }),
|
|
@@ -73,9 +79,14 @@ export async function analyzeProjectGraphNow(
|
|
|
73
79
|
analysisStatus: "UNAVAILABLE" as const, analysisErrorCode,
|
|
74
80
|
nodes: [], relations: [], totalNodes: 0, totalRelations: 0, truncated: false,
|
|
75
81
|
});
|
|
76
|
-
// "Not bound" is true only without bindings here
|
|
77
|
-
|
|
78
|
-
|
|
82
|
+
// "Not bound" is true only without bindings here. Every bound repository is named: one whose
|
|
83
|
+
// analysis did not come back used to vanish once another finished, so a Mesh of several
|
|
84
|
+
// repositories showed a single graph as if it were the whole Mesh.
|
|
85
|
+
const reported = new Set(observed.map(report => report.repositoryId));
|
|
86
|
+
const unfinished = [...new Set(bindings.map(binding => binding.repositoryId))]
|
|
87
|
+
.filter(id => !reported.has(id)).map(id => unavailable(id, "ANALYSIS_NOT_FINISHED"));
|
|
88
|
+
const needsGit = own ? [unavailable(own.repositoryId, "GIT_CHECKOUT_REQUIRED")] : [];
|
|
89
|
+
const reports = observed.length + unfinished.length + needsGit.length > 0 ? [...observed, ...unfinished, ...needsGit]
|
|
79
90
|
: [unavailable(current.project.canonicalRepositoryId, "REPOSITORY_NOT_BOUND")];
|
|
80
91
|
const receipts = requestIds?.size ? requestIds : new Set<string | undefined>([undefined]);
|
|
81
92
|
for (const id of receipts) {
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { configDir } from "../../config/runtime/paths";
|
|
4
|
+
import { writePrivateFile } from "../../config/access/write-private";
|
|
5
|
+
|
|
6
|
+
const recordPath = () => join(configDir(), "relay-link-restart.json");
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* A fresh process helps when the monitor's own link state wedged, and cannot help when the relay
|
|
10
|
+
* refuses this computer for good. One restart an hour, remembered across restarts, gives the first
|
|
11
|
+
* case its cure without turning the second into a restart loop. A record that cannot be written
|
|
12
|
+
* (a full disk) claims nothing, for the same reason.
|
|
13
|
+
*/
|
|
14
|
+
export function claimLinkRestart(now = Date.now(), spacingMs = 60 * 60_000): boolean {
|
|
15
|
+
let last = -Infinity;
|
|
16
|
+
try {
|
|
17
|
+
const value = JSON.parse(readFileSync(recordPath(), "utf8")) as { at?: unknown };
|
|
18
|
+
if (typeof value.at === "number" && Number.isFinite(value.at)) last = value.at;
|
|
19
|
+
} catch { /* no restart recorded yet */ }
|
|
20
|
+
if (last <= now && now - last < spacingMs) return false;
|
|
21
|
+
try { writePrivateFile(recordPath(), JSON.stringify({ at: now })); } catch { return false; }
|
|
22
|
+
return true;
|
|
23
|
+
}
|
|
@@ -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
|
-
|
|
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
|
|
6
|
-
|
|
7
|
-
|
|
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.
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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 {
|
|
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
|
-
/**
|
|
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:
|
|
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', '
|
|
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(
|
|
51
|
-
child.on('error',
|
|
52
|
-
|
|
53
|
-
child.
|
|
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
|
-
|
|
60
|
-
|
|
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
|
-
/**
|
|
73
|
-
|
|
74
|
-
|
|
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(
|
|
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(
|
|
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 (
|
|
118
|
+
if (!pending && Date.now() - checkedAt > (report.length ? 10 : 2) * 60_000) {
|
|
82
119
|
checkedAt = Date.now();
|
|
83
|
-
|
|
84
|
-
if (
|
|
85
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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;
|
|
81
|
-
export function desktopMeshSnapshots(
|
|
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
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
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);
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every Claude Desktop, Cursor or Codex session runs its own GrantTap MCP, and each kept a relay
|
|
3
|
+
* socket open for good under the computer's identity. The relay allows a computer only so many
|
|
4
|
+
* connections, so a dozen idle sessions left the monitor, which carries the phone's messages, no
|
|
5
|
+
* place. A session's link now closes after it goes unused, unless this process is the one leading
|
|
6
|
+
* the computer's monitoring because no separate monitor runs.
|
|
7
|
+
*/
|
|
8
|
+
export function createIdleRelease(options: {
|
|
9
|
+
idleMs: number;
|
|
10
|
+
isLeader: () => boolean;
|
|
11
|
+
release: () => void;
|
|
12
|
+
}): { touch: () => void; cancel: () => void } {
|
|
13
|
+
let timer: NodeJS.Timeout | undefined;
|
|
14
|
+
const cancel = () => { if (timer) clearTimeout(timer); timer = undefined; };
|
|
15
|
+
const touch = () => {
|
|
16
|
+
cancel();
|
|
17
|
+
timer = setTimeout(() => {
|
|
18
|
+
timer = undefined;
|
|
19
|
+
if (options.isLeader()) { touch(); return; }
|
|
20
|
+
options.release();
|
|
21
|
+
}, options.idleMs);
|
|
22
|
+
timer.unref?.();
|
|
23
|
+
};
|
|
24
|
+
return { touch, cancel };
|
|
25
|
+
}
|
|
@@ -15,12 +15,16 @@ import { confirmPendingController, controllerPeerGate } from "../../../../bridge
|
|
|
15
15
|
import { applyNetworkRoute } from "../../../../bridge/src/device-network/settings";
|
|
16
16
|
import { startEndpointPublisher } from "../../../../bridge/src/device-network/directory";
|
|
17
17
|
import { managedAdmissionOptions } from "../../../../bridge/src/managed-admission";
|
|
18
|
+
import { createIdleRelease } from "./idle-release";
|
|
18
19
|
|
|
19
20
|
const ASK_TIMEOUT_MS = Number(
|
|
20
21
|
process.env.GRANTTAP_ASK_TIMEOUT_MS ?? process.env.NODVOX_ASK_TIMEOUT_MS ?? 180_000,
|
|
21
22
|
);
|
|
22
23
|
let client: RelayClient | null = null;
|
|
23
24
|
let monitor: SessionMonitor | null = null;
|
|
25
|
+
// Longer than any question can wait for its answer, so a pending ask never loses its link.
|
|
26
|
+
const idle = createIdleRelease({ idleMs: Math.max(5 * 60_000, ASK_TIMEOUT_MS + 60_000),
|
|
27
|
+
isLeader: () => monitor?.isLeader() === true, release: () => resetRelay() });
|
|
24
28
|
let phoneLastSeenAt: number | null = null;
|
|
25
29
|
let stopEndpointPublisher = () => {};
|
|
26
30
|
|
|
@@ -64,6 +68,7 @@ export async function relay(): Promise<RelayClient | null> {
|
|
|
64
68
|
stopEndpointPublisher = startEndpointPublisher(config);
|
|
65
69
|
}
|
|
66
70
|
await client.connect();
|
|
71
|
+
idle.touch();
|
|
67
72
|
await publishHeldHeartbeat(client).catch(() => {});
|
|
68
73
|
await monitor?.publish().catch(() => {});
|
|
69
74
|
return client;
|
|
@@ -73,6 +78,7 @@ export async function relay(): Promise<RelayClient | null> {
|
|
|
73
78
|
}
|
|
74
79
|
|
|
75
80
|
export function resetRelay(): void {
|
|
81
|
+
idle.cancel();
|
|
76
82
|
stopEndpointPublisher();
|
|
77
83
|
monitor?.close();
|
|
78
84
|
monitor = null;
|
package/cursor-plugin/README.md
CHANGED
|
@@ -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.
|
|
13
|
+
npm install -g granttap-mcp@0.8.148
|
|
14
14
|
granttap setup
|
|
15
15
|
granttap status
|
|
16
16
|
```
|
package/cursor-plugin/mcp.json
CHANGED
|
@@ -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.
|
|
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.
|
|
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
|
@@ -2,6 +2,7 @@ import { retainedPayloadOptions } from "./retained-state";
|
|
|
2
2
|
/** Shared authenticated relay transport. See README.md for delivery and encryption boundaries. */
|
|
3
3
|
import WebSocket from "ws";
|
|
4
4
|
import { ManagedRelayLease, RelaySocketHealth, RelayReconnectBackoff, RelayConnectionNotifications, relayUpgradeHeaders } from "./socket-lifecycle";
|
|
5
|
+
import { RelayLinkWatch, type LinkStuckReport } from "./socket-lifecycle/link-watch";
|
|
5
6
|
import { OutboundFrameQueue, sendEncryptedPayload, priorityControlPayload } from "./outbound-scheduler";
|
|
6
7
|
import { openRelayMessage, parseRelayControl, waitForRelayPayload } from "./relay-inbound";
|
|
7
8
|
import { consumeTaskJobOffer, type TaskDispatchListener } from "./task-dispatch";
|
|
@@ -30,6 +31,11 @@ export class RelayClient {
|
|
|
30
31
|
private readonly reconnect: RelayReconnectBackoff;
|
|
31
32
|
private readonly socketHealth = new RelaySocketHealth();
|
|
32
33
|
private readonly admissionLease = new ManagedRelayLease();
|
|
34
|
+
private readonly linkStuckListeners = new Set<(report: LinkStuckReport) => void>();
|
|
35
|
+
private readonly linkWatch = new RelayLinkWatch({ onStuck: report => {
|
|
36
|
+
for (const listener of this.linkStuckListeners) { try { listener(report); } catch { /* the watch outlives a listener */ } }
|
|
37
|
+
} });
|
|
38
|
+
private readonly refusalLoggedAt = new Map<string, number>();
|
|
33
39
|
private readonly sessionKeys = new Map<string, string>();
|
|
34
40
|
private readonly replay: RelayMessageAcceptance;
|
|
35
41
|
|
|
@@ -88,6 +94,7 @@ export class RelayClient {
|
|
|
88
94
|
|
|
89
95
|
ws.on("open", () => {
|
|
90
96
|
opened = true;
|
|
97
|
+
this.linkWatch.opened();
|
|
91
98
|
clearTimeout(timer);
|
|
92
99
|
openedAt = Date.now();
|
|
93
100
|
this.socketHealth.start(ws, this.opts.pingIntervalMs ?? 20_000);
|
|
@@ -107,12 +114,13 @@ export class RelayClient {
|
|
|
107
114
|
ws.on("message", (data: WebSocket.RawData) => void this.onRaw(data.toString()).catch(() => {}));
|
|
108
115
|
ws.on('unexpected-response', (_request, response) => {
|
|
109
116
|
this.reconnect.defer(response.headers['retry-after']);
|
|
117
|
+
this.noteRefusal(response.statusCode, response.headers['x-hostwatch-client-limit']);
|
|
110
118
|
response.resume(); ws.terminate();
|
|
111
119
|
clearTimeout(timer); reject(new Error('Relay upgrade was not accepted.'));
|
|
112
120
|
});
|
|
113
121
|
ws.on("error", (err) => {
|
|
114
122
|
clearTimeout(timer);
|
|
115
|
-
if (!opened) reject(err);
|
|
123
|
+
if (!opened) { this.linkWatch.failed((err as NodeJS.ErrnoException).code ?? "connect error"); reject(err); }
|
|
116
124
|
});
|
|
117
125
|
ws.on("close", (code, reason) => {
|
|
118
126
|
frames.cancel();
|
|
@@ -120,6 +128,7 @@ export class RelayClient {
|
|
|
120
128
|
this.socketHealth.stop(ws);
|
|
121
129
|
this.admissionLease.stop(ws);
|
|
122
130
|
if (this.ws === ws) { this.reconnect.closed(openedAt, code, reason.toString()); this.ws = undefined; }
|
|
131
|
+
if (opened) this.linkWatch.closed(code, reason.toString().slice(0, 80));
|
|
123
132
|
// The relay names why it closed; without this a refusal loop looked like an idle, online computer.
|
|
124
133
|
if (opened && code !== 1000 && code !== 1001 && code !== 1005) {
|
|
125
134
|
process.stderr.write(`[relay] connection closed: ${code} ${reason.toString().slice(0, 80)}\n`);
|
|
@@ -254,6 +263,22 @@ export class RelayClient {
|
|
|
254
263
|
}
|
|
255
264
|
|
|
256
265
|
/** Observe each actual socket recovery so replaceable snapshots are sent immediately. */
|
|
266
|
+
/** Told when this computer cannot stay on the relay; see `RelayLinkWatch`. */
|
|
267
|
+
onLinkStuck(listener: (report: LinkStuckReport) => void): () => void {
|
|
268
|
+
this.linkStuckListeners.add(listener);
|
|
269
|
+
return () => { this.linkStuckListeners.delete(listener); };
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** A refused upgrade is a failure for the watch, and its reason is logged once per ten minutes. */
|
|
273
|
+
private noteRefusal(status: number | undefined, limit: string | string[] | undefined): void {
|
|
274
|
+
const reason = `${status ?? "?"} ${typeof limit === "string" && /^[a-z-]{1,40}$/.test(limit) ? limit : ""}`.trim();
|
|
275
|
+
this.linkWatch.failed(reason);
|
|
276
|
+
const now = Date.now();
|
|
277
|
+
if (now - (this.refusalLoggedAt.get(reason) ?? -Infinity) < 10 * 60_000) return;
|
|
278
|
+
this.refusalLoggedAt.set(reason, now);
|
|
279
|
+
process.stderr.write(`[relay] upgrade refused: ${reason}\n`);
|
|
280
|
+
}
|
|
281
|
+
|
|
257
282
|
onConnected(listener: () => void | Promise<void>): () => void {
|
|
258
283
|
return this.connections.subscribe(listener);
|
|
259
284
|
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export type LinkStuckReport = { failures: number; reason: string };
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Notices a computer that cannot stay on the relay. Each refused upgrade, and each socket that
|
|
5
|
+
* closes before it held for a minute, is a failure; six inside five minutes with no link that held
|
|
6
|
+
* is reported once per ten minutes with the relay's last reason. On 2026-11-05 the monitor was
|
|
7
|
+
* refused for hours while the phone showed the computer online, and nothing said why.
|
|
8
|
+
*/
|
|
9
|
+
export class RelayLinkWatch {
|
|
10
|
+
private failures: number[] = [];
|
|
11
|
+
private openedAt?: number;
|
|
12
|
+
private reportedAt = -Infinity;
|
|
13
|
+
|
|
14
|
+
constructor(private readonly options: {
|
|
15
|
+
onStuck: (report: LinkStuckReport) => void;
|
|
16
|
+
now?: () => number;
|
|
17
|
+
windowMs?: number;
|
|
18
|
+
holdMs?: number;
|
|
19
|
+
threshold?: number;
|
|
20
|
+
quietMs?: number;
|
|
21
|
+
}) {}
|
|
22
|
+
|
|
23
|
+
private get now(): number { return (this.options.now ?? Date.now)(); }
|
|
24
|
+
|
|
25
|
+
opened(): void { this.openedAt = this.now; }
|
|
26
|
+
|
|
27
|
+
closed(code: number, reason: string): void {
|
|
28
|
+
const opened = this.openedAt;
|
|
29
|
+
this.openedAt = undefined;
|
|
30
|
+
if (opened === undefined) return;
|
|
31
|
+
if (this.now - opened >= (this.options.holdMs ?? 60_000)) { this.failures = []; return; }
|
|
32
|
+
this.failed(`${code} ${reason}`.trim());
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
failed(reason: string): void {
|
|
36
|
+
const now = this.now;
|
|
37
|
+
const window = this.options.windowMs ?? 5 * 60_000;
|
|
38
|
+
this.failures = [...this.failures.filter(at => now - at < window), now];
|
|
39
|
+
if (this.failures.length < (this.options.threshold ?? 6)) return;
|
|
40
|
+
if (now - this.reportedAt < (this.options.quietMs ?? 10 * 60_000)) return;
|
|
41
|
+
this.reportedAt = now;
|
|
42
|
+
this.options.onStuck({ failures: this.failures.length, reason });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
@@ -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(),
|