@discovery-tree/runner 0.1.17 → 0.1.19

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 (3) hide show
  1. package/README.md +29 -2
  2. package/dist/cli.js +3233 -391
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -89,9 +89,165 @@ Rules:
89
89
  - For an \`ai\` task, rate \`complexity\` and \`impact\` (low, medium, high) with a one-line
90
90
  \`model_reason\`; they choose the model it runs on.`;
91
91
 
92
+ // ../contracts/src/run-result.ts
93
+ var MAX_RUN_RESULTS_PER_TURN = 5;
94
+ var MAX_RUN_RESULT_METRICS = 20;
95
+ var MAX_RUN_RESULT_SUMMARY_CHARS = 2e3;
96
+ var MAX_RUN_RESULT_METRIC_NAME_CHARS = 120;
97
+ var MAX_RUN_RESULT_METRIC_VALUE_CHARS = 120;
98
+ var MAX_RUN_RESULT_METRIC_UNIT_CHARS = 40;
99
+ var MAX_RUN_RESULT_METRIC_LINE_CHARS = MAX_RUN_RESULT_METRIC_NAME_CHARS + MAX_RUN_RESULT_METRIC_VALUE_CHARS + MAX_RUN_RESULT_METRIC_UNIT_CHARS + 20;
100
+ var EXAMPLE_TITLE2 = "Backtest of the four entry strategies, 2024 data";
101
+ var RUN_RESULT_INSTRUCTION = `## Results
102
+
103
+ When this run measured or checked something (ran a backtest, a benchmark, a load test, a
104
+ smoke run, a query that answers the task's question), record what it found as a result, so
105
+ the finding is kept as data on the task and the next round can be compared with it. End your
106
+ response with one block per result:
107
+
108
+ <!-- DT-RESULT
109
+ title: ${EXAMPLE_TITLE2}
110
+ about: this
111
+ verdict: not_met
112
+ metric: strategies rejected = 4
113
+ metric: orders placed = 0 orders
114
+ metric: spread = 10-50 fp
115
+ evidence: https://example.com/reports/backtest-2024 Backtest report
116
+ ---
117
+ All four strategies were rejected by the risk filter before placing an order: spreads of
118
+ 10-50 fp left no edge at the configured size.
119
+ -->
120
+
121
+ Rules:
122
+ - Only for something this run measured or checked. Writing code, opening a pull request or
123
+ reading files is not a result; most runs that only build write no block.
124
+ - At most ${MAX_RUN_RESULTS_PER_TURN} blocks, ${MAX_RUN_RESULT_METRICS} \`metric:\` lines each.
125
+ - \`title\`: what was measured or checked, one line.
126
+ - \`about: this\` for this task; or the id of a destination this task's work leads to, when the
127
+ result checks that destination's outcome.
128
+ - \`verdict\`: \`met\` (it holds), \`not_met\` (it does not), \`inconclusive\` (checked, could
129
+ not tell) or \`info\` (a measurement with no pass or fail).
130
+ - \`metric: name = value unit\`, one per line; the value a number where there is one.
131
+ - \`evidence:\` an http(s) URL (a report, a dashboard, a pull request), then an optional caption.
132
+ - Below \`---\`, a summary of what it showed, at most ${MAX_RUN_RESULT_SUMMARY_CHARS} characters.
133
+ - Do not write \`-->\` inside a block: it ends the block.`;
134
+ var NUM = String.raw`[-+]?[\d.,]*\d[\d.,]*(?:e[-+]?\d+)?`;
135
+ var NUMERIC_TOKEN = new RegExp(String.raw`^[~<>≈≤≥]?${NUM}(?:\s*(?:-|–|to)\s*${NUM})?%?$`, "i");
136
+
137
+ // ../contracts/src/tree-jobs.ts
138
+ var TREE_JOB_OUTPUT_KEPT_MS = 7 * 24 * 60 * 60 * 1e3;
139
+ var TREE_JOB_CWD_MAX_LENGTH = 1024;
140
+ function treeJobCwdProblem(cwd) {
141
+ if (!cwd.trim()) return "must not be empty";
142
+ if (cwd.length > TREE_JOB_CWD_MAX_LENGTH) {
143
+ return `must be at most ${TREE_JOB_CWD_MAX_LENGTH} characters`;
144
+ }
145
+ if (/[\u0000-\u001f\u007f]/.test(cwd)) return "must not contain control characters";
146
+ if (!/^(\/|[A-Za-z]:[\\/]|\\\\)/.test(cwd)) return "must be an absolute path";
147
+ if (cwd.split(/[\\/]/).includes("..")) return 'must not contain ".."';
148
+ return null;
149
+ }
150
+
151
+ // ../contracts/src/job-request.ts
152
+ var MAX_JOB_REQUEST_PURPOSE_CHARS = 2e3;
153
+ var MAX_JOB_REQUEST_EXPECT_SECONDS = 366 * 24 * 3600;
154
+ var EXAMPLE_NAME = "Record Polymarket order books for 6 hours";
155
+ var EXAMPLE_COMMAND = "python scripts/record_books.py --hours 6 --out data/books";
156
+ var EXAMPLE_CHECKOUT = "/absolute/path/of/your/checkout";
157
+ var JOB_REQUEST_INSTRUCTION = `## Jobs
158
+
159
+ When the task needs a command that keeps running after this run ends (recording data for
160
+ hours, a dev server, a bot, a dashboard), do not leave it to a person and do not wait for it.
161
+ Set it up, run it briefly to check it starts, then ask Discovery Tree to run it as a job on
162
+ this computer: end your response with one block.
163
+
164
+ <!-- DT-JOB
165
+ name: ${EXAMPLE_NAME}
166
+ command: ${EXAMPLE_COMMAND}
167
+ checkout: ${EXAMPLE_CHECKOUT}
168
+ cwd: .
169
+ url: http://localhost:8000
170
+ expect: 6h
171
+ ---
172
+ Records the order books the backtest reads from data/books.
173
+ -->
174
+
175
+ Rules:
176
+ - At most one block per turn, and only for a command that must outlive this run. A command
177
+ that finishes in minutes, run yourself.
178
+ - Nothing runs until the owner of this computer approves it, seeing the exact command and
179
+ directory. Say in your answer what you asked for; do not wait for it to start.
180
+ - \`name\`: what it does, one line.
181
+ - \`command\`: one line, exactly as you would type it in a shell here.
182
+ - \`checkout\`: the absolute path of your checkout, as \`git rev-parse --show-toplevel\` prints
183
+ it (or \`pwd\` in the folder you started in, when there is no repository).
184
+ - \`cwd\`: where to run it, relative to \`checkout\`: \`.\` for its root. Never absolute, never
185
+ \`..\`: a directory outside your checkout is refused.
186
+ - \`url\`: where it serves, when it does: an http://localhost address. Leave it out otherwise.
187
+ - \`expect\`: how long it should run (\`45m\`, \`6h\`, \`2d\`); leave it out for one that runs
188
+ until stopped.
189
+ - Below \`---\`, what it is for and where its output goes, at most
190
+ ${MAX_JOB_REQUEST_PURPOSE_CHARS} characters.
191
+ - The same job asked for again while it still waits or runs is not asked for twice.
192
+ - What the job writes in your checkout is kept for ${TREE_JOB_OUTPUT_KEPT_MS / 864e5} days after the job ends, then removed with
193
+ the checkout. Say where its output goes (below \`---\`), and when it is done record where to
194
+ find it, for example in a DT-RESULT block, so it is collected in time.
195
+ - Do not write \`-->\` inside a block: it ends the block.`;
196
+
92
197
  // ../contracts/src/environments.ts
198
+ var ENV_NAME_PATTERN = /^[A-Z_][A-Z0-9_]{0,63}$/;
199
+ var ENV_RESERVED_NAMES = [
200
+ "PATH",
201
+ "HOME",
202
+ "SHELL",
203
+ "USER",
204
+ "LOGNAME",
205
+ "PWD",
206
+ "OLDPWD",
207
+ "TMPDIR",
208
+ "TERM",
209
+ "NODE_OPTIONS",
210
+ "NODE_PATH",
211
+ "NODE_EXTRA_CA_CERTS",
212
+ "LD_PRELOAD",
213
+ "LD_LIBRARY_PATH",
214
+ "GITHUB_TOKEN",
215
+ "GH_TOKEN",
216
+ "HTTP_PROXY",
217
+ "HTTPS_PROXY",
218
+ "NO_PROXY",
219
+ "ALL_PROXY",
220
+ "REQUESTS_CA_BUNDLE",
221
+ "CURL_CA_BUNDLE",
222
+ "PYTHONPATH",
223
+ "PYTHONSTARTUP",
224
+ "BASH_ENV",
225
+ "ENV",
226
+ "PROMPT_COMMAND"
227
+ ];
228
+ var ENV_RESERVED_PREFIXES = [
229
+ "DYLD_",
230
+ "GIT_",
231
+ "SSL_CERT_",
232
+ "ANTHROPIC_",
233
+ "OPENAI_",
234
+ "CURSOR_",
235
+ "CLAUDE_",
236
+ "CODEX_",
237
+ "DT_RUNNER_"
238
+ ];
239
+ function isReservedEnvName(name) {
240
+ return ENV_RESERVED_NAMES.includes(name) || ENV_RESERVED_PREFIXES.some((p) => name.startsWith(p));
241
+ }
242
+ var ENV_SECRET_VALUE_MAX_LENGTH = 8192;
243
+ var ENV_VARIABLE_VALUE_MAX_LENGTH = 8192;
244
+ var ENV_SECRETS_MAX = 50;
245
+ var ENV_VARIABLES_MAX = 50;
93
246
  var ENV_SETUP_SCRIPT_MAX_LENGTH = 16 * 1024;
94
247
 
248
+ // ../contracts/src/tree-autonomy.ts
249
+ var MAX_AUTO_RETRY_DELAY_MINUTES = 24 * 60;
250
+
95
251
  // ../contracts/src/shared-artifacts.ts
96
252
  var SHARED_ARTIFACT_TEXT_MAX_BYTES = 1024 * 1024;
97
253
  var SHARED_ARTIFACT_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
@@ -108,7 +264,7 @@ var MAX_REVIEW_IMAGE_CAPTION_LENGTH = 300;
108
264
  var REVIEW_AGENT_ROUND_STALE_MS = 30 * 6e4;
109
265
 
110
266
  // ../contracts/src/agent-runner.ts
111
- var RUNNER_PROTOCOL_VERSION = 1;
267
+ var RUNNER_PROTOCOL_VERSION = 2;
112
268
  var RUNNER_COMMAND_POLL_MAX_WAIT_MS = 25e3;
113
269
  var RUNNER_EVENTS_MAX_BATCH = 200;
114
270
  var RUNNER_EVENT_TEXT_MAX_LENGTH = 64e3;
@@ -121,6 +277,12 @@ var RUNNER_TASK_IMAGES_DIR = ".dt-task-images";
121
277
  var RUNNER_REVIEW_IMAGE_MAX_BYTES = 5e6;
122
278
  var RUNNER_DELIVERABLE_FILE = "DELIVERABLE.md";
123
279
  var RUNNER_REFERENCE_REPOSITORY_DIR = "repository";
280
+ var RUNNER_DEFAULT_MAX_JOBS = 2;
281
+ var RUNNER_MAX_JOBS_LIMIT = 16;
282
+ var RUNNER_JOB_MISSING_GRACE_MS = 2 * 6e4;
283
+ var RUNNER_JOB_LOG_LINES_KEPT = 2e3;
284
+ var RUNNER_JOB_LOG_MAX_BATCH = 500;
285
+ var RUNNER_JOB_LOG_LINE_MAX_LENGTH = 4e3;
124
286
  var RUNNER_COMPLETION_MAX_TEXT = 2e5;
125
287
 
126
288
  // ../contracts/src/agent-permissions.ts
@@ -169,7 +331,7 @@ function toolGrantRepositoryKey(url) {
169
331
  }
170
332
 
171
333
  // src/version.ts
172
- var RUNNER_VERSION = true ? "0.1.17" : "0.0.0-dev";
334
+ var RUNNER_VERSION = true ? "0.1.19" : "0.0.0-dev";
173
335
  var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
174
336
 
175
337
  // src/api.ts
