granttap-mcp 0.8.188 → 0.8.189

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 (37) hide show
  1. package/README.md +28 -0
  2. package/apps/bridge/src/codex-hook-trust/README.md +2 -0
  3. package/apps/bridge/src/codex-hook-trust/projection.ts +8 -5
  4. package/apps/bridge/src/helper-runs/README.md +4 -0
  5. package/apps/bridge/src/install/inspect.ts +5 -4
  6. package/apps/bridge/src/install/stable-node/README.md +14 -2
  7. package/apps/bridge/src/install/stable-node/index.ts +48 -2
  8. package/apps/bridge/src/machine-load/host/process-sampler.ts +3 -0
  9. package/apps/bridge/src/mesh/catalog/README.md +5 -0
  10. package/apps/bridge/src/mesh/catalog/index.ts +46 -5
  11. package/apps/bridge/src/mesh/store/index.ts +5 -2
  12. package/apps/bridge/src/runtime-updates/selection.d.mts +2 -1
  13. package/apps/bridge/src/runtime-updates/selection.mjs +13 -5
  14. package/apps/bridge/src/sessions/README.md +6 -0
  15. package/apps/bridge/src/sessions/catalog.ts +4 -2
  16. package/apps/bridge/src/sessions/scan/claude/parse.ts +31 -6
  17. package/apps/bridge/src/sessions/scan/claude/scan.ts +4 -1
  18. package/apps/bridge/src/sessions/scan/claude/shared.ts +2 -0
  19. package/apps/bridge/src/sessions/scan/codex/parse.ts +37 -7
  20. package/apps/bridge/src/sessions/scan/codex/scan.ts +2 -1
  21. package/apps/bridge/src/sessions/scan/codex/shared.ts +3 -0
  22. package/apps/bridge/src/sessions/scan/grok.ts +9 -2
  23. package/apps/bridge/src/sessions/support/common.ts +2 -0
  24. package/apps/bridge/src/started-by/README.md +94 -0
  25. package/apps/bridge/src/started-by/attach.ts +136 -0
  26. package/apps/bridge/src/started-by/capture.ts +186 -0
  27. package/apps/bridge/src/started-by/facts.ts +154 -0
  28. package/apps/bridge/src/started-by/headless.ts +146 -0
  29. package/apps/bridge/src/started-by/index.ts +7 -0
  30. package/apps/bridge/src/started-by/links.ts +175 -0
  31. package/apps/bridge/src/started-by/mesh/index.ts +106 -0
  32. package/cursor-plugin/README.md +1 -1
  33. package/cursor-plugin/mcp.json +1 -1
  34. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  35. package/package.json +1 -1
  36. package/packages/protocol/messages/README.md +7 -0
  37. package/packages/protocol/messages/sessions/index.ts +12 -0
package/README.md CHANGED
@@ -757,6 +757,34 @@ A shell call is fingerprinted for Project policy by the command it runs —
757
757
  instead of deciding about the shell as a whole; a line with no command word
758
758
  is still plain `Shell`.
759
759
 
760
+ ### Chats started by another chat
761
+
762
+ A chat that runs another provider headless from its shell — `codex exec "…"`,
763
+ `claude -p "…"`, `grok -p "…"` — starts a chat in its own right. Its session
764
+ record names the chat that started it:
765
+
766
+ ```ts
767
+ startedBy?: { agent: "claude" | "codex" | "grok" | "cursor"; sessionId: string }
768
+ ```
769
+
770
+ The field is strict on the wire (no other key; the id is 8–128 characters of
771
+ `A–Z a–z 0–9 . _ -`) and is published even when the parent is on another
772
+ computer or gone; the phone decides how to draw the tree. Short picture runs in
773
+ a folder made for them stay nested conversations in their chat's
774
+ `childThreads`, as before.
775
+
776
+ The link is read from the run's live process — Claude Code and Codex hand every
777
+ command a chat runs that chat's id, and the run inherits it; only that variable
778
+ is read, only for headless provider processes this monitor did not start
779
+ itself — and written to `started-by.json`. A run whose process was never seen is
780
+ matched after the fact from the parent's transcript: a command that starts the
781
+ child's provider, carries the opening of its first request, and was running
782
+ when it started, on the same computer; a child two chats could have started
783
+ stays unlinked. Interactive sessions are never children. A child working in a
784
+ temp folder, a plain folder or one of its parent's checkout is in its parent's
785
+ Mesh and registers no Mesh of its own; one in a checkout of its own keeps that
786
+ checkout's. Details: [`apps/bridge/src/started-by`](apps/bridge/src/started-by/README.md).
787
+
760
788
  ### One computer, whatever the network calls it
761
789
 
762
790
  The Mesh keys a computer by an identity written down once, on first use, in
@@ -8,6 +8,8 @@ installed by this runtime (`PreToolUse` and `PermissionRequest`) can be reviewed
8
8
  A hook an earlier runtime wrote through its launcher in the private version cache
9
9
  still counts as this runtime's, because that launcher hands off to the selected
