granttap-mcp 0.8.189 → 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 (45) hide show
  1. package/README.md +30 -1
  2. package/apps/bridge/src/helper-runs/README.md +16 -0
  3. package/apps/bridge/src/helper-runs/attach.ts +7 -4
  4. package/apps/bridge/src/helper-runs/pictures/capture.ts +2 -1
  5. package/apps/bridge/src/helper-runs/pictures/chats.ts +206 -0
  6. package/apps/bridge/src/helper-runs/pictures/store.ts +73 -15
  7. package/apps/bridge/src/limit-continuation/README.md +4 -0
  8. package/apps/bridge/src/limit-continuation/index.ts +6 -3
  9. package/apps/bridge/src/mesh/catalog/index.ts +19 -4
  10. package/apps/bridge/src/mesh/runtime/graph/analysis.ts +2 -1
  11. package/apps/bridge/src/mesh/snapshot/window.ts +13 -1
  12. package/apps/bridge/src/monitor/handlers/catalog.ts +1 -1
  13. package/apps/bridge/src/monitor/handlers/inbound.ts +5 -0
  14. package/apps/bridge/src/monitor/support/runtime.ts +4 -1
  15. package/apps/bridge/src/runtime-updates/README.md +5 -2
  16. package/apps/bridge/src/runtime-updates/index.ts +25 -9
  17. package/apps/bridge/src/session-catalog/README.md +9 -0
  18. package/apps/bridge/src/session-catalog/observed-state.ts +8 -1
  19. package/apps/bridge/src/session-catalog/publish-heads.ts +3 -1
  20. package/apps/bridge/src/session-catalog/started-children.ts +36 -0
  21. package/apps/bridge/src/session-images/index.ts +5 -3
  22. package/apps/bridge/src/sessions/catalog.ts +8 -4
  23. package/apps/bridge/src/sessions/scan/codex/README.md +33 -1
  24. package/apps/bridge/src/sessions/scan/codex/activity/rows.ts +23 -8
  25. package/apps/bridge/src/sessions/scan/codex/outcome/index.ts +161 -0
  26. package/apps/bridge/src/sessions/scan/codex/outcome/rows.ts +102 -0
  27. package/apps/bridge/src/sessions/scan/codex/parse.ts +40 -4
  28. package/apps/bridge/src/sessions/scan/codex/scan.ts +14 -2
  29. package/apps/bridge/src/sessions/scan/codex/shared.ts +6 -0
  30. package/apps/bridge/src/sessions/support/common.ts +2 -0
  31. package/apps/bridge/src/working-tree/README.md +38 -0
  32. package/apps/bridge/src/working-tree/commit.ts +47 -0
  33. package/apps/bridge/src/working-tree/index.ts +65 -0
  34. package/apps/bridge/src/working-tree/relay.ts +39 -0
  35. package/apps/bridge/src/working-tree/status.ts +64 -0
  36. package/cursor-plugin/README.md +1 -1
  37. package/cursor-plugin/mcp.json +1 -1
  38. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  39. package/package.json +1 -1
  40. package/packages/core/outbound-scheduler/README.md +7 -0
  41. package/packages/core/outbound-scheduler/index.ts +18 -2
  42. package/packages/protocol/messages/README.md +23 -0
  43. package/packages/protocol/messages/sessions/index.ts +39 -4
  44. package/packages/protocol/messages/sessions/working-tree.ts +62 -0
  45. package/packages/protocol/schema.ts +6 -0
package/README.md CHANGED
@@ -785,6 +785,33 @@ temp folder, a plain folder or one of its parent's checkout is in its parent's
785
785
  Mesh and registers no Mesh of its own; one in a checkout of its own keeps that
786
786
  checkout's. Details: [`apps/bridge/src/started-by`](apps/bridge/src/started-by/README.md).
787
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
+
788
815
  ### One computer, whatever the network calls it
789
816
 
790
817
  The Mesh keys a computer by an identity written down once, on first use, in
@@ -1032,7 +1059,9 @@ See the [runtime watchdog](apps/bridge/src/runtime-watchdog/README.md).
1032
1059
 
1033
1060
  ## Automatic runtime updates
1034
1061
 
1035
- 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.
1036
1065
  Verified updates are staged separately and applied after active requests and pending
1037
1066
  decisions finish. Startup failures restore the previous version. Pairing and task
1038
1067
  policies are retained; source checkouts and running provider processes stay in place.
@@ -54,6 +54,22 @@ 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
+
57
73
  A headless run that is a chat in its own right, such as `codex exec` in a folder
58
74
  several runs share, is not a helper run: it stays a chat and names the chat that
59
75
  started it in `startedBy` ([chats started by another chat](../started-by/README.md)).
