worktrust 0.10.38 → 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.
- package/LICENSE +43 -18
- package/README.md +46 -2
- package/SECURITY.md +25 -0
- package/engine-release.json +1 -1
- package/log-session.mjs +6 -6
- package/package-release.json +1 -1
- package/package.json +35 -2
- package/remote-adapter-claude-code.mjs +111 -0
- package/remote-adapter-codex.mjs +119 -0
- package/remote-approval-bridge.mjs +122 -0
- package/remote-approvals.mjs +124 -0
- package/remote-attachments.mjs +129 -0
- package/remote-changes.mjs +94 -0
- package/remote-claude-events.mjs +212 -0
- package/remote-claude-progress.mjs +328 -0
- package/remote-cli.mjs +325 -0
- package/remote-coalesce.mjs +40 -0
- package/remote-codex-events.mjs +153 -0
- package/remote-daemon.mjs +205 -0
- package/remote-inventory.mjs +132 -0
- package/remote-journal.mjs +155 -0
- package/remote-pairing.mjs +104 -0
- package/remote-pipeline-config.mjs +177 -0
- package/remote-pipeline-parsers.mjs +121 -0
- package/remote-pipeline.mjs +234 -0
- package/remote-policy.mjs +199 -0
- package/remote-preview.mjs +146 -0
- package/remote-projects.mjs +87 -0
- package/remote-protocol.mjs +3881 -0
- package/remote-qr.mjs +175 -0
- package/remote-release-plans.mjs +88 -0
- package/remote-releases.mjs +297 -0
- package/remote-run.mjs +174 -0
- package/remote-service.mjs +101 -0
- package/remote-session-list.mjs +25 -0
- package/remote-sessions.mjs +348 -0
- package/remote-steered.mjs +114 -0
- package/remote-steering.mjs +97 -0
- package/remote-store.mjs +123 -0
- package/remote-transport.mjs +88 -0
- package/worktrust.mjs +11 -4
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE CODEX ADAPTER (2026-11-07; docs/remote-agents/PROTOCOL.md "Steering a running turn"). Codex runs as
|
|
3
|
+
* `codex app-server` (JSON-RPC over stdio, Codex 0.154.0), one process per remote session, no shell between us and it.
|
|
4
|
+
*
|
|
5
|
+
* initialize, initialized once
|
|
6
|
+
* thread/start | thread/resume the session (resume by the agent's own thread id); its id reaches `onThread`
|
|
7
|
+
* BEFORE the first turn starts, so the steered ledger names it first
|
|
8
|
+
* turn/start a prompt
|
|
9
|
+
* turn/steer { expectedTurnId } words into the RUNNING turn: measured on 0.154.0, they enter it at the next
|
|
10
|
+
* item boundary (a running command finishes first) and the turn's answer heeds them
|
|
11
|
+
* turn/interrupt end the running turn; the thread stays (measured: 0.7 s to `interrupted`)
|
|
12
|
+
* item/.../requestApproval Codex asks: classified by the computer's own policy as Bash or Edit actions;
|
|
13
|
+
* only an approvable class reaches the phone, everything else is declined here
|
|
14
|
+
* The approval policy is `untrusted` and the sandbox `workspace-write` (`read-only` in the plan mode): Codex asks before
|
|
15
|
+
* anything it does not already trust, and never writes outside the project on its own. No free argument reaches Codex.
|
|
16
|
+
*/
|
|
17
|
+
import { spawn } from "node:child_process";
|
|
18
|
+
import { changePaths, codexApprovalAsTool, refusalFor } from "./remote-codex-events.mjs";
|
|
19
|
+
|
|
20
|
+
const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
|
21
|
+
const THREAD = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
22
|
+
export const isCodexThreadId = (value) => typeof value === "string" && THREAD.test(value);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The fixed command line. The person's own Codex config stays (its model, its notify hook), but a remote session never
|
|
26
|
+
* widens the sandbox or reaches a configured MCP server (review 2026-11-07, P2-1): no extra writable roots, no network in
|
|
27
|
+
* the sandbox, no mcp_servers. MCP servers a Codex PLUGIN brings still start (measured on 0.154.0); that is part of the
|
|
28
|
+
* risk the person accepts when they turn Codex on (`worktrust remote codex on`).
|
|
29
|
+
*/
|
|
30
|
+
export function codexArgs() {
|
|
31
|
+
return ["app-server", "--config", "sandbox_workspace_write.network_access=false", "--config", "sandbox_workspace_write.writable_roots=[]", "--config", "mcp_servers={}"];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** thread/start or thread/resume parameters from the protocol's closed options. */
|
|
35
|
+
export function threadParams({ cwd, model, mode, resume }) {
|
|
36
|
+
if (mode !== "ask" && mode !== "plan") throw new Error("the protocol offers the ask and plan modes only");
|
|
37
|
+
if (model !== null && !MODEL.test(model)) throw new Error("not a model name");
|
|
38
|
+
if (resume !== null && !isCodexThreadId(resume)) throw new Error("a resume id is Codex's own thread id");
|
|
39
|
+
const common = { cwd, approvalPolicy: "untrusted", sandbox: mode === "plan" ? "read-only" : "workspace-write", ...(model ? { model } : {}) };
|
|
40
|
+
return resume ? { method: "thread/resume", params: { threadId: resume, ...common } } : { method: "thread/start", params: common };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const text = (t) => [{ type: "text", text: t }];
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* o: { file, cwd, env, model, mode, resume, onMessage(msg), onThread(threadId), onExit(how), approve(tool, input) → Promise<boolean> }.
|
|
47
|
+
* → { pid, alive, write(text), steer(text) → Promise<{ ok }>, interrupt() → Promise<boolean>, stop(), close() }.
|
|
48
|
+
*/
|
|
49
|
+
export function startCodex(o) {
|
|
50
|
+
const child = spawn(o.file, codexArgs(), { cwd: o.cwd, env: o.env, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true });
|
|
51
|
+
let buffer = "", exited = false, nextId = 1, threadId = null, turnId = null, ready = false;
|
|
52
|
+
const waiting = new Map(), queue = [], fileChanges = {};
|
|
53
|
+
const send = (msg) => { if (!exited) child.stdin.write(`${JSON.stringify(msg)}\n`); };
|
|
54
|
+
const call = (method, params) => new Promise((resolve) => { if (exited) { resolve({ error: { message: "codex exited" } }); return; } const id = nextId++; waiting.set(id, resolve); send({ id, method, params }); });
|
|
55
|
+
const turn = (t) => call("turn/start", { threadId, input: text(t) });
|
|
56
|
+
async function answer(msg) {
|
|
57
|
+
const asks = msg.method === "item/permissions/requestApproval" ? null : codexApprovalAsTool(msg.method, msg.params, fileChanges, o.cwd);
|
|
58
|
+
let allowed = false;
|
|
59
|
+
if (asks) { allowed = true; for (const a of asks) if (!(await o.approve(a.tool, a.input))) { allowed = false; break; } }
|
|
60
|
+
send({ id: msg.id, result: { decision: allowed ? "accept" : refusalFor(msg.params) } });
|
|
61
|
+
}
|
|
62
|
+
child.stdout.setEncoding("utf8");
|
|
63
|
+
child.stdout.on("data", (chunk) => {
|
|
64
|
+
buffer += chunk;
|
|
65
|
+
if (buffer.length > 16 * 1024 * 1024) { buffer = ""; return; }
|
|
66
|
+
let end;
|
|
67
|
+
while ((end = buffer.indexOf("\n")) >= 0) {
|
|
68
|
+
const raw = buffer.slice(0, end); buffer = buffer.slice(end + 1);
|
|
69
|
+
let msg;
|
|
70
|
+
try { msg = JSON.parse(raw); } catch { continue; }
|
|
71
|
+
if (msg.id !== undefined && msg.method === undefined) { waiting.get(msg.id)?.(msg); waiting.delete(msg.id); continue; }
|
|
72
|
+
if (msg.id !== undefined && typeof msg.method === "string") { answer(msg).catch(() => send({ id: msg.id, result: { decision: refusalFor(msg.params) } })); continue; }
|
|
73
|
+
if (msg.method === "turn/started") turnId = msg.params?.turn?.id ?? turnId;
|
|
74
|
+
if (msg.method === "turn/completed") turnId = null;
|
|
75
|
+
if (msg.method === "item/started" && msg.params?.item?.type === "fileChange") fileChanges[msg.params.item.id] = changePaths(msg.params.item.changes);
|
|
76
|
+
o.onMessage(msg);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
child.stderr.on("data", () => {}); // never logged: it may hold the agent's words
|
|
80
|
+
child.stdin.on("error", () => {});
|
|
81
|
+
// A call never hangs on a Codex that is gone: every one waiting is answered with an error (review 2026-11-07, P2-3).
|
|
82
|
+
const settle = () => { for (const [id, resolve] of waiting) resolve({ id, error: { message: "codex exited" } }); waiting.clear(); };
|
|
83
|
+
const exit = new Promise((resolve) => child.on("exit", (code, signal) => { exited = true; settle(); o.onExit({ code, signal }); resolve(); }));
|
|
84
|
+
child.on("error", () => { if (!exited) { exited = true; settle(); o.onExit({ code: null, signal: null, error: true }); } });
|
|
85
|
+
(async () => {
|
|
86
|
+
await call("initialize", { clientInfo: { name: "worktrust-remote", version: "1" } });
|
|
87
|
+
send({ method: "initialized" });
|
|
88
|
+
const { method, params } = threadParams({ cwd: o.cwd, model: o.model, mode: o.mode, resume: o.resume });
|
|
89
|
+
const started = await call(method, params);
|
|
90
|
+
threadId = started.result?.thread?.id ?? null;
|
|
91
|
+
if (!isCodexThreadId(threadId)) { child.kill("SIGTERM"); return; }
|
|
92
|
+
o.onThread(threadId); // the ledger names the thread before its first turn
|
|
93
|
+
ready = true;
|
|
94
|
+
for (const t of queue.splice(0)) turn(t);
|
|
95
|
+
})().catch(() => child.kill("SIGTERM"));
|
|
96
|
+
const signal = (sig) => { try { if (process.platform === "win32") child.kill(sig); else process.kill(-child.pid, sig); } catch { /* gone */ } };
|
|
97
|
+
return {
|
|
98
|
+
pid: child.pid,
|
|
99
|
+
alive: () => !exited,
|
|
100
|
+
threadId: () => threadId,
|
|
101
|
+
write: (t) => { if (ready) turn(t); else queue.push(t); },
|
|
102
|
+
/** Words into the running turn, guarded by its id: a turn that just ended refuses them, and they wait for the next. */
|
|
103
|
+
async steer(t) { if (!ready || !turnId) return { ok: false }; const r = await call("turn/steer", { threadId, expectedTurnId: turnId, input: text(t) }); return { ok: !r.error }; },
|
|
104
|
+
async interrupt() { if (!ready || !turnId) return false; const r = await call("turn/interrupt", { threadId, turnId }); return !r.error; },
|
|
105
|
+
async stop(graceMs = 3000) {
|
|
106
|
+
if (exited) return;
|
|
107
|
+
if (turnId) await Promise.race([this.interrupt(), new Promise((r) => setTimeout(r, 1000))]);
|
|
108
|
+
for (const sig of ["SIGTERM", "SIGKILL"]) { signal(sig); if (await Promise.race([exit.then(() => true), new Promise((r) => setTimeout(() => r(false), graceMs))])) return; }
|
|
109
|
+
},
|
|
110
|
+
close: () => { try { child.stdin.end(); } catch { /* closed */ } },
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** What `codex --version` and its help say this Codex can do; the app-server's methods are fixed per version. */
|
|
115
|
+
export function codexReport(version, appServerHelp) {
|
|
116
|
+
const v = /codex-cli\s+(\d+)\.(\d+)\.(\d+)/.exec(version ?? "");
|
|
117
|
+
const usable = Boolean(v) && /generate-json-schema|--listen/.test(appServerHelp ?? "") && (Number(v[1]) > 0 || Number(v[2]) >= 154);
|
|
118
|
+
return { usable, capabilities: usable ? { start: true, prompt: true, steer: true, steer_mode: "live", interrupt: true, stop: true, structured_events: true, resume_by_id: true, permission_modes: ["ask", "plan"], approvals: "structured" } : null };
|
|
119
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* THE PERMISSION-PROMPT TOOL CLAUDE CODE CALLS IN A REMOTE SESSION (2026-11-07). A tiny MCP server on stdio, started by
|
|
4
|
+
* Claude Code itself from the --mcp-config the daemon wrote for one session (`--permission-prompt-tool
|
|
5
|
+
* mcp__worktrust_remote__approve`). Claude Code calls it whenever the person's own permission rules would have asked; the
|
|
6
|
+
* person's allow and deny rules still apply first, at the desk's settings.
|
|
7
|
+
*
|
|
8
|
+
* It decides nothing. It forwards each request ({ tool_name, input, tool_use_id }) over the daemon's local socket
|
|
9
|
+
* (~/.worktrust/remote/run/, this user only), with the session's one-time token, and answers what the daemon answers:
|
|
10
|
+
* { "behavior": "allow", "updatedInput": <the input, unchanged> } only after a signed phone approval of that exact input
|
|
11
|
+
* { "behavior": "deny", "message": "<why>" } everything else, including any failure here
|
|
12
|
+
* Fail closed: no daemon, a lost socket, a malformed answer or six minutes without one is a denial. This is not the
|
|
13
|
+
* WorkTrust MCP door and opens no network connection. It also carries the agent's PLANNING tools (plan_release,
|
|
14
|
+
* plan_task, plan_list; 2026-11-08), answered by the daemon's release queue for the session's own project.
|
|
15
|
+
*/
|
|
16
|
+
import { createConnection } from "node:net";
|
|
17
|
+
import { createInterface } from "node:readline";
|
|
18
|
+
|
|
19
|
+
export const TOOL = "approve";
|
|
20
|
+
const SOCKET = process.env.WORKTRUST_REMOTE_APPROVAL_SOCKET ?? "";
|
|
21
|
+
const TOKEN = process.env.WORKTRUST_REMOTE_APPROVAL_TOKEN ?? "";
|
|
22
|
+
const WAIT_MS = 6 * 60_000;
|
|
23
|
+
const deny = (message) => ({ behavior: "deny", message });
|
|
24
|
+
|
|
25
|
+
/** Ask the daemon; any failure is a denial. */
|
|
26
|
+
export function askDaemon(request, socket = SOCKET, token = TOKEN, waitMs = WAIT_MS) {
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
if (!socket || !token) { resolve(deny("WorkTrust remote: no approval channel for this session; denied")); return; }
|
|
29
|
+
let settled = false, buffer = "";
|
|
30
|
+
const done = (answer) => { if (settled) return; settled = true; clearTimeout(timer); try { conn.destroy(); } catch { /* closed */ } resolve(answer); };
|
|
31
|
+
const conn = createConnection(socket);
|
|
32
|
+
const timer = setTimeout(() => done(deny("WorkTrust remote: no decision in time; denied")), waitMs);
|
|
33
|
+
conn.on("connect", () => conn.write(`${JSON.stringify({ token, ...request })}\n`));
|
|
34
|
+
conn.on("data", (chunk) => {
|
|
35
|
+
buffer += chunk;
|
|
36
|
+
if (buffer.length > 1_048_576) { done(deny("WorkTrust remote: malformed answer; denied")); return; }
|
|
37
|
+
const end = buffer.indexOf("\n");
|
|
38
|
+
if (end < 0) return;
|
|
39
|
+
let answer = null;
|
|
40
|
+
try { answer = JSON.parse(buffer.slice(0, end)); } catch { answer = null; }
|
|
41
|
+
if (answer?.behavior === "allow" && answer.updatedInput && typeof answer.updatedInput === "object") done({ behavior: "allow", updatedInput: answer.updatedInput });
|
|
42
|
+
else done(deny(typeof answer?.message === "string" ? answer.message.slice(0, 2000) : "WorkTrust remote: denied"));
|
|
43
|
+
});
|
|
44
|
+
conn.on("error", () => done(deny("WorkTrust remote: the daemon is not reachable; denied")));
|
|
45
|
+
conn.on("close", () => done(deny("WorkTrust remote: the daemon closed the request; denied")));
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A planning call over the same socket: the daemon's answer ({ ok, ... }), or a refusal on any failure. */
|
|
50
|
+
export function askPlan(op, args, socket = SOCKET, token = TOKEN, waitMs = 30_000) {
|
|
51
|
+
return new Promise((resolve) => {
|
|
52
|
+
const refuse = (reason) => ({ ok: false, reason });
|
|
53
|
+
if (!socket || !token) { resolve(refuse("no planning channel for this session")); return; }
|
|
54
|
+
let settled = false, buffer = "";
|
|
55
|
+
const done = (answer) => { if (settled) return; settled = true; clearTimeout(timer); try { conn.destroy(); } catch { /* closed */ } resolve(answer); };
|
|
56
|
+
const conn = createConnection(socket);
|
|
57
|
+
const timer = setTimeout(() => done(refuse("no answer in time")), waitMs);
|
|
58
|
+
conn.on("connect", () => conn.write(`${JSON.stringify({ token, plan: { op, args } })}\n`));
|
|
59
|
+
conn.on("data", (chunk) => {
|
|
60
|
+
buffer += chunk;
|
|
61
|
+
if (buffer.length > 1_048_576) { done(refuse("malformed answer")); return; }
|
|
62
|
+
const end = buffer.indexOf("\n");
|
|
63
|
+
if (end < 0) return;
|
|
64
|
+
let answer = null;
|
|
65
|
+
try { answer = JSON.parse(buffer.slice(0, end)); } catch { answer = null; }
|
|
66
|
+
done(answer && typeof answer === "object" && typeof answer.ok === "boolean" ? answer : refuse("malformed answer"));
|
|
67
|
+
});
|
|
68
|
+
conn.on("error", () => done(refuse("the daemon is not reachable")));
|
|
69
|
+
conn.on("close", () => done(refuse("the daemon closed the request")));
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* THE PLANNING TOOLS (owner, 2026-11-08: the agent arranges its own work, the phone shows it on Status). Short on
|
|
75
|
+
* purpose: their descriptions travel with every turn. The project is the session's own; nothing here runs anything.
|
|
76
|
+
*/
|
|
77
|
+
const n = (description) => ({ type: "integer", description });
|
|
78
|
+
const PLAN_TOOLS = [
|
|
79
|
+
{ name: "plan_release", op: "release", description: "Plan multi-step work as a release on the phone's Status: tasks you then do yourself. Check plan_list first.",
|
|
80
|
+
inputSchema: { type: "object", properties: { title: { type: "string" }, label: { type: "string", description: "short name, e.g. CLI 0.11.0" }, estimate_min: n("your estimate, minutes"), after: n("release number it waits for"),
|
|
81
|
+
tasks: { type: "array", items: { type: "object", properties: { title: { type: "string" }, estimate_min: n("minutes") }, required: ["title"] } } }, required: ["title"] } },
|
|
82
|
+
{ name: "plan_task", op: "task", description: "Add a task to a release, or report yours: running, done or failed (note: one line).",
|
|
83
|
+
inputSchema: { type: "object", properties: { release: n("release number, to add"), title: { type: "string" }, estimate_min: n("minutes"), task_id: { type: "string" }, state: { type: "string", enum: ["running", "done", "failed"] }, note: { type: "string" } } } },
|
|
84
|
+
{ name: "plan_list", op: "list", description: "This project's open releases and tasks.", inputSchema: { type: "object", properties: {} } },
|
|
85
|
+
];
|
|
86
|
+
|
|
87
|
+
const reply = (id, result) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`);
|
|
88
|
+
const error = (id, code, message) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } })}\n`);
|
|
89
|
+
|
|
90
|
+
export async function handle(message, ask = askDaemon, plan = askPlan) {
|
|
91
|
+
const { id, method, params } = message ?? {};
|
|
92
|
+
if (method === "initialize") return { id, result: { protocolVersion: typeof params?.protocolVersion === "string" ? params.protocolVersion : "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "worktrust-remote", version: "1" } } };
|
|
93
|
+
if (method === "ping") return { id, result: {} };
|
|
94
|
+
if (method === "tools/list") return { id, result: { tools: [{ name: TOOL, description: "WorkTrust remote: asks the person's confirmed phone to approve one permission request, or denies it.", inputSchema: { type: "object", properties: { tool_name: { type: "string" }, input: { type: "object" }, tool_use_id: { type: "string" } }, required: ["tool_name", "input"] } },
|
|
95
|
+
...PLAN_TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema }))] } };
|
|
96
|
+
if (method === "tools/call") {
|
|
97
|
+
const planTool = PLAN_TOOLS.find((t) => t.name === params?.name);
|
|
98
|
+
if (planTool) {
|
|
99
|
+
const answer = await plan(planTool.op, params.arguments && typeof params.arguments === "object" ? params.arguments : {});
|
|
100
|
+
return { id, result: { content: [{ type: "text", text: JSON.stringify(answer) }], ...(answer?.ok ? {} : { isError: true }) } };
|
|
101
|
+
}
|
|
102
|
+
if (params?.name !== TOOL) return { id, error: { code: -32602, message: "unknown tool" } };
|
|
103
|
+
const a = params.arguments ?? {};
|
|
104
|
+
const answer = typeof a.tool_name === "string" && a.input && typeof a.input === "object"
|
|
105
|
+
? await ask({ tool_name: a.tool_name, input: a.input, tool_use_id: typeof a.tool_use_id === "string" ? a.tool_use_id : null })
|
|
106
|
+
: deny("WorkTrust remote: malformed permission request; denied");
|
|
107
|
+
return { id, result: { content: [{ type: "text", text: JSON.stringify(answer) }] } };
|
|
108
|
+
}
|
|
109
|
+
if (id === undefined) return null; // a notification
|
|
110
|
+
return { id, error: { code: -32601, message: "method not found" } };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const isMain = process.argv[1] && import.meta.url.endsWith(process.argv[1].split(/[\\/]/).pop());
|
|
114
|
+
if (isMain) {
|
|
115
|
+
createInterface({ input: process.stdin }).on("line", async (line) => {
|
|
116
|
+
let message;
|
|
117
|
+
try { message = JSON.parse(line); } catch { return; }
|
|
118
|
+
const answer = await handle(message);
|
|
119
|
+
if (!answer) return;
|
|
120
|
+
if (answer.error) error(answer.id, answer.error.code, answer.error.message); else reply(answer.id, answer.result);
|
|
121
|
+
});
|
|
122
|
+
}
|
|
@@ -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
|
+
}
|