granttap-mcp 0.8.189 → 0.8.191

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 (80) hide show
  1. package/README.md +34 -3
  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/kinds.ts +1 -1
  5. package/apps/bridge/src/helper-runs/pictures/capture.ts +2 -1
  6. package/apps/bridge/src/helper-runs/pictures/chats.ts +206 -0
  7. package/apps/bridge/src/helper-runs/pictures/store.ts +73 -15
  8. package/apps/bridge/src/limit-continuation/README.md +4 -0
  9. package/apps/bridge/src/limit-continuation/index.ts +6 -3
  10. package/apps/bridge/src/machine-load/README.md +3 -0
  11. package/apps/bridge/src/machine-load/host/process-sampler.ts +11 -0
  12. package/apps/bridge/src/mesh/catalog/index.ts +19 -4
  13. package/apps/bridge/src/mesh/runtime/graph/analysis.ts +2 -1
  14. package/apps/bridge/src/mesh/snapshot/window.ts +13 -1
  15. package/apps/bridge/src/monitor/handlers/catalog.ts +1 -1
  16. package/apps/bridge/src/monitor/handlers/inbound.ts +5 -0
  17. package/apps/bridge/src/monitor/support/runtime.ts +15 -5
  18. package/apps/bridge/src/paired-phones/README.md +4 -0
  19. package/apps/bridge/src/paired-phones/index.ts +2 -2
  20. package/apps/bridge/src/paired-phones/roster.ts +22 -0
  21. package/apps/bridge/src/reply/README.md +13 -0
  22. package/apps/bridge/src/reply/in-flight.ts +10 -4
  23. package/apps/bridge/src/reply/process/index.ts +9 -2
  24. package/apps/bridge/src/reply/run-watch.ts +176 -0
  25. package/apps/bridge/src/reply/survival/README.md +2 -1
  26. package/apps/bridge/src/runtime-updates/README.md +7 -2
  27. package/apps/bridge/src/runtime-updates/index.ts +25 -9
  28. package/apps/bridge/src/session-catalog/README.md +9 -0
  29. package/apps/bridge/src/session-catalog/observed-state.ts +8 -1
  30. package/apps/bridge/src/session-catalog/publish-heads.ts +3 -1
  31. package/apps/bridge/src/session-catalog/started-children.ts +36 -0
  32. package/apps/bridge/src/session-images/index.ts +5 -3
  33. package/apps/bridge/src/sessions/catalog.ts +8 -4
  34. package/apps/bridge/src/sessions/scan/claude/parse.ts +4 -3
  35. package/apps/bridge/src/sessions/scan/codex/README.md +33 -1
  36. package/apps/bridge/src/sessions/scan/codex/activity/rows.ts +23 -8
  37. package/apps/bridge/src/sessions/scan/codex/outcome/index.ts +161 -0
  38. package/apps/bridge/src/sessions/scan/codex/outcome/rows.ts +102 -0
  39. package/apps/bridge/src/sessions/scan/codex/parse.ts +42 -5
  40. package/apps/bridge/src/sessions/scan/codex/scan.ts +14 -2
  41. package/apps/bridge/src/sessions/scan/codex/shared.ts +6 -0
  42. package/apps/bridge/src/sessions/support/common.ts +2 -0
  43. package/apps/bridge/src/started-by/README.md +62 -15
  44. package/apps/bridge/src/started-by/attach.ts +8 -3
  45. package/apps/bridge/src/started-by/facts.ts +19 -5
  46. package/apps/bridge/src/started-by/folders/index.ts +79 -0
  47. package/apps/bridge/src/started-by/folders/launches.ts +98 -0
  48. package/apps/bridge/src/started-by/headless.ts +24 -4
  49. package/apps/bridge/src/started-by/index.ts +2 -0
  50. package/apps/bridge/src/started-by/live/index.ts +133 -0
  51. package/apps/bridge/src/working-tree/README.md +38 -0
  52. package/apps/bridge/src/working-tree/commit.ts +47 -0
  53. package/apps/bridge/src/working-tree/index.ts +65 -0
  54. package/apps/bridge/src/working-tree/relay.ts +39 -0
  55. package/apps/bridge/src/working-tree/status.ts +64 -0
  56. package/apps/mcp/src/connection-center/README.md +38 -5
  57. package/apps/mcp/src/connection-center/{bridge.js → card/bridge.js} +26 -23
  58. package/apps/mcp/src/connection-center/card/card.css +187 -0
  59. package/apps/mcp/src/connection-center/card/phones-view.js +195 -0
  60. package/apps/mcp/src/connection-center/card/phones.js +145 -0
  61. package/apps/mcp/src/connection-center/card/view.js +210 -0
  62. package/apps/mcp/src/connection-center/card/widget.html +94 -0
  63. package/apps/mcp/src/connection-center/state.ts +5 -1
  64. package/apps/mcp/src/mcp-tools/README.md +2 -1
  65. package/apps/mcp/src/mcp-tools/connect/widget.ts +19 -6
  66. package/apps/mcp/src/mcp-tools/phones/index.ts +5 -2
  67. package/apps/mcp/src/mcp-tools/phones/removal.ts +6 -3
  68. package/apps/mcp/src/status/pairing-status.ts +24 -11
  69. package/cursor-plugin/README.md +1 -1
  70. package/cursor-plugin/mcp.json +1 -1
  71. package/cursor-plugin/stdio-bootstrap.cjs +1 -1
  72. package/package.json +1 -1
  73. package/packages/core/outbound-scheduler/README.md +7 -0
  74. package/packages/core/outbound-scheduler/index.ts +18 -2
  75. package/packages/protocol/messages/README.md +23 -0
  76. package/packages/protocol/messages/sessions/index.ts +39 -4
  77. package/packages/protocol/messages/sessions/working-tree.ts +62 -0
  78. package/packages/protocol/schema.ts +6 -0
  79. package/apps/mcp/src/connection-center/view.js +0 -155
  80. package/apps/mcp/src/connection-center/widget.html +0 -51
