duediligence 0.0.0-stage → 0.3.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 (147) hide show
  1. package/AGENTS.md +64 -0
  2. package/LICENSE +21 -0
  3. package/README.md +535 -2
  4. package/RESULTS.md +850 -0
  5. package/SKILL.md +249 -0
  6. package/bin/backends.mjs +762 -0
  7. package/bin/calibrate.mjs +228 -0
  8. package/bin/ci.mjs +158 -0
  9. package/bin/cli.mjs +62 -0
  10. package/bin/commitment.mjs +93 -0
  11. package/bin/confirm.mjs +370 -0
  12. package/bin/decisions.mjs +166 -0
  13. package/bin/fit.mjs +426 -0
  14. package/bin/generate.mjs +287 -0
  15. package/bin/grade.mjs +166 -0
  16. package/bin/handout.mjs +177 -0
  17. package/bin/import-archive.mjs +278 -0
  18. package/bin/judge.mjs +363 -0
  19. package/bin/lib.mjs +2048 -0
  20. package/bin/platform.mjs +145 -0
  21. package/bin/prepare.mjs +113 -0
  22. package/bin/promote.mjs +87 -0
  23. package/bin/red-team-audit.mjs +272 -0
  24. package/bin/referee.mjs +325 -0
  25. package/bin/repo.mjs +269 -0
  26. package/bin/retry.mjs +205 -0
  27. package/bin/run.mjs +170 -0
  28. package/bin/runners/boundary.mjs +220 -0
  29. package/bin/runners/cargo-test.mjs +102 -0
  30. package/bin/runners/go-test.mjs +107 -0
  31. package/bin/runners/guard.mjs +59 -0
  32. package/bin/runners/jest.mjs +103 -0
  33. package/bin/runners/native-build.mjs +63 -0
  34. package/bin/runners/node-test.mjs +108 -0
  35. package/bin/runners/pytest.mjs +149 -0
  36. package/bin/runners/shared.mjs +132 -0
  37. package/bin/runners/vitest.mjs +116 -0
  38. package/bin/seal.mjs +154 -0
  39. package/package.json +57 -4
  40. package/prompts/agent-red-team.md +22 -0
  41. package/prompts/agent.md +23 -0
  42. package/prompts/exec/agent.md +27 -0
  43. package/prompts/exec/hidden-tests.md +65 -0
  44. package/prompts/exec/public-tests.md +40 -0
  45. package/prompts/exec/reference.md +16 -0
  46. package/prompts/exec/skeleton.md +25 -0
  47. package/prompts/exec/spec-from-ticket.md +29 -0
  48. package/prompts/exec-native/agent.md +29 -0
  49. package/prompts/exec-native/hidden-tests.md +66 -0
  50. package/prompts/exec-native/public-tests.md +42 -0
  51. package/prompts/exec-native/reference.md +19 -0
  52. package/prompts/exec-native/skeleton.md +24 -0
  53. package/prompts/exec-native/spec-from-ticket.md +29 -0
  54. package/prompts/go/agent.md +22 -0
  55. package/prompts/go/hidden-tests.md +59 -0
  56. package/prompts/go/public-tests.md +33 -0
  57. package/prompts/go/reference.md +14 -0
  58. package/prompts/go/skeleton.md +31 -0
  59. package/prompts/go/spec-from-ticket.md +28 -0
  60. package/prompts/hidden-tests.md +58 -0
  61. package/prompts/http/agent.md +31 -0
  62. package/prompts/http/hidden-tests.md +67 -0
  63. package/prompts/http/public-tests.md +40 -0
  64. package/prompts/http/reference.md +19 -0
  65. package/prompts/http/skeleton.md +26 -0
  66. package/prompts/http/spec-from-ticket.md +30 -0
  67. package/prompts/http-native/agent.md +31 -0
  68. package/prompts/http-native/hidden-tests.md +70 -0
  69. package/prompts/http-native/public-tests.md +43 -0
  70. package/prompts/http-native/reference.md +20 -0
  71. package/prompts/http-native/skeleton.md +26 -0
  72. package/prompts/http-native/spec-from-ticket.md +30 -0
  73. package/prompts/lcb/agent.md +21 -0
  74. package/prompts/lcb/public-tests.md +37 -0
  75. package/prompts/public-tests.md +32 -0
  76. package/prompts/pyfunc/agent.md +19 -0
  77. package/prompts/pyfunc/hidden-tests.md +50 -0
  78. package/prompts/pyfunc/public-tests.md +30 -0
  79. package/prompts/python/agent.md +24 -0
  80. package/prompts/python/hidden-tests.md +62 -0
  81. package/prompts/python/public-tests.md +36 -0
  82. package/prompts/python/reference.md +15 -0
  83. package/prompts/python/skeleton.md +33 -0
  84. package/prompts/python/spec-from-ticket.md +30 -0
  85. package/prompts/red-team-audit.md +32 -0
  86. package/prompts/referee.md +37 -0
  87. package/prompts/reference.md +13 -0
  88. package/prompts/repo/agent-no-public.md +22 -0
  89. package/prompts/repo/agent.md +25 -0
  90. package/prompts/repo/hidden-tests.md +63 -0
  91. package/prompts/repo/public-tests.md +36 -0
  92. package/prompts/repo/reference.md +18 -0
  93. package/prompts/repo/skeleton.md +40 -0
  94. package/prompts/repo/spec-from-ticket.md +35 -0
  95. package/prompts/repo-python/agent-no-public.md +22 -0
  96. package/prompts/repo-python/agent.md +25 -0
  97. package/prompts/repo-python/hidden-tests.md +62 -0
  98. package/prompts/repo-python/public-tests.md +36 -0
  99. package/prompts/repo-python/reference.md +18 -0
  100. package/prompts/repo-python/skeleton.md +37 -0
  101. package/prompts/repo-python/spec-from-ticket.md +37 -0
  102. package/prompts/rust/agent.md +22 -0
  103. package/prompts/rust/hidden-tests.md +62 -0
  104. package/prompts/rust/public-tests.md +38 -0
  105. package/prompts/rust/reference.md +14 -0
  106. package/prompts/rust/skeleton.md +30 -0
  107. package/prompts/rust/spec-from-ticket.md +29 -0
  108. package/prompts/skeleton.md +29 -0
  109. package/prompts/spec-from-ticket.md +27 -0
  110. package/specs/duration-parse/calibration.json +104 -0
  111. package/specs/duration-parse/generation.json +69 -0
  112. package/specs/duration-parse/prepared.json +4 -0
  113. package/specs/duration-parse/reference/src/index.ts +85 -0
  114. package/specs/duration-parse/skeleton/src/index.ts +24 -0
  115. package/specs/duration-parse/spec.md +157 -0
  116. package/specs/duration-parse/tests/private/format.test.ts +157 -0
  117. package/specs/duration-parse/tests/private/parse.test.ts +252 -0
  118. package/specs/duration-parse/tests/public/format.test.ts +60 -0
  119. package/specs/duration-parse/tests/public/parse.test.ts +105 -0
  120. package/specs/duration-parse/ticket.md +7 -0
  121. package/template/.nvmrc +1 -0
  122. package/template/package-lock.json +32 -0
  123. package/template/package.json +17 -0
  124. package/template/sandbox/ambient.d.ts +86 -0
  125. package/template/sandbox/reporter.mjs +25 -0
  126. package/template/sandbox/run.mjs +121 -0
  127. package/template/sandbox/test.mjs +30 -0
  128. package/template/sandbox.env +1 -0
  129. package/template/tsconfig.json +17 -0
  130. package/template-go/README.md +15 -0
  131. package/template-go/go.mod +3 -0
  132. package/template-go/sandbox/test.sh +7 -0
  133. package/template-python/README.md +21 -0
  134. package/template-python/pytest.ini +5 -0
  135. package/template-python/requirements.txt +12 -0
  136. package/template-python/sandbox/check.py +99 -0
  137. package/template-python/sandbox/compile_check.py +28 -0
  138. package/template-python/sandbox/duediligence_reporter.py +87 -0
  139. package/template-python/sandbox/exec.py +38 -0
  140. package/template-python/sandbox/lcb/UPSTREAM +1 -0
  141. package/template-python/sandbox/lcb/__init__.py +34 -0
  142. package/template-python/sandbox/lcb/testing_util.py +592 -0
  143. package/template-python/sandbox/lcb_worker.py +18 -0
  144. package/template-python/sandbox/run.py +136 -0
  145. package/template-rust/Cargo.toml +10 -0
  146. package/template-rust/README.md +15 -0
  147. package/template-rust/sandbox/test.sh +6 -0
