granttap-mcp 0.8.174 → 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 {
@@ -28,6 +28,21 @@ clock and spend alone. Opening the conversation reads the run's own messages.
28
28
  A run whose parent was not captured, or whose parent is no longer on this
29
29
  computer, is published nowhere; the provider's own history still has it.
30
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
+
31
46
  **Meshes.** A generator's folder never registers a Mesh. Meshes registered for
32
47
  such folders before runs were recognised stay in the Mesh store and are left
33
48
  out of every list of this computer's Projects.
@@ -9,6 +9,7 @@
9
9
  import type { ActivityEntry, ChildThreadInfo, SessionInfo } from "../../../../packages/protocol/schema";
10
10
  import { boundChildThreads, childEntryFields, childTitle } from "../sessions/support/child-threads";
11
11
  import { helperRunLink, type HelperRunLink } from "./links";
12
+ import { helperRunImageId, helperRunPictures, type RunPicture } from "./pictures/store";
12
13
 
13
14
  /** A provider session a scanner recognised as a helper run and kept out of its chats. */
14
15
  export type HelperRunSession = {
@@ -24,10 +25,29 @@ function sessionKey(agent: string, sessionId: string): string {
24
25
  }
25
26
 
26
27
  /** The runs attached by the newest catalog, so a run's conversation can be read when a phone opens it. */
27
- let attached = new Map<string, SessionInfo>();
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
+ }
28
47
 
29
48
  function childOf(parent: SessionInfo, run: HelperRunSession): ChildThreadInfo {
30
49
  const { session } = run;
50
+ const images = helperRunPictures(run.folder).map((picture) => pictureImage(run.folder, picture));
31
51
  return {
32
52
  threadId: session.sessionId,
33
53
  parentThreadId: parent.sessionId,
@@ -40,6 +60,7 @@ function childOf(parent: SessionInfo, run: HelperRunSession): ChildThreadInfo {
40
60
  lastActivityAt: session.lastActivityAt,
41
61
  tokensSession: session.tokensSession,
42
62
  tokensLastTurn: session.tokensLastTurn,
63
+ ...(images.length > 0 ? { images } : {}),
43
64
  };
44
65
  }
45
66
 
@@ -54,14 +75,14 @@ export function attachHelperRuns(
54
75
  ): SessionInfo[] {
55
76
  const parents = new Map(sessions.map((session) => [sessionKey(session.agent, session.sessionId), session]));
56
77
  const children = new Map<string, ChildThreadInfo[]>();
57
- const read = new Map<string, SessionInfo>();
78
+ const read = new Map<string, { session: SessionInfo; folder: string }>();
58
79
  for (const run of runs) {
59
80
  const known = link(run.folder);
60
81
  const key = known ? sessionKey(known.parentAgent, known.parentSessionId) : undefined;
61
82
  const parent = key ? parents.get(key) : undefined;
62
83
  if (!key || !parent) continue;
63
84
  children.set(key, [...(children.get(key) ?? []), childOf(parent, run)]);
64
- read.set(run.session.sessionId, run.session);
85
+ read.set(run.session.sessionId, { session: run.session, folder: run.folder });
65
86
  }
66
87
  attached = read;
67
88
  if (children.size === 0) return sessions;
@@ -75,17 +96,31 @@ export function attachHelperRuns(
75
96
  export function helperRunThread(
76
97
  parent: SessionInfo,
77
98
  threadId: string,
78
- ): { child: ChildThreadInfo; session: SessionInfo } | undefined {
99
+ ): { child: ChildThreadInfo; session: SessionInfo; folder?: string } | undefined {
79
100
  const child = parent.childThreads?.find((item) => item.threadId === threadId && item.kind);
80
101
  if (!child) return undefined;
81
- const session = attached.get(threadId) ?? {
102
+ const known = attached.get(threadId);
103
+ if (known) return { child, ...known };
104
+ const session: SessionInfo = {
82
105
  sessionId: threadId, agent: "grok", state: child.state, startedAt: child.startedAt,
83
106
  lastActivityAt: child.lastActivityAt, tokensSession: child.tokensSession, tokensLastTurn: child.tokensLastTurn,
84
107
  };
85
108
  return { child, session };
86
109
  }
87
110
 
88
- /** A run's own messages, marked as the nested conversation they are shown in. */
89
- export function helperRunEntries(child: ChildThreadInfo, entries: readonly ActivityEntry[]): ActivityEntry[] {
90
- return entries.map((entry) => ({ ...entry, ...childEntryFields(child) }));
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);
91
126
  }
@@ -13,6 +13,7 @@ import { promisify } from "node:util";
13
13
  import type { ProcessRow } from "../machine-load/host/process-sampler";
14
14
  import { helperRunFolder, helperRunFoldersNamed, type HelperRunFolder } from "./kinds";
15
15
  import { rememberHelperRunLinks, type HelperRunLink, type HelperRunParentAgent } from "./links";
16
+ import { followHelperRunPictures } from "./pictures/capture";
16
17
 
17
18
  const run = promisify(execFile);
18
19
 
@@ -112,6 +113,8 @@ export function helperRunProcesses(
112
113
  type CaptureOptions = {
113
114
  readers?: HelperRunReaders;
114
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;
115
118
  now?: () => number;
116
119
  };
117
120
 
@@ -119,9 +122,12 @@ type CaptureOptions = {
119
122
  export function createHelperRunCapture(options: CaptureOptions = {}) {
120
123
  const readers = options.readers ?? { directories: readProcessDirectories, parents: readProcessParents };
121
124
  const remember = options.remember ?? rememberHelperRunLinks;
125
+ const follow = options.follow ?? followHelperRunPictures;
122
126
  const now = options.now ?? Date.now;
123
127
  const settled = new Set<number>();
124
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>();
125
131
 
126
132
  const folderOf = (item: HelperRunProcess, directory: string | undefined): HelperRunFolder | undefined => {
127
133
  const working = helperRunFolder(directory);
@@ -134,6 +140,7 @@ export function createHelperRunCapture(options: CaptureOptions = {}) {
134
140
  const live = new Set(processes.map((item) => item.pid));
135
141
  for (const pid of [...settled]) if (!live.has(pid)) settled.delete(pid);
136
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);
137
144
  const fresh = processes.filter((item) => !settled.has(item.pid));
138
145
  if (fresh.length === 0) return 0;
139
146
  const directories = await readers.directories(fresh.map((item) => item.pid));
@@ -153,6 +160,7 @@ export function createHelperRunCapture(options: CaptureOptions = {}) {
153
160
  settled.add(item.pid);
154
161
  const parent = parents.get(item.pid) ?? item.ancestor;
155
162
  if (parent) {
163
+ running.set(item.pid, folder.folder);
156
164
  links.push({ folder: folder.folder, kind: folder.kind, parentAgent: parent.agent,
157
165
  parentSessionId: parent.sessionId, capturedAt: now() });
158
166
  }
@@ -161,7 +169,10 @@ export function createHelperRunCapture(options: CaptureOptions = {}) {
161
169
  };
162
170
 
163
171
  return async (processes: readonly HelperRunProcess[]): Promise<number> => {
164
- try { return await examine(processes); } catch { return 0; }
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;
165
176
  };
166
177
  }
167
178
 
@@ -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
+ }
@@ -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
+ }
@@ -23,7 +23,7 @@ export function scanThreadActivity(input: SessionInfo, threadId: string): Sessio
23
23
  const session = localTaskTransfers().nativeSession(input);
24
24
  // A helper run is another provider's session; its messages are read from there.
25
25
  const run = helperRunThread(input, threadId);
26
- const all = run ? helperRunEntries(run.child, activityForSession(run.session))
26
+ const all = run ? helperRunEntries(run.child, activityForSession(run.session), run.folder)
27
27
  : session.agent === 'claude' ? claudeThreadActivity(session, threadId) : activityForSession(input);
28
28
  const entries = all.filter(entry => entry.childThreadId === threadId)
29
29
  .sort((a, b) => a.createdAt - b.createdAt).slice(-MAX_THREAD_ENTRIES);
@@ -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.174
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.174\";\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.174";
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.174",
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": {
@@ -28,6 +28,14 @@ export const ChildThreadInfo = z.object({
28
28
  * `image-generation`. A value this reader does not know is still a helper run.
29
29
  */
30
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(),
31
39
  depth: z.number().int().min(1).max(16),
32
40
  state: SessionState,
33
41
  startedAt: z.number(),