@@ -242,6 +404,10 @@ var RunnerApi = class {
242
404
  postEvents(sessionId, body) {
243
405
  return this.request("POST", `/runner/sessions/${encodeURIComponent(sessionId)}/events`, body);
244
406
  }
407
+ /** A job's status and log lines (`docs/features/RUNNER_JOBS.md`). */
408
+ postJobEvents(jobId, body) {
409
+ return this.request("POST", `/runner/jobs/${encodeURIComponent(jobId)}/events`, body);
410
+ }
245
411
  /** An image the agent rendered of a design proposal, attached to the session's task. */
246
412
  postReviewImage(sessionId, body) {
247
413
  return this.request(
@@ -306,14 +472,14 @@ var RunnerApi = class {
306
472
  import { join as join4 } from "node:path";
307
473
 
308
474
  // src/evidence.ts
309
- import { mkdir as mkdir2, mkdtemp, readdir, readFile, rename, rm as rm2, stat as stat2, writeFile } from "node:fs/promises";
475
+ import { mkdir as mkdir2, mkdtemp, readdir, readFile as readFile2, rename, rm as rm2, stat as stat2, writeFile } from "node:fs/promises";
310
476
  import { tmpdir } from "node:os";
311
477
  import { isAbsolute as isAbsolute2, join as join3 } from "node:path";
312
478
 
313
479
  // src/exec.ts
314
480
  import { spawn as spawn3 } from "node:child_process";
315
- import { access, constants } from "node:fs/promises";
316
- import { delimiter, isAbsolute, join } from "node:path";
481
+ import { access, constants, readFile } from "node:fs/promises";
482
+ import { delimiter, dirname, extname, isAbsolute, join, sep } from "node:path";
317
483
 
318
484
  // src/process-tree.ts
319
485
  import { spawn as spawn2, spawnSync } from "node:child_process";
@@ -433,12 +599,12 @@ var JobHelper = class {
433
599
  { stdio: ["pipe", "pipe", "ignore"], windowsHide: true }
434
600
  );
435
601
  let onReady = () => void 0;
436
- this.ready = new Promise((resolve2) => {
437
- const timer = setTimeout(() => resolve2(false), READY_TIMEOUT_MS);
602
+ this.ready = new Promise((resolve4) => {
603
+ const timer = setTimeout(() => resolve4(false), READY_TIMEOUT_MS);
438
604
  timer.unref();
439
605
  onReady = (ok) => {
440
606
  clearTimeout(timer);
441
- resolve2(ok);
607
+ resolve4(ok);
442
608
  };
443
609
  });
444
610
  const lines = createInterface({ input: this.child.stdout, crlfDelay: Infinity });
@@ -452,7 +618,7 @@ var JobHelper = class {
452
618
  answer(text);
453
619
  }
454
620
  });
455
- const gone = () => {
621
+ const gone2 = () => {
456
622
  if (this.exited) return;
457
623
  this.exited = true;
458
624
  onReady(false);
@@ -460,8 +626,8 @@ var JobHelper = class {
460
626
  this.waiting.clear();
461
627
  if (helper === this) helper = null;
462
628
  };
463
- this.child.on("error", gone);
464
- this.child.on("exit", gone);
629
+ this.child.on("error", gone2);
630
+ this.child.on("exit", gone2);
465
631
  this.child.stdin.on("error", () => void 0);
466
632
  this.child.unref();
467
633
  this.child.stdout.unref?.();
@@ -493,15 +659,15 @@ var JobHelper = class {
493
659
  }
494
660
  ask(request, id) {
495
661
  if (this.exited) return Promise.resolve("err gone");
496
- return new Promise((resolve2) => {
662
+ return new Promise((resolve4) => {
497
663
  const timer = setTimeout(() => {
498
664
  this.waiting.delete(id);
499
- resolve2("err timeout");
665
+ resolve4("err timeout");
500
666
  }, ANSWER_TIMEOUT_MS);
501
667
  timer.unref();
502
668
  this.waiting.set(id, (answer) => {
503
669
  clearTimeout(timer);
504
- resolve2(answer);
670
+ resolve4(answer);
505
671
  });
506
672
  this.child.stdin.write(request + "\n");
507
673
  });
@@ -627,7 +793,7 @@ async function reapTree(tree, graceMs = 2e3, deps = {}) {
627
793
  await (deps.terminateJob ?? terminateJob)(await tree.job);
628
794
  const rows = await (deps.listProcesses ?? listWindowsProcesses)();
629
795
  const orphans = descendantsOf(tree, rows);
630
- if (orphans.length) await (deps.kill ?? taskkillTrees)(orphans);
796
+ if (orphans.length) await (deps.kill ?? killWindowsTrees)(orphans);
631
797
  } catch {
632
798
  } finally {
633
799
  if (liveTrees.get(tree.pid)?.tree.startedAt === tree.startedAt) liveTrees.delete(tree.pid);
@@ -752,7 +918,7 @@ function namesPathIn(commandLine, dir) {
752
918
  }
753
919
  function listWindowsProcesses() {
754
920
  const script = `$ErrorActionPreference='SilentlyContinue';Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { "$($_.ProcessId) $($_.ParentProcessId) $(([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()) $($_.CommandLine -replace "[\\r\\n]", " ")" } }`;
755
- return new Promise((resolve2, reject) => {
921
+ return new Promise((resolve4, reject) => {
756
922
  const ps = spawn2(
757
923
  "powershell.exe",
758
924
  ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
@@ -767,7 +933,7 @@ function listWindowsProcesses() {
767
933
  });
768
934
  ps.on("close", () => {
769
935
  clearTimeout(timer);
770
- resolve2(parseProcessRows(out));
936
+ resolve4(parseProcessRows(out));
771
937
  });
772
938
  });
773
939
  }
@@ -786,13 +952,13 @@ function parseProcessRows(text) {
786
952
  }
787
953
  return rows;
788
954
  }
789
- async function taskkillTrees(pids) {
955
+ async function killWindowsTrees(pids) {
790
956
  for (let i = 0; i < pids.length; i += 50) {
791
957
  const args = pids.slice(i, i + 50).flatMap((p) => ["/pid", String(p)]);
792
- await new Promise((resolve2) => {
958
+ await new Promise((resolve4) => {
793
959
  const tk = spawn2("taskkill", [...args, "/T", "/F"], { stdio: "ignore", windowsHide: true });
794
- tk.on("error", () => resolve2());
795
- tk.on("close", () => resolve2());
960
+ tk.on("error", () => resolve4());
961
+ tk.on("close", () => resolve4());
796
962
  });
797
963
  }
798
964
  }
@@ -807,7 +973,7 @@ function signalGroup(pgid, signal) {
807
973
 
808
974
  // src/exec.ts
809
975
  function exec(cmd, args, opts = {}) {
810
- return new Promise((resolve2, reject) => {
976
+ return new Promise((resolve4, reject) => {
811
977
  const child = spawn3(cmd, args, {
812
978
  cwd: opts.cwd,
813
979
  env: opts.env ?? process.env,
@@ -842,26 +1008,149 @@ function exec(cmd, args, opts = {}) {
842
1008
  child.on("close", (code) => {
843
1009
  if (timer) clearTimeout(timer);
844
1010
  opts.signal?.removeEventListener("abort", onAbort);
845
- void reaped.then(() => resolve2({ code, stdout, stderr }));
1011
+ void reaped.then(() => resolve4({ code, stdout, stderr }));
846
1012
  });
847
1013
  child.stdin.on("error", () => void 0);
848
1014
  child.stdin.end(opts.input ?? "");
849
1015
  });
850
1016
  }
851
- async function which(name, env = process.env) {
852
- if (isAbsolute(name) || name.includes("/")) {
853
- return await isExecutable(name) ? name : null;
1017
+ var JS_LAUNCHER = /\.[cm]?js$/i;
1018
+ function isJsLauncher(file) {
1019
+ return JS_LAUNCHER.test(file);
1020
+ }
1021
+ function isWindowsSpawnable(file) {
1022
+ const ext = extname(file).toLowerCase();
1023
+ return ext === ".exe" || isJsLauncher(file);
1024
+ }
1025
+ function isWindowsShimExt(file) {
1026
+ const ext = extname(file).toLowerCase();
1027
+ return ext === ".cmd" || ext === ".bat" || ext === ".ps1" || ext === "";
1028
+ }
1029
+ async function which(name, env = process.env, options = {}) {
1030
+ if (isAbsolute(name) || name.includes("/") || name.includes("\\")) {
1031
+ return resolveWindowsPathCandidate(name, options);
1032
+ }
1033
+ if (process.platform === "win32") {
1034
+ return whichWindowsOnPath(name, env, options);
1035
+ }
1036
+ const dirs = (env.PATH ?? env.Path ?? "").split(delimiter).filter(Boolean);
1037
+ for (const dir of dirs) {
1038
+ const candidate = join(dir, name);
1039
+ if (await isExecutable(candidate)) return candidate;
1040
+ }
1041
+ return null;
1042
+ }
1043
+ async function resolveWindowsPathCandidate(file, options) {
1044
+ if (process.platform !== "win32") {
1045
+ return await isExecutable(file) ? file : null;
1046
+ }
1047
+ if (await isExecutable(file) && isWindowsSpawnable(file)) return file;
1048
+ const ext = extname(file).toLowerCase();
1049
+ if (ext === ".cmd" || ext === ".bat") {
1050
+ const resolved = await resolveNpmCmdShim(file, options.npmPackageScript);
1051
+ return resolved && await isExecutable(resolved) ? resolved : null;
1052
+ }
1053
+ if (!ext && await fileExists(file)) {
1054
+ const cmd = `${file}.cmd`;
1055
+ if (await fileExists(cmd)) {
1056
+ const resolved = await resolveNpmCmdShim(cmd, options.npmPackageScript);
1057
+ return resolved && await isExecutable(resolved) ? resolved : null;
1058
+ }
854
1059
  }
1060
+ return null;
1061
+ }
1062
+ async function whichWindowsOnPath(name, env, options) {
855
1063
  const dirs = (env.PATH ?? env.Path ?? "").split(delimiter).filter(Boolean);
856
- const exts = process.platform === "win32" ? [".exe", ""] : [""];
857
1064
  for (const dir of dirs) {
858
- for (const ext of exts) {
859
- const candidate = join(dir, name + ext);
860
- if (await isExecutable(candidate)) return candidate;
1065
+ const spawnable = await whichWindowsInDir(dir, name, options);
1066
+ if (spawnable) return spawnable;
1067
+ }
1068
+ return null;
1069
+ }
1070
+ async function whichWindowsInDir(dir, name, options) {
1071
+ const nameExt = extname(name);
1072
+ if (nameExt) {
1073
+ const qualified = join(dir, name);
1074
+ if (await fileExists(qualified)) {
1075
+ if (isWindowsSpawnable(qualified)) return qualified;
1076
+ const lower = nameExt.toLowerCase();
1077
+ if (lower === ".cmd" || lower === ".bat") {
1078
+ const resolved = await resolveNpmCmdShim(qualified, options.npmPackageScript);
1079
+ if (resolved && await fileExists(resolved)) return resolved;
1080
+ }
1081
+ }
1082
+ return null;
1083
+ }
1084
+ const exe = join(dir, `${name}.exe`);
1085
+ if (await fileExists(exe)) return exe;
1086
+ for (const ext of [".js", ".mjs", ".cjs"]) {
1087
+ const js = join(dir, name + ext);
1088
+ if (await fileExists(js)) return js;
1089
+ }
1090
+ const cmd = join(dir, `${name}.cmd`);
1091
+ if (await fileExists(cmd)) {
1092
+ const resolved = await resolveNpmCmdShim(cmd, options.npmPackageScript);
1093
+ if (resolved && await fileExists(resolved)) return resolved;
1094
+ }
1095
+ const bat = join(dir, `${name}.bat`);
1096
+ if (await fileExists(bat)) {
1097
+ const resolved = await resolveNpmCmdShim(bat, options.npmPackageScript);
1098
+ if (resolved && await fileExists(resolved)) return resolved;
1099
+ }
1100
+ const bare = join(dir, name);
1101
+ if (await fileExists(bare) && !isWindowsSpawnable(bare) && isWindowsShimExt(bare)) {
1102
+ if (await fileExists(cmd)) {
1103
+ const resolved = await resolveNpmCmdShim(cmd, options.npmPackageScript);
1104
+ if (resolved && await fileExists(resolved)) return resolved;
1105
+ }
1106
+ if (options.npmPackageScript?.length) {
1107
+ const fallback = join(dir, ...options.npmPackageScript);
1108
+ if (await fileExists(fallback)) return fallback;
861
1109
  }
862
1110
  }
863
1111
  return null;
864
1112
  }
1113
+ async function resolveNpmCmdShim(cmdPath, npmPackageScript) {
1114
+ const shimDir = dirname(cmdPath);
1115
+ let text;
1116
+ try {
1117
+ text = await readFile(cmdPath, "utf8");
1118
+ } catch {
1119
+ return npmPackageScript?.length ? tryPackageScript(shimDir, npmPackageScript) : null;
1120
+ }
1121
+ const dp0 = new RegExp(`(?:%~dp0|%dp0%)\\\\?([^"'\\r\\n%]+\\.js)`, "gi");
1122
+ for (const match of text.matchAll(dp0)) {
1123
+ const candidate = joinShimPath(shimDir, match[1]);
1124
+ if (await fileExists(candidate)) return candidate;
1125
+ }
1126
+ const quotedJs = /"([^"]+\.js)"/gi;
1127
+ for (const match of text.matchAll(quotedJs)) {
1128
+ const raw = match[1];
1129
+ const relative = /%(?:~)?dp0%/i.test(raw) ? stripDp0Prefix(raw) : raw;
1130
+ const candidate = isAbsolute(relative) ? relative : joinShimPath(shimDir, relative);
1131
+ if (await fileExists(candidate)) return candidate;
1132
+ }
1133
+ return npmPackageScript?.length ? tryPackageScript(shimDir, npmPackageScript) : null;
1134
+ }
1135
+ function stripDp0Prefix(raw) {
1136
+ return raw.replace(/^(?:%~dp0|%dp0%)\\?/i, "");
1137
+ }
1138
+ function joinShimPath(shimDir, relative) {
1139
+ const normalized = relative.replace(/\\/g, sep);
1140
+ return join(shimDir, normalized);
1141
+ }
1142
+ async function tryPackageScript(shimDir, segments) {
1143
+ const candidate = join(shimDir, ...segments);
1144
+ return await fileExists(candidate) ? candidate : null;
1145
+ }
1146
+ async function fileExists(file) {
1147
+ try {
1148
+ await access(file, constants.F_OK);
1149
+ return true;
1150
+ } catch {
1151
+ return false;
1152
+ }
1153
+ }
865
1154
  async function isExecutable(file) {
866
1155
  try {
867
1156
  await access(file, process.platform === "win32" ? constants.F_OK : constants.X_OK);
@@ -873,7 +1162,7 @@ async function isExecutable(file) {
873
1162
 
874
1163
  // src/git.ts
875
1164
  import { mkdir, rm, stat } from "node:fs/promises";
876
- import { dirname, join as join2 } from "node:path";
1165
+ import { dirname as dirname2, join as join2 } from "node:path";
877
1166
 
878
1167
  // src/log.ts
879
1168
  function createLogger(opts = {}) {
@@ -904,7 +1193,7 @@ function redactFields(fields) {
904
1193
  return out;
905
1194
  }
906
1195
  function scrubSecrets(text) {
907
- return text.replace(/(https?:\/\/)[^/\s@]+@/gi, "$1***@").replace(/\bdtr_[A-Za-z0-9_-]+/g, "dtr_***").replace(/\b(gh[pousr]_[A-Za-z0-9]{10,})/g, "***");
1196
+ return text.replace(/(https?:\/\/)(?:\[secret: [A-Z0-9_]+\]|[^/\s@])+@/gi, "$1***@").replace(/\bdtr_[A-Za-z0-9_-]+/g, "dtr_***").replace(/\b(gh[pousr]_[A-Za-z0-9]{10,})/g, "***");
908
1197
  }
909
1198
 
910
1199
  // src/git.ts
@@ -990,9 +1279,9 @@ function removeDir(path) {
990
1279
  }
991
1280
  async function ensureRepoCache(repoDir, ref, protocol) {
992
1281
  if (!await exists(join2(repoDir, ".git"))) {
993
- await mkdir(dirname(repoDir), { recursive: true });
1282
+ await mkdir(dirname2(repoDir), { recursive: true });
994
1283
  await rm(repoDir, { recursive: true, force: true });
995
- await git(dirname(repoDir), ["clone", "--no-checkout", cloneUrl(ref, protocol), repoDir]);
1284
+ await git(dirname2(repoDir), ["clone", "--no-checkout", cloneUrl(ref, protocol), repoDir]);
996
1285
  return;
997
1286
  }
998
1287
  const wanted = cloneUrl(ref, protocol);
@@ -1032,7 +1321,7 @@ async function prepareReferenceCheckout(input) {
1032
1321
  });
1033
1322
  await removeDir(input.dir);
1034
1323
  await git(repoDir, ["worktree", "prune"]);
1035
- await mkdir(dirname(input.dir), { recursive: true });
1324
+ await mkdir(dirname2(input.dir), { recursive: true });
1036
1325
  await git(repoDir, ["worktree", "add", "--detach", input.dir, sha]);
1037
1326
  return { repoDir, dir: input.dir, baseRef, sha };
1038
1327
  });
@@ -1046,6 +1335,7 @@ async function prepareWorktree(input) {
1046
1335
  const ownWorktree = join2(input.worktreesDir, input.sessionId);
1047
1336
  let worktree = join2(input.worktreesDir, input.worktreeKey || input.sessionId);
1048
1337
  const remove = input.removeDir ?? removeDir;
1338
+ const keep = input.keepWorkspace === true && worktree !== ownWorktree;
1049
1339
  return withRepoLock(repoDir, async () => {
1050
1340
  await ensureRepoCache(repoDir, ref, input.protocol);
1051
1341
  const { baseRef, start: start2 } = await resolveBase(repoDir, input.baseRef);
@@ -1055,18 +1345,46 @@ async function prepareWorktree(input) {
1055
1345
  let setAside;
1056
1346
  let leftInPlace;
1057
1347
  let dirtyKept = false;
1348
+ const released = [];
1349
+ let keptRef;
1350
+ let keptRefOwn = false;
1351
+ const revParse2 = async (dir, rev) => {
1352
+ const r = await exec(
1353
+ "git",
1354
+ [...dir ? ["-C", dir] : [], "rev-parse", "--verify", "--quiet", rev],
1355
+ { cwd: repoDir, env: gitEnv(), timeoutMs: 6e4 }
1356
+ );
1357
+ return r.code === 0 ? r.stdout.trim() : null;
1358
+ };
1359
+ const readHead = async (dir) => {
1360
+ if (!await exists(join2(dir, ".git"))) return null;
1361
+ const r = await exec("git", ["-C", dir, "symbolic-ref", "--quiet", "HEAD"], {
1362
+ cwd: repoDir,
1363
+ env: gitEnv(),
1364
+ timeoutMs: 6e4
1365
+ });
1366
+ const branch = r.code === 0 ? r.stdout.trim() : r.code === 1 ? null : void 0;
1367
+ return { branch, at: await revParse2(dir, "HEAD") };
1368
+ };
1369
+ const release = async (dir, head) => {
1370
+ if (head.branch === null) return true;
1371
+ if (!await gitOk(repoDir, ["-C", dir, "checkout", "--quiet", "--detach"])) return false;
1372
+ released.push({ dir, head: head.branch ?? null, at: head.at });
1373
+ return true;
1374
+ };
1058
1375
  const remoteWork = `refs/remotes/origin/${input.workBranch}`;
1059
- if (input.continueBranch && await exists(worktree) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
1060
- cwd: worktree,
1376
+ const reusable = async (dir) => input.continueBranch === true && await exists(dir) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
1377
+ cwd: dir,
1061
1378
  env: gitEnv(),
1062
1379
  timeoutMs: 6e4
1063
1380
  }).then((r) => r.code === 0 && r.stdout.trim() === input.workBranch) && // Only when it already has everything pushed to the work branch since: one that fell
1064
1381
  // behind (the run went on elsewhere) would have the agent work on stale code.
1065
1382
  (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${remoteWork}^{commit}`]) || await exec("git", ["merge-base", "--is-ancestor", remoteWork, "HEAD"], {
1066
- cwd: worktree,
1383
+ cwd: dir,
1067
1384
  env: gitEnv(),
1068
1385
  timeoutMs: 6e4
1069
- }).then((r) => r.code === 0))) {
1386
+ }).then((r) => r.code === 0));
1387
+ if (await reusable(worktree)) {
1070
1388
  const forkPoint = await exec("git", ["merge-base", "HEAD", start2], {
1071
1389
  cwd: worktree,
1072
1390
  env: gitEnv(),
@@ -1110,7 +1428,8 @@ async function prepareWorktree(input) {
1110
1428
  checkout = await git(repoDir, ["rev-parse", `${checkout}^{commit}`]);
1111
1429
  }
1112
1430
  }
1113
- if (input.continueBranch && await exists(worktree)) {
1431
+ const busy = keep || (input.inUse?.(worktree) ?? false);
1432
+ if (input.continueBranch && !busy && await exists(worktree)) {
1114
1433
  const dirty = await exec("git", ["status", "--porcelain"], {
1115
1434
  cwd: worktree,
1116
1435
  env: gitEnv(),
@@ -1122,44 +1441,134 @@ async function prepareWorktree(input) {
1122
1441
  else dirtyKept = true;
1123
1442
  }
1124
1443
  }
1125
- if (await exists(worktree)) {
1126
- let failure = null;
1127
- if (!dirtyKept) {
1128
- await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
1129
- failure = await remove(worktree).then(
1130
- () => null,
1131
- (err) => {
1132
- if (!isLocked(err)) throw err;
1133
- return err;
1134
- }
1135
- );
1444
+ const tipNow = await exec(
1445
+ "git",
1446
+ ["rev-parse", "--verify", "--quiet", `refs/heads/${input.workBranch}^{commit}`],
1447
+ { cwd: repoDir, env: gitEnv(), timeoutMs: 6e4 }
1448
+ );
1449
+ const old = tipNow.code === 0 ? tipNow.stdout.trim() : "";
1450
+ const target = await revParse2(null, `${checkout}^{commit}`);
1451
+ const giveBack = async () => {
1452
+ if (old && target) {
1453
+ await gitOk(repoDir, ["update-ref", `refs/heads/${input.workBranch}`, old, target]);
1136
1454
  }
1137
- if (dirtyKept || failure) {
1138
- if (worktree === ownWorktree) {
1139
- throw failure ?? new Error(`The working copy at ${worktree} could not be replaced.`);
1455
+ for (const { dir, head, at } of released) {
1456
+ if (!head || !at || await revParse2(dir, "HEAD") !== at || await revParse2(null, head) !== at) {
1457
+ continue;
1140
1458
  }
1141
- leftInPlace = worktree;
1142
- await gitOk(repoDir, ["-C", leftInPlace, "checkout", "--quiet", "--detach"]);
1143
- worktree = ownWorktree;
1144
- if (await exists(worktree)) {
1459
+ await gitOk(repoDir, ["-C", dir, "symbolic-ref", "HEAD", head]);
1460
+ }
1461
+ const branchAt = await revParse2(null, `refs/heads/${input.workBranch}`);
1462
+ if (keptRef && keptRefOwn && branchAt === old) {
1463
+ await gitOk(repoDir, ["update-ref", "-d", keptRef, old]);
1464
+ }
1465
+ };
1466
+ try {
1467
+ if (await exists(worktree)) {
1468
+ let failure = null;
1469
+ if (busy) dirtyKept = true;
1470
+ if (!dirtyKept) {
1145
1471
  await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
1146
- await remove(worktree);
1472
+ failure = await remove(worktree).then(
1473
+ () => null,
1474
+ (err) => {
1475
+ if (!isLocked(err)) throw err;
1476
+ return err;
1477
+ }
1478
+ );
1479
+ }
1480
+ if (dirtyKept || failure) {
1481
+ if (worktree === ownWorktree) {
1482
+ throw failure ?? new Error(`The working copy at ${worktree} could not be replaced.`);
1483
+ }
1484
+ if (input.inUse?.(ownWorktree)) {
1485
+ const first = keep ? `${worktree} is kept for the run's job` : busy ? `a job runs in ${worktree}` : `${worktree} could not be replaced (a program has it open)`;
1486
+ throw new Error(
1487
+ `This run cannot continue here: ${first}, and a job runs in ${ownWorktree}. Stop the job to continue.`
1488
+ );
1489
+ }
1490
+ leftInPlace = worktree;
1491
+ const head = await readHead(leftInPlace);
1492
+ const onWorkBranch = !keep || head !== null && (head.branch === void 0 || head.branch === `refs/heads/${input.workBranch}`);
1493
+ if (onWorkBranch && head && !await release(leftInPlace, head) && keep) {
1494
+ throw new Error(
1495
+ `This run cannot continue here right now: its work branch ${input.workBranch} is checked out in ${leftInPlace}, which could not let go of it (is a git command running there?). Try again.`
1496
+ );
1497
+ }
1498
+ worktree = ownWorktree;
1499
+ if (await exists(worktree)) {
1500
+ await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
1501
+ await remove(worktree);
1502
+ }
1503
+ }
1504
+ }
1505
+ await gitOk(repoDir, ["worktree", "prune"]);
1506
+ if (keep) {
1507
+ const stuck = [];
1508
+ const broken = [];
1509
+ for (const dir of await worktreesOnBranch(repoDir, input.workBranch)) {
1510
+ const head = await readHead(dir);
1511
+ if (!head) {
1512
+ broken.push(dir);
1513
+ continue;
1514
+ }
1515
+ const known = { branch: head.branch ?? `refs/heads/${input.workBranch}`, at: head.at };
1516
+ if (!await release(dir, known)) stuck.push(dir);
1517
+ }
1518
+ if (broken.length) {
1519
+ throw new Error(
1520
+ `This run cannot continue here: git still has its work branch ${input.workBranch} checked out in ${broken.join(", ")}, which is no longer a working copy. Remove that folder (and run \`git worktree prune\` in ${repoDir}), then try again.`
1521
+ );
1522
+ }
1523
+ if (stuck.length) {
1524
+ throw new Error(
1525
+ `This run cannot continue here right now: its work branch ${input.workBranch} is checked out in ${stuck.join(", ")}, which could not let go of it (is a git command running there?). Try again.`
1526
+ );
1527
+ }
1528
+ }
1529
+ if (keep && old && !await gitOk(repoDir, ["merge-base", "--is-ancestor", old, checkout])) {
1530
+ const ref2 = `refs/dt-runner/kept/${input.sessionId}`;
1531
+ const existing = await exec(
1532
+ "git",
1533
+ ["for-each-ref", "--format=%(objectname) %(refname)", "refs/dt-runner/kept/"],
1534
+ { cwd: repoDir, env: gitEnv(), timeoutMs: 6e4 }
1535
+ );
1536
+ const same2 = existing.stdout.split("\n").map((l) => l.trim().split(" ")).find(
1537
+ ([sha, name]) => sha === old && (name === ref2 || !!name?.startsWith(`${ref2}-`) && /^\d+$/.test(name.slice(ref2.length + 1)))
1538
+ );
1539
+ if (same2) {
1540
+ keptRef = same2[1];
1541
+ } else {
1542
+ for (const candidate of [ref2, `${ref2}-${Date.now()}`]) {
1543
+ if (await gitOk(repoDir, ["update-ref", candidate, old, ""])) {
1544
+ keptRef = candidate;
1545
+ keptRefOwn = true;
1546
+ break;
1547
+ }
1548
+ }
1549
+ }
1550
+ if (!keptRef) {
1551
+ throw new Error(
1552
+ `This run cannot continue here right now: its work branch ${input.workBranch} has commits only this computer has, and they could not be kept aside. Try again.`
1553
+ );
1147
1554
  }
1148
1555
  }
1556
+ await mkdir(input.worktreesDir, { recursive: true });
1557
+ await git(repoDir, [
1558
+ "worktree",
1559
+ "add",
1560
+ "--no-track",
1561
+ // A folder left in place may still be registered with the work branch checked out.
1562
+ ...leftInPlace ? ["--force"] : [],
1563
+ "-B",
1564
+ input.workBranch,
1565
+ worktree,
1566
+ checkout
1567
+ ]);
1568
+ } catch (err) {
1569
+ await giveBack();
1570
+ throw err;
1149
1571
  }
1150
- await gitOk(repoDir, ["worktree", "prune"]);
1151
- await mkdir(input.worktreesDir, { recursive: true });
1152
- await git(repoDir, [
1153
- "worktree",
1154
- "add",
1155
- "--no-track",
1156
- // A folder left in place may still be registered with the work branch checked out.
1157
- ...leftInPlace ? ["--force"] : [],
1158
- "-B",
1159
- input.workBranch,
1160
- worktree,
1161
- checkout
1162
- ]);
1163
1572
  return {
1164
1573
  repoDir,
1165
1574
  worktree,
@@ -1167,10 +1576,26 @@ async function prepareWorktree(input) {
1167
1576
  baseSha,
1168
1577
  ...continuedFrom ? { continuedFrom } : {},
1169
1578
  ...setAside ? { setAside } : {},
1170
- ...leftInPlace ? { leftInPlace } : {}
1579
+ ...leftInPlace ? { leftInPlace } : {},
1580
+ ...keptRef ? { keptRef } : {}
1171
1581
  };
1172
1582
  });
1173
1583
  }
1584
+ async function worktreesOnBranch(repoDir, branch) {
1585
+ const res = await exec("git", ["worktree", "list", "--porcelain"], {
1586
+ cwd: repoDir,
1587
+ env: gitEnv(),
1588
+ timeoutMs: 6e4
1589
+ });
1590
+ if (res.code !== 0) return [];
1591
+ const out = [];
1592
+ let dir = null;
1593
+ for (const line of res.stdout.split("\n")) {
1594
+ if (line.startsWith("worktree ")) dir = line.slice("worktree ".length).trim();
1595
+ else if (line.trim() === `branch refs/heads/${branch}` && dir) out.push(dir);
1596
+ }
1597
+ return out;
1598
+ }
1174
1599
  async function defaultBranch(repoDir) {
1175
1600
  const read = async () => {
1176
1601
  const res = await exec("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
@@ -1267,13 +1692,13 @@ async function excludeFromGit(worktree, dir, why) {
1267
1692
  const line = `/${dir}/`;
1268
1693
  let current2 = "";
1269
1694
  try {
1270
- current2 = await readFile(file, "utf8");
1695
+ current2 = await readFile2(file, "utf8");
1271
1696
  } catch {
1272
1697
  }
1273
1698
  if (current2.split("\n").some((l) => l.trim() === line)) return;
1274
1699
  await mkdir2(join3(file, ".."), { recursive: true });
1275
- const sep2 = current2 && !current2.endsWith("\n") ? "\n" : "";
1276
- await writeFile(file, `${current2}${sep2}# ${why}
1700
+ const sep4 = current2 && !current2.endsWith("\n") ? "\n" : "";
1701
+ await writeFile(file, `${current2}${sep4}# ${why}
1277
1702
  ${line}
1278
1703
  `);
1279
1704
  }
@@ -1406,7 +1831,7 @@ async function uploadReviewImages(input) {
1406
1831
  const uploaded = [];
1407
1832
  for (const f of fitting.slice(0, MAX_REVIEW_IMAGES_PER_RUN)) {
1408
1833
  try {
1409
- const bytes = await readFile(join3(dir, f.name));
1834
+ const bytes = await readFile2(join3(dir, f.name));
1410
1835
  await input.uploader.postReviewImage(input.sessionId, {
1411
1836
  filename: f.path,
1412
1837
  caption: await reviewImageCaption(dir, f.name),
@@ -1429,7 +1854,7 @@ async function uploadReviewImages(input) {
1429
1854
  async function reviewImageCaption(dir, imageName) {
1430
1855
  const sidecar = join3(dir, imageName.replace(/\.[^.]+$/, "") + ".txt");
1431
1856
  try {
1432
- const line = (await readFile(sidecar, "utf8")).split(/\r?\n/).find((l) => l.trim());
1857
+ const line = (await readFile2(sidecar, "utf8")).split(/\r?\n/).find((l) => l.trim());
1433
1858
  if (line?.trim()) return line.trim().slice(0, MAX_REVIEW_IMAGE_CAPTION_LENGTH);
1434
1859
  } catch {
1435
1860
  }
@@ -1468,15 +1893,40 @@ async function identity(cwd) {
1468
1893
  return res.code === 0 && res.stdout.trim() ? [] : ["-c", "user.name=Discovery Tree runner", "-c", "user.email=dt-runner@users.noreply.local"];
1469
1894
  }
1470
1895
 
1896
+ // src/drivers/launcher.ts
1897
+ import { access as access2 } from "node:fs/promises";
1898
+ async function exists2(file) {
1899
+ try {
1900
+ await access2(file);
1901
+ return true;
1902
+ } catch {
1903
+ return false;
1904
+ }
1905
+ }
1906
+ function isJsLauncher2(bin) {
1907
+ return /\.[cm]?js$/i.test(bin);
1908
+ }
1909
+ function launcherCommand(bin, args) {
1910
+ return isJsLauncher2(bin) ? { bin: process.execPath, args: [bin, ...args] } : { bin, args };
1911
+ }
1912
+ async function findOverride(override, env) {
1913
+ if (isJsLauncher2(override)) return await exists2(override) ? override : null;
1914
+ return which(override, env);
1915
+ }
1916
+
1471
1917
  // src/claude.ts
1472
1918
  async function findClaude(env = process.env) {
1473
1919
  const override = env.DT_RUNNER_CLAUDE_BIN?.trim();
1474
1920
  if (override) return which(override, env);
1475
1921
  return which("claude", env);
1476
1922
  }
1923
+ function runClaude(bin, args, timeoutMs) {
1924
+ const cmd = launcherCommand(bin, args);
1925
+ return exec(cmd.bin, cmd.args, { timeoutMs });
1926
+ }
1477
1927
  async function claudeVersion(bin) {
1478
1928
  try {
1479
- const res = await exec(bin, ["--version"], { timeoutMs: 15e3 });
1929
+ const res = await runClaude(bin, ["--version"], 15e3);
1480
1930
  if (res.code !== 0) return null;
1481
1931
  return res.stdout.trim().split("\n")[0] || null;
1482
1932
  } catch {
@@ -1485,7 +1935,7 @@ async function claudeVersion(bin) {
1485
1935
  }
1486
1936
  async function claudeAuthStatus(bin) {
1487
1937
  try {
1488
- const res = await exec(bin, ["auth", "status", "--json"], { timeoutMs: 2e4 });
1938
+ const res = await runClaude(bin, ["auth", "status", "--json"], 2e4);
1489
1939
  const parsed = JSON.parse(res.stdout);
1490
1940
  if (typeof parsed.loggedIn !== "boolean") return { loggedIn: null, authMethod: null };
1491
1941
  return {
@@ -1510,7 +1960,7 @@ function parseClaudeHelp(help) {
1510
1960
  }
1511
1961
  async function claudeFeatures(bin) {
1512
1962
  try {
1513
- const res = await exec(bin, ["--help"], { timeoutMs: 15e3 });
1963
+ const res = await runClaude(bin, ["--help"], 15e3);
1514
1964
  return parseClaudeHelp(res.stdout);
1515
1965
  } catch {
1516
1966
  return parseClaudeHelp("");
@@ -1608,6 +2058,7 @@ function claudeArgs(launch) {
1608
2058
  return args;
1609
2059
  }
1610
2060
  function runnerSystemPrompt(input) {
2061
+ const env = environmentSentence(input.environment);
1611
2062
  if (!input.workBranch) {
1612
2063
  const scratch = [
1613
2064
  "You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
@@ -1616,7 +2067,7 @@ function runnerSystemPrompt(input) {
1616
2067
  if (input.reference) {
1617
2068
  scratch.push(
1618
2069
  `The repository this task concerns, ${input.reference.url}, is checked out at`,
1619
- `\`${input.reference.dir}\` (\`${input.reference.baseRef}\` as it is now), for you to read.`,
2070
+ input.reference.baseRef ? `\`${input.reference.dir}\` (\`${input.reference.baseRef}\` as it is now), for you to read.` : `\`${input.reference.dir}\`, for you to read.`,
1620
2071
  "Read it before you propose anything, so your work matches the product as it is: its",
1621
2072
  "screens, components, styles, words and data. It is for reading only: do not change it,",
1622
2073
  "commit or push. Nothing in it is kept, and this task\u2019s output is your response."
@@ -1634,6 +2085,7 @@ function runnerSystemPrompt(input) {
1634
2085
  "Do not upload or link them yourself."
1635
2086
  );
1636
2087
  }
2088
+ if (env) scratch.push(env);
1637
2089
  return scratch.join(" ");
1638
2090
  }
1639
2091
  const evidence = join4(input.cwd, EVIDENCE_DIR);
@@ -1666,14 +2118,21 @@ function runnerSystemPrompt(input) {
1666
2118
  "Other runs may share this computer:",
1667
2119
  "if the port is taken, start yours on another port; never stop a process you did not start.",
1668
2120
  "Do not start databases, containers or other services yourself, directly or through a",
1669
- "package script, unless the task asks you to; if one the server needs is not running, say so."
2121
+ "package script, unless the task asks you to; if one the server needs is not running, say so.",
2122
+ ...env ? [env] : []
1670
2123
  ].join(" ");
1671
2124
  }
2125
+ function environmentSentence(env) {
2126
+ if (!env?.names.length) return "";
2127
+ const list = (names) => names.map((n) => `\`${n}\``).join(", ");
2128
+ const secrets = env.secretNames.length ? ` ${list(env.secretNames)} ${env.secretNames.length === 1 ? "is a secret" : "are secrets"}: never print, log, commit or echo ${env.secretNames.length === 1 ? "its value" : "their values"}, and do not write ${env.secretNames.length === 1 ? "it" : "them"} into files.` : "";
2129
+ return `The run's environment sets these environment variables for you: ${list(env.names)}.${secrets}`;
2130
+ }
1672
2131
 
1673
2132
  // src/claude-code-rules.ts
1674
- import { readFile as readFile2, stat as stat3 } from "node:fs/promises";
2133
+ import { readFile as readFile3, stat as stat3 } from "node:fs/promises";
1675
2134
  import { homedir } from "node:os";
1676
- import { dirname as dirname2, isAbsolute as isAbsolute3, join as join5, resolve, sep } from "node:path";
2135
+ import { dirname as dirname3, isAbsolute as isAbsolute3, join as join5, resolve, sep as sep2 } from "node:path";
1677
2136
  var EMPTY = { allow: [], deny: [], ask: [], sources: [] };
1678
2137
  var RULE_SHAPE2 = /^(?:mcp__[A-Za-z0-9_-]+__\*|[A-Za-z][A-Za-z0-9_.-]*(?:\([\s\S]*\))?)$/;
1679
2138
  var FILE_TOOLS = /* @__PURE__ */ new Set([
@@ -1706,7 +2165,7 @@ function remoteRepositoryKey(url) {
1706
2165
  }
1707
2166
  async function readText(file) {
1708
2167
  try {
1709
- return await readFile2(file, "utf8");
2168
+ return await readFile3(file, "utf8");
1710
2169
  } catch {
1711
2170
  return null;
1712
2171
  }
@@ -1738,9 +2197,9 @@ async function gitConfigOf(folder) {
1738
2197
  const linked = resolve(dir, gitdir);
1739
2198
  const common = (await readText(join5(linked, "commondir")))?.trim();
1740
2199
  const commonDir = common ? resolve(linked, common) : linked;
1741
- return { config: join5(commonDir, "config"), roots: [dir, dirname2(commonDir)] };
2200
+ return { config: join5(commonDir, "config"), roots: [dir, dirname3(commonDir)] };
1742
2201
  }
1743
- const up = dirname2(dir);
2202
+ const up = dirname3(dir);
1744
2203
  if (up === dir) break;
1745
2204
  dir = up;
1746
2205
  }
@@ -1790,7 +2249,7 @@ var ClaudeCodeRules = class {
1790
2249
  }
1791
2250
  excluded(folder) {
1792
2251
  const f = resolve(folder);
1793
- return this.exclude.some((ex) => f === ex || f.startsWith(ex + sep));
2252
+ return this.exclude.some((ex) => f === ex || f.startsWith(ex + sep2));
1794
2253
  }
1795
2254
  async read(key) {
1796
2255
  const global = await readJsonFile(this.claudeJson);
@@ -1954,7 +2413,10 @@ var PermissionRelay = class {
1954
2413
  controlRequestId: req.controlRequestId,
1955
2414
  toolName: req.toolName,
1956
2415
  input: req.input,
1957
- inputSummary: summarizeToolInput(req.toolName, req.input),
2416
+ inputSummary: summarizeToolInput(
2417
+ req.toolName,
2418
+ this.deps.redactInput ? this.deps.redactInput(req.input) : req.input
2419
+ ),
1958
2420
  requestedAt,
1959
2421
  timer
1960
2422
  };
@@ -2063,10 +2525,13 @@ var PermissionRelay = class {
2063
2525
  };
2064
2526
 
2065
2527
  // src/stream-mapper.ts
2528
+ var CAP_TEXT_MARKER = "\n\u2026 [truncated by dt-runner]";
2066
2529
  function capText(text, max = RUNNER_EVENT_TEXT_MAX_LENGTH) {
2067
2530
  if (text.length <= max) return { text, truncated: false };
2068
- const marker = "\n\u2026 [truncated by dt-runner]";
2069
- return { text: text.slice(0, max - marker.length) + marker, truncated: true };
2531
+ return {
2532
+ text: text.slice(0, max - CAP_TEXT_MARKER.length) + CAP_TEXT_MARKER,
2533
+ truncated: true
2534
+ };
2070
2535
  }
2071
2536
  var ClaudeStreamMapper = class {
2072
2537
  /** Running offset of each live text block, by providerEventId. */
@@ -2303,9 +2768,9 @@ var claudeCodeDriver = {
2303
2768
  const features = input.features;
2304
2769
  const ask = input.askTools;
2305
2770
  const allowedTools = features.settingsFlag || ask.length === 0 ? input.allowedTools : input.allowedTools.filter((r) => !overlapsAsk(r, ask));
2306
- return {
2307
- bin: input.bin,
2308
- args: claudeArgs({
2771
+ return launcherCommand(
2772
+ input.bin,
2773
+ claudeArgs({
2309
2774
  permissionMode: input.permissionMode,
2310
2775
  allowedTools,
2311
2776
  disallowedTools: input.disallowedTools,
@@ -2317,7 +2782,7 @@ var claudeCodeDriver = {
2317
2782
  appendSystemPrompt: input.systemPrompt,
2318
2783
  features
2319
2784
  })
2320
- };
2785
+ );
2321
2786
  },
2322
2787
  createMapper: () => new ClaudeStreamMapper(),
2323
2788
  encodeMessage: (content) => ({ type: "user", message: { role: "user", content } }),
@@ -2426,42 +2891,11 @@ function startupHint(stderr) {
2426
2891
  }
2427
2892
 
2428
2893
  // src/drivers/codex/codex.ts
2429
- import { delimiter as delimiter2, join as join6 } from "node:path";
2430
-
2431
- // src/drivers/launcher.ts
2432
- import { access as access2 } from "node:fs/promises";
2433
- async function exists2(file) {
2434
- try {
2435
- await access2(file);
2436
- return true;
2437
- } catch {
2438
- return false;
2439
- }
2440
- }
2441
- function isJsLauncher(bin) {
2442
- return /\.[cm]?js$/i.test(bin);
2443
- }
2444
- function launcherCommand(bin, args) {
2445
- return isJsLauncher(bin) ? { bin: process.execPath, args: [bin, ...args] } : { bin, args };
2446
- }
2447
- async function findOverride(override, env) {
2448
- if (isJsLauncher(override)) return await exists2(override) ? override : null;
2449
- return which(override, env);
2450
- }
2451
-
2452
- // src/drivers/codex/codex.ts
2894
+ var CODEX_NPM_SCRIPT = ["node_modules", "@openai", "codex", "bin", "codex.js"];
2453
2895
  async function findCodex(env = process.env) {
2454
2896
  const override = env.DT_RUNNER_CODEX_BIN?.trim();
2455
2897
  if (override) return findOverride(override, env);
2456
- const found = await which("codex", env);
2457
- if (found) return found;
2458
- if (process.platform !== "win32") return null;
2459
- for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter2).filter(Boolean)) {
2460
- if (!await exists2(join6(dir, "codex.cmd"))) continue;
2461
- const script = join6(dir, "node_modules", "@openai", "codex", "bin", "codex.js");
2462
- if (await exists2(script)) return script;
2463
- }
2464
- return null;
2898
+ return which("codex", env, { npmPackageScript: [...CODEX_NPM_SCRIPT] });
2465
2899
  }
2466
2900
  var codexCommand = launcherCommand;
2467
2901
  function runCodex(bin, args, timeoutMs, env) {
@@ -3213,9 +3647,9 @@ function agentDriverKinds() {
3213
3647
  }
3214
3648
 
3215
3649
  // src/config.ts
3216
- import { chmod, mkdir as mkdir3, readFile as readFile3, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
3650
+ import { chmod, mkdir as mkdir3, readFile as readFile4, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
3217
3651
  import { homedir as homedir2 } from "node:os";
3218
- import { dirname as dirname3, join as join7 } from "node:path";
3652
+ import { dirname as dirname4, join as join6 } from "node:path";
3219
3653
 
3220
3654
  // src/invocation.ts
3221
3655
  var RUNNER_PACKAGE = "@discovery-tree/runner";
@@ -3231,21 +3665,21 @@ function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
3231
3665
  function runnerPaths(env = process.env) {
3232
3666
  const home = homedir2();
3233
3667
  if (process.platform === "win32") {
3234
- const roaming = env.APPDATA || join7(home, "AppData", "Roaming");
3235
- const local = env.LOCALAPPDATA || join7(home, "AppData", "Local");
3668
+ const roaming = env.APPDATA || join6(home, "AppData", "Roaming");
3669
+ const local = env.LOCALAPPDATA || join6(home, "AppData", "Local");
3236
3670
  return {
3237
- configFile: join7(roaming, "discovery-tree", "runner.json"),
3238
- dataDir: join7(local, "discovery-tree", "runner"),
3239
- stateDir: join7(local, "discovery-tree", "runner", "state")
3671
+ configFile: join6(roaming, "discovery-tree", "runner.json"),
3672
+ dataDir: join6(local, "discovery-tree", "runner"),
3673
+ stateDir: join6(local, "discovery-tree", "runner", "state")
3240
3674
  };
3241
3675
  }
3242
- const config = env.XDG_CONFIG_HOME || join7(home, ".config");
3243
- const data = env.XDG_DATA_HOME || join7(home, ".local", "share");
3244
- const state = env.XDG_STATE_HOME || join7(home, ".local", "state");
3676
+ const config = env.XDG_CONFIG_HOME || join6(home, ".config");
3677
+ const data = env.XDG_DATA_HOME || join6(home, ".local", "share");
3678
+ const state = env.XDG_STATE_HOME || join6(home, ".local", "state");
3245
3679
  return {
3246
- configFile: join7(config, "discovery-tree", "runner.json"),
3247
- dataDir: join7(data, "discovery-tree", "runner"),
3248
- stateDir: join7(state, "discovery-tree", "runner")
3680
+ configFile: join6(config, "discovery-tree", "runner.json"),
3681
+ dataDir: join6(data, "discovery-tree", "runner"),
3682
+ stateDir: join6(state, "discovery-tree", "runner")
3249
3683
  };
3250
3684
  }
3251
3685
  var PERMISSION_MODES = [
@@ -3440,7 +3874,7 @@ var DEFAULT_DISALLOWED_TOOLS = [
3440
3874
  ];
3441
3875
  function configDirRules(configFile, platform = process.platform) {
3442
3876
  if (platform === "win32") return [];
3443
- const dir = dirname3(configFile);
3877
+ const dir = dirname4(configFile);
3444
3878
  if (!dir.startsWith("/")) return [];
3445
3879
  return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
3446
3880
  }
@@ -3450,7 +3884,7 @@ var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
3450
3884
  async function readConfigFile(file) {
3451
3885
  let raw;
3452
3886
  try {
3453
- raw = await readFile3(file, "utf8");
3887
+ raw = await readFile4(file, "utf8");
3454
3888
  } catch (err) {
3455
3889
  if (err.code === "ENOENT") return null;
3456
3890
  throw err;
@@ -3464,7 +3898,7 @@ async function readConfigFile(file) {
3464
3898
  }
3465
3899
  }
3466
3900
  async function writeConfigFile(file, config) {
3467
- await mkdir3(dirname3(file), { recursive: true, mode: 448 });
3901
+ await mkdir3(dirname4(file), { recursive: true, mode: 448 });
3468
3902
  await writeFile2(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
3469
3903
  await chmod(file, 384).catch(() => void 0);
3470
3904
  }
@@ -3495,6 +3929,12 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
3495
3929
  `maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
3496
3930
  );
3497
3931
  }
3932
+ const maxJobs = overrides.maxJobs ?? file?.maxJobs ?? RUNNER_DEFAULT_MAX_JOBS;
3933
+ if (!Number.isInteger(maxJobs) || maxJobs < 1 || maxJobs > RUNNER_MAX_JOBS_LIMIT) {
3934
+ throw new Error(
3935
+ `maxJobs must be a whole number from 1 to ${RUNNER_MAX_JOBS_LIMIT} (got ${maxJobs}).`
3936
+ );
3937
+ }
3498
3938
  const inherit = file?.inheritClaudeCodePermissions;
3499
3939
  if (inherit !== void 0 && typeof inherit !== "boolean") {
3500
3940
  throw new Error(
@@ -3536,8 +3976,9 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
3536
3976
  token: env.DT_RUNNER_TOKEN || file?.token || null,
3537
3977
  name: file?.name ?? null,
3538
3978
  maxSessions,
3539
- reposDir: overrides.reposDir ?? file?.reposDir ?? join7(paths.dataDir, "repos"),
3540
- worktreesDir: file?.worktreesDir ?? join7(paths.dataDir, "worktrees"),
3979
+ maxJobs,
3980
+ reposDir: overrides.reposDir ?? file?.reposDir ?? join6(paths.dataDir, "repos"),
3981
+ worktreesDir: file?.worktreesDir ?? join6(paths.dataDir, "worktrees"),
3541
3982
  permissionMode: mode,
3542
3983
  allowedTools: [...new Set(allowed)],
3543
3984
  disallowedTools: [...new Set(disallowed)],
@@ -3555,7 +3996,7 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
3555
3996
  }
3556
3997
 
3557
3998
  // src/daemon.ts
3558
- import { join as join13 } from "node:path";
3999
+ import { join as join15 } from "node:path";
3559
4000
 
3560
4001
  // src/backoff.ts
3561
4002
  function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
@@ -3563,13 +4004,13 @@ function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
3563
4004
  return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
3564
4005
  }
3565
4006
  function sleep(ms, signal) {
3566
- return new Promise((resolve2) => {
3567
- if (signal?.aborted) return resolve2();
4007
+ return new Promise((resolve4) => {
4008
+ if (signal?.aborted) return resolve4();
3568
4009
  const timer = setTimeout(done, ms);
3569
4010
  function done() {
3570
4011
  clearTimeout(timer);
3571
4012
  signal?.removeEventListener("abort", done);
3572
- resolve2();
4013
+ resolve4();
3573
4014
  }
3574
4015
  signal?.addEventListener("abort", done, { once: true });
3575
4016
  });
@@ -3578,7 +4019,7 @@ function sleep(ms, signal) {
3578
4019
  // src/completion.ts
3579
4020
  import { mkdtemp as mkdtemp2, rm as rm4 } from "node:fs/promises";
3580
4021
  import { tmpdir as tmpdir2 } from "node:os";
3581
- import { join as join8 } from "node:path";
4022
+ import { join as join7 } from "node:path";
3582
4023
  var COMPLETION_DENIED_TOOLS = [
3583
4024
  "Read",
3584
4025
  "Glob",
@@ -3626,7 +4067,7 @@ async function answerCompletion(req, deps) {
3626
4067
  try {
3627
4068
  const { bin, features } = await deps.claude();
3628
4069
  const args = completionArgs(req, features);
3629
- cwd = await mkdtemp2(join8(tmpdir2(), "dt-runner-completion-"));
4070
+ cwd = await mkdtemp2(join7(tmpdir2(), "dt-runner-completion-"));
3630
4071
  const run = deps.run ?? ((b, a, o) => exec(b, a, { ...o, ownTree: true }));
3631
4072
  const input = req.systemPrompt ? `<instructions>
3632
4073
  ${req.systemPrompt}
@@ -3677,92 +4118,2124 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
3677
4118
  return [...out];
3678
4119
  }
3679
4120
 
3680
- // src/session-manager.ts
3681
- import { mkdir as mkdir7, rm as rm6, writeFile as writeFile5 } from "node:fs/promises";
3682
- import { join as join12 } from "node:path";
4121
+ // src/jobs/job-manager.ts
4122
+ import { randomBytes as randomBytes3, scrypt, timingSafeEqual } from "node:crypto";
4123
+ import { realpathSync } from "node:fs";
4124
+ import { mkdir as mkdir6, readFile as readFile8, readdir as readdir2, stat as stat4 } from "node:fs/promises";
4125
+ import { basename, dirname as dirname7, isAbsolute as isAbsolute4, join as join10, resolve as resolve2, sep as sep3 } from "node:path";
3683
4126
 
3684
- // src/prompt-images.ts
3685
- import { mkdir as mkdir4, writeFile as writeFile3 } from "node:fs/promises";
3686
- import { join as join9 } from "node:path";
3687
- var EXTENSIONS = {
3688
- "image/png": ".png",
3689
- "image/jpeg": ".jpg",
3690
- "image/gif": ".gif",
3691
- "image/webp": ".webp"
3692
- };
3693
- function promptImageFileName(index, filename, mimeType) {
3694
- const base = (filename.split(/[\\/]/).pop() ?? "").replace(/[\u0000-\u001f\u007f<>:"|?*]+/g, "_").replace(/^\.+/, "").trim().slice(0, 120);
3695
- const ext = EXTENSIONS[mimeType] ?? "";
3696
- const named = base || `image${ext}`;
3697
- const withExt = ext && !named.toLowerCase().endsWith(ext) ? `${named}${ext}` : named;
3698
- return `${String(index + 1).padStart(2, "0")}-${withExt}`;
4127
+ // src/environment.ts
4128
+ function sessionEnvironment(raw) {
4129
+ if (!raw || typeof raw !== "object") return null;
4130
+ const { variables, secrets } = raw;
4131
+ const env = {};
4132
+ const secretValues = [];
4133
+ const skipped = [];
4134
+ const take = (from, max, maxLength, onTaken) => {
4135
+ if (!from || typeof from !== "object" || Array.isArray(from)) return;
4136
+ let n = 0;
4137
+ for (const [name, value] of Object.entries(from)) {
4138
+ const ok = ENV_NAME_PATTERN.test(name) && !isReservedEnvName(name) && typeof value === "string" && value.length <= maxLength && !value.includes("\0") && n < max;
4139
+ if (!ok) {
4140
+ skipped.push(ENV_NAME_PATTERN.test(name) ? name : "(an invalid name)");
4141
+ continue;
4142
+ }
4143
+ n++;
4144
+ env[name] = value;
4145
+ onTaken(name, value);
4146
+ }
4147
+ };
4148
+ take(variables, ENV_VARIABLES_MAX, ENV_VARIABLE_VALUE_MAX_LENGTH, () => void 0);
4149
+ take(
4150
+ secrets,
4151
+ ENV_SECRETS_MAX,
4152
+ ENV_SECRET_VALUE_MAX_LENGTH,
4153
+ (name, value) => secretValues.push({ name, value })
4154
+ );
4155
+ const names = Object.keys(env).sort();
4156
+ if (!names.length && !skipped.length) return null;
4157
+ return {
4158
+ env,
4159
+ names,
4160
+ secretNames: [...new Set(secretValues.map((s) => s.name))].sort(),
4161
+ skipped,
4162
+ unredacted: secretValues.filter((s) => s.value.length > 0 && s.value.length < SECRET_REDACTION_MIN_LENGTH).map((s) => s.name).sort(),
4163
+ redactor: new SecretRedactor(secretValues)
4164
+ };
3699
4165
  }
3700
- async function savePromptImages(input) {
3701
- const out = { saved: [], failed: [] };
3702
- if (input.images.length === 0) return out;
3703
- const dir = join9(input.cwd, RUNNER_TASK_IMAGES_DIR);
3704
- await mkdir4(dir, { recursive: true });
3705
- if (input.inRepository) {
3706
- await excludeFromGit(
3707
- input.cwd,
3708
- RUNNER_TASK_IMAGES_DIR,
3709
- "Task images dt-runner saves for its agent"
3710
- );
4166
+ var SECRET_REDACTION_MIN_LENGTH = 4;
4167
+ var RULE_PLACEHOLDER = "[secret:";
4168
+ var DELTA_STREAMS_KEPT = 64;
4169
+ var PROTOCOL_FIELDS = /* @__PURE__ */ new Set([
4170
+ "type",
4171
+ "status",
4172
+ "id",
4173
+ "providerEventId",
4174
+ "callId",
4175
+ "claudeSessionId",
4176
+ "conversationId",
4177
+ "requestedAt",
4178
+ "deniedAt"
4179
+ ]);
4180
+ var FRAME_FIELDS = /* @__PURE__ */ new Set(["tool", "request", "denial"]);
4181
+ var SecretRedactor = class {
4182
+ secrets;
4183
+ /** `[secret: NAME]` for the session's own names: already redacted, left as it is. */
4184
+ placeholders;
4185
+ /** Per live message: what was held back, and the redacted text's length so far. */
4186
+ deltas = /* @__PURE__ */ new Map();
4187
+ constructor(secrets) {
4188
+ this.secrets = secrets.filter((s) => s.value.length >= SECRET_REDACTION_MIN_LENGTH).sort((a, b) => b.value.length - a.value.length);
4189
+ this.placeholders = [...new Set(this.secrets.map((s) => placeholder(s.name)))];
4190
+ }
4191
+ /** Whether there is anything to redact. */
4192
+ get active() {
4193
+ return this.secrets.length > 0;
3711
4194
  }
3712
- for (const [index, image] of input.images.entries()) {
3713
- try {
3714
- const res = await input.fetcher.getPromptImage(input.sessionId, image.attachmentId);
3715
- const path = join9(
3716
- dir,
3717
- promptImageFileName(index, image.filename, res.mimeType || image.mimeType)
3718
- );
3719
- await writeFile3(path, Buffer.from(res.dataBase64, "base64"));
3720
- out.saved.push({ filename: image.filename, path });
3721
- } catch {
3722
- out.failed.push(image.filename);
4195
+ /**
4196
+ * `text` with every secret value replaced. Values that overlap (one inside another, or
4197
+ * sharing characters) are replaced as one span, so no part of either is left. A text the
4198
+ * runner cut to length (`capText`) also loses what a value cut off at its end left before
4199
+ * the marker: a value missing its end would no longer be recognised.
4200
+ */
4201
+ redact(text) {
4202
+ if (!this.active || !text) return text;
4203
+ if (text.endsWith(CAP_TEXT_MARKER)) {
4204
+ const raw = text.slice(0, -CAP_TEXT_MARKER.length);
4205
+ return fitEvent(this.replace(raw.slice(0, this.endOfWhole(raw))));
3723
4206
  }
4207
+ return this.replace(text);
3724
4208
  }
3725
- return out;
3726
- }
3727
- function promptWithImagePaths(prompt, images) {
3728
- if (images.saved.length === 0 && images.failed.length === 0) return prompt;
3729
- const lines = [
3730
- "",
3731
- "IMAGE FILES FOR THIS TASK \u2014 the images the attachment lists above refer to, saved as",
3732
- "files. Open each one and look at it before you start (read it as an image).",
3733
- ...images.saved.map((i) => `- ${i.filename}: ${i.path}`),
3734
- ...images.failed.map(
3735
- (name) => `- ${name}: could not be downloaded; say so rather than describing it`
3736
- )
3737
- ];
3738
- return `${prompt}
3739
- ${lines.join("\n")}`;
3740
- }
3741
-
3742
- // src/fsutil.ts
3743
- import { mkdir as mkdir5, readFile as readFile4, rename as rename2, writeFile as writeFile4 } from "node:fs/promises";
3744
- import { dirname as dirname4 } from "node:path";
3745
- async function writeJsonAtomic(file, value) {
3746
- await mkdir5(dirname4(file), { recursive: true });
3747
- const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
3748
- await writeFile4(tmp, JSON.stringify(value), { mode: 384 });
3749
- await rename2(tmp, file);
3750
- }
3751
- async function readJson(file) {
3752
- try {
3753
- return JSON.parse(await readFile4(file, "utf8"));
3754
- } catch (err) {
3755
- if (err.code === "ENOENT") return null;
3756
- if (err instanceof SyntaxError) return null;
3757
- throw err;
4209
+ /**
4210
+ * {@link redact} on the end of a longer text (`cutAtStart`: its start was dropped, as a
4211
+ * rolling stderr tail's is). What a value cut off at the start left there is dropped too: a
4212
+ * value missing its beginning would no longer be recognised.
4213
+ */
4214
+ redactWindow(text, cutAtStart) {
4215
+ if (!this.active) return text;
4216
+ return this.redact(cutAtStart ? text.slice(this.startOfWhole(text)) : text);
3758
4217
  }
3759
- }
3760
-
3761
- // src/outbox.ts
3762
- var MAX_REJECTED_ATTEMPTS = 3;
3763
- var SessionOutbox = class _SessionOutbox {
3764
- constructor(opts) {
3765
- this.opts = opts;
4218
+ /**
4219
+ * {@link redact} on a text whose end was cut off (a job's log line past its length limit):
4220
+ * what a value cut off there left at its end is dropped as well, as no longer recognisable.
4221
+ */
4222
+ redactCut(text) {
4223
+ if (!this.active || !text) return text;
4224
+ return this.replace(text.slice(0, this.endOfWhole(text)));
4225
+ }
4226
+ /**
4227
+ * Every place a value occurs, overlapping ones merged into one span (named for its longest
4228
+ * value), in order. Values inside a placeholder already written are not counted.
4229
+ */
4230
+ spans(text) {
4231
+ const kept = [];
4232
+ for (const p of this.placeholders) {
4233
+ for (let i = text.indexOf(p); i >= 0; i = text.indexOf(p, i + 1))
4234
+ kept.push([i, i + p.length]);
4235
+ }
4236
+ const found = [];
4237
+ for (const { name, value } of this.secrets) {
4238
+ for (let i = text.indexOf(value); i >= 0; i = text.indexOf(value, i + 1)) {
4239
+ const end = i + value.length;
4240
+ if (kept.some(([a, b]) => a <= i && end <= b)) continue;
4241
+ const inside = kept.find(([a, b]) => a <= i && i < b);
4242
+ found.push({ start: inside ? inside[1] : i, end, name, len: value.length });
4243
+ }
4244
+ }
4245
+ found.sort((a, b) => a.start - b.start || b.len - a.len);
4246
+ const merged = [];
4247
+ for (const span of found) {
4248
+ const last = merged.at(-1);
4249
+ if (last && span.start < last.end) {
4250
+ if (span.len > last.len) Object.assign(last, { name: span.name, len: span.len });
4251
+ last.end = Math.max(last.end, span.end);
4252
+ } else {
4253
+ merged.push({ ...span });
4254
+ }
4255
+ }
4256
+ return merged;
4257
+ }
4258
+ replace(text) {
4259
+ const spans = this.spans(text);
4260
+ if (!spans.length) return text;
4261
+ let out = "";
4262
+ let at = 0;
4263
+ for (const span of spans) {
4264
+ out += text.slice(at, span.start) + placeholder(span.name);
4265
+ at = span.end;
4266
+ }
4267
+ return out + text.slice(at);
4268
+ }
4269
+ /** The span of a whole value that `cut` falls strictly inside, if any. */
4270
+ spanAcross(text, cut2) {
4271
+ return this.spans(text).find((s) => s.start < cut2 && cut2 < s.end);
4272
+ }
4273
+ /**
4274
+ * Where `text` stops being whole at its end: before the longest end that a value starts
4275
+ * with, unless that end belongs to a whole value, which is kept (and replaced).
4276
+ */
4277
+ endOfWhole(text) {
4278
+ const cut2 = text.length - this.partialAtEnd(text);
4279
+ return this.spanAcross(text, cut2)?.end ?? cut2;
4280
+ }
4281
+ /**
4282
+ * Where `text` starts being whole: after the longest start that a value ends with (what a
4283
+ * value cut off at the start left), unless that start belongs to a whole value, kept.
4284
+ */
4285
+ startOfWhole(text) {
4286
+ let cut2 = 0;
4287
+ for (const { value } of this.secrets) {
4288
+ for (let k = Math.min(value.length - 1, text.length); k > cut2; k--) {
4289
+ if (value.endsWith(text.slice(0, k))) {
4290
+ cut2 = k;
4291
+ break;
4292
+ }
4293
+ }
4294
+ }
4295
+ return this.spanAcross(text, cut2)?.start ?? cut2;
4296
+ }
4297
+ /**
4298
+ * A call's input as rules may be built from: redacted, with each placeholder written as
4299
+ * one word (`[secret:NAME]`, {@link RULE_PLACEHOLDER}), so a command splits into words as
4300
+ * it did.
4301
+ */
4302
+ forRules(input) {
4303
+ if (!this.active) return input;
4304
+ const compact = (v) => {
4305
+ if (typeof v === "string") return this.redact(v).replace(/\[secret: /g, RULE_PLACEHOLDER);
4306
+ if (Array.isArray(v)) return v.map(compact);
4307
+ if (v && typeof v === "object") {
4308
+ return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, compact(x)]));
4309
+ }
4310
+ return v;
4311
+ };
4312
+ return compact(input);
4313
+ }
4314
+ /** {@link redact} through every string in a JSON-like value (tool inputs, outputs). */
4315
+ redactDeep(value) {
4316
+ if (!this.active) return value;
4317
+ if (typeof value === "string") return this.redact(value);
4318
+ if (Array.isArray(value)) return value.map((v) => this.redactDeep(v));
4319
+ if (value && typeof value === "object") {
4320
+ const out = {};
4321
+ for (const [k, v] of Object.entries(value)) {
4322
+ out[k] = this.redactDeep(v);
4323
+ }
4324
+ return out;
4325
+ }
4326
+ return value;
4327
+ }
4328
+ /**
4329
+ * The event as it may be posted, or null for a text delta that is all held back for now.
4330
+ */
4331
+ event(event) {
4332
+ if (!this.active) return event;
4333
+ if (event.type === "assistant_delta") return this.delta(event);
4334
+ if (event.type === "assistant_message") this.deltas.delete(event.providerEventId);
4335
+ return this.redactFrame(event);
4336
+ }
4337
+ /**
4338
+ * {@link redactDeep} over an event, keeping its protocol fields as they are: a value that
4339
+ * happens to equal `finished` or `completed` must not turn a result's status or a call's
4340
+ * status into a placeholder the server refuses. Only the event itself and its `tool`,
4341
+ * `request` and `denial` are frames; anything inside them (a call's `input`) is content.
4342
+ */
4343
+ redactFrame(frame) {
4344
+ const out = {};
4345
+ for (const [key, value] of Object.entries(frame)) {
4346
+ if (PROTOCOL_FIELDS.has(key) && typeof value === "string") out[key] = value;
4347
+ else if (FRAME_FIELDS.has(key) && value !== null && typeof value === "object" && !Array.isArray(value)) {
4348
+ out[key] = this.redactFrame(value);
4349
+ } else out[key] = this.redactDeep(value);
4350
+ }
4351
+ return out;
4352
+ }
4353
+ delta(event) {
4354
+ const key = event.providerEventId;
4355
+ const stream = this.deltas.get(key) ?? { held: "", offset: 0 };
4356
+ this.deltas.delete(key);
4357
+ this.deltas.set(key, stream);
4358
+ while (this.deltas.size > DELTA_STREAMS_KEPT) {
4359
+ this.deltas.delete(this.deltas.keys().next().value);
4360
+ }
4361
+ const text = stream.held + event.text;
4362
+ const end = text.length - this.partialAtEnd(text);
4363
+ const cut2 = this.spanAcross(text, end)?.start ?? end;
4364
+ stream.held = text.slice(cut2);
4365
+ const ready = this.replace(text.slice(0, cut2));
4366
+ if (!ready) return null;
4367
+ const offset = stream.offset;
4368
+ stream.offset += ready.length;
4369
+ return {
4370
+ ...event,
4371
+ text: ready,
4372
+ ...event.offset !== void 0 ? { offset } : {}
4373
+ };
4374
+ }
4375
+ /** The length of the longest end of `text` that a secret value starts with (not all of it). */
4376
+ partialAtEnd(text) {
4377
+ if (!text) return 0;
4378
+ const last = text.charCodeAt(text.length - 1);
4379
+ let best = 0;
4380
+ for (const { value } of this.secrets) {
4381
+ for (let k = Math.min(value.length - 1, text.length); k > best; k--) {
4382
+ if (value.charCodeAt(k - 1) !== last) continue;
4383
+ if (text.endsWith(value.slice(0, k))) {
4384
+ best = k;
4385
+ break;
4386
+ }
4387
+ }
4388
+ }
4389
+ return best;
4390
+ }
4391
+ };
4392
+ function redactingLogger(logger, redactor) {
4393
+ if (!redactor?.active) return logger;
4394
+ const wrap = (level) => (msg, fields) => logger[level](redactor.redact(msg), fields ? redactor.redactDeep(fields) : void 0);
4395
+ return { debug: wrap("debug"), info: wrap("info"), warn: wrap("warn"), error: wrap("error") };
4396
+ }
4397
+ function placeholder(name) {
4398
+ return `[secret: ${name}]`;
4399
+ }
4400
+ function fitEvent(body) {
4401
+ const room = RUNNER_EVENT_TEXT_MAX_LENGTH - CAP_TEXT_MARKER.length;
4402
+ if (body.length <= room) return body + CAP_TEXT_MARKER;
4403
+ let out = body.slice(0, room);
4404
+ const open3 = out.lastIndexOf("[");
4405
+ if (open3 >= 0 && out.indexOf("]", open3) < 0) {
4406
+ const rest = out.slice(open3);
4407
+ if (rest.startsWith("[secret: ") || "[secret: ".startsWith(rest)) out = out.slice(0, open3);
4408
+ }
4409
+ return out + CAP_TEXT_MARKER;
4410
+ }
4411
+
4412
+ // src/fsutil.ts
4413
+ import { mkdir as mkdir4, readFile as readFile5, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
4414
+ import { dirname as dirname5 } from "node:path";
4415
+ async function writeJsonAtomic(file, value) {
4416
+ await mkdir4(dirname5(file), { recursive: true });
4417
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
4418
+ await writeFile3(tmp, JSON.stringify(value), { mode: 384 });
4419
+ await rename2(tmp, file);
4420
+ }
4421
+ async function readJson(file) {
4422
+ try {
4423
+ return JSON.parse(await readFile5(file, "utf8"));
4424
+ } catch (err) {
4425
+ if (err.code === "ENOENT") return null;
4426
+ if (err instanceof SyntaxError) return null;
4427
+ throw err;
4428
+ }
4429
+ }
4430
+
4431
+ // src/jobs/job-log.ts
4432
+ import { open } from "node:fs/promises";
4433
+ function startCursor() {
4434
+ return { stdout: { offset: 0, skipping: false }, stderr: { offset: 0, skipping: false } };
4435
+ }
4436
+ var JOB_LINE_MAX_BYTES = 64 * 1024;
4437
+ var READ_CHUNK_BYTES = 1024 * 1024;
4438
+ var JOB_READ_MAX_BYTES = 8 * 1024 * 1024;
4439
+ var decoder = new TextDecoder("utf-8", { fatal: false });
4440
+ var LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
4441
+ function postableLineText(text) {
4442
+ const clean = text.replace(LONE_SURROGATE, "\uFFFD");
4443
+ const max = RUNNER_JOB_LOG_LINE_MAX_LENGTH;
4444
+ if (clean.length <= max) return clean;
4445
+ const code = clean.charCodeAt(max - 1);
4446
+ let cut2 = clean.slice(0, code >= 55296 && code <= 56319 ? max - 1 : max);
4447
+ const open3 = cut2.lastIndexOf("[secret:");
4448
+ if (open3 >= 0 && cut2.indexOf("]", open3) < 0) cut2 = cut2.slice(0, open3);
4449
+ return cut2;
4450
+ }
4451
+ function completeUtf8(bytes) {
4452
+ let lead = bytes.length - 1;
4453
+ while (lead >= 0 && bytes.length - lead <= 3 && (bytes[lead] & 192) === 128) lead--;
4454
+ if (lead < 0) return bytes.length;
4455
+ const b = bytes[lead];
4456
+ const size = b >= 240 ? 4 : b >= 224 ? 3 : b >= 192 ? 2 : 1;
4457
+ return bytes.length - lead < size ? lead : bytes.length;
4458
+ }
4459
+ var LogFileReader = class {
4460
+ constructor(file, stream, from) {
4461
+ this.file = file;
4462
+ this.stream = stream;
4463
+ this.cursor = { ...from };
4464
+ }
4465
+ handle = null;
4466
+ cursor;
4467
+ get position() {
4468
+ return { ...this.cursor };
4469
+ }
4470
+ /** The last read reached the end of what is written (false: there is more to read now). */
4471
+ atEnd = true;
4472
+ /**
4473
+ * The lines written since the last call, from at most about `maxBytes` of the file (a
4474
+ * backlog is read over several calls, never all at once); `final`: when the end is
4475
+ * reached, the partial last line too.
4476
+ */
4477
+ async read(final = false, maxBytes = JOB_READ_MAX_BYTES) {
4478
+ if (!this.handle) {
4479
+ try {
4480
+ this.handle = await open(this.file, "r");
4481
+ } catch (err) {
4482
+ this.atEnd = true;
4483
+ if (err.code === "ENOENT") return [];
4484
+ throw err;
4485
+ }
4486
+ }
4487
+ const lines = [];
4488
+ const at = (/* @__PURE__ */ new Date()).toISOString();
4489
+ let pending = Buffer.alloc(0);
4490
+ let position = this.cursor.offset;
4491
+ const limit = this.cursor.offset + Math.max(maxBytes, READ_CHUNK_BYTES);
4492
+ this.atEnd = false;
4493
+ for (; ; ) {
4494
+ if (position >= limit) break;
4495
+ const chunk = Buffer.alloc(READ_CHUNK_BYTES);
4496
+ const { bytesRead } = await this.handle.read(chunk, 0, chunk.length, position);
4497
+ if (bytesRead === 0) {
4498
+ this.atEnd = true;
4499
+ break;
4500
+ }
4501
+ position += bytesRead;
4502
+ pending = pending.length ? Buffer.concat([pending, chunk.subarray(0, bytesRead)]) : chunk.subarray(0, bytesRead);
4503
+ let start2 = 0;
4504
+ for (; ; ) {
4505
+ const nl = pending.indexOf(10, start2);
4506
+ if (nl < 0) break;
4507
+ this.take(pending.subarray(start2, nl), lines, at);
4508
+ start2 = nl + 1;
4509
+ }
4510
+ this.cursor.offset += start2;
4511
+ pending = pending.subarray(start2);
4512
+ if (pending.length > JOB_LINE_MAX_BYTES) {
4513
+ if (!this.cursor.skipping) this.emitCut(pending, lines, at);
4514
+ this.cursor.skipping = true;
4515
+ this.cursor.offset += pending.length;
4516
+ pending = Buffer.alloc(0);
4517
+ }
4518
+ if (bytesRead < chunk.length) {
4519
+ this.atEnd = true;
4520
+ break;
4521
+ }
4522
+ }
4523
+ if (final && this.atEnd && pending.length) {
4524
+ if (this.cursor.skipping) this.cursor.skipping = false;
4525
+ else this.emit(pending.subarray(0, completeUtf8(pending)), lines, at, true);
4526
+ this.cursor.offset += pending.length;
4527
+ }
4528
+ return lines;
4529
+ }
4530
+ async close() {
4531
+ const h = this.handle;
4532
+ this.handle = null;
4533
+ await h?.close().catch(() => void 0);
4534
+ }
4535
+ /** A whole line (without its `\n`): emitted, unless it is the rest of one passed over. */
4536
+ take(bytes, lines, at) {
4537
+ if (this.cursor.skipping) {
4538
+ this.cursor.skipping = false;
4539
+ return;
4540
+ }
4541
+ if (bytes.length > JOB_LINE_MAX_BYTES) this.emitCut(bytes, lines, at);
4542
+ else this.emit(bytes, lines, at);
4543
+ }
4544
+ /**
4545
+ * The first {@link JOB_LINE_MAX_BYTES} of a longer line, cut where a character starts (not
4546
+ * inside one, which would leave U+FFFD where the end of a secret's prefix is), and marked
4547
+ * as cut, so its redaction drops what a value cut off there left.
4548
+ */
4549
+ emitCut(bytes, lines, at) {
4550
+ let end = JOB_LINE_MAX_BYTES;
4551
+ while (end > 0 && (bytes[end] & 192) === 128) end--;
4552
+ this.emit(bytes.subarray(0, end), lines, at, true);
4553
+ }
4554
+ emit(bytes, lines, at, cut2 = false) {
4555
+ let text = decoder.decode(bytes);
4556
+ if (!cut2 && text.endsWith("\r")) text = text.slice(0, -1);
4557
+ lines.push({ stream: this.stream, text, at, ...cut2 ? { cut: true } : {} });
4558
+ }
4559
+ };
4560
+
4561
+ // src/jobs/job-outbox.ts
4562
+ var MAX_REJECTED_ATTEMPTS = 3;
4563
+ var JobOutbox = class _JobOutbox {
4564
+ constructor(opts) {
4565
+ this.opts = opts;
4566
+ }
4567
+ nextSeq = 1;
4568
+ pending = [];
4569
+ status = null;
4570
+ tail = startCursor();
4571
+ finished = false;
4572
+ /** What the last completed write saved: only that much may be posted. */
4573
+ durableSeq = 0;
4574
+ durableStatus = null;
4575
+ pumping = false;
4576
+ pumpTimer = null;
4577
+ stopped = false;
4578
+ discarded = false;
4579
+ stopController = new AbortController();
4580
+ persistChain = Promise.resolve();
4581
+ persistQueued = false;
4582
+ /** Writes failed in a row, and the timer of the next try. */
4583
+ persistFailures = 0;
4584
+ persistRetry = null;
4585
+ idleWaiters = [];
4586
+ finishNotified = false;
4587
+ static async open(opts) {
4588
+ const box = new _JobOutbox(opts);
4589
+ const saved = await readJson(opts.file);
4590
+ if (saved) {
4591
+ box.pending = Array.isArray(saved.pending) ? saved.pending : [];
4592
+ const last = box.pending.at(-1)?.seq ?? 0;
4593
+ box.nextSeq = Math.max(saved.nextSeq || 1, last + 1);
4594
+ box.status = saved.status ?? null;
4595
+ box.tail = saved.cursor ?? startCursor();
4596
+ box.finished = saved.finished === true;
4597
+ box.durableSeq = box.nextSeq - 1;
4598
+ box.durableStatus = box.status;
4599
+ }
4600
+ if (box.pending.length || box.status) box.schedulePump();
4601
+ return box;
4602
+ }
4603
+ /** Where reading the job's output got to, as last queued. */
4604
+ get cursor() {
4605
+ return this.tail;
4606
+ }
4607
+ /** Its last report is through (or there is none to give) and no line waits. */
4608
+ get isFinished() {
4609
+ return this.finished && this.pending.length === 0 && !this.status;
4610
+ }
4611
+ /** The job's last report is queued or sent (or it ended with none to give). */
4612
+ get hasFinalReport() {
4613
+ return this.finished;
4614
+ }
4615
+ get size() {
4616
+ return this.pending.length;
4617
+ }
4618
+ /** Queues lines read up to `cursor` (none, when reading only moved past what is not sent). */
4619
+ add(lines, cursor) {
4620
+ if (this.discarded) return;
4621
+ const moved = JSON.stringify(cursor) !== JSON.stringify(this.tail);
4622
+ if (!lines.length && !moved) return;
4623
+ this.tail = cursor;
4624
+ for (const line of lines) this.pending.push({ seq: this.nextSeq++, ...line });
4625
+ if (this.pending.length > RUNNER_JOB_LOG_LINES_KEPT) {
4626
+ this.pending = this.pending.slice(-RUNNER_JOB_LOG_LINES_KEPT);
4627
+ }
4628
+ this.persist();
4629
+ if (lines.length) this.schedulePump();
4630
+ }
4631
+ /** Queues a status; one that ends the job is its last report. */
4632
+ report(report) {
4633
+ if (this.discarded || this.finished) return;
4634
+ if (report.status === "running" && this.status && this.status.report.status !== "running") {
4635
+ return;
4636
+ }
4637
+ this.status = { report, afterSeq: this.nextSeq };
4638
+ if (report.status !== "running") this.finished = true;
4639
+ this.persist();
4640
+ this.schedulePump();
4641
+ }
4642
+ /** The job ended with nothing to say about how (it was lost): only its lines are left. */
4643
+ endWithoutReport() {
4644
+ if (this.discarded || this.finished) return;
4645
+ this.finished = true;
4646
+ if (this.status?.report.status === "running") this.status = null;
4647
+ this.persist();
4648
+ this.checkFinished();
4649
+ }
4650
+ /** Resolves once everything queued is posted (true), or the time is up (false). */
4651
+ async flush(timeoutMs) {
4652
+ if (this.stopped || this.discarded) return this.isDrained();
4653
+ if (this.pumpTimer) {
4654
+ clearTimeout(this.pumpTimer);
4655
+ this.pumpTimer = null;
4656
+ }
4657
+ await this.persistChain;
4658
+ if (!this.isDrained()) void this.pump();
4659
+ const drained = this.isDrained() ? Promise.resolve(true) : new Promise((resolve4) => this.idleWaiters.push(() => resolve4(true)));
4660
+ const done = await Promise.race([drained, sleep(timeoutMs).then(() => false)]);
4661
+ await this.persistChain;
4662
+ return done || this.isDrained();
4663
+ }
4664
+ /** Stops posting (the runner is stopping); what is unsent stays on disk. */
4665
+ async stop() {
4666
+ this.stopped = true;
4667
+ if (this.persistRetry) clearTimeout(this.persistRetry);
4668
+ this.persistRetry = null;
4669
+ this.stopController.abort();
4670
+ if (this.pumpTimer) clearTimeout(this.pumpTimer);
4671
+ this.pumpTimer = null;
4672
+ this.persist(true);
4673
+ await this.persistChain;
4674
+ }
4675
+ /** Nothing more is posted (the server does not know the job); saved as finished. */
4676
+ async discard() {
4677
+ if (this.discarded) return;
4678
+ this.pending = [];
4679
+ this.status = null;
4680
+ this.finished = true;
4681
+ this.persist();
4682
+ this.discarded = true;
4683
+ if (this.persistRetry) clearTimeout(this.persistRetry);
4684
+ this.persistRetry = null;
4685
+ this.stopController.abort();
4686
+ if (this.pumpTimer) clearTimeout(this.pumpTimer);
4687
+ this.pumpTimer = null;
4688
+ this.notifyIdle();
4689
+ await this.persistChain;
4690
+ }
4691
+ /** Resolves once no write is under way. */
4692
+ settled() {
4693
+ return this.persistChain;
4694
+ }
4695
+ isDrained() {
4696
+ return this.discarded || this.pending.length === 0 && !this.status;
4697
+ }
4698
+ /** `final`: the stop's own last write; after it, nothing more is written. */
4699
+ persist(final = false) {
4700
+ if (this.persistQueued || this.discarded) return;
4701
+ if (this.stopped && !final) return;
4702
+ this.persistQueued = true;
4703
+ this.persistChain = this.persistChain.then(async () => {
4704
+ this.persistQueued = false;
4705
+ const snapshot = {
4706
+ nextSeq: this.nextSeq,
4707
+ pending: [...this.pending],
4708
+ status: this.status,
4709
+ cursor: this.tail,
4710
+ finished: this.finished
4711
+ };
4712
+ try {
4713
+ await writeJsonAtomic(this.opts.file, snapshot);
4714
+ this.durableSeq = snapshot.nextSeq - 1;
4715
+ this.durableStatus = snapshot.status;
4716
+ this.persistFailures = 0;
4717
+ } catch (err) {
4718
+ this.persistFailures++;
4719
+ if (this.persistFailures === 1 || this.persistFailures % 10 === 0) {
4720
+ this.opts.logger.warn("could not save a job\u2019s log outbox; trying again", {
4721
+ job: this.opts.jobId,
4722
+ error: err.message,
4723
+ attempt: this.persistFailures
4724
+ });
4725
+ }
4726
+ if (!this.persistRetry && !this.discarded && !this.stopped) {
4727
+ this.persistRetry = setTimeout(
4728
+ () => {
4729
+ this.persistRetry = null;
4730
+ if (!this.stopped) this.persist();
4731
+ },
4732
+ backoffDelay(this.persistFailures - 1, this.opts.retryBaseMs ?? 1e3, 6e4)
4733
+ );
4734
+ this.persistRetry.unref?.();
4735
+ }
4736
+ }
4737
+ if (!this.pumping) this.schedulePump();
4738
+ });
4739
+ }
4740
+ schedulePump() {
4741
+ if (this.pumping || this.pumpTimer || this.stopped || this.discarded) return;
4742
+ if (!this.pending.length && !this.status) return;
4743
+ this.pumpTimer = setTimeout(() => {
4744
+ this.pumpTimer = null;
4745
+ void this.pump();
4746
+ }, this.opts.batchDelayMs ?? 500);
4747
+ this.pumpTimer.unref?.();
4748
+ }
4749
+ /** The next post: durable lines (by count and size), and the status once it may go. */
4750
+ nextBatch() {
4751
+ const durable = this.pending.filter((l) => l.seq <= this.durableSeq);
4752
+ const budget = RUNNER_EVENTS_MAX_BODY_BYTES / 2;
4753
+ let bytes = 0;
4754
+ let n = 0;
4755
+ while (n < durable.length && n < RUNNER_JOB_LOG_MAX_BATCH) {
4756
+ const size = Buffer.byteLength(JSON.stringify(durable[n])) + 1;
4757
+ if (n > 0 && bytes + size > budget) break;
4758
+ bytes += size;
4759
+ n++;
4760
+ }
4761
+ const lines = durable.slice(0, n);
4762
+ const status2 = this.status && this.durableStatus === this.status ? this.status : null;
4763
+ const sentUpTo = lines.at(-1)?.seq ?? 0;
4764
+ const before = this.pending.filter((l) => status2 && l.seq < status2.afterSeq);
4765
+ const ready = status2 && (before.length === 0 || before.at(-1).seq <= sentUpTo);
4766
+ return { lines, status: ready ? status2 : null };
4767
+ }
4768
+ async pump() {
4769
+ if (this.pumping) return;
4770
+ this.pumping = true;
4771
+ let attempt = 0;
4772
+ let rejected = 0;
4773
+ try {
4774
+ while (!this.stopped && !this.discarded) {
4775
+ const { lines, status: status2 } = this.nextBatch();
4776
+ if (!lines.length && !status2) break;
4777
+ const maxSeq = lines.at(-1)?.seq ?? 0;
4778
+ const body = {
4779
+ ...status2 ? { status: status2.report } : {},
4780
+ ...lines.length ? {
4781
+ lines: lines.map(({ seq, stream, text, at }) => ({ seq, stream, text, at }))
4782
+ } : {}
4783
+ };
4784
+ try {
4785
+ const res = await this.opts.poster.postJobEvents(this.opts.jobId, body);
4786
+ if (this.stopped || this.discarded) break;
4787
+ const lastSeq = typeof res?.lastSeq === "number" ? Math.max(res.lastSeq, maxSeq) : maxSeq;
4788
+ this.pending = this.pending.filter((l) => l.seq > lastSeq);
4789
+ if (status2 && this.status === status2) this.status = null;
4790
+ this.persist();
4791
+ attempt = 0;
4792
+ rejected = 0;
4793
+ if (res?.stop) this.opts.onStop?.();
4794
+ } catch (err) {
4795
+ if (err instanceof UnauthorizedError) {
4796
+ this.stopped = true;
4797
+ this.opts.onUnauthorized?.(err);
4798
+ break;
4799
+ }
4800
+ if (err instanceof ApiError && (err.status === 404 || err.status === 410)) {
4801
+ this.opts.logger.warn(
4802
+ `job ${this.opts.jobId}: Discovery Tree does not know this job (${err.status}); no longer reporting on it`
4803
+ );
4804
+ await this.discard();
4805
+ this.opts.onGone?.();
4806
+ break;
4807
+ }
4808
+ const tooLarge = err instanceof ApiError && err.status === 413;
4809
+ if (tooLarge || !isRetryable(err)) {
4810
+ rejected++;
4811
+ this.opts.logger.warn("the server refused a job\u2019s log lines", {
4812
+ job: this.opts.jobId,
4813
+ error: err.message,
4814
+ attempt: rejected
4815
+ });
4816
+ if (tooLarge || rejected >= MAX_REJECTED_ATTEMPTS) {
4817
+ this.pending = this.pending.filter((l) => l.seq > maxSeq);
4818
+ if (status2 && this.status === status2) this.status = null;
4819
+ this.persist();
4820
+ rejected = 0;
4821
+ continue;
4822
+ }
4823
+ } else {
4824
+ this.opts.logger.debug("posting a job\u2019s log lines failed; will retry", {
4825
+ job: this.opts.jobId,
4826
+ error: err.message
4827
+ });
4828
+ }
4829
+ await sleep(
4830
+ backoffDelay(attempt++, this.opts.retryBaseMs ?? 1e3, 6e4),
4831
+ this.stopController.signal
4832
+ );
4833
+ }
4834
+ }
4835
+ } finally {
4836
+ this.pumping = false;
4837
+ }
4838
+ if (this.isDrained()) {
4839
+ this.notifyIdle();
4840
+ this.checkFinished();
4841
+ } else if (!this.stopped && !this.discarded) {
4842
+ this.schedulePump();
4843
+ }
4844
+ }
4845
+ checkFinished() {
4846
+ if (!this.isFinished || this.discarded || this.finishNotified) return;
4847
+ this.finishNotified = true;
4848
+ this.opts.onFinished?.();
4849
+ }
4850
+ notifyIdle() {
4851
+ const waiters = this.idleWaiters;
4852
+ this.idleWaiters = [];
4853
+ for (const w of waiters) w();
4854
+ }
4855
+ };
4856
+
4857
+ // src/jobs/job-process.ts
4858
+ import { execFile, spawn as spawn4 } from "node:child_process";
4859
+ import { closeSync, openSync, readFileSync, readdirSync } from "node:fs";
4860
+ import { readFile as readFile7, writeFile as writeFile4 } from "node:fs/promises";
4861
+ import { dirname as dirname6, join as join9 } from "node:path";
4862
+
4863
+ // src/lock.ts
4864
+ import { mkdir as mkdir5, open as open2, readFile as readFile6, rm as rm5 } from "node:fs/promises";
4865
+ import { join as join8 } from "node:path";
4866
+ function lockFile(stateDir) {
4867
+ return join8(stateDir, "daemon.pid");
4868
+ }
4869
+ function pidAlive(pid) {
4870
+ if (!Number.isInteger(pid) || pid <= 0) return false;
4871
+ try {
4872
+ process.kill(pid, 0);
4873
+ return true;
4874
+ } catch (err) {
4875
+ return err.code === "EPERM";
4876
+ }
4877
+ }
4878
+ async function lockHolder(stateDir) {
4879
+ let raw;
4880
+ try {
4881
+ raw = await readFile6(lockFile(stateDir), "utf8");
4882
+ } catch {
4883
+ return null;
4884
+ }
4885
+ const pid = Number.parseInt(raw.trim(), 10);
4886
+ return pidAlive(pid) && pid !== process.pid ? pid : null;
4887
+ }
4888
+ async function acquireDaemonLock(stateDir, pid = process.pid) {
4889
+ await mkdir5(stateDir, { recursive: true, mode: 448 });
4890
+ const file = lockFile(stateDir);
4891
+ for (let attempt = 0; attempt < 3; attempt++) {
4892
+ try {
4893
+ const handle = await open2(file, "wx", 384);
4894
+ try {
4895
+ await handle.writeFile(`${pid}
4896
+ `);
4897
+ } finally {
4898
+ await handle.close();
4899
+ }
4900
+ return {
4901
+ ok: true,
4902
+ lock: {
4903
+ file,
4904
+ async release() {
4905
+ const current2 = await readFile6(file, "utf8").catch(() => "");
4906
+ if (Number.parseInt(current2.trim(), 10) === pid) await rm5(file, { force: true });
4907
+ }
4908
+ }
4909
+ };
4910
+ } catch (err) {
4911
+ if (err.code !== "EEXIST") throw err;
4912
+ }
4913
+ const raw = await readFile6(file, "utf8").catch(() => null);
4914
+ if (raw === null) continue;
4915
+ const holder = Number.parseInt(raw.trim(), 10);
4916
+ if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
4917
+ await rm5(file, { force: true });
4918
+ }
4919
+ return { ok: false, pid: null };
4920
+ }
4921
+
4922
+ // src/jobs/job-process.ts
4923
+ var JOB_IS_WINDOWS = process.platform === "win32";
4924
+ var POWERSHELL_FLAGS = [
4925
+ "-NoLogo",
4926
+ "-NoProfile",
4927
+ "-NonInteractive",
4928
+ "-ExecutionPolicy",
4929
+ "Bypass",
4930
+ // Plain text on its redirected streams, never CLIXML records.
4931
+ "-OutputFormat",
4932
+ "Text"
4933
+ ];
4934
+ function encoded(script) {
4935
+ return Buffer.from(script, "utf16le").toString("base64");
4936
+ }
4937
+ function psQuote(s) {
4938
+ return `'${s.replace(/'/g, "''")}'`;
4939
+ }
4940
+ function posixLaunch(command, exitFile) {
4941
+ return {
4942
+ bin: "/bin/sh",
4943
+ args: [
4944
+ "-c",
4945
+ '/bin/sh -c "$1"; code=$?; printf %s "$code" > "$2.tmp" && mv -f "$2.tmp" "$2"; exit "$code"',
4946
+ "dt-job",
4947
+ command,
4948
+ exitFile
4949
+ ]
4950
+ };
4951
+ }
4952
+ function powershellCommandScript(command) {
4953
+ return [
4954
+ "$ErrorActionPreference = 'Continue'",
4955
+ // No progress records, which would land in the log as noise.
4956
+ "$ProgressPreference = 'SilentlyContinue'",
4957
+ // Its own output as UTF-8 (the runner reads the log as UTF-8), not the OEM code page.
4958
+ "try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false } catch {}",
4959
+ command,
4960
+ "$dtRunnerOk = $?",
4961
+ "$dtRunnerLast = $LASTEXITCODE",
4962
+ "if ($dtRunnerOk) { exit 0 } elseif ($dtRunnerLast) { exit $dtRunnerLast } else { exit 1 }"
4963
+ ].join("\n");
4964
+ }
4965
+ function powershellJobScript(commandFile, exitFile) {
4966
+ return [
4967
+ "$ErrorActionPreference = 'Continue'",
4968
+ "$ProgressPreference = 'SilentlyContinue'",
4969
+ "try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false } catch {}",
4970
+ `& powershell.exe ${POWERSHELL_FLAGS.join(" ")} -File ${psQuote(commandFile)}`,
4971
+ "$dtRunnerCode = $LASTEXITCODE",
4972
+ "if ($null -eq $dtRunnerCode) { $dtRunnerCode = 1 }",
4973
+ `try { [IO.File]::WriteAllText(${psQuote(exitFile)}, [string]$dtRunnerCode) } catch {}`,
4974
+ "exit $dtRunnerCode"
4975
+ ].join("\n");
4976
+ }
4977
+ function psLiteralPath(path) {
4978
+ return `([WildcardPattern]::Escape(${psQuote(path)}))`;
4979
+ }
4980
+ function windowsLauncherScript(input) {
4981
+ const args = [...POWERSHELL_FLAGS, "-File", `"${input.scriptFile}"`].join(" ");
4982
+ return [
4983
+ "$ErrorActionPreference = 'Stop'",
4984
+ "$ProgressPreference = 'SilentlyContinue'",
4985
+ // Started here: Start-Process takes the current location as the job's directory.
4986
+ `Set-Location -LiteralPath ${psQuote(input.cwd)}`,
4987
+ `$p = Start-Process -FilePath 'powershell.exe' -ArgumentList ${psQuote(args)} -NoNewWindow -PassThru -RedirectStandardOutput ${psLiteralPath(input.stdoutFile)} -RedirectStandardError ${psLiteralPath(input.stderrFile)}`,
4988
+ // A command that is over already has no start time to read: now is close enough.
4989
+ "$dtRunnerAt = $null",
4990
+ "try { $dtRunnerAt = ([DateTimeOffset]$p.StartTime).ToUnixTimeMilliseconds() } catch { $dtRunnerAt = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() }",
4991
+ '[Console]::Out.WriteLine("pid " + $p.Id + " " + $dtRunnerAt)'
4992
+ ].join("\n");
4993
+ }
4994
+ async function spawnJob(input) {
4995
+ if (JOB_IS_WINDOWS) return spawnWindowsJob(input);
4996
+ const { bin, args } = posixLaunch(input.command, input.exitFile);
4997
+ const out = openSync(input.stdoutFile, "a", 384);
4998
+ let err = null;
4999
+ let child;
5000
+ try {
5001
+ err = openSync(input.stderrFile, "a", 384);
5002
+ child = spawn4(bin, args, {
5003
+ cwd: input.cwd,
5004
+ env: input.env,
5005
+ stdio: ["ignore", out, err],
5006
+ detached: true
5007
+ });
5008
+ } finally {
5009
+ closeSync(out);
5010
+ if (err !== null) closeSync(err);
5011
+ }
5012
+ child.unref();
5013
+ const exited = new Promise(
5014
+ (done) => child.once("exit", (code, signal) => done({ code, signal }))
5015
+ );
5016
+ await new Promise((up, failed) => {
5017
+ child.once("spawn", up);
5018
+ child.once("error", failed);
5019
+ });
5020
+ return { pid: child.pid, startedAt: Date.now() - 500, child, exited };
5021
+ }
5022
+ async function spawnWindowsJob(input) {
5023
+ const dir = dirname6(input.exitFile);
5024
+ const scriptFile = join9(dir, "job.ps1");
5025
+ const commandFile = join9(dir, "command.ps1");
5026
+ const bom = "\uFEFF";
5027
+ await writeFile4(commandFile, bom + powershellCommandScript(input.command), { mode: 384 });
5028
+ for (const f of [input.stdoutFile, input.stderrFile]) await writeFile4(f, "", { flag: "a" });
5029
+ await writeFile4(scriptFile, bom + powershellJobScript(commandFile, input.exitFile), {
5030
+ mode: 384
5031
+ });
5032
+ const launcher = spawn4(
5033
+ "powershell.exe",
5034
+ [
5035
+ ...POWERSHELL_FLAGS,
5036
+ "-EncodedCommand",
5037
+ encoded(windowsLauncherScript({ ...input, scriptFile }))
5038
+ ],
5039
+ // Piped (nothing inherited), so Node gives it a console without a window.
5040
+ { cwd: input.cwd, env: input.env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
5041
+ );
5042
+ let out = "";
5043
+ let err = "";
5044
+ try {
5045
+ const started = await new Promise((done, failed) => {
5046
+ let settled = false;
5047
+ const timers = [];
5048
+ const settle = (fn) => {
5049
+ if (settled) return;
5050
+ settled = true;
5051
+ for (const t of timers) clearTimeout(t);
5052
+ fn();
5053
+ };
5054
+ const look = () => {
5055
+ const m = /pid (\d+) (-?\d+)\r?\n/.exec(out);
5056
+ if (m) settle(() => done({ pid: Number(m[1]), startedAt: Number(m[2]) }));
5057
+ };
5058
+ launcher.stdout.setEncoding("utf8").on("data", (d) => {
5059
+ out += d;
5060
+ look();
5061
+ });
5062
+ launcher.stderr.setEncoding("utf8").on("data", (d) => err += d);
5063
+ launcher.once("error", (e) => settle(() => failed(e)));
5064
+ launcher.once("exit", (code) => {
5065
+ if (settled) return;
5066
+ timers.push(
5067
+ setTimeout(() => {
5068
+ look();
5069
+ const why = err.replace(/\s+/g, " ").trim().slice(0, 400) || `exit code ${code}`;
5070
+ settle(() => failed(new Error(`PowerShell could not start it: ${why}`)));
5071
+ }, 2e3)
5072
+ );
5073
+ });
5074
+ timers.push(
5075
+ setTimeout(() => {
5076
+ if (launcher.pid) void taskkill(launcher.pid, true);
5077
+ const up = /pid (\d+) /.exec(out);
5078
+ if (up) void taskkill(Number(up[1]), true);
5079
+ settle(() => failed(new Error("PowerShell did not start the job within 60 seconds.")));
5080
+ }, 6e4)
5081
+ );
5082
+ });
5083
+ return { ...started, child: null, exited: null };
5084
+ } finally {
5085
+ launcher.stdout.destroy();
5086
+ launcher.stderr.destroy();
5087
+ launcher.unref();
5088
+ }
5089
+ }
5090
+ async function processStamp(pid) {
5091
+ if (JOB_IS_WINDOWS) return null;
5092
+ try {
5093
+ const stat5 = await readFile7(`/proc/${pid}/stat`, "utf8");
5094
+ const fields = stat5.slice(stat5.lastIndexOf(")") + 2).split(" ");
5095
+ if (fields[19]) return `ticks:${fields[19]}`;
5096
+ } catch {
5097
+ }
5098
+ return new Promise((resolve4) => {
5099
+ const env = { ...process.env, LC_ALL: "C", LANG: "C", TZ: "UTC" };
5100
+ execFile("ps", ["-o", "lstart=", "-p", String(pid)], { timeout: 5e3, env }, (e, stdout) => {
5101
+ const text = e ? "" : String(stdout).trim();
5102
+ resolve4(text ? `lstartutc:${text}` : null);
5103
+ });
5104
+ });
5105
+ }
5106
+ async function isJobProcess(pid, startedAt, rows, stamp) {
5107
+ if (!pidAlive(pid)) return false;
5108
+ if (JOB_IS_WINDOWS) {
5109
+ const table = rows ?? await listWindowsProcesses().catch(() => null);
5110
+ if (!table) return true;
5111
+ const row = table.find((r) => r.pid === pid);
5112
+ return !!row && Math.abs(row.createdAt - startedAt) <= START_TOLERANCE_MS;
5113
+ }
5114
+ if (await isZombie(pid)) return false;
5115
+ if (!groupAlive(pid)) return false;
5116
+ if (stamp && (stamp.startsWith("ticks:") || stamp.startsWith("lstartutc:"))) {
5117
+ const now = await processStamp(pid);
5118
+ if (now) return now === stamp;
5119
+ }
5120
+ const started = await posixStartTime(pid);
5121
+ return started === null || Math.abs(started - startedAt) <= START_TOLERANCE_MS;
5122
+ }
5123
+ var START_TOLERANCE_MS = 5e3;
5124
+ function posixStartTime(pid) {
5125
+ return new Promise((resolve4) => {
5126
+ execFile("ps", ["-o", "etime=", "-p", String(pid)], { timeout: 5e3 }, (err, stdout) => {
5127
+ const secs = err ? null : parseElapsed(String(stdout));
5128
+ resolve4(secs === null ? null : Date.now() - secs * 1e3);
5129
+ });
5130
+ });
5131
+ }
5132
+ function parseElapsed(text) {
5133
+ const m = /^\s*(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)\s*$/.exec(text);
5134
+ if (!m) return null;
5135
+ const [, d, h, min, s] = m;
5136
+ return ((Number(d ?? 0) * 24 + Number(h ?? 0)) * 60 + Number(min)) * 60 + Number(s);
5137
+ }
5138
+ function procStat(pid) {
5139
+ try {
5140
+ const stat5 = readFileSync(`/proc/${pid}/stat`, "utf8");
5141
+ return stat5.slice(stat5.lastIndexOf(")") + 2).split(" ");
5142
+ } catch {
5143
+ return null;
5144
+ }
5145
+ }
5146
+ async function isZombie(pid) {
5147
+ if (JOB_IS_WINDOWS) return false;
5148
+ const fields = procStat(pid);
5149
+ if (fields) return fields[0] === "Z";
5150
+ if (process.platform === "linux") return false;
5151
+ return new Promise((resolve4) => {
5152
+ execFile(
5153
+ "ps",
5154
+ ["-o", "stat=", "-p", String(pid)],
5155
+ { timeout: 5e3 },
5156
+ (e, out) => resolve4(!e && String(out).trim().startsWith("Z"))
5157
+ );
5158
+ });
5159
+ }
5160
+ function processRunning(pid) {
5161
+ if (!pidAlive(pid)) return false;
5162
+ return procStat(pid)?.[0] !== "Z";
5163
+ }
5164
+ function groupHasLiveMember(pgid) {
5165
+ if (!groupAlive(pgid)) return false;
5166
+ if (process.platform !== "linux") return true;
5167
+ let entries;
5168
+ try {
5169
+ entries = readdirSync("/proc");
5170
+ } catch {
5171
+ return true;
5172
+ }
5173
+ for (const entry of entries) {
5174
+ if (!/^\d+$/.test(entry)) continue;
5175
+ const fields = procStat(Number(entry));
5176
+ if (fields && fields[2] === String(pgid) && fields[0] !== "Z") return true;
5177
+ }
5178
+ return false;
5179
+ }
5180
+ function groupAlive(pgid) {
5181
+ return signalGroup2(pgid, 0);
5182
+ }
5183
+ function signalGroup2(pgid, signal) {
5184
+ if (!Number.isInteger(pgid) || pgid <= 1) return false;
5185
+ try {
5186
+ process.kill(-pgid, signal);
5187
+ return true;
5188
+ } catch {
5189
+ return false;
5190
+ }
5191
+ }
5192
+ function taskkill(pid, force) {
5193
+ return new Promise((resolve4) => {
5194
+ const tk = spawn4("taskkill", ["/pid", String(pid), "/T", ...force ? ["/F"] : []], {
5195
+ stdio: "ignore",
5196
+ windowsHide: true
5197
+ });
5198
+ tk.on("error", () => resolve4());
5199
+ tk.on("close", () => resolve4());
5200
+ });
5201
+ }
5202
+ async function censusJobs(trees) {
5203
+ if (!JOB_IS_WINDOWS || trees.length === 0) return;
5204
+ try {
5205
+ const rows = await listWindowsProcesses();
5206
+ for (const tree of trees) recordDescendants(tree, rows);
5207
+ } catch {
5208
+ }
5209
+ }
5210
+ async function askJobToStop(tree) {
5211
+ if (!JOB_IS_WINDOWS) {
5212
+ signalGroup2(tree.pid, "SIGTERM");
5213
+ return;
5214
+ }
5215
+ await censusJobs([tree]);
5216
+ await taskkill(tree.pid, false);
5217
+ }
5218
+ async function killJobTree(tree, rootRunning) {
5219
+ try {
5220
+ if (!JOB_IS_WINDOWS) {
5221
+ signalGroup2(tree.pid, "SIGKILL");
5222
+ return;
5223
+ }
5224
+ const rows = await listWindowsProcesses().catch(() => null);
5225
+ const pids = [...rootRunning ? [tree.pid] : [], ...rows ? descendantsOf(tree, rows) : []];
5226
+ if (pids.length) await killWindowsTrees(pids);
5227
+ } catch {
5228
+ }
5229
+ }
5230
+
5231
+ // src/jobs/job-manager.ts
5232
+ var JOB_STOP_GRACE_MS = 1e4;
5233
+ var LEFTOVER_GRACE_MS = 2e3;
5234
+ var CENSUS_INTERVAL_MS2 = 3e4;
5235
+ var JOB_SECRETS_WAIT_MS = 9e4;
5236
+ var JOB_SECRETS_END_WAIT_MS = 12e4;
5237
+ var JOB_LOST_POSTING_MS = RUNNER_JOB_MISSING_GRACE_MS + 3e4;
5238
+ function secretWait() {
5239
+ let end = () => void 0;
5240
+ const over = new Promise((resolve4) => end = resolve4);
5241
+ return { since: Date.now(), over, end };
5242
+ }
5243
+ var JobManager = class {
5244
+ constructor(opts) {
5245
+ this.opts = opts;
5246
+ this.root = join10(opts.stateDir, "jobs");
5247
+ }
5248
+ jobs = /* @__PURE__ */ new Map();
5249
+ /** Folders being removed now, with how many removals hold each (see `holdForRemoval`). */
5250
+ removing = /* @__PURE__ */ new Map();
5251
+ /** Ends being handled (`finish`), which a shutdown waits for. */
5252
+ finishing = /* @__PURE__ */ new Set();
5253
+ /** Starts under way, with their directories: a slot each, from the capacity check on. */
5254
+ starting = /* @__PURE__ */ new Map();
5255
+ /** The tail of each job's command queue; never rejects. */
5256
+ queues = /* @__PURE__ */ new Map();
5257
+ timer = null;
5258
+ censusTimer = null;
5259
+ ticking = false;
5260
+ shuttingDown = false;
5261
+ /** Resolves when the runner begins to stop: an end waiting for secrets waits no more. */
5262
+ stopped = secretWait();
5263
+ root;
5264
+ /** The folder a job's record, log and outbox live in. */
5265
+ jobDir(jobId) {
5266
+ return join10(this.root, jobId);
5267
+ }
5268
+ /**
5269
+ * Jobs the runner reports in `activeJobIds`: a live process, or an end not yet reported.
5270
+ * Not a start still under way: the server takes a listed job as up, settling its
5271
+ * `start_job` as acknowledged, so a start that then fails would show as running (then lost)
5272
+ * and its refusal, with the reason, would be dropped. Left out, it loses nothing: the
5273
+ * server marks only a `running` job lost for being missing, and a start is `starting` until
5274
+ * its ack says how it went.
5275
+ */
5276
+ activeJobIds() {
5277
+ const ids = /* @__PURE__ */ new Set();
5278
+ for (const [id, job] of this.jobs) {
5279
+ if (job.phase !== "ended") ids.add(id);
5280
+ else if ((job.record.ended?.status !== "lost" || job.awaiting || job.closing || this.postingLost(job)) && !job.outbox.isFinished) {
5281
+ ids.add(id);
5282
+ }
5283
+ }
5284
+ return [...ids];
5285
+ }
5286
+ /**
5287
+ * Jobs taken up again whose output is held for want of their secrets, which a `job_secrets`
5288
+ * can bring back (the heartbeat's `jobsNeedingSecrets`). Not one whose secrets cannot be
5289
+ * checked (`unverifiable`), or that changed since its start. One that ended is listed while
5290
+ * its last output waits for them.
5291
+ */
5292
+ jobsNeedingSecrets() {
5293
+ return [...this.jobs.entries()].filter(([, job]) => job.awaiting).map(([id]) => id);
5294
+ }
5295
+ /**
5296
+ * A lost job still has lines to post, for {@link JOB_LOST_POSTING_MS} after this process
5297
+ * queued its end (or took it up with its end queued): not for good, as an outbox that
5298
+ * cannot post, or cannot save, would keep a job with no process running on the server.
5299
+ */
5300
+ postingLost(job) {
5301
+ return job.outbox.size > 0 && job.lastQueuedAt !== void 0 && performance.now() - job.lastQueuedAt < (this.opts.lostPostingMs ?? JOB_LOST_POSTING_MS);
5302
+ }
5303
+ /** Jobs with a process (or one starting), counted against `maxJobs`. */
5304
+ liveCount() {
5305
+ let n = this.starting.size;
5306
+ for (const job of this.jobs.values()) if (job.phase !== "ended") n++;
5307
+ return n;
5308
+ }
5309
+ /** For status and tests. */
5310
+ get(jobId) {
5311
+ return this.jobs.get(jobId.toLowerCase())?.record;
5312
+ }
5313
+ /** The pid of a job's process, while it has one. */
5314
+ pidOf(jobId) {
5315
+ const job = this.jobs.get(jobId.toLowerCase());
5316
+ return job && job.phase !== "ended" ? job.record.pid : null;
5317
+ }
5318
+ /**
5319
+ * Whether a running (or starting) job works in `dir` or a folder inside it: a session's
5320
+ * worktree such a job runs in must not be removed under it.
5321
+ */
5322
+ usesPath(dir) {
5323
+ if (!dir) return false;
5324
+ const cwds = [...this.starting.values()];
5325
+ for (const job of this.jobs.values()) if (job.phase !== "ended") cwds.push(job.record.cwd);
5326
+ return cwds.some((cwd) => isInside(cwd, dir));
5327
+ }
5328
+ /**
5329
+ * Claims `dir` for removal, unless a job runs (or is starting) in it: null then, and it must
5330
+ * be kept. While claimed, a start in it is refused as `retryable`. Checked and claimed in one
5331
+ * step (no await), as a start checks and takes its slot, so a job never starts in a folder
5332
+ * being removed, nor is a folder removed under a job that has just started. Call the
5333
+ * returned function once the removal is over.
5334
+ */
5335
+ holdForRemoval(dir) {
5336
+ if (!dir || this.usesPath(dir)) return null;
5337
+ const key = resolve2(dir);
5338
+ this.removing.set(key, (this.removing.get(key) ?? 0) + 1);
5339
+ let released = false;
5340
+ return () => {
5341
+ if (released) return;
5342
+ released = true;
5343
+ const left = (this.removing.get(key) ?? 1) - 1;
5344
+ if (left > 0) this.removing.set(key, left);
5345
+ else this.removing.delete(key);
5346
+ };
5347
+ }
5348
+ /**
5349
+ * Takes up the jobs a previous run of the runner left: those still running are watched
5350
+ * again, the others reported as they ended. Starts reading output.
5351
+ */
5352
+ async restore() {
5353
+ let entries = [];
5354
+ try {
5355
+ entries = await readdir2(this.root);
5356
+ } catch (err) {
5357
+ if (err.code !== "ENOENT") throw err;
5358
+ }
5359
+ let table = null;
5360
+ for (const entry of entries) {
5361
+ if (!isRunnerSessionId(entry)) continue;
5362
+ const record = await readJson(join10(this.jobDir(entry), "job.json")).catch(
5363
+ () => null
5364
+ );
5365
+ if (!record || record.jobId !== entry || record.settled) continue;
5366
+ if (JOB_IS_WINDOWS && table === null && !record.ended && record.pid) {
5367
+ table = await listWindowsProcesses().catch(() => null);
5368
+ }
5369
+ try {
5370
+ await this.restoreJob(record, table);
5371
+ } catch (err) {
5372
+ this.opts.logger.warn(`job ${entry}: could not be taken up again`, {
5373
+ error: err.message
5374
+ });
5375
+ }
5376
+ }
5377
+ this.ensureTimers();
5378
+ }
5379
+ async restoreJob(record, table) {
5380
+ const job = await this.openJob(record, null, null);
5381
+ if (record.ended) {
5382
+ job.phase = "ended";
5383
+ this.jobs.set(record.jobId, job);
5384
+ if (job.outbox.hasFinalReport) {
5385
+ job.lastQueuedAt = performance.now();
5386
+ if (job.awaiting) await this.giveUpSecrets(job, null);
5387
+ if (job.outbox.isFinished) await this.settle(job);
5388
+ return;
5389
+ }
5390
+ const ended = record.ended;
5391
+ const close = async () => {
5392
+ job.closing = true;
5393
+ try {
5394
+ await closeEnd();
5395
+ } finally {
5396
+ job.closing = false;
5397
+ }
5398
+ };
5399
+ const closeEnd = async () => {
5400
+ if (job.awaiting) {
5401
+ await this.waitForSecrets(job);
5402
+ if (this.shuttingDown || this.jobs.get(job.record.jobId) !== job) return;
5403
+ if (job.awaiting) await this.giveUpSecrets(job, "gave_up");
5404
+ }
5405
+ await this.read(job, true);
5406
+ for (const r of job.readers) await r.close();
5407
+ queueEndReport(job.outbox, ended);
5408
+ job.lastQueuedAt = performance.now();
5409
+ if (job.outbox.isFinished) await this.settle(job);
5410
+ };
5411
+ if (!job.awaiting) return close();
5412
+ this.track(close(), record.jobId);
5413
+ return;
5414
+ }
5415
+ const alive = record.pid !== null && record.startedAt !== null && await isJobProcess(record.pid, record.startedAt, table, record.processStamp);
5416
+ this.jobs.set(record.jobId, job);
5417
+ if (job.withhold && (record.withheldNotice === "changed" || record.withheldNotice === "gave_up")) {
5418
+ this.opts.logger.warn(
5419
+ `job ${record.jobId}: its output stays withheld (${record.withheldNotice === "changed" ? "a secret changed since it started" : "its secrets were given up on"}); the whole log is in ${job.dir}`
5420
+ );
5421
+ } else if (job.withhold) {
5422
+ this.opts.logger.warn(
5423
+ `job ${record.jobId}: its output is no longer sent to Discovery Tree (the runner restarted, and the runner that started it kept nothing to check its secrets against); the whole log is in ${job.dir}`
5424
+ );
5425
+ await this.noticeWithheld(job, "unverifiable");
5426
+ } else if (job.awaiting) {
5427
+ this.opts.logger.info(
5428
+ `job ${record.jobId}: its output waits for its secrets to come back from Discovery Tree, to be redacted`
5429
+ );
5430
+ }
5431
+ if (!alive) {
5432
+ this.opts.logger.info(`job ${record.jobId}: ended while the runner was not running`);
5433
+ const ended = this.finish(job, await readExitFile(job.dir));
5434
+ if (!job.awaiting) await ended;
5435
+ else this.track(ended, record.jobId);
5436
+ return;
5437
+ }
5438
+ this.opts.logger.info(`job ${record.jobId}: taken up again (pid ${record.pid})`, {
5439
+ name: record.name
5440
+ });
5441
+ if (record.stopRequestedAt) {
5442
+ job.phase = "stopping";
5443
+ if (!record.stopSignalledAt && job.tree) {
5444
+ await askJobToStop(job.tree).catch(() => void 0);
5445
+ record.stopSignalledAt = (/* @__PURE__ */ new Date()).toISOString();
5446
+ await saveRecord(job.dir, record).catch(() => void 0);
5447
+ }
5448
+ const asked = Date.parse(record.stopRequestedAt);
5449
+ const left = (this.opts.stopGraceMs ?? JOB_STOP_GRACE_MS) - (Date.now() - asked);
5450
+ job.killTimer = setTimeout(() => void this.forceKill(job), Math.max(0, left || 0));
5451
+ job.killTimer.unref?.();
5452
+ }
5453
+ }
5454
+ /** One job command, after the earlier ones for the same job. */
5455
+ handle(cmd) {
5456
+ const id = typeof cmd.jobId === "string" ? cmd.jobId.toLowerCase() : "";
5457
+ if (!isRunnerSessionId(id)) {
5458
+ return Promise.resolve({ ok: false, error: "The job id is malformed." });
5459
+ }
5460
+ const work = async () => {
5461
+ switch (cmd.type) {
5462
+ case "start_job":
5463
+ return this.start(id, cmd);
5464
+ case "stop_job":
5465
+ return this.stopCommand(id);
5466
+ case "job_secrets":
5467
+ return this.applySecrets(id, cmd);
5468
+ default:
5469
+ return {
5470
+ ok: false,
5471
+ error: `This runner does not know the job command "${cmd.type}". Update dt-runner.`
5472
+ };
5473
+ }
5474
+ };
5475
+ const previous = this.queues.get(id) ?? Promise.resolve();
5476
+ const result = previous.then(work, work);
5477
+ const tail = result.then(
5478
+ () => void 0,
5479
+ () => void 0
5480
+ );
5481
+ this.queues.set(id, tail);
5482
+ void tail.then(() => {
5483
+ if (this.queues.get(id) === tail) this.queues.delete(id);
5484
+ });
5485
+ return result;
5486
+ }
5487
+ /** The heartbeat's `stopJobIds`: stop each of them this runner still runs. */
5488
+ stopJobs(ids) {
5489
+ for (const raw of ids) {
5490
+ const job = this.jobs.get(String(raw).toLowerCase());
5491
+ if (job && job.phase === "running") {
5492
+ this.opts.logger.info(`job ${job.record.jobId}: Discovery Tree says to stop it`);
5493
+ void this.stop(job);
5494
+ }
5495
+ }
5496
+ }
5497
+ /**
5498
+ * The runner is stopping: the jobs keep running (they are taken up again when it starts),
5499
+ * what they wrote is read and given `flushMs` to post, and the rest stays on disk.
5500
+ */
5501
+ async shutdown(flushMs = 5e3) {
5502
+ this.shuttingDown = true;
5503
+ this.stopped.end();
5504
+ if (this.timer) clearInterval(this.timer);
5505
+ if (this.censusTimer) clearInterval(this.censusTimer);
5506
+ this.timer = this.censusTimer = null;
5507
+ await Promise.allSettled([...this.queues.values()]);
5508
+ await Promise.allSettled([...this.finishing]);
5509
+ const jobs = [...this.jobs.values()];
5510
+ await Promise.allSettled(jobs.map((job) => this.read(job, false)));
5511
+ await Promise.allSettled(jobs.map((job) => job.outbox.flush(flushMs)));
5512
+ for (const job of jobs) {
5513
+ if (job.killTimer) clearTimeout(job.killTimer);
5514
+ job.killTimer = null;
5515
+ await job.outbox.stop();
5516
+ for (const r of job.readers) await r.close();
5517
+ }
5518
+ const running = jobs.filter((j) => j.phase === "running" || j.phase === "stopping").length;
5519
+ if (running) {
5520
+ this.opts.logger.info(
5521
+ `${running} job(s) keep running; dt-runner takes them up again when it starts`
5522
+ );
5523
+ }
5524
+ }
5525
+ /* -------------------------------------------------------------------------------- */
5526
+ async start(id, cmd) {
5527
+ if (this.jobs.has(id)) return { ok: true };
5528
+ const earlier = await readJson(join10(this.jobDir(id), "job.json")).catch(() => null);
5529
+ if (earlier) {
5530
+ return earlier.pid === null || earlier.ended?.status === "failed" ? { ok: false, error: "The job could not be started on this runner." } : { ok: true };
5531
+ }
5532
+ if (this.shuttingDown) {
5533
+ return { ok: false, retryable: true, error: "The runner is shutting down." };
5534
+ }
5535
+ const command = typeof cmd.command === "string" ? cmd.command : "";
5536
+ if (!command.trim() || command.includes("\0")) {
5537
+ return { ok: false, error: "The job has no command to run." };
5538
+ }
5539
+ const cwd = typeof cmd.cwd === "string" ? cmd.cwd : "";
5540
+ const cwdProblem = treeJobCwdProblem(cwd) ?? (isAbsolute4(cwd) ? null : "must be an absolute path");
5541
+ if (cwdProblem) return { ok: false, error: `The job's directory ${cwdProblem}.` };
5542
+ const isDir2 = await stat4(cwd).then(
5543
+ (s) => s.isDirectory(),
5544
+ () => false
5545
+ );
5546
+ if (!isDir2) {
5547
+ return { ok: false, error: `The directory ${cwd} does not exist on this computer.` };
5548
+ }
5549
+ if ([...this.removing.keys()].some((dir) => isInside(cwd, dir))) {
5550
+ return {
5551
+ ok: false,
5552
+ retryable: true,
5553
+ error: `The runner is removing or replacing the directory ${cwd} (a session's working copy) right now.`
5554
+ };
5555
+ }
5556
+ const max = this.opts.maxJobs;
5557
+ if (this.liveCount() >= max) {
5558
+ return {
5559
+ ok: false,
5560
+ retryable: true,
5561
+ error: `The runner is busy: it is already running ${max} job(s).`
5562
+ };
5563
+ }
5564
+ this.starting.set(id, cwd);
5565
+ try {
5566
+ await this.opts.beforeLaunch?.(id);
5567
+ return await this.launch(id, cmd, command, cwd);
5568
+ } finally {
5569
+ this.starting.delete(id);
5570
+ }
5571
+ }
5572
+ async launch(id, cmd, command, cwd) {
5573
+ const name = typeof cmd.name === "string" && cmd.name.trim() ? cmd.name.slice(0, 100) : id;
5574
+ const environment = sessionEnvironment(cmd.environment);
5575
+ const redactor = environment ? jobLineRedactor(environment) : null;
5576
+ const dir = this.jobDir(id);
5577
+ await mkdir6(dir, { recursive: true, mode: 448 });
5578
+ const record = {
5579
+ jobId: id,
5580
+ name,
5581
+ command,
5582
+ cwd,
5583
+ pid: null,
5584
+ startedAt: null,
5585
+ ...environment?.names.length ? { environmentNames: environment.names } : {},
5586
+ ...environment?.secretNames.length ? { secretNames: environment.secretNames } : {},
5587
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
5588
+ };
5589
+ if (environment?.secretNames.length) {
5590
+ try {
5591
+ record.secretCheck = await secretCheckOf(environment);
5592
+ } catch (err) {
5593
+ this.opts.logger.warn(
5594
+ `job ${id}: could not fingerprint its secrets; its output is not posted after a restart`,
5595
+ { error: safeError(err, redactor) }
5596
+ );
5597
+ }
5598
+ }
5599
+ await saveRecord(dir, record);
5600
+ this.opts.logger.info(`job ${id}: starting "${name}"`, { cwd });
5601
+ const shortLines = environment ? secretsWithShortLines(environment) : [];
5602
+ if (environment?.unredacted.length || shortLines.length) {
5603
+ this.opts.logger.warn(
5604
+ `job ${id}: ${[...environment?.unredacted ?? [], ...shortLines].join(", ")} cannot be fully redacted from its log (values or lines under ${SECRET_REDACTION_MIN_LENGTH} characters)`
5605
+ );
5606
+ }
5607
+ if (environment?.skipped.length) {
5608
+ this.opts.logger.warn(
5609
+ `job ${id}: left out of the job's environment (not a name it may set): ${environment.skipped.slice(0, 20).join(", ")}`
5610
+ );
5611
+ }
5612
+ const env = { ...process.env, ...environment?.env };
5613
+ delete env.DT_RUNNER_TOKEN;
5614
+ let started;
5615
+ try {
5616
+ started = await spawnJob({
5617
+ command,
5618
+ cwd,
5619
+ env,
5620
+ stdoutFile: join10(dir, "stdout.log"),
5621
+ stderrFile: join10(dir, "stderr.log"),
5622
+ exitFile: join10(dir, "exit-code")
5623
+ });
5624
+ } catch (err) {
5625
+ const error = safeError(err, redactor);
5626
+ record.ended = {
5627
+ at: (/* @__PURE__ */ new Date()).toISOString(),
5628
+ status: "failed",
5629
+ exitCode: null,
5630
+ signal: null
5631
+ };
5632
+ record.settled = true;
5633
+ await saveRecord(dir, record).catch(() => void 0);
5634
+ this.opts.logger.error(`job ${id}: could not start`, { error });
5635
+ this.opts.onJobEnded?.(id);
5636
+ return { ok: false, error: `The job could not be started: ${error}` };
5637
+ }
5638
+ record.pid = started.pid;
5639
+ record.startedAt = started.startedAt;
5640
+ let job;
5641
+ try {
5642
+ record.processStamp = await processStamp(started.pid);
5643
+ await saveRecord(dir, record);
5644
+ job = await this.openJob(record, started.child, redactor);
5645
+ } catch (err) {
5646
+ await killJobTree({ pid: started.pid, startedAt: started.startedAt }, true);
5647
+ record.ended = {
5648
+ at: (/* @__PURE__ */ new Date()).toISOString(),
5649
+ status: "failed",
5650
+ exitCode: null,
5651
+ signal: null
5652
+ };
5653
+ record.settled = true;
5654
+ await saveRecord(dir, record).catch(() => void 0);
5655
+ const error = safeError(err, redactor);
5656
+ this.opts.logger.error(`job ${id}: could not be set up after it started; ended it`, {
5657
+ error
5658
+ });
5659
+ this.opts.onJobEnded?.(id);
5660
+ return { ok: false, error: `The job could not be started: ${error}` };
5661
+ }
5662
+ this.jobs.set(id, job);
5663
+ job.outbox.report({ status: "running" });
5664
+ void started.exited?.then((info) => this.finish(job, info));
5665
+ this.ensureTimers();
5666
+ this.opts.logger.info(`job ${id}: running (pid ${record.pid})`);
5667
+ return { ok: true };
5668
+ }
5669
+ /**
5670
+ * A job's secrets again, for one taken up after a restart: each checked against its
5671
+ * fingerprint from the start. All the same: the job's output is redacted with them and
5672
+ * posted from where the outbox got to. One changed or missing: it stays held back, one line
5673
+ * says why, and they are not asked for again.
5674
+ */
5675
+ async applySecrets(id, cmd) {
5676
+ const job = this.jobs.get(id);
5677
+ if (!job?.awaiting) return { ok: true };
5678
+ const check = job.record.secretCheck;
5679
+ const names = job.record.secretNames ?? [];
5680
+ const given = sessionEnvironment({ variables: {}, secrets: cmd.environment?.secrets ?? {} });
5681
+ const values = {};
5682
+ const changed = [];
5683
+ const matched = await inPairs(names, async (name) => {
5684
+ const value = given?.secretNames.includes(name) ? given.env[name] : void 0;
5685
+ return typeof value === "string" && !!check && await secretMatches(check, name, value) ? value : null;
5686
+ });
5687
+ names.forEach((name, i) => {
5688
+ const value = matched[i];
5689
+ if (value === null) changed.push(name);
5690
+ else values[name] = value;
5691
+ });
5692
+ if (!job.awaiting) return { ok: true };
5693
+ if (changed.length) {
5694
+ this.opts.logger.warn(
5695
+ `job ${id}: ${changed.join(", ")} ${changed.length === 1 ? "is" : "are"} not what the job started with; its output stays in ${job.dir}`
5696
+ );
5697
+ await this.giveUpSecrets(job, "changed", changed);
5698
+ return {
5699
+ ok: false,
5700
+ error: `Not the values the job started with (changed or removed since, or not readable by Discovery Tree): ${changed.join(", ")}. Its output stays on the runner.`
5701
+ };
5702
+ }
5703
+ const environment = sessionEnvironment({ variables: {}, secrets: values });
5704
+ job.redactor = environment ? jobLineRedactor(environment) : null;
5705
+ const wait = job.awaiting;
5706
+ job.awaiting = null;
5707
+ if (job.record.withheldNotice || job.record.withheldNoticeQueued) {
5708
+ job.outbox.add([noticeLine(RESUMED_NOTICE)], job.outbox.cursor);
5709
+ job.record.withheldNotice = null;
5710
+ job.record.withheldNoticeQueued = false;
5711
+ await saveRecord(job.dir, job.record).catch(() => void 0);
5712
+ }
5713
+ wait.end();
5714
+ this.opts.logger.info(`job ${id}: got its secrets back; posting its output, redacted`);
5715
+ return { ok: true };
5716
+ }
5717
+ /**
5718
+ * Its secrets will not come back (`kind` says why, or null for no line): its output is no
5719
+ * longer waited for but read past, unposted, the line saying so queued once.
5720
+ */
5721
+ async giveUpSecrets(job, kind, names = []) {
5722
+ const wait = job.awaiting;
5723
+ job.awaiting = null;
5724
+ job.withhold = true;
5725
+ if (kind) await this.noticeWithheld(job, kind, names);
5726
+ wait?.end();
5727
+ }
5728
+ /** Queues the line saying why the job's output is held back, unless it already went. */
5729
+ async noticeWithheld(job, kind, names = []) {
5730
+ const last = job.record.withheldNotice ?? (job.record.withheldNoticeQueued ? "unverifiable" : null);
5731
+ if (last === kind) return;
5732
+ job.outbox.add([noticeLine(withheldNoticeText(kind, names))], job.outbox.cursor);
5733
+ job.record.withheldNotice = kind;
5734
+ await saveRecord(job.dir, job.record).catch(() => void 0);
5735
+ }
5736
+ /** An end of a job whose secrets are to come back waits for them, for a while. */
5737
+ async waitForSecrets(job) {
5738
+ const wait = job.awaiting;
5739
+ if (!wait) return;
5740
+ const left = wait.since + (this.opts.secretsEndWaitMs ?? JOB_SECRETS_END_WAIT_MS) - Date.now();
5741
+ let timer = null;
5742
+ await Promise.race([
5743
+ wait.over,
5744
+ this.stopped.over,
5745
+ new Promise((resolve4) => {
5746
+ timer = setTimeout(resolve4, Math.max(0, left));
5747
+ timer.unref?.();
5748
+ })
5749
+ ]);
5750
+ if (timer) clearTimeout(timer);
5751
+ }
5752
+ /** An end not awaited (it waits for secrets): a shutdown waits for it, a failure is logged. */
5753
+ track(work, jobId) {
5754
+ const tracked = work.catch(
5755
+ (err) => this.opts.logger.warn(`job ${jobId}: could not be ended`, {
5756
+ error: err?.message ?? String(err)
5757
+ })
5758
+ );
5759
+ this.finishing.add(tracked);
5760
+ void tracked.then(() => this.finishing.delete(tracked));
5761
+ }
5762
+ stopCommand(id) {
5763
+ const job = this.jobs.get(id);
5764
+ if (job && job.phase === "running") {
5765
+ this.opts.logger.info(`job ${id}: stopping`);
5766
+ void this.stop(job);
5767
+ }
5768
+ return { ok: true };
5769
+ }
5770
+ async openJob(record, child, redactor) {
5771
+ const dir = this.jobDir(record.jobId);
5772
+ const needsSecrets = !redactor && !!record.secretNames?.length;
5773
+ const verifiable = needsSecrets && record.withheldNotice !== "changed" && record.withheldNotice !== "gave_up" && checksEvery(record.secretCheck, record.secretNames ?? []);
5774
+ const job = {
5775
+ record,
5776
+ dir,
5777
+ outbox: null,
5778
+ readers: [],
5779
+ redactor,
5780
+ withhold: needsSecrets && !verifiable,
5781
+ awaiting: verifiable ? secretWait() : null,
5782
+ child,
5783
+ tree: record.pid && record.startedAt ? { pid: record.pid, startedAt: record.startedAt } : null,
5784
+ phase: "running",
5785
+ killTimer: null,
5786
+ reading: Promise.resolve()
5787
+ };
5788
+ job.outbox = await JobOutbox.open({
5789
+ jobId: record.jobId,
5790
+ file: join10(dir, "outbox.json"),
5791
+ poster: this.opts.poster,
5792
+ logger: this.opts.logger,
5793
+ batchDelayMs: this.opts.outboxBatchDelayMs,
5794
+ retryBaseMs: this.opts.outboxRetryBaseMs,
5795
+ onStop: () => {
5796
+ if (job.phase === "running") {
5797
+ this.opts.logger.info(`job ${record.jobId}: Discovery Tree says it is over; stopping it`);
5798
+ void this.stop(job);
5799
+ }
5800
+ },
5801
+ onGone: () => {
5802
+ if (job.phase === "running") void this.stop(job);
5803
+ if (job.phase === "ended") void this.settle(job);
5804
+ },
5805
+ onUnauthorized: (err) => this.opts.onUnauthorized?.(err),
5806
+ onFinished: () => {
5807
+ if (job.phase === "ended") void this.settle(job);
5808
+ }
5809
+ });
5810
+ const cursor = job.outbox.cursor ?? startCursor();
5811
+ job.readers = [
5812
+ new LogFileReader(join10(dir, "stdout.log"), "stdout", cursor.stdout),
5813
+ new LogFileReader(join10(dir, "stderr.log"), "stderr", cursor.stderr)
5814
+ ];
5815
+ return job;
5816
+ }
5817
+ /** Reads what the job wrote since last time and queues it (redacted) to post. */
5818
+ read(job, final) {
5819
+ const next = job.reading.then(async () => {
5820
+ if (job.awaiting) return;
5821
+ for (; ; ) {
5822
+ let more = false;
5823
+ for (const reader of job.readers) {
5824
+ let lines;
5825
+ try {
5826
+ lines = await reader.read(final);
5827
+ } catch (err) {
5828
+ this.opts.logger.debug(`job ${job.record.jobId}: could not read its ${reader.stream}`, {
5829
+ error: err.message
5830
+ });
5831
+ continue;
5832
+ }
5833
+ if (!reader.atEnd) more = true;
5834
+ const cursor = { stdout: job.readers[0].position, stderr: job.readers[1].position };
5835
+ const posted = job.withhold ? [] : lines.map((l) => ({
5836
+ ...l,
5837
+ // Redacted whole first, then cut to what is posted: a cut never splits a
5838
+ // value into a part redaction would not know. A line the reader cut is
5839
+ // redacted as cut (a value cut off at its end is dropped).
5840
+ text: postableLineText(redactLine(job.redactor, l.text, l.cut === true))
5841
+ }));
5842
+ job.outbox.add(posted, cursor);
5843
+ }
5844
+ if (!more || !final) break;
5845
+ }
5846
+ });
5847
+ job.reading = next.catch(() => void 0);
5848
+ return job.reading;
5849
+ }
5850
+ /** Asks the job to end; kills its tree once the grace is up. */
5851
+ async stop(job) {
5852
+ if (job.phase !== "running") return;
5853
+ job.phase = "stopping";
5854
+ job.record.stopRequestedAt = (/* @__PURE__ */ new Date()).toISOString();
5855
+ await saveRecord(job.dir, job.record).catch(() => void 0);
5856
+ job.killTimer = setTimeout(
5857
+ () => void this.forceKill(job),
5858
+ this.opts.stopGraceMs ?? JOB_STOP_GRACE_MS
5859
+ );
5860
+ job.killTimer.unref?.();
5861
+ if (job.tree) await askJobToStop(job.tree).catch(() => void 0);
5862
+ job.record.stopSignalledAt = (/* @__PURE__ */ new Date()).toISOString();
5863
+ await saveRecord(job.dir, job.record).catch(() => void 0);
5864
+ }
5865
+ async forceKill(job) {
5866
+ job.killTimer = null;
5867
+ if (job.phase !== "stopping" || !job.tree) return;
5868
+ this.opts.logger.info(`job ${job.record.jobId}: did not stop in time; killing it`);
5869
+ await killJobTree(job.tree, await this.rootIsTheJob(job));
5870
+ }
5871
+ /** The job's root process is still running (and still the job's, not a later pid's). */
5872
+ async rootIsTheJob(job) {
5873
+ if (job.child) return job.child.exitCode === null && job.child.signalCode === null;
5874
+ const { pid, startedAt, processStamp: stamp } = job.record;
5875
+ return pid !== null && startedAt !== null && await isJobProcess(pid, startedAt, null, stamp);
5876
+ }
5877
+ /**
5878
+ * The job's process ended (`info` from Node, or from the exit-code file for one taken up
5879
+ * again; null when nothing says how): what it left running is ended, its last output read,
5880
+ * and how it ended queued as its last report.
5881
+ */
5882
+ finish(job, info) {
5883
+ if (job.phase === "ending" || job.phase === "ended") return Promise.resolve();
5884
+ if (this.shuttingDown) return Promise.resolve();
5885
+ const work = this.finishJob(job, info);
5886
+ this.finishing.add(work);
5887
+ const done = () => this.finishing.delete(work);
5888
+ work.then(done, done);
5889
+ return work;
5890
+ }
5891
+ async finishJob(job, info) {
5892
+ const stopping = job.phase === "stopping" || !!job.record.stopRequestedAt;
5893
+ job.phase = "ending";
5894
+ if (job.killTimer) clearTimeout(job.killTimer);
5895
+ job.killTimer = null;
5896
+ const asked = stopping ? Date.parse(job.record.stopRequestedAt ?? "") : NaN;
5897
+ const left = Number.isNaN(asked) ? 0 : asked + (this.opts.stopGraceMs ?? JOB_STOP_GRACE_MS) - Date.now();
5898
+ if (job.tree) {
5899
+ await this.endLeftovers(
5900
+ job.tree,
5901
+ Math.max(LEFTOVER_GRACE_MS, left),
5902
+ !!job.record.stopSignalledAt
5903
+ );
5904
+ }
5905
+ if (job.awaiting) {
5906
+ await this.waitForSecrets(job);
5907
+ if (this.shuttingDown) return;
5908
+ if (job.awaiting) await this.giveUpSecrets(job, "gave_up");
5909
+ }
5910
+ await this.read(job, true);
5911
+ for (const r of job.readers) await r.close();
5912
+ let report;
5913
+ if (stopping) {
5914
+ report = { status: "stopped", exitCode: info?.code ?? null, signal: info?.signal ?? null };
5915
+ } else if (info) {
5916
+ report = { status: "exited", exitCode: info.code, signal: info.signal };
5917
+ } else {
5918
+ report = null;
5919
+ }
5920
+ job.record.ended = {
5921
+ at: (/* @__PURE__ */ new Date()).toISOString(),
5922
+ status: report ? report.status : "lost",
5923
+ exitCode: info?.code ?? null,
5924
+ signal: info?.signal ?? null
5925
+ };
5926
+ await saveRecord(job.dir, job.record).catch(() => void 0);
5927
+ job.phase = "ended";
5928
+ this.opts.logger.info(
5929
+ `job ${job.record.jobId}: ${report ? `${report.status}${info?.code !== null && info?.code !== void 0 ? ` (exit code ${info.code})` : info?.signal ? ` (${info.signal})` : ""}` : "its process is gone and nothing says how it ended; Discovery Tree will mark it lost"}`
5930
+ );
5931
+ if (report) job.outbox.report(report);
5932
+ else job.outbox.endWithoutReport();
5933
+ job.lastQueuedAt = performance.now();
5934
+ if (job.outbox.isFinished) await this.settle(job);
5935
+ if (!this.shuttingDown) this.opts.onJobEnded?.(job.record.jobId);
5936
+ }
5937
+ /**
5938
+ * What the job left running after its root exited: asked to end (unless a stop asked it
5939
+ * already: a second SIGTERM is "quit now" to many programs), then killed after `graceMs`.
5940
+ */
5941
+ async endLeftovers(tree, graceMs, asked) {
5942
+ const deadline = Date.now() + graceMs;
5943
+ if (JOB_IS_WINDOWS) {
5944
+ if (graceMs > LEFTOVER_GRACE_MS) {
5945
+ while (Date.now() < deadline) {
5946
+ const rows = await listWindowsProcesses().catch(() => null);
5947
+ if (rows && descendantsOf(tree, rows).length === 0) return;
5948
+ await new Promise((r) => setTimeout(r, 1e3));
5949
+ }
5950
+ }
5951
+ await killJobTree(tree, false);
5952
+ return;
5953
+ }
5954
+ if (processRunning(tree.pid) || !groupAlive(tree.pid)) return;
5955
+ if (!asked) signalGroup2(tree.pid, "SIGTERM");
5956
+ while (Date.now() < deadline && groupHasLiveMember(tree.pid)) {
5957
+ await new Promise((r) => setTimeout(r, 50));
5958
+ }
5959
+ signalGroup2(tree.pid, "SIGKILL");
5960
+ }
5961
+ /** Its last report is through: the job is let go (its folder and log stay). */
5962
+ async settle(job) {
5963
+ if (this.jobs.get(job.record.jobId) !== job || job.phase !== "ended") return;
5964
+ this.jobs.delete(job.record.jobId);
5965
+ job.record.settled = true;
5966
+ await job.outbox.settled();
5967
+ await saveRecord(job.dir, job.record).catch(() => void 0);
5968
+ }
5969
+ ensureTimers() {
5970
+ if (this.shuttingDown) return;
5971
+ if (!this.timer) {
5972
+ this.timer = setInterval(() => void this.tick(), this.opts.pollIntervalMs ?? 500);
5973
+ this.timer.unref?.();
5974
+ }
5975
+ if (JOB_IS_WINDOWS && !this.censusTimer) {
5976
+ this.censusTimer = setInterval(() => void this.census(), CENSUS_INTERVAL_MS2);
5977
+ this.censusTimer.unref?.();
5978
+ }
5979
+ }
5980
+ /**
5981
+ * Windows: one look at the process table for every job. What descends from each is
5982
+ * remembered (see `recordDescendants`), and a job watched by its pid whose pid now names a
5983
+ * later process (Windows hands pids out again quickly) is over: `tick` alone, seeing the pid
5984
+ * alive, would hold it as running for good.
5985
+ */
5986
+ async census() {
5987
+ const live = [...this.jobs.values()].filter(
5988
+ (j) => (j.phase === "running" || j.phase === "stopping") && j.tree
5989
+ );
5990
+ if (!live.length) return;
5991
+ const rows = await listWindowsProcesses().catch(() => null);
5992
+ if (!rows) return;
5993
+ for (const job of live) {
5994
+ recordDescendants(job.tree, rows);
5995
+ if (job.child) continue;
5996
+ const row = rows.find((r) => r.pid === job.tree.pid);
5997
+ if (!row || Math.abs(row.createdAt - job.tree.startedAt) > 5e3) {
5998
+ void this.finish(job, await readExitFile(job.dir));
5999
+ }
6000
+ }
6001
+ }
6002
+ /** Reads every job's new output; notices an adopted job's process has gone. */
6003
+ async tick() {
6004
+ if (this.ticking || this.shuttingDown) return;
6005
+ this.ticking = true;
6006
+ try {
6007
+ for (const job of [...this.jobs.values()]) {
6008
+ if (job.phase !== "running" && job.phase !== "stopping") continue;
6009
+ const wait = job.awaiting;
6010
+ if (wait && Date.now() - wait.since > (this.opts.secretsWaitMs ?? JOB_SECRETS_WAIT_MS)) {
6011
+ await this.noticeWithheld(job, "waiting");
6012
+ }
6013
+ await this.read(job, false);
6014
+ if (!job.child && job.record.pid !== null && !processRunning(job.record.pid)) {
6015
+ void this.finish(job, await readExitFile(job.dir));
6016
+ }
6017
+ }
6018
+ } finally {
6019
+ this.ticking = false;
6020
+ }
6021
+ }
6022
+ };
6023
+ function samePath(a, b) {
6024
+ const fold = JOB_IS_WINDOWS || process.platform === "darwin";
6025
+ const norm = (p) => {
6026
+ const r = fold ? p.toLowerCase() : p;
6027
+ return r.length > 1 ? r.replace(/[\\/]+$/, "") : r;
6028
+ };
6029
+ return norm(resolve2(a)) === norm(resolve2(b)) || norm(canonical(a)) === norm(canonical(b));
6030
+ }
6031
+ function isInside(dir, parent) {
6032
+ const fold = JOB_IS_WINDOWS || process.platform === "darwin";
6033
+ const norm = (p) => {
6034
+ const r = fold ? p.toLowerCase() : p;
6035
+ return r.length > 1 ? r.replace(/[\\/]+$/, "") : r;
6036
+ };
6037
+ const inside = (d, p) => d === p || d.startsWith(p.endsWith(sep3) ? p : p + sep3);
6038
+ return inside(norm(resolve2(dir)), norm(resolve2(parent))) || inside(norm(canonical(dir)), norm(canonical(parent)));
6039
+ }
6040
+ function canonical(p) {
6041
+ const full = resolve2(p);
6042
+ let head = full;
6043
+ let tail = "";
6044
+ for (; ; ) {
6045
+ try {
6046
+ const real = realpathSync.native(head);
6047
+ return tail ? join10(real, tail) : real;
6048
+ } catch {
6049
+ const up = dirname7(head);
6050
+ if (up === head) return full;
6051
+ tail = tail ? join10(basename(head), tail) : basename(head);
6052
+ head = up;
6053
+ }
6054
+ }
6055
+ }
6056
+ function jobLineRedactor(environment) {
6057
+ const values = [];
6058
+ for (const name of environment.secretNames) {
6059
+ const value = environment.env[name];
6060
+ if (typeof value !== "string") continue;
6061
+ values.push({ name, value });
6062
+ const trimmed = value.trim();
6063
+ if (trimmed !== value && trimmed.length >= SECRET_REDACTION_MIN_LENGTH) {
6064
+ values.push({ name, value: trimmed });
6065
+ }
6066
+ if (!/[\r\n]/.test(value)) continue;
6067
+ for (const line of value.split(/\r?\n|\r/)) {
6068
+ for (const piece of /* @__PURE__ */ new Set([line, line.trim()])) {
6069
+ if (piece.length >= SECRET_REDACTION_MIN_LENGTH && !HARMLESS_SECRET_LINE.test(piece)) {
6070
+ values.push({ name, value: piece });
6071
+ }
6072
+ }
6073
+ }
6074
+ }
6075
+ return new SecretRedactor(values);
6076
+ }
6077
+ var HARMLESS_SECRET_LINE = /^(-----(BEGIN|END) [A-Z0-9 ]+-----|[\s{}[\],:]*(true|false|null)?[\s{}[\],:]*)$/;
6078
+ function secretsWithShortLines(environment) {
6079
+ return environment.secretNames.filter((name) => {
6080
+ const value = environment.env[name];
6081
+ if (typeof value !== "string" || !/[\r\n]/.test(value)) return false;
6082
+ return value.split(/\r?\n|\r/).map((l) => l.trim()).some(
6083
+ (l) => l.length > 0 && l.length < SECRET_REDACTION_MIN_LENGTH && !HARMLESS_SECRET_LINE.test(l)
6084
+ );
6085
+ });
6086
+ }
6087
+ async function secretCheckOf(environment) {
6088
+ const salt = randomBytes3(16).toString("base64");
6089
+ const hashes = {};
6090
+ await inPairs(environment.secretNames, async (name) => {
6091
+ const value = environment.env[name];
6092
+ if (typeof value === "string") {
6093
+ hashes[name] = (await fingerprint(salt, name, value)).toString("base64");
6094
+ }
6095
+ });
6096
+ return { v: 1, salt, hashes };
6097
+ }
6098
+ async function secretMatches(check, name, value) {
6099
+ const saved = check.hashes?.[name];
6100
+ if (typeof saved !== "string" || typeof check.salt !== "string") return false;
6101
+ const want = Buffer.from(saved, "base64");
6102
+ const got = await fingerprint(check.salt, name, value);
6103
+ return want.length === got.length && timingSafeEqual(want, got);
6104
+ }
6105
+ function checksEvery(check, names) {
6106
+ return !!check && check.v === 1 && typeof check.salt === "string" && !!check.hashes && names.every((n) => typeof check.hashes[n] === "string");
6107
+ }
6108
+ async function inPairs(items, fn) {
6109
+ const out = new Array(items.length);
6110
+ let next = 0;
6111
+ const worker = async () => {
6112
+ while (next < items.length) {
6113
+ const i = next++;
6114
+ out[i] = await fn(items[i]);
6115
+ }
6116
+ };
6117
+ await Promise.all([worker(), worker()]);
6118
+ return out;
6119
+ }
6120
+ function fingerprint(salt, name, value) {
6121
+ return new Promise(
6122
+ (resolve4, reject) => scrypt(value, `${salt}:${name}`, 32, (err, key) => err ? reject(err) : resolve4(key))
6123
+ );
6124
+ }
6125
+ var RESUMED_NOTICE = "[dt-runner] Discovery Tree handed this job\u2019s secrets back to the runner: its output from where it was held back follows, redacted.";
6126
+ function withheldNoticeText(kind, names) {
6127
+ const stays = "the job\u2019s output stays in its log on the runner\u2019s computer";
6128
+ switch (kind) {
6129
+ case "waiting":
6130
+ return `[dt-runner] The runner restarted and is waiting for Discovery Tree to hand back this job\u2019s secrets, so that it can redact them: until then, ${stays}.`;
6131
+ case "changed":
6132
+ return `[dt-runner] The runner restarted, and ${names.join(", ") || "a secret of this job"} ${names.length === 1 ? "is" : "are"} not the value the job started with (changed or removed since, or Discovery Tree could not read it): redacting another value would let the job\u2019s through, so from here on ${stays}.`;
6133
+ case "gave_up":
6134
+ return `[dt-runner] Discovery Tree did not hand back this job\u2019s secrets in time, so the runner cannot redact them: the rest of ${stays}.`;
6135
+ default:
6136
+ return `[dt-runner] The runner restarted and can no longer redact this job\u2019s secrets (the dt-runner that started it kept nothing to check them against): from here on ${stays}.`;
6137
+ }
6138
+ }
6139
+ function noticeLine(text) {
6140
+ return { stream: "stderr", text, at: (/* @__PURE__ */ new Date()).toISOString() };
6141
+ }
6142
+ function redactLine(redactor, text, cut2) {
6143
+ if (!redactor) return text;
6144
+ return cut2 ? redactor.redactCut(text) : redactor.redact(text);
6145
+ }
6146
+ function queueEndReport(outbox, ended) {
6147
+ if (ended.status === "lost" || ended.status === "failed") {
6148
+ outbox.endWithoutReport();
6149
+ return;
6150
+ }
6151
+ outbox.report(
6152
+ ended.status === "stopped" ? { status: "stopped", exitCode: ended.exitCode, signal: ended.signal } : { status: "exited", exitCode: ended.exitCode, signal: ended.signal }
6153
+ );
6154
+ }
6155
+ async function saveRecord(dir, record) {
6156
+ await writeJsonAtomic(join10(dir, "job.json"), record);
6157
+ }
6158
+ async function readExitFile(dir) {
6159
+ try {
6160
+ const code = Number.parseInt((await readFile8(join10(dir, "exit-code"), "utf8")).trim(), 10);
6161
+ return Number.isInteger(code) ? { code, signal: null } : null;
6162
+ } catch {
6163
+ return null;
6164
+ }
6165
+ }
6166
+ function safeError(err, redactor) {
6167
+ const raw = err instanceof Error ? err.message : String(err);
6168
+ return scrubSecrets(redactor ? redactor.redact(raw) : raw).slice(0, 600);
6169
+ }
6170
+
6171
+ // src/session-manager.ts
6172
+ import { existsSync, lstatSync } from "node:fs";
6173
+ import { mkdir as mkdir9, rm as rm7, writeFile as writeFile6 } from "node:fs/promises";
6174
+ import { basename as basename3, dirname as dirname10, join as join14, resolve as resolve3 } from "node:path";
6175
+
6176
+ // src/prompt-images.ts
6177
+ import { mkdir as mkdir7, writeFile as writeFile5 } from "node:fs/promises";
6178
+ import { join as join11 } from "node:path";
6179
+ var EXTENSIONS = {
6180
+ "image/png": ".png",
6181
+ "image/jpeg": ".jpg",
6182
+ "image/gif": ".gif",
6183
+ "image/webp": ".webp"
6184
+ };
6185
+ function promptImageFileName(index, filename, mimeType) {
6186
+ const base = (filename.split(/[\\/]/).pop() ?? "").replace(/[\u0000-\u001f\u007f<>:"|?*]+/g, "_").replace(/^\.+/, "").trim().slice(0, 120);
6187
+ const ext = EXTENSIONS[mimeType] ?? "";
6188
+ const named = base || `image${ext}`;
6189
+ const withExt = ext && !named.toLowerCase().endsWith(ext) ? `${named}${ext}` : named;
6190
+ return `${String(index + 1).padStart(2, "0")}-${withExt}`;
6191
+ }
6192
+ async function savePromptImages(input) {
6193
+ const out = { saved: [], failed: [] };
6194
+ if (input.images.length === 0) return out;
6195
+ const dir = join11(input.cwd, RUNNER_TASK_IMAGES_DIR);
6196
+ await mkdir7(dir, { recursive: true });
6197
+ if (input.inRepository) {
6198
+ await excludeFromGit(
6199
+ input.cwd,
6200
+ RUNNER_TASK_IMAGES_DIR,
6201
+ "Task images dt-runner saves for its agent"
6202
+ );
6203
+ }
6204
+ for (const [index, image] of input.images.entries()) {
6205
+ try {
6206
+ const res = await input.fetcher.getPromptImage(input.sessionId, image.attachmentId);
6207
+ const path = join11(
6208
+ dir,
6209
+ promptImageFileName(index, image.filename, res.mimeType || image.mimeType)
6210
+ );
6211
+ await writeFile5(path, Buffer.from(res.dataBase64, "base64"));
6212
+ out.saved.push({ filename: image.filename, path });
6213
+ } catch {
6214
+ out.failed.push(image.filename);
6215
+ }
6216
+ }
6217
+ return out;
6218
+ }
6219
+ function promptWithImagePaths(prompt, images) {
6220
+ if (images.saved.length === 0 && images.failed.length === 0) return prompt;
6221
+ const lines = [
6222
+ "",
6223
+ "IMAGE FILES FOR THIS TASK \u2014 the images the attachment lists above refer to, saved as",
6224
+ "files. Open each one and look at it before you start (read it as an image).",
6225
+ ...images.saved.map((i) => `- ${i.filename}: ${i.path}`),
6226
+ ...images.failed.map(
6227
+ (name) => `- ${name}: could not be downloaded; say so rather than describing it`
6228
+ )
6229
+ ];
6230
+ return `${prompt}
6231
+ ${lines.join("\n")}`;
6232
+ }
6233
+
6234
+ // src/outbox.ts
6235
+ var MAX_REJECTED_ATTEMPTS2 = 3;
6236
+ var SessionOutbox = class _SessionOutbox {
6237
+ constructor(opts) {
6238
+ this.opts = opts;
3766
6239
  }
3767
6240
  nextSeq = 1;
3768
6241
  pending = [];
@@ -3814,7 +6287,7 @@ var SessionOutbox = class _SessionOutbox {
3814
6287
  this.pumpTimer = null;
3815
6288
  }
3816
6289
  if (this.pending.length && !this.closed) void this.pump();
3817
- const drained = this.pending.length === 0 || this.closed ? Promise.resolve(true) : new Promise((resolve2) => this.idleWaiters.push(() => resolve2(true)));
6290
+ const drained = this.pending.length === 0 || this.closed ? Promise.resolve(true) : new Promise((resolve4) => this.idleWaiters.push(() => resolve4(true)));
3818
6291
  const result = await Promise.race([drained, sleep(timeoutMs).then(() => false)]);
3819
6292
  await this.persistChain;
3820
6293
  return result || this.pending.length === 0;
@@ -3938,7 +6411,7 @@ var SessionOutbox = class _SessionOutbox {
3938
6411
  error: err.message,
3939
6412
  attempt: rejected
3940
6413
  });
3941
- if (rejected >= MAX_REJECTED_ATTEMPTS) {
6414
+ if (rejected >= MAX_REJECTED_ATTEMPTS2) {
3942
6415
  this.pending = this.pending.filter((e) => e.seq > maxSeq);
3943
6416
  this.persist();
3944
6417
  rejected = 0;
@@ -3989,13 +6462,13 @@ function takeBatch(pending) {
3989
6462
  }
3990
6463
 
3991
6464
  // src/session.ts
3992
- import { spawn as spawn4 } from "node:child_process";
6465
+ import { spawn as spawn5 } from "node:child_process";
3993
6466
  import { randomUUID as randomUUID2 } from "node:crypto";
3994
- import { basename, dirname as dirname6 } from "node:path";
6467
+ import { basename as basename2, dirname as dirname9 } from "node:path";
3995
6468
  import { createInterface as createInterface2 } from "node:readline";
3996
6469
 
3997
6470
  // src/tool-grants.ts
3998
- import { dirname as dirname5, join as join10, posix } from "node:path";
6471
+ import { dirname as dirname8, join as join12, posix } from "node:path";
3999
6472
  var isGrantableDenial = isGrantableToolDenial;
4000
6473
  var FILE_TOOLS2 = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
4001
6474
  var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
@@ -4193,7 +6666,7 @@ function filePatternMatches(spec, file) {
4193
6666
  let pattern = spec.trim();
4194
6667
  if (pattern.startsWith("~/")) {
4195
6668
  if (!home) return false;
4196
- pattern = rulePath(join10(home, pattern.slice(2)).replace(/\\/g, "/"));
6669
+ pattern = rulePath(join12(home, pattern.slice(2)).replace(/\\/g, "/"));
4197
6670
  }
4198
6671
  if (!pattern.startsWith("//")) return false;
4199
6672
  const path = rulePath(file);
@@ -4214,7 +6687,7 @@ function shellPatternMatches(spec, command) {
4214
6687
  return new RegExp(`^${re}${optionalTail ? "(?: .*)?" : ""}$`, "s").test(command);
4215
6688
  }
4216
6689
  function toolGrantsFile(configFile) {
4217
- return join10(dirname5(configFile), "tool-grants.json");
6690
+ return join12(dirname8(configFile), "tool-grants.json");
4218
6691
  }
4219
6692
  var ToolGrantStore = class {
4220
6693
  constructor(file) {
@@ -4380,8 +6853,8 @@ function ghError(command, res) {
4380
6853
  }
4381
6854
 
4382
6855
  // src/session-store.ts
4383
- import { mkdir as mkdir6, readdir as readdir2, rm as rm5 } from "node:fs/promises";
4384
- import { join as join11 } from "node:path";
6856
+ import { mkdir as mkdir8, readdir as readdir3, rm as rm6 } from "node:fs/promises";
6857
+ import { join as join13 } from "node:path";
4385
6858
  var HANDLED_COMMAND_IDS_KEPT = 100;
4386
6859
  var pendingWrites = /* @__PURE__ */ new Map();
4387
6860
  var SessionStore = class {
@@ -4389,10 +6862,10 @@ var SessionStore = class {
4389
6862
  this.stateDir = stateDir;
4390
6863
  }
4391
6864
  dir(sessionId) {
4392
- return join11(this.stateDir, "sessions", sessionId);
6865
+ return join13(this.stateDir, "sessions", sessionId);
4393
6866
  }
4394
6867
  outboxFile(sessionId) {
4395
- return join11(this.dir(sessionId), "outbox.json");
6868
+ return join13(this.dir(sessionId), "outbox.json");
4396
6869
  }
4397
6870
  /**
4398
6871
  * Writes the record as it is now. A session's saves land in the order they were made:
@@ -4402,7 +6875,7 @@ var SessionStore = class {
4402
6875
  */
4403
6876
  async save(record) {
4404
6877
  record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4405
- const file = join11(this.dir(record.sessionId), "session.json");
6878
+ const file = join13(this.dir(record.sessionId), "session.json");
4406
6879
  const snapshot = JSON.parse(JSON.stringify(record));
4407
6880
  const previous = pendingWrites.get(file) ?? Promise.resolve();
4408
6881
  const write = previous.then(() => writeJsonAtomic(file, snapshot));
@@ -4414,23 +6887,23 @@ var SessionStore = class {
4414
6887
  await write;
4415
6888
  }
4416
6889
  async list() {
4417
- const root = join11(this.stateDir, "sessions");
4418
- await mkdir6(root, { recursive: true });
6890
+ const root = join13(this.stateDir, "sessions");
6891
+ await mkdir8(root, { recursive: true });
4419
6892
  const out = [];
4420
- for (const entry of await readdir2(root, { withFileTypes: true })) {
6893
+ for (const entry of await readdir3(root, { withFileTypes: true })) {
4421
6894
  if (!entry.isDirectory()) continue;
4422
- const rec = await readJson(join11(root, entry.name, "session.json"));
6895
+ const rec = await readJson(join13(root, entry.name, "session.json"));
4423
6896
  if (rec?.sessionId === entry.name) out.push(upgradeRecord(rec));
4424
6897
  }
4425
6898
  return out;
4426
6899
  }
4427
6900
  async remove(sessionId) {
4428
- await pendingWrites.get(join11(this.dir(sessionId), "session.json"));
4429
- await rm5(this.dir(sessionId), { recursive: true, force: true });
6901
+ await pendingWrites.get(join13(this.dir(sessionId), "session.json"));
6902
+ await rm6(this.dir(sessionId), { recursive: true, force: true });
4430
6903
  }
4431
6904
  /** Scratch working directory for a session without a repository. */
4432
6905
  scratchDir(sessionId) {
4433
- return join11(this.stateDir, "scratch", sessionId);
6906
+ return join13(this.stateDir, "scratch", sessionId);
4434
6907
  }
4435
6908
  };
4436
6909
  function upgradeRecord(stored) {
@@ -4448,7 +6921,7 @@ var DENIALS_KEPT = 200;
4448
6921
  var AgentSession = class {
4449
6922
  constructor(record, deps) {
4450
6923
  this.record = record;
4451
- this.deps = deps;
6924
+ this.deps = { ...deps, logger: redactingLogger(deps.logger, deps.environment?.redactor) };
4452
6925
  this.driver = deps.driver;
4453
6926
  this.mapper = deps.driver.createMapper();
4454
6927
  this.permissions = new PermissionRelay({
@@ -4471,7 +6944,7 @@ var AgentSession = class {
4471
6944
  input
4472
6945
  ),
4473
6946
  // Only with a repository to save a rule for.
4474
- suggestRule: (tool, input) => toolGrantRepositoryKey(this.record.repository) ? suggestRules(tool, input, this.deps.allowedTools)?.suggestedRule ?? null : null,
6947
+ suggestRule: (tool, input) => toolGrantRepositoryKey(this.record.repository) ? this.suggestSafeRules(tool, input)?.suggestedRule ?? null : null,
4475
6948
  rememberRule: (rule) => {
4476
6949
  const rules = this.record.grantRules ??= [];
4477
6950
  if (rules.includes(rule)) return;
@@ -4479,6 +6952,7 @@ var AgentSession = class {
4479
6952
  void this.deps.store.save(this.record).catch(() => void 0);
4480
6953
  this.deps.logger.info(`session ${this.sessionId}: allowed ${rule} for this repository`);
4481
6954
  },
6955
+ redactInput: deps.environment?.redactor.active ? (input) => deps.environment.redactor.redactDeep(input) : void 0,
4482
6956
  timeoutMs: deps.permissionTimeoutMs
4483
6957
  });
4484
6958
  }
@@ -4499,6 +6973,8 @@ var AgentSession = class {
4499
6973
  interruptTimer = null;
4500
6974
  controlSeq = 0;
4501
6975
  stderrTail = "";
6976
+ /** `stderrTail` lost its start (it keeps the last 4,000 characters). */
6977
+ stderrCut = false;
4502
6978
  sawResultSinceSpawn = false;
4503
6979
  /** The process was started to resume, and has not yet said it has the conversation. */
4504
6980
  spawnedWithResume = false;
@@ -4543,6 +7019,42 @@ var AgentSession = class {
4543
7019
  inheritedNow = { allow: [], deny: [], ask: [], sources: [] };
4544
7020
  /** The folders those rules came from, once logged. */
4545
7021
  loggedInherited = "";
7022
+ deps;
7023
+ /** Said once: this session's environment was lost with a restart of the runner. */
7024
+ toldEnvironmentLost = false;
7025
+ /**
7026
+ * The rules to offer for a call. A call that holds none of the session's secret values gets
7027
+ * the usual ones. One that holds a value gets only a rule that names none of it (built from
7028
+ * the call with its values replaced, each placeholder one word so a command splits as it
7029
+ * did) and still covers the real call; one that cannot be offered so is replaced by the
7030
+ * other (an "Allow once" of a prefix, which the rule shown says). Rules are posted
7031
+ * and saved: one built around a value would write it down, and one with a placeholder in
7032
+ * it could never match. Null when no such rule exists: the call shows as failed, with no
7033
+ * offer to allow it.
7034
+ */
7035
+ suggestSafeRules(toolName, input) {
7036
+ const redactor = this.deps.environment?.redactor;
7037
+ const allowed = this.deps.allowedTools;
7038
+ if (!redactor?.active) return suggestRules(toolName, input, allowed);
7039
+ if (JSON.stringify(redactor.redactDeep(input)) === JSON.stringify(input)) {
7040
+ return suggestRules(toolName, input, allowed);
7041
+ }
7042
+ const rules = suggestRules(toolName, redactor.forRules(input), allowed);
7043
+ if (!rules) return null;
7044
+ const ok = (rule) => !rule.includes(RULE_PLACEHOLDER) && grantsCover([rule], allowed, toolName, input);
7045
+ const suggested = ok(rules.suggestedRule) ? rules.suggestedRule : null;
7046
+ const once = ok(rules.onceRule) ? rules.onceRule : null;
7047
+ const fallback = once ?? suggested;
7048
+ return fallback ? { suggestedRule: suggested ?? fallback, onceRule: once ?? fallback } : null;
7049
+ }
7050
+ /**
7051
+ * An error's message for the log: the session's secrets replaced first, then credentials
7052
+ * in URLs (a value with an `@` in it would not survive that scrub whole).
7053
+ */
7054
+ safeError(err) {
7055
+ const raw = err instanceof Error ? err.message : String(err);
7056
+ return scrubSecrets(this.deps.environment?.redactor.redact(raw) ?? raw);
7057
+ }
4546
7058
  /** The person's Claude Code rules for the repository; the last read if it fails. */
4547
7059
  async readInheritedRules() {
4548
7060
  try {
@@ -4600,18 +7112,22 @@ var AgentSession = class {
4600
7112
  * Reports a tool call that was denied because nobody could answer for it, with the rules
4601
7113
  * a person could grant. Each call once; nothing for sessions not asked to report them.
4602
7114
  */
4603
- reportDenial(callId, toolName, input) {
7115
+ reportDenial(callId, toolName, rawInput) {
4604
7116
  if (!this.record.reportToolDenials) return;
4605
7117
  if (callId) {
4606
7118
  if (this.seenFailedCalls.size > 1e3) this.seenFailedCalls.clear();
4607
7119
  this.seenFailedCalls.add(callId);
4608
7120
  }
4609
- const rules = suggestRules(toolName, input, this.deps.allowedTools);
7121
+ const rules = this.suggestSafeRules(toolName, rawInput);
4610
7122
  if (!rules) return;
7123
+ const redactor = this.deps.environment?.redactor;
4611
7124
  const denial = {
4612
7125
  id: randomUUID2(),
4613
7126
  toolName,
4614
- inputSummary: summarizeToolInput(toolName, input),
7127
+ inputSummary: summarizeToolInput(
7128
+ toolName,
7129
+ redactor?.active ? redactor.redactDeep(rawInput) : rawInput
7130
+ ),
4615
7131
  ...rules,
4616
7132
  deniedAt: (/* @__PURE__ */ new Date()).toISOString()
4617
7133
  };
@@ -4720,8 +7236,36 @@ var AgentSession = class {
4720
7236
  get turnActive() {
4721
7237
  return this.record.turnActive;
4722
7238
  }
7239
+ /**
7240
+ * Queues events for the server, with the environment's secret values replaced first: the
7241
+ * outbox keeps them on disk until they are posted, and the server stores them.
7242
+ */
4723
7243
  emit(...events) {
4724
- this.deps.outbox.enqueue(...events);
7244
+ const redactor = this.deps.environment?.redactor;
7245
+ if (!redactor?.active) {
7246
+ this.deps.outbox.enqueue(...events);
7247
+ return;
7248
+ }
7249
+ const safe = events.map((e) => redactor.event(e)).filter((e) => e !== null);
7250
+ if (safe.length) this.deps.outbox.enqueue(...safe);
7251
+ }
7252
+ /**
7253
+ * A session restored after the runner restarted had an environment whose values went with
7254
+ * the old process (they are never written to disk): said in the conversation, once, before
7255
+ * the agent starts without them.
7256
+ */
7257
+ tellEnvironmentLost() {
7258
+ const names = this.record.environmentNames ?? [];
7259
+ if (this.deps.environment || !names.length || this.toldEnvironmentLost) return;
7260
+ this.toldEnvironmentLost = true;
7261
+ this.deps.logger.warn(
7262
+ `session ${this.sessionId}: the runner restarted, so the agent runs without the run's environment (${names.length} name(s))`
7263
+ );
7264
+ this.emit({
7265
+ type: "error",
7266
+ message: `The runner restarted since this session started, so ${this.driver.displayName} runs without the environment's variables and secrets (${names.join(", ").slice(0, 300)}): the runner keeps their values in memory only. To have them again, let this run end and continue it, which starts a new session with them.`,
7267
+ retryable: false
7268
+ });
4725
7269
  }
4726
7270
  /** Starts the process on the session's task (first turn). */
4727
7271
  async startFirstTurn(prompt) {
@@ -4804,7 +7348,7 @@ var AgentSession = class {
4804
7348
  const reaped = this.treeReaped;
4805
7349
  this.stopping = reason;
4806
7350
  this.reapGraceMs = graceMs;
4807
- const exited = new Promise((resolve2) => this.exitWaiters.push(resolve2));
7351
+ const exited = new Promise((resolve4) => this.exitWaiters.push(resolve4));
4808
7352
  if (child.exitCode === null && child.signalCode === null) {
4809
7353
  await snapshotTree(this.tree, this.deps.reap);
4810
7354
  }
@@ -4948,7 +7492,7 @@ ${text}` : text;
4948
7492
  /** Resolves once the current process has exited (and its exit has been handled). */
4949
7493
  waitForExit() {
4950
7494
  if (!this.child) return Promise.resolve();
4951
- return new Promise((resolve2) => this.exitWaiters.push(resolve2));
7495
+ return new Promise((resolve4) => this.exitWaiters.push(resolve4));
4952
7496
  }
4953
7497
  /** persistent agents: the session's process, started (resuming) when there is none. */
4954
7498
  async ensureProcess() {
@@ -4958,6 +7502,7 @@ ${text}` : text;
4958
7502
  }
4959
7503
  /** Starts the agent's process (with a per_turn agent's prompt), and reads what it says. */
4960
7504
  async spawnAgent(prompt) {
7505
+ this.tellEnvironmentLost();
4961
7506
  await this.prepareEvidenceDir();
4962
7507
  const { bin, features } = await this.deps.resolveAgent();
4963
7508
  const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
@@ -4990,14 +7535,16 @@ ${text}` : text;
4990
7535
  baseRef: this.record.baseRef,
4991
7536
  cwd: this.record.cwd,
4992
7537
  reviewImages: !!this.record.reviewImages,
4993
- reference: this.record.referenceRepository ?? null
7538
+ reference: this.record.referenceRepository ?? null,
7539
+ environment: this.deps.environment ? { names: this.deps.environment.names, secretNames: this.deps.environment.secretNames } : null
4994
7540
  }),
4995
7541
  ...prompt !== void 0 ? { prompt } : {},
4996
7542
  ...this.deps.agentConfig ? { agentConfig: this.deps.agentConfig } : {}
4997
7543
  });
4998
- const child = spawn4(launch.bin, launch.args, {
7544
+ const runEnv = this.deps.environment?.env;
7545
+ const child = spawn5(launch.bin, launch.args, {
4999
7546
  cwd: this.record.cwd,
5000
- env: launch.env ? { ...process.env, ...launch.env } : process.env,
7547
+ env: launch.env || runEnv ? { ...process.env, ...runEnv, ...launch.env } : process.env,
5001
7548
  stdio: ["pipe", "pipe", "pipe"],
5002
7549
  windowsHide: true,
5003
7550
  // A process group of its own, so what it starts can be ended with it. It also means
@@ -5005,10 +7552,10 @@ ${text}` : text;
5005
7552
  detached: OWN_PROCESS_GROUP
5006
7553
  });
5007
7554
  let tree = null;
5008
- await new Promise((resolve2, reject) => {
7555
+ await new Promise((resolve4, reject) => {
5009
7556
  child.once("spawn", () => {
5010
7557
  tree = trackTree(child, this.record.cwd || void 0);
5011
- resolve2();
7558
+ resolve4();
5012
7559
  });
5013
7560
  child.once(
5014
7561
  "error",
@@ -5023,6 +7570,7 @@ ${text}` : text;
5023
7570
  this.resumeDoomed = false;
5024
7571
  this.reapGraceMs = void 0;
5025
7572
  this.stderrTail = "";
7573
+ this.stderrCut = false;
5026
7574
  this.sawResultSinceSpawn = false;
5027
7575
  this.spawnedWithResume = !!this.record.conversationId;
5028
7576
  this.sawInitSinceSpawn = false;
@@ -5031,13 +7579,15 @@ ${text}` : text;
5031
7579
  { pid: child.pid }
5032
7580
  );
5033
7581
  this.treeReaped = new Promise(
5034
- (resolve2) => child.once("exit", () => void reapTree(tree, this.reapGraceMs, this.deps.reap).then(resolve2))
7582
+ (resolve4) => child.once("exit", () => void reapTree(tree, this.reapGraceMs, this.deps.reap).then(resolve4))
5035
7583
  );
5036
7584
  child.stdin.on("error", () => void 0);
5037
7585
  if (launch.stdin !== void 0) child.stdin.end(launch.stdin);
5038
7586
  else if (this.driver.processModel === "per_turn") child.stdin.end();
5039
7587
  child.stderr.setEncoding("utf8").on("data", (d) => {
5040
- this.stderrTail = (this.stderrTail + d).slice(-4e3);
7588
+ const tail = this.stderrTail + d;
7589
+ if (tail.length > 4e3) this.stderrCut = true;
7590
+ this.stderrTail = tail.slice(-4e3);
5041
7591
  });
5042
7592
  const rl = createInterface2({ input: child.stdout, crlfDelay: Infinity });
5043
7593
  rl.on("line", (line) => {
@@ -5139,7 +7689,9 @@ ${text}` : text;
5139
7689
  this.resumeRetry = this.turnText;
5140
7690
  this.record.conversationId = null;
5141
7691
  }
5142
- async endTurn(turn) {
7692
+ async endTurn(rawTurn) {
7693
+ const redactor = this.deps.environment?.redactor;
7694
+ const turn = redactor?.active && rawTurn.text ? { ...rawTurn, text: redactor.redact(rawTurn.text) } : rawTurn;
5143
7695
  this.permissions.expireAll(PERMISSION_EXPIRED_TURN_ENDED);
5144
7696
  for (const d of turn.permissionDenials ?? []) {
5145
7697
  if (d.callId && this.seenFailedCalls.has(d.callId)) continue;
@@ -5162,13 +7714,13 @@ ${text}` : text;
5162
7714
  const push = await this.pushWork();
5163
7715
  const screenshots = push.failed ? "" : await this.publishScreenshots().catch((err) => {
5164
7716
  this.deps.logger.warn(`session ${this.sessionId}: publishing screenshots failed`, {
5165
- error: scrubSecrets(err instanceof Error ? err.message : String(err))
7717
+ error: this.safeError(err)
5166
7718
  });
5167
7719
  return "";
5168
7720
  });
5169
7721
  await this.uploadReviewImages().catch((err) => {
5170
7722
  this.deps.logger.warn(`session ${this.sessionId}: uploading review images failed`, {
5171
- error: scrubSecrets(err instanceof Error ? err.message : String(err))
7723
+ error: this.safeError(err)
5172
7724
  });
5173
7725
  });
5174
7726
  const failed = turnFailed || push.failed;
@@ -5213,8 +7765,10 @@ ${text}` : text;
5213
7765
  const { pullRequest, workBranch, repository, baseRef } = this.record;
5214
7766
  const repo = parseRepoUrl(repository ?? "");
5215
7767
  if (!pullRequest || !workBranch || !repo) return null;
7768
+ const redactor = this.deps.environment?.redactor;
7769
+ const said = text && redactor ? redactor.redact(text) : text;
5216
7770
  const body = [
5217
- text?.trim() || `Work by the ${this.driver.displayName} (local) agent.`,
7771
+ said?.trim() || `Work by the ${this.driver.displayName} (local) agent.`,
5218
7772
  "",
5219
7773
  "---",
5220
7774
  pullRequest.footer
@@ -5260,7 +7814,7 @@ ${text}` : text;
5260
7814
  await ensureEvidenceDir(this.record.cwd);
5261
7815
  } catch (err) {
5262
7816
  this.deps.logger.warn(`session ${this.sessionId}: could not prepare the screenshot folder`, {
5263
- error: scrubSecrets(err instanceof Error ? err.message : String(err))
7817
+ error: this.safeError(err)
5264
7818
  });
5265
7819
  }
5266
7820
  }
@@ -5300,7 +7854,7 @@ ${text}` : text;
5300
7854
  async publishScreenshots() {
5301
7855
  const { workBranch, repoDir, cwd, repository } = this.record;
5302
7856
  const repo = parseRepoUrl(
5303
- repository ?? (repoDir ? `https://github.com/${basename(dirname6(repoDir))}/${basename(repoDir)}` : "")
7857
+ repository ?? (repoDir ? `https://github.com/${basename2(dirname9(repoDir))}/${basename2(repoDir)}` : "")
5304
7858
  );
5305
7859
  if (!workBranch || !repoDir || !repo) return "";
5306
7860
  const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
@@ -5425,10 +7979,10 @@ ${text}` : text;
5425
7979
  await this.endTurn({ text: null, isError: true, subtype: "interrupted" });
5426
7980
  return;
5427
7981
  }
5428
- const tail = scrubSecrets(this.stderrTail.trim().split("\n").slice(-3).join(" ")).slice(
5429
- 0,
5430
- 400
5431
- );
7982
+ const stderr = this.deps.environment?.redactor.redactWindow(this.stderrTail, this.stderrCut);
7983
+ const tail = scrubSecrets(
7984
+ (stderr ?? this.stderrTail).trim().split("\n").slice(-3).join(" ")
7985
+ ).slice(0, 400);
5432
7986
  const how = signal ? `was killed (${signal})` : `exited with code ${code}`;
5433
7987
  const hint = this.sawResultSinceSpawn ? "" : this.driver.startupHint(this.stderrTail);
5434
7988
  if (!this.sawResultSinceSpawn && this.driver.looksLikeSignInFailure(this.stderrTail)) {
@@ -5451,8 +8005,8 @@ ${text}` : text;
5451
8005
  };
5452
8006
  async function raceTimeout(done, ms) {
5453
8007
  let timer;
5454
- const timeout = new Promise((resolve2) => {
5455
- timer = setTimeout(() => resolve2(true), ms);
8008
+ const timeout = new Promise((resolve4) => {
8009
+ timer = setTimeout(() => resolve4(true), ms);
5456
8010
  });
5457
8011
  try {
5458
8012
  return await Promise.race([done.then(() => false), timeout]);
@@ -5502,6 +8056,23 @@ var SessionManager = class {
5502
8056
  resuming = /* @__PURE__ */ new Set();
5503
8057
  store;
5504
8058
  shuttingDown = false;
8059
+ /** Writes of `kept-for-jobs.json`, one after another. */
8060
+ keptChain = Promise.resolve();
8061
+ /**
8062
+ * A release of the folders kept for jobs came while a session was starting, and waits for
8063
+ * the starts to end: a start may be about to continue in one of those folders.
8064
+ */
8065
+ releaseDeferred = false;
8066
+ /** The release of kept folders under way: a session start waits for it to be through. */
8067
+ releasing = null;
8068
+ /** A release was asked for while one was under way: it makes one more pass. */
8069
+ releaseAgain = false;
8070
+ /**
8071
+ * Working copies of a run's earlier sessions that a start with `resume.keepWorkspace` is
8072
+ * taking over (by folder, the starting session's id): closing their session neither moves
8073
+ * nor removes them. Set from the start's first step until it is through.
8074
+ */
8075
+ takenOver = /* @__PURE__ */ new Map();
5505
8076
  /** Loads sessions a previous run left, ends turns it was in the middle of, resumes posting. */
5506
8077
  async restore() {
5507
8078
  for (const record of await this.store.list()) {
@@ -5539,6 +8110,20 @@ var SessionManager = class {
5539
8110
  get(sessionId) {
5540
8111
  return this.sessions.get(sessionId);
5541
8112
  }
8113
+ /**
8114
+ * A job command (`jobCommands` on the poll). Jobs belong to no session: they run apart
8115
+ * from every session, its limit and its idle stop, and outlive the session that asked
8116
+ * for them.
8117
+ */
8118
+ async handleJob(cmd) {
8119
+ if (!this.opts.jobs) return { ok: false, error: "This runner does not run jobs." };
8120
+ try {
8121
+ return await this.opts.jobs.handle(cmd);
8122
+ } catch (err) {
8123
+ const redactor = cmd.type === "start_job" || cmd.type === "job_secrets" ? sessionEnvironment(cmd.environment)?.redactor : null;
8124
+ return { ok: false, error: safeError2(err, redactor) };
8125
+ }
8126
+ }
5542
8127
  async handle(cmd) {
5543
8128
  try {
5544
8129
  assertSafeSessionId(cmd.sessionId);
@@ -5563,8 +8148,10 @@ var SessionManager = class {
5563
8148
  };
5564
8149
  }
5565
8150
  } catch (err) {
5566
- const refused = { ok: false, error: safeError(err) };
5567
- return cmd.type === "start_session" ? this.noteStart(cmd.sessionId, refused) : refused;
8151
+ if (cmd.type !== "start_session") return { ok: false, error: safeError2(err) };
8152
+ const redactor = sessionEnvironment(cmd.environment)?.redactor;
8153
+ const error = safeError2(err, redactor);
8154
+ return this.noteStart(cmd.sessionId, { ok: false, error });
5568
8155
  }
5569
8156
  }
5570
8157
  noteStart(sessionId, ack) {
@@ -5620,11 +8207,21 @@ var SessionManager = class {
5620
8207
  error: `The runner is busy: it is already running ${max} session(s).`
5621
8208
  };
5622
8209
  }
5623
- const promise = this.startSession(cmd).finally(() => this.starting.delete(cmd.sessionId));
8210
+ const promise = this.startSession(cmd).finally(() => {
8211
+ this.starting.delete(cmd.sessionId);
8212
+ for (const [cwd, holder] of this.takenOver) {
8213
+ if (holder === cmd.sessionId) this.takenOver.delete(cwd);
8214
+ }
8215
+ if (this.releaseDeferred && this.starting.size === 0) {
8216
+ this.releaseDeferred = false;
8217
+ void this.releaseKeptForJobs();
8218
+ }
8219
+ });
5624
8220
  this.starting.set(cmd.sessionId, promise);
5625
8221
  return promise;
5626
8222
  }
5627
8223
  async startSession(cmd) {
8224
+ await this.releasing?.catch(() => void 0);
5628
8225
  const label = cmd.title ? `"${cmd.title.slice(0, 80)}"` : `run ${cmd.runId}`;
5629
8226
  this.opts.logger.info(`session ${cmd.sessionId}: starting ${label}`, {
5630
8227
  repo: cmd.repository?.url,
@@ -5638,17 +8235,41 @@ var SessionManager = class {
5638
8235
  );
5639
8236
  }
5640
8237
  const resume = cmd.resume ?? null;
8238
+ const keepWorkspace = resume?.keepWorkspace === true;
8239
+ const earlier = [];
5641
8240
  if (resume) {
5642
8241
  for (const other of [...this.sessions.values()]) {
5643
- if (other.record.runId === cmd.runId && other.sessionId !== cmd.sessionId) {
8242
+ if (other.record.runId !== cmd.runId || other.sessionId === cmd.sessionId) continue;
8243
+ if (!keepWorkspace) {
5644
8244
  await this.close(other.sessionId);
8245
+ continue;
5645
8246
  }
8247
+ if (other.record.cwd) this.takenOver.set(other.record.cwd, cmd.sessionId);
8248
+ earlier.push(other);
8249
+ await other.stop("idle");
5646
8250
  }
5647
8251
  await Promise.allSettled([...this.closing.values()]);
5648
8252
  this.opts.logger.info(`session ${cmd.sessionId}: continuing run ${cmd.runId}`, {
5649
- resume: resume.conversationId ?? resume.claudeSessionId ? "conversation" : "fresh"
8253
+ resume: resume.conversationId ?? resume.claudeSessionId ? "conversation" : "fresh",
8254
+ ...keepWorkspace ? { keepWorkspace: true } : {}
5650
8255
  });
5651
8256
  }
8257
+ const environment = sessionEnvironment(cmd.environment);
8258
+ if (environment) {
8259
+ this.opts.logger.info(
8260
+ `session ${cmd.sessionId}: the run's environment sets ${environment.names.length} variable(s), ${environment.secretNames.length} of them secret`
8261
+ );
8262
+ if (environment.unredacted.length) {
8263
+ this.opts.logger.warn(
8264
+ `session ${cmd.sessionId}: ${environment.unredacted.join(", ")} ${environment.unredacted.length === 1 ? "is" : "are"} too short to be redacted from what the session posts (under ${SECRET_REDACTION_MIN_LENGTH} characters)`
8265
+ );
8266
+ }
8267
+ if (environment.skipped.length) {
8268
+ this.opts.logger.warn(
8269
+ `session ${cmd.sessionId}: left out of the agent's environment (not a name it may set): ${environment.skipped.slice(0, 20).join(", ")}`
8270
+ );
8271
+ }
8272
+ }
5652
8273
  const now = (/* @__PURE__ */ new Date()).toISOString();
5653
8274
  const record = {
5654
8275
  sessionId: cmd.sessionId,
@@ -5667,11 +8288,23 @@ var SessionManager = class {
5667
8288
  ...alwaysAllowTools(cmd).length ? { alwaysAllowedTools: alwaysAllowTools(cmd) } : {},
5668
8289
  ...cmd.reportToolDenials === true ? { reportToolDenials: true } : {},
5669
8290
  ...grantRules(cmd).length ? { grantRules: grantRules(cmd) } : {},
8291
+ ...environment?.names.length ? { environmentNames: environment.names } : {},
5670
8292
  createdAt: now,
5671
8293
  updatedAt: now
5672
8294
  };
5673
8295
  try {
5674
8296
  if (cmd.repository) {
8297
+ const holds = /* @__PURE__ */ new Map();
8298
+ const claim = (dir) => {
8299
+ if (!holds.get(dir)) {
8300
+ holds.set(dir, this.opts.jobs ? this.opts.jobs.holdForRemoval(dir) : () => void 0);
8301
+ }
8302
+ return holds.get(dir) ?? null;
8303
+ };
8304
+ const keptWorktreeMark = (dir) => {
8305
+ const from = keepWorkspace ? earlier.find((o) => o.record.cwd === dir) : void 0;
8306
+ return from ? from.record.keepWorktree === true : true;
8307
+ };
5675
8308
  const wt = await prepareWorktree({
5676
8309
  url: cmd.repository.url,
5677
8310
  baseRef: cmd.repository.baseRef,
@@ -5681,8 +8314,13 @@ var SessionManager = class {
5681
8314
  sessionId: cmd.sessionId,
5682
8315
  protocol: this.opts.config.gitProtocol,
5683
8316
  continueBranch: !!resume,
5684
- worktreeKey: resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : null
8317
+ worktreeKey: resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : null,
8318
+ inUse: (dir) => claim(dir) === null,
8319
+ keepWorkspace
8320
+ }).finally(() => {
8321
+ for (const release of holds.values()) release?.();
5685
8322
  });
8323
+ await this.unkeep(wt.worktree);
5686
8324
  Object.assign(record, {
5687
8325
  cwd: wt.worktree,
5688
8326
  repoDir: wt.repoDir,
@@ -5693,13 +8331,31 @@ var SessionManager = class {
5693
8331
  baseSha: wt.baseSha,
5694
8332
  // A reused kept worktree still holds the uncommitted changes it was kept for: keep
5695
8333
  // protecting it until a turn commits them, or a close before then would delete them.
5696
- ...wt.continuedFrom === "worktree" ? { keepWorktree: true } : {}
8334
+ // One continued in for a job is the earlier session's as it was: its mark carries over.
8335
+ ...wt.continuedFrom === "worktree" && keptWorktreeMark(wt.worktree) ? { keepWorktree: true } : {}
5697
8336
  });
5698
- if (wt.leftInPlace) {
8337
+ if (wt.leftInPlace && keepWorkspace) {
8338
+ this.opts.logger.info(
8339
+ `session ${cmd.sessionId}: the earlier working copy at ${wt.leftInPlace} is kept for the run's job and cannot be continued in as it is (not on ${cmd.repository.workBranch}, or behind what was pushed); left as it is, and this session works in ${wt.worktree}`
8340
+ );
8341
+ if (!earlier.some((o) => o.record.cwd === wt.leftInPlace)) {
8342
+ await this.keep({
8343
+ sessionId: safeWorktreeKey(resume?.worktreeKey, cmd.sessionId),
8344
+ cwd: wt.leftInPlace,
8345
+ repoDir: wt.repoDir,
8346
+ heldBy: cmd.sessionId
8347
+ });
8348
+ }
8349
+ } else if (wt.leftInPlace) {
5699
8350
  this.opts.logger.warn(
5700
8351
  `session ${cmd.sessionId}: the earlier working copy at ${wt.leftInPlace} is in use (close any terminal, editor or program open in it) and was left as it is; this session works in ${wt.worktree}`
5701
8352
  );
5702
8353
  }
8354
+ if (wt.keptRef) {
8355
+ this.opts.logger.warn(
8356
+ `session ${cmd.sessionId}: the work branch had commits only this computer has; they are kept as ${wt.keptRef} in ${wt.repoDir}, and this session starts from the branch as pushed`
8357
+ );
8358
+ }
5703
8359
  if (wt.setAside) {
5704
8360
  this.opts.logger.warn(
5705
8361
  `session ${cmd.sessionId}: an earlier working copy with uncommitted changes could not be reused; it was moved to ${wt.setAside}`
@@ -5709,21 +8365,47 @@ var SessionManager = class {
5709
8365
  record.cwd = this.store.scratchDir(
5710
8366
  resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : cmd.sessionId
5711
8367
  );
5712
- await mkdir7(record.cwd, { recursive: true });
8368
+ const keptEntry = keepWorkspace ? await this.keptEntry(record.cwd) : null;
8369
+ await this.unkeep(record.cwd);
8370
+ await mkdir9(record.cwd, { recursive: true });
5713
8371
  if (cmd.reviewImages === true && this.opts.reviewImageUploader) {
5714
8372
  record.reviewImages = true;
5715
- await mkdir7(join12(record.cwd, EVIDENCE_DIR), { recursive: true });
8373
+ await mkdir9(join14(record.cwd, EVIDENCE_DIR), { recursive: true });
5716
8374
  }
5717
8375
  const reference = cmd.referenceRepository;
5718
- if (reference?.url) {
8376
+ const referenceDir = join14(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR);
8377
+ const fromEntry = keptEntry?.reference;
8378
+ const entryUrl = () => fromEntry ? fromEntry.url ?? legacyUrl(fromEntry, this.opts.config.reposDir) : null;
8379
+ const fromSession = keepWorkspace ? earlier.find((o) => o.record.cwd === record.cwd)?.record.referenceRepository : void 0;
8380
+ const url = keepWorkspace && !fromSession ? entryUrl() : null;
8381
+ const candidate = !keepWorkspace ? void 0 : fromSession ?? (fromEntry && url ? {
8382
+ url,
8383
+ // Unknown for an older runner's entry: the preface then names no ref.
8384
+ baseRef: fromEntry.baseRef ?? "",
8385
+ dir: fromEntry.dir,
8386
+ repoDir: fromEntry.repoDir
8387
+ } : void 0);
8388
+ const keptReference = candidate && existsSync(candidate.dir) ? candidate : void 0;
8389
+ const referenceHold = !reference?.url ? null : this.opts.jobs ? this.opts.jobs.holdForRemoval(referenceDir) : () => void 0;
8390
+ if (reference?.url && keepWorkspace && (keptReference || existsSync(referenceDir))) {
8391
+ if (keptReference) record.referenceRepository = keptReference;
8392
+ referenceHold?.();
8393
+ this.opts.logger.info(
8394
+ `session ${cmd.sessionId}: the repository in ${referenceDir} is kept for the run's job, so it is left as it is`
8395
+ );
8396
+ } else if (reference?.url && !referenceHold) {
8397
+ this.opts.logger.warn(
8398
+ `session ${cmd.sessionId}: a job runs in ${referenceDir}, so the repository there is left as it is`
8399
+ );
8400
+ } else if (reference?.url) {
5719
8401
  try {
5720
8402
  const checkout = await prepareReferenceCheckout({
5721
8403
  url: reference.url,
5722
8404
  baseRef: reference.baseRef ?? null,
5723
8405
  reposDir: this.opts.config.reposDir,
5724
- dir: join12(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR),
8406
+ dir: join14(record.cwd, RUNNER_REFERENCE_REPOSITORY_DIR),
5725
8407
  protocol: this.opts.config.gitProtocol
5726
- });
8408
+ }).finally(() => referenceHold?.());
5727
8409
  record.referenceRepository = {
5728
8410
  url: reference.url,
5729
8411
  baseRef: checkout.baseRef,
@@ -5733,13 +8415,13 @@ var SessionManager = class {
5733
8415
  } catch (err) {
5734
8416
  this.opts.logger.warn(
5735
8417
  `session ${cmd.sessionId}: could not check out ${reference.url} for the agent to read; it works without it`,
5736
- { error: safeError(err) }
8418
+ { error: safeError2(err, environment?.redactor) }
5737
8419
  );
5738
8420
  }
5739
8421
  }
5740
8422
  const deliverable = resume?.deliverable;
5741
8423
  if (typeof deliverable === "string" && deliverable.trim()) {
5742
- await writeFile5(join12(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
8424
+ await writeFile6(join14(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
5743
8425
  }
5744
8426
  }
5745
8427
  if (resume) {
@@ -5748,19 +8430,21 @@ var SessionManager = class {
5748
8430
  }
5749
8431
  await this.store.save(record);
5750
8432
  } catch (err) {
8433
+ const error = safeError2(err, environment?.redactor);
5751
8434
  this.opts.logger.error(`session ${cmd.sessionId}: could not prepare the workspace`, {
5752
- error: safeError(err)
8435
+ error
5753
8436
  });
5754
8437
  await this.store.remove(cmd.sessionId).catch(() => void 0);
5755
- return { ok: false, error: safeError(err) };
8438
+ return { ok: false, error };
5756
8439
  }
5757
- const session = await this.openSession(record);
8440
+ const session = await this.openSession(record, environment);
5758
8441
  this.sessions.set(cmd.sessionId, session);
8442
+ for (const other of earlier) await this.close(other.sessionId);
5759
8443
  if (resume) return { ok: true };
5760
8444
  try {
5761
8445
  await session.startFirstTurn(await this.promptWithImages(cmd, record));
5762
8446
  } catch (err) {
5763
- const message = safeError(err);
8447
+ const message = safeError2(err, environment?.redactor);
5764
8448
  this.opts.logger.error(`session ${cmd.sessionId}: ${message}`);
5765
8449
  session.emit(
5766
8450
  { type: "error", message, retryable: false },
@@ -5768,7 +8452,7 @@ var SessionManager = class {
5768
8452
  );
5769
8453
  await this.forgetFailedStart(session).catch(
5770
8454
  (e) => this.opts.logger.warn(`session ${cmd.sessionId}: could not clean up the failed start`, {
5771
- error: safeError(e)
8455
+ error: safeError2(e, environment?.redactor)
5772
8456
  })
5773
8457
  );
5774
8458
  return { ok: false, error: message };
@@ -5921,7 +8605,7 @@ var SessionManager = class {
5921
8605
  });
5922
8606
  } catch (err) {
5923
8607
  this.opts.logger.warn(`session ${cmd.sessionId}: could not save the task's images`, {
5924
- error: safeError(err)
8608
+ error: safeError2(err)
5925
8609
  });
5926
8610
  }
5927
8611
  }
@@ -5944,32 +8628,186 @@ var SessionManager = class {
5944
8628
  await session.stop("close");
5945
8629
  await this.opts.beforeWorktreeRemoved?.(sessionId);
5946
8630
  const { record } = session;
5947
- if (record.repoDir && record.keepWorktree) {
8631
+ const workspace = {
8632
+ sessionId,
8633
+ cwd: record.cwd,
8634
+ repoDir: record.repoDir,
8635
+ reference: record.referenceRepository ? {
8636
+ repoDir: record.referenceRepository.repoDir,
8637
+ dir: record.referenceRepository.dir,
8638
+ url: record.referenceRepository.url,
8639
+ baseRef: record.referenceRepository.baseRef
8640
+ } : null
8641
+ };
8642
+ const holder = record.cwd ? this.takenOver.get(record.cwd) : void 0;
8643
+ if (holder) {
8644
+ await this.rehold(sessionId, holder);
8645
+ if (this.sessions.get(holder)?.record.cwd === record.cwd) {
8646
+ this.opts.logger.info(`session ${sessionId}: session ${holder} continues in ${record.cwd}`);
8647
+ } else {
8648
+ const uncommitted = !!record.repoDir && record.keepWorktree === true;
8649
+ if (uncommitted) {
8650
+ this.opts.logger.warn(
8651
+ `session ${sessionId}: keeping the worktree ${record.cwd}, which holds changes that could not be committed; session ${holder} works elsewhere`
8652
+ );
8653
+ } else {
8654
+ this.opts.logger.info(
8655
+ `session ${sessionId}: keeping ${record.cwd}, which the run's job may use, until session ${holder} closes`
8656
+ );
8657
+ }
8658
+ await this.keep({ ...workspace, heldBy: holder, ...uncommitted ? { uncommitted } : {} });
8659
+ }
8660
+ } else if (record.repoDir && record.keepWorktree) {
5948
8661
  this.opts.logger.warn(
5949
8662
  `session ${sessionId}: keeping the worktree ${record.cwd}, which holds changes that could not be committed`
5950
8663
  );
5951
- } else if (record.repoDir) {
5952
- await removeWorktree(record.repoDir, record.cwd).catch(
5953
- (err) => this.opts.logger.warn(`session ${sessionId}: could not remove the worktree`, {
5954
- error: safeError(err)
8664
+ } else if (!await this.removeUnlessInUse(workspace)) {
8665
+ this.opts.logger.info(
8666
+ `session ${sessionId}: keeping ${record.cwd} while a job runs in it; it is removed once the job ends`
8667
+ );
8668
+ await this.keep(workspace);
8669
+ }
8670
+ await session.outbox.settled();
8671
+ await this.store.remove(sessionId);
8672
+ this.opts.logger.info(`session ${sessionId}: closed`);
8673
+ void this.releaseKeptForJobs();
8674
+ }
8675
+ /**
8676
+ * Removes the workspace unless a job runs in it (false then: it is to be kept). The check
8677
+ * and the claim are one step (`holdForRemoval`), and no job starts in it while it goes.
8678
+ */
8679
+ async removeUnlessInUse(w) {
8680
+ const jobs = this.opts.jobs;
8681
+ const hold = jobs && w.cwd ? jobs.holdForRemoval(w.cwd) : () => void 0;
8682
+ if (!hold) return false;
8683
+ try {
8684
+ await this.removeWorkspace(w);
8685
+ } finally {
8686
+ hold();
8687
+ }
8688
+ return true;
8689
+ }
8690
+ /** Removes a closed session's worktree (the branch stays) or scratch folder. */
8691
+ async removeWorkspace(w) {
8692
+ if (w.repoDir) {
8693
+ await removeWorktree(w.repoDir, w.cwd).catch(
8694
+ (err) => this.opts.logger.warn(`session ${w.sessionId}: could not remove the worktree`, {
8695
+ error: safeError2(err)
5955
8696
  })
5956
8697
  );
5957
- } else if (record.cwd) {
5958
- if (record.referenceRepository) {
5959
- await removeWorktree(
5960
- record.referenceRepository.repoDir,
5961
- record.referenceRepository.dir
5962
- ).catch(
5963
- (err) => this.opts.logger.warn(`session ${sessionId}: could not remove the checkout it read`, {
5964
- error: safeError(err)
8698
+ } else if (w.cwd) {
8699
+ if (w.reference) {
8700
+ await removeWorktree(w.reference.repoDir, w.reference.dir).catch(
8701
+ (err) => this.opts.logger.warn(`session ${w.sessionId}: could not remove the checkout it read`, {
8702
+ error: safeError2(err)
5965
8703
  })
5966
8704
  );
5967
8705
  }
5968
- await rm6(record.cwd, { recursive: true, force: true }).catch(() => void 0);
8706
+ await rm7(w.cwd, { recursive: true, force: true }).catch(() => void 0);
8707
+ }
8708
+ }
8709
+ keptFile() {
8710
+ return join14(this.opts.config.stateDir, "kept-for-jobs.json");
8711
+ }
8712
+ /** The entry kept for `cwd` in `kept-for-jobs.json`, if any. */
8713
+ async keptEntry(cwd) {
8714
+ await this.keptChain;
8715
+ const saved = await readJson(this.keptFile()).catch(() => null);
8716
+ return (Array.isArray(saved) ? saved : []).find((k) => k.cwd === cwd) ?? null;
8717
+ }
8718
+ /** Changes the list of workspaces kept for jobs, one change at a time. */
8719
+ changeKept(change) {
8720
+ const run = this.keptChain.then(async () => {
8721
+ const saved = await readJson(this.keptFile()).catch(() => null);
8722
+ const before = Array.isArray(saved) ? saved : [];
8723
+ const { list, result } = await change(before);
8724
+ if (list.length !== before.length || list.some((w, i) => w !== before[i])) {
8725
+ await writeJsonAtomic(this.keptFile(), list);
8726
+ }
8727
+ return result;
8728
+ });
8729
+ this.keptChain = run.catch(() => void 0);
8730
+ return run;
8731
+ }
8732
+ keep(w) {
8733
+ return this.changeKept(async (list) => {
8734
+ const was = list.find((k) => k.cwd === w.cwd);
8735
+ const entry = was?.uncommitted && !w.uncommitted ? { ...w, uncommitted: true } : w;
8736
+ return { list: [...list.filter((k) => k.cwd !== w.cwd), entry], result: void 0 };
8737
+ }).catch(
8738
+ (err) => this.opts.logger.warn(`session ${w.sessionId}: could not note the worktree kept for a job`, {
8739
+ error: safeError2(err)
8740
+ })
8741
+ );
8742
+ }
8743
+ /** Folders kept until `from` closed are kept until `to` closes instead. */
8744
+ rehold(from, to) {
8745
+ return this.changeKept(async (list) => ({
8746
+ list: list.map((k) => k.heldBy === from ? { ...k, heldBy: to } : k),
8747
+ result: void 0
8748
+ })).catch(
8749
+ (err) => this.opts.logger.warn(
8750
+ `session ${from}: could not hand the folders it kept over to session ${to}`,
8751
+ { error: safeError2(err) }
8752
+ )
8753
+ );
8754
+ }
8755
+ /** A session now works in `cwd` again: it is no longer kept for a job. */
8756
+ unkeep(cwd) {
8757
+ return this.changeKept(async (list) => ({
8758
+ list: list.filter((k) => k.cwd !== cwd),
8759
+ result: void 0
8760
+ })).catch(() => void 0);
8761
+ }
8762
+ /**
8763
+ * Removes the closed sessions' worktrees kept for jobs that no job runs in any more (a job
8764
+ * ended, or the runner restarted and the job is gone). Never rejects.
8765
+ */
8766
+ async releaseKeptForJobs() {
8767
+ if (this.starting.size > 0) {
8768
+ this.releaseDeferred = true;
8769
+ return;
8770
+ }
8771
+ if (this.releasing) {
8772
+ this.releaseAgain = true;
8773
+ return this.releasing;
8774
+ }
8775
+ this.releasing = (async () => {
8776
+ do {
8777
+ this.releaseAgain = false;
8778
+ await this.release();
8779
+ } while (this.releaseAgain && this.starting.size === 0);
8780
+ if (this.releaseAgain) this.releaseDeferred = true;
8781
+ })().finally(() => this.releasing = null);
8782
+ return this.releasing;
8783
+ }
8784
+ async release() {
8785
+ const free = await this.changeKept(async (list) => {
8786
+ const worked = (w) => [...this.sessions.values()].some((s) => s.record.cwd === w.cwd);
8787
+ const kept = list.filter((w) => !worked(w) && w.uncommitted === true && !gone(w.cwd));
8788
+ const rest = list.filter((w) => !worked(w) && !kept.includes(w));
8789
+ const held = (w) => !!w.heldBy && (this.sessions.has(w.heldBy) || this.starting.has(w.heldBy));
8790
+ const mine = rest.filter((w) => !held(w));
8791
+ const used = mine.map((w) => this.opts.jobs?.usesPath(w.cwd) ?? false);
8792
+ return {
8793
+ list: [...kept, ...rest.filter(held), ...mine.filter((_, i) => used[i])],
8794
+ result: mine.filter((_, i) => !used[i])
8795
+ };
8796
+ }).catch(() => []);
8797
+ for (const [i, w] of free.entries()) {
8798
+ if (this.starting.size > 0) {
8799
+ for (const rest of free.slice(i)) await this.keep(rest);
8800
+ this.releaseDeferred = true;
8801
+ return;
8802
+ }
8803
+ if (await this.removeUnlessInUse(w)) {
8804
+ this.opts.logger.info(
8805
+ `session ${w.sessionId}: no job ran in ${w.cwd} any more; removed it`
8806
+ );
8807
+ } else {
8808
+ await this.keep(w);
8809
+ }
5969
8810
  }
5970
- await session.outbox.settled();
5971
- await this.store.remove(sessionId);
5972
- this.opts.logger.info(`session ${sessionId}: closed`);
5973
8811
  }
5974
8812
  /** Ends Claude Code processes that have been idle too long; their sessions stay resumable. */
5975
8813
  async stopIdle(now = Date.now()) {
@@ -6019,7 +8857,8 @@ var SessionManager = class {
6019
8857
  driverFor(kind) {
6020
8858
  return this.opts.driver ?? agentDriver(kind);
6021
8859
  }
6022
- async openSession(record) {
8860
+ /** `environment`: a start's, in memory; none for a session restored from disk. */
8861
+ async openSession(record, environment = null) {
6023
8862
  const outbox = await SessionOutbox.open({
6024
8863
  sessionId: record.sessionId,
6025
8864
  file: this.store.outboxFile(record.sessionId),
@@ -6054,7 +8893,8 @@ var SessionManager = class {
6054
8893
  permissionTimeoutMs: this.opts.permissionTimeoutMs,
6055
8894
  savedRules: async (url) => this.opts.grants ? await this.opts.grants.rulesFor(url) : [],
6056
8895
  reviewImageUploader: this.opts.reviewImageUploader,
6057
- inheritedRules: this.opts.inherited ? (url) => this.opts.inherited.rulesFor(url) : void 0
8896
+ inheritedRules: this.opts.inherited ? (url) => this.opts.inherited.rulesFor(url) : void 0,
8897
+ environment
6058
8898
  });
6059
8899
  }
6060
8900
  };
@@ -6076,6 +8916,20 @@ function alwaysAllowTools(cmd) {
6076
8916
  )
6077
8917
  ];
6078
8918
  }
8919
+ function legacyUrl(entry, reposDir) {
8920
+ const repoDir = resolve3(entry.repoDir);
8921
+ if (!samePath(dirname10(dirname10(repoDir)), reposDir)) return null;
8922
+ const url = `https://github.com/${basename3(dirname10(repoDir))}/${basename3(repoDir)}`;
8923
+ return parseRepoUrl(url) ? url : null;
8924
+ }
8925
+ function gone(path) {
8926
+ try {
8927
+ lstatSync(path);
8928
+ return false;
8929
+ } catch (err) {
8930
+ return err.code === "ENOENT";
8931
+ }
8932
+ }
6079
8933
  function safeWorktreeKey(key, fallback) {
6080
8934
  if (!key) return fallback;
6081
8935
  try {
@@ -6097,8 +8951,9 @@ ${task.slice(0, 2e4)}` : "",
6097
8951
  "The person\u2019s message follows."
6098
8952
  ].filter(Boolean).join("\n\n");
6099
8953
  }
6100
- function safeError(err) {
6101
- return scrubSecrets(err instanceof Error ? err.message : String(err)).slice(0, 600);
8954
+ function safeError2(err, redactor) {
8955
+ const raw = err instanceof Error ? err.message : String(err);
8956
+ return scrubSecrets(redactor ? redactor.redact(raw) : raw).slice(0, 600);
6102
8957
  }
6103
8958
 
6104
8959
  // src/daemon.ts
@@ -6112,6 +8967,16 @@ var RunnerDaemon = class {
6112
8967
  this.opts = opts;
6113
8968
  this.api = opts.api ?? new RunnerApi({ server: opts.config.server, token: opts.config.token });
6114
8969
  this.grants = opts.grants ?? new ToolGrantStore(toolGrantsFile(opts.config.configFile));
8970
+ this.jobs = new JobManager({
8971
+ stateDir: opts.config.stateDir,
8972
+ maxJobs: opts.config.maxJobs,
8973
+ poster: this.api,
8974
+ logger: opts.logger,
8975
+ onUnauthorized: (err) => this.unauthorized(err),
8976
+ // A worktree a closed session left for a job can go once no job uses it.
8977
+ onJobEnded: () => void this.manager.releaseKeptForJobs(),
8978
+ ...opts.jobOverrides
8979
+ });
6115
8980
  this.manager = new SessionManager({
6116
8981
  config: opts.config,
6117
8982
  poster: this.api,
@@ -6123,6 +8988,7 @@ var RunnerDaemon = class {
6123
8988
  grants: this.grants,
6124
8989
  reviewImageUploader: this.api,
6125
8990
  promptImageFetcher: this.api,
8991
+ jobs: this.jobs,
6126
8992
  // What the person already allows in their own Claude Code for a repository.
6127
8993
  inherited: opts.config.inheritClaudeCodePermissions ? new ClaudeCodeRules({
6128
8994
  exclude: [opts.config.reposDir, opts.config.worktreesDir]
@@ -6132,6 +8998,7 @@ var RunnerDaemon = class {
6132
8998
  }
6133
8999
  api;
6134
9000
  manager;
9001
+ jobs;
6135
9002
  controller = new AbortController();
6136
9003
  exitReason = "stopped";
6137
9004
  agentInfo = null;
@@ -6176,15 +9043,19 @@ var RunnerDaemon = class {
6176
9043
  /** Runs until stopped (signal) or the token is refused. */
6177
9044
  async run() {
6178
9045
  const { logger, config } = this.opts;
9046
+ await this.jobs.restore();
6179
9047
  await this.manager.restore();
9048
+ await this.manager.releaseKeptForJobs();
6180
9049
  logger.info(`dt-runner ${RUNNER_VERSION} connected to ${config.server}`, {
6181
9050
  maxSessions: config.maxSessions,
9051
+ maxJobs: config.maxJobs,
6182
9052
  permissionMode: config.permissionMode
6183
9053
  });
6184
9054
  const loops = [this.heartbeatLoop(), this.commandLoop(), this.idleLoop()];
6185
9055
  await Promise.all(loops);
6186
9056
  await Promise.allSettled([...this.inFlight]);
6187
9057
  await this.manager.shutdown();
9058
+ await this.jobs.shutdown();
6188
9059
  return this.exitReason;
6189
9060
  }
6190
9061
  /** Begins a graceful stop; `run()` resolves once sessions are wound down. */
@@ -6335,13 +9206,28 @@ var RunnerDaemon = class {
6335
9206
  // And saves the images a prompt names as files for its agent (`promptImages`).
6336
9207
  receivesPromptImages: true,
6337
9208
  // And checks out a non-code task's repository for it to read (`referenceRepository`).
6338
- checksOutReferenceRepository: true
9209
+ checksOutReferenceRepository: true,
9210
+ // And sets the run's variables and secrets for its agent (`environment`), in
9211
+ // memory only, redacting the secrets from what it posts.
9212
+ receivesEnvironment: true,
9213
+ // And runs jobs outside any session; with it, `activeJobIds` is always sent.
9214
+ runsJobs: true,
9215
+ // And keeps a run's folder a job uses when the run is continued here
9216
+ // (`resume.keepWorkspace`): continued in, or left as it is.
9217
+ keepsJobWorkspaces: true,
9218
+ // And gets the secrets of a job it took up again back (`jobsNeedingSecrets`,
9219
+ // `job_secrets`), to post its output redacted.
9220
+ receivesJobSecrets: true
6339
9221
  },
6340
9222
  activeSessionIds: this.heartbeatSessionIds(),
6341
9223
  maxConcurrentSessions: this.opts.config.maxSessions,
6342
9224
  activeCompletionIds: [...this.completionControllers.keys()],
6343
- toolGrants: await this.toolGrants()
9225
+ toolGrants: await this.toolGrants(),
9226
+ activeJobIds: this.jobs.activeJobIds(),
9227
+ maxJobs: this.opts.config.maxJobs,
9228
+ jobsNeedingSecrets: this.jobs.jobsNeedingSecrets()
6344
9229
  });
9230
+ if (res?.stopJobIds?.length) this.jobs.stopJobs(res.stopJobIds);
6345
9231
  if (res?.toolGrantChanges?.length) {
6346
9232
  for (const problem of await this.grants.apply(res.toolGrantChanges)) {
6347
9233
  this.opts.logger.warn(`a saved tool permission was not applied: ${problem}`);
@@ -6399,6 +9285,7 @@ var RunnerDaemon = class {
6399
9285
  attempt = 0;
6400
9286
  limited = 0;
6401
9287
  for (const cmd of res?.commands ?? []) this.track(this.dispatch(cmd));
9288
+ for (const cmd of res?.jobCommands ?? []) this.track(this.dispatchJob(cmd));
6402
9289
  for (const req of res?.completions ?? []) this.track(this.answer(req));
6403
9290
  } catch (err) {
6404
9291
  if (this.signal.aborted) break;
@@ -6444,7 +9331,7 @@ var RunnerDaemon = class {
6444
9331
  if (this.droppedSessionIds.has(id)) return;
6445
9332
  this.droppedSessionIds.add(id);
6446
9333
  this.opts.logger.warn(
6447
- `session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${join13(this.opts.config.stateDir, "sessions", id)})`
9334
+ `session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${join15(this.opts.config.stateDir, "sessions", id)})`
6448
9335
  );
6449
9336
  });
6450
9337
  }
@@ -6476,6 +9363,15 @@ var RunnerDaemon = class {
6476
9363
  }
6477
9364
  await this.ack(cmd.id, ack);
6478
9365
  }
9366
+ /** A job command: handled (in order, per job) and acknowledged. */
9367
+ async dispatchJob(cmd) {
9368
+ this.opts.logger.debug(`job command ${cmd.type}`, { id: cmd.id, job: cmd.jobId });
9369
+ const ack = await this.manager.handleJob(cmd);
9370
+ if (!ack.ok) {
9371
+ this.opts.logger.warn(`${cmd.type} for job ${cmd.jobId} refused`, { error: ack.error });
9372
+ }
9373
+ await this.ack(cmd.id, ack);
9374
+ }
6479
9375
  /**
6480
9376
  * A slot to run a completion in: at once while fewer than the runner's session limit run,
6481
9377
  * else after the next one ends. False when `cancelled` fires first: the request leaves
@@ -6487,15 +9383,15 @@ var RunnerDaemon = class {
6487
9383
  this.completionsRunning++;
6488
9384
  return Promise.resolve(true);
6489
9385
  }
6490
- return new Promise((resolve2) => {
9386
+ return new Promise((resolve4) => {
6491
9387
  const handOver = () => {
6492
9388
  cancelled.removeEventListener("abort", leave);
6493
- resolve2(true);
9389
+ resolve4(true);
6494
9390
  };
6495
9391
  const leave = () => {
6496
9392
  const at = this.completionWaiters.indexOf(handOver);
6497
9393
  if (at >= 0) this.completionWaiters.splice(at, 1);
6498
- resolve2(false);
9394
+ resolve4(false);
6499
9395
  };
6500
9396
  this.completionWaiters.push(handOver);
6501
9397
  cancelled.addEventListener("abort", leave, { once: true });
@@ -6670,67 +9566,8 @@ function formatChecks(checks) {
6670
9566
  return checks.map((c) => `${mark[c.level]} ${c.name}: ${c.detail}`).join("\n");
6671
9567
  }
6672
9568
 
6673
- // src/lock.ts
6674
- import { mkdir as mkdir8, open, readFile as readFile5, rm as rm7 } from "node:fs/promises";
6675
- import { join as join14 } from "node:path";
6676
- function lockFile(stateDir) {
6677
- return join14(stateDir, "daemon.pid");
6678
- }
6679
- function pidAlive(pid) {
6680
- if (!Number.isInteger(pid) || pid <= 0) return false;
6681
- try {
6682
- process.kill(pid, 0);
6683
- return true;
6684
- } catch (err) {
6685
- return err.code === "EPERM";
6686
- }
6687
- }
6688
- async function lockHolder(stateDir) {
6689
- let raw;
6690
- try {
6691
- raw = await readFile5(lockFile(stateDir), "utf8");
6692
- } catch {
6693
- return null;
6694
- }
6695
- const pid = Number.parseInt(raw.trim(), 10);
6696
- return pidAlive(pid) && pid !== process.pid ? pid : null;
6697
- }
6698
- async function acquireDaemonLock(stateDir, pid = process.pid) {
6699
- await mkdir8(stateDir, { recursive: true, mode: 448 });
6700
- const file = lockFile(stateDir);
6701
- for (let attempt = 0; attempt < 3; attempt++) {
6702
- try {
6703
- const handle = await open(file, "wx", 384);
6704
- try {
6705
- await handle.writeFile(`${pid}
6706
- `);
6707
- } finally {
6708
- await handle.close();
6709
- }
6710
- return {
6711
- ok: true,
6712
- lock: {
6713
- file,
6714
- async release() {
6715
- const current2 = await readFile5(file, "utf8").catch(() => "");
6716
- if (Number.parseInt(current2.trim(), 10) === pid) await rm7(file, { force: true });
6717
- }
6718
- }
6719
- };
6720
- } catch (err) {
6721
- if (err.code !== "EEXIST") throw err;
6722
- }
6723
- const raw = await readFile5(file, "utf8").catch(() => null);
6724
- if (raw === null) continue;
6725
- const holder = Number.parseInt(raw.trim(), 10);
6726
- if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
6727
- await rm7(file, { force: true });
6728
- }
6729
- return { ok: false, pid: null };
6730
- }
6731
-
6732
9569
  // src/pairing.ts
6733
- import { spawn as spawn5 } from "node:child_process";
9570
+ import { spawn as spawn6 } from "node:child_process";
6734
9571
  async function pair(api, opts) {
6735
9572
  const start2 = await api.startPairing({ name: opts.name, platform: RUNNER_PLATFORM });
6736
9573
  opts.ui.showCode(start2.userCode, start2.verificationUrl, start2.expiresInSeconds);
@@ -6794,7 +9631,7 @@ function openUrl(url) {
6794
9631
  if (!/^https?:\/\//i.test(url)) return;
6795
9632
  const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
6796
9633
  try {
6797
- const child = spawn5(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
9634
+ const child = spawn6(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
6798
9635
  child.on("error", () => void 0);
6799
9636
  child.unref();
6800
9637
  } catch {
@@ -6810,8 +9647,9 @@ Usage:
6810
9647
  dt-runner login [--server <url>] [--name <name>] [--no-browser] [--yes]
6811
9648
  Pair this computer with your Discovery Tree account.
6812
9649
  --yes skips the "is this your account?" question.
6813
- dt-runner start [--max-sessions <n>] [--repos-dir <dir>] [--json] [--verbose]
6814
- Run: wait for agent sessions and run them with Claude Code.
9650
+ dt-runner start [--max-sessions <n>] [--max-jobs <n>] [--repos-dir <dir>] [--json] [--verbose]
9651
+ Run: wait for agent sessions and run them with Claude Code,
9652
+ and run the jobs you approve (up to --max-jobs at once).
6815
9653
  dt-runner status Show the configuration and check the connection.
6816
9654
  dt-runner doctor Check Node.js, git and Claude Code on this computer.
6817
9655
  dt-runner logout Forget this runner's token (deletes the config file).
@@ -6841,6 +9679,7 @@ async function main(argv) {
6841
9679
  "no-browser": { type: "boolean" },
6842
9680
  yes: { type: "boolean", short: "y" },
6843
9681
  "max-sessions": { type: "string" },
9682
+ "max-jobs": { type: "string" },
6844
9683
  "repos-dir": { type: "string" },
6845
9684
  json: { type: "boolean" },
6846
9685
  verbose: { type: "boolean" },
@@ -6863,6 +9702,7 @@ async function main(argv) {
6863
9702
  case "start":
6864
9703
  return start({
6865
9704
  maxSessions: values["max-sessions"] !== void 0 ? Number(values["max-sessions"]) : void 0,
9705
+ maxJobs: values["max-jobs"] !== void 0 ? Number(values["max-jobs"]) : void 0,
6866
9706
  reposDir: values["repos-dir"],
6867
9707
  json: values.json,
6868
9708
  verbose: values.verbose
@@ -6947,6 +9787,7 @@ async function start(opts) {
6947
9787
  const paths = runnerPaths();
6948
9788
  const config = resolveConfig(await readConfigFile(paths.configFile), {
6949
9789
  maxSessions: opts.maxSessions,
9790
+ maxJobs: opts.maxJobs,
6950
9791
  reposDir: opts.reposDir
6951
9792
  });
6952
9793
  if (!config.token) {
@@ -7009,7 +9850,7 @@ async function start(opts) {
7009
9850
  signals++;
7010
9851
  if (signals === 1) {
7011
9852
  logger.info(
7012
- `${sig}: stopping (Claude Code processes end, sessions stay resumable). Press Ctrl+C again to force.`
9853
+ `${sig}: stopping (Claude Code processes end, sessions stay resumable, jobs keep running). Press Ctrl+C again to force.`
7013
9854
  );
7014
9855
  daemon.stop();
7015
9856
  } else {
@@ -7043,6 +9884,7 @@ async function status() {
7043
9884
  console.log(
7044
9885
  `Sessions: up to ${config.maxSessions} at once, permission mode ${config.permissionMode}`
7045
9886
  );
9887
+ console.log(`Jobs: up to ${config.maxJobs} at once`);
7046
9888
  console.log(`Repos: ${config.reposDir}`);
7047
9889
  console.log(`Worktrees: ${config.worktreesDir}`);
7048
9890
  console.log(`State: ${config.stateDir}`);