granttap-mcp 0.8.192 → 0.8.194
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/apps/bridge/src/monitor/support/runtime.ts +4 -0
- package/apps/bridge/src/session-catalog/README.md +4 -8
- package/apps/bridge/src/session-catalog/started-children/README.md +45 -0
- package/apps/bridge/src/session-catalog/started-children/beyond-window.ts +100 -0
- package/apps/bridge/src/session-catalog/started-children/index.ts +91 -0
- package/apps/bridge/src/session-catalog/started-children/ledger.ts +138 -0
- package/apps/bridge/src/session-catalog/started-children/publish.ts +69 -0
- package/apps/bridge/src/sessions/catalog.ts +7 -3
- package/apps/bridge/src/sessions/provider-discovery/index.ts +15 -5
- package/apps/bridge/src/sessions/scan/codex/index.ts +1 -0
- package/apps/bridge/src/started-by/README.md +3 -1
- package/apps/bridge/src/started-by/index.ts +3 -3
- package/apps/bridge/src/started-by/links.ts +7 -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/outbound-scheduler/README.md +7 -0
- package/packages/core/outbound-scheduler/index.ts +2 -1
- package/packages/protocol/messages/README.md +12 -3
- package/packages/protocol/messages/sessions/index.ts +22 -5
- package/packages/protocol/schema.ts +2 -0
- package/apps/bridge/src/session-catalog/started-children.ts +0 -36
|
@@ -30,6 +30,7 @@ import type { UpdateBlocker } from "../../runtime-updates/drain";
|
|
|
30
30
|
import { singleFlightPublisher } from "./single-flight";
|
|
31
31
|
import { publishedCatalog, rememberPublishedCatalog, resumePublishedChats,
|
|
32
32
|
publishCatalogHeads, stopCatalogHeads } from "../../session-catalog";
|
|
33
|
+
import { publishStartedChildren, settleRunsBeyondWindow } from "../../session-catalog/started-children";
|
|
33
34
|
import { createMachineLoadPublisher } from "../../machine-load";
|
|
34
35
|
import { startMachineLoadLoop } from "../../machine-load/host/loop";
|
|
35
36
|
import { captureStartedRunsNow } from "../../machine-load/host/process-sampler";
|
|
@@ -187,6 +188,9 @@ async function publishMonitorTick(input: {
|
|
|
187
188
|
cachedNativeAccountUsage).catch(() => {});
|
|
188
189
|
void keepNotedChatPictures().catch(() => {});
|
|
189
190
|
publishCatalogHeads(client, status, subscriptions, publishSessionEvents);
|
|
191
|
+
// Which chats each listed chat started, for chats the phone keeps from before; then runs past the window.
|
|
192
|
+
void publishStartedChildren(client, status, Date.now(), INTERVAL_MS * 24).catch(() => {});
|
|
193
|
+
void settleRunsBeyondWindow().catch(() => {});
|
|
190
194
|
if (loadRuntimeConfig().meshEnabled) publishMonitorMeshes(client, status);
|
|
191
195
|
publishMonitorCapabilities(client, status, () => history(false));
|
|
192
196
|
return { lastHistoryPublishedAt };
|
|
@@ -15,14 +15,10 @@ in the background. Fresh discovery replaces that saved state. Closed-history
|
|
|
15
15
|
discovery runs separately from the first live publication. The phone continues
|
|
16
16
|
its durable historical backfill independently.
|
|
17
17
|
|
|
18
|
-
**Runs another chat started** (`started-children.
|
|
19
|
-
runs
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
stay rows, and the full catalog still finds every child for a phone that opens it or a message for it.
|
|
23
|
-
Finished children are not refreshed as bulk transcript heads either; an open one still is. With 600
|
|
24
|
-
finished runs a catalog went from 635 rows (about 0.3 MB, sealed per phone each refresh) to 38 rows
|
|
25
|
-
under 20 KB (`tests/started-children/`).
|
|
18
|
+
**Runs another chat started** ([`started-children/`](started-children/README.md)). Among the finished
|
|
19
|
+
runs one listed chat started, the newest three stay rows; the parent carries `startedChildren`, counted
|
|
20
|
+
over every run it is known to have started, also those past the catalog's window, and the phone is told
|
|
21
|
+
the ids of all of them (`sessions.children`).
|
|
26
22
|
|
|
27
23
|
Tests live in `tests/`. This runtime module uses the repository GrantTap Commercial Source License.
|
|
28
24
|
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# Runs another chat started, in the catalog
|
|
2
|
+
|
|
3
|
+
Public entry: [`index.ts`](index.ts). Part of the [session catalog](../README.md); the links themselves
|
|
4
|
+
come from [started-by](../../started-by/README.md).
|
|
5
|
+
|
|
6
|
+
A chat that starts hundreds of short headless runs (`codex exec` per picture) does not get hundreds of
|
|
7
|
+
catalog rows. Among the finished runs one listed chat started, the newest three stay rows; the parent
|
|
8
|
+
carries `startedChildren { finished, stopped, limited, pictures, lastAt }`. Running children and
|
|
9
|
+
children whose parent is not listed stay rows, and the full catalog still finds every child for a
|
|
10
|
+
phone that opens it or a message for it. Finished children are not refreshed as bulk transcript heads
|
|
11
|
+
either; an open one still is. With 600 finished runs a catalog went from 635 rows (about 0.3 MB, sealed
|
|
12
|
+
per phone each refresh) to 38 rows under 20 KB (`tests/compaction.test.ts`).
|
|
13
|
+
|
|
14
|
+
**Every run, not the window's** (`ledger.ts`). The catalog reads each provider's newest 200
|
|
15
|
+
transcripts. A course chat on 17 November 2026 started 909 Codex runs in a day; the parent counted
|
|
16
|
+
the newest 200 alone ("200 of 200 stopped"). Each finished run a catalog sees is now written down
|
|
17
|
+
under the chat that started it, once: how it ended (answered; stopped by a usage or rate limit, as
|
|
18
|
+
the phone reads a limit; stopped on another error), whether it saved a picture, and when. The counts
|
|
19
|
+
on the parent are those of every run written down, together with the listed ones: `finished` all of
|
|
20
|
+
them, `stopped` every stop, `limited` the limit stops among them, `pictures` those with a picture. The
|
|
21
|
+
newest rows are counted too. `started-runs.json` in the config folder keeps ids, an outcome letter and
|
|
22
|
+
a time, at most 20,000 runs over six months, the oldest let go first; no folder or request.
|
|
23
|
+
|
|
24
|
+
**Past the window** (`beyond-window.ts`). Runs that left the window before a catalog saw them
|
|
25
|
+
finished, or before this runtime ran, are read at most once a minute by the leading monitor after it
|
|
26
|
+
publishes a catalog: the up to 2,000 Codex rollouts just past the window, no more than two days old
|
|
27
|
+
(older ones cannot be linked from a transcript any more), skipping by file name those written down
|
|
28
|
+
and reading again only a changed file. Each headless one is linked by the catalog's own rules against
|
|
29
|
+
the chats the last catalog read that ran commands, and written down. On the course's 909 runs the
|
|
30
|
+
first pass read 709 rollouts in about 2 s; later passes read none.
|
|
31
|
+
|
|
32
|
+
**The ids, for the phone** (`publish.ts`). A phone keeps what it was once sent: an older catalog's row
|
|
33
|
+
of a run, made before runs named their parent, and the Mesh Task an older runtime made for it. A count
|
|
34
|
+
does not say which of those are runs. For each listed parent with runs, the monitor sends
|
|
35
|
+
`sessions.children { parent, children, total }`: every run written down and every link, newest first,
|
|
36
|
+
at most 4,000 ids. It is sent once, again when the list changes (at most once a minute while a script
|
|
37
|
+
still starts runs), and every quarter hour for a phone that was away; nothing in between. The course
|
|
38
|
+
parent's list is 909 ids in 35.6 KB, against a 200 KB catalog sent every 30 s.
|
|
39
|
+
|
|
40
|
+
Tests: `tests/ledger.test.ts` (outcomes, rewrites, caps, unreadable and unwritable files),
|
|
41
|
+
`tests/beyond-window.test.ts` (a course of 230 runs, 30 past the window: linked, counted once, a run
|
|
42
|
+
past two days, a person's chat and another folder left alone), `tests/publish.test.ts` (what is sent,
|
|
43
|
+
when, its size and bounds), `tests/compaction.test.ts`.
|
|
44
|
+
|
|
45
|
+
This runtime module uses the repository GrantTap Commercial Source License.
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs another chat started that the catalog's window no longer reads.
|
|
3
|
+
*
|
|
4
|
+
* A catalog reads each provider's newest 200 transcripts, so a script that starts hundreds of
|
|
5
|
+
* `codex exec` runs pushes its earlier ones out within the hour: they were never linked to the chat
|
|
6
|
+
* that started them, never counted on it, and a phone that had them as chats kept them as chats of
|
|
7
|
+
* their own. At most once a minute, on the leading monitor, this pass reads the Codex rollouts just
|
|
8
|
+
* beyond the window that are no more than two days old and not yet written down, links each headless
|
|
9
|
+
* one by the same rules as the catalog (`started-by`: its request, else its folder, against the
|
|
10
|
+
* chats the last catalog read), and writes down how each linked run ended (`ledger.ts`). A rollout
|
|
11
|
+
* whose run is written down is skipped by its file name, without being read; one read before is read
|
|
12
|
+
* again only when it changed. Requests and answers are not kept.
|
|
13
|
+
*/
|
|
14
|
+
import { statSync } from "node:fs";
|
|
15
|
+
import { setImmediate } from "node:timers/promises";
|
|
16
|
+
import { parseCodexFile } from "../../sessions/scan/codex";
|
|
17
|
+
import { codexSessionsRoot, MAX_FILES, recentLogs } from "../../sessions/support/common";
|
|
18
|
+
import { providerScanEnabled } from "../../sessions/provider-discovery";
|
|
19
|
+
import { startedByKey, startedByParents, TRANSCRIPT_MATCH_MS, type LineageFact } from "../../started-by";
|
|
20
|
+
import { countedRun, countedRuns, countStartedRuns, type CountedRun } from "./ledger";
|
|
21
|
+
|
|
22
|
+
/** How many rollouts beyond the window one pass looks at, newest first. */
|
|
23
|
+
export const BEYOND_WINDOW_FILES = 2_000;
|
|
24
|
+
const PASS_EVERY_MS = 60_000;
|
|
25
|
+
/** A rollout file names its session: `rollout-<time>-<uuid>.jsonl`. */
|
|
26
|
+
const ROLLOUT_ID = /-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i;
|
|
27
|
+
|
|
28
|
+
type Read = { mtimeMs: number; size: number; fact?: LineageFact; run?: CountedRun };
|
|
29
|
+
|
|
30
|
+
let parents: LineageFact[] = [];
|
|
31
|
+
const reads = new Map<string, Read>();
|
|
32
|
+
let running: Promise<number> | undefined;
|
|
33
|
+
let lastPassAt = 0;
|
|
34
|
+
|
|
35
|
+
/** The chats the last catalog read that ran commands: the only ones a run can be linked to. */
|
|
36
|
+
export function noteCatalogParents(facts: readonly LineageFact[]): void {
|
|
37
|
+
parents = facts.filter((fact) => fact.calls?.length || fact.launches?.length);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** One rollout's lineage and outcome: from the last read when the file has not changed. */
|
|
41
|
+
function readRollout(file: string, mtimeMs: number, size: number): Read {
|
|
42
|
+
const known = reads.get(file);
|
|
43
|
+
if (known && known.mtimeMs === mtimeMs && known.size === size) return known;
|
|
44
|
+
const candidate = parseCodexFile(file);
|
|
45
|
+
const fact = candidate && !candidate.child && candidate.lineage?.headless
|
|
46
|
+
&& (candidate.requested !== false || candidate.session.summary) ? candidate.lineage : undefined;
|
|
47
|
+
const read: Read = { mtimeMs, size, fact,
|
|
48
|
+
run: fact && candidate ? countedRun(candidate.session, Boolean(candidate.pictures?.length)) : undefined };
|
|
49
|
+
reads.set(file, read);
|
|
50
|
+
return read;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
type PassOptions = { now?: number; window?: number; depth?: number };
|
|
54
|
+
|
|
55
|
+
async function pass({ now = Date.now(), window = MAX_FILES, depth = BEYOND_WINDOW_FILES }: PassOptions): Promise<number> {
|
|
56
|
+
if (parents.length === 0 || !providerScanEnabled("codex")) return 0;
|
|
57
|
+
const files = recentLogs(codexSessionsRoot(), 5, window + depth).slice(window);
|
|
58
|
+
const counted = countedRuns();
|
|
59
|
+
const seen = new Set<string>();
|
|
60
|
+
const found: Read[] = [];
|
|
61
|
+
for (const [index, file] of files.entries()) {
|
|
62
|
+
if (index % 16 === 15) await setImmediate();
|
|
63
|
+
const id = ROLLOUT_ID.exec(file)?.[1];
|
|
64
|
+
if (id && counted.has(id)) continue;
|
|
65
|
+
let stat;
|
|
66
|
+
try { stat = statSync(file); } catch { continue; }
|
|
67
|
+
// Newest first: past two days no run can be linked from a transcript any more.
|
|
68
|
+
if (now - stat.mtimeMs > TRANSCRIPT_MATCH_MS) break;
|
|
69
|
+
seen.add(file);
|
|
70
|
+
const read = readRollout(file, stat.mtimeMs, stat.size);
|
|
71
|
+
if (read.fact) found.push(read);
|
|
72
|
+
}
|
|
73
|
+
for (const file of reads.keys()) if (!seen.has(file)) reads.delete(file);
|
|
74
|
+
if (found.length === 0) return 0;
|
|
75
|
+
const links = startedByParents([...parents, ...found.map((read) => read.fact!)], now);
|
|
76
|
+
return countStartedRuns(found.flatMap(({ fact, run }) => {
|
|
77
|
+
const link = run ? links.get(startedByKey(fact!)) : undefined;
|
|
78
|
+
return link ? [{ parent: link.parent, run: run! }] : [];
|
|
79
|
+
}), now);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Link and count the runs beyond the window. Single-flight, and at most once a minute unless `force`.
|
|
84
|
+
* Returns how many runs were newly written down.
|
|
85
|
+
*/
|
|
86
|
+
export function settleRunsBeyondWindow(options: PassOptions & { force?: boolean } = {}): Promise<number> {
|
|
87
|
+
const now = options.now ?? Date.now();
|
|
88
|
+
if (running) return running;
|
|
89
|
+
if (!options.force && now - lastPassAt < PASS_EVERY_MS && now >= lastPassAt) return Promise.resolve(0);
|
|
90
|
+
lastPassAt = now;
|
|
91
|
+
running = pass({ ...options, now }).finally(() => { running = undefined; });
|
|
92
|
+
return running;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** For tests: forget what was read and when the last pass ran. */
|
|
96
|
+
export function forgetBeyondWindow(): void {
|
|
97
|
+
parents = [];
|
|
98
|
+
reads.clear();
|
|
99
|
+
lastPassAt = 0;
|
|
100
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hundreds of short headless runs one chat started (`codex exec` per picture) are not hundreds of
|
|
3
|
+
* catalog rows. A finished run another chat started is kept as a row only among the newest few of
|
|
4
|
+
* that parent's; the rest are counted on the parent as `startedChildren`. A running child, a child
|
|
5
|
+
* whose parent is not in the list, and every other chat stay rows. The full catalog still finds a
|
|
6
|
+
* child that is no row (a phone opening it, a message for it).
|
|
7
|
+
*
|
|
8
|
+
* The counts cover every run the parent is known to have started, not only the ones the catalog's
|
|
9
|
+
* window still reads: each finished run is written down when a catalog sees it (`ledger.ts`), and
|
|
10
|
+
* runs the window never held are read by a slower pass (`beyond-window.ts`).
|
|
11
|
+
*/
|
|
12
|
+
import type { SessionInfo } from "../../../../../packages/protocol/schema";
|
|
13
|
+
import { lineageAgent, type StartedBy } from "../../started-by";
|
|
14
|
+
import { countedRun, countedRuns, countStartedRuns, type CountedRun } from "./ledger";
|
|
15
|
+
|
|
16
|
+
export { countedRun, countedRuns, countStartedRuns, startedRunsPath, type CountedRun } from "./ledger";
|
|
17
|
+
export { noteCatalogParents, settleRunsBeyondWindow } from "./beyond-window";
|
|
18
|
+
export { publishStartedChildren, startedChildIds, MAX_PUBLISHED_CHILDREN } from "./publish";
|
|
19
|
+
|
|
20
|
+
/** Finished children of one parent kept as rows, newest first. */
|
|
21
|
+
export const FINISHED_CHILD_ROWS = 3;
|
|
22
|
+
|
|
23
|
+
type Summary = NonNullable<SessionInfo["startedChildren"]>;
|
|
24
|
+
|
|
25
|
+
const key = (agent: string, sessionId: string) => `${agent}\0${sessionId}`;
|
|
26
|
+
|
|
27
|
+
/** Each finished child this list holds, written down under the chat that started it. */
|
|
28
|
+
export function recordStartedChildren(sessions: readonly SessionInfo[], now = Date.now()): number {
|
|
29
|
+
const found = sessions.flatMap((session) => {
|
|
30
|
+
const run = session.startedBy ? countedRun(session) : undefined;
|
|
31
|
+
return run ? [{ parent: session.startedBy as StartedBy, run }] : [];
|
|
32
|
+
});
|
|
33
|
+
try {
|
|
34
|
+
return found.length ? countStartedRuns(found, now) : 0;
|
|
35
|
+
} catch {
|
|
36
|
+
return 0; // Written down by the next catalog; this one counts from its own rows.
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** What every finished run a chat started came to: the written-down runs and the listed ones. */
|
|
41
|
+
function summary(counted: ReadonlyMap<string, CountedRun>, listed: readonly CountedRun[]): Summary | undefined {
|
|
42
|
+
if (counted.size === 0 && listed.length === 0) return undefined;
|
|
43
|
+
const runs = new Map(counted);
|
|
44
|
+
for (const run of listed) runs.set(run.sessionId, run);
|
|
45
|
+
if (runs.size === 0) return undefined;
|
|
46
|
+
let stopped = 0, limited = 0, pictures = 0, lastAt = 0;
|
|
47
|
+
for (const run of runs.values()) {
|
|
48
|
+
if (run.end !== "answered") stopped += 1;
|
|
49
|
+
if (run.end === "limit") limited += 1;
|
|
50
|
+
if (run.picture) pictures += 1;
|
|
51
|
+
lastAt = Math.max(lastAt, run.at);
|
|
52
|
+
}
|
|
53
|
+
return { finished: runs.size, stopped, limited, pictures, lastAt };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The finished children each listed parent has among these rows. */
|
|
57
|
+
function finishedChildren(sessions: readonly SessionInfo[]): Map<string, SessionInfo[]> {
|
|
58
|
+
const present = new Set(sessions.map((session) => key(session.agent, session.sessionId)));
|
|
59
|
+
const finished = new Map<string, SessionInfo[]>();
|
|
60
|
+
for (const session of sessions) {
|
|
61
|
+
const parent = session.startedBy && key(session.startedBy.agent, session.startedBy.sessionId);
|
|
62
|
+
if (!parent || session.state !== "idle" || !present.has(parent)) continue;
|
|
63
|
+
finished.set(parent, [...(finished.get(parent) ?? []), session]);
|
|
64
|
+
}
|
|
65
|
+
return finished;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function withSummaries(sessions: readonly SessionInfo[], finished: ReadonlyMap<string, SessionInfo[]>): SessionInfo[] {
|
|
69
|
+
const counted = countedRuns();
|
|
70
|
+
return sessions.map((session) => {
|
|
71
|
+
if (!lineageAgent(session.agent)) return session;
|
|
72
|
+
const listed = (finished.get(key(session.agent, session.sessionId)) ?? []).flatMap((child) => countedRun(child) ?? []);
|
|
73
|
+
const counts = summary(counted.of({ agent: session.agent, sessionId: session.sessionId }), listed);
|
|
74
|
+
return counts ? { ...session, startedChildren: counts } : session;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function compactStartedChildren(sessions: readonly SessionInfo[], keep = FINISHED_CHILD_ROWS): SessionInfo[] {
|
|
79
|
+
const finished = finishedChildren(sessions);
|
|
80
|
+
const dropped = new Set<string>();
|
|
81
|
+
for (const children of finished.values()) {
|
|
82
|
+
const newest = [...children].sort((a, b) => b.lastActivityAt - a.lastActivityAt);
|
|
83
|
+
for (const child of newest.slice(keep)) dropped.add(key(child.agent, child.sessionId));
|
|
84
|
+
}
|
|
85
|
+
return withSummaries(sessions.filter((session) => !dropped.has(key(session.agent, session.sessionId))), finished);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The same counts on every listed parent, with no row left out: a page of history lists every chat. */
|
|
89
|
+
export function countStartedChildren(sessions: readonly SessionInfo[]): SessionInfo[] {
|
|
90
|
+
return withSummaries(sessions, finishedChildren(sessions));
|
|
91
|
+
}
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What each run another chat started came to, kept after the run leaves the catalog's window.
|
|
3
|
+
*
|
|
4
|
+
* The catalog reads the newest 200 transcripts of each provider. A chat whose script starts nine
|
|
5
|
+
* hundred `codex exec` runs in a day has most of them outside that window within hours, so counting
|
|
6
|
+
* only what the window holds said "200 of 200 stopped" about a script whose earlier runs had made
|
|
7
|
+
* hundreds of pictures. Each finished run is written down here once, by the chat that started it:
|
|
8
|
+
* how it ended (answered, stopped by a usage or rate limit, stopped on another error), whether it
|
|
9
|
+
* saved a picture, and when. Only ids, an outcome letter and a time are kept (`started-runs.json`).
|
|
10
|
+
*/
|
|
11
|
+
import { readFileSync, statSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import type { SessionInfo } from "../../../../../packages/protocol/schema";
|
|
14
|
+
import { writePrivateFile } from "../../config/access/write-private";
|
|
15
|
+
import { configDir } from "../../config/runtime/paths";
|
|
16
|
+
import { HISTORY_RETENTION_MS } from "../../sessions/support/common";
|
|
17
|
+
import { lineageAgent, SESSION_ID, startedByKey, type StartedBy } from "../../started-by";
|
|
18
|
+
|
|
19
|
+
export type RunEnd = "answered" | "limit" | "error";
|
|
20
|
+
|
|
21
|
+
/** One finished run: its session id, how it ended, whether it saved a picture, and when it last moved. */
|
|
22
|
+
export type CountedRun = { sessionId: string; end: RunEnd; picture: boolean; at: number };
|
|
23
|
+
|
|
24
|
+
/** At most this many runs are kept across every chat, the oldest let go first. */
|
|
25
|
+
export const MAX_COUNTED_RUNS = 20_000;
|
|
26
|
+
|
|
27
|
+
const CODES: Record<RunEnd, string> = { answered: "a", limit: "l", error: "e" };
|
|
28
|
+
const ENDS: Record<string, RunEnd> = { a: "answered", l: "limit", e: "error" };
|
|
29
|
+
|
|
30
|
+
type Ledger = { parents: Map<string, { parent: StartedBy; runs: Map<string, CountedRun> }>; owner: Map<string, string> };
|
|
31
|
+
|
|
32
|
+
export function startedRunsPath(): string {
|
|
33
|
+
return join(configDir(), "started-runs.json");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** How a finished session ended, or nothing while it still works. */
|
|
37
|
+
export function countedRun(session: SessionInfo, picture = false): CountedRun | undefined {
|
|
38
|
+
if (session.state !== "idle" || !SESSION_ID.test(session.sessionId)) return undefined;
|
|
39
|
+
const reason = session.stopped?.reason;
|
|
40
|
+
// As the phone reads a run: a usage or rate limit, or a limit the provider still reports, is a limit.
|
|
41
|
+
const limited = reason === "usage_limit" || reason === "rate_limit" || (!reason && Boolean(session.usageLimit));
|
|
42
|
+
const end: RunEnd = limited ? "limit" : reason ? "error" : "answered";
|
|
43
|
+
return { sessionId: session.sessionId, end, picture: picture || Boolean(session.images?.length), at: session.lastActivityAt };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let cached: { path: string; stamp: string; ledger: Ledger } | undefined;
|
|
47
|
+
|
|
48
|
+
function stampOf(path: string): string | undefined {
|
|
49
|
+
try {
|
|
50
|
+
const stat = statSync(path);
|
|
51
|
+
return `${stat.mtimeMs}:${stat.size}`;
|
|
52
|
+
} catch {
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function emptyLedger(): Ledger {
|
|
58
|
+
return { parents: new Map(), owner: new Map() };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function add(ledger: Ledger, parent: StartedBy, run: CountedRun): void {
|
|
62
|
+
const key = startedByKey(parent);
|
|
63
|
+
const entry = ledger.parents.get(key) ?? { parent, runs: new Map<string, CountedRun>() };
|
|
64
|
+
const previous = ledger.owner.get(run.sessionId);
|
|
65
|
+
if (previous && previous !== key) ledger.parents.get(previous)?.runs.delete(run.sessionId);
|
|
66
|
+
entry.runs.set(run.sessionId, run);
|
|
67
|
+
ledger.parents.set(key, entry);
|
|
68
|
+
ledger.owner.set(run.sessionId, key);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function parse(text: string): Ledger {
|
|
72
|
+
const ledger = emptyLedger();
|
|
73
|
+
const stored = JSON.parse(text) as { parents?: unknown };
|
|
74
|
+
for (const value of Array.isArray(stored.parents) ? stored.parents : []) {
|
|
75
|
+
const item = value as { agent?: unknown; sessionId?: unknown; runs?: unknown } | null;
|
|
76
|
+
if (!item || !lineageAgent(item.agent) || typeof item.sessionId !== "string" || !SESSION_ID.test(item.sessionId)) continue;
|
|
77
|
+
const parent: StartedBy = { agent: item.agent, sessionId: item.sessionId };
|
|
78
|
+
for (const row of Array.isArray(item.runs) ? item.runs : []) {
|
|
79
|
+
const [sessionId, code, at] = Array.isArray(row) ? row : [];
|
|
80
|
+
const end = typeof code === "string" ? ENDS[code[0] ?? ""] : undefined;
|
|
81
|
+
if (typeof sessionId !== "string" || !SESSION_ID.test(sessionId) || !end || typeof at !== "number" || !Number.isFinite(at)) continue;
|
|
82
|
+
if (sessionId === parent.sessionId) continue;
|
|
83
|
+
add(ledger, parent, { sessionId, end, picture: (code as string).endsWith("p"), at });
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return ledger;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** What is known, read again only when the file changed. */
|
|
90
|
+
function ledgerState(): Ledger {
|
|
91
|
+
const path = startedRunsPath();
|
|
92
|
+
const stamp = stampOf(path);
|
|
93
|
+
if (!stamp) return emptyLedger();
|
|
94
|
+
if (cached?.path === path && cached.stamp === stamp) return cached.ledger;
|
|
95
|
+
let ledger = emptyLedger();
|
|
96
|
+
try { ledger = parse(readFileSync(path, "utf8")); } catch { /* Unreadable: counted again from the transcripts. */ }
|
|
97
|
+
cached = { path, stamp, ledger };
|
|
98
|
+
return ledger;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function write(ledger: Ledger, now: number): void {
|
|
102
|
+
const runs = [...ledger.parents.values()].flatMap(({ parent, runs }) => [...runs.values()].map((run) => ({ parent, run })))
|
|
103
|
+
.filter(({ run }) => run.at >= now - HISTORY_RETENTION_MS)
|
|
104
|
+
.sort((left, right) => left.run.at - right.run.at).slice(-MAX_COUNTED_RUNS);
|
|
105
|
+
const kept = emptyLedger();
|
|
106
|
+
for (const { parent, run } of runs) add(kept, parent, run);
|
|
107
|
+
const parents = [...kept.parents.values()].map(({ parent, runs }) => ({ ...parent,
|
|
108
|
+
runs: [...runs.values()].map((run) => [run.sessionId, `${CODES[run.end]}${run.picture ? "p" : ""}`, run.at]) }));
|
|
109
|
+
const path = startedRunsPath();
|
|
110
|
+
writePrivateFile(path, JSON.stringify({ version: 1, parents }));
|
|
111
|
+
const stamp = stampOf(path);
|
|
112
|
+
cached = stamp ? { path, stamp, ledger: kept } : undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const same = (left: CountedRun | undefined, right: CountedRun) => left?.end === right.end
|
|
116
|
+
&& left.picture === right.picture && left.at === right.at;
|
|
117
|
+
|
|
118
|
+
/** Write down finished runs and the chat that started each. Returns how many were new or changed. */
|
|
119
|
+
export function countStartedRuns(found: ReadonlyArray<{ parent: StartedBy; run: CountedRun }>, now = Date.now()): number {
|
|
120
|
+
const current = ledgerState();
|
|
121
|
+
const changed = found.filter(({ parent, run }) => run.sessionId !== parent.sessionId
|
|
122
|
+
&& (current.owner.get(run.sessionId) !== startedByKey(parent)
|
|
123
|
+
|| !same(current.parents.get(startedByKey(parent))?.runs.get(run.sessionId), run)));
|
|
124
|
+
if (changed.length === 0) return 0;
|
|
125
|
+
const next = emptyLedger();
|
|
126
|
+
for (const { parent, runs } of current.parents.values()) for (const run of runs.values()) add(next, parent, run);
|
|
127
|
+
for (const { parent, run } of changed) add(next, parent, run);
|
|
128
|
+
write(next, now);
|
|
129
|
+
return changed.length;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The runs written down now, one reading for a whole list: each chat's, and whether a run is among them. */
|
|
133
|
+
export function countedRuns(): { of: (parent: StartedBy) => ReadonlyMap<string, CountedRun>; has: (sessionId: string) => boolean } {
|
|
134
|
+
let ledger: Ledger;
|
|
135
|
+
try { ledger = ledgerState(); } catch { ledger = emptyLedger(); }
|
|
136
|
+
return { of: (parent) => ledger.parents.get(startedByKey(parent))?.runs ?? new Map(),
|
|
137
|
+
has: (sessionId) => ledger.owner.has(sessionId) };
|
|
138
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tell the phone every chat a listed chat started (`sessions.children`).
|
|
3
|
+
*
|
|
4
|
+
* A phone keeps what it was once sent: a catalog row from before runs named their parent, a Mesh Task
|
|
5
|
+
* an older runtime made for each run. Counting runs on the parent does not tell the phone which of the
|
|
6
|
+
* chats it keeps are such runs, so each parent in the catalog that has started any has the ids of all
|
|
7
|
+
* of them sent once, again when they change (at most once a minute while a script still starts runs),
|
|
8
|
+
* and again every quarter of an hour for a phone that was away. A parent with nothing new costs
|
|
9
|
+
* nothing between those. Ids only; at most 4,000 a parent, newest first.
|
|
10
|
+
*/
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import type { RelayClient } from "../../../../../packages/core/relay-client";
|
|
13
|
+
import type { SessionInfo, SessionsChildren, SessionsStatus } from "../../../../../packages/protocol/schema";
|
|
14
|
+
import { lineageAgent, SESSION_ID, startedByKey, startedChildLinks, type StartedBy } from "../../started-by";
|
|
15
|
+
import { countedRuns } from "./ledger";
|
|
16
|
+
|
|
17
|
+
export const MAX_PUBLISHED_CHILDREN = 4_000;
|
|
18
|
+
/** Parents told about in one catalog tick; the rest wait for the next. */
|
|
19
|
+
const PARENTS_PER_TICK = 8;
|
|
20
|
+
const CHANGED_EVERY_MS = 60_000;
|
|
21
|
+
const UNCHANGED_EVERY_MS = 15 * 60_000;
|
|
22
|
+
|
|
23
|
+
/** Every chat this one is known to have started, newest first, and how many there are. */
|
|
24
|
+
export function startedChildIds(parent: StartedBy, max = MAX_PUBLISHED_CHILDREN): { ids: string[]; total: number } {
|
|
25
|
+
const latest = new Map<string, number>();
|
|
26
|
+
for (const run of countedRuns().of(parent).values()) latest.set(run.sessionId, run.at);
|
|
27
|
+
for (const link of startedChildLinks(parent)) {
|
|
28
|
+
latest.set(link.sessionId, Math.max(latest.get(link.sessionId) ?? 0, link.at));
|
|
29
|
+
}
|
|
30
|
+
const ids = [...latest.entries()].filter(([id]) => id !== parent.sessionId && SESSION_ID.test(id))
|
|
31
|
+
.sort((left, right) => right[1] - left[1] || left[0].localeCompare(right[0])).map(([id]) => id);
|
|
32
|
+
return { ids: ids.slice(0, max), total: ids.length };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const told = new WeakMap<RelayClient, Map<string, { digest: string; at: number }>>();
|
|
36
|
+
|
|
37
|
+
function parentsOf(status: SessionsStatus): StartedBy[] {
|
|
38
|
+
const rows: SessionInfo[] = [...status.sessions, ...(status.history ?? [])].filter((row) => row.startedChildren);
|
|
39
|
+
const seen = new Set<string>();
|
|
40
|
+
return rows.sort((left, right) => right.lastActivityAt - left.lastActivityAt).flatMap((row) => {
|
|
41
|
+
if (!lineageAgent(row.agent)) return [];
|
|
42
|
+
const parent: StartedBy = { agent: row.agent, sessionId: row.sessionId };
|
|
43
|
+
if (seen.has(startedByKey(parent))) return [];
|
|
44
|
+
seen.add(startedByKey(parent));
|
|
45
|
+
return [parent];
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Send what changed for the parents in this catalog. Returns how many parents were told. */
|
|
50
|
+
export async function publishStartedChildren(client: RelayClient, status: SessionsStatus, now = Date.now(),
|
|
51
|
+
ttlMs = 12 * 60_000): Promise<number> {
|
|
52
|
+
const sent = told.get(client) ?? new Map<string, { digest: string; at: number }>();
|
|
53
|
+
told.set(client, sent);
|
|
54
|
+
let count = 0;
|
|
55
|
+
for (const parent of parentsOf(status)) {
|
|
56
|
+
if (count >= PARENTS_PER_TICK) break;
|
|
57
|
+
const { ids, total } = startedChildIds(parent);
|
|
58
|
+
if (ids.length === 0) continue;
|
|
59
|
+
const digest = createHash("sha256").update(ids.join("\n")).digest("hex").slice(0, 24);
|
|
60
|
+
const before = sent.get(startedByKey(parent));
|
|
61
|
+
const wait = before?.digest === digest ? UNCHANGED_EVERY_MS : CHANGED_EVERY_MS;
|
|
62
|
+
if (before && now - before.at < wait && now >= before.at) continue;
|
|
63
|
+
const message: SessionsChildren = { type: "sessions.children", parent, children: ids, total, generatedAt: now };
|
|
64
|
+
await client.send(message, "phone", { ttlMs, reliable: false });
|
|
65
|
+
sent.set(startedByKey(parent), { digest, at: now });
|
|
66
|
+
count += 1;
|
|
67
|
+
}
|
|
68
|
+
return count;
|
|
69
|
+
}
|
|
@@ -5,7 +5,7 @@ import { providerScans, cooperativeProviderScans, type ProviderScan } from "./pr
|
|
|
5
5
|
import { attachHelperRuns } from "../helper-runs";
|
|
6
6
|
import { attachChatPictures, noteChatPictureHints } from "../helper-runs/pictures/chats";
|
|
7
7
|
import { attachStartedBy } from "../started-by";
|
|
8
|
-
import { compactStartedChildren } from "../session-catalog/started-children";
|
|
8
|
+
import { compactStartedChildren, countStartedChildren, noteCatalogParents, recordStartedChildren } from "../session-catalog/started-children";
|
|
9
9
|
|
|
10
10
|
function sessionKey(session: SessionInfo): string {
|
|
11
11
|
return `${session.agent}\0${session.sessionId}`;
|
|
@@ -54,8 +54,12 @@ function pickWithReserve(
|
|
|
54
54
|
function catalogFromScans(scans: ProviderScan[]) {
|
|
55
55
|
// A helper run is a conversation of the chat that started it, never a chat in these lists.
|
|
56
56
|
// A chat another chat ran headless stays a chat, and names the chat that started it.
|
|
57
|
+
const lineage = scans.flatMap((scan) => scan.lineage ?? []);
|
|
57
58
|
const native = attachChatPictures(attachStartedBy(attachHelperRuns(sortedUniqueSessions(scans.flatMap((scan) => scan.sessions)),
|
|
58
|
-
scans.flatMap((scan) => scan.helperRuns ?? [])),
|
|
59
|
+
scans.flatMap((scan) => scan.helperRuns ?? [])), lineage));
|
|
60
|
+
// Each finished run is counted on its parent for good; runs past the window are read by a slower pass.
|
|
61
|
+
recordStartedChildren(native);
|
|
62
|
+
noteCatalogParents(lineage);
|
|
59
63
|
// Pictures a chat's own answer saved are kept by the monitor (`keepNotedChatPictures`).
|
|
60
64
|
noteChatPictureHints(scans.flatMap((scan) => scan.pictures ?? []));
|
|
61
65
|
// Prepared transfers replace native ids; rank their native activity before
|
|
@@ -125,7 +129,7 @@ function historyCatalog(sessions: SessionInfo[]): SessionInfo[] {
|
|
|
125
129
|
export function scanSessionHistoryForPaging(maxFiles = MAX_FILES): { sessions: SessionInfo[]; sourceLimited: boolean } {
|
|
126
130
|
const scan = scanCatalog(maxFiles);
|
|
127
131
|
return {
|
|
128
|
-
sessions: scan.all.sort((left, right) =>
|
|
132
|
+
sessions: countStartedChildren(scan.all).sort((left, right) =>
|
|
129
133
|
right.lastActivityAt - left.lastActivityAt
|
|
130
134
|
|| left.agent.localeCompare(right.agent)
|
|
131
135
|
|| left.sessionId.localeCompare(right.sessionId)
|
|
@@ -18,22 +18,32 @@ function emptyScan(): ProviderScan {
|
|
|
18
18
|
* Explicit provider roots isolate fixtures and diagnostics from real user logs.
|
|
19
19
|
* In normal operation (no overrides) every installed provider is scanned.
|
|
20
20
|
*/
|
|
21
|
-
function
|
|
22
|
-
|
|
23
|
-
const explicit = {
|
|
21
|
+
function explicitRoots() {
|
|
22
|
+
return {
|
|
24
23
|
claude: Boolean(process.env.GRANTTAP_CLAUDE_PROJECTS_DIR || process.env.NODVOX_CLAUDE_PROJECTS_DIR),
|
|
25
24
|
codex: Boolean(process.env.GRANTTAP_CODEX_SESSIONS_DIR || process.env.NODVOX_CODEX_SESSIONS_DIR),
|
|
26
25
|
cursor: Boolean(process.env.GRANTTAP_CURSOR_TRANSCRIPTS_DIR || process.env.GRANTTAP_CURSOR_STATE_DB),
|
|
27
26
|
grok: Boolean(process.env.GRANTTAP_GROK_SESSIONS_DIR || process.env.GROK_HOME),
|
|
28
27
|
};
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Whether the catalog reads this provider: it is on, and no other provider's root alone is set. */
|
|
31
|
+
export function providerScanEnabled(agent: keyof ReturnType<typeof explicitRoots>,
|
|
32
|
+
settings = loadRuntimeConfig().providerSettings, explicit = explicitRoots()): boolean {
|
|
29
33
|
const isolated = Object.values(explicit).some(Boolean);
|
|
34
|
+
return settings[agent] && (!isolated || explicit[agent]);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function providerReaders(maxFiles: number) {
|
|
38
|
+
const settings = loadRuntimeConfig().providerSettings;
|
|
39
|
+
const explicit = explicitRoots();
|
|
30
40
|
const cooperative = { claude: scanClaudeCooperatively, codex: scanCodexCooperatively,
|
|
31
41
|
cursor: async (limit: number) => scanCursor(limit), grok: async (limit: number) => scanGrok(limit) };
|
|
32
42
|
return Object.entries({ claude: scanClaude, codex: scanCodex, cursor: scanCursor, grok: scanGrok })
|
|
33
43
|
.map(([agent, read]) => {
|
|
34
|
-
const key = agent as keyof typeof
|
|
44
|
+
const key = agent as keyof typeof cooperative;
|
|
35
45
|
return { agent, read: () => read(maxFiles), cooperative: () => cooperative[key](maxFiles),
|
|
36
|
-
enabled:
|
|
46
|
+
enabled: providerScanEnabled(key, settings, explicit) };
|
|
37
47
|
});
|
|
38
48
|
}
|
|
39
49
|
|
|
@@ -111,7 +111,9 @@ child its request did not link is linked when all of these hold:
|
|
|
111
111
|
- the parent started before the child and is not the child.
|
|
112
112
|
|
|
113
113
|
Such a link is written like any other read from a transcript (`source:
|
|
114
|
-
"transcript"`).
|
|
114
|
+
"transcript"`). Runs past the catalog's window of 200 transcripts are linked by
|
|
115
|
+
the same rules, at most once a minute, by the [catalog's slower
|
|
116
|
+
pass](../session-catalog/started-children/README.md). A run in a checkout or in a folder two chats used, whose
|
|
115
117
|
request a script built from a file, or whose script names no provider and was
|
|
116
118
|
not written by the chat, is linked only while its process is alive.
|
|
117
119
|
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/** Chats started by another chat: captured from their process, matched from transcripts, published as `startedBy`. */
|
|
2
|
-
export { headlessRun, headlessTargets, lineageAgent, lineageText, promptLead, type LineageAgent, type PromptLead } from "./headless";
|
|
2
|
+
export { headlessRun, headlessTargets, lineageAgent, lineageText, promptLead, SESSION_ID, type LineageAgent, type PromptLead } from "./headless";
|
|
3
3
|
export { createClaudeLineageCalls, createCodexLineageCalls, type LineageCall, type LineageCalls, type LineageFact } from "./facts";
|
|
4
|
-
export { attachStartedBy, startedByParents, transcriptParent } from "./attach";
|
|
4
|
+
export { attachStartedBy, startedByParents, transcriptParent, TRANSCRIPT_MATCH_MS } from "./attach";
|
|
5
5
|
export { captureStartedRuns, startedRunProcesses } from "./capture";
|
|
6
6
|
export { folderParents } from "./folders";
|
|
7
7
|
export { watchHeadlessRuns, type HeadlessRunWatch } from "./live";
|
|
8
|
-
export { startedByLink, startedChildSessionIds, type StartedBy, type StartedByLink } from "./links";
|
|
8
|
+
export { startedByKey, startedByLink, startedChildLinks, startedChildSessionIds, type StartedBy, type StartedByLink } from "./links";
|
|
9
9
|
export { childrenLast, inheritsParentMesh, parentPlacement, startedChildrenProjects, type MeshPlacement } from "./mesh";
|
|
@@ -126,6 +126,13 @@ export function startedChildSessionIds(): ReadonlySet<string> {
|
|
|
126
126
|
return ids;
|
|
127
127
|
}
|
|
128
128
|
|
|
129
|
+
/** Every chat known to have been started by this one, newest link first. */
|
|
130
|
+
export function startedChildLinks(parent: StartedBy): StartedByLink[] {
|
|
131
|
+
const key = startedByKey(parent);
|
|
132
|
+
return [...startedByState().links.values()].filter((link) => startedByKey(link.parent) === key)
|
|
133
|
+
.sort((left, right) => right.at - left.at);
|
|
134
|
+
}
|
|
135
|
+
|
|
129
136
|
const sameRun = (left: StartedRun, right: StartedRun) => left.agent === right.agent && left.pid === right.pid
|
|
130
137
|
&& Math.abs(left.startedAt - right.startedAt) <= 2_000;
|
|
131
138
|
|
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.194
|
|
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.194\";\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.194";
|
|
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
|
@@ -14,6 +14,13 @@ superseded; only a queue of controls refuses with "relay outbound queue is full"
|
|
|
14
14
|
A burst of catalog and Mesh refreshes for hundreds of short runs once filled the
|
|
15
15
|
queue and refused 103 Graph answers in a day; a Graph answer now also travels in
|
|
16
16
|
the control lane.
|
|
17
|
+
Every answer a phone waits on travels there too (`PHONE_ANSWERS`): a requested
|
|
18
|
+
picture, a chat's changes and commit result, a computer's phones and cache
|
|
19
|
+
(`device.manage.result`), files and schedules. A Mesh Task's result goes from
|
|
20
|
+
computer to computer over its own transport and is not listed. On a Mac whose
|
|
21
|
+
snapshot lane was dropping frames, the phones list and the Changes sheet waited
|
|
22
|
+
until the phone gave up. `tests/phone-answers.test.ts` reads every `*.result`
|
|
23
|
+
type from the protocol, so a new phone answer cannot be left in the snapshot lane.
|
|
17
24
|
|
|
18
25
|
Disconnect rejects the current write as well as queued frames. Catalog and
|
|
19
26
|
history publishers can retry on the next connection even if the previous
|
|
@@ -114,7 +114,8 @@ export class OutboundFrameQueue {
|
|
|
114
114
|
* Answers a phone waits on go here, never among replaceable snapshots: a snapshot can be dropped for
|
|
115
115
|
* newer traffic, and an answer behind a backed-up upload arrives after the phone stopped waiting.
|
|
116
116
|
*/
|
|
117
|
-
const PHONE_ANSWERS = new Set<Payload["type"]>(["session.image.chunk", "session.changes.result", "session.commit.result"
|
|
117
|
+
const PHONE_ANSWERS = new Set<Payload["type"]>(["session.image.chunk", "session.changes.result", "session.commit.result",
|
|
118
|
+
"device.manage.result", "session.workspace.result", "task.schedules.result"]);
|
|
118
119
|
|
|
119
120
|
export const priorityControlPayload = (type: Payload["type"]) => type === "hello" || PHONE_ANSWERS.has(type)
|
|
120
121
|
|| type.startsWith("approval.") || type.startsWith("config.") || type.startsWith("pairing.") || type === "session.key.grant"
|
|
@@ -30,9 +30,18 @@ does not continue by itself (everything but Claude).
|
|
|
30
30
|
`session.commit` / `session.commit.result` messages live in `sessions/working-tree.ts`; the contract
|
|
31
31
|
is in `apps/bridge/src/working-tree/README.md`.
|
|
32
32
|
|
|
33
|
-
`startedChildren` (optional, strict: `{ finished, stopped, pictures, lastAt }`, non-negative
|
|
34
|
-
and a time in ms) counts
|
|
35
|
-
|
|
33
|
+
`startedChildren` (optional, strict: `{ finished, stopped, limited?, pictures, lastAt }`, non-negative
|
|
34
|
+
integers and a time in ms) counts every finished chat this chat started headless, however long ago, the
|
|
35
|
+
newest three included, which stay rows of their own with `startedBy`: all of them, those that stopped on
|
|
36
|
+
an error (a limit among them), those a usage or rate limit stopped (`limited`, added after MCP 0.8.193;
|
|
37
|
+
absent from older runtimes), and those that saved a picture. MCP 0.8.190–0.8.193 counted only the runs within
|
|
38
|
+
the catalog's window of 200 transcripts.
|
|
39
|
+
|
|
40
|
+
`sessions.children` (strict: `{ parent, children, total, generatedAt }`) lists, newest first and at most
|
|
41
|
+
4,000, the session ids of every chat this computer knows `parent` started, and `total` of them, so a
|
|
42
|
+
phone can hang beneath their parent, or leave out, rows and Mesh Tasks it keeps from before it knew.
|
|
43
|
+
A phone that does not know the message ignores it. See
|
|
44
|
+
`apps/bridge/src/session-catalog/started-children/README.md`.
|
|
36
45
|
|
|
37
46
|
`images` (optional, at most 12 of `{ id, name, markdown }`, the same shape as a helper run's
|
|
38
47
|
`childThreads[].images`) lists pictures the chat's own answer saved in its working folder, kept by the
|
|
@@ -161,15 +161,17 @@ export const SessionInfo = z.object({
|
|
|
161
161
|
* `session.image.query` on this chat or on the chat that started it (`startedBy`).
|
|
162
162
|
*/
|
|
163
163
|
images: z.array(KeptPicture).max(12).optional(),
|
|
164
|
-
/**
|
|
165
|
-
* Finished chats this one started headless that the catalog counts here instead of listing: all of
|
|
166
|
-
* them (`finished`), those that stopped on an error, those that saved a picture, and the newest one's
|
|
167
|
-
* time. The newest few stay rows of their own.
|
|
168
|
-
*/
|
|
169
164
|
/** The working folder's uncommitted state when it is a Git checkout (`./working-tree.ts`). */
|
|
170
165
|
workingTree: SessionWorkingTree.optional(),
|
|
166
|
+
/**
|
|
167
|
+
* Every finished chat this one started headless, however long ago, counted here instead of listed:
|
|
168
|
+
* all of them (`finished`), those that stopped on an error (`stopped`, a limit among them), those a
|
|
169
|
+
* usage or rate limit stopped (`limited`, added after MCP 0.8.193), those that saved a picture, and the newest
|
|
170
|
+
* one's time. The newest few stay rows of their own, and are counted here too.
|
|
171
|
+
*/
|
|
171
172
|
startedChildren: z.object({
|
|
172
173
|
finished: z.number().int().nonnegative(), stopped: z.number().int().nonnegative(),
|
|
174
|
+
limited: z.number().int().nonnegative().optional(),
|
|
173
175
|
pictures: z.number().int().nonnegative(), lastAt: z.number().nonnegative(),
|
|
174
176
|
}).strict().optional(),
|
|
175
177
|
});
|
|
@@ -260,6 +262,21 @@ export const SessionsHistoryPage = z.object({
|
|
|
260
262
|
}).strict();
|
|
261
263
|
export type SessionsHistoryPage = z.infer<typeof SessionsHistoryPage>;
|
|
262
264
|
|
|
265
|
+
/**
|
|
266
|
+
* Every chat this computer knows one chat started headless, newest first, so a phone can hang beneath
|
|
267
|
+
* it, or leave out, a chat it keeps from before it knew: an older catalog's row or a Mesh Task. Sent
|
|
268
|
+
* when the list changes, and again now and then for a phone that was away. `total` counts them all
|
|
269
|
+
* when there are more than the list holds.
|
|
270
|
+
*/
|
|
271
|
+
export const SessionsChildren = z.object({
|
|
272
|
+
type: z.literal("sessions.children"),
|
|
273
|
+
parent: SessionStartedBy,
|
|
274
|
+
children: z.array(z.string().regex(/^[A-Za-z0-9._-]{8,128}$/)).max(4_000),
|
|
275
|
+
total: z.number().int().nonnegative(),
|
|
276
|
+
generatedAt: z.number(),
|
|
277
|
+
}).strict();
|
|
278
|
+
export type SessionsChildren = z.infer<typeof SessionsChildren>;
|
|
279
|
+
|
|
263
280
|
export { ConfigSet, ConfigCommandResult, CortexIntegrationSet } from "./configuration";
|
|
264
281
|
|
|
265
282
|
export const SessionAccessSet = z.object({
|
|
@@ -87,6 +87,7 @@ import {
|
|
|
87
87
|
SessionsStatus,
|
|
88
88
|
SessionsHistoryQuery,
|
|
89
89
|
SessionsHistoryPage,
|
|
90
|
+
SessionsChildren,
|
|
90
91
|
} from "./messages/sessions";
|
|
91
92
|
|
|
92
93
|
export * from "./messages/provider-hooks";
|
|
@@ -174,6 +175,7 @@ export const Payload = z.union([
|
|
|
174
175
|
SessionsStatus,
|
|
175
176
|
SessionsHistoryQuery,
|
|
176
177
|
SessionsHistoryPage,
|
|
178
|
+
SessionsChildren,
|
|
177
179
|
ConfigSet,
|
|
178
180
|
ConfigCommandResult,
|
|
179
181
|
SessionAccessSet,
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Hundreds of short headless runs one chat started (`codex exec` per picture) are not hundreds of
|
|
3
|
-
* catalog rows. A finished run another chat started is kept as a row only among the newest few of
|
|
4
|
-
* that parent's; the rest are counted on the parent as `startedChildren`. A running child, a child
|
|
5
|
-
* whose parent is not in the list, and every other chat stay rows. The full catalog still finds a
|
|
6
|
-
* child that is no row (a phone opening it, a message for it).
|
|
7
|
-
*/
|
|
8
|
-
import type { SessionInfo } from "../../../../packages/protocol/schema";
|
|
9
|
-
|
|
10
|
-
/** Finished children of one parent kept as rows, newest first. */
|
|
11
|
-
export const FINISHED_CHILD_ROWS = 3;
|
|
12
|
-
|
|
13
|
-
const key = (agent: string, sessionId: string) => `${agent}\0${sessionId}`;
|
|
14
|
-
|
|
15
|
-
export function compactStartedChildren(sessions: readonly SessionInfo[], keep = FINISHED_CHILD_ROWS): SessionInfo[] {
|
|
16
|
-
const present = new Set(sessions.map((session) => key(session.agent, session.sessionId)));
|
|
17
|
-
const finished = new Map<string, SessionInfo[]>();
|
|
18
|
-
for (const session of sessions) {
|
|
19
|
-
const parent = session.startedBy && key(session.startedBy.agent, session.startedBy.sessionId);
|
|
20
|
-
if (!parent || session.state !== "idle" || !present.has(parent)) continue;
|
|
21
|
-
finished.set(parent, [...(finished.get(parent) ?? []), session]);
|
|
22
|
-
}
|
|
23
|
-
if (finished.size === 0) return [...sessions];
|
|
24
|
-
const dropped = new Set<string>();
|
|
25
|
-
const summaries = new Map<string, NonNullable<SessionInfo["startedChildren"]>>();
|
|
26
|
-
for (const [parent, children] of finished) {
|
|
27
|
-
const newest = [...children].sort((a, b) => b.lastActivityAt - a.lastActivityAt);
|
|
28
|
-
for (const child of newest.slice(keep)) dropped.add(key(child.agent, child.sessionId));
|
|
29
|
-
summaries.set(parent, { finished: children.length, stopped: children.filter((child) => child.stopped).length,
|
|
30
|
-
pictures: children.filter((child) => child.images?.length).length, lastAt: newest[0]!.lastActivityAt });
|
|
31
|
-
}
|
|
32
|
-
return sessions.filter((session) => !dropped.has(key(session.agent, session.sessionId))).map((session) => {
|
|
33
|
-
const summary = summaries.get(key(session.agent, session.sessionId));
|
|
34
|
-
return summary ? { ...session, startedChildren: summary } : session;
|
|
35
|
-
});
|
|
36
|
-
}
|