granttap-mcp 0.8.172 → 0.8.174

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.
Files changed (32) hide show
  1. package/README.md +7 -0
  2. package/apps/bridge/src/bin/runtime/monitor.ts +9 -3
  3. package/apps/bridge/src/helper-runs/README.md +38 -0
  4. package/apps/bridge/src/helper-runs/attach.ts +91 -0
  5. package/apps/bridge/src/helper-runs/capture.ts +178 -0
  6. package/apps/bridge/src/helper-runs/index.ts +5 -0
  7. package/apps/bridge/src/helper-runs/kinds.ts +101 -0
  8. package/apps/bridge/src/helper-runs/links.ts +99 -0
  9. package/apps/bridge/src/machine-load/host/process-sampler.ts +3 -0
  10. package/apps/bridge/src/mesh/catalog/index.ts +3 -1
  11. package/apps/bridge/src/mesh/store/index.ts +3 -1
  12. package/apps/bridge/src/monitor/message-delivery/README.md +3 -0
  13. package/apps/bridge/src/monitor/message-delivery/acceptance.ts +11 -1
  14. package/apps/bridge/src/monitor/support/runtime.ts +6 -1
  15. package/apps/bridge/src/reply/in-flight.ts +13 -1
  16. package/apps/bridge/src/reply/index.ts +1 -1
  17. package/apps/bridge/src/runtime-updates/README.md +39 -4
  18. package/apps/bridge/src/runtime-updates/drain/index.ts +140 -0
  19. package/apps/bridge/src/runtime-updates/index.ts +35 -20
  20. package/apps/bridge/src/runtime-updates/readiness.ts +11 -5
  21. package/apps/bridge/src/sessions/catalog.ts +4 -1
  22. package/apps/bridge/src/sessions/scan/grok.ts +11 -3
  23. package/apps/bridge/src/sessions/session-activity.ts +5 -1
  24. package/apps/bridge/src/sessions/support/common.ts +2 -0
  25. package/apps/bridge/src/task-dispatch/README.md +7 -0
  26. package/apps/bridge/src/task-dispatch/worker/monitor.ts +8 -3
  27. package/cursor-plugin/README.md +1 -1
  28. package/cursor-plugin/mcp.json +1 -1
  29. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  30. package/docs/device-management.md +3 -1
  31. package/package.json +1 -1
  32. package/packages/protocol/messages/sessions/index.ts +5 -0
package/README.md CHANGED
@@ -940,6 +940,13 @@ Verified updates are staged separately and applied after active requests and pen
940
940
  decisions finish. Startup failures restore the previous version. Pairing and task
941
941
  policies are retained; source checkouts and running provider processes stay in place.
942
942
 
943
+ A computer that always has a chat running is never idle on its own. When an update is
944
+ ready, the background monitor therefore stops starting newly arrived phone messages for
945
+ up to ten minutes, lets the runs already going finish, and then switches. Messages that
946
+ arrive meanwhile are kept and delivered by the new version; none is refused or run
947
+ twice. If a run outlasts the ten minutes, messages run again and the update follows
948
+ when that run has ended.
949
+
943
950
  In the plugin's GrantTap connection card, use **Automatic updates: On / Off**.
944
951
  The choice is saved for this computer and takes effect without restarting the
945
952
  service. Off prevents further update checks and activation; an already running
@@ -1,5 +1,7 @@
1
1
  import { startRuntimeUpdates } from "../../runtime-updates";
2
2
  import { runtimeUpdateReadiness } from "../../runtime-updates/readiness";
3
+ import { UpdateDrain } from "../../runtime-updates/drain";
4
+ import { oldestDeliveryStartedAt } from "../../reply";
3
5
  /** Persistent, terminal-free task sync for the GrantTap phone app on macOS. */
4
6
  import { join } from "node:path";
5
7
  import { RelayClient } from "../../../../../packages/core/relay-client";
@@ -33,6 +35,9 @@ let stopEngineRecovery = () => {};
33
35
  let stopRuntimeUpdates = () => {};
34
36
  let stopUpdateReadiness = () => {};
35
37
  const stopWatchdog = startRuntimeWatchdog();
38
+ // Messages keep arriving, so a newer runtime cannot wait for an idle moment: queued work is held for it instead.
39
+ const updateDrain = new UpdateDrain({ oldestRun: oldestDeliveryStartedAt,
40
+ log: line => process.stderr.write(`[monitor] ${line}\n`) });
36
41
 
37
42
  publishStableNode();
38
43
 
@@ -46,12 +51,13 @@ try {
46
51
  });
47
52
  monitor = startSessionMonitor(client, { primary: process.env.GRANTTAP_MONITOR_PRIMARY === "1", config: cfg });
