granttap-mcp 0.8.188 → 0.8.190

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 (68) hide show
  1. package/README.md +58 -1
  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 +20 -0
  5. package/apps/bridge/src/helper-runs/attach.ts +7 -4
  6. package/apps/bridge/src/helper-runs/pictures/capture.ts +2 -1
  7. package/apps/bridge/src/helper-runs/pictures/chats.ts +206 -0
  8. package/apps/bridge/src/helper-runs/pictures/store.ts +73 -15
  9. package/apps/bridge/src/install/inspect.ts +5 -4
  10. package/apps/bridge/src/install/stable-node/README.md +14 -2
  11. package/apps/bridge/src/install/stable-node/index.ts +48 -2
  12. package/apps/bridge/src/limit-continuation/README.md +4 -0
  13. package/apps/bridge/src/limit-continuation/index.ts +6 -3
  14. package/apps/bridge/src/machine-load/host/process-sampler.ts +3 -0
  15. package/apps/bridge/src/mesh/catalog/README.md +5 -0
  16. package/apps/bridge/src/mesh/catalog/index.ts +63 -7
  17. package/apps/bridge/src/mesh/runtime/graph/analysis.ts +2 -1
  18. package/apps/bridge/src/mesh/snapshot/window.ts +13 -1
  19. package/apps/bridge/src/mesh/store/index.ts +5 -2
  20. package/apps/bridge/src/monitor/handlers/catalog.ts +1 -1
  21. package/apps/bridge/src/monitor/handlers/inbound.ts +5 -0
  22. package/apps/bridge/src/monitor/support/runtime.ts +4 -1
  23. package/apps/bridge/src/runtime-updates/README.md +5 -2
  24. package/apps/bridge/src/runtime-updates/index.ts +25 -9
  25. package/apps/bridge/src/runtime-updates/selection.d.mts +2 -1
  26. package/apps/bridge/src/runtime-updates/selection.mjs +13 -5
  27. package/apps/bridge/src/session-catalog/README.md +9 -0
  28. package/apps/bridge/src/session-catalog/observed-state.ts +8 -1
  29. package/apps/bridge/src/session-catalog/publish-heads.ts +3 -1
  30. package/apps/bridge/src/session-catalog/started-children.ts +36 -0
  31. package/apps/bridge/src/session-images/index.ts +5 -3
  32. package/apps/bridge/src/sessions/README.md +6 -0
  33. package/apps/bridge/src/sessions/catalog.ts +10 -4
  34. package/apps/bridge/src/sessions/scan/claude/parse.ts +31 -6
  35. package/apps/bridge/src/sessions/scan/claude/scan.ts +4 -1
  36. package/apps/bridge/src/sessions/scan/claude/shared.ts +2 -0
  37. package/apps/bridge/src/sessions/scan/codex/README.md +33 -1
  38. package/apps/bridge/src/sessions/scan/codex/activity/rows.ts +23 -8
  39. package/apps/bridge/src/sessions/scan/codex/outcome/index.ts +161 -0
  40. package/apps/bridge/src/sessions/scan/codex/outcome/rows.ts +102 -0
  41. package/apps/bridge/src/sessions/scan/codex/parse.ts +75 -9
  42. package/apps/bridge/src/sessions/scan/codex/scan.ts +15 -2
  43. package/apps/bridge/src/sessions/scan/codex/shared.ts +9 -0
  44. package/apps/bridge/src/sessions/scan/grok.ts +9 -2
  45. package/apps/bridge/src/sessions/support/common.ts +4 -0
  46. package/apps/bridge/src/started-by/README.md +94 -0
  47. package/apps/bridge/src/started-by/attach.ts +136 -0
  48. package/apps/bridge/src/started-by/capture.ts +186 -0
  49. package/apps/bridge/src/started-by/facts.ts +154 -0
  50. package/apps/bridge/src/started-by/headless.ts +146 -0
  51. package/apps/bridge/src/started-by/index.ts +7 -0
  52. package/apps/bridge/src/started-by/links.ts +175 -0
  53. package/apps/bridge/src/started-by/mesh/index.ts +106 -0
  54. package/apps/bridge/src/working-tree/README.md +38 -0
  55. package/apps/bridge/src/working-tree/commit.ts +47 -0
  56. package/apps/bridge/src/working-tree/index.ts +65 -0
  57. package/apps/bridge/src/working-tree/relay.ts +39 -0
  58. package/apps/bridge/src/working-tree/status.ts +64 -0
  59. package/cursor-plugin/README.md +1 -1
  60. package/cursor-plugin/mcp.json +1 -1
  61. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  62. package/package.json +1 -1
  63. package/packages/core/outbound-scheduler/README.md +7 -0
  64. package/packages/core/outbound-scheduler/index.ts +18 -2
  65. package/packages/protocol/messages/README.md +30 -0
  66. package/packages/protocol/messages/sessions/index.ts +51 -4
  67. package/packages/protocol/messages/sessions/working-tree.ts +62 -0
  68. package/packages/protocol/schema.ts +6 -0