package/README.md CHANGED
@@ -150,7 +150,9 @@ Every phone or iPad that scanned a QR for a computer keeps a key there until som
150
150
  debug installs pile up. In the app, **Devices → a computer → Phones** lists each phone with its name or label,
151
151
  **This iPhone**, and when it last reached the computer, and removes one (swipe or context menu), several, or
152
152
  every phone not seen for 30 days. Removing the phone in use is its own confirmed action, **Unpair this
153
- phone**, and the last phone always stays. A removed phone stops receiving from the computer at once, in every
153
+ phone**, and the last phone always stays. On the computer, the GrantTap connection card in Claude, Codex, Grok
154
+ Build or Cursor (`connection_status`) lists the same phones with **Remove** on each and **Remove N** for those
155
+ not seen for 30 days; a removal there is confirmed on the card and then with a yes on a phone (`remove_phones`). A removed phone stops receiving from the computer at once, in every
154
156
  running GrantTap process, without a restart; it needs a new QR to pair again. Removing the first pairing hands
155
157
  its place to the phone heard from most recently.
156
158
 
@@ -649,7 +651,7 @@ trust.
649
651
  | `connect_with_passkey` | Link this computer to the user's GrantTap account so a signed-in phone can connect without a QR; returns a 15-minute granttap.com link, the passkey is entered only there, and existing QR pairings stay unchanged |
650
652
  | `connect` | Show the existing pairing on the connection card, or on an unpaired computer create a one-time QR shown only on the card |
651
653
  | `reconnect` | After explicit confirmation, show a one-time QR to reconnect or add an independent controller device while retaining the current room |
652
- | `remove_phones` | Ask the person to remove paired phones that are no longer used, by `notSeenForDays` and/or `phoneIds` from `connection_status`; nothing is removed without a yes on a phone, and the phone that answers, any phone heard from while the question is open, and the last phone stay |
654
+ | `remove_phones` | Ask the person to remove paired phones that are no longer used, by `notSeenForDays` (never the phone heard from most recently; `connection_status` marks the 30-day ones `stale`) and/or `phoneIds` from `connection_status`; nothing is removed without a yes on a phone, and the phone that answers, any phone heard from while the question is open, and the last phone stay |
653
655
  | `notify` | Send a non-blocking status of at most 2,000 characters that nobody answers, and/or one task-scoped Mesh event |
654
656
  | `ask_yes_no` | Ask a yes/no question and wait about three minutes for the explicit answer; a timeout is neither yes nor no |
655
657
  | `ask` | Ask an open question and wait about three minutes for typed or spoken text |
@@ -785,6 +787,33 @@ temp folder, a plain folder or one of its parent's checkout is in its parent's
785
787
  Mesh and registers no Mesh of its own; one in a checkout of its own keeps that
786
788
  checkout's. Details: [`apps/bridge/src/started-by`](apps/bridge/src/started-by/README.md).
787
789
 