10
10
  version; setup keeps it, so an automatic update does not void its Codex trust.
11
+ The hook's absolute Node may be another existing `node` than the one reading it
12
+ ([stable Node](../install/stable-node/README.md)).
11
13
  Project, plugin, managed, ambiguous, or unrelated commands are never approved.
12
14
  Unsupported native APIs report unknown; configured hooks alone do not establish
13
15
  readiness or computer enforcement.
@@ -2,8 +2,8 @@ import { dirname, join } from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { ProviderHook, type ProviderHook as Hook } from "../../../../packages/protocol/messages/provider-hooks";
4
4
  import { configDir } from "../config/runtime/paths";
5
- import { cachedHookLauncher, runtimeVersion } from "../runtime-updates/selection.mjs";
6
- import { hookNodeCommand } from "../install/stable-node";
5
+ import { runtimeVersion } from "../runtime-updates/selection.mjs";
6
+ import { hookLaunchesRuntime, hookNodeCommand } from "../install/stable-node";
7
7
 
8
8
  const root = join(dirname(fileURLToPath(import.meta.url)), "..", "..", "..", "..");
9
9
 
@@ -12,10 +12,13 @@ export function ownedHookCommands() {
12
12
  return { policy: `${base} codex-policy`, permission: `${base} codex` };
13
13
  }
14
14
 
15
- /** This runtime's command, or an earlier runtime's cached launcher that hands off to it. */
15
+ /**
16
+ * This runtime's command, or an earlier runtime's cached launcher that hands off to it, run by any
17
+ * existing Node the setup named: which Node reads the hook does not decide whether it is installed.
18
+ */
16
19
  export function ownedHookCommand(command: unknown, kind: "policy" | "permission"): boolean {
17
- return command === ownedHookCommands()[kind] || cachedHookLauncher(command,
18
- kind === "policy" ? "codex-policy" : "codex", join(configDir(), "runtime-updates"), runtimeVersion(root), hookNodeCommand("codex"));
20
+ return command === ownedHookCommands()[kind] || hookLaunchesRuntime(command,
21
+ kind === "policy" ? "codex-policy" : "codex", root, runtimeVersion(root), join(configDir(), "runtime-updates"));
19
22
  }
20
23
 
21
24
  /** Only the two exact user-config hooks installed by this runtime are reviewable. */
@@ -54,6 +54,10 @@ in place of the path line that names them. A phone reads one with
54
54
  picture's content, never a path, and only the chat that started the run is
55
55
  answered.
56
56
 
57
+ A headless run that is a chat in its own right, such as `codex exec` in a folder
58
+ several runs share, is not a helper run: it stays a chat and names the chat that
59
+ started it in `startedBy` ([chats started by another chat](../started-by/README.md)).
60
+
57
61
  **Meshes.** A run is not passed to the Mesh, and a generator's folder never
58
62
  registers one. A Mesh without a remote whose folder is a generator's, is
59
63
  gone from the temp directory, or lies inside a Git checkout without being a
@@ -43,8 +43,8 @@ import { monitorPlistLooksInstalled } from "./monitor-helper";
43
43
  import { inspectLinuxService } from "./linux-service";
44
44
  import { codexHooksExplicitlyDisabled } from "./hooks";
45
45
  import { cachedCodexHooks, codexHookSet } from "../codex-hook-trust";
46
- import { cachedHookLauncher, runtimeVersion } from "../runtime-updates/selection.mjs";
47
- import { hookNodeCommand } from "./stable-node";
46
+ import { runtimeVersion } from "../runtime-updates/selection.mjs";
47
+ import { hookLaunchesRuntime, hookNodeCommand } from "./stable-node";
48
48
  import type { ProviderHook } from "../../../../packages/protocol/messages/provider-hooks";
49
49
  export { codexHookSet } from "../codex-hook-trust";
50
50
 
@@ -76,11 +76,12 @@ export function commandHasRoute(command: unknown, route: HookRoute): boolean {
76
76
  /**
77
77
  * This runtime's command, or an earlier runtime's launcher in the version cache,
78
78
  * which hands off to this one. Keeping that command after an automatic update
79
- * also keeps the trust Codex records for it.
79
+ * also keeps the trust Codex records for it. A Codex hook may name another
80
+ * existing Node than the one reading it (`hookNodeAccepted`).
80
81
  */
81
82
  export function hookCommandIsCurrent(command: unknown, route: HookRoute): boolean {
82
83
  return typeof command === "string" && (command.trim() === hookCommand(route)
83
- || cachedHookLauncher(command, route, join(configDir(), "runtime-updates"), runtimeVersion(repoRoot), hookNodeCommand(route)));
84
+ || hookLaunchesRuntime(command, route, repoRoot, runtimeVersion(repoRoot), join(configDir(), "runtime-updates")));
84
85
  }
85
86
 
86
87
  export type InstallResult = { status: "installed" | "already" | "manual"; detail: string };