package/README.md CHANGED
@@ -757,6 +757,61 @@ 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
+
788
+ ### Uncommitted changes of a chat, and committing them from the phone
789
+
790
+ A chat whose working folder is a Git checkout carries `workingTree { branch?, detached?, ahead?,
791
+ behind?, changed, operation?, observedAt }`, read at most every five seconds per folder. The phone asks
792
+ `session.changes.query` for up to 200 changed paths with Git's status letters and a `treeToken`, and
793
+ sends `session.commit { message ≤ 2000, paths, treeToken, confirmWhileWorking? }`; the computer commits
794
+ exactly those paths (`git add -A -- …`, `git commit -m … -- …`, hooks run, no push) or refuses with
795
+ `changed`, `detached`, `operation`, `working`, `unavailable` or `failed`. Both answers go only to the
796
+ phone that asked. See [working tree](apps/bridge/src/working-tree/README.md).
797
+
798
+ ### What a run's end says
799
+
800
+ A Codex turn that ends on Codex's own error instead of an answer says so: the chat's last message is
801
+ `Codex stopped: You’ve hit your usage limit.` (Codex's first sentence, without its links), its
802
+ transcript ends with that sentence, and the session carries `stopped { reason, message?, at }`
803
+ (`reason`: `usage_limit`, `rate_limit`, `context_window`, `sign_in`, `service`, `error`). A used-up
804
+ limit adds `usageLimit { resetsAt, autoContinue: false }`, read from Codex's "try again at …". An answer
805
+ Codex writes only in its newer `item_completed` or `task_complete` rows is shown like any other.
806
+
807
+ A headless run whose answer names a picture it saved inside its working folder shows `Picture saved:
808
+ <file name>` as its last message; the computer keeps a reduced copy and publishes it as the session's
809
+ `images` and on the answer that names it, readable with `session.image.query` by that chat and the chat
810
+ that started it. A Codex run nobody has asked anything yet is no chat and no Mesh Task until its request
811
+ appears, and Tasks an earlier runtime made for such chats (`codex task`, "Continue this coding task")
812
+ are left out of what the phone is sent. See [Codex outcomes](apps/bridge/src/sessions/scan/codex/README.md)
813
+ and [chat pictures](apps/bridge/src/helper-runs/README.md#pictures-a-chat-saved).
814
+
760
815
  ### One computer, whatever the network calls it
761
816
 
762
817
  The Mesh keys a computer by an identity written down once, on first use, in
@@ -1004,7 +1059,9 @@ See the [runtime watchdog](apps/bridge/src/runtime-watchdog/README.md).
1004
1059
 
1005
1060
  ## Automatic runtime updates
1006
1061
 
1007
- Installed GrantTap background services check for stable MCP updates automatically.
1062
+ Installed GrantTap background services check for stable MCP updates automatically, once an
1063
+ hour with one small registry request; a failed check is retried after 5, 10, 20 and 40 minutes,
1064
+ then hourly.
1008
1065
  Verified updates are staged separately and applied after active requests and pending
1009
1066
  decisions finish. Startup failures restore the previous version. Pairing and task
1010
1067
  policies are retained; source checkouts and running provider processes stay in place.
@@ -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,26 @@ 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
+ ### Pictures a chat saved
58
+
59
+ The same store keeps pictures a chat's own answer saved (`pictures/chats.ts`): today the final answer
60
+ of a Codex chat, typically a headless image run started by another chat (`startedBy`) that answers with
61
+ the path it saved. A picture is an image file (`.png`, `.jpg`, `.jpeg`, `.webp`) the answer names,
62
+ bare, in backticks, as a Markdown link or `file://` URL, absolute or relative to the chat's working
63
+ folder; it must lie inside that folder when both are read as real paths (a link out of it does not
64
+ count), be a regular file, and have been written since the turn began. A working folder that is `/`
65
+ or the home folder holds none. Only the monitor keeps them, one at a time and once per file size and
66
+ time, for answers seen in the last two days: the first 12 bytes must announce an image before the file
67
+ is read further, at most 48 MB is read, and the copy is reduced as above. They are kept under the chat
68
+ (`owner { agent, sessionId }` in `index.json`), at most 12 per chat, within the same store bounds.
69
+ The session carries them as `images`; the transcript puts each on the answer that names it, in place
70
+ of its path line. `session.image.query` answers the chat itself and the chat that started it, no other.
71
+ Other providers' scanners can pass hints the same way; Claude, Cursor and Grok do not yet.
72
+
73
+ A headless run that is a chat in its own right, such as `codex exec` in a folder
74
+ several runs share, is not a helper run: it stays a chat and names the chat that
75
+ started it in `startedBy` ([chats started by another chat](../started-by/README.md)).
76
+
57
77
  **Meshes.** A run is not passed to the Mesh, and a generator's folder never
58
78
  registers one. A Mesh without a remote whose folder is a generator's, is
59
79
  gone from the temp directory, or lies inside a Git checkout without being a
@@ -30,21 +30,24 @@ let attached = new Map<string, { session: SessionInfo; folder: string }>();
30
30
  type MessageImage = NonNullable<ActivityEntry["images"]>[number];
31
31
 
32
32
  /** The `/var` and `/private/var` spellings of a macOS temp path name one folder. */
33
- function samePath(text: string): string {
33
+ export function samePath(text: string): string {
34
34
  return text.replace(/\\/g, "/").replace(/^\/private\/(var|tmp)\//, "/$1/");
35
35
  }
36
36
 
37
37
  /**
38
38
  * A kept picture as a phone shows it. When a line of the message is the path
39
- * the run wrote the picture to, the picture takes that line's place.
39
+ * the picture was written to, the picture takes that line's place.
40
40
  */
41
- function pictureImage(folder: string, picture: RunPicture, text = ""): MessageImage {
42
- const id = helperRunImageId(folder, picture.hash);
41
+ export function pictureAttachment(id: string, picture: RunPicture, text = ""): MessageImage {
43
42
  const line = text.split("\n").map((item) => item.trim().replace(/^(?:[-*+] |\d+\. )/, ""))
44
43
  .find((item) => samePath(item.replace(/^`(.*)`$/, "$1")) === samePath(picture.source));
45
44
  return { id, name: picture.name, markdown: line && line.length <= 2_400 ? line : `![${picture.name}](granttap-image:${id})` };
46
45
  }
47
46
 
47
+ function pictureImage(folder: string, picture: RunPicture, text = ""): MessageImage {
48
+ return pictureAttachment(helperRunImageId(folder, picture.hash), picture, text);
49
+ }
50
+
48
51
  function childOf(parent: SessionInfo, run: HelperRunSession): ChildThreadInfo {
49
52
  const { session } = run;
50
53
  const images = helperRunPictures(run.folder).map((picture) => pictureImage(run.folder, picture));
@@ -25,7 +25,8 @@ import {
25
25
  const run = promisify(execFile);
26
26
 
27
27
  const PICTURE_NAME = /\.(?:png|jpe?g|webp)$/i;
28
- const MAX_SOURCE_BYTES = 48 * 1024 * 1024;
28
+ /** The largest picture file read at all; a bigger one is left alone. */
29
+ export const MAX_SOURCE_BYTES = 48 * 1024 * 1024;
29
30
  const MAX_ENTRIES = 200;
30
31
  const LOOK_EVERY_MS = 200;
31
32
  /** A picture this small is kept as it is. */
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Pictures a chat's own answer saved in its own working folder.
3
+ *
4
+ * A headless image run (`codex exec "… save the file, print the path"`) answers
5
+ * with the path of the picture it saved. Its scanner passes the answer here. A
6
+ * picture is an image file the answer names that lies inside the chat's working
7
+ * folder (both read as real paths, so a link out of the folder does not count),
8
+ * is a regular file, and was written since the turn began. A working folder that
9
+ * is the file system root or the home folder holds no such pictures.
10
+ *
11
+ * Only the monitor keeps them, one at a time: the file is read, recognised by
12
+ * its first bytes, reduced and kept like a helper run's picture, under the chat.
13
+ * Catalogs and transcripts only read what was kept.
14
+ */
15
+ import { closeSync, openSync, readFileSync, readSync, realpathSync, statSync } from "node:fs";
16
+ import { homedir } from "node:os";
17
+ import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
18
+ import type { KeptPicture, SessionActivity, SessionInfo } from "../../../../../packages/protocol/schema";
19
+ import { pictureAttachment, samePath } from "../attach";
20
+ import { MAX_SOURCE_BYTES, reducePicture, type Reducer } from "./capture";
21
+ import {
22
+ chatPictureImageId, chatPictureLookup, chatPictures, keepHelperRunPicture, pictureComplete, pictureHash, pictureMime,
23
+ type PictureOwner,
24
+ } from "./store";
25
+
26
+ /** A picture as an answer names it: where it is, and the spelling the answer used. */
27
+ export type NamedPicture = { path: string; source: string };
28
+ /** What a scanner found in one chat's newest answer; never published. */
29
+ export type ChatPictureHint = PictureOwner & { cwd: string; at: number; pictures: NamedPicture[] };
30
+
31
+ const IMAGE_NAME = /\.(?:png|jpe?g|webp)$/i;
32
+ const MAX_NAMED = 12;
33
+ /** A file written this long before the turn's first row was still written by it. */
34
+ const CLOCK_SLACK_MS = 2_000;
35
+ /** Answers older than this are not looked at again for pictures. */
36
+ const RECENT_MS = 48 * 60 * 60_000;
37
+ const MAX_TRIED = 4_096;
38
+
39
+ /** Every different image path an answer spells: bare, in backticks, as a Markdown link target. */
40
+ function namedPaths(answer: string): string[] {
41
+ const out: string[] = [];
42
+ for (const raw of answer.split(/[\s`'"<>()[\]]+/)) {
43
+ let token = raw.replace(/^[*_]+/, "").replace(/[.,;:!?*_]+$/, "");
44
+ if (token.startsWith("file://")) {
45
+ try { token = decodeURIComponent(token.slice("file://".length)); } catch { continue; }
46
+ }
47
+ if (!token || token.length > 1_024 || !IMAGE_NAME.test(token) || /[\u0000-\u001f]/.test(token)) continue;
48
+ if (!out.includes(token)) out.push(token);
49
+ if (out.length >= MAX_NAMED) break;
50
+ }
51
+ return out;
52
+ }
53
+
54
+ /** The real path of a regular file inside the folder, and never the folder itself. */
55
+ function insideFolder(path: string, folder: string): string | undefined {
56
+ try {
57
+ const root = realpathSync(folder), real = realpathSync(path);
58
+ const child = relative(root, real);
59
+ if (!child || child === ".." || child.startsWith(`..${sep}`) || isAbsolute(child)) return undefined;
60
+ return statSync(real).isFile() ? real : undefined;
61
+ } catch {
62
+ return undefined;
63
+ }
64
+ }
65
+
66
+ /** A folder that is the whole disk or the whole home folder is not a chat's own working folder here. */
67
+ function ownWorkingFolder(folder: string, home: string): boolean {
68
+ try {
69
+ const real = realpathSync(folder);
70
+ return real !== sep && real !== realpathSync(home);
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+
76
+ /** The pictures an answer names that the turn saved inside its working folder. */
77
+ export function savedPictures(answer: string | undefined, cwd: string | undefined, since: number,
78
+ home = homedir()): NamedPicture[] {
79
+ if (!answer || !cwd || !isAbsolute(cwd) || !ownWorkingFolder(cwd, home)) return [];
80
+ const found: NamedPicture[] = [];
81
+ const seen = new Set<string>();
82
+ for (const source of namedPaths(answer)) {
83
+ const path = source.startsWith("~/") ? join(home, source.slice(2)) : isAbsolute(source) ? source : resolve(cwd, source);
84
+ const real = insideFolder(path, cwd);
85
+ if (!real || seen.has(real)) continue;
86
+ try { if (statSync(real).mtimeMs < since - CLOCK_SLACK_MS) continue; } catch { continue; }
87
+ seen.add(real);
88
+ found.push({ path, source });
89
+ }
90
+ return found;
91
+ }
92
+
93
+ /** What a phone that does not read `images` sees as the chat's newest message. */
94
+ export function pictureSavedText(pictures: readonly { path: string }[], generated?: string): string | undefined {
95
+ const names = [...new Set(pictures.map((picture) => basename(picture.path)))];
96
+ if (names.length === 0 && generated) names.push(generated);
97
+ if (names.length === 0) return undefined;
98
+ return `Picture saved: ${names.slice(0, 3).join(", ")}${names.length > 3 ? ` and ${names.length - 3} more` : ""}`;
99
+ }
100
+
101
+ let noted: readonly ChatPictureHint[] = [];
102
+ const tried = new Set<string>();
103
+ let queue: Promise<unknown> = Promise.resolve();
104
+
105
+ /** The newest catalog's hints, for the monitor to keep; other processes only note them. */
106
+ export function noteChatPictureHints(hints: readonly ChatPictureHint[]): void {
107
+ noted = hints;
108
+ }
109
+
110
+ /** The first bytes alone: a file that does not start as a picture is read no further. */
111
+ function header(path: string): Uint8Array {
112
+ const fd = openSync(path, "r");
113
+ try {
114
+ const bytes = Buffer.alloc(12);
115
+ return bytes.subarray(0, readSync(fd, bytes, 0, 12, 0));
116
+ } finally {
117
+ closeSync(fd);
118
+ }
119
+ }
120
+
121
+ type KeepOptions = { reduce?: Reducer; keep?: typeof keepHelperRunPicture; now?: () => number };
122
+
123
+ async function keepOne(hint: ChatPictureHint, picture: NamedPicture, options: Required<KeepOptions>): Promise<void> {
124
+ const real = insideFolder(picture.path, hint.cwd);
125
+ if (!real) return;
126
+ const stat = statSync(real);
127
+ if (stat.size === 0 || stat.size > MAX_SOURCE_BYTES || !pictureMime(header(real))) return;
128
+ const bytes = readFileSync(real);
129
+ const mime = pictureMime(bytes.subarray(0, 12));
130
+ if (!mime || !pictureComplete(bytes, mime)) return;
131
+ const owner: PictureOwner = { agent: hint.agent, sessionId: hint.sessionId };
132
+ const hash = pictureHash(bytes);
133
+ if (chatPictures(owner).some((item) => item.hash === hash)) return;
134
+ const reduced = await options.reduce(bytes, mime);
135
+ if (!reduced) return;
136
+ options.keep(hint.cwd, { hash, name: basename(real).slice(0, 256), source: picture.source, mime: reduced.mime,
137
+ capturedAt: options.now() }, reduced.bytes, options.now(), owner);
138
+ }
139
+
140
+ /**
141
+ * Keep each picture the noted answers saved that is not kept yet, one at a time. A file is tried
142
+ * once in each size and modification time it has. Resolves when this pass is done.
143
+ */
144
+ export function keepNotedChatPictures(options: KeepOptions = {}): Promise<unknown> {
145
+ const settings = { reduce: options.reduce ?? reducePicture, keep: options.keep ?? keepHelperRunPicture,
146
+ now: options.now ?? Date.now };
147
+ const now = settings.now();
148
+ for (const hint of noted) {
149
+ if (hint.at < now - RECENT_MS) continue;
150
+ for (const picture of hint.pictures) {
151
+ let key: string;
152
+ try {
153
+ const stat = statSync(picture.path);
154
+ key = `${hint.agent}\0${hint.sessionId}\0${picture.path}\0${stat.size}\0${stat.mtimeMs}`;
155
+ } catch { continue; }
156
+ if (tried.has(key)) continue;
157
+ if (tried.size >= MAX_TRIED) tried.clear();
158
+ tried.add(key);
159
+ queue = queue.then(() => keepOne(hint, picture, settings)).catch(() => undefined);
160
+ }
161
+ }
162
+ return queue;
163
+ }
164
+
165
+ /** For tests: forget what was noted and tried. */
166
+ export function forgetChatPictures(): void {
167
+ noted = [];
168
+ tried.clear();
169
+ }
170
+
171
+ function kept(owner: PictureOwner, lookup: (owner: PictureOwner) => ReturnType<typeof chatPictures>, text = ""): KeptPicture[] {
172
+ return lookup(owner).slice(-12).map((picture) => pictureAttachment(chatPictureImageId(owner, picture.hash), picture, text));
173
+ }
174
+
175
+ /** Each chat with the pictures kept from its own answers. */
176
+ export function attachChatPictures(sessions: SessionInfo[]): SessionInfo[] {
177
+ const lookup = chatPictureLookup();
178
+ return sessions.map((session) => {
179
+ const images = kept({ agent: session.agent as PictureOwner["agent"], sessionId: session.sessionId }, lookup);
180
+ return images.length > 0 ? { ...session, images } : session;
181
+ });
182
+ }
183
+
184
+ /**
185
+ * A chat's own kept pictures on the answers that name them. A page without such an answer, or an
186
+ * agent conversation of the chat, is left as it is.
187
+ */
188
+ export function withChatPictures(activity: SessionActivity, session: SessionInfo | undefined): SessionActivity {
189
+ if (!session || activity.threadId || session.sessionId !== activity.sessionId) return activity;
190
+ const owner: PictureOwner = { agent: session.agent as PictureOwner["agent"], sessionId: session.sessionId };
191
+ const pictures = chatPictures(owner);
192
+ if (pictures.length === 0) return activity;
193
+ const entries = [...activity.entries];
194
+ for (const picture of pictures) {
195
+ const id = chatPictureImageId(owner, picture.hash);
196
+ if (entries.some((entry) => entry.images?.some((image) => image.id === id))) continue;
197
+ const source = samePath(picture.source);
198
+ const at = entries.map((entry, index) => ["final", "message"].includes(entry.kind) && !entry.childThreadId
199
+ && namedPaths(entry.text).some((token) => samePath(token) === source) ? index : -1)
200
+ .filter((index) => index >= 0).at(-1);
201
+ if (at === undefined) continue;
202
+ const entry = entries[at]!;
203
+ entries[at] = { ...entry, images: [...(entry.images ?? []), ...kept(owner, () => [picture], entry.text)].slice(0, 32) };
204
+ }
205
+ return { ...activity, entries };
206
+ }
@@ -1,10 +1,12 @@
1
1
  /**
2
- * The pictures kept from helper runs, after the runs' folders are gone.
2
+ * The pictures kept from helper runs, after the runs' folders are gone, and the
3
+ * pictures a chat's own answer saved in its working folder.
3
4
  *
4
5
  * Each picture a run made is kept once, reduced, under the config directory,
5
6
  * next to one index that says which run made it and where the run wrote it.
6
- * A picture is offered only to the chat that started its run, by an id that
7
- * names the run and the picture's content and never a path.
7
+ * A helper run's picture is offered only to the chat that started its run; a
8
+ * chat's own picture to that chat and to the chat that started it. The id names
9
+ * the run or chat and the picture's content, never a path.
8
10
  */
9
11
  import { createHash } from "node:crypto";
10
12
  import { closeSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, statSync } from "node:fs";
@@ -12,8 +14,14 @@ import { join } from "node:path";
12
14
  import { writePrivateFile } from "../../config/access/write-private";
13
15
  import { configDir } from "../../config/runtime/paths";
14
16
  import { HISTORY_RETENTION_MS } from "../../sessions/support/common";
17
+ import { startedByLink } from "../../started-by/links";
15
18
  import { helperRunLink, type HelperRunLink } from "../links";
16
19
 
20
+ /** A chat whose own answer saved the pictures, as its provider names it. */
21
+ export type PictureOwner = { agent: "claude" | "codex" | "cursor" | "grok"; sessionId: string };
22
+ /** The chat that started an owner's chat, when one is known. */
23
+ export type ParentOf = (owner: PictureOwner) => { sessionId: string } | undefined;
24
+
17
25
  export type PictureMime = "image/png" | "image/jpeg" | "image/webp";
18
26
 
19
27
  export type RunPicture = {
@@ -29,8 +37,11 @@ export type RunPicture = {
29
37
  capturedAt: number;
30
38
  };
31
39
 
32
- type StoredRun = { folder: string; pictures: RunPicture[] };
40
+ /** A helper run, by its folder; or a chat, by `owner`, with the folder it works in. */
41
+ type StoredRun = { folder: string; owner?: PictureOwner; pictures: RunPicture[] };
33
42
  type Index = Map<string, StoredRun>;
43
+ const AGENTS = new Set(["claude", "codex", "cursor", "grok"]);
44
+ const SESSION_ID = /^[A-Za-z0-9._-]{8,128}$/;
34
45
 
35
46
  export const MAX_KEPT_BYTES = 8 * 1024 * 1024;
36
47
  const MAX_PICTURES_PER_RUN = 12;
@@ -53,6 +64,22 @@ export function runKey(folder: string): string {
53
64
  return createHash("sha256").update(folder).digest("hex").slice(0, 24);
54
65
  }
55
66
 
67
+ /** A chat's own pictures are keyed by the chat; a folder path never starts this way. */
68
+ function ownerKey(owner: PictureOwner): string {
69
+ return runKey(`chat:${owner.agent}:${owner.sessionId}`);
70
+ }
71
+
72
+ function storedKey(run: Pick<StoredRun, "folder" | "owner">): string {
73
+ return run.owner ? ownerKey(run.owner) : runKey(run.folder);
74
+ }
75
+
76
+ function validOwner(value: unknown): PictureOwner | undefined {
77
+ const owner = value as Record<string, unknown> | undefined;
78
+ return owner && typeof owner.agent === "string" && AGENTS.has(owner.agent)
79
+ && typeof owner.sessionId === "string" && SESSION_ID.test(owner.sessionId)
80
+ ? { agent: owner.agent as PictureOwner["agent"], sessionId: owner.sessionId } : undefined;
81
+ }
82
+
56
83
  export function pictureHash(bytes: Uint8Array): string {
57
84
  return createHash("sha256").update(bytes).digest("hex").slice(0, 24);
58
85
  }
@@ -65,6 +92,10 @@ export function helperRunImageId(folder: string, hash: string): string {
65
92
  return `helper-image:${runKey(folder)}:${hash}`;
66
93
  }
67
94
 
95
+ export function chatPictureImageId(owner: PictureOwner, hash: string): string {
96
+ return `helper-image:${ownerKey(owner)}:${hash}`;
97
+ }
98
+
68
99
  export function isHelperRunImageId(id: string): boolean {
69
100
  return id.startsWith("helper-image:");
70
101
  }
@@ -113,9 +144,12 @@ function parseIndex(text: string): Index {
113
144
  if (!value || typeof value !== "object") continue;
114
145
  const run = value as Record<string, unknown>;
115
146
  if (typeof run.folder !== "string" || !run.folder || run.folder.length > 1_024) continue;
147
+ const owner = run.owner === undefined ? undefined : validOwner(run.owner);
148
+ if (run.owner !== undefined && !owner) continue;
116
149
  const pictures = (Array.isArray(run.pictures) ? run.pictures : []).map(validPicture)
117
150
  .filter((item): item is RunPicture => item !== undefined).slice(0, MAX_PICTURES_PER_RUN);
118
- if (pictures.length > 0) index.set(runKey(run.folder), { folder: run.folder, pictures });
151
+ const stored = { folder: run.folder, ...(owner ? { owner } : {}), pictures };
152
+ if (pictures.length > 0) index.set(storedKey(stored), stored);
119
153
  }
120
154
  return index;
121
155
  }
@@ -147,6 +181,17 @@ export function hasHelperRunPicture(folder: string, hash: string): boolean {
147
181
  return helperRunPictures(folder).some((picture) => picture.hash === hash);
148
182
  }
149
183
 
184
+ /** The pictures kept from a chat's own answers, oldest first. */
185
+ export function chatPictures(owner: PictureOwner): RunPicture[] {
186
+ return readIndex().get(ownerKey(owner))?.pictures ?? [];
187
+ }
188
+
189
+ /** The same for many chats from one reading of the index; a catalog asks about every chat. */
190
+ export function chatPictureLookup(): (owner: PictureOwner) => RunPicture[] {
191
+ const index = readIndex();
192
+ return (owner) => index.size === 0 ? [] : index.get(ownerKey(owner))?.pictures ?? [];
193
+ }
194
+
150
195
  /** Drop runs older than history, then the oldest, until the store is within its bounds. */
151
196
  function bounded(index: Index, now: number): { kept: Index; dropped: string[] } {
152
197
  const runs = [...index.entries()].sort((left, right) =>
@@ -167,37 +212,50 @@ function bounded(index: Index, now: number): { kept: Index; dropped: string[] }
167
212
  return { kept: new Map(runs), dropped };
168
213
  }
169
214
 
170
- /** Keep one reduced picture from the run in this folder. Returns whether it was new. */
215
+ /**
216
+ * Keep one reduced picture from the run in this folder, or with `owner` from that chat's own
217
+ * answer in the folder it works in. Returns whether it was new.
218
+ */
171
219
  export function keepHelperRunPicture(folder: string, picture: Omit<RunPicture, "bytes">,
172
- bytes: Uint8Array, now = Date.now()): boolean {
220
+ bytes: Uint8Array, now = Date.now(), owner?: PictureOwner): boolean {
173
221
  if (!HASH.test(picture.hash) || bytes.length === 0 || bytes.length > MAX_KEPT_BYTES) return false;
174
222
  if (pictureMime(bytes.subarray(0, 12)) !== picture.mime) return false;
223
+ if (owner && !validOwner(owner)) return false;
175
224
  let index: Index = new Map();
176
225
  try { index = parseIndex(readFileSync(indexPath(), "utf8")); } catch { /* Nothing kept yet. */ }
177
- const key = runKey(folder);
178
- const run = index.get(key) ?? { folder, pictures: [] };
226
+ const key = storedKey({ folder, owner });
227
+ const run = index.get(key) ?? { folder, ...(owner ? { owner } : {}), pictures: [] };
179
228
  if (run.pictures.some((item) => item.hash === picture.hash) || run.pictures.length >= MAX_PICTURES_PER_RUN) return false;
180
229
  mkdirSync(picturesDirectory(), { recursive: true, mode: 0o700 });
181
230
  const kept: RunPicture = { ...picture, bytes: bytes.length };
182
231
  writePrivateFile(keptFile(key, kept), bytes);
183
- index.set(key, { folder, pictures: [...run.pictures, kept] });
232
+ index.set(key, { ...run, pictures: [...run.pictures, kept] });
184
233
  const { kept: stored, dropped } = bounded(index, now);
185
- writePrivateFile(indexPath(), JSON.stringify({ version: 1,
186
- runs: [...stored.values()].map((item) => ({ folder: item.folder, pictures: item.pictures })) }));
234
+ writePrivateFile(indexPath(), JSON.stringify({ version: 1, runs: [...stored.values()].map((item) =>
235
+ ({ folder: item.folder, ...(item.owner ? { owner: item.owner } : {}), pictures: item.pictures })) }));
187
236
  for (const file of dropped) rmSync(file, { force: true });
188
237
  cached = undefined;
189
238
  return stored.get(key)?.pictures.some((item) => item.hash === picture.hash) === true;
190
239
  }
191
240
 
192
- /** Read one bounded chunk of a kept picture for the chat that started its run, and for no other. */
241
+ const startedByParent: ParentOf = (owner) => startedByLink(owner)?.parent;
242
+
243
+ /** The chat that started a helper run may read its pictures; a chat's own, that chat and the one that started it. */
244
+ function mayRead(run: StoredRun, chatId: string, link: (folder: string) => HelperRunLink | undefined,
245
+ parentOf: ParentOf): boolean {
246
+ if (!run.owner) return link(run.folder)?.parentSessionId === chatId;
247
+ return run.owner.sessionId === chatId || parentOf(run.owner)?.sessionId === chatId;
248
+ }
249
+
250
+ /** Read one bounded chunk of a kept picture for a chat allowed to see it, and for no other. */
193
251
  export function helperRunPictureChunk(chatId: string, imageId: string, offset: number,
194
- link: (folder: string) => HelperRunLink | undefined = helperRunLink) {
252
+ link: (folder: string) => HelperRunLink | undefined = helperRunLink, parentOf: ParentOf = startedByParent) {
195
253
  const match = IMAGE_ID.exec(imageId);
196
254
  if (!match || !Number.isSafeInteger(offset) || offset < 0) return undefined;
197
255
  const [, key, hash] = match as unknown as [string, string, string];
198
256
  const run = readIndex().get(key);
199
257
  const picture = run?.pictures.find((item) => item.hash === hash);
200
- if (!run || !picture || link(run.folder)?.parentSessionId !== chatId) return undefined;
258
+ if (!run || !picture || !mayRead(run, chatId, link, parentOf)) return undefined;
201
259
  let fd: number | undefined;
202
260
  try {
203
261
  fd = openSync(keptFile(key, picture), "r");
@@ -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.