48
53
  stopTaskDispatch = startTaskDispatchMonitor({ config: cfg, client,
49
- isLeader: monitor.isLeader, peerAllowed: controllerPeerGate(cfg), publish: monitor.publish });
54
+ isLeader: monitor.isLeader, peerAllowed: controllerPeerGate(cfg), publish: monitor.publish,
55
+ held: () => updateDrain.holding(), track: monitor.track });
50
56
  stopTaskNetwork = startTaskNetworkMonitor({ config: cfg, client,
51
57
  isLeader: monitor.isLeader, peerAllowed: controllerPeerGate(cfg), publish: monitor.publish });
52
58
  stopEndpointPublisher = startEndpointPublisher(cfg);
53
- stopRuntimeUpdates = startRuntimeUpdates(monitor.canUpdate);
54
- stopUpdateReadiness = runtimeUpdateReadiness(monitor.canUpdate);
59
+ stopRuntimeUpdates = startRuntimeUpdates(monitor.canUpdate, updateDrain);
60
+ stopUpdateReadiness = runtimeUpdateReadiness(monitor.canUpdate, updateDrain);
55
61
  } catch (error) {
56
62
  process.stderr.write(
57
63
  `[granttap-mcp] monitor is not paired: ${error instanceof Error ? error.message : String(error)}\n`,
@@ -0,0 +1,38 @@
1
+ # Helper runs
2
+
3
+ A chat that asks for a picture runs a script, and the script starts its own
4
+ headless provider session in a throwaway folder inside the system temp
5
+ directory. That session is the chat's work. It is shown as one of the chat's
6
+ nested conversations, labelled for what it is, and never as a chat or a Mesh
7
+ of its own.
8
+
9
+ **Recognised** (`kinds.ts`). A run is a headless session whose working folder
10
+ sits directly inside a temp directory and carries a generator's prefix.
11
+ `GENERATORS` is the one place a generator is listed: its folder prefix, the
12
+ kind its runs are, and the label a phone that does not know the kind shows.
13
+ A session in a temp folder is not a run unless a generator claims the folder.
14
+
15
+ **Linked** (`capture.ts`, `links.ts`). Nothing recorded after the fact names
16
+ the chat that started a run. The run's live process does: Claude Code and
17
+ Codex give every command a chat runs that chat's id, and the run inherits it.
18
+ Each process sample (`machine-load`) passes its provider processes here. A
19
+ process is looked at once: its working folder is read, and only when that is a
20
+ generator's folder is its environment read, for the chat's id alone. Nothing
21
+ read from a process is logged or kept beyond that id. The link is written to
22
+ `helper-runs.json` in the config directory, keyed by the run's folder, and
23
+ outlives the process. The first capture of a run stands.
24
+
25
+ **Shown** (`attach.ts`). The session catalog adds each linked run to its
26
+ parent's `childThreads` with `kind` set, and leaves the parent's own state,
27
+ clock and spend alone. Opening the conversation reads the run's own messages.
28
+ A run whose parent was not captured, or whose parent is no longer on this
29
+ computer, is published nowhere; the provider's own history still has it.
30
+
31
+ **Meshes.** A generator's folder never registers a Mesh. Meshes registered for
32
+ such folders before runs were recognised stay in the Mesh store and are left
33
+ out of every list of this computer's Projects.
34
+
35
+ Tests live in `tests/`; the Mesh behaviour is covered in
36
+ `../mesh/runtime/tests/helper-run-meshes.test.ts`.
37
+
38
+ Licensed under the GrantTap Commercial Source License. See the repository root `LICENSE`.
@@ -0,0 +1,91 @@
1
+ /**
2
+ * Show a helper run where it belongs: under the chat that started it.
3
+ *
4
+ * A run is the chat's work, like one of its agents, so it is published as one
5
+ * of the chat's nested conversations and never as a chat of its own. A run
6
+ * whose parent was not captured, or whose parent is no longer on this
7
+ * computer, is published nowhere; the provider's own history still has it.
8
+ */
9
+ import type { ActivityEntry, ChildThreadInfo, SessionInfo } from "../../../../packages/protocol/schema";
10
+ import { boundChildThreads, childEntryFields, childTitle } from "../sessions/support/child-threads";
11
+ import { helperRunLink, type HelperRunLink } from "./links";
12
+
13
+ /** A provider session a scanner recognised as a helper run and kept out of its chats. */
14
+ export type HelperRunSession = {
15
+ session: SessionInfo;
16
+ kind: string;
17
+ /** What a phone that does not know the kind calls the run. */
18
+ label: string;
19
+ folder: string;
20
+ };
21
+
22
+ function sessionKey(agent: string, sessionId: string): string {
23
+ return `${agent}\0${sessionId}`;
24
+ }
25
+
26
+ /** The runs attached by the newest catalog, so a run's conversation can be read when a phone opens it. */
27
+ let attached = new Map<string, SessionInfo>();
28
+
29
+ function childOf(parent: SessionInfo, run: HelperRunSession): ChildThreadInfo {
30
+ const { session } = run;
31
+ return {
32
+ threadId: session.sessionId,
33
+ parentThreadId: parent.sessionId,
34
+ title: childTitle(session.title),
35
+ agentName: run.label,
36
+ kind: run.kind,
37
+ depth: 1,
38
+ state: session.state,
39
+ startedAt: session.startedAt,
40
+ lastActivityAt: session.lastActivityAt,
41
+ tokensSession: session.tokensSession,
42
+ tokensLastTurn: session.tokensLastTurn,
43
+ };
44
+ }
45
+
46
+ /**
47
+ * Add each run to its parent's nested conversations. The parent's own state,
48
+ * clock and spend stay its own: the run is another provider's work.
49
+ */
50
+ export function attachHelperRuns(
51
+ sessions: SessionInfo[],
52
+ runs: readonly HelperRunSession[],
53
+ link: (folder: string) => HelperRunLink | undefined = helperRunLink,
54
+ ): SessionInfo[] {
55
+ const parents = new Map(sessions.map((session) => [sessionKey(session.agent, session.sessionId), session]));
56
+ const children = new Map<string, ChildThreadInfo[]>();
57
+ const read = new Map<string, SessionInfo>();
58
+ for (const run of runs) {
59
+ const known = link(run.folder);
60
+ const key = known ? sessionKey(known.parentAgent, known.parentSessionId) : undefined;
61
+ const parent = key ? parents.get(key) : undefined;
62
+ if (!key || !parent) continue;
63
+ children.set(key, [...(children.get(key) ?? []), childOf(parent, run)]);
64
+ read.set(run.session.sessionId, run.session);
65
+ }
66
+ attached = read;
67
+ if (children.size === 0) return sessions;
68
+ return sessions.map((session) => {
69
+ const own = children.get(sessionKey(session.agent, session.sessionId));
70
+ return own ? { ...session, childThreads: boundChildThreads([...(session.childThreads ?? []), ...own]) } : session;
71
+ });
72
+ }
73
+
74
+ /** The helper run behind one of a chat's nested conversations, when that conversation is one. */
75
+ export function helperRunThread(
76
+ parent: SessionInfo,
77
+ threadId: string,
78
+ ): { child: ChildThreadInfo; session: SessionInfo } | undefined {
79
+ const child = parent.childThreads?.find((item) => item.threadId === threadId && item.kind);
80
+ if (!child) return undefined;
81
+ const session = attached.get(threadId) ?? {
82
+ sessionId: threadId, agent: "grok", state: child.state, startedAt: child.startedAt,
83
+ lastActivityAt: child.lastActivityAt, tokensSession: child.tokensSession, tokensLastTurn: child.tokensLastTurn,
84
+ };
85
+ return { child, session };
86
+ }
87
+
88
+ /** A run's own messages, marked as the nested conversation they are shown in. */
89
+ export function helperRunEntries(child: ChildThreadInfo, entries: readonly ActivityEntry[]): ActivityEntry[] {
90
+ return entries.map((entry) => ({ ...entry, ...childEntryFields(child) }));
91
+ }
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Learn which chat started a helper run while the run's process is alive.
3
+ *
4
+ * The provider's own record of the run names no parent, and the parent's
5
+ * transcript does not name the run. The live process does: a chat hands its id
6
+ * to everything its shell starts, and the run's process inherits it. Only a
7
+ * process already known to be a helper run has its environment read, only the
8
+ * chat's id is kept from it, and nothing read here is ever logged.
9
+ */
10
+ import { execFile } from "node:child_process";
11
+ import { existsSync, readlinkSync } from "node:fs";
12
+ import { promisify } from "node:util";
13
+ import type { ProcessRow } from "../machine-load/host/process-sampler";
14
+ import { helperRunFolder, helperRunFoldersNamed, type HelperRunFolder } from "./kinds";
15
+ import { rememberHelperRunLinks, type HelperRunLink, type HelperRunParentAgent } from "./links";
16
+
17
+ const run = promisify(execFile);
18
+
19
+ export type HelperRunParent = { agent: HelperRunParentAgent; sessionId: string };
20
+
21
+ /** One provider process the listing shows. Its command line is searched for a generator's folder and never kept. */
22
+ export type HelperRunProcess = { pid: number; command: string; ancestor?: HelperRunParent };
23
+
24
+ export type HelperRunReaders = {
25
+ directories: (pids: readonly number[]) => Promise<Map<number, string>>;
26
+ parents: (pids: readonly number[]) => Promise<Map<number, HelperRunParent>>;
27
+ };
28
+
29
+ /** The variable each provider gives the commands a chat runs, naming that chat. */
30
+ const PARENT_VARIABLES: ReadonlyArray<readonly [HelperRunParentAgent, RegExp]> = [
31
+ ["claude", /(?:^|\s)CLAUDE_CODE_SESSION_ID=([A-Za-z0-9._-]{8,128})(?=\s|$)/],
32
+ ["codex", /(?:^|\s)CODEX_THREAD_ID=([A-Za-z0-9._-]{8,128})(?=\s|$)/],
33
+ ];
34
+ const PARENT_AGENTS = new Set<string>(PARENT_VARIABLES.map(([agent]) => agent));
35
+ const MAX_FOLDER_READS = 3;
36
+ const LSOF = "/usr/sbin/lsof";
37
+
38
+ /** `lsof -Fn` prints `p<pid>`, then `n<path>` for the one descriptor asked for. */
39
+ export function parseProcessDirectories(stdout: string): Map<number, string> {
40
+ const out = new Map<number, string>();
41
+ let pid: number | undefined;
42
+ for (const line of stdout.split("\n")) {
43
+ if (/^p\d+$/.test(line)) pid = Number(line.slice(1));
44
+ else if (line.startsWith("n/") && pid != null && !out.has(pid)) out.set(pid, line.slice(1));
45
+ }
46
+ return out;
47
+ }
48
+
49
+ /** `ps -E -o pid=,uid=,command=`: the chat's id is taken and the rest of the line is dropped. */
50
+ export function parseProcessParents(stdout: string, uid?: number): Map<number, HelperRunParent> {
51
+ const out = new Map<number, HelperRunParent>();
52
+ for (const line of stdout.split("\n")) {
53
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);
54
+ if (!match || (uid != null && Number(match[2]) !== uid)) continue;
55
+ for (const [agent, variable] of PARENT_VARIABLES) {
56
+ const sessionId = variable.exec(match[3]!)?.[1];
57
+ if (sessionId) { out.set(Number(match[1]), { agent, sessionId }); break; }
58
+ }
59
+ }
60
+ return out;
61
+ }
62
+
63
+ export async function readProcessDirectories(pids: readonly number[]): Promise<Map<number, string>> {
64
+ if (pids.length === 0) return new Map();
65
+ if (process.platform === "linux") {
66
+ const out = new Map<number, string>();
67
+ for (const pid of pids) {
68
+ try { out.set(pid, readlinkSync(`/proc/${pid}/cwd`)); } catch { /* Exited, or not this person's. */ }
69
+ }
70
+ return out;
71
+ }
72
+ try {
73
+ const { stdout } = await run(existsSync(LSOF) ? LSOF : "lsof", ["-a", "-d", "cwd", "-Fn", "-p", pids.join(",")],
74
+ { encoding: "utf8", maxBuffer: 1_000_000, timeout: 5_000 });
75
+ return parseProcessDirectories(String(stdout));
76
+ } catch (error) {
77
+ // The tool exits non-zero when one of the processes is gone and still lists the rest.
78
+ return parseProcessDirectories(String((error as { stdout?: unknown }).stdout ?? ""));
79
+ }
80
+ }
81
+
82
+ export async function readProcessParents(pids: readonly number[]): Promise<Map<number, HelperRunParent>> {
83
+ if (pids.length === 0) return new Map();
84
+ try {
85
+ const { stdout } = await run("ps", ["-E", "-o", "pid=,uid=,command=", "-p", pids.join(",")],
86
+ { encoding: "utf8", maxBuffer: 8_000_000, timeout: 5_000 });
87
+ return parseProcessParents(String(stdout), process.getuid?.());
88
+ } catch {
89
+ // The error carries every environment it read; none of it leaves here.
90
+ throw new Error("process environment unavailable");
91
+ }
92
+ }
93
+
94
+ /** The provider processes in a listing, each with the chat of the provider process it was started under. */
95
+ export function helperRunProcesses(
96
+ rows: readonly ProcessRow[],
97
+ ownership: { agents: ReadonlyMap<number, string>; roots: ReadonlyMap<number, number> },
98
+ sessions: ReadonlyMap<number, string>,
99
+ ): HelperRunProcess[] {
100
+ return rows.filter((row) => ownership.roots.get(row.pid) === row.pid).map((row) => {
101
+ const above = row.ppid != null ? ownership.roots.get(row.ppid) : undefined;
102
+ const agent = above != null ? ownership.agents.get(above) : undefined;
103
+ const sessionId = above != null ? sessions.get(above) : undefined;
104
+ return {
105
+ pid: row.pid, command: row.command,
106
+ ...(agent && sessionId && PARENT_AGENTS.has(agent)
107
+ ? { ancestor: { agent: agent as HelperRunParentAgent, sessionId } } : {}),
108
+ };
109
+ });
110
+ }
111
+
112
+ type CaptureOptions = {
113
+ readers?: HelperRunReaders;
114
+ remember?: (links: HelperRunLink[]) => number;
115
+ now?: () => number;
116
+ };
117
+
118
+ /** One capture per monitor: it remembers which processes it has already looked at. */
119
+ export function createHelperRunCapture(options: CaptureOptions = {}) {
120
+ const readers = options.readers ?? { directories: readProcessDirectories, parents: readProcessParents };
121
+ const remember = options.remember ?? rememberHelperRunLinks;
122
+ const now = options.now ?? Date.now;
123
+ const settled = new Set<number>();
124
+ const folderReads = new Map<number, number>();
125
+
126
+ const folderOf = (item: HelperRunProcess, directory: string | undefined): HelperRunFolder | undefined => {
127
+ const working = helperRunFolder(directory);
128
+ if (working) return working;
129
+ const named = helperRunFoldersNamed(item.command);
130
+ return named.length === 1 ? named[0] : undefined;
131
+ };
132
+
133
+ const examine = async (processes: readonly HelperRunProcess[]): Promise<number> => {
134
+ const live = new Set(processes.map((item) => item.pid));
135
+ for (const pid of [...settled]) if (!live.has(pid)) settled.delete(pid);
136
+ for (const pid of [...folderReads.keys()]) if (!live.has(pid)) folderReads.delete(pid);
137
+ const fresh = processes.filter((item) => !settled.has(item.pid));
138
+ if (fresh.length === 0) return 0;
139
+ const directories = await readers.directories(fresh.map((item) => item.pid));
140
+ const runs: Array<{ item: HelperRunProcess; folder: HelperRunFolder }> = [];
141
+ for (const item of fresh) {
142
+ const directory = directories.get(item.pid);
143
+ const folder = folderOf(item, directory);
144
+ if (folder) { runs.push({ item, folder }); continue; }
145
+ const reads = (folderReads.get(item.pid) ?? 0) + 1;
146
+ folderReads.set(item.pid, reads);
147
+ if (directory !== undefined || reads >= MAX_FOLDER_READS) settled.add(item.pid);
148
+ }
149
+ if (runs.length === 0) return 0;
150
+ const parents = await readers.parents(runs.map(({ item }) => item.pid));
151
+ const links: HelperRunLink[] = [];
152
+ for (const { item, folder } of runs) {
153
+ settled.add(item.pid);
154
+ const parent = parents.get(item.pid) ?? item.ancestor;
155
+ if (parent) {
156
+ links.push({ folder: folder.folder, kind: folder.kind, parentAgent: parent.agent,
157
+ parentSessionId: parent.sessionId, capturedAt: now() });
158
+ }
159
+ }
160
+ return links.length > 0 ? remember(links) : 0;
161
+ };
162
+
163
+ return async (processes: readonly HelperRunProcess[]): Promise<number> => {
164
+ try { return await examine(processes); } catch { return 0; }
165
+ };
166
+ }
167
+
168
+ let capture = createHelperRunCapture();
169
+
170
+ /** For tests: forget which processes were looked at, and read through other tools. */
171
+ export function resetHelperRunCapture(options?: CaptureOptions): void {
172
+ capture = createHelperRunCapture(options);
173
+ }
174
+
175
+ /** Called with every process sample; a helper run lives long enough to be in at least one. */
176
+ export function captureHelperRuns(processes: readonly HelperRunProcess[]): Promise<number> {
177
+ return capture(processes);
178
+ }
@@ -0,0 +1,5 @@
1
+ /** Short helper runs a chat starts, such as image generation: recognised, linked to their chat, shown under it. */
2
+ export { helperRunFolder, helperRunLabel, helperRunProject, type HelperRunFolder, type HelperRunKind } from "./kinds";
3
+ export { helperRunLink, rememberHelperRunLinks, type HelperRunLink } from "./links";
4
+ export { attachHelperRuns, helperRunEntries, helperRunThread, type HelperRunSession } from "./attach";
5
+ export { captureHelperRuns, helperRunProcesses } from "./capture";
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Which working folders belong to a generator's short helper run.
3
+ *
4
+ * A chat that asks for a picture runs a script, and the script starts its own
5
+ * headless provider session in a throwaway folder inside the system temp
6
+ * directory. The folder's name carries the generator's prefix; nothing else
7
+ * about the run says what it is. A session in a temp folder is not a helper
8
+ * run by itself: only a generator listed here makes it one.
9
+ */
10
+ import { realpathSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+
13
+ export type HelperRunKind = "image-generation";
14
+
15
+ type Generator = {
16
+ /** How the generator names its throwaway folder. */
17
+ prefix: string;
18
+ kind: HelperRunKind;
19
+ /** What a phone that does not know the kind calls the run. */
20
+ label: string;
21
+ };
22
+
23
+ /** Every generator, in one place: add a row to recognise another one. */
24
+ const GENERATORS: readonly Generator[] = [
25
+ { prefix: "hw-image-", kind: "image-generation", label: "Image generation" },
26
+ ];
27
+
28
+ const RUN_SUFFIX = /^[A-Za-z0-9_-]{4,64}$/;
29
+ /** macOS gives each person a temp directory of this shape, with or without `/private`. */
30
+ const PER_USER_TEMP = /^\/var\/folders\/[^/]+\/[^/]+\/T$/;
31
+
32
+ export type HelperRunFolder = {
33
+ kind: HelperRunKind;
34
+ label: string;
35
+ /** The folder in one spelling, so a path read from a process and one read from a log compare equal. */
36
+ folder: string;
37
+ };
38
+
39
+ function plain(path: string): string {
40
+ const trimmed = path.trim().replace(/\\/g, "/").replace(/\/+$/, "");
41
+ return /^\/private\/(var|tmp)(\/|$)/.test(trimmed) ? trimmed.slice("/private".length) : trimmed;
42
+ }
43
+
44
+ let ownTemp: readonly string[] | undefined;
45
+
46
+ /** This computer's temp directory, as the environment names it and as the disk does. */
47
+ function systemTempRoots(): readonly string[] {
48
+ if (ownTemp) return ownTemp;
49
+ const named = tmpdir();
50
+ let resolved = named;
51
+ try { resolved = realpathSync(named); } catch { /* The named path stands. */ }
52
+ ownTemp = [named, resolved, "/tmp"];
53
+ return ownTemp;
54
+ }
55
+
56
+ function isTempRoot(directory: string, roots: readonly string[]): boolean {
57
+ return PER_USER_TEMP.test(directory) || roots.some((root) => plain(root) === directory);
58
+ }
59
+
60
+ /** The generator a working folder belongs to, when it is one's throwaway folder directly inside a temp directory. */
61
+ export function helperRunFolder(
62
+ path: string | undefined,
63
+ tempRoots: readonly string[] = systemTempRoots(),
64
+ ): HelperRunFolder | undefined {
65
+ if (!path) return undefined;
66
+ const folder = plain(path);
67
+ const cut = folder.lastIndexOf("/");
68
+ if (cut <= 0 || !isTempRoot(folder.slice(0, cut), tempRoots)) return undefined;
69
+ const name = folder.slice(cut + 1);
70
+ const generator = GENERATORS.find((item) =>
71
+ name.startsWith(item.prefix) && RUN_SUFFIX.test(name.slice(item.prefix.length)));
72
+ return generator ? { kind: generator.kind, label: generator.label, folder } : undefined;
73
+ }
74
+
75
+ /** Every different generator folder a text names, such as a process's command line. */
76
+ export function helperRunFoldersNamed(text: string, tempRoots?: readonly string[]): HelperRunFolder[] {
77
+ const found = new Map<string, HelperRunFolder>();
78
+ for (const generator of GENERATORS) {
79
+ const name = generator.prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
80
+ for (const match of text.matchAll(new RegExp(`/[A-Za-z0-9._/-]+/${name}[A-Za-z0-9_-]{4,64}`, "g"))) {
81
+ const folder = helperRunFolder(match[0], tempRoots);
82
+ if (folder) found.set(folder.folder, folder);
83
+ }
84
+ }
85
+ return [...found.values()];
86
+ }
87
+
88
+ export function helperRunLabel(kind: string): string {
89
+ return GENERATORS.find((item) => item.kind === kind)?.label ?? "Helper run";
90
+ }
91
+
92
+ /**
93
+ * A Mesh that was registered for a helper run's folder before helper runs were recognised.
94
+ * A repository with a remote is a real Project wherever it was cloned.
95
+ */
96
+ export function helperRunProject(project: { repositoryRoot?: string; canonicalRepositoryId: string }): boolean {
97
+ const identity = project.canonicalRepositoryId;
98
+ if (!identity.startsWith("local:")) return false;
99
+ return helperRunFolder(project.repositoryRoot) !== undefined
100
+ || helperRunFolder(identity.slice("local:".length)) !== undefined;
101
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Which chat started each helper run, kept after the run is over.
3
+ *
4
+ * Only the run's live process names its parent, and it lives for half a
5
+ * minute. The link is therefore written down the moment it is seen, keyed by
6
+ * the run's throwaway folder: the folder is what the process and the
7
+ * provider's own session record both carry, and each run has its own.
8
+ */
9
+ import { readFileSync, statSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { writePrivateFile } from "../config/access/write-private";
12
+ import { configDir } from "../config/runtime/paths";
13
+ import { HISTORY_RETENTION_MS } from "../sessions/support/common";
14
+ import { helperRunFolder } from "./kinds";
15
+
16
+ export type HelperRunParentAgent = "claude" | "codex";
17
+
18
+ export type HelperRunLink = {
19
+ folder: string;
20
+ kind: string;
21
+ parentAgent: HelperRunParentAgent;
22
+ parentSessionId: string;
23
+ capturedAt: number;
24
+ };
25
+
26
+ const MAX_LINKS = 2_000;
27
+ const SESSION_ID = /^[A-Za-z0-9._-]{8,128}$/;
28
+
29
+ export function helperRunLinksPath(): string {
30
+ return join(configDir(), "helper-runs.json");
31
+ }
32
+
33
+ function valid(value: unknown): HelperRunLink | undefined {
34
+ if (!value || typeof value !== "object") return undefined;
35
+ const item = value as Record<string, unknown>;
36
+ const folder = typeof item.folder === "string" ? helperRunFolder(item.folder)?.folder : undefined;
37
+ if (!folder || typeof item.kind !== "string" || !item.kind || item.kind.length > 40) return undefined;
38
+ if (item.parentAgent !== "claude" && item.parentAgent !== "codex") return undefined;
39
+ if (typeof item.parentSessionId !== "string" || !SESSION_ID.test(item.parentSessionId)) return undefined;
40
+ if (typeof item.capturedAt !== "number" || !Number.isFinite(item.capturedAt)) return undefined;
41
+ return { folder, kind: item.kind, parentAgent: item.parentAgent,
42
+ parentSessionId: item.parentSessionId, capturedAt: item.capturedAt };
43
+ }
44
+
45
+ let cached: { path: string; stamp: string; links: Map<string, HelperRunLink> } | undefined;
46
+
47
+ function stampOf(path: string): string | undefined {
48
+ try {
49
+ const stat = statSync(path);
50
+ return `${stat.mtimeMs}:${stat.size}`;
51
+ } catch {
52
+ return undefined;
53
+ }
54
+ }
55
+
56
+ function readLinks(): Map<string, HelperRunLink> {
57
+ const path = helperRunLinksPath();
58
+ const stamp = stampOf(path);
59
+ if (!stamp) return new Map();
60
+ if (cached?.path === path && cached.stamp === stamp) return cached.links;
61
+ const links = new Map<string, HelperRunLink>();
62
+ try {
63
+ const stored = JSON.parse(readFileSync(path, "utf8")) as { links?: unknown };
64
+ for (const value of Array.isArray(stored.links) ? stored.links : []) {
65
+ const link = valid(value);
66
+ if (link && !links.has(link.folder)) links.set(link.folder, link);
67
+ }
68
+ } catch {
69
+ // A file that cannot be read holds no links; the next capture rewrites it.
70
+ }
71
+ cached = { path, stamp, links };
72
+ return links;
73
+ }
74
+
75
+ /** The chat that started the run in this folder, when it was captured. */
76
+ export function helperRunLink(folder: string | undefined): HelperRunLink | undefined {
77
+ const key = helperRunFolder(folder)?.folder;
78
+ return key ? readLinks().get(key) : undefined;
79
+ }
80
+
81
+ /** Write newly captured parents down. The first capture of a run stands. Returns how many were new. */
82
+ export function rememberHelperRunLinks(captured: readonly HelperRunLink[], now = Date.now()): number {
83
+ const known = readLinks();
84
+ const fresh = new Map<string, HelperRunLink>();
85
+ for (const value of captured) {
86
+ const link = valid(value);
87
+ if (link && !known.has(link.folder) && !fresh.has(link.folder)) fresh.set(link.folder, link);
88
+ }
89
+ if (fresh.size === 0) return 0;
90
+ const kept = [...known.values(), ...fresh.values()]
91
+ .filter((link) => link.capturedAt >= now - HISTORY_RETENTION_MS)
92
+ .sort((left, right) => left.capturedAt - right.capturedAt)
93
+ .slice(-MAX_LINKS);
94
+ const path = helperRunLinksPath();
95
+ writePrivateFile(path, JSON.stringify({ version: 1, links: kept }));
96
+ const stamp = stampOf(path);
97
+ cached = stamp ? { path, stamp, links: new Map(kept.map((link) => [link.folder, link])) } : undefined;
98
+ return fresh.size;
99
+ }
@@ -1,6 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import { recordCommandProcessSample } from "../command-process/history";
4
+ import { captureHelperRuns, helperRunProcesses } from "../../helper-runs/capture";
4
5
  import { sampleProcessRows } from "./ps-reader";
5
6
  import { attributeByAncestry, processDetail, processGroupName } from "./process-ownership";
6
7
  export { executableOf, processGroupName, processDetail } from "./process-ownership";
@@ -224,6 +225,8 @@ export async function sampleAgentProcesses(): Promise<Record<string, AgentProces
224
225
  const sampledAt = Date.now();
225
226
  const sessions = await resolveSessions(rows);
226
227
  const ownership = attributeByAncestry(rows);
228
+ // A helper run lives for half a minute; this sample may be the only one that sees its process.
229
+ await captureHelperRuns(helperRunProcesses(rows, ownership, sessions));
227
230
  recordCommandProcessSample(rows.flatMap((row) => {
228
231
  const agent = ownership.agents.get(row.pid);
229
232
  if (!agent) return [];
@@ -20,6 +20,7 @@ import type { MeshStore } from "../store";
20
20
  import { queueProjectBindingSync } from "../../engine/runtime/engine-projects";
21
21
  import { isCursorTaskCloneId } from "../../sessions/cursor/catalog";
22
22
  import { localTaskTransfers } from '../../task-transfer';
23
+ import { helperRunFolder } from '../../helper-runs';
23
24
  export { inspectRepositoryAsync, inspectWorkingTreeAsync, readRepositoryGit } from "./repository-inspection";
24
25
  export { prepareMonitorInspection } from "./monitor-inspection";
25
26
  import type { CatalogInspection } from "./monitor-inspection";
@@ -171,7 +172,8 @@ function linkSession(input: {
171
172
  const { store, session, computerId, inspect } = input;
172
173
  const agent = provider(session.agent);
173
174
  const cwd = session.cwd?.trim();
174
- if (!agent || !cwd) return session;
175
+ // A generator's throwaway folder is not a workspace: registering it minted a Mesh per run.
176
+ if (!agent || !cwd || helperRunFolder(cwd)) return session;
175
177
  const knownTaskId = store.taskForExecution(computerId, agent, session.sessionId);
176
178
  const knownProjectId = knownTaskId ? store.task(knownTaskId)?.projectId : undefined;
177
179
  const previous = knownProjectId ? store.snapshot(knownProjectId)?.executions.find(row =>
@@ -34,6 +34,7 @@ import { restoreHandoffResult, validStoredReceipt } from './receipts';
34
34
  import {
35
35
  projectCapabilityRequests,
36
36
  } from "../catalog/project/requests";
37
+ import { helperRunProject } from "../../helper-runs";
37
38
 
38
39
  export class MeshStore extends MeshPreparedStore {
39
40
  recordReceipt(input: ReceiptValue): void {
@@ -266,9 +267,10 @@ export class MeshStore extends MeshPreparedStore {
266
267
  return this.state.events.filter((event) => event.projectId === projectId);
267
268
  }
268
269
 
270
+ /** One registered for a helper run's throwaway folder, before such runs were recognised, is kept but not listed. */
269
271
  projectIds(): string[] {
270
272
  this.sync();
271
- return this.state.projects.map((project) => project.projectId);
273
+ return this.state.projects.filter((project) => !helperRunProject(project)).map((project) => project.projectId);
272
274
  }
273
275
 
274
276
  workspaceForRepository(canonicalRepositoryId: string, computerId?: string): string | undefined {
@@ -7,6 +7,9 @@ Terminal responses remain correlated to the original message id.
7
7
 
8
8
  `acceptance.ts` decides when a phone message counts as delivered: when the agent
9
9
  has taken it, not when its whole turn ends. Tests live in `tests/acceptance.test.ts`.
10
+ `lateRunsSettling` stays true until the answer of such a run has been sent, so a
11
+ runtime update cannot replace the monitor between the provider exiting and its
12
+ answer reaching the phone.
10
13
 
11
14
  Integration tests: `tests/delivery/processing-receipt.test.ts`; attachment rejection
12
15
  coverage: `tests/attachment/attachment-uploads.test.ts`. See the monitor README.
@@ -20,6 +20,15 @@ export const ACCEPTANCE_WINDOW_MS = 3_000;
20
20
  /** A safety bound for an unattended turn; the person stops a run with Stop, not with a deadline. */
21
21
  export const PHONE_RUN_LIMIT_MS = 6 * 60 * 60_000;
22
22
 
23
+ let settling = 0;
24
+
25
+ /**
26
+ * True while a run that outlived its acceptance window still owes its chat the answer. The provider
27
+ * process ending is not the end of the turn: the answer is sent after it, and a runtime handoff in
28
+ * between would lose it.
29
+ */
30
+ export function lateRunsSettling(): boolean { return settling > 0; }
31
+
23
32
  export async function acceptWhenStarted<T>(
24
33
  run: Promise<T>,
25
34
  finish: (result: T) => Promise<unknown>,
@@ -32,6 +41,7 @@ export async function acceptWhenStarted<T>(
32
41
  const first = await Promise.race([run, started]);
33
42
  clearTimeout(timer);
34
43
  if (first !== "started") return first;
35
- void run.then(finish).catch(() => {});
44
+ settling += 1;
45
+ void run.then(finish).catch(() => {}).finally(() => { settling -= 1; });
36
46
  return "started";
37
47
  }