@@ -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");
@@ -17,6 +17,10 @@ and missing readings never go early. The early continuation is tried once per ch
17
17
  The one due at the reset stays queued until the chat goes on; a chat refused again for the same
18
18
  reset keeps it and gets no second early try.
19
19
 
20
+ Only Claude chats are continued. A Codex chat stopped by its usage limit carries `usageLimit
21
+ { resetsAt, autoContinue: false }` (`resetsAt` from Codex's "try again at …"), so the phone says
22
+ "Limit reached" and when it resets; nothing is queued for it.
23
+
20
24
  The phone turns it off or on per chat with `session.autocontinue.set`. It is on by default.
21
25
  Turning it off takes the queued copies back from the relay. A copy the relay still offers afterwards
22
26
  is refused at delivery. The same happens when the chat went on by itself first. A limit that reset
@@ -37,12 +37,15 @@ export function setAutoContinue(sessionId: string, enabled: boolean): void {
37
37
  writeLimitContinuationState(state);
38
38
  }
39
39
 
40
- /** The phone shows whether a limited chat will go on by itself; that is the default. */
40
+ /**
41
+ * The phone shows whether a limited chat will go on by itself; that is the default for Claude. Only
42
+ * Claude chats are continued (`wanted`), so another agent's limited chat says it will not be.
43
+ */
41
44
  export function annotateLimitContinuations(sessions: SessionInfo[]): SessionInfo[] {
42
45
  if (!sessions.some(session => session.usageLimit)) return sessions;
43
46
  const off = new Set(readLimitContinuationState().off);
44
- return sessions.map(session => session.usageLimit
45
- ? { ...session, usageLimit: { ...session.usageLimit, autoContinue: !off.has(session.sessionId) } } : session);
47
+ return sessions.map(session => session.usageLimit ? { ...session, usageLimit: { ...session.usageLimit,
48
+ autoContinue: session.agent === 'claude' && !off.has(session.sessionId) } } : session);
46
49
  }
47
50
 
48
51
  /**
@@ -117,9 +117,25 @@ export function meshTaskTitle(session: SessionInfo, agent: string): string {
117
117
  return (opening ?? `${agent} task`).slice(0, 160);
118
118
  }
119
119
 
120
+ /**
121
+ * A chat with no request and no answer yet names no Task: it is not linked until one appears.
122
+ * Earlier runtimes made such Tasks anyway; snapshots leave them out (`requestlessTask`).
123
+ */
124
+ export function hasTaskSubject(session: SessionInfo): boolean {
125
+ return Boolean(presentableTitle(session.title) || session.summary?.trim());
126
+ }
127
+
128
+ /** The chat's newest message, else its request; `hasTaskSubject` holds, so one of them has words. */
129
+ function taskGoal(session: SessionInfo): string {
130
+ const goal = session.summary?.trim() ? session.summary : presentableTitle(session.title) ? session.title : undefined;
131
+ return (goal ?? "").slice(0, 1_000);
132
+ }
133
+
120
134
  function taskState(session: SessionInfo): TaskState {
121
135
  if (session.state === "waiting") return "needs_user";
122
136
  if (session.state === "working") return "working";
137
+ // Its turn ended on the provider's error (a used-up limit): nothing goes on until something changes.
138
+ if (session.stopped) return "blocked";
123
139
  return "planned";
124
140
  }
125
141
 
@@ -186,7 +202,7 @@ function linkSession(input: LinkInput): SessionInfo {
186
202
  const agent = provider(session.agent);
187
203
  const cwd = session.cwd?.trim();
188
204
  // A generator's throwaway folder is not a workspace: registering it minted a Mesh per run.
189
- if (!agent || !cwd || helperRunFolder(cwd)) return session;
205
+ if (!agent || !cwd || helperRunFolder(cwd) || !hasTaskSubject(session)) return session;
190
206
  const knownTaskId = store.taskForExecution(computerId, agent, session.sessionId);
191
207
  const knownProjectId = knownTaskId ? store.task(knownTaskId)?.projectId : undefined;
192
208
  const previous = knownProjectId ? store.snapshot(knownProjectId)?.executions.find(row =>
@@ -221,7 +237,7 @@ function linkSession(input: LinkInput): SessionInfo {
221
237
  taskId,
222
238
  projectId,
223
239
  title: meshTaskTitle(session, agent),
224
- goal: (session.summary ?? session.title ?? "Continue this coding task").slice(0, 1_000),
240
+ goal: taskGoal(session),
225
241
  state: taskState(session),
226
242
  ownerSessionId: session.sessionId,
227
243
  createdAt: session.startedAt,
@@ -260,8 +276,7 @@ function linkStartedChild(input: LinkInput, agent: MeshProvider, cwd: string, kn
260
276
  // A Task an older runtime made in a Mesh of the child's own folder stays there; the chat moves on.
261
277
  const taskId = known?.projectId === parent.projectId ? known.taskId : taskIdentity(parent.projectId, agent, session.sessionId);
262
278
  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),
279
+ taskId, projectId: parent.projectId, title: meshTaskTitle(session, agent), goal: taskGoal(session),
265
280
  state: taskState(session), ownerSessionId: session.sessionId, createdAt: session.startedAt, updatedAt: session.lastActivityAt,
266
281
  });
267
282
  store.linkExecution({
@@ -35,7 +35,8 @@ const graphAnalysisDependencies: GraphAnalysisDependencies = {
35
35
  endpoint: computerId,
36
36
  details: snapshot => repositoryDetails(snapshot, computerId()),
37
37
  send: (client, snapshot) => sendMeshPayload(client, snapshot, "phone", {
38
- ttlMs: 60_000, reliable: true,
38
+ // The phone's Graph spinner waits for this answer; it goes ahead of bulk catalog and Mesh refreshes.
39
+ ttlMs: 60_000, reliable: true, urgent: true,
39
40
  }),
40
41
  };
41
42
 
@@ -6,12 +6,24 @@ import {
6
6
  import { isTerminalTaskState } from "../admin/convergence";
7
7
 
8
8
  const MAX_SNAPSHOT_TASKS = 64;
9
+ /** The goal earlier runtimes gave a Task whose chat had neither a request nor an answer. */
10
+ const NO_GOAL = "Continue this coding task";
11
+ const NO_TITLE = /^(?:claude|codex|cursor|grok) task$/;
12
+
13
+ /**
14
+ * A Task an earlier runtime made for a chat nobody had asked anything: titled `<agent> task`, with
15
+ * that goal. Today such a chat names no Task, so the leftover is kept in the store and shown nowhere.
16
+ */
17
+ export function requestlessTask(task: Pick<TaskValue, "title" | "goal">): boolean {
18
+ return task.goal === NO_GOAL && NO_TITLE.test(task.title);
19
+ }
9
20
 
10
21
  /** Keep the newest window, plus older work that is still live. */
11
- export function selectSnapshotTasks(all: TaskValue[]): {
22
+ export function selectSnapshotTasks(listed: TaskValue[]): {
12
23
  tasks: TaskValue[];
13
24
  incomplete: boolean;
14
25
  } {
26
+ const all = listed.filter((task) => !requestlessTask(task));
15
27
  const ordered = [...all].sort((left, right) =>
16
28
  left.updatedAt - right.updatedAt || left.taskId.localeCompare(right.taskId));
17
29
  const recent = ordered.slice(-MAX_SNAPSHOT_TASKS);
@@ -90,7 +90,7 @@ async function sendTranscript(
90
90
  const activity = threadId ? scanThreadActivity(session, threadId)
91
91
  : (history?.history ? readTranscriptHistory(session, history.historyCursor) : undefined)
92
92
  ?? cachedSessionActivity(session, false, observation?.revision);
93
- await sendSessionPayload(client, activityWithImages(activity), sessionId, "phone", {
93
+ await sendSessionPayload(client, activityWithImages(activity, session), sessionId, "phone", {
94
94
  ttlMs: INTERVAL_MS * 24,
95
95
  reliable: false,
96
96
  peerPublicKey: history?.peerPublicKey,
@@ -37,6 +37,7 @@ import {
37
37
  import { handleTaskCreate } from "./task-create";
38
38
  import { handleInboundUserMessage } from "../message-delivery";
39
39
  import { publishSessionEvents } from "./catalog";
40
+ import { handleWorkingTreeRequest } from "../../working-tree/relay";
40
41
  import { publishSessionImage } from '../../session-images';
41
42
  import { publishTaskWorkspace } from '../../task-files/relay';
42
43
  import { publishHistoryPage } from "../history/pages";
@@ -95,6 +96,10 @@ export async function handleMonitorMessage(
95
96
  return handleInboundSubscription(client, payload, subscriptions, publish, input.peerPublicKey);
96
97
  } else if (payload.type === "session.events" || payload.type === "session.image.query" || payload.type === "session.workspace.query") {
97
98
  return handleSessionRead(client, payload, input.peerPublicKey);
99
+ } else if (payload.type === "session.changes.query" || payload.type === "session.commit") {
100
+ const answered = await handleWorkingTreeRequest(client, payload, input.peerPublicKey);
101
+ if (payload.type === "session.commit") void publish().catch(() => {});
102
+ return answered;
98
103
  } else if (payload.type === "sessions.refresh") {
99
104
  return handleInboundRefresh(client, payload, publish, input.peerPublicKey);
100
105
  } else if (payload.type === "sessions.history.query") {