@@ -0,0 +1,762 @@
1
+ // The writer backends other than claude-cli, which lib.mjs `session` loads
2
+ // on demand: `codex-cli`, `anthropic-api` and `exec`. Each takes the same
3
+ // options as lib.mjs `claudeCli`, writes the same transcript shape (Claude
4
+ // Code's stream-json: a `system`/`init` line, `assistant` lines whose
5
+ // content holds `text` and `tool_use` blocks with Claude Code's tool names
6
+ // and inputs, `user` lines with `tool_result` blocks, a final `result`
7
+ // line), so `peeks`, `audit` and every report read any backend's transcript
8
+ // unchanged, and resolves with the same record plus `backend`.
9
+ //
10
+ // Blindness by placement. claude-cli is held by Claude Code's deny rules
11
+ // (lib.mjs `sessionSettings`); these backends run what the writer does
12
+ // under an OS sandbox instead (`placement`): sandbox-exec on macOS, bwrap
13
+ // on Linux. Reads and writes are refused in the person's home, the
14
+ // package, HOME/SPECS/RUNS/RESULTS wherever they are, the transcripts,
15
+ // WORK_ROOT and the temp folders, except the session's own workdir and its
16
+ // state folder (WORK_ROOT/sessions/<id>/: CODEX_HOME, HOME, TMPDIR), which
17
+ // are the only writable places; the tool's own install and interpreters
18
+ // are readable. The staged workdir already holds only what the writer may
19
+ // see (lib.mjs `stage`), so a writer cannot reach a hidden suite at rest,
20
+ // another workdir, a judge tree or a transcript, whatever it runs.
21
+ //
22
+ // - codex-cli: the Codex CLI (@openai/codex, pinned, installed once under
23
+ // HOME/backends/ with the pinned npm) on the person's own Codex login,
24
+ // ~/.codex/auth.json copied into the session's CODEX_HOME and written
25
+ // back if Codex refreshed it, then removed. Codex runs on the host under
26
+ // `placement`, not in a container, and with its own sandbox off
27
+ // (`--dangerously-bypass-approvals-and-sandbox`, the mode Codex documents
28
+ // for an externally sandboxed run): the staged trees hold host toolchains
29
+ // (a Python venv linked to the host interpreter, a repository base with
30
+ // node_modules built for this OS) that a Linux container could not run,
31
+ // and one sandbox over the whole process is simpler to check than two.
32
+ // Model: a non-Claude `model`, else DUEDILIGENCE_CODEX_MODEL, else
33
+ // the person's ~/.codex/config.toml `model` and reasoning effort. Billing
34
+ // is the Codex subscription, so costUsd is null. A usage or rate limit is
35
+ // reported as apiError `usage_limit_reached`, which the callers halt on.
36
+ // - anthropic-api: Claude through the Messages API (ANTHROPIC_API_KEY,
37
+ // ANTHROPIC_BASE_URL), the official SDK installed once under
38
+ // HOME/backends/, a manual tool loop over Bash, Read, Write, Edit, Glob
39
+ // and Grep. The file tools resolve every path inside the workdir (real
40
+ // paths, so no symlink leaves it); Bash runs under `placement` without
41
+ // network. Cost from usage at list prices, stopped at the kind's budget.
42
+ // - exec: any command (`command`, DUEDILIGENCE_EXEC or toolchain.json
43
+ // `exec`) run by sh in the workdir under `placement`, the prompt on its
44
+ // stdin; its output is the transcript's one assistant message.
45
+ //
46
+ // `placement`'s denial is checked by evidence/backends.mjs `sandbox`, a
47
+ // negative test that reads a hidden-suite path and the home from inside.
48
+ // Windows has neither sandbox: there `placement` runs the command as it
49
+ // is, the shell being Git for Windows' bash, and says so once (lib.mjs
50
+ // `warnUnsandboxed`); the staged workdir and the transcript audit are what
51
+ // keep a writer blind, and anthropic-api's file tools stay confined.
52
+
53
+ import { spawn } from "node:child_process";
54
+ import { randomUUID } from "node:crypto";
55
+ import {
56
+ appendFileSync,
57
+ existsSync,
58
+ mkdirSync,
59
+ readFileSync,
60
+ realpathSync,
61
+ renameSync,
62
+ rmSync,
63
+ statSync,
64
+ writeFileSync,
65
+ } from "node:fs";
66
+ import { createRequire } from "node:module";
67
+ import { homedir, tmpdir } from "node:os";
68
+ import { basename, dirname, join, posix, relative, resolve } from "node:path";
69
+ import { pathToFileURL } from "node:url";
70
+ import {
71
+ DEFAULT_MODEL,
72
+ HOME,
73
+ PRIVATE,
74
+ PYTHON,
75
+ RESULTS,
76
+ TRANSCRIPTS,
77
+ WORK_ROOT,
78
+ installEnv,
79
+ killGroup,
80
+ limits,
81
+ listFiles,
82
+ log,
83
+ sha256,
84
+ takeSlot,
85
+ warnUnsandboxed,
86
+ } from "./lib.mjs";
87
+ import { GROUP, OS_SANDBOX, WINDOWS, gitBash, inside, pathKey, slash, spawnCommand, which } from "./platform.mjs";
88
+
89
+ export const CODEX_VERSION = "0.164.0";
90
+ export const SDK_VERSION = "0.137.0";
91
+ /** Per session: CODEX_HOME, HOME, TMPDIR, the API backend's messages. */
92
+ export const SESSIONS = join(WORK_ROOT, "sessions");
93
+
94
+ /** `path` made real as far as it exists (the sandboxes match real paths). */
95
+ export function real(path) {
96
+ let at = resolve(path);
97
+ const rest = [];
98
+ while (!existsSync(at) && dirname(at) !== at) {
99
+ rest.unshift(basename(at));
100
+ at = dirname(at);
101
+ }
102
+ return join(realpathSync(at), ...rest);
103
+ }
104
+
105
+ /**
106
+ * An npm package at an exact version, installed once with the pinned npm
107
+ * under HOME/backends/<name>-<version>/ (a partial folder renamed, as
108
+ * lib.mjs `ensureTemplate` does). Network once.
109
+ */
110
+ export function installTool(name, spec, version) {
111
+ const dest = join(HOME, "backends", `${name}-${version}`);
112
+ if (existsSync(join(dest, ".installed.json"))) return dest;
113
+ const partial = `${dest}.partial-${process.pid}`;
114
+ rmSync(partial, { recursive: true, force: true });
115
+ mkdirSync(partial, { recursive: true });
116
+ writeFileSync(join(partial, "package.json"), `${JSON.stringify({ private: true })}\n`);
117
+ log(`installing ${spec}@${version} into ${dest} (npm@10.9.2, once)`);
118
+ const out = spawnCommand("npx", ["-y", "npm@10.9.2", "install", "--no-audit", "--no-fund", "--save-exact", `${spec}@${version}`], {
119
+ cwd: partial,
120
+ encoding: "utf8",
121
+ maxBuffer: 64 * 1024 * 1024,
122
+ env: installEnv(),
123
+ });
124
+ if (out.status !== 0) {
125
+ rmSync(partial, { recursive: true, force: true });
126
+ throw new Error(`installing ${spec}@${version} failed:\n${`${out.error ?? ""}${out.stdout}${out.stderr}`.slice(-4000)}`);
127
+ }
128
+ writeFileSync(join(partial, ".installed.json"), `${JSON.stringify({ spec, version, at: new Date().toISOString() })}\n`);
129
+ if (existsSync(join(dest, ".installed.json"))) rmSync(partial, { recursive: true, force: true });
130
+ else {
131
+ rmSync(dest, { recursive: true, force: true });
132
+ renameSync(partial, dest);
133
+ }
134
+ return dest;
135
+ }
136
+
137
+ /** The install prefix of a binary (two folders above its real path), for the sandbox's read list. */
138
+ function prefixOf(bin) {
139
+ const found = which(bin);
140
+ if (found === null) return null;
141
+ return dirname(dirname(realpathSync(found)));
142
+ }
143
+
144
+ /**
145
+ * What a placed process may not read or write, what it may only read, and
146
+ * what it may write. `read` adds the tool's own install. A readable or
147
+ * writable path that holds a private folder is refused outright.
148
+ */
149
+ export function placementPaths({ cwd, state, read = [] }) {
150
+ const temp = real(tmpdir());
151
+ const denied = [
152
+ homedir(),
153
+ ...PRIVATE,
154
+ RESULTS,
155
+ TRANSCRIPTS,
156
+ WORK_ROOT,
157
+ temp,
158
+ // macOS: the per-user folder above TMPDIR (T/, C/, 0/).
159
+ ...(process.platform === "darwin" && temp.startsWith("/private/var/folders/") ? [dirname(temp)] : []),
160
+ process.platform === "darwin" ? "/private/tmp" : "/tmp",
161
+ ...(process.platform === "darwin" ? ["/Volumes"] : []),
162
+ ];
163
+ const deny = [...new Set(denied.map(real))].filter((path) => path !== "/").sort();
164
+ const extra = (process.env.DUEDILIGENCE_SANDBOX_READ ?? "").split(":").filter(Boolean);
165
+ // Only what a denied folder would hide needs naming; anything else is readable already.
166
+ const readable = [...new Set([...read, prefixOf(process.execPath), prefixOf(PYTHON), ...extra].filter(Boolean).map(real))]
167
+ .filter((path) => deny.some((folder) => inside(path, folder)))
168
+ .sort();
169
+ const writable = [cwd, state].map(real);
170
+ for (const path of [...readable, ...writable])
171
+ for (const folder of PRIVATE.map(real))
172
+ if (inside(folder, path)) throw new Error(`The sandbox may not open ${path}: it holds ${folder}.`);
173
+ return { deny, readable, writable };
174
+ }
175
+
176
+ const sbpl = (path) => `"${path.replaceAll("\\", "\\\\").replaceAll('"', '\\"')}"`;
177
+ /** The macOS sandbox profile: the last matching rule wins, so the allows follow the denies. */
178
+ export function seatbeltProfile({ deny, readable, writable }, network) {
179
+ const paths = (list) => list.map((path) => `(subpath ${sbpl(path)})`).join(" ");
180
+ // Resolving a real path stats every folder above it: those folders' own
181
+ // metadata, never their listing or contents.
182
+ const above = new Set();
183
+ for (const path of [...readable, ...writable])
184
+ for (let at = dirname(path); at !== "/" && deny.some((folder) => inside(at, folder)); at = dirname(at)) above.add(at);
185
+ return [
186
+ "(version 1)",
187
+ "(allow default)",
188
+ `(deny file-read* file-write* ${paths(deny)})`,
189
+ ...(above.size > 0 ? [`(allow file-read-metadata ${[...above].sort().map((path) => `(literal ${sbpl(path)})`).join(" ")})`] : []),
190
+ ...(readable.length > 0 ? [`(allow file-read* ${paths(readable)})`] : []),
191
+ "(deny file-write*)",
192
+ '(allow file-write* (literal "/dev/null") (literal "/dev/zero") (literal "/dev/tty") (literal "/dev/dtracehelper") (regex #"^/dev/fd/") (regex #"^/dev/ttys") (literal "/dev/ptmx"))',
193
+ `(allow file-read* file-write* ${paths(writable)})`,
194
+ ...(network ? [] : ["(deny network*)"]),
195
+ ].join("\n");
196
+ }
197
+
198
+ /** The Linux equivalent: bwrap over a read-only root, the denied folders blanked, the workdir and state bound. */
199
+ export function bwrapArgs({ deny, readable, writable }, network, cwd) {
200
+ const out = ["--die-with-parent", "--new-session", "--unshare-all", ...(network ? ["--share-net"] : []), "--ro-bind", "/", "/", "--dev", "/dev", "--proc", "/proc"];
201
+ for (const path of deny) {
202
+ if (!existsSync(path)) continue;
203
+ out.push(...(statSync(path).isDirectory() ? ["--tmpfs", path] : ["--ro-bind", "/dev/null", path]));
204
+ }
205
+ for (const path of readable) if (existsSync(path)) out.push("--ro-bind", path, path);
206
+ for (const path of writable) out.push("--bind", path, path);
207
+ out.push("--chdir", cwd);
208
+ return out;
209
+ }
210
+
211
+ /**
212
+ * The shell `placement` runs a command line in: /bin/sh and /bin/bash on
213
+ * macOS and Linux, Git for Windows' bash on Windows (what Claude Code's
214
+ * Bash tool runs there).
215
+ */
216
+ export function shellBin(name) {
217
+ if (!WINDOWS) return `/bin/${name}`;
218
+ const bash = gitBash();
219
+ if (bash === null) throw new Error("No bash: install Git for Windows, or set CLAUDE_CODE_GIT_BASH_PATH to its bash.exe.");
220
+ return bash;
221
+ }
222
+ /** `bin argv` wrapped in the platform's sandbox: [bin, argv]. Windows has none: [bin, argv] as given. */
223
+ export function placement(bin, argv, { cwd, state, read = [], network = true }) {
224
+ if (!OS_SANDBOX) {
225
+ warnUnsandboxed();
226
+ return [bin, argv];
227
+ }
228
+ const paths = placementPaths({ cwd, state, read });
229
+ if (process.platform === "darwin") return ["/usr/bin/sandbox-exec", ["-p", seatbeltProfile(paths, network), bin, ...argv]];
230
+ const found = which("bwrap");
231
+ if (found === null) throw new Error("No bwrap on PATH: a non-Claude backend on Linux needs bubblewrap for its sandbox.");
232
+ return [found, [...bwrapArgs(paths, network, cwd), "--", bin, ...argv]];
233
+ }
234
+
235
+ /** A session's state folder, kept across a resume of the same transcript and cleared on a fresh start. */
236
+ function stateOf(transcript, resume) {
237
+ const dir = join(SESSIONS, sha256(transcript).slice(0, 16));
238
+ if (!resume) rmSync(dir, { recursive: true, force: true });
239
+ for (const sub of ["home", "tmp"]) mkdirSync(join(dir, sub), { recursive: true });
240
+ return dir;
241
+ }
242
+
243
+ /**
244
+ * The environment a placed process starts with: nothing of the caller's
245
+ * but the basics, plus on Windows what any process there needs to start
246
+ * (SystemRoot, ComSpec, PATHEXT) and the state folder as its profile and
247
+ * temp folder too.
248
+ */
249
+ function childEnv(state, extra = {}) {
250
+ const keep = ["LANG", "LC_ALL", "LC_CTYPE", "TERM", "USER", "LOGNAME", "SHELL"];
251
+ const windows = ["SystemRoot", "SystemDrive", "windir", "ComSpec", "PATHEXT", "USERNAME", "NUMBER_OF_PROCESSORS", "PROCESSOR_ARCHITECTURE"];
252
+ const home = join(state, "home");
253
+ const temp = join(state, "tmp");
254
+ return {
255
+ [pathKey(process.env)]: process.env[pathKey(process.env)],
256
+ ...Object.fromEntries(
257
+ [...keep, ...(WINDOWS ? windows : [])].filter((key) => process.env[key] !== undefined).map((key) => [key, process.env[key]]),
258
+ ),
259
+ HOME: home,
260
+ TMPDIR: temp,
261
+ ...(WINDOWS ? { USERPROFILE: home, TEMP: temp, TMP: temp, APPDATA: join(home, "AppData", "Roaming"), LOCALAPPDATA: join(home, "AppData", "Local") } : {}),
262
+ ...extra,
263
+ };
264
+ }
265
+
266
+ /** Appends Claude Code stream-json lines, each stamped with its time. */
267
+ function transcriptWriter(path, resume) {
268
+ mkdirSync(dirname(path), { recursive: true });
269
+ if (!resume) writeFileSync(path, "");
270
+ return (event) => appendFileSync(path, `${JSON.stringify({ ...event, timestamp: new Date().toISOString() })}\n`);
271
+ }
272
+ const toolUse = (id, name, input) => ({ type: "tool_use", id, name, input });
273
+ const assistant = (content) => ({ type: "assistant", message: { role: "assistant", content } });
274
+ const toolResults = (results) => ({ type: "user", message: { role: "user", content: results } });
275
+ const LIMITED = /usage limit|rate.?limit|quota|too many requests|429|out of credits|add credits/i;
276
+
277
+ /** Runs a placed child to its end or its time limit: { code, timedOut, stderr }, stdout line by line to `onLine`. */
278
+ function runChild(bin, argv, { cwd, env, input, minutes, onLine }) {
279
+ return new Promise((done) => {
280
+ // A group leader, its group killed when it closes: nothing it started outlives the session.
281
+ const child = spawn(bin, argv, { cwd, env, stdio: ["pipe", "pipe", "pipe"], ...GROUP });
282
+ const reap = () => killGroup(child.pid);
283
+ process.once("exit", reap);
284
+ child.on("exit", reap);
285
+ let stderr = "";
286
+ let buffer = "";
287
+ child.stdout.setEncoding("utf8");
288
+ child.stdout.on("data", (chunk) => {
289
+ buffer += chunk;
290
+ const lines = buffer.split("\n");
291
+ buffer = lines.pop();
292
+ for (const line of lines) onLine(line);
293
+ });
294
+ child.stderr.on("data", (chunk) => (stderr = (stderr + chunk).slice(-20_000)));
295
+ child.stdin.on("error", () => {});
296
+ child.stdin.end(input);
297
+ let timedOut = false;
298
+ const timer = setTimeout(() => {
299
+ timedOut = true;
300
+ child.kill("SIGTERM");
301
+ setTimeout(() => child.kill("SIGKILL"), 10_000).unref();
302
+ }, minutes * 60_000);
303
+ child.on("error", (error) => (stderr += String(error)));
304
+ child.on("close", (code) => {
305
+ clearTimeout(timer);
306
+ reap();
307
+ process.removeListener("exit", reap);
308
+ if (buffer !== "") onLine(buffer);
309
+ done({ code, timedOut, stderr });
310
+ });
311
+ });
312
+ }
313
+
314
+ /** The person's Codex settings worth keeping: top-level `model` and `model_reasoning_effort`, nothing else (no MCP servers, plugins or notify hooks). */
315
+ function codexSettings() {
316
+ const source = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "config.toml");
317
+ const text = existsSync(source) ? readFileSync(source, "utf8") : "";
318
+ const top = text.split(/^\[/m)[0];
319
+ const pick = (key) => new RegExp(`^${key}\\s*=\\s*"([^"]*)"`, "m").exec(top)?.[1] ?? null;
320
+ return { model: pick("model"), effort: pick("model_reasoning_effort") };
321
+ }
322
+
323
+ const CODEX_OFF = ["apps", "plugins", "remote_plugin", "browser_use", "browser_use_external", "in_app_browser", "computer_use", "image_generation", "hooks", "multi_agent", "skill_search", "skill_mcp_dependency_install", "tool_suggest"];
324
+
325
+ async function codexCli({ cwd, text, transcript, kind, resume, model, chain }) {
326
+ const { minutes } = limits(kind, chain);
327
+ const install = installTool("codex", "@openai/codex", CODEX_VERSION);
328
+ const state = stateOf(transcript, resume);
329
+ const codexHome = join(state, "codex");
330
+ mkdirSync(codexHome, { recursive: true });
331
+ const settings = codexSettings();
332
+ const chosen = (model && !/^claude/.test(model) ? model : null) ?? process.env.DUEDILIGENCE_CODEX_MODEL ?? settings.model;
333
+ // A writer gets the shell and file edits only: no web search, ChatGPT
334
+ // apps (the person's connected accounts), plugins, browser, computer use,
335
+ // hooks, sub-agents or image generation.
336
+ writeFileSync(
337
+ join(codexHome, "config.toml"),
338
+ [
339
+ chosen && `model = "${chosen}"`,
340
+ settings.effort && `model_reasoning_effort = "${settings.effort}"`,
341
+ 'web_search = "disabled"',
342
+ "",
343
+ "[features]",
344
+ ...CODEX_OFF.map((feature) => `${feature} = false`),
345
+ ]
346
+ .filter((line) => typeof line === "string")
347
+ .join("\n") + "\n",
348
+ );
349
+ const authSource = join(process.env.CODEX_HOME ?? join(homedir(), ".codex"), "auth.json");
350
+ const authCopy = join(codexHome, "auth.json");
351
+ const authBefore = existsSync(authSource) ? readFileSync(authSource) : null;
352
+ if (authBefore !== null) writeFileSync(authCopy, authBefore, { mode: 0o600 });
353
+ const flags = ["--json", "--skip-git-repo-check", "--dangerously-bypass-approvals-and-sandbox", "--ignore-rules", "--strict-config"];
354
+ const argv = [
355
+ join(install, "node_modules", "@openai", "codex", "bin", "codex.js"),
356
+ "exec",
357
+ ...(resume ? ["resume", resume, ...flags, "-"] : [...flags, "-C", cwd, "-"]),
358
+ ];
359
+ const [bin, wrapped] = placement(process.execPath, argv, { cwd, state, read: [install] });
360
+ const write = transcriptWriter(transcript, resume);
361
+ const raw = transcript.replace(/(\.jsonl)?$/, ".codex.jsonl");
362
+ if (!resume) writeFileSync(raw, "");
363
+ const env = childEnv(state, { CODEX_HOME: codexHome });
364
+ for (const key of ["OPENAI_API_KEY", "CODEX_API_KEY"]) if (process.env[key]) env[key] = process.env[key];
365
+
366
+ const slot = await takeSlot();
367
+ const started = Date.now();
368
+ let sessionId = resume ?? null;
369
+ let finalText = "";
370
+ let turns = 0;
371
+ let usage = null;
372
+ let failure = null;
373
+ let completed = false;
374
+ const { code, timedOut, stderr } = await (async () => {
375
+ try {
376
+ return await runChild(bin, wrapped, {
377
+ cwd,
378
+ env,
379
+ input: text,
380
+ minutes,
381
+ onLine: (line) => {
382
+ if (!line.startsWith("{")) return;
383
+ appendFileSync(raw, `${line}\n`);
384
+ let event;
385
+ try {
386
+ event = JSON.parse(line);
387
+ } catch {
388
+ return;
389
+ }
390
+ if (event.type === "thread.started") {
391
+ sessionId = event.thread_id;
392
+ write({ type: "system", subtype: "init", session_id: sessionId, model: chosen, cwd, backend: "codex-cli", resumed: resume ?? null });
393
+ } else if (event.type === "turn.completed") {
394
+ completed = true;
395
+ usage = event.usage ?? null;
396
+ } else if (event.type === "turn.failed") failure = event.error?.message ?? "turn failed";
397
+ else if (event.type === "error") failure = event.message ?? "error";
398
+ else if (event.type === "item.completed") {
399
+ const item = event.item ?? {};
400
+ if (item.type === "agent_message") {
401
+ finalText = item.text ?? "";
402
+ turns += 1;
403
+ write(assistant([{ type: "text", text: finalText }]));
404
+ } else if (item.type === "command_execution") {
405
+ turns += 1;
406
+ write(assistant([toolUse(item.id, "Bash", { command: item.command })]));
407
+ write(toolResults([{ type: "tool_result", tool_use_id: item.id, content: (item.aggregated_output ?? "").slice(-4000), is_error: item.exit_code !== 0 }]));
408
+ } else if (item.type === "file_change") {
409
+ turns += 1;
410
+ const changes = item.changes ?? [];
411
+ write(assistant(changes.map((change, at) => toolUse(`${item.id}-${at}`, change.kind === "add" ? "Write" : "Edit", { file_path: change.path, kind: change.kind }))));
412
+ write(toolResults(changes.map((_, at) => ({ type: "tool_result", tool_use_id: `${item.id}-${at}`, content: item.status ?? "", is_error: item.status === "failed" }))));
413
+ } else if (item.type === "error") failure = item.message ?? "error";
414
+ else if (!["reasoning", "todo_list"].includes(item.type)) {
415
+ turns += 1;
416
+ const { id, type, ...input } = item;
417
+ write(assistant([toolUse(id, type, input)]));
418
+ }
419
+ }
420
+ },
421
+ });
422
+ } finally {
423
+ rmSync(slot, { force: true });
424
+ // A refreshed login goes back to the person's Codex home, unless it changed there meanwhile.
425
+ if (existsSync(authCopy)) {
426
+ const after = readFileSync(authCopy);
427
+ const now = existsSync(authSource) ? readFileSync(authSource) : null;
428
+ if (authBefore !== null && now !== null && now.equals(authBefore) && !after.equals(authBefore)) {
429
+ writeFileSync(`${authSource}.partial-${process.pid}`, after, { mode: 0o600 });
430
+ renameSync(`${authSource}.partial-${process.pid}`, authSource);
431
+ }
432
+ rmSync(authCopy, { force: true });
433
+ }
434
+ }
435
+ })();
436
+ const limitHit = [failure ?? "", completed ? "" : stderr].some((message) => LIMITED.test(message));
437
+ const ok = code === 0 && completed && failure === null && !timedOut;
438
+ const result = {
439
+ sessionId,
440
+ model: chosen,
441
+ ok,
442
+ exitCode: code,
443
+ timedOut,
444
+ costUsd: null,
445
+ turns,
446
+ durationMs: Date.now() - started,
447
+ subtype: ok ? "success" : timedOut ? "error_timeout" : "error_during_execution",
448
+ apiError: ok ? null : limitHit ? "usage_limit_reached" : failure === null ? null : "error",
449
+ finalText: finalText || (failure ?? ""),
450
+ stderr: stderr.slice(-2000),
451
+ backend: "codex-cli",
452
+ };
453
+ write({ type: "result", subtype: result.subtype, is_error: !ok, session_id: sessionId, total_cost_usd: null, num_turns: turns, result: result.finalText, usage, api_error: result.apiError, backend: "codex-cli" });
454
+ return result;
455
+ }
456
+
457
+ async function execBackend({ cwd, text, transcript, kind, resume, chain, command }) {
458
+ const { minutes } = limits(kind, chain);
459
+ const line = command ?? process.env.DUEDILIGENCE_EXEC ?? chain?.exec;
460
+ const write = transcriptWriter(transcript, resume);
461
+ const sessionId = resume ?? randomUUID();
462
+ const base = { sessionId, model: null, costUsd: null, turns: 1, apiError: null, backend: "exec" };
463
+ if (typeof line !== "string" || line === "") {
464
+ const finalText = "No command: set DUEDILIGENCE_EXEC or toolchain.json `exec`.";
465
+ write({ type: "result", subtype: "error_during_execution", is_error: true, session_id: sessionId, result: finalText, backend: "exec" });
466
+ return { ...base, ok: false, exitCode: null, timedOut: false, durationMs: 0, subtype: "error_during_execution", finalText, stderr: "" };
467
+ }
468
+ const state = stateOf(transcript, resume);
469
+ const [bin, argv] = placement(shellBin("sh"), ["-c", line], { cwd, state });
470
+ const passed = (process.env.DUEDILIGENCE_EXEC_ENV ?? "").split(",").filter((key) => key && process.env[key] !== undefined);
471
+ const env = childEnv(state, Object.fromEntries(passed.map((key) => [key, process.env[key]])));
472
+ write({ type: "system", subtype: "init", session_id: sessionId, model: null, cwd, backend: "exec", command: line });
473
+ const slot = await takeSlot();
474
+ const started = Date.now();
475
+ let stdout = "";
476
+ let outcome;
477
+ try {
478
+ outcome = await runChild(bin, argv, { cwd, env, input: text, minutes, onLine: (out) => (stdout = `${stdout}${out}\n`.slice(-100_000)) });
479
+ } finally {
480
+ rmSync(slot, { force: true });
481
+ }
482
+ const ok = outcome.code === 0 && !outcome.timedOut;
483
+ const finalText = stdout.trim().slice(-20_000);
484
+ write(assistant([{ type: "text", text: finalText }]));
485
+ const subtype = ok ? "success" : outcome.timedOut ? "error_timeout" : "error_during_execution";
486
+ write({ type: "result", subtype, is_error: !ok, session_id: sessionId, total_cost_usd: null, num_turns: 1, result: finalText, backend: "exec" });
487
+ return { ...base, ok, exitCode: outcome.code, timedOut: outcome.timedOut, durationMs: Date.now() - started, subtype, finalText, stderr: outcome.stderr.slice(-2000) };
488
+ }
489
+
490
+ // ---- anthropic-api ----
491
+
492
+ /** List prices per million tokens (claude-api skill, cached 2026-10-06); a cache write costs 1.25x input. */
493
+ const PRICES = {
494
+ "claude-fable-5-1": { input: 10, output: 50, cacheRead: 0.25 },
495
+ "claude-opus-5-5": { input: 4, output: 20, cacheRead: 0.2 },
496
+ "claude-sonnet-5-5": { input: 2, output: 10, cacheRead: 0.2 },
497
+ "claude-haiku-5-5": { input: 0.1, output: 0.5, cacheRead: 0.01 },
498
+ };
499
+ /** Models that take the server-side refusal fallback (`fallbacks: "default"`). */
500
+ const FALLBACK_MODELS = ["claude-fable-5-1", "claude-opus-5-5", "claude-opus-5", "claude-sonnet-5-5"];
501
+ const costOf = (model, usage) => {
502
+ const price = PRICES[model];
503
+ if (price === undefined || usage === undefined) return 0;
504
+ return (
505
+ ((usage.input_tokens ?? 0) * price.input +
506
+ (usage.cache_creation_input_tokens ?? 0) * price.input * 1.25 +
507
+ (usage.cache_read_input_tokens ?? 0) * price.cacheRead +
508
+ (usage.output_tokens ?? 0) * price.output) /
509
+ 1e6
510
+ );
511
+ };
512
+
513
+ /** The SDK's Anthropic class, from its pinned install under HOME/backends/. */
514
+ async function anthropicSdk() {
515
+ const install = installTool("anthropic-sdk", "@anthropic-ai/sdk", SDK_VERSION);
516
+ const entry = createRequire(join(install, "package.json")).resolve("@anthropic-ai/sdk");
517
+ const mod = await import(pathToFileURL(entry).href);
518
+ return mod.default?.default ?? mod.default ?? mod.Anthropic;
519
+ }
520
+
521
+ const TOOL_DEFS = [
522
+ {
523
+ name: "Bash",
524
+ description: "Run a shell command in the working directory (bash -c, no network). Returns its output and exit code.",
525
+ input_schema: { type: "object", properties: { command: { type: "string" }, timeout: { type: "number", description: "milliseconds, at most 600000" } }, required: ["command"] },
526
+ },
527
+ {
528
+ name: "Read",
529
+ description: "Read a file in the working directory, with line numbers.",
530
+ input_schema: { type: "object", properties: { file_path: { type: "string" }, offset: { type: "number" }, limit: { type: "number" } }, required: ["file_path"] },
531
+ },
532
+ {
533
+ name: "Write",
534
+ description: "Write a file in the working directory, replacing it if it exists.",
535
+ input_schema: { type: "object", properties: { file_path: { type: "string" }, content: { type: "string" } }, required: ["file_path", "content"] },
536
+ },
537
+ {
538
+ name: "Edit",
539
+ description: "Replace old_string with new_string in a file; old_string must occur exactly once unless replace_all.",
540
+ input_schema: {
541
+ type: "object",
542
+ properties: { file_path: { type: "string" }, old_string: { type: "string" }, new_string: { type: "string" }, replace_all: { type: "boolean" } },
543
+ required: ["file_path", "old_string", "new_string"],
544
+ },
545
+ },
546
+ {
547
+ name: "Glob",
548
+ description: "List files in the working directory matching a glob such as **/*.ts.",
549
+ input_schema: { type: "object", properties: { pattern: { type: "string" }, path: { type: "string" } }, required: ["pattern"] },
550
+ },
551
+ {
552
+ name: "Grep",
553
+ description: "Search file contents in the working directory with a regular expression; returns path:line:text.",
554
+ input_schema: { type: "object", properties: { pattern: { type: "string" }, path: { type: "string" }, glob: { type: "string" } }, required: ["pattern"] },
555
+ },
556
+ ];
557
+
558
+ /** A glob over relative paths as a RegExp: `**`, `*`, `?`, `{a,b}`. */
559
+ export function globRegExp(glob) {
560
+ let out = "";
561
+ for (let at = 0; at < glob.length; at += 1) {
562
+ const char = glob[at];
563
+ if (char === "*" && glob[at + 1] === "*") {
564
+ at += 1;
565
+ if (glob[at + 1] === "/") {
566
+ at += 1;
567
+ out += "(?:.*/)?";
568
+ } else out += ".*";
569
+ } else if (char === "*") out += "[^/]*";
570
+ else if (char === "?") out += "[^/]";
571
+ else if (char === "{") {
572
+ const end = glob.indexOf("}", at);
573
+ out += `(?:${glob.slice(at + 1, end).split(",").map((alt) => alt.replace(/[.+^$()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*")).join("|")})`;
574
+ at = end;
575
+ } else out += char.replace(/[.+^$()|[\]\\]/g, "\\$&");
576
+ }
577
+ return new RegExp(`^${out}$`);
578
+ }
579
+
580
+ /**
581
+ * The file tools, each confined to `root`: a path is resolved against it
582
+ * and refused unless its real path (as far as it exists) is inside it.
583
+ */
584
+ function fileTools(root, runBash) {
585
+ const realRoot = real(root);
586
+ const confined = (path = ".") => {
587
+ const full = resolve(root, path);
588
+ if (!inside(real(full), realRoot)) throw new Error(`${path} is outside the working directory ${root}`);
589
+ return full;
590
+ };
591
+ const shown = (full) => slash(relative(root, full)) || ".";
592
+ return {
593
+ Bash: (input) => runBash(String(input.command ?? ""), Math.min(Number(input.timeout ?? 120_000), 600_000)),
594
+ Read: (input) => {
595
+ const full = confined(input.file_path);
596
+ const lines = readFileSync(full, "utf8").split("\n");
597
+ const from = Math.max(Number(input.offset ?? 1), 1);
598
+ const count = Number(input.limit ?? 2000);
599
+ return lines
600
+ .slice(from - 1, from - 1 + count)
601
+ .map((line, at) => `${String(from + at).padStart(6)}\t${line.slice(0, 2000)}`)
602
+ .join("\n");
603
+ },
604
+ Write: (input) => {
605
+ const full = confined(input.file_path);
606
+ mkdirSync(dirname(full), { recursive: true });
607
+ writeFileSync(full, String(input.content ?? ""));
608
+ return `wrote ${shown(full)}`;
609
+ },
610
+ Edit: (input) => {
611
+ const full = confined(input.file_path);
612
+ const source = readFileSync(full, "utf8");
613
+ const old = String(input.old_string ?? "");
614
+ const found = old === "" ? 0 : source.split(old).length - 1;
615
+ if (found === 0) throw new Error("old_string was not found");
616
+ if (found > 1 && input.replace_all !== true) throw new Error(`old_string occurs ${found} times; give more context or replace_all`);
617
+ writeFileSync(full, input.replace_all === true ? source.replaceAll(old, String(input.new_string)) : source.replace(old, () => String(input.new_string)));
618
+ return `edited ${shown(full)}`;
619
+ },
620
+ Glob: (input) => {
621
+ const base = confined(input.path);
622
+ const matches = globRegExp(String(input.pattern));
623
+ const hits = listFiles(base).filter((path) => matches.test(path) || (!String(input.pattern).includes("/") && matches.test(basename(path))));
624
+ return hits.slice(0, 500).map((path) => posix.join(shown(base) === "." ? "" : shown(base), path)).join("\n") || "no files";
625
+ },
626
+ Grep: (input) => {
627
+ const base = confined(input.path);
628
+ const pattern = new RegExp(String(input.pattern));
629
+ const only = input.glob ? globRegExp(String(input.glob)) : null;
630
+ const out = [];
631
+ const files = statSync(base).isDirectory() ? listFiles(base).map((path) => join(base, path)) : [base];
632
+ for (const full of files) {
633
+ if (only !== null && !only.test(slash(relative(base, full))) && !only.test(basename(full))) continue;
634
+ if (statSync(full).size > 1_000_000) continue;
635
+ const lines = readFileSync(full, "utf8").split("\n");
636
+ lines.forEach((line, at) => {
637
+ if (out.length < 250 && pattern.test(line)) out.push(`${shown(full)}:${at + 1}:${line.slice(0, 500)}`);
638
+ });
639
+ }
640
+ return out.join("\n") || "no matches";
641
+ },
642
+ };
643
+ }
644
+
645
+ const systemPrompt = (cwd) =>
646
+ `You are a coding agent working in ${cwd}. It is your working directory and the only folder you can read or write: every tool resolves paths inside it, and Bash runs there without network. Do the task you are given with the tools. When it is done, reply with your final message and no tool call.`;
647
+
648
+ async function anthropicApi({ cwd, text, transcript, kind, resume, model, maxTurns, chain }) {
649
+ const { minutes, budgetUsd } = limits(kind, chain);
650
+ const chosen = model && /^claude/.test(model) ? model : (process.env.DUEDILIGENCE_MODEL ?? DEFAULT_MODEL);
651
+ const state = stateOf(transcript, resume);
652
+ const write = transcriptWriter(transcript, resume);
653
+ const saved = join(state, "messages.json");
654
+ const sessionId = resume ?? randomUUID();
655
+ const messages = resume && existsSync(saved) ? JSON.parse(readFileSync(saved, "utf8")) : [];
656
+ messages.push({ role: "user", content: text });
657
+ write({ type: "system", subtype: "init", session_id: sessionId, model: chosen, cwd, backend: "anthropic-api", resumed: resume ?? null });
658
+ const started = Date.now();
659
+ const deadline = started + minutes * 60_000;
660
+ const runBash = (command, timeout) => {
661
+ const [bin, argv] = placement(shellBin("bash"), ["-c", command], { cwd, state, network: false });
662
+ return new Promise((done) => {
663
+ let output = "";
664
+ const child = spawn(bin, argv, { cwd, env: childEnv(state), stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
665
+
666
+ const take = (chunk) => (output = (output + chunk).slice(-30_000));
667
+ child.stdout.on("data", take);
668
+ child.stderr.on("data", take);
669
+ const timer = setTimeout(() => child.kill("SIGKILL"), Math.max(1000, Math.min(timeout, deadline - Date.now())));
670
+ child.on("close", (code) => {
671
+ clearTimeout(timer);
672
+ done(`${output}${output.endsWith("\n") || output === "" ? "" : "\n"}(exit ${code ?? "killed"})`);
673
+ });
674
+ });
675
+ };
676
+ const tools = fileTools(cwd, runBash);
677
+ const base = { sessionId, model: chosen, backend: "anthropic-api" };
678
+ const finish = (fields) => {
679
+ writeFileSync(saved, JSON.stringify(messages));
680
+ const result = { ...base, costUsd: Math.round(cost * 1e6) / 1e6, turns, durationMs: Date.now() - started, stderr: "", ...fields };
681
+ write({ type: "result", subtype: result.subtype, is_error: !result.ok, session_id: sessionId, total_cost_usd: result.costUsd, num_turns: turns, result: result.finalText, api_error: result.apiError, backend: "anthropic-api" });
682
+ return result;
683
+ };
684
+ let cost = 0;
685
+ let turns = 0;
686
+ let finalText = "";
687
+ if (!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_AUTH_TOKEN)
688
+ return finish({ ok: false, exitCode: null, timedOut: false, subtype: "error_during_execution", apiError: "authentication_error", finalText: "ANTHROPIC_API_KEY is not set." });
689
+ const Anthropic = await anthropicSdk();
690
+ const client = new Anthropic({ maxRetries: 4 });
691
+ const slot = await takeSlot();
692
+ try {
693
+ for (;;) {
694
+ if (Date.now() >= deadline) return finish({ ok: false, exitCode: null, timedOut: true, subtype: "error_timeout", apiError: null, finalText });
695
+ if (cost >= budgetUsd) return finish({ ok: false, exitCode: null, timedOut: false, subtype: "error_max_budget_usd", apiError: null, finalText });
696
+ if (maxTurns && turns >= maxTurns) return finish({ ok: false, exitCode: null, timedOut: false, subtype: "error_max_turns", apiError: null, finalText });
697
+ const params = {
698
+ model: chosen,
699
+ max_tokens: 16000,
700
+ system: systemPrompt(cwd),
701
+ tools: TOOL_DEFS,
702
+ messages,
703
+ cache_control: { type: "ephemeral" },
704
+ output_config: { effort: "high" },
705
+ };
706
+ const options = { timeout: Math.max(10_000, deadline - Date.now()) };
707
+ let response;
708
+ try {
709
+ response = FALLBACK_MODELS.includes(chosen)
710
+ ? await client.beta.messages.create({ ...params, betas: ["server-side-fallback-2026-07-01"], fallbacks: "default" }, options)
711
+ : await client.messages.create(params, options);
712
+ } catch (error) {
713
+ if (error instanceof Anthropic.RateLimitError)
714
+ return finish({ ok: false, exitCode: null, timedOut: false, subtype: "error_during_execution", apiError: "usage_limit_reached", finalText: error.message });
715
+ if (error instanceof Anthropic.APIError)
716
+ return finish({ ok: false, exitCode: null, timedOut: false, subtype: "error_during_execution", apiError: error.error?.error?.type ?? `http_${error.status}`, finalText: error.message });
717
+ throw error;
718
+ }
719
+ turns += 1;
720
+ cost += costOf(chosen, response.usage);
721
+ messages.push({ role: "assistant", content: response.content });
722
+ write({ type: "assistant", message: response });
723
+ const said = response.content.filter((block) => block.type === "text").map((block) => block.text).join("\n");
724
+ if (said !== "") finalText = said;
725
+ if (response.stop_reason === "pause_turn") continue;
726
+ if (response.stop_reason === "refusal")
727
+ return finish({ ok: false, exitCode: 0, timedOut: false, subtype: "error_refusal", apiError: "refusal", finalText });
728
+ const calls = response.content.filter((block) => block.type === "tool_use");
729
+ if (calls.length === 0) return finish({ ok: true, exitCode: 0, timedOut: false, subtype: "success", apiError: null, finalText });
730
+ const results = [];
731
+ for (const call of calls) {
732
+ // An input cut off at max_tokens may parse as a valid partial object: never run it.
733
+ if (response.stop_reason === "max_tokens") {
734
+ results.push({ type: "tool_result", tool_use_id: call.id, is_error: true, content: "Your reply hit max_tokens and this call was cut off; write smaller pieces." });
735
+ continue;
736
+ }
737
+ try {
738
+ const tool = tools[call.name];
739
+ if (tool === undefined) throw new Error(`No tool ${call.name}`);
740
+ results.push({ type: "tool_result", tool_use_id: call.id, content: String(await tool(call.input ?? {})) });
741
+ } catch (error) {
742
+ results.push({ type: "tool_result", tool_use_id: call.id, is_error: true, content: String(error.message ?? error) });
743
+ }
744
+ }
745
+ messages.push({ role: "user", content: results });
746
+ write(toolResults(results));
747
+ }
748
+ } finally {
749
+ rmSync(slot, { force: true });
750
+ }
751
+ }
752
+
753
+ /** lib.mjs `session` for any backend but claude-cli. */
754
+ export async function runBackend(backend, options) {
755
+ if (backend === "codex-cli") return codexCli(options);
756
+ if (backend === "anthropic-api") return anthropicApi(options);
757
+ if (backend === "exec") return execBackend(options);
758
+ throw new Error(`No backend ${backend}`);
759
+ }
760
+
761
+ /** A session's state folder's files: what it left behind (evidence/backends.mjs checks no login copy stays). */
762
+ export const stateFiles = (transcript) => listFiles(join(SESSIONS, sha256(transcript).slice(0, 16)));