790
+ ### Uncommitted changes of a chat, and committing them from the phone
791
+
792
+ A chat whose working folder is a Git checkout carries `workingTree { branch?, detached?, ahead?,
793
+ behind?, changed, operation?, observedAt }`, read at most every five seconds per folder. The phone asks
794
+ `session.changes.query` for up to 200 changed paths with Git's status letters and a `treeToken`, and
795
+ sends `session.commit { message ≤ 2000, paths, treeToken, confirmWhileWorking? }`; the computer commits
796
+ exactly those paths (`git add -A -- …`, `git commit -m … -- …`, hooks run, no push) or refuses with
797
+ `changed`, `detached`, `operation`, `working`, `unavailable` or `failed`. Both answers go only to the
798
+ phone that asked. See [working tree](apps/bridge/src/working-tree/README.md).
799
+
800
+ ### What a run's end says
801
+
802
+ A Codex turn that ends on Codex's own error instead of an answer says so: the chat's last message is
803
+ `Codex stopped: You’ve hit your usage limit.` (Codex's first sentence, without its links), its
804
+ transcript ends with that sentence, and the session carries `stopped { reason, message?, at }`
805
+ (`reason`: `usage_limit`, `rate_limit`, `context_window`, `sign_in`, `service`, `error`). A used-up
806
+ limit adds `usageLimit { resetsAt, autoContinue: false }`, read from Codex's "try again at …". An answer
807
+ Codex writes only in its newer `item_completed` or `task_complete` rows is shown like any other.
808
+
809
+ A headless run whose answer names a picture it saved inside its working folder shows `Picture saved:
810
+ <file name>` as its last message; the computer keeps a reduced copy and publishes it as the session's
811
+ `images` and on the answer that names it, readable with `session.image.query` by that chat and the chat
812
+ that started it. A Codex run nobody has asked anything yet is no chat and no Mesh Task until its request
813
+ appears, and Tasks an earlier runtime made for such chats (`codex task`, "Continue this coding task")
814
+ are left out of what the phone is sent. See [Codex outcomes](apps/bridge/src/sessions/scan/codex/README.md)
815
+ and [chat pictures](apps/bridge/src/helper-runs/README.md#pictures-a-chat-saved).
816
+
788
817
  ### One computer, whatever the network calls it
789
818
 
790
819
  The Mesh keys a computer by an identity written down once, on first use, in
@@ -1032,7 +1061,9 @@ See the [runtime watchdog](apps/bridge/src/runtime-watchdog/README.md).
1032
1061
 
1033
1062
  ## Automatic runtime updates
1034
1063
 
1035
- Installed GrantTap background services check for stable MCP updates automatically.
1064
+ Installed GrantTap background services check for stable MCP updates automatically, once an
1065
+ hour with one small registry request; a failed check is retried after 5, 10, 20 and 40 minutes,
1066
+ then hourly.
1036
1067
  Verified updates are staged separately and applied after active requests and pending
1037
1068
  decisions finish. Startup failures restore the previous version. Pairing and task
1038
1069
  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));
@@ -125,7 +125,7 @@ function parentOf(folder: string): string | undefined {
125
125
  }
126
126
 
127
127
  /** Whether a folder lies inside a Git checkout: one of the folders above it holds `.git`. */
128
- function insideCheckout(folder: string): boolean {
128
+ export function insideCheckout(folder: string): boolean {
129
129
  let above = parentOf(folder);
130
130
  for (let depth = 0; above !== undefined && depth < 48; depth += 1) {
131
131
  if (existsSync(`${above === "/" ? "" : above}/.git`)) return true;
@@ -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
  /**
@@ -5,6 +5,9 @@ catalogs. `index.ts` assembles and publishes the bounded wire payload,
5
5
  `host/process-sampler.ts` owns agent ancestry, `host/ps-reader.ts` reads operating-system
6
6
  CPU time and RSS, `mcp/scan-cost.ts` retains provider discovery cost, and `host/loop.ts`
7
7
  runs a two-second active / thirty-second idle cadence from cached session status.
8
+ `captureStartedRunsNow` lists processes once for headless runs alone and reports
9
+ nothing; a new provider transcript asks for it, since a run a usage limit stops can
10
+ end between two samples ([chats started by another chat](../started-by/README.md)).
8
11
 
9
12
  `command-process/history.ts` hashes process command fingerprints and uses
10
13
  the provider's existing call/result timestamps to match one newly started
@@ -221,6 +221,17 @@ export function resetSessionResolver(read?: EnvironmentReader, now?: () => numbe
221
221
  resolveSessions = createSessionResolver(read, now);
222
222
  }
223
223
 
224
+ /**
225
+ * One listing for headless runs alone, nothing reported: a run a usage limit stops lives three or
226
+ * four seconds, so a new transcript asks for this at once (`started-by/live`).
227
+ */
228
+ export async function captureStartedRunsNow(): Promise<number> {
229
+ const rows = await sampleProcessRows();
230
+ const sampledAt = Date.now();
231
+ const sessions = await resolveSessions(rows);
232
+ return captureStartedRuns(startedRunProcesses(rows, attributeByAncestry(rows), sessions, sampledAt));
233
+ }
234
+
224
235
  export async function sampleAgentProcesses(): Promise<Record<string, AgentProcessLoad>> {
225
236
  const rows = await sampleProcessRows();
226
237
  const sampledAt = Date.now();
@@ -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