granttap-mcp 0.8.173 → 0.8.175

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.
@@ -3,7 +3,7 @@ import { chmodSync, existsSync, mkdirSync, renameSync, unlinkSync, writeFileSync
3
3
  import { dirname } from "node:path";
4
4
 
5
5
  /** Write ~/.granttap files so a second save cannot fail on Windows overwrite. */
6
- export function writePrivateFile(path: string, contents: string): void {
6
+ export function writePrivateFile(path: string, contents: string | Uint8Array): void {
7
7
  mkdirSync(dirname(path), { recursive: true });
8
8
  const temporary = `${path}.tmp-${process.pid}-${randomUUID()}`;
9
9
  try {
@@ -0,0 +1,53 @@
1
+ # Helper runs
2
+
3
+ A chat that asks for a picture runs a script, and the script starts its own
4
+ headless provider session in a throwaway folder inside the system temp
5
+ directory. That session is the chat's work. It is shown as one of the chat's
6
+ nested conversations, labelled for what it is, and never as a chat or a Mesh
7
+ of its own.
8
+
9
+ **Recognised** (`kinds.ts`). A run is a headless session whose working folder
10
+ sits directly inside a temp directory and carries a generator's prefix.
11
+ `GENERATORS` is the one place a generator is listed: its folder prefix, the
12
+ kind its runs are, and the label a phone that does not know the kind shows.
13
+ A session in a temp folder is not a run unless a generator claims the folder.
14
+
15
+ **Linked** (`capture.ts`, `links.ts`). Nothing recorded after the fact names
16
+ the chat that started a run. The run's live process does: Claude Code and
17
+ Codex give every command a chat runs that chat's id, and the run inherits it.
18
+ Each process sample (`machine-load`) passes its provider processes here. A
19
+ process is looked at once: its working folder is read, and only when that is a
20
+ generator's folder is its environment read, for the chat's id alone. Nothing
21
+ read from a process is logged or kept beyond that id. The link is written to
22
+ `helper-runs.json` in the config directory, keyed by the run's folder, and
23
+ outlives the process. The first capture of a run stands.
24
+
25
+ **Shown** (`attach.ts`). The session catalog adds each linked run to its
26
+ parent's `childThreads` with `kind` set, and leaves the parent's own state,
27
+ clock and spend alone. Opening the conversation reads the run's own messages.
28
+ A run whose parent was not captured, or whose parent is no longer on this
29
+ computer, is published nowhere; the provider's own history still has it.
30
+
31
+ **Pictures** (`pictures/`). The script copies a
32
+ run's picture away and deletes the run's folder the moment the run ends, so
33
+ the folder of every live linked run is looked at five times a second while
34
+ its process lives (file events arrived seconds late under load, after such a
35
+ folder was gone). A picture is read as soon as it is written to its end and is
36
+ kept from memory: on macOS as a JPEG at most 1600 pixels long (`sips`, never
37
+ enlarged), elsewhere as it is when it is at most 8 MB. Copies live in
38
+ `helper-run-pictures/` in the config directory with one `index.json`, at most
39
+ 12 per run, and are let go with the run's history or when the store passes its
40
+ bounds. The run's card carries them as `images`, and its last answer shows them
41
+ in place of the path line that names them. A phone reads one with
42
+ `session.image.query` on the parent chat; the id names the run and the
43
+ picture's content, never a path, and only the chat that started the run is
44
+ answered.
45
+
46
+ **Meshes.** A generator's folder never registers a Mesh. Meshes registered for
47
+ such folders before runs were recognised stay in the Mesh store and are left
48
+ out of every list of this computer's Projects.
49
+
50
+ Tests live in `tests/`; the Mesh behaviour is covered in
51
+ `../mesh/runtime/tests/helper-run-meshes.test.ts`.
52
+
53
+ Licensed under the GrantTap Commercial Source License. See the repository root `LICENSE`.
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Show a helper run where it belongs: under the chat that started it.
3
+ *
4
+ * A run is the chat's work, like one of its agents, so it is published as one
5
+ * of the chat's nested conversations and never as a chat of its own. A run
6
+ * whose parent was not captured, or whose parent is no longer on this
7
+ * computer, is published nowhere; the provider's own history still has it.
8
+ */
9
+ import type { ActivityEntry, ChildThreadInfo, SessionInfo } from "../../../../packages/protocol/schema";
10
+ import { boundChildThreads, childEntryFields, childTitle } from "../sessions/support/child-threads";
11
+ import { helperRunLink, type HelperRunLink } from "./links";
12
+ import { helperRunImageId, helperRunPictures, type RunPicture } from "./pictures/store";
13
+
14
+ /** A provider session a scanner recognised as a helper run and kept out of its chats. */
15
+ export type HelperRunSession = {
16
+ session: SessionInfo;
17
+ kind: string;
18
+ /** What a phone that does not know the kind calls the run. */
19
+ label: string;
20
+ folder: string;
21
+ };
22
+
23
+ function sessionKey(agent: string, sessionId: string): string {
24
+ return `${agent}\0${sessionId}`;
25
+ }
26
+
27
+ /** The runs attached by the newest catalog, so a run's conversation can be read when a phone opens it. */
28
+ let attached = new Map<string, { session: SessionInfo; folder: string }>();
29
+
30
+ type MessageImage = NonNullable<ActivityEntry["images"]>[number];
31
+
32
+ /** The `/var` and `/private/var` spellings of a macOS temp path name one folder. */
33
+ function samePath(text: string): string {
34
+ return text.replace(/\\/g, "/").replace(/^\/private\/(var|tmp)\//, "/$1/");
35
+ }
36
+
37
+ /**
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.
40
+ */
41
+ function pictureImage(folder: string, picture: RunPicture, text = ""): MessageImage {
42
+ const id = helperRunImageId(folder, picture.hash);
43
+ const line = text.split("\n").map((item) => item.trim().replace(/^(?:[-*+] |\d+\. )/, ""))
44
+ .find((item) => samePath(item.replace(/^`(.*)`$/, "$1")) === samePath(picture.source));
45
+ return { id, name: picture.name, markdown: line && line.length <= 2_400 ? line : `![${picture.name}](granttap-image:${id})` };
46
+ }
47
+
48
+ function childOf(parent: SessionInfo, run: HelperRunSession): ChildThreadInfo {
49
+ const { session } = run;
50
+ const images = helperRunPictures(run.folder).map((picture) => pictureImage(run.folder, picture));
51
+ return {
52
+ threadId: session.sessionId,
53
+ parentThreadId: parent.sessionId,
54
+ title: childTitle(session.title),
55
+ agentName: run.label,
56
+ kind: run.kind,
57
+ depth: 1,
58
+ state: session.state,
59
+ startedAt: session.startedAt,
60
+ lastActivityAt: session.lastActivityAt,
61
+ tokensSession: session.tokensSession,
62
+ tokensLastTurn: session.tokensLastTurn,
63
+ ...(images.length > 0 ? { images } : {}),
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Add each run to its parent's nested conversations. The parent's own state,
69
+ * clock and spend stay its own: the run is another provider's work.
70
+ */
71
+ export function attachHelperRuns(
72
+ sessions: SessionInfo[],
73
+ runs: readonly HelperRunSession[],
74
+ link: (folder: string) => HelperRunLink | undefined = helperRunLink,
75
+ ): SessionInfo[] {
76
+ const parents = new Map(sessions.map((session) => [sessionKey(session.agent, session.sessionId), session]));
77
+ const children = new Map<string, ChildThreadInfo[]>();
78
+ const read = new Map<string, { session: SessionInfo; folder: string }>();
79
+ for (const run of runs) {
80
+ const known = link(run.folder);
81
+ const key = known ? sessionKey(known.parentAgent, known.parentSessionId) : undefined;
82
+ const parent = key ? parents.get(key) : undefined;
83
+ if (!key || !parent) continue;
84
+ children.set(key, [...(children.get(key) ?? []), childOf(parent, run)]);
85
+ read.set(run.session.sessionId, { session: run.session, folder: run.folder });
86
+ }
87
+ attached = read;
88
+ if (children.size === 0) return sessions;
89
+ return sessions.map((session) => {
90
+ const own = children.get(sessionKey(session.agent, session.sessionId));
91
+ return own ? { ...session, childThreads: boundChildThreads([...(session.childThreads ?? []), ...own]) } : session;
92
+ });
93
+ }
94
+
95
+ /** The helper run behind one of a chat's nested conversations, when that conversation is one. */
96
+ export function helperRunThread(
97
+ parent: SessionInfo,
98
+ threadId: string,
99
+ ): { child: ChildThreadInfo; session: SessionInfo; folder?: string } | undefined {
100
+ const child = parent.childThreads?.find((item) => item.threadId === threadId && item.kind);
101
+ if (!child) return undefined;
102
+ const known = attached.get(threadId);
103
+ if (known) return { child, ...known };
104
+ const session: SessionInfo = {
105
+ sessionId: threadId, agent: "grok", state: child.state, startedAt: child.startedAt,
106
+ lastActivityAt: child.lastActivityAt, tokensSession: child.tokensSession, tokensLastTurn: child.tokensLastTurn,
107
+ };
108
+ return { child, session };
109
+ }
110
+
111
+ /**
112
+ * A run's own messages, marked as the nested conversation they are shown in.
113
+ * The pictures kept from the run are shown on its last answer.
114
+ */
115
+ export function helperRunEntries(child: ChildThreadInfo, entries: readonly ActivityEntry[],
116
+ folder?: string): ActivityEntry[] {
117
+ const marked = entries.map((entry) => ({ ...entry, ...childEntryFields(child) }));
118
+ const pictures = helperRunPictures(folder);
119
+ if (!folder || pictures.length === 0) return marked;
120
+ const lastOf = (kind: ActivityEntry["kind"]) => marked.map((entry) => entry.kind).lastIndexOf(kind);
121
+ const at = lastOf("final") >= 0 ? lastOf("final") : lastOf("message");
122
+ if (at < 0) return marked;
123
+ const answer = marked[at]!;
124
+ const images = pictures.map((picture) => pictureImage(folder, picture, answer.text));
125
+ return marked.map((entry, index) => index === at ? { ...entry, images: [...(entry.images ?? []), ...images].slice(0, 32) } : entry);
126
+ }
@@ -0,0 +1,189 @@
1
+ /**
2
+ * Learn which chat started a helper run while the run's process is alive.
3
+ *
4
+ * The provider's own record of the run names no parent, and the parent's
5
+ * transcript does not name the run. The live process does: a chat hands its id
6
+ * to everything its shell starts, and the run's process inherits it. Only a
7
+ * process already known to be a helper run has its environment read, only the
8
+ * chat's id is kept from it, and nothing read here is ever logged.
9
+ */
10
+ import { execFile } from "node:child_process";
11
+ import { existsSync, readlinkSync } from "node:fs";
12
+ import { promisify } from "node:util";
13
+ import type { ProcessRow } from "../machine-load/host/process-sampler";
14
+ import { helperRunFolder, helperRunFoldersNamed, type HelperRunFolder } from "./kinds";
15
+ import { rememberHelperRunLinks, type HelperRunLink, type HelperRunParentAgent } from "./links";
16
+ import { followHelperRunPictures } from "./pictures/capture";
17
+
18
+ const run = promisify(execFile);
19
+
20
+ export type HelperRunParent = { agent: HelperRunParentAgent; sessionId: string };
21
+
22
+ /** One provider process the listing shows. Its command line is searched for a generator's folder and never kept. */
23
+ export type HelperRunProcess = { pid: number; command: string; ancestor?: HelperRunParent };
24
+
25
+ export type HelperRunReaders = {
26
+ directories: (pids: readonly number[]) => Promise<Map<number, string>>;
27
+ parents: (pids: readonly number[]) => Promise<Map<number, HelperRunParent>>;
28
+ };
29
+
30
+ /** The variable each provider gives the commands a chat runs, naming that chat. */
31
+ const PARENT_VARIABLES: ReadonlyArray<readonly [HelperRunParentAgent, RegExp]> = [
32
+ ["claude", /(?:^|\s)CLAUDE_CODE_SESSION_ID=([A-Za-z0-9._-]{8,128})(?=\s|$)/],
33
+ ["codex", /(?:^|\s)CODEX_THREAD_ID=([A-Za-z0-9._-]{8,128})(?=\s|$)/],
34
+ ];
35
+ const PARENT_AGENTS = new Set<string>(PARENT_VARIABLES.map(([agent]) => agent));
36
+ const MAX_FOLDER_READS = 3;
37
+ const LSOF = "/usr/sbin/lsof";
38
+
39
+ /** `lsof -Fn` prints `p<pid>`, then `n<path>` for the one descriptor asked for. */
40
+ export function parseProcessDirectories(stdout: string): Map<number, string> {
41
+ const out = new Map<number, string>();
42
+ let pid: number | undefined;
43
+ for (const line of stdout.split("\n")) {
44
+ if (/^p\d+$/.test(line)) pid = Number(line.slice(1));
45
+ else if (line.startsWith("n/") && pid != null && !out.has(pid)) out.set(pid, line.slice(1));
46
+ }
47
+ return out;
48
+ }
49
+
50
+ /** `ps -E -o pid=,uid=,command=`: the chat's id is taken and the rest of the line is dropped. */
51
+ export function parseProcessParents(stdout: string, uid?: number): Map<number, HelperRunParent> {
52
+ const out = new Map<number, HelperRunParent>();
53
+ for (const line of stdout.split("\n")) {
54
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);
55
+ if (!match || (uid != null && Number(match[2]) !== uid)) continue;
56
+ for (const [agent, variable] of PARENT_VARIABLES) {
57
+ const sessionId = variable.exec(match[3]!)?.[1];
58
+ if (sessionId) { out.set(Number(match[1]), { agent, sessionId }); break; }
59
+ }
60
+ }
61
+ return out;
62
+ }
63
+
64
+ export async function readProcessDirectories(pids: readonly number[]): Promise<Map<number, string>> {
65
+ if (pids.length === 0) return new Map();
66
+ if (process.platform === "linux") {
67
+ const out = new Map<number, string>();
68
+ for (const pid of pids) {
69
+ try { out.set(pid, readlinkSync(`/proc/${pid}/cwd`)); } catch { /* Exited, or not this person's. */ }
70
+ }
71
+ return out;
72
+ }
73
+ try {
74
+ const { stdout } = await run(existsSync(LSOF) ? LSOF : "lsof", ["-a", "-d", "cwd", "-Fn", "-p", pids.join(",")],
75
+ { encoding: "utf8", maxBuffer: 1_000_000, timeout: 5_000 });
76
+ return parseProcessDirectories(String(stdout));
77
+ } catch (error) {
78
+ // The tool exits non-zero when one of the processes is gone and still lists the rest.
79
+ return parseProcessDirectories(String((error as { stdout?: unknown }).stdout ?? ""));
80
+ }
81
+ }
82
+
83
+ export async function readProcessParents(pids: readonly number[]): Promise<Map<number, HelperRunParent>> {
84
+ if (pids.length === 0) return new Map();
85
+ try {
86
+ const { stdout } = await run("ps", ["-E", "-o", "pid=,uid=,command=", "-p", pids.join(",")],
87
+ { encoding: "utf8", maxBuffer: 8_000_000, timeout: 5_000 });
88
+ return parseProcessParents(String(stdout), process.getuid?.());
89
+ } catch {
90
+ // The error carries every environment it read; none of it leaves here.
91
+ throw new Error("process environment unavailable");
92
+ }
93
+ }
94
+
95
+ /** The provider processes in a listing, each with the chat of the provider process it was started under. */
96
+ export function helperRunProcesses(
97
+ rows: readonly ProcessRow[],
98
+ ownership: { agents: ReadonlyMap<number, string>; roots: ReadonlyMap<number, number> },
99
+ sessions: ReadonlyMap<number, string>,
100
+ ): HelperRunProcess[] {
101
+ return rows.filter((row) => ownership.roots.get(row.pid) === row.pid).map((row) => {
102
+ const above = row.ppid != null ? ownership.roots.get(row.ppid) : undefined;
103
+ const agent = above != null ? ownership.agents.get(above) : undefined;
104
+ const sessionId = above != null ? sessions.get(above) : undefined;
105
+ return {
106
+ pid: row.pid, command: row.command,
107
+ ...(agent && sessionId && PARENT_AGENTS.has(agent)
108
+ ? { ancestor: { agent: agent as HelperRunParentAgent, sessionId } } : {}),
109
+ };
110
+ });
111
+ }
112
+
113
+ type CaptureOptions = {
114
+ readers?: HelperRunReaders;
115
+ remember?: (links: HelperRunLink[]) => number;
116
+ /** Told, at every sample, the folders of the linked runs still alive, so their pictures are caught. */
117
+ follow?: (folders: readonly string[]) => void;
118
+ now?: () => number;
119
+ };
120
+
121
+ /** One capture per monitor: it remembers which processes it has already looked at. */
122
+ export function createHelperRunCapture(options: CaptureOptions = {}) {
123
+ const readers = options.readers ?? { directories: readProcessDirectories, parents: readProcessParents };
124
+ const remember = options.remember ?? rememberHelperRunLinks;
125
+ const follow = options.follow ?? followHelperRunPictures;
126
+ const now = options.now ?? Date.now;
127
+ const settled = new Set<number>();
128
+ const folderReads = new Map<number, number>();
129
+ /** The folder of each live linked run, by its process. */
130
+ const running = new Map<number, string>();
131
+
132
+ const folderOf = (item: HelperRunProcess, directory: string | undefined): HelperRunFolder | undefined => {
133
+ const working = helperRunFolder(directory);
134
+ if (working) return working;
135
+ const named = helperRunFoldersNamed(item.command);
136
+ return named.length === 1 ? named[0] : undefined;
137
+ };
138
+
139
+ const examine = async (processes: readonly HelperRunProcess[]): Promise<number> => {
140
+ const live = new Set(processes.map((item) => item.pid));
141
+ for (const pid of [...settled]) if (!live.has(pid)) settled.delete(pid);
142
+ for (const pid of [...folderReads.keys()]) if (!live.has(pid)) folderReads.delete(pid);
143
+ for (const pid of [...running.keys()]) if (!live.has(pid)) running.delete(pid);
144
+ const fresh = processes.filter((item) => !settled.has(item.pid));
145
+ if (fresh.length === 0) return 0;
146
+ const directories = await readers.directories(fresh.map((item) => item.pid));
147
+ const runs: Array<{ item: HelperRunProcess; folder: HelperRunFolder }> = [];
148
+ for (const item of fresh) {
149
+ const directory = directories.get(item.pid);
150
+ const folder = folderOf(item, directory);
151
+ if (folder) { runs.push({ item, folder }); continue; }
152
+ const reads = (folderReads.get(item.pid) ?? 0) + 1;
153
+ folderReads.set(item.pid, reads);
154
+ if (directory !== undefined || reads >= MAX_FOLDER_READS) settled.add(item.pid);
155
+ }
156
+ if (runs.length === 0) return 0;
157
+ const parents = await readers.parents(runs.map(({ item }) => item.pid));
158
+ const links: HelperRunLink[] = [];
159
+ for (const { item, folder } of runs) {
160
+ settled.add(item.pid);
161
+ const parent = parents.get(item.pid) ?? item.ancestor;
162
+ if (parent) {
163
+ running.set(item.pid, folder.folder);
164
+ links.push({ folder: folder.folder, kind: folder.kind, parentAgent: parent.agent,
165
+ parentSessionId: parent.sessionId, capturedAt: now() });
166
+ }
167
+ }
168
+ return links.length > 0 ? remember(links) : 0;
169
+ };
170
+
171
+ return async (processes: readonly HelperRunProcess[]): Promise<number> => {
172
+ let fresh = 0;
173
+ try { fresh = await examine(processes); } catch { /* The next sample tries again. */ }
174
+ try { follow([...new Set(running.values())]); } catch { /* A picture missed here is looked for at the next sample. */ }
175
+ return fresh;
176
+ };
177
+ }
178
+
179
+ let capture = createHelperRunCapture();
180
+
181
+ /** For tests: forget which processes were looked at, and read through other tools. */
182
+ export function resetHelperRunCapture(options?: CaptureOptions): void {
183
+ capture = createHelperRunCapture(options);
184
+ }
185
+
186
+ /** Called with every process sample; a helper run lives long enough to be in at least one. */
187
+ export function captureHelperRuns(processes: readonly HelperRunProcess[]): Promise<number> {
188
+ return capture(processes);
189
+ }
@@ -0,0 +1,5 @@
1
+ /** Short helper runs a chat starts, such as image generation: recognised, linked to their chat, shown under it. */
2
+ export { helperRunFolder, helperRunLabel, helperRunProject, type HelperRunFolder, type HelperRunKind } from "./kinds";
3
+ export { helperRunLink, rememberHelperRunLinks, type HelperRunLink } from "./links";
4
+ export { attachHelperRuns, helperRunEntries, helperRunThread, type HelperRunSession } from "./attach";
5
+ export { captureHelperRuns, helperRunProcesses } from "./capture";
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Which working folders belong to a generator's short helper run.
3
+ *
4
+ * A chat that asks for a picture runs a script, and the script starts its own
5
+ * headless provider session in a throwaway folder inside the system temp
6
+ * directory. The folder's name carries the generator's prefix; nothing else
7
+ * about the run says what it is. A session in a temp folder is not a helper
8
+ * run by itself: only a generator listed here makes it one.
9
+ */
10
+ import { realpathSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+
13
+ export type HelperRunKind = "image-generation";
14
+
15
+ type Generator = {
16
+ /** How the generator names its throwaway folder. */
17
+ prefix: string;
18
+ kind: HelperRunKind;
19
+ /** What a phone that does not know the kind calls the run. */
20
+ label: string;
21
+ };
22
+
23
+ /** Every generator, in one place: add a row to recognise another one. */
24
+ const GENERATORS: readonly Generator[] = [
25
+ { prefix: "hw-image-", kind: "image-generation", label: "Image generation" },
26
+ ];
27
+
28
+ const RUN_SUFFIX = /^[A-Za-z0-9_-]{4,64}$/;
29
+ /** macOS gives each person a temp directory of this shape, with or without `/private`. */
30
+ const PER_USER_TEMP = /^\/var\/folders\/[^/]+\/[^/]+\/T$/;
31
+
32
+ export type HelperRunFolder = {
33
+ kind: HelperRunKind;
34
+ label: string;
35
+ /** The folder in one spelling, so a path read from a process and one read from a log compare equal. */
36
+ folder: string;
37
+ };
38
+
39
+ function plain(path: string): string {
40
+ const trimmed = path.trim().replace(/\\/g, "/").replace(/\/+$/, "");
41
+ return /^\/private\/(var|tmp)(\/|$)/.test(trimmed) ? trimmed.slice("/private".length) : trimmed;
42
+ }
43
+
44
+ let ownTemp: readonly string[] | undefined;
45
+
46
+ /** This computer's temp directory, as the environment names it and as the disk does. */
47
+ function systemTempRoots(): readonly string[] {
48
+ if (ownTemp) return ownTemp;
49
+ const named = tmpdir();
50
+ let resolved = named;
51
+ try { resolved = realpathSync(named); } catch { /* The named path stands. */ }
52
+ ownTemp = [named, resolved, "/tmp"];
53
+ return ownTemp;
54
+ }
55
+
56
+ function isTempRoot(directory: string, roots: readonly string[]): boolean {
57
+ return PER_USER_TEMP.test(directory) || roots.some((root) => plain(root) === directory);
58
+ }
59
+
60
+ /** The generator a working folder belongs to, when it is one's throwaway folder directly inside a temp directory. */
61
+ export function helperRunFolder(
62
+ path: string | undefined,
63
+ tempRoots: readonly string[] = systemTempRoots(),
64
+ ): HelperRunFolder | undefined {
65
+ if (!path) return undefined;
66
+ const folder = plain(path);
67
+ const cut = folder.lastIndexOf("/");
68
+ if (cut <= 0 || !isTempRoot(folder.slice(0, cut), tempRoots)) return undefined;
69
+ const name = folder.slice(cut + 1);
70
+ const generator = GENERATORS.find((item) =>
71
+ name.startsWith(item.prefix) && RUN_SUFFIX.test(name.slice(item.prefix.length)));
72
+ return generator ? { kind: generator.kind, label: generator.label, folder } : undefined;
73
+ }
74
+
75
+ /** Every different generator folder a text names, such as a process's command line. */
76
+ export function helperRunFoldersNamed(text: string, tempRoots?: readonly string[]): HelperRunFolder[] {
77
+ const found = new Map<string, HelperRunFolder>();
78
+ for (const generator of GENERATORS) {
79
+ const name = generator.prefix.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
80
+ for (const match of text.matchAll(new RegExp(`/[A-Za-z0-9._/-]+/${name}[A-Za-z0-9_-]{4,64}`, "g"))) {
81
+ const folder = helperRunFolder(match[0], tempRoots);
82
+ if (folder) found.set(folder.folder, folder);
83
+ }
84
+ }
85
+ return [...found.values()];
86
+ }
87
+
88
+ export function helperRunLabel(kind: string): string {
89
+ return GENERATORS.find((item) => item.kind === kind)?.label ?? "Helper run";
90
+ }
91
+
92
+ /**
93
+ * A Mesh that was registered for a helper run's folder before helper runs were recognised.
94
+ * A repository with a remote is a real Project wherever it was cloned.
95
+ */
96
+ export function helperRunProject(project: { repositoryRoot?: string; canonicalRepositoryId: string }): boolean {
97
+ const identity = project.canonicalRepositoryId;
98
+ if (!identity.startsWith("local:")) return false;
99
+ return helperRunFolder(project.repositoryRoot) !== undefined
100
+ || helperRunFolder(identity.slice("local:".length)) !== undefined;
101
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Which chat started each helper run, kept after the run is over.
3
+ *
4
+ * Only the run's live process names its parent, and it lives for half a
5
+ * minute. The link is therefore written down the moment it is seen, keyed by
6
+ * the run's throwaway folder: the folder is what the process and the
7
+ * provider's own session record both carry, and each run has its own.
8
+ */
9
+ import { readFileSync, statSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { writePrivateFile } from "../config/access/write-private";
12
+ import { configDir } from "../config/runtime/paths";
13
+ import { HISTORY_RETENTION_MS } from "../sessions/support/common";
14
+ import { helperRunFolder } from "./kinds";
15
+
16
+ export type HelperRunParentAgent = "claude" | "codex";
17
+
18
+ export type HelperRunLink = {
19
+ folder: string;
20
+ kind: string;
21
+ parentAgent: HelperRunParentAgent;
22
+ parentSessionId: string;
23
+ capturedAt: number;
24
+ };
25
+
26
+ const MAX_LINKS = 2_000;
27
+ const SESSION_ID = /^[A-Za-z0-9._-]{8,128}$/;
28
+
29
+ export function helperRunLinksPath(): string {
30
+ return join(configDir(), "helper-runs.json");
31
+ }
32
+
33
+ function valid(value: unknown): HelperRunLink | undefined {
34
+ if (!value || typeof value !== "object") return undefined;
35
+ const item = value as Record<string, unknown>;
36
+ const folder = typeof item.folder === "string" ? helperRunFolder(item.folder)?.folder : undefined;
37
+ if (!folder || typeof item.kind !== "string" || !item.kind || item.kind.length > 40) return undefined;
38
+ if (item.parentAgent !== "claude" && item.parentAgent !== "codex") return undefined;
39
+ if (typeof item.parentSessionId !== "string" || !SESSION_ID.test(item.parentSessionId)) return undefined;
40
+ if (typeof item.capturedAt !== "number" || !Number.isFinite(item.capturedAt)) return undefined;
41
+ return { folder, kind: item.kind, parentAgent: item.parentAgent,
42
+ parentSessionId: item.parentSessionId, capturedAt: item.capturedAt };
43
+ }
44
+
45
+ let cached: { path: string; stamp: string; links: Map<string, HelperRunLink> } | undefined;
46
+
47
+ function stampOf(path: string): string | undefined {
48
+ try {
49
+ const stat = statSync(path);
50
+ return `${stat.mtimeMs}:${stat.size}`;
51
+ } catch {
52
+ return undefined;
53
+ }
54
+ }
55
+
56
+ function readLinks(): Map<string, HelperRunLink> {
57
+ const path = helperRunLinksPath();
58
+ const stamp = stampOf(path);
59
+ if (!stamp) return new Map();
60
+ if (cached?.path === path && cached.stamp === stamp) return cached.links;
61
+ const links = new Map<string, HelperRunLink>();
62
+ try {
63
+ const stored = JSON.parse(readFileSync(path, "utf8")) as { links?: unknown };
64
+ for (const value of Array.isArray(stored.links) ? stored.links : []) {
65
+ const link = valid(value);
66
+ if (link && !links.has(link.folder)) links.set(link.folder, link);
67
+ }
68
+ } catch {
69
+ // A file that cannot be read holds no links; the next capture rewrites it.
70
+ }
71
+ cached = { path, stamp, links };
72
+ return links;
73
+ }
74
+
75
+ /** The chat that started the run in this folder, when it was captured. */
76
+ export function helperRunLink(folder: string | undefined): HelperRunLink | undefined {
77
+ const key = helperRunFolder(folder)?.folder;
78
+ return key ? readLinks().get(key) : undefined;
79
+ }
80
+
81
+ /** Write newly captured parents down. The first capture of a run stands. Returns how many were new. */
82
+ export function rememberHelperRunLinks(captured: readonly HelperRunLink[], now = Date.now()): number {
83
+ const known = readLinks();
84
+ const fresh = new Map<string, HelperRunLink>();
85
+ for (const value of captured) {
86
+ const link = valid(value);
87
+ if (link && !known.has(link.folder) && !fresh.has(link.folder)) fresh.set(link.folder, link);
88
+ }
89
+ if (fresh.size === 0) return 0;
90
+ const kept = [...known.values(), ...fresh.values()]
91
+ .filter((link) => link.capturedAt >= now - HISTORY_RETENTION_MS)
92
+ .sort((left, right) => left.capturedAt - right.capturedAt)
93
+ .slice(-MAX_LINKS);
94
+ const path = helperRunLinksPath();
95
+ writePrivateFile(path, JSON.stringify({ version: 1, links: kept }));
96
+ const stamp = stampOf(path);
97
+ cached = stamp ? { path, stamp, links: new Map(kept.map((link) => [link.folder, link])) } : undefined;
98
+ return fresh.size;
99
+ }
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Catch each picture a helper run makes while the run is alive.
3
+ *
4
+ * A run writes its picture into its throwaway folder, and the script that
5
+ * started it copies the picture away and deletes the folder the moment the run
6
+ * ends. So the folder of every live run is looked at five times a second: a
7
+ * picture is read as soon as it is written to its end, and reduced and kept
8
+ * from memory, so deleting the folder afterwards loses nothing. The system's
9
+ * file events are not used: under load they arrived seconds late, after such a
10
+ * folder was gone. Each process sample also looks again.
11
+ */
12
+ import { execFile } from "node:child_process";
13
+ import {
14
+ existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync,
15
+ type Dirent, type Stats,
16
+ } from "node:fs";
17
+ import { tmpdir } from "node:os";
18
+ import { basename, join, relative, sep } from "node:path";
19
+ import { promisify } from "node:util";
20
+ import {
21
+ hasHelperRunPicture, keepHelperRunPicture, MAX_KEPT_BYTES, pictureComplete, pictureHash, pictureMime,
22
+ type PictureMime,
23
+ } from "./store";
24
+
25
+ const run = promisify(execFile);
26
+
27
+ const PICTURE_NAME = /\.(?:png|jpe?g|webp)$/i;
28
+ const MAX_SOURCE_BYTES = 48 * 1024 * 1024;
29
+ const MAX_ENTRIES = 200;
30
+ const LOOK_EVERY_MS = 200;
31
+ /** A picture this small is kept as it is. */
32
+ const KEEP_AS_IS_BYTES = 400 * 1024;
33
+ const LONG_EDGE = 1_600;
34
+ const SIPS = "/usr/bin/sips";
35
+
36
+ export type Reduced = { bytes: Uint8Array; mime: PictureMime };
37
+ export type Reducer = (bytes: Uint8Array, mime: PictureMime) => Promise<Reduced | undefined>;
38
+
39
+ /** The picture's own pixel size, from `sips -g`. */
40
+ export function parseSipsSize(stdout: string): { width: number; height: number } | undefined {
41
+ const width = Number(/pixelWidth:\s*(\d+)/.exec(stdout)?.[1]);
42
+ const height = Number(/pixelHeight:\s*(\d+)/.exec(stdout)?.[1]);
43
+ return width > 0 && height > 0 ? { width, height } : undefined;
44
+ }
45
+
46
+ /**
47
+ * Make the copy a phone downloads: a JPEG whose long side is at most 1600
48
+ * pixels, never enlarged. Where macOS's own converter is not available the
49
+ * picture is kept as it is when it fits.
50
+ */
51
+ export async function reducePicture(bytes: Uint8Array, mime: PictureMime): Promise<Reduced | undefined> {
52
+ const asIs = bytes.length <= MAX_KEPT_BYTES ? { bytes, mime } : undefined;
53
+ if (bytes.length <= KEEP_AS_IS_BYTES || process.platform !== "darwin" || !existsSync(SIPS)) return asIs;
54
+ const work = mkdtempSync(join(tmpdir(), "granttap-picture-"));
55
+ try {
56
+ const source = join(work, `source.${mime === "image/png" ? "png" : mime === "image/jpeg" ? "jpg" : "webp"}`);
57
+ const target = join(work, "reduced.jpg");
58
+ writeFileSync(source, bytes, { mode: 0o600 });
59
+ const size = parseSipsSize((await run(SIPS, ["-g", "pixelWidth", "-g", "pixelHeight", source],
60
+ { encoding: "utf8", timeout: 15_000 })).stdout);
61
+ const resize = size && Math.max(size.width, size.height) > LONG_EDGE ? ["-Z", String(LONG_EDGE)] : [];
62
+ await run(SIPS, ["-s", "format", "jpeg", "-s", "formatOptions", "75", ...resize, source, "--out", target],
63
+ { encoding: "utf8", timeout: 30_000 });
64
+ const reduced = readFileSync(target);
65
+ if (pictureMime(reduced.subarray(0, 12)) !== "image/jpeg" || !pictureComplete(reduced, "image/jpeg")
66
+ || reduced.length > MAX_KEPT_BYTES) return asIs;
67
+ return reduced.length < bytes.length ? { bytes: reduced, mime: "image/jpeg" } : asIs;
68
+ } catch {
69
+ return asIs;
70
+ } finally {
71
+ rmSync(work, { recursive: true, force: true });
72
+ }
73
+ }
74
+
75
+ type Followed = { folder: string; seen: Set<string>; stop: () => void };
76
+
77
+ export type PictureFollowerOptions = {
78
+ reduce?: Reducer;
79
+ keep?: typeof keepHelperRunPicture;
80
+ /** Calls `look` again and again; returns how to stop. */
81
+ repeat?: (look: () => void) => () => void;
82
+ now?: () => number;
83
+ };
84
+
85
+ /** Look at a live run's folder again and again until told to stop. */
86
+ function lookRepeatedly(look: () => void): () => void {
87
+ const timer = setInterval(look, LOOK_EVERY_MS);
88
+ timer.unref?.();
89
+ return () => clearInterval(timer);
90
+ }
91
+
92
+ /** Picture files in the folder and the folders directly inside it. */
93
+ function pictureFiles(folder: string): string[] {
94
+ const out: string[] = [];
95
+ const visit = (directory: string, depth: number) => {
96
+ let names: Dirent[];
97
+ try { names = readdirSync(directory, { withFileTypes: true }); } catch { return; }
98
+ for (const entry of names.slice(0, MAX_ENTRIES)) {
99
+ const path = join(directory, entry.name);
100
+ if (entry.isFile() && PICTURE_NAME.test(entry.name)) out.push(path);
101
+ else if (entry.isDirectory() && depth < 1) visit(path, depth + 1);
102
+ }
103
+ };
104
+ visit(folder, 0);
105
+ return out;
106
+ }
107
+
108
+ export function createPictureFollower(options: PictureFollowerOptions = {}) {
109
+ const reduce = options.reduce ?? reducePicture;
110
+ const keep = options.keep ?? keepHelperRunPicture;
111
+ const repeat = options.repeat ?? lookRepeatedly;
112
+ const now = options.now ?? Date.now;
113
+ const followed = new Map<string, Followed>();
114
+ let queue: Promise<unknown> = Promise.resolve();
115
+
116
+ const take = (item: Followed, path: string) => {
117
+ let stat: Stats;
118
+ try { stat = statSync(path); } catch { return; }
119
+ if (!stat.isFile() || stat.size === 0 || stat.size > MAX_SOURCE_BYTES) return;
120
+ const key = `${path}\0${stat.size}\0${stat.mtimeMs}`;
121
+ if (item.seen.has(key)) return;
122
+ let bytes: Buffer;
123
+ try { bytes = readFileSync(path); } catch { return; }
124
+ const mime = pictureMime(bytes.subarray(0, 12));
125
+ // Still being written: the write that finishes it is seen again.
126
+ if (!mime || !pictureComplete(bytes, mime)) return;
127
+ item.seen.add(key);
128
+ const hash = pictureHash(bytes);
129
+ if (hasHelperRunPicture(item.folder, hash)) return;
130
+ // Spelled as the run's folder is, so it matches the path the run's own messages give.
131
+ const source = `${item.folder}/${relative(item.folder, path).split(sep).join("/")}`;
132
+ const name = basename(path);
133
+ queue = queue.then(async () => {
134
+ const reduced = await reduce(bytes, mime);
135
+ if (reduced) keep(item.folder, { hash, name, source, mime: reduced.mime, capturedAt: now() }, reduced.bytes);
136
+ }).catch(() => undefined);
137
+ };
138
+
139
+ const scan = (item: Followed) => {
140
+ for (const path of pictureFiles(item.folder)) take(item, path);
141
+ };
142
+
143
+ const stop = (item: Followed) => {
144
+ item.stop();
145
+ followed.delete(item.folder);
146
+ };
147
+
148
+ /** Follow exactly these run folders: start on new ones, look again at each, stop on the rest. */
149
+ const follow = (folders: readonly string[]) => {
150
+ const live = new Set(folders);
151
+ for (const item of [...followed.values()]) if (!live.has(item.folder)) stop(item);
152
+ for (const folder of live) {
153
+ let item = followed.get(folder);
154
+ if (!item) {
155
+ const fresh: Followed = { folder, seen: new Set(), stop: () => undefined };
156
+ fresh.stop = repeat(() => scan(fresh));
157
+ followed.set(folder, fresh);
158
+ item = fresh;
159
+ }
160
+ scan(item);
161
+ }
162
+ };
163
+
164
+ return {
165
+ follow,
166
+ /** For tests: wait until every picture read so far is kept. */
167
+ settled: () => queue,
168
+ following: () => [...followed.keys()],
169
+ };
170
+ }
171
+
172
+ let follower = createPictureFollower();
173
+
174
+ /** For tests: replace how pictures are reduced and kept. */
175
+ export function resetPictureFollower(options?: PictureFollowerOptions): ReturnType<typeof createPictureFollower> {
176
+ follower.follow([]);
177
+ follower = createPictureFollower(options);
178
+ return follower;
179
+ }
180
+
181
+ export function followHelperRunPictures(folders: readonly string[]): void {
182
+ follower.follow(folders);
183
+ }
@@ -0,0 +1,215 @@
1
+ /**
2
+ * The pictures kept from helper runs, after the runs' folders are gone.
3
+ *
4
+ * Each picture a run made is kept once, reduced, under the config directory,
5
+ * 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.
8
+ */
9
+ import { createHash } from "node:crypto";
10
+ import { closeSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, statSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { writePrivateFile } from "../../config/access/write-private";
13
+ import { configDir } from "../../config/runtime/paths";
14
+ import { HISTORY_RETENTION_MS } from "../../sessions/support/common";
15
+ import { helperRunLink, type HelperRunLink } from "../links";
16
+
17
+ export type PictureMime = "image/png" | "image/jpeg" | "image/webp";
18
+
19
+ export type RunPicture = {
20
+ /** The first 24 hex of the sha256 of the picture as the run wrote it. */
21
+ hash: string;
22
+ /** The file name the run gave it. */
23
+ name: string;
24
+ /** Where the run wrote it, in the spelling the run's folder has. */
25
+ source: string;
26
+ mime: PictureMime;
27
+ /** Size of the kept copy. */
28
+ bytes: number;
29
+ capturedAt: number;
30
+ };
31
+
32
+ type StoredRun = { folder: string; pictures: RunPicture[] };
33
+ type Index = Map<string, StoredRun>;
34
+
35
+ export const MAX_KEPT_BYTES = 8 * 1024 * 1024;
36
+ const MAX_PICTURES_PER_RUN = 12;
37
+ const MAX_RUNS = 600;
38
+ const MAX_TOTAL_BYTES = 400 * 1024 * 1024;
39
+ const CHUNK_BYTES = 64 * 1024;
40
+ const HASH = /^[a-f0-9]{24}$/;
41
+ const IMAGE_ID = /^helper-image:([a-f0-9]{24}):([a-f0-9]{24})$/;
42
+ const EXTENSION: Record<PictureMime, string> = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp" };
43
+
44
+ export function picturesDirectory(): string {
45
+ return join(configDir(), "helper-run-pictures");
46
+ }
47
+
48
+ function indexPath(): string {
49
+ return join(picturesDirectory(), "index.json");
50
+ }
51
+
52
+ export function runKey(folder: string): string {
53
+ return createHash("sha256").update(folder).digest("hex").slice(0, 24);
54
+ }
55
+
56
+ export function pictureHash(bytes: Uint8Array): string {
57
+ return createHash("sha256").update(bytes).digest("hex").slice(0, 24);
58
+ }
59
+
60
+ function keptFile(key: string, picture: Pick<RunPicture, "hash" | "mime">): string {
61
+ return join(picturesDirectory(), `${key}-${picture.hash}.${EXTENSION[picture.mime]}`);
62
+ }
63
+
64
+ export function helperRunImageId(folder: string, hash: string): string {
65
+ return `helper-image:${runKey(folder)}:${hash}`;
66
+ }
67
+
68
+ export function isHelperRunImageId(id: string): boolean {
69
+ return id.startsWith("helper-image:");
70
+ }
71
+
72
+ /** The format the first bytes announce. */
73
+ export function pictureMime(header: Uint8Array): PictureMime | undefined {
74
+ const bytes = Buffer.from(header.buffer, header.byteOffset, header.byteLength);
75
+ if (bytes.length >= 8 && bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png";
76
+ if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
77
+ if (bytes.length >= 12 && bytes.toString("ascii", 0, 4) === "RIFF" && bytes.toString("ascii", 8, 12) === "WEBP") return "image/webp";
78
+ return undefined;
79
+ }
80
+
81
+ /** Whether a picture has been written to its end; a run's file is read while it may still be growing. */
82
+ export function pictureComplete(bytes: Uint8Array, mime: PictureMime): boolean {
83
+ const data = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
84
+ if (mime === "image/png") {
85
+ return data.length > 20 && data.subarray(-12).equals(Buffer.from([0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130]));
86
+ }
87
+ if (mime === "image/jpeg") {
88
+ const tail = data.subarray(-32);
89
+ for (let index = tail.length - 2; index >= 0; index--) if (tail[index] === 255 && tail[index + 1] === 217) return true;
90
+ return false;
91
+ }
92
+ return data.length >= 12 && data.readUInt32LE(4) + 8 === data.length;
93
+ }
94
+
95
+ function validPicture(value: unknown): RunPicture | undefined {
96
+ if (!value || typeof value !== "object") return undefined;
97
+ const item = value as Record<string, unknown>;
98
+ if (typeof item.hash !== "string" || !HASH.test(item.hash)) return undefined;
99
+ if (typeof item.name !== "string" || !item.name || item.name.length > 256) return undefined;
100
+ if (typeof item.source !== "string" || !item.source || item.source.length > 2_048) return undefined;
101
+ if (item.mime !== "image/png" && item.mime !== "image/jpeg" && item.mime !== "image/webp") return undefined;
102
+ if (typeof item.bytes !== "number" || !Number.isSafeInteger(item.bytes) || item.bytes <= 0
103
+ || item.bytes > MAX_KEPT_BYTES) return undefined;
104
+ if (typeof item.capturedAt !== "number" || !Number.isFinite(item.capturedAt)) return undefined;
105
+ return { hash: item.hash, name: item.name, source: item.source, mime: item.mime,
106
+ bytes: item.bytes, capturedAt: item.capturedAt };
107
+ }
108
+
109
+ function parseIndex(text: string): Index {
110
+ const index: Index = new Map();
111
+ const stored = JSON.parse(text) as { runs?: unknown };
112
+ for (const value of Array.isArray(stored.runs) ? stored.runs : []) {
113
+ if (!value || typeof value !== "object") continue;
114
+ const run = value as Record<string, unknown>;
115
+ if (typeof run.folder !== "string" || !run.folder || run.folder.length > 1_024) continue;
116
+ const pictures = (Array.isArray(run.pictures) ? run.pictures : []).map(validPicture)
117
+ .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 });
119
+ }
120
+ return index;
121
+ }
122
+
123
+ let cached: { path: string; stamp: string; index: Index } | undefined;
124
+
125
+ function readIndex(): Index {
126
+ const path = indexPath();
127
+ let stamp: string;
128
+ try {
129
+ const stat = statSync(path);
130
+ stamp = `${stat.mtimeMs}:${stat.size}`;
131
+ } catch {
132
+ return new Map();
133
+ }
134
+ if (cached?.path === path && cached.stamp === stamp) return cached.index;
135
+ let index: Index = new Map();
136
+ try { index = parseIndex(readFileSync(path, "utf8")); } catch { /* An unreadable index keeps nothing; the next picture rewrites it. */ }
137
+ cached = { path, stamp, index };
138
+ return index;
139
+ }
140
+
141
+ /** The pictures kept from the run in this folder, oldest first. */
142
+ export function helperRunPictures(folder: string | undefined): RunPicture[] {
143
+ return folder ? readIndex().get(runKey(folder))?.pictures ?? [] : [];
144
+ }
145
+
146
+ export function hasHelperRunPicture(folder: string, hash: string): boolean {
147
+ return helperRunPictures(folder).some((picture) => picture.hash === hash);
148
+ }
149
+
150
+ /** Drop runs older than history, then the oldest, until the store is within its bounds. */
151
+ function bounded(index: Index, now: number): { kept: Index; dropped: string[] } {
152
+ const runs = [...index.entries()].sort((left, right) =>
153
+ Math.max(...left[1].pictures.map((item) => item.capturedAt))
154
+ - Math.max(...right[1].pictures.map((item) => item.capturedAt)));
155
+ const dropped: string[] = [];
156
+ let total = runs.reduce((sum, [, run]) => sum + run.pictures.reduce((inner, item) => inner + item.bytes, 0), 0);
157
+ while (runs.length > 0) {
158
+ const [key, run] = runs[0]!;
159
+ const newest = Math.max(...run.pictures.map((item) => item.capturedAt));
160
+ if (newest >= now - HISTORY_RETENTION_MS && runs.length <= MAX_RUNS && total <= MAX_TOTAL_BYTES) break;
161
+ runs.shift();
162
+ for (const picture of run.pictures) {
163
+ total -= picture.bytes;
164
+ dropped.push(keptFile(key, picture));
165
+ }
166
+ }
167
+ return { kept: new Map(runs), dropped };
168
+ }
169
+
170
+ /** Keep one reduced picture from the run in this folder. Returns whether it was new. */
171
+ export function keepHelperRunPicture(folder: string, picture: Omit<RunPicture, "bytes">,
172
+ bytes: Uint8Array, now = Date.now()): boolean {
173
+ if (!HASH.test(picture.hash) || bytes.length === 0 || bytes.length > MAX_KEPT_BYTES) return false;
174
+ if (pictureMime(bytes.subarray(0, 12)) !== picture.mime) return false;
175
+ let index: Index = new Map();
176
+ try { index = parseIndex(readFileSync(indexPath(), "utf8")); } catch { /* Nothing kept yet. */ }
177
+ const key = runKey(folder);
178
+ const run = index.get(key) ?? { folder, pictures: [] };
179
+ if (run.pictures.some((item) => item.hash === picture.hash) || run.pictures.length >= MAX_PICTURES_PER_RUN) return false;
180
+ mkdirSync(picturesDirectory(), { recursive: true, mode: 0o700 });
181
+ const kept: RunPicture = { ...picture, bytes: bytes.length };
182
+ writePrivateFile(keptFile(key, kept), bytes);
183
+ index.set(key, { folder, pictures: [...run.pictures, kept] });
184
+ 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 })) }));
187
+ for (const file of dropped) rmSync(file, { force: true });
188
+ cached = undefined;
189
+ return stored.get(key)?.pictures.some((item) => item.hash === picture.hash) === true;
190
+ }
191
+
192
+ /** Read one bounded chunk of a kept picture for the chat that started its run, and for no other. */
193
+ export function helperRunPictureChunk(chatId: string, imageId: string, offset: number,
194
+ link: (folder: string) => HelperRunLink | undefined = helperRunLink) {
195
+ const match = IMAGE_ID.exec(imageId);
196
+ if (!match || !Number.isSafeInteger(offset) || offset < 0) return undefined;
197
+ const [, key, hash] = match as unknown as [string, string, string];
198
+ const run = readIndex().get(key);
199
+ const picture = run?.pictures.find((item) => item.hash === hash);
200
+ if (!run || !picture || link(run.folder)?.parentSessionId !== chatId) return undefined;
201
+ let fd: number | undefined;
202
+ try {
203
+ fd = openSync(keptFile(key, picture), "r");
204
+ const size = fstatSync(fd).size;
205
+ if (size <= offset || size > MAX_KEPT_BYTES) return undefined;
206
+ const bytes = Buffer.alloc(Math.min(CHUNK_BYTES, size - offset));
207
+ if (readSync(fd, bytes, 0, bytes.length, offset) !== bytes.length) return undefined;
208
+ if (offset === 0 && pictureMime(bytes.subarray(0, 12)) !== picture.mime) return undefined;
209
+ return { mime_type: picture.mime, total_bytes: size, offset, data_base64: bytes.toString("base64") };
210
+ } catch {
211
+ return undefined;
212
+ } finally {
213
+ if (fd !== undefined) closeSync(fd);
214
+ }
215
+ }
@@ -1,6 +1,7 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { promisify } from "node:util";
3
3
  import { recordCommandProcessSample } from "../command-process/history";
4
+ import { captureHelperRuns, helperRunProcesses } from "../../helper-runs/capture";
4
5
  import { sampleProcessRows } from "./ps-reader";
5
6
  import { attributeByAncestry, processDetail, processGroupName } from "./process-ownership";
6
7
  export { executableOf, processGroupName, processDetail } from "./process-ownership";
@@ -224,6 +225,8 @@ export async function sampleAgentProcesses(): Promise<Record<string, AgentProces
224
225
  const sampledAt = Date.now();
225
226
  const sessions = await resolveSessions(rows);
226
227
  const ownership = attributeByAncestry(rows);
228
+ // A helper run lives for half a minute; this sample may be the only one that sees its process.
229
+ await captureHelperRuns(helperRunProcesses(rows, ownership, sessions));
227
230
  recordCommandProcessSample(rows.flatMap((row) => {
228
231
  const agent = ownership.agents.get(row.pid);
229
232
  if (!agent) return [];
@@ -20,6 +20,7 @@ import type { MeshStore } from "../store";
20
20
  import { queueProjectBindingSync } from "../../engine/runtime/engine-projects";
21
21
  import { isCursorTaskCloneId } from "../../sessions/cursor/catalog";
22
22
  import { localTaskTransfers } from '../../task-transfer';
23
+ import { helperRunFolder } from '../../helper-runs';
23
24
  export { inspectRepositoryAsync, inspectWorkingTreeAsync, readRepositoryGit } from "./repository-inspection";
24
25
  export { prepareMonitorInspection } from "./monitor-inspection";
25
26
  import type { CatalogInspection } from "./monitor-inspection";
@@ -171,7 +172,8 @@ function linkSession(input: {
171
172
  const { store, session, computerId, inspect } = input;
172
173
  const agent = provider(session.agent);
173
174
  const cwd = session.cwd?.trim();
174
- if (!agent || !cwd) return session;
175
+ // A generator's throwaway folder is not a workspace: registering it minted a Mesh per run.
176
+ if (!agent || !cwd || helperRunFolder(cwd)) return session;
175
177
  const knownTaskId = store.taskForExecution(computerId, agent, session.sessionId);
176
178
  const knownProjectId = knownTaskId ? store.task(knownTaskId)?.projectId : undefined;
177
179
  const previous = knownProjectId ? store.snapshot(knownProjectId)?.executions.find(row =>
@@ -34,6 +34,7 @@ import { restoreHandoffResult, validStoredReceipt } from './receipts';
34
34
  import {
35
35
  projectCapabilityRequests,
36
36
  } from "../catalog/project/requests";
37
+ import { helperRunProject } from "../../helper-runs";
37
38
 
38
39
  export class MeshStore extends MeshPreparedStore {
39
40
  recordReceipt(input: ReceiptValue): void {
@@ -266,9 +267,10 @@ export class MeshStore extends MeshPreparedStore {
266
267
  return this.state.events.filter((event) => event.projectId === projectId);
267
268
  }
268
269
 
270
+ /** One registered for a helper run's throwaway folder, before such runs were recognised, is kept but not listed. */
269
271
  projectIds(): string[] {
270
272
  this.sync();
271
- return this.state.projects.map((project) => project.projectId);
273
+ return this.state.projects.filter((project) => !helperRunProject(project)).map((project) => project.projectId);
272
274
  }
273
275
 
274
276
  workspaceForRepository(canonicalRepositoryId: string, computerId?: string): string | undefined {
@@ -7,6 +7,9 @@ The reader checks the requested image against that conversation's page. Workspac
7
7
  artifacts retain the desktop reader's execution/workspace checks. Native user
8
8
  pictures are read only from that conversation's provider transcript.
9
9
 
10
+ A picture kept from a helper run (`helper-image:` ids) is read from the run
11
+ picture store in `../helper-runs`, for the chat that started the run only.
12
+
10
13
  Unavailable sources produce an explicit reply; they do not change pairing or
11
14
  account state. Apple clients retain validated original bytes locally and use
12
15
  their scoped copy when offline. Tests live in `tests/`.
@@ -7,6 +7,7 @@ import { publishedSession } from '../session-catalog';
7
7
  import { cachedSessionActivity } from '../monitor/support/session-activity';
8
8
  import { findSessionCooperatively } from '../sessions';
9
9
  import { sessionImageChunk, transcriptImages } from '../../../mcp/src/desktop/image';
10
+ import { helperRunPictureChunk, isHelperRunImageId } from '../helper-runs/pictures/store';
10
11
 
11
12
  export function activityWithImages(activity: SessionActivity): SessionActivity {
12
13
  return { ...activity, entries: activity.entries.map((entry: ActivityEntry) => {
@@ -24,11 +25,10 @@ export function readSessionImage(query: SessionImageQuery, session: SessionInfo,
24
25
 
25
26
  export async function publishSessionImage(client: RelayClient, query: SessionImageQuery,
26
27
  peerPublicKey?: string): Promise<boolean> {
27
- const session = publishedSession(client, query.sessionId)
28
- ?? await findSessionCooperatively(query.sessionId);
29
- const activity = session ? readTranscriptHistory(session, query.historyCursor)
30
- ?? cachedSessionActivity(session) : undefined;
31
- const chunk = session && activity ? readSessionImage(query, session, activity) : undefined;
28
+ const chunk = isHelperRunImageId(query.imageId)
29
+ // A picture kept from a helper run, offered only to the chat that started the run.
30
+ ? helperRunPictureChunk(query.sessionId, query.imageId, query.offset)
31
+ : await transcriptImageChunk(client, query);
32
32
  await sendSessionPayload(client, SessionImageChunk.parse({ type: 'session.image.chunk', sessionId: query.sessionId,
33
33
  requestId: query.requestId, imageId: query.imageId, offset: query.offset,
34
34
  ...(chunk ? { mimeType: chunk.mime_type, totalBytes: chunk.total_bytes,
@@ -36,3 +36,11 @@ export async function publishSessionImage(client: RelayClient, query: SessionIma
36
36
  'phone', { ttlMs: 20_000, reliable: false, peerPublicKey });
37
37
  return chunk !== undefined;
38
38
  }
39
+
40
+ async function transcriptImageChunk(client: RelayClient, query: SessionImageQuery) {
41
+ const session = publishedSession(client, query.sessionId)
42
+ ?? await findSessionCooperatively(query.sessionId);
43
+ const activity = session ? readTranscriptHistory(session, query.historyCursor)
44
+ ?? cachedSessionActivity(session) : undefined;
45
+ return session && activity ? readSessionImage(query, session, activity) : undefined;
46
+ }
@@ -2,6 +2,7 @@ import type { SessionInfo } from "../../../../packages/protocol/schema";
2
2
  import { localTaskTransfers, localTransferContinuations } from "../task-transfer";
3
3
  import { MAX_FILES, MAX_HISTORY, MAX_LIVE, TOKEN_WINDOW_MS } from "./support/common";
4
4
  import { providerScans, cooperativeProviderScans, type ProviderScan } from "./provider-discovery";
5
+ import { attachHelperRuns } from "../helper-runs";
5
6
 
6
7
  function sessionKey(session: SessionInfo): string {
7
8
  return `${session.agent}\0${session.sessionId}`;
@@ -48,7 +49,9 @@ function pickWithReserve(
48
49
  }
49
50
 
50
51
  function catalogFromScans(scans: ProviderScan[]) {
51
- const native = sortedUniqueSessions(scans.flatMap((scan) => scan.sessions));
52
+ // A helper run is a conversation of the chat that started it, never a chat in these lists.
53
+ const native = attachHelperRuns(sortedUniqueSessions(scans.flatMap((scan) => scan.sessions)),
54
+ scans.flatMap((scan) => scan.helperRuns ?? []));
52
55
  // Prepared transfers replace native ids; rank their native activity before
53
56
  // the bounded live/history windows, rather than appending them after older chats.
54
57
  const sessions = sortedUniqueSessions(localTaskTransfers().catalog(native));
@@ -22,6 +22,7 @@ import { grokTimeline } from '../../providers/grok-timeline';
22
22
  import { grokToolCalls, grokToolCompletions, grokToolSummary, grokRecordedChanges } from '../../providers/grok-tools';
23
23
  import { captureGrokConversation, readGrokConversation } from '../../providers/grok-conversation';
24
24
  import { GrokCatalogCache, type GrokParsedContext } from '../../providers/grok-catalog-cache';
25
+ import { helperRunFolder, type HelperRunSession } from '../../helper-runs';
25
26
 
26
27
  type Summary = {
27
28
  info?: { id?: unknown; cwd?: unknown };
@@ -30,6 +31,7 @@ type Summary = {
30
31
  created_at?: unknown;
31
32
  updated_at?: unknown;
32
33
  current_model_id?: unknown;
34
+ session_kind?: unknown;
33
35
  };
34
36
 
35
37
  const catalogCache = new GrokCatalogCache();
@@ -172,6 +174,7 @@ function parseSummary(path: string): Summary | null {
172
174
 
173
175
  export function scanGrok(maxFiles = MAX_FILES): Scan {
174
176
  const sessions: SessionInfo[] = [];
177
+ const helperRuns: HelperRunSession[] = [];
175
178
  const activities = new Map<string, ActivityEntry[]>();
176
179
  const usages = new Map<string, CapabilityObservation[]>();
177
180
  let tokensRecent = 0;
@@ -202,14 +205,18 @@ export function scanGrok(maxFiles = MAX_FILES): Scan {
202
205
  .find((value): value is string => typeof value === "string" && value.trim().length > 0);
203
206
  const cwd = typeof summary.info?.cwd === "string" ? summary.info.cwd : undefined;
204
207
  const live = grokNativeActivity(sessionId, directory);
205
- sessions.push({
208
+ // A generator's headless run in its throwaway folder is its chat's work, not a chat.
209
+ const helper = summary.session_kind === "headless" ? helperRunFolder(cwd) : undefined;
210
+ const session: SessionInfo = {
206
211
  sessionId, agent: "grok", title: title?.trim().slice(0, 120), cwd,
207
212
  model: typeof summary.current_model_id === "string" ? summary.current_model_id : undefined,
208
213
  state: live?.state ?? stateFor(updatedAt), startedAt, lastActivityAt: Math.max(updatedAt, live?.updatedAt ?? 0),
209
214
  ...(parsed.lastMessageAt ? { lastMessageAt: parsed.lastMessageAt } : {}),
210
215
  tokensSession: parsed.tokens, tokensLastTurn: parsed.lastTurn,
211
216
  contextTokensUsed: parsed.tokens,
212
- });
217
+ };
218
+ if (helper) helperRuns.push({ session, kind: helper.kind, label: helper.label, folder: helper.folder });
219
+ else sessions.push(session);
213
220
  logPaths.set(sessionId, join(directory, "chat_history.jsonl"));
214
221
  activities.set(sessionId, parsed.entries);
215
222
  usages.set(sessionId, parsed.usage);
@@ -218,7 +225,8 @@ export function scanGrok(maxFiles = MAX_FILES): Scan {
218
225
  activityBySession = activities;
219
226
  catalogCache.retain(admitted);
220
227
  usageBySession = usages;
221
- return { sessions, tokensRecent, sourceLimited: listed.length > maxFiles };
228
+ return { sessions, tokensRecent, sourceLimited: listed.length > maxFiles,
229
+ ...(helperRuns.length > 0 ? { helperRuns } : {}) };
222
230
  }
223
231
 
224
232
  export function grokActivity(session: SessionInfo, fullText = false): ActivityEntry[] {
@@ -5,6 +5,7 @@ import { claudeThreadActivity } from './scan/claude/threads';
5
5
  import { codexActivity } from './scan/codex';
6
6
  import { cursorActivity } from './cursor';
7
7
  import { grokActivity } from './scan/grok';
8
+ import { helperRunEntries, helperRunThread } from '../helper-runs';
8
9
 
9
10
  export function activityForSession(input: SessionInfo): ActivityEntry[] {
10
11
  const session = localTaskTransfers().nativeSession(input);
@@ -20,7 +21,10 @@ export const MAX_THREAD_ENTRIES = 60;
20
21
  /** Read one nested conversation with a bounded native window, newest last. */
21
22
  export function scanThreadActivity(input: SessionInfo, threadId: string): SessionActivity {
22
23
  const session = localTaskTransfers().nativeSession(input);
23
- const all = session.agent === 'claude' ? claudeThreadActivity(session, threadId) : activityForSession(input);
24
+ // A helper run is another provider's session; its messages are read from there.
25
+ const run = helperRunThread(input, threadId);
26
+ const all = run ? helperRunEntries(run.child, activityForSession(run.session), run.folder)
27
+ : session.agent === 'claude' ? claudeThreadActivity(session, threadId) : activityForSession(input);
24
28
  const entries = all.filter(entry => entry.childThreadId === threadId)
25
29
  .sort((a, b) => a.createdAt - b.createdAt).slice(-MAX_THREAD_ENTRIES);
26
30
  return { type: 'session.activity', sessionId: input.sessionId, agent: input.agent,
@@ -25,6 +25,8 @@ export type Scan = {
25
25
  sessions: import("../../../../../packages/protocol/schema").SessionInfo[];
26
26
  tokensRecent: number;
27
27
  sourceLimited?: boolean;
28
+ /** Short runs a chat started, kept out of `sessions`: they are shown under that chat. */
29
+ helperRuns?: import("../../helper-runs").HelperRunSession[];
28
30
  };
29
31
 
30
32
  /**
@@ -4,6 +4,7 @@ import type { ActivityEntry, SessionInfo, SessionActivity } from '../../../../..
4
4
  import { nativeTranscriptImage, nativeTranscriptEntry } from '../../../../bridge/src/transcript-history';
5
5
  import { readStoreState } from '../../../../bridge/src/mesh/store/state';
6
6
  import { configDir } from '../../../../bridge/src/config';
7
+ import { helperRunPictureChunk, isHelperRunImageId } from '../../../../bridge/src/helper-runs/pictures/store';
7
8
  import { join } from 'node:path';
8
9
 
9
10
  export function transcriptImages(entry: ActivityEntry) {
@@ -57,6 +58,11 @@ export function desktopTaskImage(input: unknown, storePath?: string,
57
58
  || activity.project_id !== query.project_id || activity.task_id !== query.task_id) return undefined;
58
59
  const session: SessionInfo = { sessionId: activity.session_id, agent: activity.agent,
59
60
  state: "idle", startedAt: 0, lastActivityAt: 0, tokensSession: 0, tokensLastTurn: 0 };
61
+ if (isHelperRunImageId(imageId)) {
62
+ // A picture kept from a helper run this Task's chat started.
63
+ const chunk = helperRunPictureChunk(activity.session_id, imageId, offset);
64
+ return chunk ? { operation: "desktop.task_image", image_id: imageId, ...chunk } : undefined;
65
+ }
60
66
  const cursor = query.history_cursor;
61
67
  if (cursor !== undefined && (typeof cursor !== "string" || cursor.length > 512)) return undefined;
62
68
  const artifact = sessionArtifact(session, activity, imageId, cursor as string | undefined);
@@ -10,7 +10,7 @@ keeps each phone response tied to the exact originating chat and prompt.
10
10
  Install the supported CLI on this computer, then run:
11
11
 
12
12
  ```bash
13
- npm install -g granttap-mcp@0.8.173
13
+ npm install -g granttap-mcp@0.8.175
14
14
  granttap setup
15
15
  granttap status
16
16
  ```
@@ -4,7 +4,7 @@
4
4
  "command": "node",
5
5
  "args": [
6
6
  "-e",
7
- "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.173\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
7
+ "\"use strict\";\n\n// Cursor may start this MCP from any cwd. Execute JavaScript entry points with\n// Node itself: Windows batch shims require shell quoting that differs by host.\nconst { spawn } = require(\"node:child_process\");\nconst { existsSync } = require(\"node:fs\");\nconst { delimiter, dirname, join } = require(\"node:path\");\n\nconst PACKAGE = \"granttap-mcp@0.8.175\";\nconst dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === \"1\";\nconst platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM\n ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;\nconst nodeRoot = dryRun && process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT\n ? process.env.GRANTTAP_BOOTSTRAP_NODE_ROOT : dirname(process.execPath);\nconst pathRoots = (process.env.PATH || \"\").split(delimiter).filter(Boolean);\nconst appData = process.env.APPDATA;\nconst roots = [nodeRoot, ...pathRoots, ...(appData ? [join(appData, \"npm\")] : [])];\nconst first = (paths) => paths.find((path) => existsSync(path));\n\nfunction launch() {\n if (platform !== \"win32\") {\n const installed = first(roots.map((root) => join(root, \"granttap-mcp\")));\n if (installed) return { command: installed, args: [] };\n const npx = first(roots.map((root) => join(root, \"npx\"))) || \"npx\";\n return { command: npx, args: [\"-y\", PACKAGE] };\n }\n const installed = first(roots.map((root) =>\n join(root, \"node_modules\", \"granttap-mcp\", \"bin\", \"granttap-mcp.mjs\")));\n if (installed) return { command: process.execPath, args: [installed] };\n const npx = first(roots.map((root) =>\n join(root, \"node_modules\", \"npm\", \"bin\", \"npx-cli.js\")));\n if (npx) return { command: process.execPath, args: [npx, \"-y\", PACKAGE] };\n throw new Error(\"Node.js/npm 22.13.0+ is required on this Windows device. Install npm and retry GrantTap.\");\n}\n\nlet target;\ntry { target = launch(); }\ncatch (error) {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n}\n\nif (dryRun) {\n process.stdout.write(JSON.stringify(target));\n process.exit(0);\n}\n\nconst child = spawn(target.command, target.args, { stdio: \"inherit\", windowsHide: true });\nchild.on(\"error\", (error) => {\n process.stderr.write(`[granttap] ${error.message}\\n`);\n process.exit(1);\n});\nchild.on(\"exit\", (code, signal) => {\n if (signal && platform !== \"win32\") {\n try { process.kill(process.pid, signal); } catch { process.exit(code ?? 1); }\n return;\n }\n process.exit(code ?? 1);\n});\n"
8
8
  ]
9
9
  }
10
10
  }
@@ -7,7 +7,7 @@ const { spawn } = require("node:child_process");
7
7
  const { existsSync } = require("node:fs");
8
8
  const { delimiter, dirname, join } = require("node:path");
9
9
 
10
- const PACKAGE = "granttap-mcp@0.8.173";
10
+ const PACKAGE = "granttap-mcp@0.8.175";
11
11
  const dryRun = process.env.GRANTTAP_BOOTSTRAP_DRY_RUN === "1";
12
12
  const platform = dryRun && process.env.GRANTTAP_BOOTSTRAP_PLATFORM
13
13
  ? process.env.GRANTTAP_BOOTSTRAP_PLATFORM : process.platform;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "granttap-mcp",
3
- "version": "0.8.173",
3
+ "version": "0.8.175",
4
4
  "description": "Commercial computer runtime connecting local coding agents to GrantTap on Mac, iPhone, iPad and Apple Watch.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -23,6 +23,19 @@ export const ChildThreadInfo = z.object({
23
23
  parentThreadId: z.string().max(256),
24
24
  title: z.string().max(160).optional(),
25
25
  agentName: z.string().max(160).optional(),
26
+ /**
27
+ * Set when the conversation is a short helper run the chat started, not one of its own agents:
28
+ * `image-generation`. A value this reader does not know is still a helper run.
29
+ */
30
+ kind: z.string().min(1).max(40).optional(),
31
+ /**
32
+ * Pictures a helper run made, kept by the computer after the run's folder is gone.
33
+ * Read with `session.image.query` on the parent chat, like a message's pictures.
34
+ */
35
+ images: z.array(z.object({
36
+ id: z.string().min(1).max(512), name: z.string().min(1).max(256),
37
+ markdown: z.string().min(1).max(2400),
38
+ })).max(12).optional(),
26
39
  depth: z.number().int().min(1).max(16),
27
40
  state: SessionState,
28
41
  startedAt: z.number(),