@@ -12,9 +12,21 @@ that require `node` on PATH; the changed definitions require native hook review.
12
12
  The launcher path can still survive runtime updates when the Node command is
13
13
  unchanged. Other providers keep their existing hook definitions.
14
14
 
15
- Public entries: `publishStableNode` and `hookNodeCommand`. Windows gets no link.
15
+ Which Node reads a Codex hook does not decide whether it is installed: the
16
+ monitor and the MCP server a chat starts can run on different Node versions, and
17
+ the hook names the one setup ran on. `hookNodeAccepted` takes any existing
18
+ executable named `node` (`node.exe` on Windows) given by an absolute, quoted
19
+ path, the stable link included; a path that is gone or names another program is
20
+ not accepted. Every other check stands: the route, the exact shape setup writes,
21
+ and a launcher that is this runtime or a valid cached one not newer than it
22
+ (`hookLaunchesRuntime`). Setup leaves such a command as written, so the trust
23
+ Codex keeps for that exact command is not voided.
24
+
25
+ Public entries: `publishStableNode`, `hookNodeCommand`, `hookNodeAccepted` and
26
+ `hookLaunchesRuntime`. Windows gets no link.
16
27
  A storage failure never stops the monitor from starting. Tests run the published
17
- link and cover replacement, Windows, and an unwritable folder.
28
+ link and cover replacement, Windows, and an unwritable folder;
29
+ `tests/install/codex-hook-node.test.ts` reads a hook set up under another Node.
18
30
 
19
31
  License: this module is distributed under the GrantTap Commercial Source License
20
32
  in the repository-root `LICENSE` file.
