worktrust 0.10.37 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +43 -18
  2. package/README.md +59 -2
  3. package/SECURITY.md +25 -0
  4. package/chat-exports.mjs +20 -20
  5. package/engine-release.json +1 -1
  6. package/export-facts.mjs +71 -0
  7. package/log-session.mjs +15 -15
  8. package/package-release.json +1 -1
  9. package/package.json +36 -2
  10. package/remote-adapter-claude-code.mjs +111 -0
  11. package/remote-adapter-codex.mjs +119 -0
  12. package/remote-approval-bridge.mjs +122 -0
  13. package/remote-approvals.mjs +124 -0
  14. package/remote-attachments.mjs +129 -0
  15. package/remote-changes.mjs +94 -0
  16. package/remote-claude-events.mjs +212 -0
  17. package/remote-claude-progress.mjs +328 -0
  18. package/remote-cli.mjs +325 -0
  19. package/remote-coalesce.mjs +40 -0
  20. package/remote-codex-events.mjs +153 -0
  21. package/remote-daemon.mjs +205 -0
  22. package/remote-inventory.mjs +132 -0
  23. package/remote-journal.mjs +155 -0
  24. package/remote-pairing.mjs +104 -0
  25. package/remote-pipeline-config.mjs +177 -0
  26. package/remote-pipeline-parsers.mjs +121 -0
  27. package/remote-pipeline.mjs +234 -0
  28. package/remote-policy.mjs +199 -0
  29. package/remote-preview.mjs +146 -0
  30. package/remote-projects.mjs +87 -0
  31. package/remote-protocol.mjs +3881 -0
  32. package/remote-qr.mjs +175 -0
  33. package/remote-release-plans.mjs +88 -0
  34. package/remote-releases.mjs +297 -0
  35. package/remote-run.mjs +174 -0
  36. package/remote-service.mjs +101 -0
  37. package/remote-session-list.mjs +25 -0
  38. package/remote-sessions.mjs +348 -0
  39. package/remote-steered.mjs +114 -0
  40. package/remote-steering.mjs +97 -0
  41. package/remote-store.mjs +123 -0
  42. package/remote-transport.mjs +88 -0
  43. package/worktrust.mjs +13 -6