@@ -1,6 +1,7 @@
1
- import { mkdirSync, readlinkSync, renameSync, rmSync, symlinkSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { accessSync, constants, mkdirSync, readlinkSync, renameSync, rmSync, statSync, symlinkSync } from "node:fs";
2
+ import { basename, join, resolve, win32 } from "node:path";
3
3
  import { configDir } from "../../config";
4
+ import { cachedHookLauncher, hookLauncherParts } from "../../runtime-updates/selection.mjs";
4
5
 
5
6
  /** User Codex hooks run outside the plugin PATH, including apps started from the Dock. */
6
7
  export function hookNodeCommand(route: string, nodePath = process.execPath,
@@ -11,6 +12,51 @@ export function hookNodeCommand(route: string, nodePath = process.execPath,
11
12
  return `"${escaped}"`;
12
13
  }
13
14
 
15
+ /** The path a quoted Node token names, undone the way `hookNodeCommand` escaped it. */
16
+ function quotedPath(token: string, platform: NodeJS.Platform): string | undefined {
17
+ if (token.length < 3 || !token.startsWith('"') || !token.endsWith('"')) return undefined;
18
+ const inner = token.slice(1, -1);
19
+ return platform === "win32" ? inner.replaceAll('""', '"') : inner.replace(/\\(["\\$`])/g, "$1");
20
+ }
21
+
22
+ /**
23
+ * Whether a hook's Node token is one its route may run with. Other providers keep plain `node`. A
24
+ * Codex hook names a Node by absolute path, and which one was the setup's: the monitor and the MCP
25
+ * server a chat starts can run on different Node versions, and one of them reading the hook must
26
+ * not call the other's hook missing. Any existing executable named `node` by an absolute, quoted
27
+ * path qualifies, the stable link in the configuration folder included; a path that is gone does not.
28
+ */
29
+ export function hookNodeAccepted(route: string, token: string, nodePath = process.execPath,
30
+ platform: NodeJS.Platform = process.platform): boolean {
31
+ if (route !== "codex" && route !== "codex-policy") return token === "node";
32
+ if (token === hookNodeCommand(route, nodePath, platform)) return true;
33
+ const path = quotedPath(token, platform);
34
+ if (!path) return false;
35
+ const windows = platform === "win32";
36
+ const absolute = windows ? win32.isAbsolute(path) && /^[A-Za-z]:[\\/]/.test(path) : path.startsWith("/");
37
+ const name = windows ? win32.basename(path).toLowerCase() : basename(path);
38
+ if (!absolute || name !== (windows ? "node.exe" : "node")) return false;
39
+ try {
40
+ if (!statSync(path).isFile()) return false;
41
+ if (!windows) accessSync(path, constants.X_OK);
42
+ return true;
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
47
+
48
+ /**
49
+ * A hook command for `route` that launches the runtime in `root`, or an earlier cached launcher that
50
+ * hands off to it (`current` is that runtime's version), with a Node the route accepts.
51
+ */
52
+ export function hookLaunchesRuntime(command: unknown, route: string, root: string, current: string,
53
+ cache = join(configDir(), "runtime-updates")): boolean {
54
+ const node = (token: string) => hookNodeAccepted(route, token);
55
+ const parts = hookLauncherParts(command);
56
+ if (parts && parts.route === route && node(parts.node) && resolve(parts.root) === resolve(root)) return true;
57
+ return cachedHookLauncher(command, route, cache, current, node);
58
+ }
59
+
14
60
  function currentTarget(link: string): string | undefined {
15
61
  try { return readlinkSync(link); } catch { return undefined; }
16
62
  }
@@ -2,6 +2,7 @@ import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import { recordCommandProcessSample } from "../command-process/history";
4
4
  import { captureHelperRuns, helperRunProcesses } from "../../helper-runs/capture";
5
+ import { captureStartedRuns, startedRunProcesses } from "../../started-by/capture";
5
6
  import { sampleProcessRows } from "./ps-reader";
6
7
  import { attributeByAncestry, processDetail, processGroupName } from "./process-ownership";
7
8
  export { executableOf, processGroupName, processDetail } from "./process-ownership";
@@ -227,6 +228,8 @@ export async function sampleAgentProcesses(): Promise<Record<string, AgentProces
227
228
  const ownership = attributeByAncestry(rows);
228
229
  // A helper run lives for half a minute; this sample may be the only one that sees its process.
229
230
  await captureHelperRuns(helperRunProcesses(rows, ownership, sessions));
231
+ // So is a chat another chat runs headless: only its live process names the chat that started it.
232
+ await captureStartedRuns(startedRunProcesses(rows, ownership, sessions, sampledAt));
230
233
  recordCommandProcessSample(rows.flatMap((row) => {
231
234
  const agent = ownership.agents.get(row.pid);
232
235
  if (!agent) return [];
@@ -12,6 +12,11 @@ bound to the parent folder's Mesh as before; one with its own remote is not
12
12
  there is taken out with a removal record. Apple clients partition workspace Tasks
13
13
  using those observations without moving them between access scopes.
14
14
 
15
+ A chat another chat started (`startedBy`) whose folder is no checkout of its
16
+ own is placed in its parent's Mesh and binds nothing for its folder; parents are
17
+ linked first within a batch
18
+ ([chats started by another chat](../../started-by/README.md)).
19
+
15
20
  Git facts are shared only within one catalog batch. The next reading refreshes
16
21
  the root, origin, worktree, and revision, including a workspace which becomes an
17
22
  empty Git repository before its first commit or later gains an origin. Neither
@@ -22,6 +22,7 @@ import { queueProjectBindingSync } from "../../engine/runtime/engine-projects";
22
22
  import { isCursorTaskCloneId } from "../../sessions/cursor/catalog";
23
23
  import { localTaskTransfers } from '../../task-transfer';
24
24
  import { helperRunFolder } from '../../helper-runs';
25
+ import { childrenLast, inheritsParentMesh, parentPlacement, type MeshPlacement } from '../../started-by/mesh';
25
26
  import { presentableTitle } from '../../sessions/support/activity-helpers';
26
27
  export { inspectRepositoryAsync, inspectWorkingTreeAsync, readRepositoryGit } from "./repository-inspection";
27
28
  export { prepareMonitorInspection } from "./monitor-inspection";
@@ -161,16 +162,26 @@ export function linkSessionsToProjects(
161
162
  }
162
163
  return facts;
163
164
  };
164
- return visible.map((session) => linkSession({ store, session, computerId, inspect: inspectOnce, inspectWorkingTree }));
165
+ // A chat another chat started follows its parent into the parent's Mesh, so parents go first.
166
+ const placed = new Map<string, MeshPlacement>();
167
+ const linked: SessionInfo[] = [...visible];
168
+ for (const index of childrenLast(visible)) {
169
+ linked[index] = linkSession({ store, session: visible[index]!, computerId, inspect: inspectOnce, inspectWorkingTree, placed });
170
+ }
171
+ return linked;
165
172
  }
166
173
 
167
- function linkSession(input: {
174
+ type LinkInput = {
168
175
  store: MeshStore;
169
176
  session: SessionInfo;
170
177
  computerId: string;
171
178
  inspect: (cwd: string) => RepositoryFacts;
172
179
  inspectWorkingTree: (cwd: string) => boolean | undefined;
173
- }): SessionInfo {
180
+ /** Where this catalog put each chat so far, by provider and session. */
181
+ placed: Map<string, MeshPlacement>;
182
+ };
183
+
184
+ function linkSession(input: LinkInput): SessionInfo {
174
185
  const { store, session, computerId, inspect } = input;
175
186
  const agent = provider(session.agent);
176
187
  const cwd = session.cwd?.trim();
@@ -187,6 +198,8 @@ function linkSession(input: {
187
198
  if (retained.worktree && retained.revision
188
199
  && retained.canonicalRepositoryId === previous.repositoryId) repository = retained;
189
200
  }
201
+ // A child in a folder that is no checkout of its own is its parent's work: no Mesh for its folder.
202
+ if (inheritsParentMesh(session, repository)) return linkStartedChild(input, agent, cwd, knownTaskId);
190
203
  const projectId = (knownTaskId ? store.task(knownTaskId)?.projectId : undefined)
191
204
  ?? store.projectIdForRepository(repository.canonicalRepositoryId, computerId)
192
205
  ?? projectIdentity(repository.canonicalRepositoryId);
@@ -215,14 +228,16 @@ function linkSession(input: {
215
228
  updatedAt: session.lastActivityAt,
216
229
  };
217
230
  store.upsertTask(task);
231
+ const repositoryId = repository.worktree ? repository.canonicalRepositoryId
232
+ : previous?.repositoryId ?? repository.canonicalRepositoryId;
233
+ input.placed.set(`${session.agent}\0${session.sessionId}`, { projectId, repositoryId });
218
234
  store.linkExecution({
219
235
  taskId,
220
236
  sessionId: session.sessionId,
221
237
  provider: agent,
222
238
  computerId,
223
239
  workspace: cwd,
224
- repositoryId: repository.worktree ? repository.canonicalRepositoryId
225
- : previous?.repositoryId ?? repository.canonicalRepositoryId,
240
+ repositoryId,
226
241
  activeAt: session.lastActivityAt,
227
242
  state: session.state, continuedAt: session.transfer?.continuedAt,
228
243
  branch: repository.branch ?? session.branch,
@@ -233,6 +248,32 @@ function linkSession(input: {
233
248
  return { ...session, projectId, taskId, computerId, worktree: repository.worktree ?? previous?.worktree };
234
249
  }
235
250
 
251
+ /**
252
+ * A chat another chat started, in a folder that is no checkout of its own, in its parent's Mesh. The
253
+ * folder is bound to nothing. Without its parent's Mesh on this computer the child is in none.
254
+ */
255
+ function linkStartedChild(input: LinkInput, agent: MeshProvider, cwd: string, knownTaskId: string | undefined): SessionInfo {
256
+ const { store, session, computerId } = input;
257
+ const parent = parentPlacement(session.startedBy!, input.placed, store, computerId);
258
+ if (!parent) return session;
259
+ const known = knownTaskId ? store.task(knownTaskId) : undefined;
260
+ // A Task an older runtime made in a Mesh of the child's own folder stays there; the chat moves on.
261
+ const taskId = known?.projectId === parent.projectId ? known.taskId : taskIdentity(parent.projectId, agent, session.sessionId);
262
+ store.upsertTask({
263
+ taskId, projectId: parent.projectId, title: meshTaskTitle(session, agent),
264
+ goal: (session.summary ?? session.title ?? "Continue this coding task").slice(0, 1_000),
265
+ state: taskState(session), ownerSessionId: session.sessionId, createdAt: session.startedAt, updatedAt: session.lastActivityAt,
266
+ });
267
+ store.linkExecution({
268
+ taskId, sessionId: session.sessionId, provider: agent, computerId, workspace: cwd,
269
+ ...(parent.repositoryId ? { repositoryId: parent.repositoryId } : {}),
270
+ activeAt: session.lastActivityAt, state: session.state, continuedAt: session.transfer?.continuedAt,
271
+ branch: session.branch, startedAt: session.startedAt,
272
+ });
273
+ input.placed.set(`${session.agent}\0${session.sessionId}`, parent);
274
+ return { ...session, projectId: parent.projectId, taskId, computerId };
275
+ }
276
+
236
277
  /**
237
278
  * Bind the chat's checkout to its Project on this computer. A repository the
238
279
  * person took out of that Project here stays out, however many chats run in it.
@@ -35,6 +35,7 @@ import {
35
35
  projectCapabilityRequests,
36
36
  } from "../catalog/project/requests";
37
37
  import { helperRunProject } from "../../helper-runs";
38
+ import { startedChildrenProjects } from "../../started-by/mesh";
38
39
  import { supersedingProject } from "../local-remote/folder-meshes";
39
40
 
40
41
  export class MeshStore extends MeshRepositoryStore {
@@ -268,10 +269,12 @@ export class MeshStore extends MeshRepositoryStore {
268
269
  return this.state.events.filter((event) => event.projectId === projectId);
269
270
  }
270
271
 
271
- /** One registered for a helper run's throwaway folder, before such runs were recognised, is kept but not listed. */
272
+ /** One registered for a helper run's or a started chat's folder, before they were recognised, is kept but not listed. */
272
273
  projectIds(): string[] {
273
274
  this.sync();
274
- return this.state.projects.filter((project) => !helperRunProject(project)).map((project) => project.projectId);
275
+ const children = startedChildrenProjects(this.state.projects, this.state.tasks, this.state.executions);
276
+ return this.state.projects.filter((project) => !helperRunProject(project) && !children.has(project.projectId))
277
+ .map((project) => project.projectId);
275
278
  }
276
279
 
277
280
  workspaceForRepository(canonicalRepositoryId: string, computerId?: string): string | undefined {
@@ -7,5 +7,6 @@ export function runtimeVersion(root:string):string;
7
7
  export function versionRoot(directory:string,version:string):string;
8
8
  export function validRuntime(root:string|undefined,directory:string,version:string|undefined):boolean;
9
9
  export function selectedRuntime(bundled:string,directory:string):string;
10
- export function cachedHookLauncher(command:unknown,route:string,directory:string,current:string,nodeCommand?:string):boolean;
10
+ export function hookLauncherParts(command:unknown):{node:string;root:string;route:string}|undefined;
11
+ export function cachedHookLauncher(command:unknown,route:string,directory:string,current:string,nodeCommand?:string|((token:string)=>boolean)):boolean;
11
12
  export function rollbackRuntime(bundled:string,directory:string,failedRoot?:string):boolean;
@@ -34,17 +34,25 @@ export function selectedRuntime(bundled, directory) {
34
34
  return validRuntime(state.root,directory,state.version) && newerVersion(state.version,runtimeVersion(bundled))
35
35
  ? state.root : bundled;
36
36
  }
37
+ /** `node` or one double-quoted Node path, the launcher's quoted path, and the route: the shape setup writes. */
38
+ const HOOK_SHAPE=/^(node|"(?:[^"\\]|\\.)+") "([^"]+)[\\/]bin[\\/]granttap-mcp\.mjs" internal hook (\S+)$/;
39
+ /** A hook command in the shape setup writes, taken apart; anything else is not one. */
40
+ export function hookLauncherParts(command) {
41
+ const match=typeof command==='string' ? command.trim().match(HOOK_SHAPE) : null;
42
+ return match ? { node:match[1], root:match[2], route:match[3] } : undefined;
43
+ }
37
44
  /**
38
45
  * A provider hook written by an earlier runtime names that runtime's launcher in
39
46
  * this cache. Each cached launcher hands off to the selection above, so the hook
40
47
  * stays current after an update; one naming a newer, rolled-back release does not.
48
+ * `nodeCommand` is the exact Node token, or a test of it for a route that accepts more than one.
41
49
  */
42
50
  export function cachedHookLauncher(command, route, directory, current, nodeCommand = 'node') {
43
- const prefix=nodeCommand+' "', raw=typeof command==='string' ? command.trim() : '';
44
- const match=raw.startsWith(prefix) && raw.slice(prefix.length).match(/^(.+)[\\/]bin[\\/]granttap-mcp\.mjs" internal hook (\S+)$/);
45
- if(!match || match[2]!==route) return false;
46
- try { const version=runtimeVersion(match[1]);
47
- return validRuntime(match[1],directory,version) && !newerVersion(version,current); } catch { return false; }
51
+ const parts=hookLauncherParts(command);
52
+ const node=typeof nodeCommand==='function' ? nodeCommand : token => token===nodeCommand;
53
+ if(!parts || parts.route!==route || !node(parts.node)) return false;
54
+ try { const version=runtimeVersion(parts.root);
55
+ return validRuntime(parts.root,directory,version) && !newerVersion(version,current); } catch { return false; }
48
56
  }
49
57
  /** A new background service that exits during startup restores the last working selection. */
50
58
  export function rollbackRuntime(bundled, directory, failedRoot) {
@@ -39,6 +39,12 @@ the scanner records that mapping. Parent and sibling logs are not reparsed for
39
39
  each child request. Old records outside that recent window are not included in
40
40
  the child snapshot. Root chat pagination remains in `TranscriptHistory`.
41
41
 
42
+ Each scan also reports, per session and never published, whether it was
43
+ started headless, how its first request opened, and the commands it ran that
44
+ start another provider headless (`Scan.lineage`). The catalog uses them to name
45
+ the chat that started a chat (`startedBy`,
46
+ [chats started by another chat](../started-by/README.md)).
47
+
42
48
  Feature tests live in `tests/`; the reusable multi-provider conversation harness
43
49
  lives in the repository `tests/thread/` directory.
44
50
 
@@ -3,6 +3,7 @@ import { localTaskTransfers, localTransferContinuations } from "../task-transfer
3
3
  import { MAX_FILES, MAX_HISTORY, MAX_LIVE, TOKEN_WINDOW_MS } from "./support/common";
4
4
  import { providerScans, cooperativeProviderScans, type ProviderScan } from "./provider-discovery";
5
5
  import { attachHelperRuns } from "../helper-runs";
6
+ import { attachStartedBy } from "../started-by";
6
7
 
7
8
  function sessionKey(session: SessionInfo): string {
8
9
  return `${session.agent}\0${session.sessionId}`;
@@ -50,8 +51,9 @@ function pickWithReserve(
50
51
 
51
52
  function catalogFromScans(scans: ProviderScan[]) {
52
53
  // A helper run is a conversation of the chat that started it, never a chat in these lists.
53
- const native = attachHelperRuns(sortedUniqueSessions(scans.flatMap((scan) => scan.sessions)),
54
- scans.flatMap((scan) => scan.helperRuns ?? []));
54
+ // A chat another chat ran headless stays a chat, and names the chat that started it.
55
+ const native = attachStartedBy(attachHelperRuns(sortedUniqueSessions(scans.flatMap((scan) => scan.sessions)),
56
+ scans.flatMap((scan) => scan.helperRuns ?? [])), scans.flatMap((scan) => scan.lineage ?? []));
55
57
  // Prepared transfers replace native ids; rank their native activity before
56
58
  // the bounded live/history windows, rather than appending them after older chats.
57
59
  const sessions = sortedUniqueSessions(localTaskTransfers().catalog(native));
@@ -22,6 +22,7 @@ import {
22
22
 
23
23
  import { readTranscriptRows } from "./transcript-reading";
24
24
  import { readClaudeChild } from "./child-reading";
25
+ import { createClaudeLineageCalls, promptLead, type LineageCalls, type LineageFact, type PromptLead } from "../../../started-by";
25
26
 
26
27
  type ClaudeParseState = ClaudeTurnClock & {
27
28
  sessionId: string;
@@ -47,6 +48,10 @@ type ClaudeParseState = ClaudeTurnClock & {
47
48
  repositoryPaths: string[];
48
49
  changedPaths: string[];
49
50
  turnEnded: boolean;
51
+ /** How the chat was started: `cli` at a terminal, `sdk-cli` for `claude -p`. The first record says. */
52
+ entrypoint?: string;
53
+ /** The opening of the first request, for finding the chat that started this one. */
54
+ prompt?: PromptLead;
50
55
  };
51
56
 
52
57
  const CLAUDE_EFFORTS = new Set(["low", "medium", "high", "xhigh", "max"]);
@@ -71,6 +76,7 @@ function applyClaudeLine(d: any, state: ClaudeParseState): void {
71
76
  state.repositoryPaths = state.repositoryPaths.slice(-64);
72
77
  state.changedPaths = state.changedPaths.slice(-64);
73
78
  if (d.sessionId && !state.sessionId) state.sessionId = String(d.sessionId);
79
+ if (!state.entrypoint && typeof d.entrypoint === "string") state.entrypoint = d.entrypoint;
74
80
  if (d.isSidechain !== true) {
75
81
  if (typeof d.cwd === "string" && d.cwd.trim()) {
76
82
  state.cwd = d.cwd;
@@ -98,7 +104,10 @@ function applyClaudeLine(d: any, state: ClaudeParseState): void {
98
104
  : "";
99
105
  // Named by what the person wrote, without the host's wrappers around it.
100
106
  const clean = visibleUserText(raw).replace(/\s+/g, " ").trim();
101
- if (clean) state.title = clean.slice(0, 120);
107
+ if (clean) {
108
+ state.title = clean.slice(0, 120);
109
+ state.prompt = promptLead(clean);
110
+ }
102
111
  }
103
112
  const t = ts(d.timestamp);
104
113
  if (t) {
@@ -142,9 +151,12 @@ function applyClaudeLine(d: any, state: ClaudeParseState): void {
142
151
  }
143
152
  }
144
153
 
145
- type ClaudeParseResult = { session: SessionInfo; tokensSession: number; childPaths: string[] } | undefined;
154
+ type ClaudeParseResult = { session: SessionInfo; tokensSession: number; childPaths: string[]; lineage?: LineageFact } | undefined;
146
155
 
147
- /** What was already read from one growing transcript. It holds summaries, never message text. */
156
+ /**
157
+ * What was already read from one growing transcript. It holds summaries, never message text, beside
158
+ * the opening of the first request and the commands that start another provider (`started-by`).
159
+ */
148
160
  export type ClaudeParseProgress = {
149
161
  device: number;
150
162
  inode: number;
@@ -153,6 +165,8 @@ export type ClaudeParseProgress = {
153
165
  tail: Buffer;
154
166
  state: ClaudeParseState;
155
167
  capabilities: ReturnType<typeof createClaudeCapabilityCollector>;
168
+ /** Commands the chat ran that start another provider's chat headless. */
169
+ lineage: LineageCalls;
156
170
  children: Map<string, { fingerprint: string; summary: ChildThreadInfo; observations: ReturnType<typeof claudeCapabilityUsage> }>;
157
171
  };
158
172
 
@@ -161,7 +175,7 @@ function newProgress(device: number, inode: number, fallbackSessionId: string):
161
175
  sessionId: "", startedAt: 0, lastActivityAt: 0, lastMessageAt: 0,
162
176
  tokensSession: 0, tokensLastTurn: 0, repositoryPaths: [], changedPaths: [], turnEnded: false,
163
177
  };
164
- return { device, inode, offset: 0, tail: Buffer.alloc(0), state, children: new Map(),
178
+ return { device, inode, offset: 0, tail: Buffer.alloc(0), state, children: new Map(), lineage: createClaudeLineageCalls(),
165
179
  capabilities: createClaudeCapabilityCollector(() => ({ sessionId: state.sessionId || fallbackSessionId,
166
180
  lastActivityAt: state.lastActivityAt, cwd: state.cwd })) };
167
181
  }
@@ -178,6 +192,7 @@ function applyRow(line: string, progress: ClaudeParseProgress): boolean {
178
192
  if (!row) return false;
179
193
  applyClaudeLine(row, progress.state);
180
194
  progress.capabilities.add(row);
195
+ progress.lineage.add(row);
181
196
  return true;
182
197
  }
183
198
 
@@ -237,7 +252,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
237
252
  state: stateFor(child.lastActivityAt),
238
253
  })),
239
254
  };
240
- return { session, tokensSession: cached.tokensSession, childPaths };
255
+ return { session, tokensSession: cached.tokensSession, childPaths, lineage: cached.lineage };
241
256
  }
242
257
  // Taken out of the cache while in use: a parallel reader starts its own pass
243
258
  // instead of applying the same rows to this one between our slices.
@@ -288,6 +303,7 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
288
303
  const observations = progress.capabilities.snapshot();
289
304
  const childThreads = yield* readChildren(actualChildPaths, ownSession, progress, observations);
290
305
  const session = aggregateChildThreads(ownSession, childThreads);
306
+ const lineage = claudeLineage(state, ownSession, progress.lineage.snapshot());
291
307
  claudeSummaryCache.set(file, {
292
308
  mtimeMs: fileStat.mtimeMs,
293
309
  size: fileStat.size,
@@ -298,8 +314,17 @@ export function* parseClaudeFileSteps(file: string): Generator<void, ClaudeParse
298
314
  observations,
299
315
  turnEnded: state.turnEnded,
300
316
  waits: { background: state.background, limit: state.limit },
317
+ lineage,
301
318
  // A chat that has gone quiet gives its memory back and is read again if it returns.
302
319
  progress: Date.now() - session.lastActivityAt <= LIVE_MS ? progress : undefined,
303
320
  });
304
- return { session, tokensSession: session.tokensSession, childPaths: actualChildPaths };
321
+ return { session, tokensSession: session.tokensSession, childPaths: actualChildPaths, lineage };
322
+ }
323
+
324
+ /** Where the chat came from, for `startedBy`: never published itself. */
325
+ function claudeLineage(state: ClaudeParseState, session: SessionInfo, calls: LineageFact["calls"]): LineageFact {
326
+ const headless = /^sdk-/.test(state.entrypoint ?? "");
327
+ return { agent: "claude", sessionId: session.sessionId, cwd: state.launchCwd ?? session.cwd, startedAt: session.startedAt,
328
+ ...(headless ? { headless } : {}), ...(headless && state.prompt ? { prompt: state.prompt } : {}),
329
+ ...(calls?.length ? { calls } : {}) };
305
330
  }
@@ -8,6 +8,7 @@ import {
8
8
  import { parseClaudeFileSteps } from "./parse";
9
9
  import { recentLogs, claudeProjectsRoot, MAX_FILES, TOKEN_WINDOW_MS, type Scan } from "../../support/common";
10
10
  import type { SessionInfo } from "../../../../../../packages/protocol/schema";
11
+ import type { LineageFact } from "../../../started-by";
11
12
 
12
13
  export function scanClaude(maxFiles = MAX_FILES): Scan {
13
14
  return withCheckoutObservationCache(() => finishScan(scanClaudeCatalog(maxFiles)));
@@ -26,6 +27,7 @@ function* scanClaudeCatalog(maxFiles: number): Generator<void, Scan> {
26
27
  const activeFiles = new Set(files);
27
28
  const seenSessionIds = new Set<string>();
28
29
  const sources: Array<{ sessionId: string; file: string; childPaths: string[] }> = [];
30
+ const lineage: LineageFact[] = [];
29
31
 
30
32
  for (const file of files) {
31
33
  yield;
@@ -37,6 +39,7 @@ function* scanClaudeCatalog(maxFiles: number): Generator<void, Scan> {
37
39
  tokensRecent += parsed.tokensSession;
38
40
  }
39
41
  sessions.push(parsed.session);
42
+ if (parsed.lineage) lineage.push(parsed.lineage);
40
43
  }
41
44
  for (const file of claudeSummaryCache.keys()) {
42
45
  if (!activeFiles.has(file)) claudeSummaryCache.delete(file);
@@ -47,5 +50,5 @@ function* scanClaudeCatalog(maxFiles: number): Generator<void, Scan> {
47
50
  claudeLogPathBySession.set(source.sessionId, source.file);
48
51
  claudeChildLogPathsBySession.set(source.sessionId, source.childPaths);
49
52
  }
50
- return { sessions, tokensRecent, sourceLimited: listed.length > maxFiles };
53
+ return { sessions, tokensRecent, sourceLimited: listed.length > maxFiles, lineage };
51
54
  }
@@ -61,6 +61,8 @@ export type CachedClaudeSummary = {
61
61
  waits?: ClaudeWaits;
62
62
  /** Where a growing transcript was last read to; see `ClaudeParseProgress`. */
63
63
  progress?: unknown;
64
+ /** Where the chat came from, kept after `progress` is let go. */
65
+ lineage?: import("../../../started-by").LineageFact;
64
66
  };
65
67
 
66
68
  export const claudeSummaryCache = new Map<string, CachedClaudeSummary>();