@@ -0,0 +1,124 @@
1
+ /**
2
+ * APPROVALS ON THE COMPUTER: CLASSIFIED HERE, DECIDED ONCE, FAIL CLOSED (2026-11-07; owner decision 6).
3
+ *
4
+ * Claude Code's permission-prompt tool (remote-approval-bridge.mjs) asks over a local socket in ~/.worktrust/remote/run/
5
+ * (this user only) with its session's one-time token. Each request is classified by remote-policy.mjs. Only a class
6
+ * `phoneMayDecide` admits becomes an agent.approval_required for the phone, with the exact input and its action hash;
7
+ * every other request is denied here at once and the phone is told why (an agent.output_delta on the tool stream). Then:
8
+ * - a signed decision counts only from a CONFIRMED phone, for a pending approval, bound to its hash, in time, of an
9
+ * approvable class (verifyApprovalDecision), and is spent in the journal BEFORE the agent hears it;
10
+ * - no phone online means deny; no decision in five minutes means deny; a daemon that stops denies everything open.
11
+ * This file is the only place that may send agent.approval_required (scripts/check-remote-cli.mjs holds it). The same
12
+ * socket takes the session's planning calls (`{ token, plan: { op, args } }`, 2026-11-08) and hands them to ctx.plan,
13
+ * the release queue's: they never reach the approval path and never run anything.
14
+ */
15
+ import { createServer } from "node:net";
16
+ import { chmodSync, existsSync, mkdirSync, rmSync } from "node:fs";
17
+ import { join } from "node:path";
18
+ import * as P from "./remote-protocol.mjs";
19
+ import { classifyAction, phoneMayDecide } from "./remote-policy.mjs";
20
+
21
+ export const APPROVAL_LIFETIME_MS = 5 * 60_000;
22
+
23
+ export function createApprovals(ctx) {
24
+ const byToken = new Map(); // token -> session
25
+ const pending = new Map(); // approval_id -> { record, resolve, timer, session_id }
26
+ let server = null;
27
+
28
+ const deny = (message) => ({ behavior: "deny", message });
29
+ const finish = (approvalId, answer) => {
30
+ const open = pending.get(approvalId);
31
+ if (!open) return;
32
+ pending.delete(approvalId);
33
+ clearTimeout(open.timer);
34
+ open.resolve(answer);
35
+ ctx.onApprovalSettled?.(open.session_id, approvalId);
36
+ };
37
+
38
+ /** One permission request from the bridge → the answer the bridge gives Claude Code. */
39
+ async function request(session, toolName, input) {
40
+ if (ctx.paused()) return deny("WorkTrust remote is paused on this computer; denied");
41
+ const { action, reason } = classifyAction(session.adapter, toolName, input, session.projectPath);
42
+ if (!phoneMayDecide(action)) {
43
+ ctx.emit(session.session_id, "agent.output_delta", { stream: "tool", offset: 0, text: `Denied on the computer (${action.tool}): ${reason}` }, session.command_id);
44
+ return deny(`WorkTrust remote: ${reason}`);
45
+ }
46
+ if (!ctx.phoneOnline()) return deny("WorkTrust remote: no confirmed phone is connected; denied");
47
+ const approval_id = P.mintId("apr", ctx.random), expires_at = ctx.now() + APPROVAL_LIFETIME_MS;
48
+ const action_hash = P.actionHash({ approval_id, session_id: session.session_id, project_id: session.project_id, adapter: session.adapter }, action);
49
+ const record = { approval_id, session_id: session.session_id, computer_device_id: ctx.deviceId, action_hash, class: action.class, expires_at };
50
+ const answer = new Promise((resolve) => {
51
+ const timer = setTimeout(() => finish(approval_id, deny("WorkTrust remote: no decision in time; denied")), Math.max(0, expires_at - ctx.now()));
52
+ pending.set(approval_id, { record, resolve, timer, session_id: session.session_id, input });
53
+ });
54
+ ctx.onApprovalOpened?.(session.session_id, approval_id);
55
+ ctx.emit(session.session_id, "agent.approval_required", { approval_id, action, action_hash, expires_at }, session.command_id, "needs_you");
56
+ return answer;
57
+ }
58
+
59
+ return {
60
+ pendingOf: (sessionId) => [...pending.values()].filter((p) => p.session_id === sessionId).map((p) => p.record.approval_id),
61
+ register(session) { const token = P.toBase64Url(ctx.random(24)); byToken.set(token, session); return token; },
62
+ unregister(token) {
63
+ const session = byToken.get(token);
64
+ byToken.delete(token);
65
+ if (session) for (const [id, p] of pending) if (p.session_id === session.session_id) finish(id, deny("WorkTrust remote: the session ended; denied"));
66
+ },
67
+ /** A signed decision from approval.decision. Spent before the agent hears it; a refusal leaves the action unapproved. */
68
+ decide(token) {
69
+ const checked = P.verifyApprovalDecision(token, {
70
+ controllers: ctx.controllers(),
71
+ pending: new Map([...pending].map(([id, p]) => [id, p.record])),
72
+ decided: ctx.journal.decidedSet(),
73
+ now: ctx.now(),
74
+ });
75
+ if (!checked.ok) return checked;
76
+ const open = pending.get(checked.value.approval_id);
77
+ ctx.journal.spend(checked.value.approval_id, ctx.now());
78
+ finish(checked.value.approval_id, checked.value.decision === "approve" ? { behavior: "allow", updatedInput: open.input } : deny("WorkTrust remote: denied on your phone"));
79
+ return checked;
80
+ },
81
+ denyAll() { for (const id of [...pending.keys()]) finish(id, deny("WorkTrust remote: the daemon stopped; denied")); },
82
+ async listen(dir) {
83
+ let path;
84
+ if (process.platform === "win32") path = `\\\\.\\pipe\\worktrust-remote-${P.toBase64Url(ctx.random(12))}`;
85
+ else {
86
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
87
+ chmodSync(dir, 0o700);
88
+ path = join(dir, "a.sock");
89
+ rmSync(path, { force: true });
90
+ }
91
+ server = createServer((conn) => {
92
+ let buffer = "";
93
+ conn.setEncoding("utf8");
94
+ conn.on("error", () => {});
95
+ conn.on("data", async (chunk) => {
96
+ buffer += chunk;
97
+ if (buffer.length > 1_048_576) { conn.destroy(); return; }
98
+ const end = buffer.indexOf("\n");
99
+ if (end < 0) return;
100
+ let msg = null;
101
+ try { msg = JSON.parse(buffer.slice(0, end)); } catch { msg = null; }
102
+ buffer = "";
103
+ const session = msg && byToken.get(msg.token);
104
+ // A planning call (the bridge's plan_* tools): the session's own project, answered by the release queue.
105
+ if (msg && msg.plan && typeof msg.plan === "object") {
106
+ const planned = !session ? { ok: false, reason: "unknown session" } : typeof msg.plan.op !== "string" || !ctx.plan ? { ok: false, reason: "unsupported" } : await ctx.plan(session, msg.plan.op, msg.plan.args ?? {});
107
+ conn.end(`${JSON.stringify(planned)}\n`);
108
+ return;
109
+ }
110
+ const answer = !session || typeof msg.tool_name !== "string" || !msg.input || typeof msg.input !== "object"
111
+ ? deny("WorkTrust remote: unknown session; denied")
112
+ : await request(session, msg.tool_name, msg.input);
113
+ conn.end(`${JSON.stringify(answer)}\n`);
114
+ });
115
+ });
116
+ await new Promise((resolve, reject) => { server.once("error", reject); server.listen(path, resolve); });
117
+ if (process.platform !== "win32") chmodSync(path, 0o600);
118
+ return path;
119
+ },
120
+ close() { this.denyAll(); try { server?.close(); } catch { /* closed */ } },
121
+ /** For tests: the request path without a socket. */
122
+ request,
123
+ };
124
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * FILES FROM THE PHONE, INTO THE SESSION'S PROJECT (owner, 2026-11-07; docs/remote-agents/PROTOCOL.md "Attachments").
3
+ *
4
+ * `attachment.put` brings one chunk of one file. Chunks are kept apart under the session's inbox (`.parts/<id>/<n>`,
5
+ * 0600) until all arrived; then they are joined, the SHA-256 the phone named is checked, the bytes are checked to be what
6
+ * the type says (magic numbers; text is UTF-8 without NUL), and the file is written ONCE, 0600, never executable, at
7
+ * `<project>/.worktrust/inbox/<session_id>/<safe name>`: a name of [A-Za-z0-9._-] from the phone's, no leading dot, made
8
+ * unique. Every folder on the way is a real folder inside the project (a link anywhere on the way refuses the file). A HEIC
9
+ * photo is converted to JPEG with macOS `sips` when it is there (Claude Code reads JPEG, not HEIC), else kept as it is.
10
+ * Caps: 25 MB a file, 100 MB a session. `attachment.clear` removes the session's inbox. Nothing here is ever run.
11
+ */
12
+ import { createHash } from "node:crypto";
13
+ import { execFileSync } from "node:child_process";
14
+ import { closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
15
+ import { basename, dirname, extname, join, sep } from "node:path";
16
+ import * as P from "./remote-protocol.mjs";
17
+
18
+ const EXT = { "image/png": ".png", "image/jpeg": ".jpg", "image/heic": ".heic", "image/webp": ".webp", "application/pdf": ".pdf", "text/plain": ".txt", "text/markdown": ".md", "text/csv": ".csv",
19
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ".docx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ".xlsx" };
20
+ const starts = (b, ...bytes) => bytes.every((x, i) => b[i] === x);
21
+ const ascii = (b, at, s) => b.subarray(at, at + s.length).toString("latin1") === s;
22
+
23
+ /** The bytes are what the type says. */
24
+ export function looksLike(type, b) {
25
+ if (type === "image/png") return starts(b, 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a);
26
+ if (type === "image/jpeg") return starts(b, 0xff, 0xd8, 0xff);
27
+ if (type === "image/webp") return ascii(b, 0, "RIFF") && ascii(b, 8, "WEBP");
28
+ if (type === "image/heic") return ascii(b, 4, "ftyp") && /^(heic|heix|hevc|mif1|msf1)$/.test(b.subarray(8, 12).toString("latin1"));
29
+ if (type === "application/pdf") return ascii(b, 0, "%PDF-");
30
+ if (type.endsWith(".document") || type.endsWith(".sheet")) return starts(b, 0x50, 0x4b, 0x03, 0x04);
31
+ if (type.startsWith("text/")) { if (b.includes(0)) return false; try { new TextDecoder("utf-8", { fatal: true }).decode(b); return true; } catch { return false; } }
32
+ return false;
33
+ }
34
+
35
+ /** A name for the file on disk: [A-Za-z0-9._-] only, no leading dot, the type's extension, at most 100 characters. */
36
+ export function safeName(name, type) {
37
+ const stem = basename(String(name)).replace(extname(String(name)), "").replace(/[^A-Za-z0-9._-]+/g, "-").replace(/^[.-]+/, "").replace(/\.+$/, "").slice(0, 80) || "attachment";
38
+ return `${stem}${EXT[type]}`;
39
+ }
40
+
41
+ /** Make each folder from the project down, refusing a link or a file on the way. → the folder, or null. */
42
+ function realDir(project, parts) {
43
+ let at;
44
+ try { at = realpathSync(project); } catch { return null; }
45
+ for (const part of parts) {
46
+ at = join(at, part);
47
+ if (existsSync(at)) { const st = lstatSync(at); if (st.isSymbolicLink() || !st.isDirectory()) return null; } else mkdirSync(at, { mode: 0o700 });
48
+ }
49
+ return at;
50
+ }
51
+
52
+ const writeOnce = (file, bytes) => { const fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | (constants.O_NOFOLLOW ?? 0), 0o600); try { writeSync(fd, bytes); } finally { closeSync(fd); } };
53
+ const sizeOf = (dir) => { try { return readdirSync(dir).reduce((n, f) => { const st = lstatSync(join(dir, f)); return n + (st.isFile() ? st.size : st.isDirectory() ? sizeOf(join(dir, f)) : 0); }, 0); } catch { return 0; } };
54
+
55
+ export function createAttachments(ctx) {
56
+ // ctx: { journal, now, emit, projects(), sessionProject(session_id) → project | null, log }
57
+ const done = new Map(); // `${session_id}/${attachment_id}` -> relative path
58
+
59
+ function put(env, a) {
60
+ const project = ctx.sessionProject(env.session_id);
61
+ if (!project) return "not_found";
62
+ const bad = P.attachmentRule(a);
63
+ if (bad) return "unsupported";
64
+ const key = `${env.session_id}/${a.attachment_id}`;
65
+ if (done.has(key)) return "conflict";
66
+ const inbox = realDir(project.path, [".worktrust", "inbox", env.session_id]);
67
+ const parts = inbox && realDir(inbox, [".parts", a.attachment_id]);
68
+ if (!inbox || !parts) return "unsupported";
69
+ const chunk = Buffer.from(P.fromBase64Url(a.data));
70
+ const expected = a.chunk < a.chunks - 1 ? P.ATTACHMENT_CHUNK_BYTES : a.size - P.ATTACHMENT_CHUNK_BYTES * (a.chunks - 1);
71
+ if (chunk.length !== expected) return "unsupported";
72
+ if (sizeOf(inbox) + chunk.length > P.MAX_SESSION_ATTACHMENT_BYTES) return "busy";
73
+ const part = join(parts, String(a.chunk));
74
+ if (!existsSync(part)) writeOnce(part, chunk);
75
+ const received = readdirSync(parts).filter((f) => /^\d+$/.test(f)).length;
76
+ let path = null;
77
+ if (received === a.chunks) {
78
+ const whole = Buffer.concat(Array.from({ length: a.chunks }, (_, n) => readFileSync(join(parts, String(n)))));
79
+ rmSync(parts, { recursive: true, force: true });
80
+ if (whole.length !== a.size || !createHash("sha256").update(whole).digest().equals(Buffer.from(P.fromBase64Url(a.sha256))) || !looksLike(a.content_type, whole)) return "unsupported";
81
+ let name = safeName(a.name, a.content_type);
82
+ for (let i = 2; existsSync(join(inbox, name)); i += 1) name = name.replace(/(-\d+)?(\.[a-z]+)$/, `-${i}$2`);
83
+ const file = join(inbox, name);
84
+ writeOnce(file, whole);
85
+ const kept = a.content_type === "image/heic" ? heicToJpeg(file) : file;
86
+ if (dirname(realpathSync(kept)) !== realpathSync(inbox)) { rmSync(kept, { force: true }); return "unsupported"; }
87
+ path = [".worktrust", "inbox", env.session_id, basename(kept)].join("/");
88
+ done.set(key, path);
89
+ }
90
+ ctx.emit(env.session_id, "attachment.stored", { attachment_id: a.attachment_id, received, chunks: a.chunks, path, size: a.size, content_type: a.content_type }, env.command_id);
91
+ return "taken";
92
+ }
93
+
94
+ function heicToJpeg(file) {
95
+ if (process.platform !== "darwin" || !existsSync("/usr/bin/sips")) return file;
96
+ const out = file.replace(/\.heic$/, ".jpg");
97
+ try { execFileSync("/usr/bin/sips", ["-s", "format", "jpeg", file, "--out", out], { stdio: "ignore", timeout: 30_000 }); } catch { return file; }
98
+ if (!existsSync(out)) return file;
99
+ rmSync(file, { force: true });
100
+ try { statSync(out); } catch { return file; }
101
+ return out;
102
+ }
103
+
104
+ function clear(env) {
105
+ const project = ctx.sessionProject(env.session_id);
106
+ if (!project) return "not_found";
107
+ const inbox = realDir(project.path, [".worktrust", "inbox", env.session_id]);
108
+ if (!inbox) return "unsupported";
109
+ const removed = readdirSync(inbox).filter((f) => f !== ".parts").length;
110
+ rmSync(inbox, { recursive: true, force: true });
111
+ for (const key of [...done.keys()]) if (key.startsWith(`${env.session_id}/`)) done.delete(key);
112
+ ctx.emit(env.session_id, "attachment.cleared", { removed }, env.command_id);
113
+ return "taken";
114
+ }
115
+
116
+ return {
117
+ handle: (env, payload) => (env.type === "attachment.put" ? put(env, payload) : clear(env)),
118
+ /**
119
+ * The words that tell the agent where its attachments are, appended to a prompt; null when one is not stored whole
120
+ * in this session (the prompt is then refused, never sent without the file it names).
121
+ */
122
+ referenceText(sessionId, ids) {
123
+ if (!ids?.length) return "";
124
+ const paths = ids.map((id) => done.get(`${sessionId}/${id}`));
125
+ if (paths.some((p) => !p)) return null;
126
+ return `\n\nAttached from the phone (files in this project, read them as needed):\n${paths.map((p) => `- ${p}`).join("\n")}`;
127
+ },
128
+ };
129
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * WHICH FILES A TURN CHANGED, WITH A BOUNDED DIFF EACH (owner, 2026-11-07: the phone shows the code so the person can
3
+ * steer). Read-only on the person's repository: nothing is staged, stashed, committed or written into .git.
4
+ *
5
+ * When the turn begins (`snapshotChanges`): HEAD, and the content of every file that was already changed or untracked
6
+ * then (bounded). When it ends (`collectChanges`): every file whose content differs from that snapshot, inside the project
7
+ * folder only, as a unified diff from git itself (`git diff HEAD -- <file>` for a file that was clean, `git diff --no-index`
8
+ * against the kept content for one that was not). Caps: 32 KiB per file, 256 KiB per result, 200 files; each cut is said.
9
+ * A binary file is named, never shown; a secret file (remote-policy.mjs) is named with its diff withheld (diff_cut).
10
+ * Outside a repository the files come from the agent's own edit tools, named without a diff (`agent_tools`).
11
+ * Every git call is execFile with fixed arguments, `--` before paths, and no shell.
12
+ */
13
+ import { execFileSync } from "node:child_process";
14
+ import { createHash } from "node:crypto";
15
+ import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { isSecretPath } from "./remote-policy.mjs";
18
+
19
+ export const PER_FILE = 32_768, PER_RESULT = 262_144, MAX_FILES = 200;
20
+ const KEEP_BYTES = 1_048_576, KEEP_FILES = 500;
21
+ const EMPTY_TREE = "4b825dc642cb6eb9a060e54bf8d69288fbee4904";
22
+
23
+ function git(cwd, args, okCodes = [0]) {
24
+ try { return execFileSync("git", args, { cwd, encoding: "buffer", timeout: 15_000, maxBuffer: 32 * 1024 * 1024, stdio: ["ignore", "pipe", "ignore"], env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_PAGER: "cat", GIT_EXTERNAL_DIFF: "" } }); }
25
+ catch (error) { if (okCodes.includes(error.status) && error.stdout) return error.stdout; return null; }
26
+ }
27
+ const lines0 = (buf) => (buf ? buf.toString("utf8").split("\0").filter(Boolean) : []);
28
+ const hashOf = (file) => { try { return statSync(file).size > KEEP_BYTES ? `size:${statSync(file).size}:${statSync(file).mtimeMs}` : createHash("sha256").update(readFileSync(file)).digest("hex"); } catch { return null; } };
29
+ const isBinary = (bytes) => bytes.subarray(0, 8000).includes(0);
30
+
31
+ /** The state when a turn begins. `{ source: "none" }` outside a repository or without git. */
32
+ export function snapshotChanges(cwd) {
33
+ if (git(cwd, ["rev-parse", "--is-inside-work-tree"])?.toString().trim() !== "true") return { source: "agent_tools" };
34
+ const head = git(cwd, ["rev-parse", "--verify", "-q", "HEAD"])?.toString().trim() || EMPTY_TREE;
35
+ const dirty = [...new Set([...lines0(git(cwd, ["diff", "--relative", "--name-only", "-z", head])), ...lines0(git(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]))])].slice(0, KEEP_FILES);
36
+ const kept = new Map();
37
+ for (const path of dirty) {
38
+ const file = join(cwd, path);
39
+ try { kept.set(path, statSync(file).size <= KEEP_BYTES ? { hash: hashOf(file), bytes: readFileSync(file) } : { hash: hashOf(file), bytes: null }); } catch { kept.set(path, { hash: null, bytes: null }); }
40
+ }
41
+ return { source: "vcs", head, kept, untracked: new Set(lines0(git(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]))) };
42
+ }
43
+
44
+ function capDiff(text) {
45
+ if (!text) return { diff: null, diff_cut: false };
46
+ return text.length > PER_FILE ? { diff: `${text.slice(0, PER_FILE - 64)}\n[cut: the rest of this diff is not shown]`, diff_cut: true } : { diff: text, diff_cut: false };
47
+ }
48
+
49
+ /** The files the turn changed, for agent.completed's result. `agentFiles` are the edit tools' own paths (outside a repo). */
50
+ export function collectChanges(snapshot, cwd, agentFiles = [], scratchDir = null) {
51
+ if (snapshot.source !== "vcs") {
52
+ const files = [...new Set(agentFiles)].slice(0, MAX_FILES).map((path) => ({ path: String(path).slice(0, 4096), change: "modified", binary: false, diff: null, diff_cut: false }));
53
+ return { source: files.length ? "agent_tools" : "none", files, files_cut: new Set(agentFiles).size > MAX_FILES };
54
+ }
55
+ const changed = new Map(); // path -> change
56
+ const status = lines0(git(cwd, ["diff", "--relative", "--name-status", "-z", "--no-renames", snapshot.head]));
57
+ for (let i = 0; i + 1 < status.length; i += 2) changed.set(status[i + 1], status[i] === "A" ? "added" : status[i] === "D" ? "deleted" : "modified");
58
+ for (const path of lines0(git(cwd, ["ls-files", "--others", "--exclude-standard", "-z"]))) changed.set(path, snapshot.untracked.has(path) ? "modified" : "added");
59
+ for (const [path, before] of snapshot.kept) {
60
+ const now = existsSync(join(cwd, path)) ? hashOf(join(cwd, path)) : null;
61
+ if (now === before.hash) changed.delete(path); // unchanged during the turn: not this turn's work
62
+ else if (now === null) changed.set(path, "deleted");
63
+ }
64
+ const paths = [...changed.keys()].sort();
65
+ const files = [];
66
+ let budget = PER_RESULT;
67
+ const tmp = scratchDir ? mkdtempSync(join(scratchDir, "diff-")) : null;
68
+ try {
69
+ for (const path of paths.slice(0, MAX_FILES)) {
70
+ const change = changed.get(path), file = join(cwd, path);
71
+ const entry = { path: path.slice(0, 4096), change, binary: false, diff: null, diff_cut: false };
72
+ let current = null;
73
+ try { current = change === "deleted" ? null : readFileSync(file); } catch { current = null; }
74
+ const before = snapshot.kept.get(path);
75
+ if ((current && isBinary(current)) || (before?.bytes && isBinary(before.bytes))) { files.push({ ...entry, binary: true }); continue; }
76
+ if (isSecretPath(file)) { files.push({ ...entry, diff_cut: true }); continue; }
77
+ let text = null;
78
+ if (before && before.bytes && tmp) {
79
+ const old = join(tmp, "before");
80
+ writeFileSync(old, before.bytes);
81
+ text = git(cwd, ["diff", "--no-index", "--no-color", "-U3", "--", old, change === "deleted" ? "/dev/null" : file], [0, 1])?.toString("utf8").replace(/^(diff --git |--- |\+\+\+ )[^\n]*\n/gm, "") ?? null;
82
+ if (text) text = `--- a/${path}\n+++ b/${path}\n${text}`;
83
+ } else if (change === "added" && current && !snapshot.untracked.has(path) && !before) {
84
+ const body = current.toString("utf8"), rows = body.split("\n"); if (rows.at(-1) === "") rows.pop();
85
+ text = `--- /dev/null\n+++ b/${path}\n@@ -0,0 +1,${rows.length} @@\n${rows.map((r) => `+${r}`).join("\n")}\n`;
86
+ } else if (!before) text = git(cwd, ["diff", "--relative", "--no-color", "--no-ext-diff", "-U3", snapshot.head, "--", path])?.toString("utf8") ?? null;
87
+ const capped = capDiff(text && text.trim() ? text : null);
88
+ if (capped.diff && capped.diff.length > budget) { files.push({ ...entry, diff_cut: true }); continue; }
89
+ budget -= capped.diff?.length ?? 0;
90
+ files.push({ ...entry, ...capped });
91
+ }
92
+ } finally { if (tmp) rmSync(tmp, { recursive: true, force: true }); }
93
+ return { source: "vcs", files, files_cut: paths.length > MAX_FILES };
94
+ }
@@ -0,0 +1,212 @@
1
+ /**
2
+ * CLAUDE CODE'S STREAM, AS THE PROTOCOL'S EVENTS: ONE PURE FUNCTION (2026-11-07). `claude -p --input-format stream-json
3
+ * --output-format stream-json --verbose [--include-partial-messages]` writes one JSON object per line;
4
+ * `mapClaudeLine(state, line, mint, now)` turns one of them into the protocol's sealed events and says when a turn starts
5
+ * or ends. No I/O and no clock of its own: `mint(prefix)` makes opaque ids, `now` is the computer's clock or null. Held by
6
+ * scripts/test-remote-claude-events.mjs against two recorded Claude Code 2.1.286 runs (scripts/fixtures/remote/), one
7
+ * with partial messages, and a third in the same format with a plan and subagents. The plan, the agent map and the
8
+ * tokens are remote-claude-progress.mjs (owner, 2026-11-07).
9
+ *
10
+ * Claude Code line protocol event(s) turn
11
+ * system/init (the session's own id, model and folder noted; started
12
+ * the turn's started_at)
13
+ * stream_event text_delta (partial messages) agent.output_delta {assistant}, coalesced: one event
14
+ * per 2,048 characters or at the block's end
15
+ * stream_event message_start / message_delta agent.usage {running}, the main agent's only
16
+ * assistant: text block (no partial messages) agent.output_delta {assistant}, cut at 65,536
17
+ * assistant: tool_use block agent.step_started {label, kind, steps, plan_item_id}
18
+ * assistant: TodoWrite, TaskCreate, TaskUpdate + agent.plan, whole, when the plan changed
19
+ * assistant: Task or Agent tool_use + agent.subagent {started}
20
+ * assistant: a message's usage + agent.usage {running}, the main agent's only
21
+ * assistant: thinking block, thinking deltas (nothing: never sent)
22
+ * user: tool_result block agent.step_completed {ok | failed, duration_ms}
23
+ * user: tool_result, is_error + agent.output_delta {tool} with the reason
24
+ * user: tool_result of a test command (its outcome and counts kept for the result)
25
+ * user: a Task's result (tool_use_result) + agent.subagent {done | failed, tokens, steps, duration}
26
+ * a tracked subagent's assistant / user line its steps {subagent_id}, agent.subagent {working, steps};
27
+ * (parent_tool_use_id) its text is never sent as the reply
28
+ * system task_started / task_progress / agent.subagent {the tokens, tool uses, duration, end}
29
+ * task_notification
30
+ * result, success agent.usage {final}, agent.completed {summary, steps,
31
+ * result: the full answer and the tests; the files are
32
+ * added by the session; started_at, duration_ms} ended
33
+ * result, an error subtype or is_error agent.usage, agent.failed {adapter_error | timeout} ended
34
+ * an untracked subagent's line, system/status, system/thinking_tokens, rate_limit_event, other stream_event types,
35
+ * anything else: nothing, counted
36
+ */
37
+ import { emptyProgress, planItemNow, progressAssistant, progressEndSubagents, progressInit, progressResult, progressStream, progressTask, progressUser, subagentLine, subagentOf } from "./remote-claude-progress.mjs";
38
+
39
+ /** The agent's run ended (a stop, its exit): every subagent not ended is stopped, background ones too. */
40
+ export function endClaudeRun(state, now = null) {
41
+ const p = progressEndSubagents(state.progress, Number.isSafeInteger(now) ? now : null, { background: true });
42
+ return { state: { ...state, progress: p.state }, events: p.events };
43
+ }
44
+
45
+ export const CHUNK_CHARS = 2048;
46
+ const MAX_ANSWER = 262_144;
47
+ export const emptyClaudeState = () => ({ steps: {}, stepAt: {}, tests: {}, testRuns: [], started: 0, completed: 0, offset: 0, pending: "", streamed: false, cwd: null, sessionRef: null, model: null, ignored: 0, turnStartedAt: null, progress: emptyProgress() });
48
+
49
+ const cut = (text, max) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
50
+ const relative = (cwd, path) => (typeof path !== "string" ? "" : cwd && path.startsWith(`${cwd}/`) ? path.slice(cwd.length + 1) : path);
51
+ export const TEST_COMMAND = /(^|\s)(test|tests|pytest|jest|vitest|mocha|--test)(\s|$)/;
52
+
53
+ /** The step's words and kind, from the tool's own name and input. */
54
+ export function stepOf(name, input, cwd) {
55
+ const a = input && typeof input === "object" ? input : {};
56
+ switch (name) {
57
+ case "Bash": { const command = String(a.command ?? ""); return { label: cut(`Run ${command}`, 500), kind: TEST_COMMAND.test(command) ? "test" : "command" }; }
58
+ case "Read": case "NotebookRead": return { label: cut(`Read ${relative(cwd, a.file_path ?? a.notebook_path)}`, 500), kind: "read" };
59
+ case "Edit": case "MultiEdit": case "NotebookEdit": return { label: cut(`Edit ${relative(cwd, a.file_path ?? a.notebook_path)}`, 500), kind: "edit" };
60
+ case "Write": return { label: cut(`Write ${relative(cwd, a.file_path)}`, 500), kind: "edit" };
61
+ case "Glob": case "Grep": return { label: cut(`Search ${String(a.pattern ?? "")}`, 500), kind: "search" };
62
+ case "WebFetch": case "WebSearch": return { label: cut(`Look up ${String(a.url ?? a.query ?? "")}`, 500), kind: "search" };
63
+ case "Task": case "Agent": return { label: cut(`Delegate ${String(a.description ?? "")}`, 500), kind: "tool" };
64
+ case "TodoWrite": case "TaskCreate": case "TaskUpdate": return { label: "Plan the work", kind: "think" };
65
+ default: return { label: cut(`Use ${String(name ?? "a tool")}`, 500), kind: "tool" };
66
+ }
67
+ }
68
+
69
+ /** Counts a test runner printed: node --test, Jest, Vitest, pytest, Go and cargo. Null when it named none. */
70
+ export function testCounts(output) {
71
+ const t = String(output ?? "");
72
+ const num = (re) => { const m = re.exec(t); return m ? Number(m[1]) : null; };
73
+ let passed = num(/(?:^|\n)[ℹ#] pass (\d+)/), failed = num(/(?:^|\n)[ℹ#] fail (\d+)/), total = num(/(?:^|\n)[ℹ#] tests (\d+)/);
74
+ if (passed === null) { const jest = /Tests:\s+(?:(\d+) failed, )?(?:\d+ skipped, )?(?:(\d+) passed, )?(\d+) total/.exec(t); if (jest) { failed = Number(jest[1] ?? 0); passed = Number(jest[2] ?? 0); total = Number(jest[3]); } }
75
+ if (passed === null) { const vitest = /Tests\s+(?:(\d+) failed \| )?(\d+) passed/.exec(t); if (vitest) { failed = Number(vitest[1] ?? 0); passed = Number(vitest[2]); } }
76
+ if (passed === null) { const py = /=+ (?:(\d+) failed, )?(\d+) passed/.exec(t) ?? /(\d+) passed/.exec(t); if (py) { passed = Number(py[2] ?? py[1]); failed = num(/(\d+) failed/) ?? 0; } }
77
+ if (passed === null) { const cargo = /test result: \w+\. (\d+) passed; (\d+) failed/.exec(t); if (cargo) { passed = Number(cargo[1]); failed = Number(cargo[2]); } }
78
+ return passed === null && failed === null ? null : { passed, failed, total: total ?? (passed !== null && failed !== null ? passed + failed : null) };
79
+ }
80
+
81
+ const steps = (s) => ({ kind: "steps", started: s.started, completed: s.completed });
82
+ const textOfResult = (content) => (typeof content === "string" ? content : Array.isArray(content) ? content.filter((b) => b?.type === "text").map((b) => b.text).join("\n") : "");
83
+ function flush(s, events, all) {
84
+ while (s.pending.length >= CHUNK_CHARS || (all && s.pending.length > 0)) {
85
+ const text = s.pending.slice(0, CHUNK_CHARS);
86
+ s.pending = s.pending.slice(text.length);
87
+ events.push({ type: "agent.output_delta", body: { stream: "assistant", offset: s.offset, text } });
88
+ s.offset += text.length;
89
+ }
90
+ }
91
+
92
+ const toolUses = (content) => content.filter((b) => b?.type === "tool_use" && typeof b.id === "string").length;
93
+ const at = (now) => (Number.isSafeInteger(now) && now >= 0 ? now : null);
94
+ /** started_at and duration_ms of the turn that ends now, where the clock was given. */
95
+ const turnTime = (s, now) => (s.turnStartedAt !== null && at(now) !== null && now >= s.turnStartedAt ? { started_at: s.turnStartedAt, duration_ms: now - s.turnStartedAt } : s.turnStartedAt !== null ? { started_at: s.turnStartedAt } : {});
96
+
97
+ /**
98
+ * "READY, BUT A JOB IS STILL RUNNING" (owner, 2026-11-08): the background jobs the agent itself reports, by Claude Code's
99
+ * own task lines (system task_started with is_backgrounded, then its task_notification). Counted only: never a process
100
+ * looked at, never a job's output read. → the open task ids, or null while the agent reported no background job at all
101
+ * (a surface then shows nothing, never a 0 it cannot know).
102
+ */
103
+ export function backgroundJobs(open, line) {
104
+ if (line?.type !== "system" || typeof line.task_id !== "string") return open;
105
+ if (line.subtype === "task_started" && line.is_backgrounded === true) return new Set([...(open ?? []), line.task_id]);
106
+ if (line.subtype === "task_notification" && open?.has(line.task_id)) { const next = new Set(open); next.delete(line.task_id); return next; }
107
+ return open;
108
+ }
109
+
110
+ /**
111
+ * One line in, the protocol's events out. `mint(prefix)` makes an opaque id of that kind ("stp" by default); `now` is the
112
+ * computer's clock in milliseconds, or null (no times are then sent).
113
+ */
114
+ export function mapClaudeLine(state, line, mint, now = null) {
115
+ const s = { ...state, steps: { ...state.steps }, tests: { ...state.tests }, testRuns: [...state.testRuns], stepAt: { ...state.stepAt } };
116
+ const events = [];
117
+ const id = (prefix = "stp") => mint(prefix);
118
+ if (!line || typeof line !== "object") return { state: { ...s, ignored: s.ignored + 1 }, events, turn: null };
119
+ const parent = typeof line.parent_tool_use_id === "string" && line.parent_tool_use_id ? line.parent_tool_use_id : null;
120
+ const sub = parent ? subagentOf(s.progress, parent) : null;
121
+ // A line of a subagent this computer does not track (past the cap, or of an untracked parent): nothing, counted.
122
+ if (parent && (!sub || (line.type !== "assistant" && line.type !== "user"))) return { state: { ...s, ignored: s.ignored + 1 }, events, turn: null };
123
+ if (line.type === "system" && line.subtype === "init") {
124
+ s.sessionRef = typeof line.session_id === "string" ? line.session_id : s.sessionRef;
125
+ s.model = typeof line.model === "string" ? line.model : s.model;
126
+ s.cwd = typeof line.cwd === "string" ? line.cwd : s.cwd;
127
+ s.turnStartedAt = at(now);
128
+ s.progress = progressInit(s.progress, line);
129
+ return { state: s, events, turn: "started" };
130
+ }
131
+ if (line.type === "system" && /^task_(started|progress|notification)$/.test(line.subtype ?? "")) {
132
+ const p = progressTask(s.progress, line, at(now));
133
+ return { state: { ...s, progress: p.state }, events: p.events, turn: null };
134
+ }
135
+ if (line.type === "stream_event") {
136
+ const e = line.event ?? {};
137
+ if (e.type === "content_block_delta" && e.delta?.type === "text_delta" && typeof e.delta.text === "string") { s.streamed = true; s.pending += e.delta.text; flush(s, events, false); }
138
+ else if (e.type === "content_block_stop" || e.type === "message_stop") flush(s, events, true);
139
+ const p = progressStream(s.progress, line);
140
+ s.progress = p.state;
141
+ events.push(...p.events);
142
+ return { state: s, events, turn: null };
143
+ }
144
+ if (line.type === "assistant" && Array.isArray(line.message?.content)) {
145
+ const minted = {};
146
+ for (const block of line.message.content) {
147
+ if (block?.type === "text" && typeof block.text === "string" && block.text.length > 0 && !s.streamed && !sub) {
148
+ const text = block.text.slice(0, 65_536);
149
+ events.push({ type: "agent.output_delta", body: { stream: "assistant", offset: s.offset, text } });
150
+ s.offset += text.length;
151
+ } else if (block?.type === "tool_use" && typeof block.id === "string") {
152
+ if (!sub) flush(s, events, true);
153
+ const step_id = id("stp");
154
+ minted[block.id] = step_id;
155
+ s.steps[block.id] = step_id;
156
+ s.stepAt[block.id] = at(now);
157
+ s.started += 1;
158
+ const step = stepOf(block.name, block.input, s.cwd);
159
+ if (step.kind === "test") s.tests[block.id] = String(block.input?.command ?? "").slice(0, 500);
160
+ const item = planItemNow(s.progress);
161
+ events.push({ type: "agent.step_started", body: { step_id, ...step, progress: steps(s), ...(item ? { plan_item_id: item } : {}), ...(sub ? { subagent_id: sub.subagent_id } : {}) } });
162
+ }
163
+ }
164
+ const p = progressAssistant(s.progress, line, { now: at(now), mint: id, stepFor: (b) => minted[b.id] });
165
+ s.progress = p.state;
166
+ events.push(...p.events);
167
+ if (sub) { const e = subagentLine(s.progress, parent, toolUses(line.message.content)); if (e) events.push(e); }
168
+ return { state: s, events, turn: null };
169
+ }
170
+ if (line.type === "user" && Array.isArray(line.message?.content)) {
171
+ for (const block of line.message.content) {
172
+ if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
173
+ const step_id = s.steps[block.tool_use_id];
174
+ if (!step_id) { s.ignored += 1; continue; }
175
+ const began = s.stepAt[block.tool_use_id];
176
+ delete s.steps[block.tool_use_id];
177
+ delete s.stepAt[block.tool_use_id];
178
+ s.completed += 1;
179
+ const duration = began !== null && began !== undefined && at(now) !== null && now >= began ? { duration_ms: now - began } : {};
180
+ events.push({ type: "agent.step_completed", body: { step_id, outcome: block.is_error ? "failed" : "ok", progress: steps(s), ...duration } });
181
+ const output = textOfResult(block.content);
182
+ if (s.tests[block.tool_use_id] !== undefined && s.testRuns.length < 20) {
183
+ const counts = testCounts(output);
184
+ const outcome = block.is_error || (counts?.failed ?? 0) > 0 ? "failed" : counts ? "passed" : "unknown";
185
+ s.testRuns.push({ command: s.tests[block.tool_use_id] || "tests", outcome, passed: counts?.passed ?? null, failed: counts?.failed ?? null, total: counts?.total ?? null });
186
+ delete s.tests[block.tool_use_id];
187
+ }
188
+ const reason = block.is_error && !sub ? output.trim() : "";
189
+ if (reason) events.push({ type: "agent.output_delta", body: { stream: "tool", offset: 0, text: cut(reason, 2000) } });
190
+ }
191
+ const p = progressUser(s.progress, line, { now: at(now), textOf: (b) => textOfResult(b.content) });
192
+ s.progress = p.state;
193
+ events.push(...p.events);
194
+ if (sub) { const e = subagentLine(s.progress, parent, 0); if (e) events.push(e); }
195
+ return { state: s, events, turn: null };
196
+ }
197
+ if (line.type === "result") {
198
+ flush(s, events, true);
199
+ const failed = line.is_error === true || (typeof line.subtype === "string" && line.subtype !== "success");
200
+ const answer = typeof line.result === "string" && line.result.trim() ? line.result.trim() : null;
201
+ let p = progressResult(s.progress, line);
202
+ events.push(...p.events);
203
+ if (failed) { const ended = progressEndSubagents(p.state, at(now), { background: false }); p = { ...p, state: ended.state }; events.push(...ended.events); }
204
+ const time = turnTime(s, now);
205
+ events.push(failed
206
+ ? { type: "agent.failed", body: { reason: line.subtype === "error_max_turns" ? "timeout" : "adapter_error", message: answer ? cut(answer, 4000) : null, ...time } }
207
+ : { type: "agent.completed", body: { summary: answer ? cut(answer, 4000) : null, progress: steps(s), result: { answer: answer ? answer.slice(0, MAX_ANSWER) : null, answer_cut: (answer?.length ?? 0) > MAX_ANSWER, source: "none", files: [], files_cut: false, tests: s.testRuns }, ...time } });
208
+ // A new turn counts its own steps and tests; the plan, the subagents and the session's tokens go on.
209
+ return { state: { ...s, progress: p.state, steps: {}, stepAt: {}, tests: {}, testRuns: [], started: 0, completed: 0, streamed: false, pending: "", turnStartedAt: null }, events, turn: "ended" };
210
+ }
211
+ return { state: { ...s, ignored: s.ignored + 1 }, events, turn: null };
212
+ }