@discovery-tree/runner 0.1.15 → 0.1.16

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 +89 -14
  2. package/dist/cli.js +2494 -1015
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  // src/cli.ts
4
4
  import { hostname } from "node:os";
5
- import { createInterface as createInterface2 } from "node:readline/promises";
5
+ import { createInterface as createInterface3 } from "node:readline/promises";
6
6
  import { parseArgs } from "node:util";
7
7
 
8
8
  // ../contracts/src/agent-config.ts
@@ -115,7 +115,7 @@ function toolGrantRepositoryKey(url) {
115
115
  }
116
116
 
117
117
  // src/version.ts
118
- var RUNNER_VERSION = true ? "0.1.15" : "0.0.0-dev";
118
+ var RUNNER_VERSION = true ? "0.1.16" : "0.0.0-dev";
119
119
  var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
120
120
 
121
121
  // src/api.ts
@@ -248,15 +248,247 @@ import { tmpdir } from "node:os";
248
248
  import { isAbsolute as isAbsolute2, join as join3 } from "node:path";
249
249
 
250
250
  // src/exec.ts
251
- import { spawn as spawn2 } from "node:child_process";
251
+ import { spawn as spawn3 } from "node:child_process";
252
252
  import { access, constants } from "node:fs/promises";
253
253
  import { delimiter, isAbsolute, join } from "node:path";
254
254
 
255
255
  // src/process-tree.ts
256
- import { spawn, spawnSync } from "node:child_process";
256
+ import { spawn as spawn2, spawnSync } from "node:child_process";
257
+
258
+ // src/windows-job.ts
259
+ import { spawn } from "node:child_process";
260
+ import { createInterface } from "node:readline";
261
+ var HELPER_SCRIPT = String.raw`
262
+ $ErrorActionPreference = 'Stop'
263
+ Add-Type -TypeDefinition @'
264
+ using System;
265
+ using System.Collections.Generic;
266
+ using System.Runtime.InteropServices;
267
+ public static class DtRunnerJobs {
268
+ [StructLayout(LayoutKind.Sequential)]
269
+ struct Basic { public long A; public long B; public uint LimitFlags; public UIntPtr C; public UIntPtr D; public uint E; public UIntPtr F; public uint G; public uint H; }
270
+ [StructLayout(LayoutKind.Sequential)]
271
+ struct Io { public ulong A, B, C, D, E, F; }
272
+ [StructLayout(LayoutKind.Sequential)]
273
+ struct Extended { public Basic Basic; public Io Io; public UIntPtr A, B, C, D; }
274
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
275
+ static extern IntPtr CreateJobObjectW(IntPtr attributes, string name);
276
+ [DllImport("kernel32.dll", SetLastError = true)]
277
+ static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref Extended info, uint size);
278
+ [DllImport("kernel32.dll", SetLastError = true)]
279
+ static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
280
+ [DllImport("kernel32.dll", SetLastError = true)]
281
+ static extern bool TerminateJobObject(IntPtr job, uint exitCode);
282
+ [DllImport("kernel32.dll", SetLastError = true)]
283
+ static extern IntPtr OpenProcess(uint access, bool inherit, uint pid);
284
+ [DllImport("kernel32.dll", SetLastError = true)]
285
+ static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user);
286
+ [DllImport("kernel32.dll", SetLastError = true)]
287
+ static extern bool CloseHandle(IntPtr handle);
288
+ static readonly Dictionary<string, IntPtr> jobs = new Dictionary<string, IntPtr>();
289
+ static string Assign(string id, uint pid, long notAfterMs) {
290
+ IntPtr job = CreateJobObjectW(IntPtr.Zero, null);
291
+ if (job == IntPtr.Zero) return "err " + id + " CreateJobObject " + Marshal.GetLastWin32Error();
292
+ Extended info = new Extended();
293
+ info.Basic.LimitFlags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
294
+ if (!SetInformationJobObject(job, 9, ref info, (uint)Marshal.SizeOf(typeof(Extended)))) {
295
+ int e = Marshal.GetLastWin32Error();
296
+ CloseHandle(job);
297
+ return "err " + id + " SetInformationJobObject " + e;
298
+ }
299
+ // PROCESS_SET_QUOTA | PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION
300
+ IntPtr process = OpenProcess(0x1101, false, pid);
301
+ if (process == IntPtr.Zero) {
302
+ int e = Marshal.GetLastWin32Error();
303
+ CloseHandle(job);
304
+ return "err " + id + " OpenProcess " + e;
305
+ }
306
+ // A process created after the one we were told about holds a reused pid: not ours.
307
+ long creation, exit, kernel, user;
308
+ if (!GetProcessTimes(process, out creation, out exit, out kernel, out user) ||
309
+ (DateTime.FromFileTimeUtc(creation) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds > notAfterMs) {
310
+ CloseHandle(process);
311
+ CloseHandle(job);
312
+ return "err " + id + " not the process asked for";
313
+ }
314
+ bool ok = AssignProcessToJobObject(job, process);
315
+ int error = Marshal.GetLastWin32Error();
316
+ CloseHandle(process);
317
+ if (!ok) {
318
+ CloseHandle(job);
319
+ return "err " + id + " AssignProcessToJobObject " + error;
320
+ }
321
+ jobs[id] = job;
322
+ return "ok " + id;
323
+ }
324
+ static string Kill(string id) {
325
+ IntPtr job;
326
+ if (jobs.TryGetValue(id, out job)) {
327
+ jobs.Remove(id);
328
+ TerminateJobObject(job, 1);
329
+ CloseHandle(job);
330
+ }
331
+ return "killed " + id;
332
+ }
333
+ public static string Run(string line) {
334
+ string[] parts = line.Split(' ');
335
+ if (parts.Length == 4 && parts[0] == "assign") return Assign(parts[1], UInt32.Parse(parts[2]), Int64.Parse(parts[3]));
336
+ if (parts.Length == 2 && parts[0] == "kill") return Kill(parts[1]);
337
+ return "err ? unknown request";
338
+ }
339
+ }
340
+ '@
341
+ [Console]::Out.WriteLine('ready')
342
+ [Console]::Out.Flush()
343
+ while ($true) {
344
+ $line = [Console]::In.ReadLine()
345
+ if ($null -eq $line) { break }
346
+ try { $answer = [DtRunnerJobs]::Run($line) } catch { $answer = 'err ? ' + ($_ -replace '[\r\n]', ' ') }
347
+ [Console]::Out.WriteLine($answer)
348
+ [Console]::Out.Flush()
349
+ }
350
+ `;
351
+ var READY_TIMEOUT_MS = 3e4;
352
+ var ANSWER_TIMEOUT_MS = 1e4;
353
+ var JobHelper = class {
354
+ ready;
355
+ child;
356
+ waiting = /* @__PURE__ */ new Map();
357
+ exited = false;
358
+ constructor() {
359
+ this.child = spawn(
360
+ "powershell.exe",
361
+ [
362
+ "-NoLogo",
363
+ "-NoProfile",
364
+ "-NonInteractive",
365
+ "-ExecutionPolicy",
366
+ "Bypass",
367
+ "-EncodedCommand",
368
+ Buffer.from(HELPER_SCRIPT, "utf16le").toString("base64")
369
+ ],
370
+ { stdio: ["pipe", "pipe", "ignore"], windowsHide: true }
371
+ );
372
+ let onReady = () => void 0;
373
+ this.ready = new Promise((resolve2) => {
374
+ const timer = setTimeout(() => resolve2(false), READY_TIMEOUT_MS);
375
+ timer.unref();
376
+ onReady = (ok) => {
377
+ clearTimeout(timer);
378
+ resolve2(ok);
379
+ };
380
+ });
381
+ const lines = createInterface({ input: this.child.stdout, crlfDelay: Infinity });
382
+ lines.on("line", (line) => {
383
+ const text = line.trim();
384
+ if (text === "ready") return onReady(true);
385
+ const id = text.split(" ")[1];
386
+ const answer = id ? this.waiting.get(id) : void 0;
387
+ if (answer) {
388
+ this.waiting.delete(id);
389
+ answer(text);
390
+ }
391
+ });
392
+ const gone = () => {
393
+ if (this.exited) return;
394
+ this.exited = true;
395
+ onReady(false);
396
+ for (const answer of this.waiting.values()) answer("err gone");
397
+ this.waiting.clear();
398
+ if (helper === this) helper = null;
399
+ };
400
+ this.child.on("error", gone);
401
+ this.child.on("exit", gone);
402
+ this.child.stdin.on("error", () => void 0);
403
+ this.child.unref();
404
+ this.child.stdout.unref?.();
405
+ this.child.stdin.unref?.();
406
+ }
407
+ get alive() {
408
+ return !this.exited;
409
+ }
410
+ /** Puts the process in a job of its own; resolves to the job's id, or null when it could not. */
411
+ async assign(target, startedBy) {
412
+ if (!await this.ready) return null;
413
+ if (!target.pid || target.exitCode !== null || target.signalCode !== null) return null;
414
+ const id = `j${++jobSeq}`;
415
+ const answer = await this.ask(`assign ${id} ${target.pid} ${Math.ceil(startedBy)}`, id);
416
+ return answer.startsWith("ok ") ? id : null;
417
+ }
418
+ /** Ends every process in the job, and the job. */
419
+ async kill(id) {
420
+ if (!await this.ready) return;
421
+ await this.ask(`kill ${id}`, id);
422
+ }
423
+ /** Ends the helper, and with it every job it holds. Synchronous: safe in an exit hook. */
424
+ close() {
425
+ if (this.exited) return;
426
+ try {
427
+ this.child.kill();
428
+ } catch {
429
+ }
430
+ }
431
+ ask(request, id) {
432
+ if (this.exited) return Promise.resolve("err gone");
433
+ return new Promise((resolve2) => {
434
+ const timer = setTimeout(() => {
435
+ this.waiting.delete(id);
436
+ resolve2("err timeout");
437
+ }, ANSWER_TIMEOUT_MS);
438
+ timer.unref();
439
+ this.waiting.set(id, (answer) => {
440
+ clearTimeout(timer);
441
+ resolve2(answer);
442
+ });
443
+ this.child.stdin.write(request + "\n");
444
+ });
445
+ }
446
+ };
447
+ var helper = null;
448
+ var jobSeq = 0;
449
+ var disabled = process.platform !== "win32";
450
+ function current() {
451
+ if (disabled) return null;
452
+ if (!helper || !helper.alive) helper = new JobHelper();
453
+ return helper;
454
+ }
455
+ async function startJobHelper() {
456
+ const h = current();
457
+ if (!h) return false;
458
+ const ok = await h.ready;
459
+ if (!ok) {
460
+ disabled = true;
461
+ h.close();
462
+ }
463
+ return ok;
464
+ }
465
+ async function assignToJob(target, startedBy) {
466
+ const h = current();
467
+ if (!h) return null;
468
+ try {
469
+ return await h.assign(target, startedBy);
470
+ } catch {
471
+ return null;
472
+ }
473
+ }
474
+ async function terminateJob(id) {
475
+ if (!id || !helper) return;
476
+ try {
477
+ await helper.kill(id);
478
+ } catch {
479
+ }
480
+ }
481
+ function closeJobHelper() {
482
+ helper?.close();
483
+ }
484
+
485
+ // src/process-tree.ts
257
486
  var OWN_PROCESS_GROUP = process.platform !== "win32";
258
487
  var liveTrees = /* @__PURE__ */ new Map();
259
488
  var exitHookInstalled = false;
489
+ var CENSUS_INTERVAL_MS = 3e4;
490
+ var censusTimer = null;
491
+ var censusRunning = false;
260
492
  function trackTree(child, cwd) {
261
493
  if (!child.pid) return null;
262
494
  const tree = {
@@ -264,11 +496,20 @@ function trackTree(child, cwd) {
264
496
  startedAt: Date.now() - 2e3,
265
497
  ...cwd ? { cwd } : {}
266
498
  };
267
- liveTrees.set(child.pid, { ...tree, child });
499
+ liveTrees.set(child.pid, { tree, child });
500
+ if (!OWN_PROCESS_GROUP) {
501
+ const startedBy = Date.now() + 1e3;
502
+ tree.job = assignToJob(child, startedBy);
503
+ startCensus();
504
+ }
268
505
  if (!exitHookInstalled) {
269
506
  exitHookInstalled = true;
270
507
  process.once("exit", () => {
271
- for (const { pid, child: root } of liveTrees.values()) {
508
+ closeJobHelper();
509
+ for (const {
510
+ tree: { pid },
511
+ child: root
512
+ } of liveTrees.values()) {
272
513
  if (OWN_PROCESS_GROUP) signalGroup(pid, "SIGKILL");
273
514
  else if (root.exitCode === null && root.signalCode === null) {
274
515
  spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], {
@@ -289,7 +530,7 @@ function signalTree(child, signal) {
289
530
  return;
290
531
  }
291
532
  if (signal === "SIGKILL") {
292
- const tk = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
533
+ const tk = spawn2("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
293
534
  stdio: "ignore",
294
535
  windowsHide: true
295
536
  });
@@ -320,14 +561,68 @@ async function reapTree(tree, graceMs = 2e3, deps = {}) {
320
561
  signalGroup(tree.pid, "SIGKILL");
321
562
  return;
322
563
  }
564
+ await (deps.terminateJob ?? terminateJob)(await tree.job);
323
565
  const rows = await (deps.listProcesses ?? listWindowsProcesses)();
324
566
  const orphans = descendantsOf(tree, rows);
325
567
  if (orphans.length) await (deps.kill ?? taskkillTrees)(orphans);
326
568
  } catch {
327
569
  } finally {
328
- if (liveTrees.get(tree.pid)?.startedAt === tree.startedAt) liveTrees.delete(tree.pid);
570
+ if (liveTrees.get(tree.pid)?.tree.startedAt === tree.startedAt) liveTrees.delete(tree.pid);
571
+ if (liveTrees.size === 0) stopCensus();
572
+ }
573
+ }
574
+ function recordDescendants(tree, rows) {
575
+ const byPid = new Map(rows.map((r) => [r.pid, r]));
576
+ const seen = tree.seen ?? /* @__PURE__ */ new Map();
577
+ for (const [pid, createdAt] of seen) {
578
+ if (!sameProcess(byPid.get(pid), createdAt)) seen.delete(pid);
579
+ }
580
+ for (const pid of descendantsOf(tree, rows)) {
581
+ const row = byPid.get(pid);
582
+ if (row) seen.set(pid, row.createdAt);
583
+ }
584
+ tree.seen = seen;
585
+ }
586
+ async function snapshotTree(tree, deps = {}, timeoutMs = 5e3) {
587
+ if (!tree || OWN_PROCESS_GROUP) return;
588
+ let timer;
589
+ try {
590
+ const rows = await Promise.race([
591
+ (deps.listProcesses ?? listWindowsProcesses)(),
592
+ new Promise((r) => timer = setTimeout(() => r(null), timeoutMs))
593
+ ]);
594
+ if (rows) recordDescendants(tree, rows);
595
+ } catch {
596
+ } finally {
597
+ if (timer) clearTimeout(timer);
598
+ }
599
+ }
600
+ function startCensus() {
601
+ if (censusTimer) return;
602
+ censusTimer = setInterval(() => void census(), CENSUS_INTERVAL_MS);
603
+ censusTimer.unref();
604
+ }
605
+ function stopCensus() {
606
+ if (!censusTimer) return;
607
+ clearInterval(censusTimer);
608
+ censusTimer = null;
609
+ }
610
+ async function census() {
611
+ if (censusRunning || liveTrees.size === 0) return;
612
+ censusRunning = true;
613
+ try {
614
+ const rows = await listWindowsProcesses();
615
+ for (const { tree, child } of liveTrees.values()) {
616
+ if (child.exitCode === null && child.signalCode === null) recordDescendants(tree, rows);
617
+ }
618
+ } catch {
619
+ } finally {
620
+ censusRunning = false;
329
621
  }
330
622
  }
623
+ function sameProcess(row, createdAt) {
624
+ return !!row && Math.abs(row.createdAt - createdAt) <= 1e3;
625
+ }
331
626
  function descendantsOf(tree, rows) {
332
627
  const byParent = /* @__PURE__ */ new Map();
333
628
  const byPid = /* @__PURE__ */ new Map();
@@ -344,9 +639,18 @@ function descendantsOf(tree, rows) {
344
639
  const queue = [
345
640
  { pid: tree.pid, since: tree.startedAt, until: reusedAt }
346
641
  ];
642
+ if (tree.seen) {
643
+ for (const [pid, createdAt] of tree.seen) {
644
+ const row = byPid.get(pid);
645
+ if (seen.has(pid) || !sameProcess(row, createdAt)) continue;
646
+ seen.add(pid);
647
+ out.push(pid);
648
+ queue.push({ pid, since: row.createdAt - 1e3, until: null });
649
+ }
650
+ }
347
651
  if (tree.cwd) {
348
652
  for (const row of rows) {
349
- if (row.pid === tree.pid || row.createdAt < tree.startedAt) continue;
653
+ if (seen.has(row.pid) || row.createdAt < tree.startedAt) continue;
350
654
  const parent = byPid.get(row.ppid);
351
655
  const orphaned = !parent || parent.createdAt > row.createdAt;
352
656
  if (orphaned && namesPathIn(row.commandLine, tree.cwd)) {
@@ -386,7 +690,7 @@ function namesPathIn(commandLine, dir) {
386
690
  function listWindowsProcesses() {
387
691
  const script = `$ErrorActionPreference='SilentlyContinue';Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { "$($_.ProcessId) $($_.ParentProcessId) $(([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()) $($_.CommandLine -replace "[\\r\\n]", " ")" } }`;
388
692
  return new Promise((resolve2, reject) => {
389
- const ps = spawn(
693
+ const ps = spawn2(
390
694
  "powershell.exe",
391
695
  ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
392
696
  { stdio: ["ignore", "pipe", "ignore"], windowsHide: true }
@@ -423,7 +727,7 @@ async function taskkillTrees(pids) {
423
727
  for (let i = 0; i < pids.length; i += 50) {
424
728
  const args = pids.slice(i, i + 50).flatMap((p) => ["/pid", String(p)]);
425
729
  await new Promise((resolve2) => {
426
- const tk = spawn("taskkill", [...args, "/T", "/F"], { stdio: "ignore", windowsHide: true });
730
+ const tk = spawn2("taskkill", [...args, "/T", "/F"], { stdio: "ignore", windowsHide: true });
427
731
  tk.on("error", () => resolve2());
428
732
  tk.on("close", () => resolve2());
429
733
  });
@@ -441,7 +745,7 @@ function signalGroup(pgid, signal) {
441
745
  // src/exec.ts
442
746
  function exec(cmd, args, opts = {}) {
443
747
  return new Promise((resolve2, reject) => {
444
- const child = spawn2(cmd, args, {
748
+ const child = spawn3(cmd, args, {
445
749
  cwd: opts.cwd,
446
750
  env: opts.env ?? process.env,
447
751
  stdio: ["pipe", "pipe", "pipe"],
@@ -642,11 +946,11 @@ async function prepareWorktree(input) {
642
946
  ]);
643
947
  } else {
644
948
  const wanted = cloneUrl(ref, input.protocol);
645
- const current = await exec("git", ["config", "--get", "remote.origin.url"], {
949
+ const current2 = await exec("git", ["config", "--get", "remote.origin.url"], {
646
950
  cwd: repoDir,
647
951
  env: gitEnv()
648
952
  });
649
- if (current.stdout.trim() !== wanted) {
953
+ if (current2.stdout.trim() !== wanted) {
650
954
  await git(repoDir, ["remote", "set-url", "origin", wanted]);
651
955
  }
652
956
  await git(repoDir, ["fetch", "--prune", "origin"]);
@@ -868,17 +1172,17 @@ async function ensureEvidenceDir(worktree) {
868
1172
  const rel = await git(worktree, ["rev-parse", "--git-path", "info/exclude"]);
869
1173
  const file = isAbsolute2(rel) ? rel : join3(worktree, rel);
870
1174
  const line = `/${EVIDENCE_DIR}/`;
871
- let current = "";
1175
+ let current2 = "";
872
1176
  try {
873
- current = await readFile(file, "utf8");
1177
+ current2 = await readFile(file, "utf8");
874
1178
  } catch {
875
1179
  }
876
- if (current.split("\n").some((l) => l.trim() === line)) return;
1180
+ if (current2.split("\n").some((l) => l.trim() === line)) return;
877
1181
  await mkdir2(join3(file, ".."), { recursive: true });
878
- const sep2 = current && !current.endsWith("\n") ? "\n" : "";
1182
+ const sep2 = current2 && !current2.endsWith("\n") ? "\n" : "";
879
1183
  await writeFile(
880
1184
  file,
881
- `${current}${sep2}# Screenshots dt-runner publishes on their own branch
1185
+ `${current2}${sep2}# Screenshots dt-runner publishes on their own branch
882
1186
  ${line}
883
1187
  `
884
1188
  );
@@ -1267,69 +1571,1611 @@ function runnerSystemPrompt(input) {
1267
1571
  ].join(" ");
1268
1572
  }
1269
1573
 
1270
- // src/config.ts
1271
- import { chmod, mkdir as mkdir3, readFile as readFile2, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
1574
+ // src/claude-code-rules.ts
1575
+ import { readFile as readFile2, stat as stat3 } from "node:fs/promises";
1272
1576
  import { homedir } from "node:os";
1273
- import { dirname as dirname2, join as join5 } from "node:path";
1274
-
1275
- // src/invocation.ts
1276
- var RUNNER_PACKAGE = "@discovery-tree/runner";
1277
- function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
1278
- if (env.npm_command === "exec") return true;
1279
- return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
1577
+ import { dirname as dirname2, isAbsolute as isAbsolute3, join as join5, resolve, sep } from "node:path";
1578
+ var EMPTY = { allow: [], deny: [], ask: [], sources: [] };
1579
+ var RULE_SHAPE2 = /^(?:mcp__[A-Za-z0-9_-]+__\*|[A-Za-z][A-Za-z0-9_.-]*(?:\([\s\S]*\))?)$/;
1580
+ var FILE_TOOLS = /* @__PURE__ */ new Set([
1581
+ "Read",
1582
+ "Edit",
1583
+ "Write",
1584
+ "MultiEdit",
1585
+ "NotebookEdit",
1586
+ "Glob",
1587
+ "Grep",
1588
+ "LS"
1589
+ ]);
1590
+ function usableRule(raw, kind, committed) {
1591
+ if (typeof raw !== "string") return null;
1592
+ const rule = raw.trim();
1593
+ if (!rule || rule.length > TOOL_GRANT_RULE_MAX_LENGTH) return null;
1594
+ if (/[\u0000-\u001f\u007f]/.test(rule) || !RULE_SHAPE2.test(rule)) return null;
1595
+ const tool = /^([A-Za-z][A-Za-z0-9_.-]*)/.exec(rule)?.[1] ?? "";
1596
+ if (kind === "allow" && FILE_TOOLS.has(tool)) return null;
1597
+ if (kind === "allow" && committed && toolGrantRuleProblem(rule) !== null) return null;
1598
+ return rule;
1280
1599
  }
1281
- function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
1282
- return viaNpx ? `npx ${RUNNER_PACKAGE}@latest ${subcommand}` : `dt-runner ${subcommand}`;
1600
+ function remoteRepositoryKey(url) {
1601
+ const u = url.trim();
1602
+ const ssh = /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
1603
+ if (ssh) return toolGrantRepositoryKey(`https://github.com/${ssh[1]}/${ssh[2]}`);
1604
+ const https = /^(?:https?|git):\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
1605
+ if (https) return toolGrantRepositoryKey(`https://github.com/${https[1]}/${https[2]}`);
1606
+ return null;
1283
1607
  }
1284
-
1285
- // src/config.ts
1286
- function runnerPaths(env = process.env) {
1287
- const home = homedir();
1288
- if (process.platform === "win32") {
1289
- const roaming = env.APPDATA || join5(home, "AppData", "Roaming");
1290
- const local = env.LOCALAPPDATA || join5(home, "AppData", "Local");
1608
+ async function readText(file) {
1609
+ try {
1610
+ return await readFile2(file, "utf8");
1611
+ } catch {
1612
+ return null;
1613
+ }
1614
+ }
1615
+ async function readJsonFile(file) {
1616
+ const text = await readText(file);
1617
+ if (text === null) return null;
1618
+ try {
1619
+ return JSON.parse(text);
1620
+ } catch {
1621
+ return null;
1622
+ }
1623
+ }
1624
+ async function isDir(path) {
1625
+ try {
1626
+ return (await stat3(path)).isDirectory();
1627
+ } catch {
1628
+ return false;
1629
+ }
1630
+ }
1631
+ async function gitConfigOf(folder) {
1632
+ let dir = folder;
1633
+ for (let i = 0; i < 6; i++) {
1634
+ const dotGit = join5(dir, ".git");
1635
+ if (await isDir(dotGit)) return { config: join5(dotGit, "config"), roots: [dir] };
1636
+ const pointer = await readText(dotGit);
1637
+ const gitdir = pointer && /^gitdir:\s*(.+)\s*$/m.exec(pointer)?.[1];
1638
+ if (gitdir) {
1639
+ const linked = resolve(dir, gitdir);
1640
+ const common = (await readText(join5(linked, "commondir")))?.trim();
1641
+ const commonDir = common ? resolve(linked, common) : linked;
1642
+ return { config: join5(commonDir, "config"), roots: [dir, dirname2(commonDir)] };
1643
+ }
1644
+ const up = dirname2(dir);
1645
+ if (up === dir) break;
1646
+ dir = up;
1647
+ }
1648
+ return null;
1649
+ }
1650
+ function remoteKeys(config) {
1651
+ const keys = /* @__PURE__ */ new Set();
1652
+ let inRemote = false;
1653
+ for (const line of config.split(/\r?\n/)) {
1654
+ const section = /^\s*\[([^\]]*)\]/.exec(line);
1655
+ if (section) {
1656
+ inRemote = /^remote\s+"/i.test(section[1].trim());
1657
+ continue;
1658
+ }
1659
+ if (!inRemote) continue;
1660
+ const url = /^\s*url\s*=\s*(.+?)\s*$/i.exec(line);
1661
+ const key = url ? remoteRepositoryKey(url[1]) : null;
1662
+ if (key) keys.add(key);
1663
+ }
1664
+ return keys;
1665
+ }
1666
+ function rulesIn(settings, kind, committed) {
1667
+ const perms = settings?.permissions;
1668
+ const list = perms?.[kind];
1669
+ if (!Array.isArray(list)) return [];
1670
+ return list.map((r) => usableRule(r, kind, committed)).filter((r) => r !== null);
1671
+ }
1672
+ var ClaudeCodeRules = class {
1673
+ claudeJson;
1674
+ exclude;
1675
+ cacheMs;
1676
+ cache = /* @__PURE__ */ new Map();
1677
+ constructor(opts = {}) {
1678
+ this.claudeJson = opts.claudeJson ?? (process.env.CLAUDE_CONFIG_DIR ? join5(process.env.CLAUDE_CONFIG_DIR, ".claude.json") : join5(homedir(), ".claude.json"));
1679
+ this.exclude = (opts.exclude ?? []).map((p) => resolve(p));
1680
+ this.cacheMs = opts.cacheMs ?? 3e4;
1681
+ }
1682
+ /** The rules for a repository URL; none for a session without a GitHub repository. */
1683
+ rulesFor(repositoryUrl) {
1684
+ const key = toolGrantRepositoryKey(repositoryUrl);
1685
+ if (!key) return Promise.resolve(EMPTY);
1686
+ const hit = this.cache.get(key);
1687
+ if (hit && Date.now() - hit.at < this.cacheMs) return hit.rules;
1688
+ const rules = this.read(key).catch(() => EMPTY);
1689
+ this.cache.set(key, { at: Date.now(), rules });
1690
+ return rules;
1691
+ }
1692
+ excluded(folder) {
1693
+ const f = resolve(folder);
1694
+ return this.exclude.some((ex) => f === ex || f.startsWith(ex + sep));
1695
+ }
1696
+ async read(key) {
1697
+ const global = await readJsonFile(this.claudeJson);
1698
+ const projects = global?.projects;
1699
+ if (!projects || typeof projects !== "object") return EMPTY;
1700
+ const allow = /* @__PURE__ */ new Set();
1701
+ const deny = /* @__PURE__ */ new Set();
1702
+ const ask = /* @__PURE__ */ new Set();
1703
+ const sources = [];
1704
+ const checkouts = [];
1705
+ for (const [folder, entry] of Object.entries(projects)) {
1706
+ if (!entry || entry.hasTrustDialogAccepted !== true) continue;
1707
+ if (!isAbsolute3(folder) || this.excluded(folder)) continue;
1708
+ const git2 = await gitConfigOf(folder);
1709
+ const text = git2 ? await readText(git2.config) : null;
1710
+ if (!git2 || !text || !remoteKeys(text).has(key)) continue;
1711
+ const roots = [...new Set([folder, ...git2.roots].map((d) => resolve(d)))];
1712
+ const legacy = Array.isArray(entry.allowedTools) ? entry.allowedTools : [];
1713
+ checkouts.push({ folder, roots, legacy });
1714
+ }
1715
+ for (const { folder, roots, legacy } of checkouts) {
1716
+ const found = [];
1717
+ const denied = [];
1718
+ const asked = [];
1719
+ for (const dir of roots) {
1720
+ const local = await readJsonFile(join5(dir, ".claude", "settings.local.json"));
1721
+ const shared = await readJsonFile(join5(dir, ".claude", "settings.json"));
1722
+ found.push(...rulesIn(local, "allow", false), ...rulesIn(shared, "allow", true));
1723
+ denied.push(...rulesIn(local, "deny", false), ...rulesIn(shared, "deny", false));
1724
+ asked.push(...rulesIn(local, "ask", false), ...rulesIn(shared, "ask", false));
1725
+ }
1726
+ found.push(
1727
+ ...legacy.map((r) => usableRule(r, "allow", false)).filter((r) => r !== null)
1728
+ );
1729
+ const kept = found;
1730
+ if (kept.length || denied.length || asked.length) sources.push(folder);
1731
+ for (const r of kept) allow.add(r);
1732
+ for (const r of denied) deny.add(r);
1733
+ for (const r of asked) ask.add(r);
1734
+ }
1291
1735
  return {
1292
- configFile: join5(roaming, "discovery-tree", "runner.json"),
1293
- dataDir: join5(local, "discovery-tree", "runner"),
1294
- stateDir: join5(local, "discovery-tree", "runner", "state")
1736
+ allow: [...allow].filter((r) => !deny.has(r) && !ask.has(r)),
1737
+ deny: [...deny],
1738
+ ask: [...ask].filter((r) => !deny.has(r)),
1739
+ sources
1295
1740
  };
1296
1741
  }
1297
- const config = env.XDG_CONFIG_HOME || join5(home, ".config");
1298
- const data = env.XDG_DATA_HOME || join5(home, ".local", "share");
1299
- const state = env.XDG_STATE_HOME || join5(home, ".local", "state");
1300
- return {
1301
- configFile: join5(config, "discovery-tree", "runner.json"),
1302
- dataDir: join5(data, "discovery-tree", "runner"),
1303
- stateDir: join5(state, "discovery-tree", "runner")
1304
- };
1742
+ };
1743
+ function ruleHead(rule) {
1744
+ const m = /^([A-Za-z][A-Za-z0-9_.-]*(?:__\*)?)(?:\(([\s\S]*)\))?$/.exec(rule.trim());
1745
+ if (!m) return null;
1746
+ const spec = m[2];
1747
+ if (spec === void 0) return { tool: m[1], head: null };
1748
+ return { tool: m[1], head: spec.replace(/:\*$/, " *").split("*")[0] };
1305
1749
  }
1306
- var PERMISSION_MODES = [
1307
- "acceptEdits",
1308
- "auto",
1309
- "default",
1310
- "manual",
1311
- "dontAsk",
1312
- "plan",
1313
- "bypassPermissions"
1314
- ];
1315
- var DEFAULT_ALLOWED_TOOLS = [
1316
- "Read",
1317
- "Edit",
1318
- "MultiEdit",
1319
- "Write",
1320
- "Glob",
1321
- "Grep",
1322
- "LS",
1323
- "NotebookEdit",
1324
- "TodoWrite",
1325
- "Task",
1326
- // Stops a command started with the Bash tool's background option (a dev server); its
1327
- // output is a file the agent reads with Read.
1328
- "TaskStop",
1329
- "Bash(git status *)",
1330
- "Bash(git diff *)",
1331
- "Bash(git log *)",
1332
- "Bash(git show *)",
1750
+ function sameTool(a, b) {
1751
+ if (a === b) return true;
1752
+ const wild = (w, t) => w.endsWith("__*") && t.startsWith(w.slice(0, -1));
1753
+ return wild(a, b) || wild(b, a);
1754
+ }
1755
+ function overlapsAsk(allowRule, askRules) {
1756
+ const a = ruleHead(allowRule);
1757
+ if (!a) return false;
1758
+ return askRules.some((rule) => {
1759
+ const q = ruleHead(rule);
1760
+ if (!q || !sameTool(a.tool, q.tool)) return false;
1761
+ if (a.head === null || q.head === null) return true;
1762
+ return a.head.startsWith(q.head) || q.head.startsWith(a.head);
1763
+ });
1764
+ }
1765
+
1766
+ // src/permissions.ts
1767
+ import { randomUUID } from "node:crypto";
1768
+ function parseCanUseTool(line) {
1769
+ if (line?.type !== "control_request") return null;
1770
+ const req = line.request;
1771
+ if (!req || req.subtype !== "can_use_tool") return null;
1772
+ if (typeof line.request_id !== "string" || !line.request_id) return null;
1773
+ const toolName = typeof req.tool_name === "string" && req.tool_name ? req.tool_name : "tool";
1774
+ return { controlRequestId: line.request_id, toolName, input: req.input ?? {} };
1775
+ }
1776
+ function parseControlCancel(line) {
1777
+ if (line?.type !== "control_cancel_request") return null;
1778
+ return typeof line.request_id === "string" ? line.request_id : null;
1779
+ }
1780
+ function summarizeToolInput(toolName, input) {
1781
+ const i = input && typeof input === "object" ? input : {};
1782
+ const s = (v) => typeof v === "string" && v.trim() ? v : null;
1783
+ let summary = null;
1784
+ switch (toolName) {
1785
+ case "Bash":
1786
+ summary = s(i.command);
1787
+ break;
1788
+ case "WebFetch":
1789
+ summary = s(i.url);
1790
+ break;
1791
+ case "WebSearch":
1792
+ summary = s(i.query);
1793
+ break;
1794
+ case "Read":
1795
+ case "Edit":
1796
+ case "MultiEdit":
1797
+ case "Write":
1798
+ summary = s(i.file_path);
1799
+ break;
1800
+ case "NotebookEdit":
1801
+ summary = s(i.notebook_path);
1802
+ break;
1803
+ case "Glob":
1804
+ case "Grep":
1805
+ summary = s(i.pattern) ? `${i.pattern}${s(i.path) ? ` in ${i.path}` : ""}` : null;
1806
+ break;
1807
+ }
1808
+ if (summary === null) {
1809
+ try {
1810
+ summary = JSON.stringify(input) ?? "";
1811
+ } catch {
1812
+ summary = "";
1813
+ }
1814
+ }
1815
+ return cut(summary, AGENT_PERMISSION_INPUT_SUMMARY_MAX_LENGTH);
1816
+ }
1817
+ function cut(text, max) {
1818
+ return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
1819
+ }
1820
+ var PERMISSION_EXPIRED_TURN_ENDED = "The turn ended before anyone answered.";
1821
+ var PERMISSION_EXPIRED_INTERRUPTED = "The turn was interrupted before anyone answered.";
1822
+ var PERMISSION_EXPIRED_STOPPED = "Claude Code stopped before anyone answered.";
1823
+ var PERMISSION_EXPIRED_TIMEOUT = `Nobody answered within ${Math.round(
1824
+ RUNNER_PERMISSION_REQUEST_TIMEOUT_MS / 6e4
1825
+ )} minutes.`;
1826
+ var PERMISSION_EXPIRED_CANCELLED = "Claude Code stopped waiting for an answer.";
1827
+ var PERMISSION_EXPIRED_UNKNOWN = "The runner no longer has this request (it may have restarted), so the answer could not be applied.";
1828
+ var DENIED_MESSAGE = "The person denied permission for this tool call in Discovery Tree.";
1829
+ var SETTLED_KEPT = 200;
1830
+ var PermissionRelay = class {
1831
+ constructor(deps) {
1832
+ this.deps = deps;
1833
+ }
1834
+ pending = /* @__PURE__ */ new Map();
1835
+ byControlId = /* @__PURE__ */ new Map();
1836
+ settled = /* @__PURE__ */ new Map();
1837
+ get pendingCount() {
1838
+ return this.pending.size;
1839
+ }
1840
+ /** Claude Code asks; returns whether it was allowed at once or relayed. */
1841
+ request(req) {
1842
+ if (this.deps.alwaysAllowed().includes(req.toolName) || this.deps.grantedByRule?.(req.toolName, req.input)) {
1843
+ this.deps.respond(req.controlRequestId, { behavior: "allow", updatedInput: req.input });
1844
+ return "auto_allowed";
1845
+ }
1846
+ const id = (this.deps.newId ?? randomUUID)();
1847
+ const requestedAt = (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
1848
+ const timer = setTimeout(
1849
+ () => this.expire(id, PERMISSION_EXPIRED_TIMEOUT, true),
1850
+ this.deps.timeoutMs ?? RUNNER_PERMISSION_REQUEST_TIMEOUT_MS
1851
+ );
1852
+ timer.unref?.();
1853
+ const pending = {
1854
+ id,
1855
+ controlRequestId: req.controlRequestId,
1856
+ toolName: req.toolName,
1857
+ input: req.input,
1858
+ inputSummary: summarizeToolInput(req.toolName, req.input),
1859
+ requestedAt,
1860
+ timer
1861
+ };
1862
+ this.pending.set(id, pending);
1863
+ this.byControlId.set(req.controlRequestId, id);
1864
+ const suggestedRule = this.deps.suggestRule?.(req.toolName, req.input) ?? null;
1865
+ this.deps.emit({
1866
+ type: "permission_request",
1867
+ request: {
1868
+ id,
1869
+ toolName: pending.toolName,
1870
+ inputSummary: pending.inputSummary,
1871
+ ...suggestedRule ? { suggestedRule } : {},
1872
+ requestedAt,
1873
+ status: "pending"
1874
+ }
1875
+ });
1876
+ return "relayed";
1877
+ }
1878
+ /** A person's decision, from the server. */
1879
+ decide(requestId, decision) {
1880
+ const pending = this.pending.get(requestId);
1881
+ if (!pending) {
1882
+ const settled = this.settled.get(requestId);
1883
+ if (settled === "decided") return "already_applied";
1884
+ if (settled === void 0) {
1885
+ this.settle(requestId, "expired");
1886
+ this.deps.emit({
1887
+ type: "permission_request",
1888
+ request: {
1889
+ id: requestId,
1890
+ toolName: "tool",
1891
+ inputSummary: "",
1892
+ requestedAt: (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
1893
+ status: "expired",
1894
+ expiredReason: PERMISSION_EXPIRED_UNKNOWN
1895
+ }
1896
+ });
1897
+ }
1898
+ return "not_pending";
1899
+ }
1900
+ this.forget(pending);
1901
+ this.settle(requestId, "decided");
1902
+ if (decision.behavior === "allow") {
1903
+ if (decision.alwaysAllowTool && !this.deps.alwaysAllowed().includes(pending.toolName)) {
1904
+ this.deps.rememberAlwaysAllowed(pending.toolName);
1905
+ }
1906
+ const rule = decision.alwaysAllowRule?.trim();
1907
+ if (rule && toolGrantRuleProblem(rule) === null) this.deps.rememberRule?.(rule);
1908
+ this.deps.respond(pending.controlRequestId, {
1909
+ behavior: "allow",
1910
+ updatedInput: pending.input
1911
+ });
1912
+ } else {
1913
+ const message = decision.message?.trim();
1914
+ this.deps.respond(pending.controlRequestId, {
1915
+ behavior: "deny",
1916
+ message: message ? `${DENIED_MESSAGE} Their message: ${cut(message, AGENT_PERMISSION_MESSAGE_MAX_LENGTH)}` : DENIED_MESSAGE
1917
+ });
1918
+ }
1919
+ return "applied";
1920
+ }
1921
+ /** Claude Code withdrew a request (it stopped waiting): expired, nothing to answer. */
1922
+ cancel(controlRequestId) {
1923
+ const id = this.byControlId.get(controlRequestId);
1924
+ if (id) this.expire(id, PERMISSION_EXPIRED_CANCELLED, false);
1925
+ }
1926
+ /** Expire everything still waiting, answering Claude Code with a denial. */
1927
+ expireAll(reason) {
1928
+ for (const id of [...this.pending.keys()]) this.expire(id, reason, true);
1929
+ }
1930
+ expire(id, reason, answerClaude) {
1931
+ const pending = this.pending.get(id);
1932
+ if (!pending) return;
1933
+ this.forget(pending);
1934
+ this.settle(id, "expired");
1935
+ if (answerClaude) {
1936
+ this.deps.respond(pending.controlRequestId, {
1937
+ behavior: "deny",
1938
+ message: `Permission for this tool call was not granted: ${reason}`
1939
+ });
1940
+ }
1941
+ this.deps.emit({
1942
+ type: "permission_request",
1943
+ request: {
1944
+ id,
1945
+ toolName: pending.toolName,
1946
+ inputSummary: pending.inputSummary,
1947
+ requestedAt: pending.requestedAt,
1948
+ status: "expired",
1949
+ expiredReason: reason
1950
+ }
1951
+ });
1952
+ }
1953
+ forget(pending) {
1954
+ clearTimeout(pending.timer);
1955
+ this.pending.delete(pending.id);
1956
+ this.byControlId.delete(pending.controlRequestId);
1957
+ }
1958
+ settle(id, how) {
1959
+ this.settled.set(id, how);
1960
+ while (this.settled.size > SETTLED_KEPT) {
1961
+ this.settled.delete(this.settled.keys().next().value);
1962
+ }
1963
+ }
1964
+ };
1965
+
1966
+ // src/stream-mapper.ts
1967
+ function capText(text, max = RUNNER_EVENT_TEXT_MAX_LENGTH) {
1968
+ if (text.length <= max) return { text, truncated: false };
1969
+ const marker = "\n\u2026 [truncated by dt-runner]";
1970
+ return { text: text.slice(0, max - marker.length) + marker, truncated: true };
1971
+ }
1972
+ var ClaudeStreamMapper = class {
1973
+ /** Running offset of each live text block, by providerEventId. */
1974
+ deltaOffsets = /* @__PURE__ */ new Map();
1975
+ /** Stream block index → providerEventId for text blocks of the message streaming now. */
1976
+ streamTextKeys = /* @__PURE__ */ new Map();
1977
+ streamMessageId = null;
1978
+ streamTextCount = 0;
1979
+ /** Text blocks already seen in completed `assistant` lines, per message id. */
1980
+ completedTextCount = /* @__PURE__ */ new Map();
1981
+ /** Tool calls by id, for the name/input a result line does not repeat. */
1982
+ calls = /* @__PURE__ */ new Map();
1983
+ lastAssistantText = null;
1984
+ running = false;
1985
+ /** A new turn is starting (we wrote a user message); the next activity is not news. */
1986
+ markRunning() {
1987
+ this.running = true;
1988
+ }
1989
+ map(line) {
1990
+ const out = { events: [] };
1991
+ if (line.parent_tool_use_id) return out;
1992
+ switch (line.type) {
1993
+ case "system":
1994
+ if (line.subtype === "init" && typeof line.session_id === "string") {
1995
+ out.conversationId = line.session_id;
1996
+ this.ensureRunning(out);
1997
+ }
1998
+ break;
1999
+ case "stream_event":
2000
+ this.mapStreamEvent(line, out);
2001
+ break;
2002
+ case "assistant":
2003
+ this.mapAssistant(line, out);
2004
+ break;
2005
+ case "user":
2006
+ this.mapUser(line, out);
2007
+ break;
2008
+ case "result": {
2009
+ const resultText = typeof line.result === "string" && line.result ? line.result : null;
2010
+ out.turnEnd = {
2011
+ text: resultText ?? this.lastAssistantText,
2012
+ isError: line.is_error === true || (line.subtype ?? "success") !== "success",
2013
+ subtype: typeof line.subtype === "string" ? line.subtype : null
2014
+ };
2015
+ const denials = Array.isArray(line.permission_denials) ? line.permission_denials.filter((d) => d && typeof d.tool_name === "string").map((d) => ({
2016
+ callId: typeof d.tool_use_id === "string" ? d.tool_use_id : null,
2017
+ name: d.tool_name,
2018
+ input: d.tool_input ?? {}
2019
+ })) : [];
2020
+ if (denials.length) out.turnEnd.permissionDenials = denials;
2021
+ this.endTurn();
2022
+ break;
2023
+ }
2024
+ case "control_response": {
2025
+ const res = line.response ?? {};
2026
+ if (typeof res.request_id === "string") {
2027
+ out.controlResponse = { requestId: res.request_id, ok: res.subtype === "success" };
2028
+ }
2029
+ break;
2030
+ }
2031
+ }
2032
+ return out;
2033
+ }
2034
+ ensureRunning(out) {
2035
+ if (!this.running) {
2036
+ this.running = true;
2037
+ out.turnStarted = true;
2038
+ out.events.push({ type: "status", status: "running" });
2039
+ }
2040
+ }
2041
+ mapStreamEvent(line, out) {
2042
+ const ev = line.event ?? {};
2043
+ switch (ev.type) {
2044
+ case "message_start": {
2045
+ this.ensureRunning(out);
2046
+ const id = ev.message?.id ?? line.api_message_id ?? null;
2047
+ this.beginStreamMessage(typeof id === "string" ? id : null);
2048
+ break;
2049
+ }
2050
+ case "content_block_start": {
2051
+ const id = this.streamMessageIdFor(line);
2052
+ if (ev.content_block?.type === "text" && id && typeof ev.index === "number") {
2053
+ const key = textKey(id, this.streamTextCount++);
2054
+ this.streamTextKeys.set(ev.index, key);
2055
+ const initial = typeof ev.content_block.text === "string" ? ev.content_block.text : "";
2056
+ this.deltaOffsets.set(key, 0);
2057
+ if (initial) this.pushDelta(out, key, initial);
2058
+ }
2059
+ break;
2060
+ }
2061
+ case "content_block_delta": {
2062
+ if (ev.delta?.type !== "text_delta" || typeof ev.delta.text !== "string") break;
2063
+ if (!ev.delta.text) break;
2064
+ const key = this.streamTextKeys.get(ev.index);
2065
+ if (key) this.pushDelta(out, key, ev.delta.text);
2066
+ break;
2067
+ }
2068
+ }
2069
+ }
2070
+ streamMessageIdFor(line) {
2071
+ const id = typeof line.api_message_id === "string" ? line.api_message_id : null;
2072
+ if (id && id !== this.streamMessageId) this.beginStreamMessage(id);
2073
+ return this.streamMessageId;
2074
+ }
2075
+ beginStreamMessage(id) {
2076
+ if (id === this.streamMessageId) return;
2077
+ this.streamMessageId = id;
2078
+ this.streamTextKeys.clear();
2079
+ this.streamTextCount = 0;
2080
+ }
2081
+ pushDelta(out, key, text) {
2082
+ const offset = this.deltaOffsets.get(key) ?? 0;
2083
+ this.deltaOffsets.set(key, offset + text.length);
2084
+ out.events.push({ type: "assistant_delta", providerEventId: key, text, offset });
2085
+ }
2086
+ mapAssistant(line, out) {
2087
+ const msg = line.message ?? {};
2088
+ const id = typeof msg.id === "string" ? msg.id : `msg_${line.uuid ?? Date.now()}`;
2089
+ const content = Array.isArray(msg.content) ? msg.content : [];
2090
+ this.ensureRunning(out);
2091
+ for (const block of content) {
2092
+ switch (block?.type) {
2093
+ case "text": {
2094
+ const n = this.completedTextCount.get(id) ?? 0;
2095
+ this.completedTextCount.set(id, n + 1);
2096
+ const text = typeof block.text === "string" ? block.text : "";
2097
+ if (!text.trim()) break;
2098
+ const key = textKey(id, n);
2099
+ this.deltaOffsets.delete(key);
2100
+ this.lastAssistantText = text;
2101
+ out.events.push({
2102
+ type: "assistant_message",
2103
+ providerEventId: key,
2104
+ text: capText(text).text
2105
+ });
2106
+ break;
2107
+ }
2108
+ case "thinking":
2109
+ case "redacted_thinking": {
2110
+ const text = typeof block.thinking === "string" && block.thinking.trim() ? block.thinking : null;
2111
+ out.events.push({
2112
+ type: "thinking",
2113
+ providerEventId: `${id}:thinking:${this.thinkingIndex(id)}`,
2114
+ text: text === null ? null : capText(text).text
2115
+ });
2116
+ break;
2117
+ }
2118
+ case "tool_use":
2119
+ case "server_tool_use":
2120
+ case "mcp_tool_use": {
2121
+ if (typeof block.id !== "string") break;
2122
+ const name = block.type === "mcp_tool_use" && block.server_name ? `${block.server_name}.${block.name}` : String(block.name ?? "tool");
2123
+ this.calls.set(block.id, { name, input: block.input });
2124
+ out.events.push({
2125
+ type: "tool_call",
2126
+ providerEventId: block.id,
2127
+ tool: { callId: block.id, name, status: "running", input: block.input }
2128
+ });
2129
+ break;
2130
+ }
2131
+ }
2132
+ }
2133
+ }
2134
+ thinkingCounts = /* @__PURE__ */ new Map();
2135
+ thinkingIndex(id) {
2136
+ const n = this.thinkingCounts.get(id) ?? 0;
2137
+ this.thinkingCounts.set(id, n + 1);
2138
+ return n;
2139
+ }
2140
+ mapUser(line, out) {
2141
+ const content = line.message?.content;
2142
+ if (!Array.isArray(content)) return;
2143
+ for (const block of content) {
2144
+ if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
2145
+ const known = this.calls.get(block.tool_use_id);
2146
+ const full = toolResultText(block.content);
2147
+ const { text, truncated } = capText(full);
2148
+ if (block.is_error) {
2149
+ (out.failedTools ??= []).push({
2150
+ callId: block.tool_use_id,
2151
+ name: known?.name ?? "tool",
2152
+ input: known?.input ?? {},
2153
+ text: full
2154
+ });
2155
+ }
2156
+ const tool = {
2157
+ callId: block.tool_use_id,
2158
+ name: known?.name ?? "tool",
2159
+ status: block.is_error ? "failed" : "completed",
2160
+ ...known ? { input: known.input } : {},
2161
+ output: text,
2162
+ ...truncated ? { truncated: true } : {}
2163
+ };
2164
+ out.events.push({ type: "tool_call", providerEventId: block.tool_use_id, tool });
2165
+ }
2166
+ }
2167
+ endTurn() {
2168
+ this.running = false;
2169
+ this.lastAssistantText = null;
2170
+ this.deltaOffsets.clear();
2171
+ this.streamTextKeys.clear();
2172
+ this.streamMessageId = null;
2173
+ this.streamTextCount = 0;
2174
+ this.completedTextCount.clear();
2175
+ this.thinkingCounts.clear();
2176
+ if (this.calls.size > 500) this.calls.clear();
2177
+ }
2178
+ };
2179
+ function textKey(messageId, n) {
2180
+ return n === 0 ? messageId : `${messageId}:${n}`;
2181
+ }
2182
+ function toolResultText(content) {
2183
+ if (typeof content === "string") return content;
2184
+ if (!Array.isArray(content)) return content == null ? "" : JSON.stringify(content);
2185
+ return content.map((b) => {
2186
+ if (b?.type === "text" && typeof b.text === "string") return b.text;
2187
+ if (b?.type === "image") return "[image]";
2188
+ return "";
2189
+ }).filter(Boolean).join("\n");
2190
+ }
2191
+
2192
+ // src/drivers/claude.ts
2193
+ var claudeCodeDriver = {
2194
+ kind: "claude_code",
2195
+ displayName: "Claude Code",
2196
+ processModel: "persistent",
2197
+ resolveBinary: (env) => findClaude(env),
2198
+ notInstalledMessage: () => "Claude Code is not installed on the runner\u2019s computer (no `claude` on PATH).",
2199
+ readFeatures: (bin) => claudeFeatures(bin),
2200
+ probe: (env) => probeAgent(env),
2201
+ doctor,
2202
+ validateModel: (model) => assertValidModel(model),
2203
+ launch(input) {
2204
+ const features = input.features;
2205
+ const ask = input.askTools;
2206
+ const allowedTools = features.settingsFlag || ask.length === 0 ? input.allowedTools : input.allowedTools.filter((r) => !overlapsAsk(r, ask));
2207
+ return {
2208
+ bin: input.bin,
2209
+ args: claudeArgs({
2210
+ permissionMode: input.permissionMode,
2211
+ allowedTools,
2212
+ disallowedTools: input.disallowedTools,
2213
+ loadProjectSettings: input.loadProjectSettings,
2214
+ model: input.model,
2215
+ resume: input.resume,
2216
+ relayPermissions: input.relayPermissions,
2217
+ askTools: ask,
2218
+ appendSystemPrompt: input.systemPrompt,
2219
+ features
2220
+ })
2221
+ };
2222
+ },
2223
+ createMapper: () => new ClaudeStreamMapper(),
2224
+ encodeMessage: (content) => ({ type: "user", message: { role: "user", content } }),
2225
+ // As the Agent SDK sends it: Claude Code ends the turn with an `error_during_execution`.
2226
+ interruptMessage: (requestId) => ({
2227
+ type: "control_request",
2228
+ request_id: requestId,
2229
+ request: { subtype: "interrupt" }
2230
+ }),
2231
+ control: {
2232
+ relays: (input) => relaysPermissions({
2233
+ relayPermissions: input.relayPermissions,
2234
+ permissionMode: input.permissionMode,
2235
+ features: input.features
2236
+ }),
2237
+ parse(line) {
2238
+ if (line.type === "control_request") {
2239
+ const ask = parseCanUseTool(line);
2240
+ if (ask) return { kind: "permission", ask };
2241
+ return {
2242
+ kind: "unsupported",
2243
+ requestId: typeof line.request_id === "string" ? line.request_id : null
2244
+ };
2245
+ }
2246
+ const cancelled = parseControlCancel(line);
2247
+ return cancelled ? { kind: "cancel", controlRequestId: cancelled } : null;
2248
+ },
2249
+ permissionResponse: (controlRequestId, response) => ({
2250
+ type: "control_response",
2251
+ response: { subtype: "success", request_id: controlRequestId, response }
2252
+ }),
2253
+ unsupportedResponse: (requestId) => ({
2254
+ type: "control_response",
2255
+ response: {
2256
+ subtype: "error",
2257
+ request_id: requestId,
2258
+ error: "dt-runner does not handle this control request."
2259
+ }
2260
+ })
2261
+ },
2262
+ looksLikeSignInFailure,
2263
+ turnFailedToSignIn,
2264
+ signInFix,
2265
+ turnErrorMessage,
2266
+ startupHint,
2267
+ resumeNotFound: (stderr) => /No conversation found/i.test(stderr)
2268
+ };
2269
+ async function doctor(env = process.env) {
2270
+ const checks = [];
2271
+ const bin = await findClaude(env);
2272
+ if (!bin) {
2273
+ checks.push({
2274
+ name: "Claude Code",
2275
+ level: "fail",
2276
+ detail: env.DT_RUNNER_CLAUDE_BIN ? `DT_RUNNER_CLAUDE_BIN=${env.DT_RUNNER_CLAUDE_BIN} was not found` : "not installed: see https://docs.claude.com/en/docs/claude-code (no `claude` on PATH)"
2277
+ });
2278
+ } else {
2279
+ const version = await claudeVersion(bin);
2280
+ checks.push({
2281
+ name: "Claude Code",
2282
+ level: version ? "ok" : "fail",
2283
+ detail: version ? `${version} (${bin})` : `${bin} --version failed`
2284
+ });
2285
+ if (version) {
2286
+ const auth = await claudeAuthStatus(bin);
2287
+ checks.push(
2288
+ auth.loggedIn === true ? {
2289
+ name: "Claude sign-in",
2290
+ level: "ok",
2291
+ detail: `signed in${auth.authMethod ? ` (${auth.authMethod})` : ""}`
2292
+ } : auth.loggedIn === false ? {
2293
+ name: "Claude sign-in",
2294
+ level: "fail",
2295
+ detail: "not signed in: run `claude` and sign in with your Claude account"
2296
+ } : {
2297
+ name: "Claude sign-in",
2298
+ level: "warn",
2299
+ detail: "could not tell (this Claude Code has no `claude auth status`); update Claude Code"
2300
+ }
2301
+ );
2302
+ }
2303
+ }
2304
+ return checks;
2305
+ }
2306
+ function turnErrorMessage(turn) {
2307
+ switch (turn.subtype) {
2308
+ case "error_max_turns":
2309
+ return "Claude Code stopped: it reached its maximum number of turns.";
2310
+ case "error_max_budget_usd":
2311
+ return "Claude Code stopped: it reached its spending limit.";
2312
+ default:
2313
+ if (turnFailedToSignIn(turn)) {
2314
+ return `Claude Code could not sign in to Claude (${turn.text.slice(0, 200)}). ${signInFix()} Then send a message here to try again.`;
2315
+ }
2316
+ return turn.text ? `Claude Code reported an error: ${turn.text.slice(0, 500)}` : `Claude Code ended the turn with an error (${turn.subtype ?? "unknown"}).`;
2317
+ }
2318
+ }
2319
+ function startupHint(stderr) {
2320
+ if (looksLikeSignInFailure(stderr)) {
2321
+ return ` Claude Code does not seem to be signed in on the runner\u2019s computer. ${signInFix()}`;
2322
+ }
2323
+ if (/No conversation found|session.*not found/i.test(stderr)) {
2324
+ return " The Claude Code conversation to resume was not found on this computer.";
2325
+ }
2326
+ return "";
2327
+ }
2328
+
2329
+ // src/drivers/codex/codex.ts
2330
+ import { delimiter as delimiter2, join as join6 } from "node:path";
2331
+
2332
+ // src/drivers/launcher.ts
2333
+ import { access as access2 } from "node:fs/promises";
2334
+ async function exists2(file) {
2335
+ try {
2336
+ await access2(file);
2337
+ return true;
2338
+ } catch {
2339
+ return false;
2340
+ }
2341
+ }
2342
+ function isJsLauncher(bin) {
2343
+ return /\.[cm]?js$/i.test(bin);
2344
+ }
2345
+ function launcherCommand(bin, args) {
2346
+ return isJsLauncher(bin) ? { bin: process.execPath, args: [bin, ...args] } : { bin, args };
2347
+ }
2348
+ async function findOverride(override, env) {
2349
+ if (isJsLauncher(override)) return await exists2(override) ? override : null;
2350
+ return which(override, env);
2351
+ }
2352
+
2353
+ // src/drivers/codex/codex.ts
2354
+ async function findCodex(env = process.env) {
2355
+ const override = env.DT_RUNNER_CODEX_BIN?.trim();
2356
+ if (override) return findOverride(override, env);
2357
+ const found = await which("codex", env);
2358
+ if (found) return found;
2359
+ if (process.platform !== "win32") return null;
2360
+ for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter2).filter(Boolean)) {
2361
+ if (!await exists2(join6(dir, "codex.cmd"))) continue;
2362
+ const script = join6(dir, "node_modules", "@openai", "codex", "bin", "codex.js");
2363
+ if (await exists2(script)) return script;
2364
+ }
2365
+ return null;
2366
+ }
2367
+ var codexCommand = launcherCommand;
2368
+ function runCodex(bin, args, timeoutMs, env) {
2369
+ const cmd = codexCommand(bin, args);
2370
+ return exec(cmd.bin, cmd.args, { timeoutMs, env });
2371
+ }
2372
+ async function codexVersion(bin, env = process.env) {
2373
+ try {
2374
+ const res = await runCodex(bin, ["--version"], 15e3, env);
2375
+ if (res.code !== 0) return null;
2376
+ return res.stdout.trim().split("\n")[0] || null;
2377
+ } catch {
2378
+ return null;
2379
+ }
2380
+ }
2381
+ async function codexAuthStatus(bin, env = process.env) {
2382
+ try {
2383
+ const res = await runCodex(bin, ["login", "status"], 2e4, env);
2384
+ const said = `${res.stdout}
2385
+ ${res.stderr}`;
2386
+ if (res.code !== 0) return { loggedIn: false, authMethod: null };
2387
+ return {
2388
+ loggedIn: true,
2389
+ authMethod: /chatgpt/i.test(said) ? "ChatGPT" : /api key/i.test(said) ? "API key" : null
2390
+ };
2391
+ } catch {
2392
+ return { loggedIn: null, authMethod: null };
2393
+ }
2394
+ }
2395
+ function codexSignInFix(env = process.env) {
2396
+ const key = codexKeyVariable(env);
2397
+ if (key) {
2398
+ return `\`${key}\` is set where the runner runs, so Codex may use that key instead of your ChatGPT sign-in. Unset it (or replace it with a working key) and restart the runner, or run \`codex login\` on the runner\u2019s computer.`;
2399
+ }
2400
+ return "On the runner\u2019s computer, run `codex login` and sign in (with ChatGPT or an API key), and check that `codex login status` says you are logged in.";
2401
+ }
2402
+ function codexKeyVariable(env = process.env) {
2403
+ if (env.CODEX_API_KEY) return "CODEX_API_KEY";
2404
+ if (env.OPENAI_API_KEY) return "OPENAI_API_KEY";
2405
+ return null;
2406
+ }
2407
+ async function probeCodex(env = process.env) {
2408
+ const bin = await findCodex(env);
2409
+ if (!bin) {
2410
+ return {
2411
+ codexVersion: null,
2412
+ codexReady: false,
2413
+ codexProblem: env.DT_RUNNER_CODEX_BIN ? `DT_RUNNER_CODEX_BIN=${env.DT_RUNNER_CODEX_BIN} was not found.` : "Codex is not installed on this computer (no `codex` on PATH). Install it with `npm i -g @openai/codex`."
2414
+ };
2415
+ }
2416
+ const version = await codexVersion(bin, env);
2417
+ if (!version) {
2418
+ return {
2419
+ codexVersion: null,
2420
+ codexReady: false,
2421
+ codexProblem: "`codex --version` failed; reinstall or update Codex."
2422
+ };
2423
+ }
2424
+ const auth = await codexAuthStatus(bin, env);
2425
+ if (auth.loggedIn === false) {
2426
+ return {
2427
+ codexVersion: version,
2428
+ codexReady: false,
2429
+ codexProblem: "Codex is not signed in. Run `codex login` on this computer."
2430
+ };
2431
+ }
2432
+ return { codexVersion: version, codexReady: auth.loggedIn, codexProblem: null };
2433
+ }
2434
+ var SIGN_IN_FAILURE2 = /not logged in|please (run|use) `?codex login|401 unauthorized|status 401|invalid[_ ]api[_ ]key|incorrect api key|refresh token|token (has )?expired|token_expired|could not be refreshed/i;
2435
+ function looksLikeCodexSignInFailure(text) {
2436
+ return !!text && SIGN_IN_FAILURE2.test(text);
2437
+ }
2438
+ var MODEL_NAME2 = /^[A-Za-z0-9][\w.:@/-]{0,199}$/;
2439
+ function assertValidCodexModel(model) {
2440
+ if (model && !MODEL_NAME2.test(model)) {
2441
+ throw new Error(
2442
+ `The model "${model.slice(0, 80)}" is not a valid Codex model name; the runner refused to start it.`
2443
+ );
2444
+ }
2445
+ }
2446
+ function codexArgs(launch) {
2447
+ const args = ["exec", "--json", "--skip-git-repo-check", "--sandbox", launch.sandbox];
2448
+ if (launch.sandbox === "workspace-write" && launch.networkAccess) {
2449
+ args.push("-c", "sandbox_workspace_write.network_access=true");
2450
+ }
2451
+ if (launch.model) {
2452
+ assertValidCodexModel(launch.model);
2453
+ args.push(`--model=${launch.model}`);
2454
+ }
2455
+ args.push("-C", launch.cwd);
2456
+ if (launch.resume) args.push("resume", launch.resume);
2457
+ args.push("-");
2458
+ return args;
2459
+ }
2460
+ function codexFirstPrompt(systemPrompt, prompt) {
2461
+ return systemPrompt ? `${systemPrompt}
2462
+
2463
+ ---
2464
+
2465
+ ${prompt}` : prompt;
2466
+ }
2467
+
2468
+ // src/drivers/codex/codex-stream-mapper.ts
2469
+ import { randomBytes } from "node:crypto";
2470
+ var CodexStreamMapper = class {
2471
+ running = false;
2472
+ /** The turn's end was reported: what its process says afterwards is no news. */
2473
+ ended = false;
2474
+ turn = 0;
2475
+ turnKey = "";
2476
+ lastMessage = null;
2477
+ /** Error the turn reported before its end (`error` lines). */
2478
+ lastError = null;
2479
+ /** Each session's mapper has its own tag, so a restarted runner's turns are not taken for earlier ones. */
2480
+ tag = randomBytes(3).toString("hex");
2481
+ constructor() {
2482
+ this.beginTurn();
2483
+ }
2484
+ markRunning() {
2485
+ this.running = true;
2486
+ this.beginTurn();
2487
+ }
2488
+ beginTurn() {
2489
+ this.turn++;
2490
+ this.turnKey = `codex-${this.tag}-t${this.turn}`;
2491
+ this.ended = false;
2492
+ this.lastMessage = null;
2493
+ this.lastError = null;
2494
+ }
2495
+ map(line) {
2496
+ const out = { events: [] };
2497
+ if (this.ended) return out;
2498
+ switch (line.type) {
2499
+ case "thread.started":
2500
+ if (typeof line.thread_id === "string" && line.thread_id) {
2501
+ out.conversationId = line.thread_id;
2502
+ }
2503
+ this.ensureRunning(out);
2504
+ break;
2505
+ case "turn.started":
2506
+ this.ensureRunning(out);
2507
+ break;
2508
+ case "item.started":
2509
+ case "item.updated":
2510
+ case "item.completed":
2511
+ if (line.item && typeof line.item === "object") {
2512
+ this.ensureRunning(out);
2513
+ this.mapItem(line.type, line.item, out);
2514
+ }
2515
+ break;
2516
+ case "turn.completed":
2517
+ out.turnEnd = { text: this.lastMessage, isError: false, subtype: "success" };
2518
+ this.endTurn();
2519
+ break;
2520
+ case "turn.failed": {
2521
+ const message = errorMessage(line.error) ?? this.lastError;
2522
+ out.turnEnd = { text: message, isError: true, subtype: "turn_failed" };
2523
+ this.endTurn();
2524
+ break;
2525
+ }
2526
+ case "error": {
2527
+ const message = errorMessage(line) ?? "Codex reported an error.";
2528
+ if (/\b(retrying|reconnecting)\b/i.test(message)) break;
2529
+ out.turnEnd = { text: message, isError: true, subtype: "error" };
2530
+ this.endTurn();
2531
+ break;
2532
+ }
2533
+ }
2534
+ return out;
2535
+ }
2536
+ ensureRunning(out) {
2537
+ if (this.running) return;
2538
+ this.running = true;
2539
+ out.turnStarted = true;
2540
+ out.events.push({ type: "status", status: "running" });
2541
+ }
2542
+ endTurn() {
2543
+ this.running = false;
2544
+ this.ended = true;
2545
+ }
2546
+ mapItem(phase, item, out) {
2547
+ const id = typeof item.id === "string" && item.id ? item.id : null;
2548
+ if (!id) return;
2549
+ const key = `${this.turnKey}:${id}`;
2550
+ const done = phase === "item.completed";
2551
+ switch (item.type) {
2552
+ case "agent_message": {
2553
+ const text = typeof item.text === "string" ? item.text : "";
2554
+ if (!done || !text.trim()) break;
2555
+ this.lastMessage = text;
2556
+ out.events.push({
2557
+ type: "assistant_message",
2558
+ providerEventId: key,
2559
+ text: capText(text).text
2560
+ });
2561
+ break;
2562
+ }
2563
+ case "reasoning": {
2564
+ if (!done) break;
2565
+ const text = typeof item.text === "string" && item.text.trim() ? item.text : null;
2566
+ out.events.push({
2567
+ type: "thinking",
2568
+ providerEventId: key,
2569
+ text: text === null ? null : capText(text).text
2570
+ });
2571
+ break;
2572
+ }
2573
+ case "command_execution": {
2574
+ const command = typeof item.command === "string" ? item.command : "";
2575
+ const exitCode = typeof item.exit_code === "number" ? item.exit_code : null;
2576
+ const failed = item.status === "failed" || item.status === "declined" || exitCode !== null && exitCode !== 0;
2577
+ const status2 = done ? failed ? "failed" : "completed" : "running";
2578
+ const output = typeof item.aggregated_output === "string" ? item.aggregated_output : "";
2579
+ this.pushTool(out, key, "Bash", status2, { command }, done ? output : null);
2580
+ break;
2581
+ }
2582
+ case "file_change": {
2583
+ const changes = Array.isArray(item.changes) ? item.changes.filter((c) => c && typeof c.path === "string").map((c) => ({ path: c.path, kind: typeof c.kind === "string" ? c.kind : null })) : [];
2584
+ const failed = item.status === "failed";
2585
+ const status2 = done || item.status === "completed" ? failed ? "failed" : "completed" : "running";
2586
+ const summary = changes.map((c) => `${c.kind ?? "edit"} ${c.path}`).join("\n");
2587
+ this.pushTool(
2588
+ out,
2589
+ key,
2590
+ "Edit",
2591
+ status2,
2592
+ { paths: changes.map((c) => c.path), changes },
2593
+ status2 === "running" ? null : summary
2594
+ );
2595
+ break;
2596
+ }
2597
+ case "mcp_tool_call": {
2598
+ const name = typeof item.server === "string" && typeof item.tool === "string" ? `${item.server}.${item.tool}` : String(item.tool ?? "mcp");
2599
+ const error = errorMessage(item.error);
2600
+ const failed = item.status === "failed" || !!error;
2601
+ const status2 = done ? failed ? "failed" : "completed" : "running";
2602
+ const output = error ?? (item.result !== void 0 ? mcpResultText(item.result) : null);
2603
+ this.pushTool(out, key, name, status2, item.arguments ?? {}, done ? output : null);
2604
+ break;
2605
+ }
2606
+ case "web_search": {
2607
+ const query = typeof item.query === "string" ? item.query : "";
2608
+ this.pushTool(out, key, "WebSearch", done ? "completed" : "running", { query }, null);
2609
+ break;
2610
+ }
2611
+ case "todo_list": {
2612
+ const todos = Array.isArray(item.items) ? item.items.filter((t) => t && typeof t.text === "string").map((t) => ({ text: t.text, completed: t.completed === true })) : [];
2613
+ this.pushTool(out, key, "TodoWrite", done ? "completed" : "running", { todos }, null);
2614
+ break;
2615
+ }
2616
+ case "error": {
2617
+ const message = errorMessage(item);
2618
+ if (done && message) {
2619
+ this.lastError = message;
2620
+ out.events.push({ type: "error", message: capText(message).text, retryable: false });
2621
+ }
2622
+ break;
2623
+ }
2624
+ }
2625
+ }
2626
+ pushTool(out, key, name, status2, input, output) {
2627
+ const tool = { callId: key, name, status: status2, input };
2628
+ if (output !== null) {
2629
+ const capped = capText(output);
2630
+ tool.output = capped.text;
2631
+ if (capped.truncated) tool.truncated = true;
2632
+ }
2633
+ out.events.push({ type: "tool_call", providerEventId: key, tool });
2634
+ }
2635
+ };
2636
+ function errorMessage(value) {
2637
+ if (typeof value === "string") return value.trim() || null;
2638
+ if (value && typeof value === "object") {
2639
+ const m = value.message;
2640
+ if (typeof m === "string" && m.trim()) return m;
2641
+ }
2642
+ return null;
2643
+ }
2644
+ function mcpResultText(result) {
2645
+ const content = result?.content;
2646
+ if (Array.isArray(content)) {
2647
+ const text = content.map((b) => b?.type === "text" && typeof b.text === "string" ? b.text : "").filter(Boolean).join("\n");
2648
+ if (text) return text;
2649
+ }
2650
+ return result == null ? "" : JSON.stringify(result);
2651
+ }
2652
+
2653
+ // src/drivers/codex.ts
2654
+ var codexDriver = {
2655
+ kind: "codex",
2656
+ displayName: "Codex",
2657
+ processModel: "per_turn",
2658
+ resolveBinary: (env) => findCodex(env),
2659
+ notInstalledMessage: () => "Codex is not installed on the runner\u2019s computer (no `codex` on PATH). Install it with `npm i -g @openai/codex` and run `codex login`.",
2660
+ readFeatures: async () => ({}),
2661
+ probe: async (env) => ({
2662
+ claudeVersion: null,
2663
+ claudeReady: null,
2664
+ ...await probeCodex(env),
2665
+ runsCodex: true
2666
+ }),
2667
+ doctor: doctor2,
2668
+ validateModel: (model) => assertValidCodexModel(model),
2669
+ launch(input) {
2670
+ const prompt = input.resume ? input.prompt ?? "" : codexFirstPrompt(input.systemPrompt, input.prompt ?? "");
2671
+ const cmd = codexCommand(
2672
+ input.bin,
2673
+ codexArgs({
2674
+ cwd: input.cwd,
2675
+ model: input.model,
2676
+ sandbox: input.agentConfig?.codexSandbox ?? "workspace-write",
2677
+ networkAccess: input.agentConfig?.codexNetworkAccess === true,
2678
+ resume: input.resume
2679
+ })
2680
+ );
2681
+ return { ...cmd, stdin: prompt };
2682
+ },
2683
+ createMapper: () => new CodexStreamMapper(),
2684
+ looksLikeSignInFailure: looksLikeCodexSignInFailure,
2685
+ turnFailedToSignIn: (turn) => turn.isError && looksLikeCodexSignInFailure(turn.text),
2686
+ signInFix: (env) => codexSignInFix(env),
2687
+ turnErrorMessage: turnErrorMessage2,
2688
+ startupHint(stderr) {
2689
+ if (looksLikeCodexSignInFailure(stderr)) {
2690
+ return ` Codex does not seem to be signed in on the runner\u2019s computer. ${codexSignInFix()}`;
2691
+ }
2692
+ if (codexResumeNotFound(stderr)) {
2693
+ return " The Codex conversation to resume was not found on this computer.";
2694
+ }
2695
+ return "";
2696
+ },
2697
+ resumeNotFound: (stderr) => codexResumeNotFound(stderr)
2698
+ };
2699
+ function codexResumeNotFound(text) {
2700
+ return /no (rollout|session|thread|conversation)s? found|(thread|session|conversation|rollout)\b[^\n]{0,60}\bnot found/i.test(
2701
+ text
2702
+ );
2703
+ }
2704
+ function turnErrorMessage2(turn) {
2705
+ if (turn.isError && looksLikeCodexSignInFailure(turn.text)) {
2706
+ return `Codex could not sign in (${turn.text.slice(0, 200)}). ${codexSignInFix()} Then send a message here to try again.`;
2707
+ }
2708
+ return turn.text ? `Codex reported an error: ${turn.text.slice(0, 500)}` : "Codex ended the turn with an error.";
2709
+ }
2710
+ async function doctor2(env = process.env) {
2711
+ const checks = [];
2712
+ const bin = await findCodex(env);
2713
+ if (!bin) {
2714
+ checks.push({
2715
+ name: "Codex",
2716
+ level: env.DT_RUNNER_CODEX_BIN ? "fail" : "ok",
2717
+ detail: env.DT_RUNNER_CODEX_BIN ? `DT_RUNNER_CODEX_BIN=${env.DT_RUNNER_CODEX_BIN} was not found` : "not installed (optional): runs can use Codex once `npm i -g @openai/codex` and `codex login` are done"
2718
+ });
2719
+ return checks;
2720
+ }
2721
+ const version = await codexVersion(bin, env);
2722
+ checks.push({
2723
+ name: "Codex",
2724
+ level: version ? "ok" : "warn",
2725
+ detail: version ? `${version} (${bin})` : `${bin} --version failed: Codex runs will not start`
2726
+ });
2727
+ if (!version) return checks;
2728
+ const auth = await codexAuthStatus(bin, env);
2729
+ checks.push(
2730
+ auth.loggedIn === true ? {
2731
+ name: "Codex sign-in",
2732
+ level: "ok",
2733
+ detail: `signed in${auth.authMethod ? ` (${auth.authMethod})` : ""}`
2734
+ } : auth.loggedIn === false ? {
2735
+ name: "Codex sign-in",
2736
+ level: "warn",
2737
+ detail: "not signed in: run `codex login` before starting Codex runs"
2738
+ } : {
2739
+ name: "Codex sign-in",
2740
+ level: "warn",
2741
+ detail: "could not tell (`codex login status` failed)"
2742
+ }
2743
+ );
2744
+ const key = codexKeyVariable(env);
2745
+ if (key) {
2746
+ checks.push({
2747
+ name: key,
2748
+ level: "warn",
2749
+ detail: `is set: Codex runs may bill that API key instead of your ChatGPT plan. Unset it before starting the runner unless that is what you want.`
2750
+ });
2751
+ }
2752
+ return checks;
2753
+ }
2754
+
2755
+ // src/drivers/cursor/cursor.ts
2756
+ async function findCursor(env = process.env) {
2757
+ const override = env.DT_RUNNER_CURSOR_BIN?.trim();
2758
+ if (override) return findOverride(override, env);
2759
+ return await which("cursor-agent", env) ?? await which("agent", env);
2760
+ }
2761
+ function runCursor(bin, args, timeoutMs, env) {
2762
+ const cmd = launcherCommand(bin, args);
2763
+ return exec(cmd.bin, cmd.args, { timeoutMs, env });
2764
+ }
2765
+ async function cursorVersion(bin, env = process.env) {
2766
+ try {
2767
+ const res = await runCursor(bin, ["--version"], 15e3, env);
2768
+ if (res.code !== 0) return null;
2769
+ return res.stdout.trim().split("\n")[0] || null;
2770
+ } catch {
2771
+ return null;
2772
+ }
2773
+ }
2774
+ async function cursorAuthStatus(bin, env = process.env) {
2775
+ try {
2776
+ const res = await runCursor(bin, ["status"], 2e4, env);
2777
+ const said = `${res.stdout}
2778
+ ${res.stderr}`;
2779
+ if (/not (logged|signed) in|not authenticated|login required|authentication required/i.test(said)) {
2780
+ return { loggedIn: false };
2781
+ }
2782
+ if (res.code === 0 && /logged in|signed in|authenticated/i.test(said))
2783
+ return { loggedIn: true };
2784
+ return { loggedIn: null };
2785
+ } catch {
2786
+ return { loggedIn: null };
2787
+ }
2788
+ }
2789
+ function cursorKeyVariable(env = process.env) {
2790
+ return env.CURSOR_API_KEY ? "CURSOR_API_KEY" : null;
2791
+ }
2792
+ function cursorSignInFix(env = process.env) {
2793
+ if (cursorKeyVariable(env)) {
2794
+ return "`CURSOR_API_KEY` is set where the runner runs, so the Cursor CLI signs in with that key. Unset it (or replace it with a working key) and restart the runner, or run `cursor-agent login` on the runner\u2019s computer.";
2795
+ }
2796
+ return "On the runner\u2019s computer, run `cursor-agent login` and sign in, and check that `cursor-agent status` says you are logged in.";
2797
+ }
2798
+ async function probeCursor(env = process.env) {
2799
+ const bin = await findCursor(env);
2800
+ if (!bin) {
2801
+ return {
2802
+ cursorVersion: null,
2803
+ cursorReady: false,
2804
+ cursorProblem: env.DT_RUNNER_CURSOR_BIN ? `DT_RUNNER_CURSOR_BIN=${env.DT_RUNNER_CURSOR_BIN} was not found.` : "The Cursor Agent CLI is not installed on this computer (no `cursor-agent` on PATH). Install it from https://cursor.com/cli."
2805
+ };
2806
+ }
2807
+ const version = await cursorVersion(bin, env);
2808
+ if (!version) {
2809
+ return {
2810
+ cursorVersion: null,
2811
+ cursorReady: false,
2812
+ cursorProblem: "`cursor-agent --version` failed; reinstall or update the Cursor Agent CLI."
2813
+ };
2814
+ }
2815
+ const auth = await cursorAuthStatus(bin, env);
2816
+ if (auth.loggedIn === false) {
2817
+ return {
2818
+ cursorVersion: version,
2819
+ cursorReady: false,
2820
+ cursorProblem: "The Cursor Agent CLI is not signed in. Run `cursor-agent login` on this computer."
2821
+ };
2822
+ }
2823
+ return { cursorVersion: version, cursorReady: auth.loggedIn, cursorProblem: null };
2824
+ }
2825
+ var SIGN_IN_FAILURE3 = /authentication required|not (logged|signed) in|please run `?(cursor-)?agent login|invalid api key|401 unauthorized|status 401|unauthenticated|session (has )?expired/i;
2826
+ function looksLikeCursorSignInFailure(text) {
2827
+ return !!text && SIGN_IN_FAILURE3.test(text);
2828
+ }
2829
+ var MODEL_NAME3 = /^[A-Za-z0-9][\w.:@/-]{0,199}$/;
2830
+ function assertValidCursorModel(model) {
2831
+ if (model && !MODEL_NAME3.test(model)) {
2832
+ throw new Error(
2833
+ `The model "${model.slice(0, 80)}" is not a valid Cursor model name; the runner refused to start it.`
2834
+ );
2835
+ }
2836
+ }
2837
+ function cursorArgs(launch) {
2838
+ const args = ["-p", "--output-format", "stream-json"];
2839
+ if (launch.model) {
2840
+ assertValidCursorModel(launch.model);
2841
+ args.push(`--model=${launch.model}`);
2842
+ }
2843
+ if (launch.resume) args.push(`--resume=${launch.resume}`);
2844
+ if (launch.force) args.push("--force");
2845
+ args.push(launch.prompt.startsWith("-") ? `
2846
+ ${launch.prompt}` : launch.prompt);
2847
+ return args;
2848
+ }
2849
+ function cursorFirstPrompt(systemPrompt, prompt) {
2850
+ return systemPrompt ? `${systemPrompt}
2851
+
2852
+ ---
2853
+
2854
+ ${prompt}` : prompt;
2855
+ }
2856
+
2857
+ // src/drivers/cursor/cursor-stream-mapper.ts
2858
+ import { randomBytes as randomBytes2 } from "node:crypto";
2859
+ var CursorStreamMapper = class {
2860
+ running = false;
2861
+ /** The turn's end was reported: what its process says afterwards is no news. */
2862
+ ended = false;
2863
+ turn = 0;
2864
+ turnKey = "";
2865
+ messages = 0;
2866
+ lastMessage = null;
2867
+ /** Each session's mapper has its own tag, so a restarted runner's turns are not taken for earlier ones. */
2868
+ tag = randomBytes2(3).toString("hex");
2869
+ constructor() {
2870
+ this.beginTurn();
2871
+ }
2872
+ markRunning() {
2873
+ this.running = true;
2874
+ this.beginTurn();
2875
+ }
2876
+ beginTurn() {
2877
+ this.turn++;
2878
+ this.turnKey = `cursor-${this.tag}-t${this.turn}`;
2879
+ this.ended = false;
2880
+ this.messages = 0;
2881
+ this.lastMessage = null;
2882
+ }
2883
+ map(line) {
2884
+ const out = { events: [] };
2885
+ if (this.ended) return out;
2886
+ switch (line.type) {
2887
+ case "system":
2888
+ if (line.subtype === "init") {
2889
+ if (typeof line.session_id === "string" && line.session_id) {
2890
+ out.conversationId = line.session_id;
2891
+ }
2892
+ this.ensureRunning(out);
2893
+ }
2894
+ break;
2895
+ case "assistant": {
2896
+ this.ensureRunning(out);
2897
+ const content = Array.isArray(line.message?.content) ? line.message.content : [];
2898
+ const text = content.map((b) => b?.type === "text" && typeof b.text === "string" ? b.text : "").join("");
2899
+ if (!text.trim()) break;
2900
+ this.lastMessage = text;
2901
+ out.events.push({
2902
+ type: "assistant_message",
2903
+ providerEventId: `${this.turnKey}:msg:${this.messages++}`,
2904
+ text: capText(text).text
2905
+ });
2906
+ break;
2907
+ }
2908
+ case "tool_call":
2909
+ if (typeof line.call_id === "string" && line.call_id && line.tool_call) {
2910
+ this.ensureRunning(out);
2911
+ this.mapToolCall(line, out);
2912
+ }
2913
+ break;
2914
+ case "result": {
2915
+ const text = typeof line.result === "string" && line.result ? line.result : null;
2916
+ const subtype = typeof line.subtype === "string" ? line.subtype : null;
2917
+ out.turnEnd = {
2918
+ text: text ?? this.lastMessage,
2919
+ isError: line.is_error === true || (subtype ?? "success") !== "success",
2920
+ subtype
2921
+ };
2922
+ this.running = false;
2923
+ this.ended = true;
2924
+ break;
2925
+ }
2926
+ }
2927
+ return out;
2928
+ }
2929
+ ensureRunning(out) {
2930
+ if (this.running) return;
2931
+ this.running = true;
2932
+ out.turnStarted = true;
2933
+ out.events.push({ type: "status", status: "running" });
2934
+ }
2935
+ mapToolCall(line, out) {
2936
+ const [kind, call] = Object.entries(line.tool_call)[0] ?? [];
2937
+ if (!kind || !call || typeof call !== "object") return;
2938
+ const key = `${this.turnKey}:${line.call_id}`;
2939
+ const done = line.subtype === "completed";
2940
+ const { name, input } = toolNameAndInput(kind, call);
2941
+ const tool = { callId: key, name, status: "running", input };
2942
+ if (done) {
2943
+ const outcome = toolOutcome(kind, call.result);
2944
+ tool.status = outcome.failed ? "failed" : "completed";
2945
+ if (outcome.output !== null) {
2946
+ const capped = capText(outcome.output);
2947
+ tool.output = capped.text;
2948
+ if (capped.truncated) tool.truncated = true;
2949
+ }
2950
+ }
2951
+ out.events.push({ type: "tool_call", providerEventId: key, tool });
2952
+ }
2953
+ };
2954
+ var TOOL_NAMES = {
2955
+ shellToolCall: "Bash",
2956
+ readToolCall: "Read",
2957
+ editToolCall: "Edit",
2958
+ writeToolCall: "Write",
2959
+ deleteToolCall: "Delete",
2960
+ grepToolCall: "Grep",
2961
+ globToolCall: "Glob",
2962
+ lsToolCall: "LS",
2963
+ updateTodosToolCall: "TodoWrite",
2964
+ todoToolCall: "TodoWrite",
2965
+ webSearchToolCall: "WebSearch"
2966
+ };
2967
+ function toolNameAndInput(kind, call) {
2968
+ if (kind === "function") {
2969
+ let input = call.arguments ?? {};
2970
+ if (typeof input === "string") {
2971
+ try {
2972
+ input = JSON.parse(input);
2973
+ } catch {
2974
+ }
2975
+ }
2976
+ return { name: typeof call.name === "string" && call.name ? call.name : "tool", input };
2977
+ }
2978
+ return {
2979
+ name: TOOL_NAMES[kind] ?? kind.replace(/ToolCall$/, ""),
2980
+ input: call.args ?? {}
2981
+ };
2982
+ }
2983
+ function toolOutcome(kind, result) {
2984
+ if (!result || typeof result !== "object") return { failed: false, output: null };
2985
+ const r = result;
2986
+ const failure = r.error ?? r.failure ?? r.rejected;
2987
+ if (failure !== void 0) return { failed: true, output: describe(failure) };
2988
+ const success = r.success;
2989
+ if (success === void 0) return { failed: false, output: describe(r) };
2990
+ if (kind === "shellToolCall" && success && typeof success === "object") {
2991
+ const text = [success.stdout, success.stderr].filter((t) => typeof t === "string" && t).join("\n");
2992
+ const exitCode = typeof success.exitCode === "number" ? success.exitCode : 0;
2993
+ return { failed: exitCode !== 0, output: text };
2994
+ }
2995
+ if (kind === "readToolCall" && typeof success?.content === "string") {
2996
+ return { failed: false, output: success.content };
2997
+ }
2998
+ return { failed: false, output: describe(success) };
2999
+ }
3000
+ function describe(value) {
3001
+ if (typeof value === "string") return value;
3002
+ const message = value?.message ?? value?.reason;
3003
+ if (typeof message === "string" && message) return message;
3004
+ return value == null ? "" : JSON.stringify(value);
3005
+ }
3006
+
3007
+ // src/drivers/cursor.ts
3008
+ var cursorDriver = {
3009
+ kind: "cursor",
3010
+ displayName: "Cursor",
3011
+ processModel: "per_turn",
3012
+ resolveBinary: (env) => findCursor(env),
3013
+ notInstalledMessage: () => "The Cursor Agent CLI is not installed on the runner\u2019s computer (no `cursor-agent` on PATH). Install it from https://cursor.com/cli and run `cursor-agent login`.",
3014
+ readFeatures: async () => ({}),
3015
+ probe: async (env) => ({
3016
+ claudeVersion: null,
3017
+ claudeReady: null,
3018
+ ...await probeCursor(env),
3019
+ runsCursor: true
3020
+ }),
3021
+ doctor: doctor3,
3022
+ validateModel: (model) => assertValidCursorModel(model),
3023
+ launch(input) {
3024
+ const prompt = input.resume ? input.prompt ?? "" : cursorFirstPrompt(input.systemPrompt, input.prompt ?? "");
3025
+ return launcherCommand(
3026
+ input.bin,
3027
+ cursorArgs({
3028
+ model: input.model,
3029
+ resume: input.resume,
3030
+ force: input.agentConfig?.cursorForce === true,
3031
+ prompt
3032
+ })
3033
+ );
3034
+ },
3035
+ createMapper: () => new CursorStreamMapper(),
3036
+ looksLikeSignInFailure: looksLikeCursorSignInFailure,
3037
+ turnFailedToSignIn: (turn) => turn.isError && looksLikeCursorSignInFailure(turn.text),
3038
+ signInFix: (env) => cursorSignInFix(env),
3039
+ turnErrorMessage: turnErrorMessage3,
3040
+ startupHint(stderr) {
3041
+ if (looksLikeCursorSignInFailure(stderr)) {
3042
+ return ` The Cursor Agent CLI does not seem to be signed in on the runner\u2019s computer. ${cursorSignInFix()}`;
3043
+ }
3044
+ if (cursorResumeNotFound(stderr)) {
3045
+ return " The Cursor chat to resume was not found on this computer.";
3046
+ }
3047
+ return "";
3048
+ },
3049
+ resumeNotFound: (stderr) => cursorResumeNotFound(stderr)
3050
+ };
3051
+ function cursorResumeNotFound(text) {
3052
+ return /no (chat|session|conversation)s? found|(chat|session|conversation)\b[^\n]{0,60}\bnot found/i.test(
3053
+ text
3054
+ );
3055
+ }
3056
+ function turnErrorMessage3(turn) {
3057
+ if (turn.isError && looksLikeCursorSignInFailure(turn.text)) {
3058
+ return `The Cursor Agent CLI could not sign in (${turn.text.slice(0, 200)}). ${cursorSignInFix()} Then send a message here to try again.`;
3059
+ }
3060
+ return turn.text ? `Cursor reported an error: ${turn.text.slice(0, 500)}` : `Cursor ended the turn with an error (${turn.subtype ?? "unknown"}).`;
3061
+ }
3062
+ async function doctor3(env = process.env) {
3063
+ const checks = [];
3064
+ const bin = await findCursor(env);
3065
+ if (!bin) {
3066
+ checks.push({
3067
+ name: "Cursor Agent CLI",
3068
+ level: env.DT_RUNNER_CURSOR_BIN ? "fail" : "ok",
3069
+ detail: env.DT_RUNNER_CURSOR_BIN ? `DT_RUNNER_CURSOR_BIN=${env.DT_RUNNER_CURSOR_BIN} was not found` : "not installed (optional): runs can use Cursor once the CLI (https://cursor.com/cli) is installed and `cursor-agent login` is done"
3070
+ });
3071
+ return checks;
3072
+ }
3073
+ const version = await cursorVersion(bin, env);
3074
+ checks.push({
3075
+ name: "Cursor Agent CLI",
3076
+ level: version ? "ok" : "warn",
3077
+ detail: version ? `${version} (${bin})` : `${bin} --version failed: Cursor runs will not start`
3078
+ });
3079
+ if (!version) return checks;
3080
+ const auth = await cursorAuthStatus(bin, env);
3081
+ checks.push(
3082
+ auth.loggedIn === true ? { name: "Cursor sign-in", level: "ok", detail: "signed in" } : auth.loggedIn === false ? {
3083
+ name: "Cursor sign-in",
3084
+ level: "warn",
3085
+ detail: "not signed in: run `cursor-agent login` before starting Cursor runs"
3086
+ } : {
3087
+ name: "Cursor sign-in",
3088
+ level: "warn",
3089
+ detail: "could not tell (`cursor-agent status` said nothing the runner reads)"
3090
+ }
3091
+ );
3092
+ if (cursorKeyVariable(env)) {
3093
+ checks.push({
3094
+ name: "CURSOR_API_KEY",
3095
+ level: "warn",
3096
+ detail: "is set: Cursor runs sign in with that API key instead of your `cursor-agent login`. Unset it before starting the runner unless that is what you want."
3097
+ });
3098
+ }
3099
+ return checks;
3100
+ }
3101
+
3102
+ // src/agent-driver.ts
3103
+ var DEFAULT_AGENT_KIND = "claude_code";
3104
+ var DRIVERS = new Map(
3105
+ [claudeCodeDriver, codexDriver, cursorDriver].map((d) => [d.kind, d])
3106
+ );
3107
+ function agentDriver(kind = DEFAULT_AGENT_KIND) {
3108
+ const driver = DRIVERS.get(kind || DEFAULT_AGENT_KIND);
3109
+ if (!driver) throw new Error(`This runner cannot run "${kind}" agents.`);
3110
+ return driver;
3111
+ }
3112
+ function agentDriverKinds() {
3113
+ return [...DRIVERS.keys()];
3114
+ }
3115
+
3116
+ // src/config.ts
3117
+ import { chmod, mkdir as mkdir3, readFile as readFile3, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
3118
+ import { homedir as homedir2 } from "node:os";
3119
+ import { dirname as dirname3, join as join7 } from "node:path";
3120
+
3121
+ // src/invocation.ts
3122
+ var RUNNER_PACKAGE = "@discovery-tree/runner";
3123
+ function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
3124
+ if (env.npm_command === "exec") return true;
3125
+ return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
3126
+ }
3127
+ function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
3128
+ return viaNpx ? `npx ${RUNNER_PACKAGE}@latest ${subcommand}` : `dt-runner ${subcommand}`;
3129
+ }
3130
+
3131
+ // src/config.ts
3132
+ function runnerPaths(env = process.env) {
3133
+ const home = homedir2();
3134
+ if (process.platform === "win32") {
3135
+ const roaming = env.APPDATA || join7(home, "AppData", "Roaming");
3136
+ const local = env.LOCALAPPDATA || join7(home, "AppData", "Local");
3137
+ return {
3138
+ configFile: join7(roaming, "discovery-tree", "runner.json"),
3139
+ dataDir: join7(local, "discovery-tree", "runner"),
3140
+ stateDir: join7(local, "discovery-tree", "runner", "state")
3141
+ };
3142
+ }
3143
+ const config = env.XDG_CONFIG_HOME || join7(home, ".config");
3144
+ const data = env.XDG_DATA_HOME || join7(home, ".local", "share");
3145
+ const state = env.XDG_STATE_HOME || join7(home, ".local", "state");
3146
+ return {
3147
+ configFile: join7(config, "discovery-tree", "runner.json"),
3148
+ dataDir: join7(data, "discovery-tree", "runner"),
3149
+ stateDir: join7(state, "discovery-tree", "runner")
3150
+ };
3151
+ }
3152
+ var PERMISSION_MODES = [
3153
+ "acceptEdits",
3154
+ "auto",
3155
+ "default",
3156
+ "manual",
3157
+ "dontAsk",
3158
+ "plan",
3159
+ "bypassPermissions"
3160
+ ];
3161
+ var DEFAULT_ALLOWED_TOOLS = [
3162
+ "Read",
3163
+ "Edit",
3164
+ "MultiEdit",
3165
+ "Write",
3166
+ "Glob",
3167
+ "Grep",
3168
+ "LS",
3169
+ "NotebookEdit",
3170
+ "TodoWrite",
3171
+ "Task",
3172
+ // Stops a command started with the Bash tool's background option (a dev server); its
3173
+ // output is a file the agent reads with Read.
3174
+ "TaskStop",
3175
+ "Bash(git status *)",
3176
+ "Bash(git diff *)",
3177
+ "Bash(git log *)",
3178
+ "Bash(git show *)",
1333
3179
  "Bash(git add *)",
1334
3180
  "Bash(git commit *)",
1335
3181
  "Bash(git restore *)",
@@ -1495,7 +3341,7 @@ var DEFAULT_DISALLOWED_TOOLS = [
1495
3341
  ];
1496
3342
  function configDirRules(configFile, platform = process.platform) {
1497
3343
  if (platform === "win32") return [];
1498
- const dir = dirname2(configFile);
3344
+ const dir = dirname3(configFile);
1499
3345
  if (!dir.startsWith("/")) return [];
1500
3346
  return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
1501
3347
  }
@@ -1505,7 +3351,7 @@ var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
1505
3351
  async function readConfigFile(file) {
1506
3352
  let raw;
1507
3353
  try {
1508
- raw = await readFile2(file, "utf8");
3354
+ raw = await readFile3(file, "utf8");
1509
3355
  } catch (err) {
1510
3356
  if (err.code === "ENOENT") return null;
1511
3357
  throw err;
@@ -1519,7 +3365,7 @@ async function readConfigFile(file) {
1519
3365
  }
1520
3366
  }
1521
3367
  async function writeConfigFile(file, config) {
1522
- await mkdir3(dirname2(file), { recursive: true, mode: 448 });
3368
+ await mkdir3(dirname3(file), { recursive: true, mode: 448 });
1523
3369
  await writeFile2(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
1524
3370
  await chmod(file, 384).catch(() => void 0);
1525
3371
  }
@@ -1556,6 +3402,24 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
1556
3402
  `inheritClaudeCodePermissions in ${paths.configFile} must be true or false (got ${JSON.stringify(inherit)}).`
1557
3403
  );
1558
3404
  }
3405
+ const codexSandbox = file?.codexSandbox ?? "workspace-write";
3406
+ if (codexSandbox !== "workspace-write" && codexSandbox !== "danger-full-access") {
3407
+ throw new Error(
3408
+ `codexSandbox "${String(codexSandbox)}" in ${paths.configFile} is not one of workspace-write, danger-full-access.`
3409
+ );
3410
+ }
3411
+ const codexNetwork = file?.codexNetworkAccess;
3412
+ if (codexNetwork !== void 0 && typeof codexNetwork !== "boolean") {
3413
+ throw new Error(
3414
+ `codexNetworkAccess in ${paths.configFile} must be true or false (got ${JSON.stringify(codexNetwork)}).`
3415
+ );
3416
+ }
3417
+ const cursorForce = file?.cursorForce;
3418
+ if (cursorForce !== void 0 && typeof cursorForce !== "boolean") {
3419
+ throw new Error(
3420
+ `cursorForce in ${paths.configFile} must be true or false (got ${JSON.stringify(cursorForce)}).`
3421
+ );
3422
+ }
1559
3423
  const allowed = [
1560
3424
  ...file?.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
1561
3425
  ...file?.extraAllowedTools ?? []
@@ -1573,8 +3437,8 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
1573
3437
  token: env.DT_RUNNER_TOKEN || file?.token || null,
1574
3438
  name: file?.name ?? null,
1575
3439
  maxSessions,
1576
- reposDir: overrides.reposDir ?? file?.reposDir ?? join5(paths.dataDir, "repos"),
1577
- worktreesDir: file?.worktreesDir ?? join5(paths.dataDir, "worktrees"),
3440
+ reposDir: overrides.reposDir ?? file?.reposDir ?? join7(paths.dataDir, "repos"),
3441
+ worktreesDir: file?.worktreesDir ?? join7(paths.dataDir, "worktrees"),
1578
3442
  permissionMode: mode,
1579
3443
  allowedTools: [...new Set(allowed)],
1580
3444
  disallowedTools: [...new Set(disallowed)],
@@ -1583,13 +3447,16 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
1583
3447
  inheritClaudeCodePermissions: inherit !== false,
1584
3448
  gitProtocol: file?.gitProtocol === "ssh" ? "ssh" : "https",
1585
3449
  idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
3450
+ codexSandbox,
3451
+ codexNetworkAccess: codexNetwork === true,
3452
+ cursorForce: cursorForce === true,
1586
3453
  stateDir: paths.stateDir,
1587
3454
  configFile: paths.configFile
1588
3455
  };
1589
3456
  }
1590
3457
 
1591
3458
  // src/daemon.ts
1592
- import { join as join11 } from "node:path";
3459
+ import { join as join12 } from "node:path";
1593
3460
 
1594
3461
  // src/backoff.ts
1595
3462
  function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
@@ -1612,7 +3479,7 @@ function sleep(ms, signal) {
1612
3479
  // src/completion.ts
1613
3480
  import { mkdtemp as mkdtemp2, rm as rm4 } from "node:fs/promises";
1614
3481
  import { tmpdir as tmpdir2 } from "node:os";
1615
- import { join as join6 } from "node:path";
3482
+ import { join as join8 } from "node:path";
1616
3483
  var COMPLETION_DENIED_TOOLS = [
1617
3484
  "Read",
1618
3485
  "Glob",
@@ -1660,7 +3527,7 @@ async function answerCompletion(req, deps) {
1660
3527
  try {
1661
3528
  const { bin, features } = await deps.claude();
1662
3529
  const args = completionArgs(req, features);
1663
- cwd = await mkdtemp2(join6(tmpdir2(), "dt-runner-completion-"));
3530
+ cwd = await mkdtemp2(join8(tmpdir2(), "dt-runner-completion-"));
1664
3531
  const run = deps.run ?? ((b, a, o) => exec(b, a, { ...o, ownTree: true }));
1665
3532
  const input = req.systemPrompt ? `<instructions>
1666
3533
  ${req.systemPrompt}
@@ -1713,20 +3580,20 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
1713
3580
 
1714
3581
  // src/session-manager.ts
1715
3582
  import { mkdir as mkdir6, rm as rm6, writeFile as writeFile4 } from "node:fs/promises";
1716
- import { join as join10 } from "node:path";
3583
+ import { join as join11 } from "node:path";
1717
3584
 
1718
3585
  // src/fsutil.ts
1719
- import { mkdir as mkdir4, readFile as readFile3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
1720
- import { dirname as dirname3 } from "node:path";
3586
+ import { mkdir as mkdir4, readFile as readFile4, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
3587
+ import { dirname as dirname4 } from "node:path";
1721
3588
  async function writeJsonAtomic(file, value) {
1722
- await mkdir4(dirname3(file), { recursive: true });
3589
+ await mkdir4(dirname4(file), { recursive: true });
1723
3590
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
1724
3591
  await writeFile3(tmp, JSON.stringify(value), { mode: 384 });
1725
3592
  await rename2(tmp, file);
1726
3593
  }
1727
3594
  async function readJson(file) {
1728
3595
  try {
1729
- return JSON.parse(await readFile3(file, "utf8"));
3596
+ return JSON.parse(await readFile4(file, "utf8"));
1730
3597
  } catch (err) {
1731
3598
  if (err.code === "ENOENT") return null;
1732
3599
  if (err instanceof SyntaxError) return null;
@@ -1929,251 +3796,51 @@ var SessionOutbox = class _SessionOutbox {
1929
3796
  await sleep(
1930
3797
  backoffDelay(attempt++, this.opts.retryBaseMs ?? 1e3),
1931
3798
  this.stopController.signal
1932
- );
1933
- } finally {
1934
- this.inFlightUpTo = 0;
1935
- }
1936
- }
1937
- } finally {
1938
- this.pumping = false;
1939
- }
1940
- if (!this.pending.length || this.closed) this.notifyIdle();
1941
- else if (!this.stopped) this.schedulePump();
1942
- }
1943
- markClosed(reason) {
1944
- this.opts.logger.info(`session ${this.opts.sessionId}: ${reason}`);
1945
- this.discard();
1946
- this.opts.onClosed?.();
1947
- }
1948
- notifyIdle() {
1949
- const waiters = this.idleWaiters;
1950
- this.idleWaiters = [];
1951
- for (const w of waiters) w();
1952
- }
1953
- };
1954
- function takeBatch(pending) {
1955
- const budget = RUNNER_EVENTS_MAX_BODY_BYTES / 2;
1956
- let bytes = 0;
1957
- let n = 0;
1958
- while (n < pending.length && n < RUNNER_EVENTS_MAX_BATCH) {
1959
- const size = Buffer.byteLength(JSON.stringify(pending[n]));
1960
- if (n > 0 && bytes + size > budget) break;
1961
- bytes += size;
1962
- n++;
1963
- }
1964
- return pending.slice(0, n);
1965
- }
1966
-
1967
- // src/session.ts
1968
- import { spawn as spawn3 } from "node:child_process";
1969
- import { randomUUID as randomUUID2 } from "node:crypto";
1970
- import { basename, dirname as dirname6 } from "node:path";
1971
- import { createInterface } from "node:readline";
1972
-
1973
- // src/permissions.ts
1974
- import { randomUUID } from "node:crypto";
1975
- function parseCanUseTool(line) {
1976
- if (line?.type !== "control_request") return null;
1977
- const req = line.request;
1978
- if (!req || req.subtype !== "can_use_tool") return null;
1979
- if (typeof line.request_id !== "string" || !line.request_id) return null;
1980
- const toolName = typeof req.tool_name === "string" && req.tool_name ? req.tool_name : "tool";
1981
- return { controlRequestId: line.request_id, toolName, input: req.input ?? {} };
1982
- }
1983
- function parseControlCancel(line) {
1984
- if (line?.type !== "control_cancel_request") return null;
1985
- return typeof line.request_id === "string" ? line.request_id : null;
1986
- }
1987
- function summarizeToolInput(toolName, input) {
1988
- const i = input && typeof input === "object" ? input : {};
1989
- const s = (v) => typeof v === "string" && v.trim() ? v : null;
1990
- let summary = null;
1991
- switch (toolName) {
1992
- case "Bash":
1993
- summary = s(i.command);
1994
- break;
1995
- case "WebFetch":
1996
- summary = s(i.url);
1997
- break;
1998
- case "WebSearch":
1999
- summary = s(i.query);
2000
- break;
2001
- case "Read":
2002
- case "Edit":
2003
- case "MultiEdit":
2004
- case "Write":
2005
- summary = s(i.file_path);
2006
- break;
2007
- case "NotebookEdit":
2008
- summary = s(i.notebook_path);
2009
- break;
2010
- case "Glob":
2011
- case "Grep":
2012
- summary = s(i.pattern) ? `${i.pattern}${s(i.path) ? ` in ${i.path}` : ""}` : null;
2013
- break;
2014
- }
2015
- if (summary === null) {
2016
- try {
2017
- summary = JSON.stringify(input) ?? "";
2018
- } catch {
2019
- summary = "";
2020
- }
2021
- }
2022
- return cut(summary, AGENT_PERMISSION_INPUT_SUMMARY_MAX_LENGTH);
2023
- }
2024
- function cut(text, max) {
2025
- return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
2026
- }
2027
- var PERMISSION_EXPIRED_TURN_ENDED = "The turn ended before anyone answered.";
2028
- var PERMISSION_EXPIRED_INTERRUPTED = "The turn was interrupted before anyone answered.";
2029
- var PERMISSION_EXPIRED_STOPPED = "Claude Code stopped before anyone answered.";
2030
- var PERMISSION_EXPIRED_TIMEOUT = `Nobody answered within ${Math.round(
2031
- RUNNER_PERMISSION_REQUEST_TIMEOUT_MS / 6e4
2032
- )} minutes.`;
2033
- var PERMISSION_EXPIRED_CANCELLED = "Claude Code stopped waiting for an answer.";
2034
- var PERMISSION_EXPIRED_UNKNOWN = "The runner no longer has this request (it may have restarted), so the answer could not be applied.";
2035
- var DENIED_MESSAGE = "The person denied permission for this tool call in Discovery Tree.";
2036
- var SETTLED_KEPT = 200;
2037
- var PermissionRelay = class {
2038
- constructor(deps) {
2039
- this.deps = deps;
2040
- }
2041
- pending = /* @__PURE__ */ new Map();
2042
- byControlId = /* @__PURE__ */ new Map();
2043
- settled = /* @__PURE__ */ new Map();
2044
- get pendingCount() {
2045
- return this.pending.size;
2046
- }
2047
- /** Claude Code asks; returns whether it was allowed at once or relayed. */
2048
- request(req) {
2049
- if (this.deps.alwaysAllowed().includes(req.toolName) || this.deps.grantedByRule?.(req.toolName, req.input)) {
2050
- this.deps.respond(req.controlRequestId, { behavior: "allow", updatedInput: req.input });
2051
- return "auto_allowed";
2052
- }
2053
- const id = (this.deps.newId ?? randomUUID)();
2054
- const requestedAt = (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
2055
- const timer = setTimeout(
2056
- () => this.expire(id, PERMISSION_EXPIRED_TIMEOUT, true),
2057
- this.deps.timeoutMs ?? RUNNER_PERMISSION_REQUEST_TIMEOUT_MS
2058
- );
2059
- timer.unref?.();
2060
- const pending = {
2061
- id,
2062
- controlRequestId: req.controlRequestId,
2063
- toolName: req.toolName,
2064
- input: req.input,
2065
- inputSummary: summarizeToolInput(req.toolName, req.input),
2066
- requestedAt,
2067
- timer
2068
- };
2069
- this.pending.set(id, pending);
2070
- this.byControlId.set(req.controlRequestId, id);
2071
- const suggestedRule = this.deps.suggestRule?.(req.toolName, req.input) ?? null;
2072
- this.deps.emit({
2073
- type: "permission_request",
2074
- request: {
2075
- id,
2076
- toolName: pending.toolName,
2077
- inputSummary: pending.inputSummary,
2078
- ...suggestedRule ? { suggestedRule } : {},
2079
- requestedAt,
2080
- status: "pending"
2081
- }
2082
- });
2083
- return "relayed";
2084
- }
2085
- /** A person's decision, from the server. */
2086
- decide(requestId, decision) {
2087
- const pending = this.pending.get(requestId);
2088
- if (!pending) {
2089
- const settled = this.settled.get(requestId);
2090
- if (settled === "decided") return "already_applied";
2091
- if (settled === void 0) {
2092
- this.settle(requestId, "expired");
2093
- this.deps.emit({
2094
- type: "permission_request",
2095
- request: {
2096
- id: requestId,
2097
- toolName: "tool",
2098
- inputSummary: "",
2099
- requestedAt: (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
2100
- status: "expired",
2101
- expiredReason: PERMISSION_EXPIRED_UNKNOWN
2102
- }
2103
- });
2104
- }
2105
- return "not_pending";
2106
- }
2107
- this.forget(pending);
2108
- this.settle(requestId, "decided");
2109
- if (decision.behavior === "allow") {
2110
- if (decision.alwaysAllowTool && !this.deps.alwaysAllowed().includes(pending.toolName)) {
2111
- this.deps.rememberAlwaysAllowed(pending.toolName);
3799
+ );
3800
+ } finally {
3801
+ this.inFlightUpTo = 0;
3802
+ }
2112
3803
  }
2113
- const rule = decision.alwaysAllowRule?.trim();
2114
- if (rule && toolGrantRuleProblem(rule) === null) this.deps.rememberRule?.(rule);
2115
- this.deps.respond(pending.controlRequestId, {
2116
- behavior: "allow",
2117
- updatedInput: pending.input
2118
- });
2119
- } else {
2120
- const message = decision.message?.trim();
2121
- this.deps.respond(pending.controlRequestId, {
2122
- behavior: "deny",
2123
- message: message ? `${DENIED_MESSAGE} Their message: ${cut(message, AGENT_PERMISSION_MESSAGE_MAX_LENGTH)}` : DENIED_MESSAGE
2124
- });
2125
- }
2126
- return "applied";
2127
- }
2128
- /** Claude Code withdrew a request (it stopped waiting): expired, nothing to answer. */
2129
- cancel(controlRequestId) {
2130
- const id = this.byControlId.get(controlRequestId);
2131
- if (id) this.expire(id, PERMISSION_EXPIRED_CANCELLED, false);
2132
- }
2133
- /** Expire everything still waiting, answering Claude Code with a denial. */
2134
- expireAll(reason) {
2135
- for (const id of [...this.pending.keys()]) this.expire(id, reason, true);
2136
- }
2137
- expire(id, reason, answerClaude) {
2138
- const pending = this.pending.get(id);
2139
- if (!pending) return;
2140
- this.forget(pending);
2141
- this.settle(id, "expired");
2142
- if (answerClaude) {
2143
- this.deps.respond(pending.controlRequestId, {
2144
- behavior: "deny",
2145
- message: `Permission for this tool call was not granted: ${reason}`
2146
- });
3804
+ } finally {
3805
+ this.pumping = false;
2147
3806
  }
2148
- this.deps.emit({
2149
- type: "permission_request",
2150
- request: {
2151
- id,
2152
- toolName: pending.toolName,
2153
- inputSummary: pending.inputSummary,
2154
- requestedAt: pending.requestedAt,
2155
- status: "expired",
2156
- expiredReason: reason
2157
- }
2158
- });
3807
+ if (!this.pending.length || this.closed) this.notifyIdle();
3808
+ else if (!this.stopped) this.schedulePump();
2159
3809
  }
2160
- forget(pending) {
2161
- clearTimeout(pending.timer);
2162
- this.pending.delete(pending.id);
2163
- this.byControlId.delete(pending.controlRequestId);
3810
+ markClosed(reason) {
3811
+ this.opts.logger.info(`session ${this.opts.sessionId}: ${reason}`);
3812
+ this.discard();
3813
+ this.opts.onClosed?.();
2164
3814
  }
2165
- settle(id, how) {
2166
- this.settled.set(id, how);
2167
- while (this.settled.size > SETTLED_KEPT) {
2168
- this.settled.delete(this.settled.keys().next().value);
2169
- }
3815
+ notifyIdle() {
3816
+ const waiters = this.idleWaiters;
3817
+ this.idleWaiters = [];
3818
+ for (const w of waiters) w();
2170
3819
  }
2171
3820
  };
3821
+ function takeBatch(pending) {
3822
+ const budget = RUNNER_EVENTS_MAX_BODY_BYTES / 2;
3823
+ let bytes = 0;
3824
+ let n = 0;
3825
+ while (n < pending.length && n < RUNNER_EVENTS_MAX_BATCH) {
3826
+ const size = Buffer.byteLength(JSON.stringify(pending[n]));
3827
+ if (n > 0 && bytes + size > budget) break;
3828
+ bytes += size;
3829
+ n++;
3830
+ }
3831
+ return pending.slice(0, n);
3832
+ }
3833
+
3834
+ // src/session.ts
3835
+ import { spawn as spawn4 } from "node:child_process";
3836
+ import { randomUUID as randomUUID2 } from "node:crypto";
3837
+ import { basename, dirname as dirname6 } from "node:path";
3838
+ import { createInterface as createInterface2 } from "node:readline";
2172
3839
 
2173
3840
  // src/tool-grants.ts
2174
- import { dirname as dirname4, join as join7, posix } from "node:path";
3841
+ import { dirname as dirname5, join as join9, posix } from "node:path";
2175
3842
  var isGrantableDenial = isGrantableToolDenial;
2176
- var FILE_TOOLS = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
3843
+ var FILE_TOOLS2 = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
2177
3844
  var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
2178
3845
  function suggestRules(toolName, input, allowedTools = []) {
2179
3846
  const i = input && typeof input === "object" ? input : {};
@@ -2185,7 +3852,7 @@ function suggestRules(toolName, input, allowedTools = []) {
2185
3852
  } else if (toolName === "WebFetch") {
2186
3853
  const host = hostOf(str(i.url));
2187
3854
  if (host) out = same(`WebFetch(domain:${host})`);
2188
- } else if (FILE_TOOLS.has(toolName)) {
3855
+ } else if (FILE_TOOLS2.has(toolName)) {
2189
3856
  const file = str(i.file_path) ?? str(i.notebook_path);
2190
3857
  const ruleTool = EDIT_TOOLS.has(toolName) ? "Edit" : "Read";
2191
3858
  if (file) {
@@ -2278,7 +3945,7 @@ function ruleAllows(rule, toolName, input) {
2278
3945
  if (toolName === "WebFetch" && parsed.spec.startsWith("domain:")) {
2279
3946
  return hostOf(typeof i.url === "string" ? i.url : null) === parsed.spec.slice(7).toLowerCase();
2280
3947
  }
2281
- if (FILE_TOOLS.has(toolName)) {
3948
+ if (FILE_TOOLS2.has(toolName)) {
2282
3949
  const file = typeof i.file_path === "string" ? i.file_path : typeof i.notebook_path === "string" ? i.notebook_path : "";
2283
3950
  return filePatternMatches(parsed.spec, file);
2284
3951
  }
@@ -2313,7 +3980,7 @@ function grantsCover(granted, base, toolName, input) {
2313
3980
  function askedFor(rules, toolName, input) {
2314
3981
  if (rules.length === 0) return false;
2315
3982
  if (rules.some((rule) => rule.trim() === toolName)) return true;
2316
- if (FILE_TOOLS.has(toolName)) {
3983
+ if (FILE_TOOLS2.has(toolName)) {
2317
3984
  const family = EDIT_TOOLS.has(toolName) ? "Edit" : toolName;
2318
3985
  const relative = rules.some((rule) => {
2319
3986
  const parsed = parseRule(rule);
@@ -2369,7 +4036,7 @@ function filePatternMatches(spec, file) {
2369
4036
  let pattern = spec.trim();
2370
4037
  if (pattern.startsWith("~/")) {
2371
4038
  if (!home) return false;
2372
- pattern = rulePath(join7(home, pattern.slice(2)).replace(/\\/g, "/"));
4039
+ pattern = rulePath(join9(home, pattern.slice(2)).replace(/\\/g, "/"));
2373
4040
  }
2374
4041
  if (!pattern.startsWith("//")) return false;
2375
4042
  const path = rulePath(file);
@@ -2390,7 +4057,7 @@ function shellPatternMatches(spec, command) {
2390
4057
  return new RegExp(`^${re}${optionalTail ? "(?: .*)?" : ""}$`, "s").test(command);
2391
4058
  }
2392
4059
  function toolGrantsFile(configFile) {
2393
- return join7(dirname4(configFile), "tool-grants.json");
4060
+ return join9(dirname5(configFile), "tool-grants.json");
2394
4061
  }
2395
4062
  var ToolGrantStore = class {
2396
4063
  constructor(file) {
@@ -2433,230 +4100,38 @@ var ToolGrantStore = class {
2433
4100
  await this.change(async (grants) => {
2434
4101
  const next = grants.filter((g) => g.id !== id);
2435
4102
  removed = next.length !== grants.length;
2436
- return next;
2437
- });
2438
- return removed;
2439
- }
2440
- /** Applies the changes a heartbeat answer handed over; each failure is returned, not thrown. */
2441
- async apply(changes) {
2442
- const problems = [];
2443
- for (const c of changes) {
2444
- try {
2445
- if (c?.op === "add" && c.grant) await this.add(c.grant);
2446
- else if (c?.op === "revoke" && typeof c.id === "string") await this.revoke(c.id);
2447
- } catch (err) {
2448
- problems.push(err.message);
2449
- }
2450
- }
2451
- return problems;
2452
- }
2453
- change(fn) {
2454
- const run = this.chain.then(async () => {
2455
- const current = await this.list();
2456
- const next = await fn(current);
2457
- if (next === current) return;
2458
- await writeJsonAtomic(this.file, { version: 1, grants: next });
2459
- this.cache = next;
2460
- });
2461
- this.chain = run.catch(() => void 0);
2462
- return run;
2463
- }
2464
- };
2465
- function isUsableGrant(g) {
2466
- const x = g;
2467
- return !!x && typeof x.id === "string" && typeof x.repository === "string" && typeof x.rule === "string" && toolGrantRuleProblem(x.rule) === null;
2468
- }
2469
-
2470
- // src/claude-code-rules.ts
2471
- import { readFile as readFile4, stat as stat3 } from "node:fs/promises";
2472
- import { homedir as homedir2 } from "node:os";
2473
- import { dirname as dirname5, isAbsolute as isAbsolute3, join as join8, resolve, sep } from "node:path";
2474
- var EMPTY = { allow: [], deny: [], ask: [], sources: [] };
2475
- var RULE_SHAPE2 = /^(?:mcp__[A-Za-z0-9_-]+__\*|[A-Za-z][A-Za-z0-9_.-]*(?:\([\s\S]*\))?)$/;
2476
- var FILE_TOOLS2 = /* @__PURE__ */ new Set([
2477
- "Read",
2478
- "Edit",
2479
- "Write",
2480
- "MultiEdit",
2481
- "NotebookEdit",
2482
- "Glob",
2483
- "Grep",
2484
- "LS"
2485
- ]);
2486
- function usableRule(raw, kind, committed) {
2487
- if (typeof raw !== "string") return null;
2488
- const rule = raw.trim();
2489
- if (!rule || rule.length > TOOL_GRANT_RULE_MAX_LENGTH) return null;
2490
- if (/[\u0000-\u001f\u007f]/.test(rule) || !RULE_SHAPE2.test(rule)) return null;
2491
- const tool = /^([A-Za-z][A-Za-z0-9_.-]*)/.exec(rule)?.[1] ?? "";
2492
- if (kind === "allow" && FILE_TOOLS2.has(tool)) return null;
2493
- if (kind === "allow" && committed && toolGrantRuleProblem(rule) !== null) return null;
2494
- return rule;
2495
- }
2496
- function remoteRepositoryKey(url) {
2497
- const u = url.trim();
2498
- const ssh = /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
2499
- if (ssh) return toolGrantRepositoryKey(`https://github.com/${ssh[1]}/${ssh[2]}`);
2500
- const https = /^(?:https?|git):\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
2501
- if (https) return toolGrantRepositoryKey(`https://github.com/${https[1]}/${https[2]}`);
2502
- return null;
2503
- }
2504
- async function readText(file) {
2505
- try {
2506
- return await readFile4(file, "utf8");
2507
- } catch {
2508
- return null;
2509
- }
2510
- }
2511
- async function readJsonFile(file) {
2512
- const text = await readText(file);
2513
- if (text === null) return null;
2514
- try {
2515
- return JSON.parse(text);
2516
- } catch {
2517
- return null;
2518
- }
2519
- }
2520
- async function isDir(path) {
2521
- try {
2522
- return (await stat3(path)).isDirectory();
2523
- } catch {
2524
- return false;
2525
- }
2526
- }
2527
- async function gitConfigOf(folder) {
2528
- let dir = folder;
2529
- for (let i = 0; i < 6; i++) {
2530
- const dotGit = join8(dir, ".git");
2531
- if (await isDir(dotGit)) return { config: join8(dotGit, "config"), roots: [dir] };
2532
- const pointer = await readText(dotGit);
2533
- const gitdir = pointer && /^gitdir:\s*(.+)\s*$/m.exec(pointer)?.[1];
2534
- if (gitdir) {
2535
- const linked = resolve(dir, gitdir);
2536
- const common = (await readText(join8(linked, "commondir")))?.trim();
2537
- const commonDir = common ? resolve(linked, common) : linked;
2538
- return { config: join8(commonDir, "config"), roots: [dir, dirname5(commonDir)] };
2539
- }
2540
- const up = dirname5(dir);
2541
- if (up === dir) break;
2542
- dir = up;
2543
- }
2544
- return null;
2545
- }
2546
- function remoteKeys(config) {
2547
- const keys = /* @__PURE__ */ new Set();
2548
- let inRemote = false;
2549
- for (const line of config.split(/\r?\n/)) {
2550
- const section = /^\s*\[([^\]]*)\]/.exec(line);
2551
- if (section) {
2552
- inRemote = /^remote\s+"/i.test(section[1].trim());
2553
- continue;
2554
- }
2555
- if (!inRemote) continue;
2556
- const url = /^\s*url\s*=\s*(.+?)\s*$/i.exec(line);
2557
- const key = url ? remoteRepositoryKey(url[1]) : null;
2558
- if (key) keys.add(key);
2559
- }
2560
- return keys;
2561
- }
2562
- function rulesIn(settings, kind, committed) {
2563
- const perms = settings?.permissions;
2564
- const list = perms?.[kind];
2565
- if (!Array.isArray(list)) return [];
2566
- return list.map((r) => usableRule(r, kind, committed)).filter((r) => r !== null);
2567
- }
2568
- var ClaudeCodeRules = class {
2569
- claudeJson;
2570
- exclude;
2571
- cacheMs;
2572
- cache = /* @__PURE__ */ new Map();
2573
- constructor(opts = {}) {
2574
- this.claudeJson = opts.claudeJson ?? (process.env.CLAUDE_CONFIG_DIR ? join8(process.env.CLAUDE_CONFIG_DIR, ".claude.json") : join8(homedir2(), ".claude.json"));
2575
- this.exclude = (opts.exclude ?? []).map((p) => resolve(p));
2576
- this.cacheMs = opts.cacheMs ?? 3e4;
2577
- }
2578
- /** The rules for a repository URL; none for a session without a GitHub repository. */
2579
- rulesFor(repositoryUrl) {
2580
- const key = toolGrantRepositoryKey(repositoryUrl);
2581
- if (!key) return Promise.resolve(EMPTY);
2582
- const hit = this.cache.get(key);
2583
- if (hit && Date.now() - hit.at < this.cacheMs) return hit.rules;
2584
- const rules = this.read(key).catch(() => EMPTY);
2585
- this.cache.set(key, { at: Date.now(), rules });
2586
- return rules;
2587
- }
2588
- excluded(folder) {
2589
- const f = resolve(folder);
2590
- return this.exclude.some((ex) => f === ex || f.startsWith(ex + sep));
2591
- }
2592
- async read(key) {
2593
- const global = await readJsonFile(this.claudeJson);
2594
- const projects = global?.projects;
2595
- if (!projects || typeof projects !== "object") return EMPTY;
2596
- const allow = /* @__PURE__ */ new Set();
2597
- const deny = /* @__PURE__ */ new Set();
2598
- const ask = /* @__PURE__ */ new Set();
2599
- const sources = [];
2600
- const checkouts = [];
2601
- for (const [folder, entry] of Object.entries(projects)) {
2602
- if (!entry || entry.hasTrustDialogAccepted !== true) continue;
2603
- if (!isAbsolute3(folder) || this.excluded(folder)) continue;
2604
- const git2 = await gitConfigOf(folder);
2605
- const text = git2 ? await readText(git2.config) : null;
2606
- if (!git2 || !text || !remoteKeys(text).has(key)) continue;
2607
- const roots = [...new Set([folder, ...git2.roots].map((d) => resolve(d)))];
2608
- const legacy = Array.isArray(entry.allowedTools) ? entry.allowedTools : [];
2609
- checkouts.push({ folder, roots, legacy });
2610
- }
2611
- for (const { folder, roots, legacy } of checkouts) {
2612
- const found = [];
2613
- const denied = [];
2614
- const asked = [];
2615
- for (const dir of roots) {
2616
- const local = await readJsonFile(join8(dir, ".claude", "settings.local.json"));
2617
- const shared = await readJsonFile(join8(dir, ".claude", "settings.json"));
2618
- found.push(...rulesIn(local, "allow", false), ...rulesIn(shared, "allow", true));
2619
- denied.push(...rulesIn(local, "deny", false), ...rulesIn(shared, "deny", false));
2620
- asked.push(...rulesIn(local, "ask", false), ...rulesIn(shared, "ask", false));
4103
+ return next;
4104
+ });
4105
+ return removed;
4106
+ }
4107
+ /** Applies the changes a heartbeat answer handed over; each failure is returned, not thrown. */
4108
+ async apply(changes) {
4109
+ const problems = [];
4110
+ for (const c of changes) {
4111
+ try {
4112
+ if (c?.op === "add" && c.grant) await this.add(c.grant);
4113
+ else if (c?.op === "revoke" && typeof c.id === "string") await this.revoke(c.id);
4114
+ } catch (err) {
4115
+ problems.push(err.message);
2621
4116
  }
2622
- found.push(
2623
- ...legacy.map((r) => usableRule(r, "allow", false)).filter((r) => r !== null)
2624
- );
2625
- const kept = found;
2626
- if (kept.length || denied.length || asked.length) sources.push(folder);
2627
- for (const r of kept) allow.add(r);
2628
- for (const r of denied) deny.add(r);
2629
- for (const r of asked) ask.add(r);
2630
4117
  }
2631
- return {
2632
- allow: [...allow].filter((r) => !deny.has(r) && !ask.has(r)),
2633
- deny: [...deny],
2634
- ask: [...ask].filter((r) => !deny.has(r)),
2635
- sources
2636
- };
4118
+ return problems;
4119
+ }
4120
+ change(fn) {
4121
+ const run = this.chain.then(async () => {
4122
+ const current2 = await this.list();
4123
+ const next = await fn(current2);
4124
+ if (next === current2) return;
4125
+ await writeJsonAtomic(this.file, { version: 1, grants: next });
4126
+ this.cache = next;
4127
+ });
4128
+ this.chain = run.catch(() => void 0);
4129
+ return run;
2637
4130
  }
2638
4131
  };
2639
- function ruleHead(rule) {
2640
- const m = /^([A-Za-z][A-Za-z0-9_.-]*(?:__\*)?)(?:\(([\s\S]*)\))?$/.exec(rule.trim());
2641
- if (!m) return null;
2642
- const spec = m[2];
2643
- if (spec === void 0) return { tool: m[1], head: null };
2644
- return { tool: m[1], head: spec.replace(/:\*$/, " *").split("*")[0] };
2645
- }
2646
- function sameTool(a, b) {
2647
- if (a === b) return true;
2648
- const wild = (w, t) => w.endsWith("__*") && t.startsWith(w.slice(0, -1));
2649
- return wild(a, b) || wild(b, a);
2650
- }
2651
- function overlapsAsk(allowRule, askRules) {
2652
- const a = ruleHead(allowRule);
2653
- if (!a) return false;
2654
- return askRules.some((rule) => {
2655
- const q = ruleHead(rule);
2656
- if (!q || !sameTool(a.tool, q.tool)) return false;
2657
- if (a.head === null || q.head === null) return true;
2658
- return a.head.startsWith(q.head) || q.head.startsWith(a.head);
2659
- });
4132
+ function isUsableGrant(g) {
4133
+ const x = g;
4134
+ return !!x && typeof x.id === "string" && typeof x.repository === "string" && typeof x.rule === "string" && toolGrantRuleProblem(x.rule) === null;
2660
4135
  }
2661
4136
 
2662
4137
  // src/pull-request.ts
@@ -2749,271 +4224,49 @@ function ghError(command, res) {
2749
4224
 
2750
4225
  // src/session-store.ts
2751
4226
  import { mkdir as mkdir5, readdir as readdir2, rm as rm5 } from "node:fs/promises";
2752
- import { join as join9 } from "node:path";
4227
+ import { join as join10 } from "node:path";
2753
4228
  var HANDLED_COMMAND_IDS_KEPT = 100;
2754
4229
  var SessionStore = class {
2755
4230
  constructor(stateDir) {
2756
4231
  this.stateDir = stateDir;
2757
4232
  }
2758
- dir(sessionId) {
2759
- return join9(this.stateDir, "sessions", sessionId);
2760
- }
2761
- outboxFile(sessionId) {
2762
- return join9(this.dir(sessionId), "outbox.json");
2763
- }
2764
- async save(record) {
2765
- record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2766
- await writeJsonAtomic(join9(this.dir(record.sessionId), "session.json"), record);
2767
- }
2768
- async list() {
2769
- const root = join9(this.stateDir, "sessions");
2770
- await mkdir5(root, { recursive: true });
2771
- const out = [];
2772
- for (const entry of await readdir2(root, { withFileTypes: true })) {
2773
- if (!entry.isDirectory()) continue;
2774
- const rec = await readJson(join9(root, entry.name, "session.json"));
2775
- if (rec?.sessionId === entry.name) out.push(rec);
2776
- }
2777
- return out;
2778
- }
2779
- async remove(sessionId) {
2780
- await rm5(this.dir(sessionId), { recursive: true, force: true });
2781
- }
2782
- /** Scratch working directory for a session without a repository. */
2783
- scratchDir(sessionId) {
2784
- return join9(this.stateDir, "scratch", sessionId);
2785
- }
2786
- };
2787
- function assertSafeSessionId(id) {
2788
- if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(id) || id.includes("..")) {
2789
- throw new Error(`Session id "${id}" is not usable as a directory name.`);
2790
- }
2791
- }
2792
-
2793
- // src/stream-mapper.ts
2794
- function capText(text, max = RUNNER_EVENT_TEXT_MAX_LENGTH) {
2795
- if (text.length <= max) return { text, truncated: false };
2796
- const marker = "\n\u2026 [truncated by dt-runner]";
2797
- return { text: text.slice(0, max - marker.length) + marker, truncated: true };
2798
- }
2799
- var ClaudeStreamMapper = class {
2800
- /** Running offset of each live text block, by providerEventId. */
2801
- deltaOffsets = /* @__PURE__ */ new Map();
2802
- /** Stream block index → providerEventId for text blocks of the message streaming now. */
2803
- streamTextKeys = /* @__PURE__ */ new Map();
2804
- streamMessageId = null;
2805
- streamTextCount = 0;
2806
- /** Text blocks already seen in completed `assistant` lines, per message id. */
2807
- completedTextCount = /* @__PURE__ */ new Map();
2808
- /** Tool calls by id, for the name/input a result line does not repeat. */
2809
- calls = /* @__PURE__ */ new Map();
2810
- lastAssistantText = null;
2811
- running = false;
2812
- /** A new turn is starting (we wrote a user message); the next activity is not news. */
2813
- markRunning() {
2814
- this.running = true;
2815
- }
2816
- map(line) {
2817
- const out = { events: [] };
2818
- if (line.parent_tool_use_id) return out;
2819
- switch (line.type) {
2820
- case "system":
2821
- if (line.subtype === "init" && typeof line.session_id === "string") {
2822
- out.claudeSessionId = line.session_id;
2823
- this.ensureRunning(out);
2824
- }
2825
- break;
2826
- case "stream_event":
2827
- this.mapStreamEvent(line, out);
2828
- break;
2829
- case "assistant":
2830
- this.mapAssistant(line, out);
2831
- break;
2832
- case "user":
2833
- this.mapUser(line, out);
2834
- break;
2835
- case "result": {
2836
- const resultText = typeof line.result === "string" && line.result ? line.result : null;
2837
- out.turnEnd = {
2838
- text: resultText ?? this.lastAssistantText,
2839
- isError: line.is_error === true || (line.subtype ?? "success") !== "success",
2840
- subtype: typeof line.subtype === "string" ? line.subtype : null
2841
- };
2842
- const denials = Array.isArray(line.permission_denials) ? line.permission_denials.filter((d) => d && typeof d.tool_name === "string").map((d) => ({
2843
- callId: typeof d.tool_use_id === "string" ? d.tool_use_id : null,
2844
- name: d.tool_name,
2845
- input: d.tool_input ?? {}
2846
- })) : [];
2847
- if (denials.length) out.turnEnd.permissionDenials = denials;
2848
- this.endTurn();
2849
- break;
2850
- }
2851
- case "control_response": {
2852
- const res = line.response ?? {};
2853
- if (typeof res.request_id === "string") {
2854
- out.controlResponse = { requestId: res.request_id, ok: res.subtype === "success" };
2855
- }
2856
- break;
2857
- }
2858
- }
2859
- return out;
2860
- }
2861
- ensureRunning(out) {
2862
- if (!this.running) {
2863
- this.running = true;
2864
- out.turnStarted = true;
2865
- out.events.push({ type: "status", status: "running" });
2866
- }
2867
- }
2868
- mapStreamEvent(line, out) {
2869
- const ev = line.event ?? {};
2870
- switch (ev.type) {
2871
- case "message_start": {
2872
- this.ensureRunning(out);
2873
- const id = ev.message?.id ?? line.api_message_id ?? null;
2874
- this.beginStreamMessage(typeof id === "string" ? id : null);
2875
- break;
2876
- }
2877
- case "content_block_start": {
2878
- const id = this.streamMessageIdFor(line);
2879
- if (ev.content_block?.type === "text" && id && typeof ev.index === "number") {
2880
- const key = textKey(id, this.streamTextCount++);
2881
- this.streamTextKeys.set(ev.index, key);
2882
- const initial = typeof ev.content_block.text === "string" ? ev.content_block.text : "";
2883
- this.deltaOffsets.set(key, 0);
2884
- if (initial) this.pushDelta(out, key, initial);
2885
- }
2886
- break;
2887
- }
2888
- case "content_block_delta": {
2889
- if (ev.delta?.type !== "text_delta" || typeof ev.delta.text !== "string") break;
2890
- if (!ev.delta.text) break;
2891
- const key = this.streamTextKeys.get(ev.index);
2892
- if (key) this.pushDelta(out, key, ev.delta.text);
2893
- break;
2894
- }
2895
- }
2896
- }
2897
- streamMessageIdFor(line) {
2898
- const id = typeof line.api_message_id === "string" ? line.api_message_id : null;
2899
- if (id && id !== this.streamMessageId) this.beginStreamMessage(id);
2900
- return this.streamMessageId;
2901
- }
2902
- beginStreamMessage(id) {
2903
- if (id === this.streamMessageId) return;
2904
- this.streamMessageId = id;
2905
- this.streamTextKeys.clear();
2906
- this.streamTextCount = 0;
2907
- }
2908
- pushDelta(out, key, text) {
2909
- const offset = this.deltaOffsets.get(key) ?? 0;
2910
- this.deltaOffsets.set(key, offset + text.length);
2911
- out.events.push({ type: "assistant_delta", providerEventId: key, text, offset });
2912
- }
2913
- mapAssistant(line, out) {
2914
- const msg = line.message ?? {};
2915
- const id = typeof msg.id === "string" ? msg.id : `msg_${line.uuid ?? Date.now()}`;
2916
- const content = Array.isArray(msg.content) ? msg.content : [];
2917
- this.ensureRunning(out);
2918
- for (const block of content) {
2919
- switch (block?.type) {
2920
- case "text": {
2921
- const n = this.completedTextCount.get(id) ?? 0;
2922
- this.completedTextCount.set(id, n + 1);
2923
- const text = typeof block.text === "string" ? block.text : "";
2924
- if (!text.trim()) break;
2925
- const key = textKey(id, n);
2926
- this.deltaOffsets.delete(key);
2927
- this.lastAssistantText = text;
2928
- out.events.push({
2929
- type: "assistant_message",
2930
- providerEventId: key,
2931
- text: capText(text).text
2932
- });
2933
- break;
2934
- }
2935
- case "thinking":
2936
- case "redacted_thinking": {
2937
- const text = typeof block.thinking === "string" && block.thinking.trim() ? block.thinking : null;
2938
- out.events.push({
2939
- type: "thinking",
2940
- providerEventId: `${id}:thinking:${this.thinkingIndex(id)}`,
2941
- text: text === null ? null : capText(text).text
2942
- });
2943
- break;
2944
- }
2945
- case "tool_use":
2946
- case "server_tool_use":
2947
- case "mcp_tool_use": {
2948
- if (typeof block.id !== "string") break;
2949
- const name = block.type === "mcp_tool_use" && block.server_name ? `${block.server_name}.${block.name}` : String(block.name ?? "tool");
2950
- this.calls.set(block.id, { name, input: block.input });
2951
- out.events.push({
2952
- type: "tool_call",
2953
- providerEventId: block.id,
2954
- tool: { callId: block.id, name, status: "running", input: block.input }
2955
- });
2956
- break;
2957
- }
2958
- }
2959
- }
2960
- }
2961
- thinkingCounts = /* @__PURE__ */ new Map();
2962
- thinkingIndex(id) {
2963
- const n = this.thinkingCounts.get(id) ?? 0;
2964
- this.thinkingCounts.set(id, n + 1);
2965
- return n;
4233
+ dir(sessionId) {
4234
+ return join10(this.stateDir, "sessions", sessionId);
2966
4235
  }
2967
- mapUser(line, out) {
2968
- const content = line.message?.content;
2969
- if (!Array.isArray(content)) return;
2970
- for (const block of content) {
2971
- if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
2972
- const known = this.calls.get(block.tool_use_id);
2973
- const full = toolResultText(block.content);
2974
- const { text, truncated } = capText(full);
2975
- if (block.is_error) {
2976
- (out.failedTools ??= []).push({
2977
- callId: block.tool_use_id,
2978
- name: known?.name ?? "tool",
2979
- input: known?.input ?? {},
2980
- text: full
2981
- });
2982
- }
2983
- const tool = {
2984
- callId: block.tool_use_id,
2985
- name: known?.name ?? "tool",
2986
- status: block.is_error ? "failed" : "completed",
2987
- ...known ? { input: known.input } : {},
2988
- output: text,
2989
- ...truncated ? { truncated: true } : {}
2990
- };
2991
- out.events.push({ type: "tool_call", providerEventId: block.tool_use_id, tool });
4236
+ outboxFile(sessionId) {
4237
+ return join10(this.dir(sessionId), "outbox.json");
4238
+ }
4239
+ async save(record) {
4240
+ record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
4241
+ await writeJsonAtomic(join10(this.dir(record.sessionId), "session.json"), record);
4242
+ }
4243
+ async list() {
4244
+ const root = join10(this.stateDir, "sessions");
4245
+ await mkdir5(root, { recursive: true });
4246
+ const out = [];
4247
+ for (const entry of await readdir2(root, { withFileTypes: true })) {
4248
+ if (!entry.isDirectory()) continue;
4249
+ const rec = await readJson(join10(root, entry.name, "session.json"));
4250
+ if (rec?.sessionId === entry.name) out.push(upgradeRecord(rec));
2992
4251
  }
4252
+ return out;
2993
4253
  }
2994
- endTurn() {
2995
- this.running = false;
2996
- this.lastAssistantText = null;
2997
- this.deltaOffsets.clear();
2998
- this.streamTextKeys.clear();
2999
- this.streamMessageId = null;
3000
- this.streamTextCount = 0;
3001
- this.completedTextCount.clear();
3002
- this.thinkingCounts.clear();
3003
- if (this.calls.size > 500) this.calls.clear();
4254
+ async remove(sessionId) {
4255
+ await rm5(this.dir(sessionId), { recursive: true, force: true });
4256
+ }
4257
+ /** Scratch working directory for a session without a repository. */
4258
+ scratchDir(sessionId) {
4259
+ return join10(this.stateDir, "scratch", sessionId);
3004
4260
  }
3005
4261
  };
3006
- function textKey(messageId, n) {
3007
- return n === 0 ? messageId : `${messageId}:${n}`;
4262
+ function upgradeRecord(stored) {
4263
+ const { claudeSessionId, ...rest } = stored;
4264
+ return { ...rest, conversationId: stored.conversationId ?? claudeSessionId ?? null };
3008
4265
  }
3009
- function toolResultText(content) {
3010
- if (typeof content === "string") return content;
3011
- if (!Array.isArray(content)) return content == null ? "" : JSON.stringify(content);
3012
- return content.map((b) => {
3013
- if (b?.type === "text" && typeof b.text === "string") return b.text;
3014
- if (b?.type === "image") return "[image]";
3015
- return "";
3016
- }).filter(Boolean).join("\n");
4266
+ function assertSafeSessionId(id) {
4267
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(id) || id.includes("..")) {
4268
+ throw new Error(`Session id "${id}" is not usable as a directory name.`);
4269
+ }
3017
4270
  }
3018
4271
 
3019
4272
  // src/session.ts
@@ -3022,6 +4275,8 @@ var AgentSession = class {
3022
4275
  constructor(record, deps) {
3023
4276
  this.record = record;
3024
4277
  this.deps = deps;
4278
+ this.driver = deps.driver;
4279
+ this.mapper = deps.driver.createMapper();
3025
4280
  this.permissions = new PermissionRelay({
3026
4281
  respond: (controlRequestId, response) => this.answerPermission(controlRequestId, response),
3027
4282
  emit: (event) => this.emit(event),
@@ -3054,7 +4309,15 @@ var AgentSession = class {
3054
4309
  });
3055
4310
  }
3056
4311
  child = null;
3057
- mapper = new ClaudeStreamMapper();
4312
+ driver;
4313
+ mapper;
4314
+ /** per_turn agents: messages sent mid-turn, sent together as the next turn. */
4315
+ queuedTurns = [];
4316
+ /**
4317
+ * per_turn agents: a turn's process is being started. Claimed before the first await, so a
4318
+ * message arriving meanwhile is queued rather than starting a second process.
4319
+ */
4320
+ startingTurn = false;
3058
4321
  /** stdout lines are handled one at a time, in order, including the async turn end. */
3059
4322
  lineChain = Promise.resolve();
3060
4323
  stopping = null;
@@ -3063,7 +4326,7 @@ var AgentSession = class {
3063
4326
  controlSeq = 0;
3064
4327
  stderrTail = "";
3065
4328
  sawResultSinceSpawn = false;
3066
- /** The process was started with `--resume`, and has not yet said it has the conversation. */
4329
+ /** The process was started to resume, and has not yet said it has the conversation. */
3067
4330
  spawnedWithResume = false;
3068
4331
  sawInitSinceSpawn = false;
3069
4332
  /** The message that began the current turn, as the person wrote it (before any preface). */
@@ -3082,6 +4345,8 @@ var AgentSession = class {
3082
4345
  exitWaiters = [];
3083
4346
  /** Settles once the current process has exited and what it left in its tree is gone. */
3084
4347
  treeReaped = Promise.resolve();
4348
+ /** The current process's tree, for the census taken before it is stopped. */
4349
+ tree = null;
3085
4350
  /** How long what is left in the group gets after SIGTERM: a stop's grace, or the default. */
3086
4351
  reapGraceMs;
3087
4352
  lastActivity = Date.now();
@@ -3150,7 +4415,7 @@ var AgentSession = class {
3150
4415
  outcome = `${saved} now: the agent may use it in this turn.`;
3151
4416
  } else {
3152
4417
  this.restartAfterTurn = true;
3153
- outcome = `${saved}. Claude Code cannot change its permissions in the middle of a turn, so it takes effect when this turn ends.`;
4418
+ outcome = `${saved}. ${this.driver.displayName} cannot change its permissions in the middle of a turn, so it takes effect when this turn ends.`;
3154
4419
  }
3155
4420
  this.deps.logger.info(`session ${this.sessionId}: granted ${rule} (${scope})`);
3156
4421
  const denial = this.denials.get(denialId);
@@ -3193,7 +4458,7 @@ var AgentSession = class {
3193
4458
  else this.seenFailedCalls.add(f.callId);
3194
4459
  }
3195
4460
  }
3196
- /** Restarts Claude Code with the rules granted mid-turn, then sends what waited for it. */
4461
+ /** Restarts the agent with the rules granted mid-turn, then sends what waited for it. */
3197
4462
  async restartWithGrants() {
3198
4463
  const texts = this.deferredMessages.splice(0);
3199
4464
  try {
@@ -3203,7 +4468,7 @@ var AgentSession = class {
3203
4468
  this.emit(
3204
4469
  {
3205
4470
  type: "error",
3206
- message: `Claude Code could not be started again with the permission you granted: ${err.message}`,
4471
+ message: `${this.driver.displayName} could not be started again with the permission you granted: ${err.message}`,
3207
4472
  retryable: true
3208
4473
  },
3209
4474
  { type: "result", status: "failed", text: null }
@@ -3224,24 +4489,28 @@ var AgentSession = class {
3224
4489
  }
3225
4490
  return outcome;
3226
4491
  }
3227
- /** Claude Code's answer to a `can_use_tool`; dropped when the process is already gone. */
4492
+ /** The answer to a permission request; dropped when the process is already gone. */
3228
4493
  answerPermission(controlRequestId, response) {
4494
+ const control = this.driver.control;
4495
+ if (!control) return;
3229
4496
  try {
3230
- this.write({
3231
- type: "control_response",
3232
- response: { subtype: "success", request_id: controlRequestId, response }
3233
- });
4497
+ this.write(control.permissionResponse(controlRequestId, response));
3234
4498
  } catch {
3235
4499
  }
3236
4500
  }
3237
4501
  /**
3238
- * A control request from Claude Code: a permission prompt is relayed (or, for a session
3239
- * not set up to relay, denied, which is what `--permission-prompts none` would have done).
3240
- * Anything else is answered as unsupported, so Claude Code never waits on it.
4502
+ * A control line from the agent: a permission prompt is relayed (or, for a session not set
4503
+ * up to relay, denied, which is what `--permission-prompts none` would have done), a
4504
+ * cancelled one is withdrawn. Any other request is answered as unsupported, so the agent
4505
+ * never waits on it.
3241
4506
  */
3242
- async handleControlRequest(line) {
3243
- const ask = parseCanUseTool(line);
3244
- if (ask) {
4507
+ async handleControlLine(control, line) {
4508
+ if (line.kind === "cancel") {
4509
+ this.permissions.cancel(line.controlRequestId);
4510
+ return;
4511
+ }
4512
+ if (line.kind === "permission") {
4513
+ const ask = line.ask;
3245
4514
  if (!this.record.relayPermissionRequests) {
3246
4515
  this.answerPermission(ask.controlRequestId, {
3247
4516
  behavior: "deny",
@@ -3253,21 +4522,14 @@ var AgentSession = class {
3253
4522
  this.inheritedNow = await this.readInheritedRules();
3254
4523
  if (this.permissions.request(ask) === "relayed") {
3255
4524
  this.deps.logger.info(
3256
- `session ${this.sessionId}: Claude Code asks permission for ${ask.toolName}; waiting for an answer in Discovery Tree`
4525
+ `session ${this.sessionId}: ${this.driver.displayName} asks permission for ${ask.toolName}; waiting for an answer in Discovery Tree`
3257
4526
  );
3258
4527
  }
3259
4528
  return;
3260
4529
  }
3261
- if (typeof line.request_id === "string") {
4530
+ if (line.requestId !== null) {
3262
4531
  try {
3263
- this.write({
3264
- type: "control_response",
3265
- response: {
3266
- subtype: "error",
3267
- request_id: line.request_id,
3268
- error: "dt-runner does not handle this control request."
3269
- }
3270
- });
4532
+ this.write(control.unsupportedResponse(line.requestId));
3271
4533
  } catch {
3272
4534
  }
3273
4535
  }
@@ -3297,7 +4559,8 @@ var AgentSession = class {
3297
4559
  }
3298
4560
  /**
3299
4561
  * Delivers a person's message: written to the live process (mid-turn is fine), or the
3300
- * process is started again with `--resume` first.
4562
+ * process is started again resuming the conversation first. A per_turn agent starts a
4563
+ * turn's process with it, or (mid-turn) takes it as the next turn.
3301
4564
  */
3302
4565
  async sendMessage(text, commandId) {
3303
4566
  if (this.restartAfterTurn && this.record.turnActive) {
@@ -3310,7 +4573,7 @@ var AgentSession = class {
3310
4573
  this.emit({ type: "user_message_echo", providerEventId: commandId, text, delivered: true });
3311
4574
  return;
3312
4575
  }
3313
- await this.ensureProcess();
4576
+ if (this.driver.processModel === "persistent") await this.ensureProcess();
3314
4577
  const ids = this.record.handledCommandIds ??= [];
3315
4578
  ids.push(commandId);
3316
4579
  if (ids.length > HANDLED_COMMAND_IDS_KEPT) ids.splice(0, ids.length - HANDLED_COMMAND_IDS_KEPT);
@@ -3330,32 +4593,34 @@ var AgentSession = class {
3330
4593
  }
3331
4594
  }
3332
4595
  /**
3333
- * Stops the current turn. Claude Code takes an `interrupt` control request on stdin (as
3334
- * the Agent SDK sends it) and ends the turn with an `error_during_execution` result; if it
3335
- * has not answered within the grace period, SIGINT does the same the hard way.
4596
+ * Stops the current turn. An agent that takes an interrupt request on stdin (Claude Code,
4597
+ * as the Agent SDK sends it) gets one and ends the turn itself; if it has not within the
4598
+ * grace period, or takes none, SIGINT does the same the hard way.
3336
4599
  */
3337
4600
  interrupt() {
3338
4601
  const child = this.child;
3339
4602
  if (!child || !this.record.turnActive) return false;
3340
4603
  this.interruptRequested = true;
3341
4604
  this.permissions.expireAll(PERMISSION_EXPIRED_INTERRUPTED);
3342
- this.write({
3343
- type: "control_request",
3344
- request_id: `dt_interrupt_${++this.controlSeq}`,
3345
- request: { subtype: "interrupt" }
3346
- });
4605
+ const sigint = () => child.kill("SIGINT");
4606
+ const message = this.driver.interruptMessage?.(`dt_interrupt_${++this.controlSeq}`);
4607
+ if (message === void 0) {
4608
+ sigint();
4609
+ return true;
4610
+ }
4611
+ this.write(message);
3347
4612
  if (this.interruptTimer) clearTimeout(this.interruptTimer);
3348
4613
  this.interruptTimer = setTimeout(() => {
3349
4614
  this.interruptTimer = null;
3350
4615
  if (this.child === child && this.record.turnActive) {
3351
4616
  this.deps.logger.warn(`session ${this.sessionId}: no answer to interrupt; sending SIGINT`);
3352
- child.kill("SIGINT");
4617
+ sigint();
3353
4618
  }
3354
4619
  }, this.deps.interruptGraceMs ?? 5e3);
3355
4620
  return true;
3356
4621
  }
3357
4622
  /**
3358
- * Ends the process (closing stdin first, so Claude Code saves its session and exits), and
4623
+ * Ends the process (closing stdin first, so the agent saves its session and exits), and
3359
4624
  * with it everything it started: the background commands still in its process group are
3360
4625
  * ended once it has exited, and SIGTERM and SIGKILL go to the whole group.
3361
4626
  */
@@ -3366,6 +4631,9 @@ var AgentSession = class {
3366
4631
  this.stopping = reason;
3367
4632
  this.reapGraceMs = graceMs;
3368
4633
  const exited = new Promise((resolve2) => this.exitWaiters.push(resolve2));
4634
+ if (child.exitCode === null && child.signalCode === null) {
4635
+ await snapshotTree(this.tree, this.deps.reap);
4636
+ }
3369
4637
  child.stdin.end();
3370
4638
  const timedOut = await raceTimeout(exited, graceMs);
3371
4639
  if (timedOut && this.child === child) {
@@ -3389,9 +4657,10 @@ var AgentSession = class {
3389
4657
  * Writes a user message to a running process that is not being stopped (starting it, or
3390
4658
  * waiting out a stop in progress and starting it again, first). The turn counts as active
3391
4659
  * only once the message is written: a write that fails leaves no turn waiting for a
3392
- * result that will never come.
4660
+ * result that will never come. A per_turn agent starts the turn's own process instead.
3393
4661
  */
3394
4662
  async beginTurn(text, before) {
4663
+ if (this.driver.processModel === "per_turn") return this.beginProcessTurn(text, before);
3395
4664
  while (!this.child || this.stopping || this.resumeDoomed) await this.ensureProcess();
3396
4665
  let content = text;
3397
4666
  const preface = this.record.freshPreface;
@@ -3404,7 +4673,66 @@ ${text}`;
3404
4673
  this.record.freshPreface = null;
3405
4674
  await this.deps.store.save(this.record);
3406
4675
  }
3407
- this.write({ type: "user", message: { role: "user", content } });
4676
+ this.write(this.driver.encodeMessage(content));
4677
+ await this.turnBegun(text, before);
4678
+ }
4679
+ /**
4680
+ * A per_turn agent's turn: a process of its own, given the message and the conversation to
4681
+ * resume. A message sent while a turn runs (or starts) waits for it, and goes with any
4682
+ * others as the next turn; messages still waiting go ahead of this one, in order.
4683
+ */
4684
+ async beginProcessTurn(text, before) {
4685
+ if (this.record.turnActive || this.startingTurn) {
4686
+ this.queuedTurns.push(text);
4687
+ this.lastActivity = Date.now();
4688
+ if (before) this.emit(before);
4689
+ return;
4690
+ }
4691
+ const waiting = this.queuedTurns.splice(0);
4692
+ try {
4693
+ await this.startProcessTurn([...waiting, text], before);
4694
+ } catch (err) {
4695
+ this.queuedTurns.unshift(...waiting);
4696
+ throw err;
4697
+ }
4698
+ }
4699
+ /** Starts a per_turn agent's process on these messages (oldest first), as one turn. */
4700
+ async startProcessTurn(texts, before) {
4701
+ this.startingTurn = true;
4702
+ try {
4703
+ while (this.child) await this.stop("idle");
4704
+ const text = texts.join("\n\n");
4705
+ const preface = this.record.freshPreface;
4706
+ const fresh = !this.record.conversationId;
4707
+ const prompt = preface && fresh ? `${preface}
4708
+
4709
+ ---
4710
+
4711
+ ${text}` : text;
4712
+ const previousTurnText = this.turnText;
4713
+ if (preface && fresh) this.record.freshPreface = null;
4714
+ this.turnText = text;
4715
+ this.record.turnActive = true;
4716
+ this.mapper.markRunning();
4717
+ this.lastActivity = Date.now();
4718
+ try {
4719
+ await this.deps.store.save(this.record);
4720
+ await this.spawnAgent(prompt);
4721
+ } catch (err) {
4722
+ this.record.turnActive = false;
4723
+ if (preface && fresh) this.record.freshPreface = preface;
4724
+ this.turnText = previousTurnText;
4725
+ await this.deps.store.save(this.record).catch(() => void 0);
4726
+ throw err;
4727
+ }
4728
+ if (before) this.emit(before);
4729
+ this.emit({ type: "status", status: "running" });
4730
+ } finally {
4731
+ this.startingTurn = false;
4732
+ }
4733
+ }
4734
+ /** The turn's message went to the agent: the turn is active, and said to be. */
4735
+ async turnBegun(text, before) {
3408
4736
  if (!this.record.turnActive) this.turnText = text;
3409
4737
  this.lastActivity = Date.now();
3410
4738
  if (before) this.emit(before);
@@ -3415,9 +4743,31 @@ ${text}`;
3415
4743
  await this.deps.store.save(this.record);
3416
4744
  }
3417
4745
  }
4746
+ /** per_turn agents: once the turn is over, however it ended, what waited for it goes next. */
4747
+ scheduleQueuedTurns() {
4748
+ if (this.driver.processModel !== "per_turn" || !this.queuedTurns.length) return;
4749
+ setTimeout(() => void this.runQueuedTurns(), 0);
4750
+ }
4751
+ /** per_turn agents: the messages that waited for the last turn, as the next one. */
4752
+ async runQueuedTurns() {
4753
+ if (!this.queuedTurns.length || this.record.turnActive || this.startingTurn) return;
4754
+ const texts = this.queuedTurns.splice(0);
4755
+ try {
4756
+ await this.startProcessTurn(texts);
4757
+ } catch (err) {
4758
+ this.emit(
4759
+ {
4760
+ type: "error",
4761
+ message: `${this.driver.displayName} could not be started for the next message: ${err.message}`,
4762
+ retryable: true
4763
+ },
4764
+ { type: "result", status: "failed", text: null }
4765
+ );
4766
+ }
4767
+ }
3418
4768
  write(message) {
3419
4769
  if (!this.child || this.stopping || this.child.stdin.writableEnded) {
3420
- throw new Error("Claude Code is not running for this session.");
4770
+ throw new Error(`${this.driver.displayName} is not running for this session.`);
3421
4771
  }
3422
4772
  this.child.stdin.write(JSON.stringify(message) + "\n");
3423
4773
  }
@@ -3426,15 +4776,19 @@ ${text}`;
3426
4776
  if (!this.child) return Promise.resolve();
3427
4777
  return new Promise((resolve2) => this.exitWaiters.push(resolve2));
3428
4778
  }
4779
+ /** persistent agents: the session's process, started (resuming) when there is none. */
3429
4780
  async ensureProcess() {
3430
4781
  while (this.child && (this.stopping || this.resumeDoomed)) await this.waitForExit();
3431
4782
  if (this.child) return;
4783
+ await this.spawnAgent();
4784
+ }
4785
+ /** Starts the agent's process (with a per_turn agent's prompt), and reads what it says. */
4786
+ async spawnAgent(prompt) {
3432
4787
  await this.prepareEvidenceDir();
3433
- const { bin, features } = await this.deps.claude();
4788
+ const { bin, features } = await this.deps.resolveAgent();
3434
4789
  const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
3435
4790
  this.inheritedNow = await this.readInheritedRules();
3436
- const ask = this.inheritedNow.ask;
3437
- const assembled = [
4791
+ const allowedTools = [
3438
4792
  .../* @__PURE__ */ new Set([
3439
4793
  ...this.deps.allowedTools,
3440
4794
  ...this.inheritedNow.allow,
@@ -3442,30 +4796,33 @@ ${text}`;
3442
4796
  ...this.record.grantRules ?? []
3443
4797
  ])
3444
4798
  ];
3445
- const allowedTools = features.settingsFlag || ask.length === 0 ? assembled : assembled.filter((r) => !overlapsAsk(r, ask));
3446
4799
  const disallowedTools = [
3447
4800
  .../* @__PURE__ */ new Set([...this.deps.disallowedTools ?? [], ...this.inheritedNow.deny])
3448
4801
  ];
3449
- const args = claudeArgs({
4802
+ const launch = this.driver.launch({
4803
+ bin,
4804
+ features,
4805
+ cwd: this.record.cwd,
3450
4806
  permissionMode: this.deps.permissionMode,
3451
4807
  allowedTools,
3452
4808
  disallowedTools,
3453
- loadProjectSettings: this.deps.loadProjectSettings,
4809
+ askTools: this.inheritedNow.ask,
4810
+ loadProjectSettings: !!this.deps.loadProjectSettings,
3454
4811
  model: this.record.model,
3455
- resume: this.record.claudeSessionId,
4812
+ resume: this.record.conversationId,
3456
4813
  relayPermissions: !!this.record.relayPermissionRequests,
3457
- askTools: ask,
3458
- appendSystemPrompt: runnerSystemPrompt({
4814
+ systemPrompt: runnerSystemPrompt({
3459
4815
  workBranch: this.record.workBranch,
3460
4816
  baseRef: this.record.baseRef,
3461
4817
  cwd: this.record.cwd,
3462
4818
  reviewImages: !!this.record.reviewImages
3463
4819
  }),
3464
- features
4820
+ ...prompt !== void 0 ? { prompt } : {},
4821
+ ...this.deps.agentConfig ? { agentConfig: this.deps.agentConfig } : {}
3465
4822
  });
3466
- const child = spawn3(bin, args, {
4823
+ const child = spawn4(launch.bin, launch.args, {
3467
4824
  cwd: this.record.cwd,
3468
- env: process.env,
4825
+ env: launch.env ? { ...process.env, ...launch.env } : process.env,
3469
4826
  stdio: ["pipe", "pipe", "pipe"],
3470
4827
  windowsHide: true,
3471
4828
  // A process group of its own, so what it starts can be ended with it. It also means
@@ -3480,36 +4837,43 @@ ${text}`;
3480
4837
  });
3481
4838
  child.once(
3482
4839
  "error",
3483
- (err) => reject(new Error(`Could not start Claude Code (${bin}): ${err.message}`))
4840
+ (err) => reject(
4841
+ new Error(`Could not start ${this.driver.displayName} (${launch.bin}): ${err.message}`)
4842
+ )
3484
4843
  );
3485
4844
  });
3486
4845
  this.child = child;
4846
+ this.tree = tree;
3487
4847
  this.stopping = null;
3488
4848
  this.resumeDoomed = false;
3489
4849
  this.reapGraceMs = void 0;
3490
4850
  this.stderrTail = "";
3491
4851
  this.sawResultSinceSpawn = false;
3492
- this.spawnedWithResume = !!this.record.claudeSessionId;
4852
+ this.spawnedWithResume = !!this.record.conversationId;
3493
4853
  this.sawInitSinceSpawn = false;
3494
4854
  this.deps.logger.info(
3495
- `session ${this.sessionId}: Claude Code started${this.record.claudeSessionId ? " (resumed)" : ""}`,
4855
+ `session ${this.sessionId}: ${this.driver.displayName} started${this.record.conversationId ? " (resumed)" : ""}`,
3496
4856
  { pid: child.pid }
3497
4857
  );
3498
4858
  this.treeReaped = new Promise(
3499
4859
  (resolve2) => child.once("exit", () => void reapTree(tree, this.reapGraceMs, this.deps.reap).then(resolve2))
3500
4860
  );
3501
4861
  child.stdin.on("error", () => void 0);
4862
+ if (launch.stdin !== void 0) child.stdin.end(launch.stdin);
4863
+ else if (this.driver.processModel === "per_turn") child.stdin.end();
3502
4864
  child.stderr.setEncoding("utf8").on("data", (d) => {
3503
4865
  this.stderrTail = (this.stderrTail + d).slice(-4e3);
3504
4866
  });
3505
- const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
4867
+ const rl = createInterface2({ input: child.stdout, crlfDelay: Infinity });
3506
4868
  rl.on("line", (line) => {
3507
4869
  if (!line.trim()) return;
3508
4870
  let parsed;
3509
4871
  try {
3510
4872
  parsed = JSON.parse(line);
3511
4873
  } catch {
3512
- this.deps.logger.debug(`session ${this.sessionId}: non-JSON output from claude`);
4874
+ this.deps.logger.debug(
4875
+ `session ${this.sessionId}: non-JSON output from ${this.driver.displayName}`
4876
+ );
3513
4877
  return;
3514
4878
  }
3515
4879
  this.lineChain = this.lineChain.then(() => this.handleLine(parsed)).catch((err) => {
@@ -3525,22 +4889,19 @@ ${text}`;
3525
4889
  }
3526
4890
  async handleLine(line) {
3527
4891
  this.lastActivity = Date.now();
3528
- if (line.type === "control_request") {
3529
- await this.handleControlRequest(line);
3530
- return;
3531
- }
3532
- const cancelled = parseControlCancel(line);
3533
- if (cancelled) {
3534
- this.permissions.cancel(cancelled);
4892
+ const control = this.driver.control;
4893
+ const controlLine = control?.parse(line);
4894
+ if (control && controlLine) {
4895
+ await this.handleControlLine(control, controlLine);
3535
4896
  return;
3536
4897
  }
3537
4898
  const mapped = this.mapper.map(line);
3538
4899
  let dirty = false;
3539
- if (mapped.claudeSessionId) this.sawInitSinceSpawn = true;
4900
+ if (mapped.conversationId) this.sawInitSinceSpawn = true;
3540
4901
  let learnedSessionId = null;
3541
- if (mapped.claudeSessionId && mapped.claudeSessionId !== this.record.claudeSessionId) {
3542
- this.record.claudeSessionId = mapped.claudeSessionId;
3543
- learnedSessionId = mapped.claudeSessionId;
4902
+ if (mapped.conversationId && mapped.conversationId !== this.record.conversationId) {
4903
+ this.record.conversationId = mapped.conversationId;
4904
+ learnedSessionId = mapped.conversationId;
3544
4905
  dirty = true;
3545
4906
  }
3546
4907
  if (mapped.turnStarted && !this.record.turnActive) {
@@ -3550,17 +4911,11 @@ ${text}`;
3550
4911
  if (dirty) await this.deps.store.save(this.record);
3551
4912
  if (learnedSessionId) {
3552
4913
  const at = mapped.events.findIndex((e) => e.type === "status");
4914
+ const ids = this.conversationIds(learnedSessionId);
3553
4915
  if (at >= 0) {
3554
- mapped.events[at] = {
3555
- ...mapped.events[at],
3556
- claudeSessionId: learnedSessionId
3557
- };
4916
+ mapped.events[at] = { ...mapped.events[at], ...ids };
3558
4917
  } else {
3559
- mapped.events.push({
3560
- type: "status",
3561
- status: "running",
3562
- claudeSessionId: learnedSessionId
3563
- });
4918
+ mapped.events.push({ type: "status", status: "running", ...ids });
3564
4919
  }
3565
4920
  }
3566
4921
  if (mapped.events.length) this.emit(...mapped.events);
@@ -3572,9 +4927,9 @@ ${text}`;
3572
4927
  }
3573
4928
  if (mapped.turnEnd && this.resumeFailedBeforeTurn(mapped.turnEnd.isError)) {
3574
4929
  this.deps.logger.warn(
3575
- `session ${this.sessionId}: the Claude Code conversation to resume was not found; starting a fresh one`
4930
+ `session ${this.sessionId}: the ${this.driver.displayName} conversation to resume was not found; starting a fresh one`
3576
4931
  );
3577
- this.record.claudeSessionId = null;
4932
+ this.record.conversationId = null;
3578
4933
  this.resumeDoomed = true;
3579
4934
  await this.deps.store.save(this.record);
3580
4935
  this.child?.stdin.end();
@@ -3587,7 +4942,7 @@ ${text}`;
3587
4942
  }
3588
4943
  /**
3589
4944
  * The process was started to resume a conversation and failed before it said it had it
3590
- * (no `system/init`): Claude Code did not find the conversation on this computer.
4945
+ * (Claude Code: no `system/init`): the agent did not find the conversation on this computer.
3591
4946
  */
3592
4947
  resumeNotFound(isError) {
3593
4948
  return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && this.record.turnActive && this.turnText !== null;
@@ -3595,12 +4950,19 @@ ${text}`;
3595
4950
  resumeFailedBeforeTurn(isError) {
3596
4951
  return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && !this.record.turnActive;
3597
4952
  }
4953
+ /**
4954
+ * How an event names the agent's conversation: `conversationId` for every agent, and
4955
+ * Claude Code's also as `claudeSessionId`, which servers that predate the neutral name read.
4956
+ */
4957
+ conversationIds(id) {
4958
+ return this.driver.kind === DEFAULT_AGENT_KIND ? { claudeSessionId: id, conversationId: id } : { conversationId: id };
4959
+ }
3598
4960
  planFreshRetry() {
3599
4961
  this.deps.logger.warn(
3600
- `session ${this.sessionId}: the Claude Code conversation to resume was not found; starting a fresh one`
4962
+ `session ${this.sessionId}: the ${this.driver.displayName} conversation to resume was not found; starting a fresh one`
3601
4963
  );
3602
4964
  this.resumeRetry = this.turnText;
3603
- this.record.claudeSessionId = null;
4965
+ this.record.conversationId = null;
3604
4966
  }
3605
4967
  async endTurn(turn) {
3606
4968
  this.permissions.expireAll(PERMISSION_EXPIRED_TURN_ENDED);
@@ -3613,12 +4975,12 @@ ${text}`;
3613
4975
  if (this.interruptTimer) clearTimeout(this.interruptTimer);
3614
4976
  this.interruptTimer = null;
3615
4977
  const turnFailed = turn.isError && !interrupted;
3616
- if (turnFailed && turnFailedToSignIn(turn)) this.deps.onClaudeSignIn?.(false);
3617
- else if (!turn.isError) this.deps.onClaudeSignIn?.(true);
4978
+ if (turnFailed && this.driver.turnFailedToSignIn(turn)) this.deps.onAgentSignIn?.(false);
4979
+ else if (!turn.isError) this.deps.onAgentSignIn?.(true);
3618
4980
  if (turnFailed) {
3619
4981
  this.emit({
3620
4982
  type: "error",
3621
- message: turnErrorMessage(turn),
4983
+ message: this.driver.turnErrorMessage(turn),
3622
4984
  retryable: true
3623
4985
  });
3624
4986
  }
@@ -3653,12 +5015,14 @@ ${text}`;
3653
5015
  ...push.failed ? { unpushedWork: true } : {},
3654
5016
  // So the server can have a later session resume this conversation (a run continued
3655
5017
  // after it ended).
3656
- ...this.record.claudeSessionId ? { claudeSessionId: this.record.claudeSessionId } : {}
5018
+ ...this.record.conversationId ? this.conversationIds(this.record.conversationId) : {}
3657
5019
  });
3658
5020
  this.lastActivity = Date.now();
3659
5021
  if (this.restartAfterTurn) {
3660
5022
  this.restartAfterTurn = false;
3661
5023
  setTimeout(() => void this.restartWithGrants(), 0);
5024
+ } else {
5025
+ this.scheduleQueuedTurns();
3662
5026
  }
3663
5027
  this.deps.logger.info(
3664
5028
  `session ${this.sessionId}: turn ${interrupted ? "interrupted" : turnFailed ? "ended with an error" : push.failed ? "finished, but its work was not pushed" : "finished"}`,
@@ -3675,7 +5039,7 @@ ${text}`;
3675
5039
  const repo = parseRepoUrl(repository ?? "");
3676
5040
  if (!pullRequest || !workBranch || !repo) return null;
3677
5041
  const body = [
3678
- text?.trim() || "Work by the Claude Code (local) agent.",
5042
+ text?.trim() || `Work by the ${this.driver.displayName} (local) agent.`,
3679
5043
  "",
3680
5044
  "---",
3681
5045
  pullRequest.footer
@@ -3831,21 +5195,25 @@ ${text}`;
3831
5195
  const waiters = this.exitWaiters;
3832
5196
  this.exitWaiters = [];
3833
5197
  try {
3834
- if (this.resumeRetry === null && !reason && this.record.turnActive && this.resumeNotFound(true) && /No conversation found/i.test(this.stderrTail)) {
5198
+ if (this.resumeRetry === null && !reason && this.record.turnActive && this.resumeNotFound(true) && this.driver.resumeNotFound(this.stderrTail)) {
3835
5199
  this.planFreshRetry();
3836
5200
  }
3837
5201
  if (this.resumeRetry !== null) {
3838
5202
  const text = this.resumeRetry;
3839
5203
  this.resumeRetry = null;
5204
+ const perTurn = this.driver.processModel === "per_turn";
5205
+ if (perTurn) this.startingTurn = true;
3840
5206
  this.record.turnActive = false;
3841
- await this.deps.store.save(this.record);
3842
5207
  try {
3843
- await this.beginTurn(text);
5208
+ await this.deps.store.save(this.record);
5209
+ if (perTurn) await this.startProcessTurn([text]);
5210
+ else await this.beginTurn(text);
3844
5211
  } catch (err) {
5212
+ this.startingTurn = false;
3845
5213
  this.emit(
3846
5214
  {
3847
5215
  type: "error",
3848
- message: `Claude Code could not be started again for this message: ${err.message}`,
5216
+ message: `${this.driver.displayName} could not be started again for this message: ${err.message}`,
3849
5217
  retryable: true
3850
5218
  },
3851
5219
  { type: "result", status: "failed", text: null }
@@ -3854,11 +5222,13 @@ ${text}`;
3854
5222
  return;
3855
5223
  }
3856
5224
  if (reason) {
3857
- this.deps.logger.info(`session ${this.sessionId}: Claude Code stopped (${reason})`);
5225
+ this.deps.logger.info(
5226
+ `session ${this.sessionId}: ${this.driver.displayName} stopped (${reason})`
5227
+ );
3858
5228
  if (reason !== "shutdown" && this.record.turnActive) {
3859
5229
  this.emit({
3860
5230
  type: "error",
3861
- message: "Claude Code was stopped in the middle of this turn. Send a message to continue.",
5231
+ message: `${this.driver.displayName} was stopped in the middle of this turn. Send a message to continue.`,
3862
5232
  retryable: true
3863
5233
  });
3864
5234
  this.record.turnActive = false;
@@ -3868,10 +5238,12 @@ ${text}`;
3868
5238
  return;
3869
5239
  }
3870
5240
  if (!this.record.turnActive) {
3871
- this.deps.logger.info(`session ${this.sessionId}: Claude Code exited while idle`, {
3872
- code,
3873
- signal
3874
- });
5241
+ if (this.driver.processModel === "persistent") {
5242
+ this.deps.logger.info(
5243
+ `session ${this.sessionId}: ${this.driver.displayName} exited while idle`,
5244
+ { code, signal }
5245
+ );
5246
+ }
3875
5247
  return;
3876
5248
  }
3877
5249
  if (this.interruptRequested) {
@@ -3883,46 +5255,25 @@ ${text}`;
3883
5255
  400
3884
5256
  );
3885
5257
  const how = signal ? `was killed (${signal})` : `exited with code ${code}`;
3886
- const hint = this.sawResultSinceSpawn ? "" : startupHint(this.stderrTail);
3887
- if (!this.sawResultSinceSpawn && looksLikeSignInFailure(this.stderrTail)) {
3888
- this.deps.onClaudeSignIn?.(false);
5258
+ const hint = this.sawResultSinceSpawn ? "" : this.driver.startupHint(this.stderrTail);
5259
+ if (!this.sawResultSinceSpawn && this.driver.looksLikeSignInFailure(this.stderrTail)) {
5260
+ this.deps.onAgentSignIn?.(false);
3889
5261
  }
3890
5262
  this.emit({
3891
5263
  type: "error",
3892
- message: `Claude Code ${how} in the middle of a turn.${hint}${tail ? ` ${tail}` : ""}`,
5264
+ message: `${this.driver.displayName} ${how} in the middle of a turn.${hint}${tail ? ` ${tail}` : ""}`,
3893
5265
  retryable: true
3894
5266
  });
3895
5267
  this.record.turnActive = false;
3896
5268
  await this.deps.store.save(this.record);
3897
5269
  this.emit({ type: "result", status: "failed", text: null });
3898
- this.deps.logger.warn(`session ${this.sessionId}: Claude Code ${how}`);
5270
+ this.deps.logger.warn(`session ${this.sessionId}: ${this.driver.displayName} ${how}`);
3899
5271
  } finally {
5272
+ if (reason !== "shutdown" && reason !== "close") this.scheduleQueuedTurns();
3900
5273
  for (const w of waiters) w();
3901
5274
  }
3902
5275
  }
3903
5276
  };
3904
- function turnErrorMessage(turn) {
3905
- switch (turn.subtype) {
3906
- case "error_max_turns":
3907
- return "Claude Code stopped: it reached its maximum number of turns.";
3908
- case "error_max_budget_usd":
3909
- return "Claude Code stopped: it reached its spending limit.";
3910
- default:
3911
- if (turnFailedToSignIn(turn)) {
3912
- return `Claude Code could not sign in to Claude (${turn.text.slice(0, 200)}). ${signInFix()} Then send a message here to try again.`;
3913
- }
3914
- return turn.text ? `Claude Code reported an error: ${turn.text.slice(0, 500)}` : `Claude Code ended the turn with an error (${turn.subtype ?? "unknown"}).`;
3915
- }
3916
- }
3917
- function startupHint(stderr) {
3918
- if (looksLikeSignInFailure(stderr)) {
3919
- return ` Claude Code does not seem to be signed in on the runner\u2019s computer. ${signInFix()}`;
3920
- }
3921
- if (/No conversation found|session.*not found/i.test(stderr)) {
3922
- return " The Claude Code conversation to resume was not found on this computer.";
3923
- }
3924
- return "";
3925
- }
3926
5277
  async function raceTimeout(done, ms) {
3927
5278
  let timer;
3928
5279
  const timeout = new Promise((resolve2) => {
@@ -4065,7 +5416,18 @@ var SessionManager = class {
4065
5416
  if (cmd.repository && !parseRepoUrl(cmd.repository.url)) {
4066
5417
  return { ok: false, error: repositoryUrlError(cmd.repository.url) };
4067
5418
  }
4068
- assertValidModel(cmd.model);
5419
+ const driver = this.driverFor(cmd.agent);
5420
+ driver.validateModel(cmd.model);
5421
+ const problem = await this.opts.agentProblem?.(driver);
5422
+ if (problem) {
5423
+ return {
5424
+ ok: false,
5425
+ error: `${driver.displayName} cannot run on this runner right now: ${problem}`
5426
+ };
5427
+ }
5428
+ if (this.sessions.has(cmd.sessionId)) return { ok: true };
5429
+ const checking = this.starting.get(cmd.sessionId);
5430
+ if (checking) return checking;
4069
5431
  const max = this.opts.config.maxSessions;
4070
5432
  if (this.liveCount() >= max) {
4071
5433
  await this.stopOldestIdle(cmd.sessionId);
@@ -4093,7 +5455,13 @@ var SessionManager = class {
4093
5455
  repo: cmd.repository?.url,
4094
5456
  branch: cmd.repository?.workBranch
4095
5457
  });
4096
- await this.opts.claude();
5458
+ const driver = this.driverFor(cmd.agent);
5459
+ await this.opts.resolveAgent(driver);
5460
+ if (!driver.control && (cmd.relayPermissionRequests || cmd.reportToolDenials)) {
5461
+ this.opts.logger.info(
5462
+ `session ${cmd.sessionId}: ${driver.displayName} does not support relaying permission requests or reporting tool denials; its sandbox decides instead`
5463
+ );
5464
+ }
4097
5465
  const resume = cmd.resume ?? null;
4098
5466
  if (resume) {
4099
5467
  for (const other of [...this.sessions.values()]) {
@@ -4103,7 +5471,7 @@ var SessionManager = class {
4103
5471
  }
4104
5472
  await Promise.allSettled([...this.closing.values()]);
4105
5473
  this.opts.logger.info(`session ${cmd.sessionId}: continuing run ${cmd.runId}`, {
4106
- resume: resume.claudeSessionId ? "conversation" : "fresh"
5474
+ resume: resume.conversationId ?? resume.claudeSessionId ? "conversation" : "fresh"
4107
5475
  });
4108
5476
  }
4109
5477
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -4117,7 +5485,8 @@ var SessionManager = class {
4117
5485
  workBranch: null,
4118
5486
  baseRef: null,
4119
5487
  baseSha: null,
4120
- claudeSessionId: null,
5488
+ ...driver.kind !== DEFAULT_AGENT_KIND ? { agentKind: driver.kind } : {},
5489
+ conversationId: null,
4121
5490
  turnActive: false,
4122
5491
  ...cmd.relayPermissionRequests === true ? { relayPermissionRequests: true } : {},
4123
5492
  ...alwaysAllowTools(cmd).length ? { alwaysAllowedTools: alwaysAllowTools(cmd) } : {},
@@ -4168,15 +5537,15 @@ var SessionManager = class {
4168
5537
  await mkdir6(record.cwd, { recursive: true });
4169
5538
  if (cmd.reviewImages === true && this.opts.reviewImageUploader) {
4170
5539
  record.reviewImages = true;
4171
- await mkdir6(join10(record.cwd, EVIDENCE_DIR), { recursive: true });
5540
+ await mkdir6(join11(record.cwd, EVIDENCE_DIR), { recursive: true });
4172
5541
  }
4173
5542
  const deliverable = resume?.deliverable;
4174
5543
  if (typeof deliverable === "string" && deliverable.trim()) {
4175
- await writeFile4(join10(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
5544
+ await writeFile4(join11(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
4176
5545
  }
4177
5546
  }
4178
5547
  if (resume) {
4179
- record.claudeSessionId = resume.claudeSessionId?.trim() || null;
5548
+ record.conversationId = (resume.conversationId ?? resume.claudeSessionId)?.trim() || null;
4180
5549
  record.freshPreface = continuationPreface(cmd);
4181
5550
  }
4182
5551
  await this.store.save(record);
@@ -4408,6 +5777,10 @@ var SessionManager = class {
4408
5777
  await Promise.all(sessions.map((s) => s.outbox.flush(flushMs)));
4409
5778
  await Promise.all(sessions.map((s) => s.outbox.stop()));
4410
5779
  }
5780
+ /** The agent a session of this kind runs (the test override, else the registry's). */
5781
+ driverFor(kind) {
5782
+ return this.opts.driver ?? agentDriver(kind);
5783
+ }
4411
5784
  async openSession(record) {
4412
5785
  const outbox = await SessionOutbox.open({
4413
5786
  sessionId: record.sessionId,
@@ -4421,17 +5794,24 @@ var SessionManager = class {
4421
5794
  void this.close(record.sessionId);
4422
5795
  }
4423
5796
  });
5797
+ const driver = this.driverFor(record.agentKind);
4424
5798
  return new AgentSession(record, {
4425
5799
  store: this.store,
4426
5800
  outbox,
4427
5801
  logger: this.opts.logger,
4428
- claude: this.opts.claude,
5802
+ driver,
5803
+ resolveAgent: () => this.opts.resolveAgent(driver),
4429
5804
  permissionMode: this.opts.config.permissionMode,
4430
5805
  allowedTools: this.opts.config.allowedTools,
4431
5806
  disallowedTools: this.opts.config.disallowedTools ?? [],
4432
5807
  loadProjectSettings: this.opts.config.loadProjectSettings ?? false,
5808
+ agentConfig: {
5809
+ codexSandbox: this.opts.config.codexSandbox ?? "workspace-write",
5810
+ codexNetworkAccess: this.opts.config.codexNetworkAccess === true,
5811
+ cursorForce: this.opts.config.cursorForce === true
5812
+ },
4433
5813
  interruptGraceMs: this.opts.interruptGraceMs,
4434
- onClaudeSignIn: this.opts.onClaudeSignIn,
5814
+ onAgentSignIn: this.opts.onAgentSignIn ? (ok) => this.opts.onAgentSignIn(ok, driver.kind) : void 0,
4435
5815
  openPullRequest: this.opts.openPullRequest,
4436
5816
  permissionTimeoutMs: this.opts.permissionTimeoutMs,
4437
5817
  savedRules: async (url) => this.opts.grants ? await this.opts.grants.rulesFor(url) : [],
@@ -4498,9 +5878,10 @@ var RunnerDaemon = class {
4498
5878
  config: opts.config,
4499
5879
  poster: this.api,
4500
5880
  logger: opts.logger,
4501
- claude: () => this.resolveClaude(),
5881
+ resolveAgent: (driver) => this.resolveAgent(driver),
4502
5882
  onUnauthorized: (err) => this.unauthorized(err),
4503
- onClaudeSignIn: (ok) => this.claudeSignIn(ok),
5883
+ onAgentSignIn: (ok, kind) => this.agentSignIn(ok, kind),
5884
+ agentProblem: (driver) => this.agentProblem(driver),
4504
5885
  grants: this.grants,
4505
5886
  reviewImageUploader: this.api,
4506
5887
  // What the person already allows in their own Claude Code for a repository.
@@ -4516,12 +5897,17 @@ var RunnerDaemon = class {
4516
5897
  exitReason = "stopped";
4517
5898
  agentInfo = null;
4518
5899
  /**
4519
- * A turn's Claude Code could not sign in to Claude. `claude auth status` may still say it
4520
- * is signed in (an expired sign-in it cannot refresh), so this outranks the probe until a
4521
- * later turn finishes.
5900
+ * The agents (`AgentDriver.kind`) a turn could not sign in. Claude Code's `claude auth
5901
+ * status` (or `codex login status`) may still say it is signed in (an expired sign-in it
5902
+ * cannot refresh), so this outranks the probe until a later turn finishes.
4522
5903
  */
4523
- signInFailed = false;
4524
- claudeCache = null;
5904
+ signInFailed = /* @__PURE__ */ new Set();
5905
+ /** Each agent's binary and features, by `AgentDriver.kind`, trusted for the probe's TTL. */
5906
+ agentInstalls = /* @__PURE__ */ new Map();
5907
+ /** The agent the heartbeat's `claude*` fields report on: the default kind's. */
5908
+ driver = agentDriver();
5909
+ /** The optional agents (Codex, Cursor), each reported in its own heartbeat fields. */
5910
+ optional = OPTIONAL_AGENTS;
4525
5911
  inFlight = /* @__PURE__ */ new Set();
4526
5912
  /** The tail of each session's command queue (see `inSessionOrder`); never rejects. */
4527
5913
  sessionQueues = /* @__PURE__ */ new Map();
@@ -4574,44 +5960,108 @@ var RunnerDaemon = class {
4574
5960
  );
4575
5961
  this.stop();
4576
5962
  }
4577
- async resolveClaude() {
5963
+ async resolveAgent(driver) {
4578
5964
  const ttl = this.opts.agentProbeTtlMs ?? 5 * 6e4;
4579
- if (this.claudeCache && Date.now() - this.claudeCache.at < ttl) return this.claudeCache;
4580
- const bin = await findClaude();
4581
- if (!bin) {
4582
- throw new Error(
4583
- "Claude Code is not installed on the runner\u2019s computer (no `claude` on PATH)."
4584
- );
4585
- }
4586
- this.claudeCache = { bin, features: await claudeFeatures(bin), at: Date.now() };
4587
- return this.claudeCache;
5965
+ const cached = this.agentInstalls.get(driver.kind);
5966
+ if (cached && Date.now() - cached.at < ttl) return cached;
5967
+ const bin = await driver.resolveBinary();
5968
+ if (!bin) throw new Error(driver.notInstalledMessage());
5969
+ const install = { bin, features: await driver.readFeatures(bin), at: Date.now() };
5970
+ this.agentInstalls.set(driver.kind, install);
5971
+ return install;
5972
+ }
5973
+ /** Claude Code, for planning requests (answered by Claude Code only; see `completion.ts`). */
5974
+ async resolveClaude() {
5975
+ const { bin, features } = await this.resolveAgent(claudeCodeDriver);
5976
+ return { bin, features };
4588
5977
  }
4589
5978
  async agent() {
4590
5979
  const ttl = this.opts.agentProbeTtlMs ?? 5 * 6e4;
4591
5980
  if (!this.agentInfo || Date.now() - this.agentInfo.at > ttl) {
4592
- const info2 = await probeAgent();
5981
+ const [claude, ...others] = await Promise.all([
5982
+ this.driver.probe(),
5983
+ ...this.optional.map((a) => a.driver.probe())
5984
+ ]);
5985
+ let info2 = {
5986
+ claudeVersion: claude.claudeVersion,
5987
+ claudeReady: claude.claudeReady,
5988
+ claudeProblem: claude.claudeProblem ?? null
5989
+ };
5990
+ this.optional.forEach((a, i) => {
5991
+ info2 = { ...withAgentFields(info2, a, readAgentFields(others[i], a)), [a.runs]: true };
5992
+ });
4593
5993
  if (info2.claudeProblem && info2.claudeProblem !== this.agentInfo?.info.claudeProblem) {
4594
5994
  this.opts.logger.warn(info2.claudeProblem);
4595
5995
  }
5996
+ for (const a of this.optional) {
5997
+ const now = readAgentFields(info2, a);
5998
+ const before = this.agentInfo ? readAgentFields(this.agentInfo.info, a) : null;
5999
+ if (now.version && now.problem && now.problem !== before?.problem) {
6000
+ this.opts.logger.warn(now.problem);
6001
+ }
6002
+ }
4596
6003
  this.agentInfo = { info: info2, at: Date.now() };
4597
6004
  }
4598
- const { info } = this.agentInfo;
4599
- if (!this.signInFailed || !info.claudeVersion || info.claudeReady === false) return info;
4600
- return {
4601
- ...info,
4602
- claudeReady: false,
4603
- claudeProblem: `A run could not sign in to Claude. ${signInFix()}`
4604
- };
6005
+ let { info } = this.agentInfo;
6006
+ if (this.signInFailed.has(this.driver.kind) && info.claudeVersion && info.claudeReady !== false) {
6007
+ info = {
6008
+ ...info,
6009
+ claudeReady: false,
6010
+ claudeProblem: `A run could not sign in to Claude. ${this.driver.signInFix()}`
6011
+ };
6012
+ }
6013
+ for (const a of this.optional) {
6014
+ const now = readAgentFields(info, a);
6015
+ if (this.signInFailed.has(a.driver.kind) && now.version && now.ready !== false) {
6016
+ info = withAgentFields(info, a, {
6017
+ ...now,
6018
+ ready: false,
6019
+ problem: `A run could not sign in to ${a.driver.displayName}. ${a.driver.signInFix()}`
6020
+ });
6021
+ }
6022
+ }
6023
+ return info;
4605
6024
  }
4606
- claudeSignIn(ok) {
4607
- if (ok && this.agentInfo?.info.claudeReady === false && this.agentInfo.info.claudeVersion) {
4608
- this.agentInfo.info = { ...this.agentInfo.info, claudeReady: true, claudeProblem: null };
6025
+ /**
6026
+ * Why a session of this agent would not run now (see `SessionManagerOptions.agentProblem`).
6027
+ * Asked of the agent itself, not of the heartbeat's cached or overridden view: a person who
6028
+ * just installed it or signed in is not refused for a probe taken before, nor for a turn
6029
+ * that failed to sign in earlier (a new turn that fails says so in its own error).
6030
+ */
6031
+ async agentProblem(driver) {
6032
+ const agent = this.optional.find((a) => a.driver.kind === driver.kind);
6033
+ if (!agent) return null;
6034
+ const fresh = readAgentFields(await agent.driver.probe(), agent);
6035
+ if (this.agentInfo) this.agentInfo.info = withAgentFields(this.agentInfo.info, agent, fresh);
6036
+ if (fresh.ready === true) this.signInFailed.delete(agent.driver.kind);
6037
+ if (fresh.ready !== false) return null;
6038
+ return fresh.problem || `${agent.driver.displayName} is not ready. ${agent.driver.signInFix()}`;
6039
+ }
6040
+ agentSignIn(ok, kind = this.driver.kind) {
6041
+ const cached = this.agentInfo?.info;
6042
+ const agent = this.optional.find((a) => a.driver.kind === kind);
6043
+ if (ok && cached) {
6044
+ if (kind === this.driver.kind && cached.claudeReady === false && cached.claudeVersion) {
6045
+ this.agentInfo.info = { ...cached, claudeReady: true, claudeProblem: null };
6046
+ } else if (agent) {
6047
+ const now = readAgentFields(cached, agent);
6048
+ if (now.ready === false && now.version) {
6049
+ this.agentInfo.info = withAgentFields(cached, agent, {
6050
+ ...now,
6051
+ ready: true,
6052
+ problem: null
6053
+ });
6054
+ }
6055
+ }
4609
6056
  }
4610
- if (ok === !this.signInFailed) return;
4611
- this.signInFailed = !ok;
4612
- if (!ok) {
4613
- this.opts.logger.warn(`Claude Code could not sign in to Claude. ${signInFix()}`);
6057
+ if (ok === !this.signInFailed.has(kind)) return;
6058
+ if (ok) {
6059
+ this.signInFailed.delete(kind);
6060
+ return;
4614
6061
  }
6062
+ this.signInFailed.add(kind);
6063
+ const driver = agent?.driver ?? this.driver;
6064
+ this.opts.logger.warn(`${driver.displayName} could not sign in. ${driver.signInFix()}`);
4615
6065
  }
4616
6066
  /**
4617
6067
  * The runner's one heartbeat, for all of its sessions (each session's state rides in it).
@@ -4751,7 +6201,7 @@ var RunnerDaemon = class {
4751
6201
  if (this.droppedSessionIds.has(id)) return;
4752
6202
  this.droppedSessionIds.add(id);
4753
6203
  this.opts.logger.warn(
4754
- `session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${join11(this.opts.config.stateDir, "sessions", id)})`
6204
+ `session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${join12(this.opts.config.stateDir, "sessions", id)})`
4755
6205
  );
4756
6206
  });
4757
6207
  }
@@ -4857,8 +6307,8 @@ var RunnerDaemon = class {
4857
6307
  error: result.error
4858
6308
  });
4859
6309
  }
4860
- if (result.signInFailed) this.claudeSignIn(false);
4861
- else if (result.ok) this.claudeSignIn(true);
6310
+ if (result.signInFailed) this.agentSignIn(false);
6311
+ else if (result.ok) this.agentSignIn(true);
4862
6312
  for (let attempt = 0; attempt < 5; attempt++) {
4863
6313
  try {
4864
6314
  await this.api.postCompletion(req.id, result);
@@ -4897,6 +6347,37 @@ var RunnerDaemon = class {
4897
6347
  });
4898
6348
  }
4899
6349
  };
6350
+ var OPTIONAL_AGENTS = [
6351
+ {
6352
+ driver: codexDriver,
6353
+ version: "codexVersion",
6354
+ ready: "codexReady",
6355
+ problem: "codexProblem",
6356
+ runs: "runsCodex"
6357
+ },
6358
+ {
6359
+ driver: cursorDriver,
6360
+ version: "cursorVersion",
6361
+ ready: "cursorReady",
6362
+ problem: "cursorProblem",
6363
+ runs: "runsCursor"
6364
+ }
6365
+ ];
6366
+ function readAgentFields(info, agent) {
6367
+ return {
6368
+ version: info[agent.version] ?? null,
6369
+ ready: info[agent.ready] ?? null,
6370
+ problem: info[agent.problem] ?? null
6371
+ };
6372
+ }
6373
+ function withAgentFields(info, agent, fields) {
6374
+ return {
6375
+ ...info,
6376
+ [agent.version]: fields.version,
6377
+ [agent.ready]: fields.ready,
6378
+ [agent.problem]: fields.problem
6379
+ };
6380
+ }
4900
6381
 
4901
6382
  // src/doctor.ts
4902
6383
  async function runDoctor(env = process.env) {
@@ -4931,39 +6412,7 @@ async function runDoctor(env = process.env) {
4931
6412
  detail: "not installed (no `gh` on PATH): pull requests cannot be opened as you; see https://cli.github.com"
4932
6413
  });
4933
6414
  }
4934
- const bin = await findClaude(env);
4935
- if (!bin) {
4936
- checks.push({
4937
- name: "Claude Code",
4938
- level: "fail",
4939
- detail: env.DT_RUNNER_CLAUDE_BIN ? `DT_RUNNER_CLAUDE_BIN=${env.DT_RUNNER_CLAUDE_BIN} was not found` : "not installed: see https://docs.claude.com/en/docs/claude-code (no `claude` on PATH)"
4940
- });
4941
- } else {
4942
- const version = await claudeVersion(bin);
4943
- checks.push({
4944
- name: "Claude Code",
4945
- level: version ? "ok" : "fail",
4946
- detail: version ? `${version} (${bin})` : `${bin} --version failed`
4947
- });
4948
- if (version) {
4949
- const auth = await claudeAuthStatus(bin);
4950
- checks.push(
4951
- auth.loggedIn === true ? {
4952
- name: "Claude sign-in",
4953
- level: "ok",
4954
- detail: `signed in${auth.authMethod ? ` (${auth.authMethod})` : ""}`
4955
- } : auth.loggedIn === false ? {
4956
- name: "Claude sign-in",
4957
- level: "fail",
4958
- detail: "not signed in: run `claude` and sign in with your Claude account"
4959
- } : {
4960
- name: "Claude sign-in",
4961
- level: "warn",
4962
- detail: "could not tell (this Claude Code has no `claude auth status`); update Claude Code"
4963
- }
4964
- );
4965
- }
4966
- }
6415
+ for (const kind of agentDriverKinds()) checks.push(...await agentDriver(kind).doctor(env));
4967
6416
  if (env.ANTHROPIC_API_KEY) {
4968
6417
  checks.push({
4969
6418
  name: "ANTHROPIC_API_KEY",
@@ -4980,9 +6429,9 @@ function formatChecks(checks) {
4980
6429
 
4981
6430
  // src/lock.ts
4982
6431
  import { mkdir as mkdir7, open, readFile as readFile5, rm as rm7 } from "node:fs/promises";
4983
- import { join as join12 } from "node:path";
6432
+ import { join as join13 } from "node:path";
4984
6433
  function lockFile(stateDir) {
4985
- return join12(stateDir, "daemon.pid");
6434
+ return join13(stateDir, "daemon.pid");
4986
6435
  }
4987
6436
  function pidAlive(pid) {
4988
6437
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -5020,8 +6469,8 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
5020
6469
  lock: {
5021
6470
  file,
5022
6471
  async release() {
5023
- const current = await readFile5(file, "utf8").catch(() => "");
5024
- if (Number.parseInt(current.trim(), 10) === pid) await rm7(file, { force: true });
6472
+ const current2 = await readFile5(file, "utf8").catch(() => "");
6473
+ if (Number.parseInt(current2.trim(), 10) === pid) await rm7(file, { force: true });
5025
6474
  }
5026
6475
  }
5027
6476
  };
@@ -5038,7 +6487,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
5038
6487
  }
5039
6488
 
5040
6489
  // src/pairing.ts
5041
- import { spawn as spawn4 } from "node:child_process";
6490
+ import { spawn as spawn5 } from "node:child_process";
5042
6491
  async function pair(api, opts) {
5043
6492
  const start2 = await api.startPairing({ name: opts.name, platform: RUNNER_PLATFORM });
5044
6493
  opts.ui.showCode(start2.userCode, start2.verificationUrl, start2.expiresInSeconds);
@@ -5102,7 +6551,7 @@ function openUrl(url) {
5102
6551
  if (!/^https?:\/\//i.test(url)) return;
5103
6552
  const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
5104
6553
  try {
5105
- const child = spawn4(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
6554
+ const child = spawn5(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
5106
6555
  child.on("error", () => void 0);
5107
6556
  child.unref();
5108
6557
  } catch {
@@ -5178,7 +6627,7 @@ async function main(argv) {
5178
6627
  case "status":
5179
6628
  return status();
5180
6629
  case "doctor":
5181
- return doctor();
6630
+ return doctor4();
5182
6631
  case "logout":
5183
6632
  return logout();
5184
6633
  default:
@@ -5223,7 +6672,7 @@ async function login(server, name, openBrowser, yes) {
5223
6672
  isTTY: process.stdin.isTTY === true,
5224
6673
  print: (line) => console.log(line),
5225
6674
  async ask(question) {
5226
- const rl = createInterface2({ input: process.stdin, output: process.stdout });
6675
+ const rl = createInterface3({ input: process.stdin, output: process.stdout });
5227
6676
  try {
5228
6677
  return await rl.question(question);
5229
6678
  } finally {
@@ -5266,6 +6715,27 @@ async function start(opts) {
5266
6715
  "ANTHROPIC_API_KEY is set: Claude Code will bill that API key, not your Claude subscription. Unset it unless that is what you want."
5267
6716
  );
5268
6717
  }
6718
+ const codexKey = codexKeyVariable(process.env);
6719
+ if (codexKey) {
6720
+ logger.warn(
6721
+ `${codexKey} is set: Codex runs may bill that API key, not your ChatGPT plan. Unset it unless that is what you want.`
6722
+ );
6723
+ }
6724
+ if (config.codexSandbox === "danger-full-access") {
6725
+ logger.warn(
6726
+ 'codexSandbox is danger-full-access: Codex runs can run ANY command and edit ANY file on this computer. Remove "codexSandbox" from the config to go back to workspace-write.'
6727
+ );
6728
+ }
6729
+ if (cursorKeyVariable(process.env)) {
6730
+ logger.warn(
6731
+ "CURSOR_API_KEY is set: Cursor runs sign in with that API key, not your `cursor-agent login`. Unset it unless that is what you want."
6732
+ );
6733
+ }
6734
+ if (config.cursorForce) {
6735
+ logger.warn(
6736
+ 'cursorForce is on: Cursor runs get --force and can run ANY command and edit ANY file on this computer without asking. Remove "cursorForce" from the config to turn it off.'
6737
+ );
6738
+ }
5269
6739
  if (config.permissionMode === "bypassPermissions") {
5270
6740
  logger.warn(
5271
6741
  "!!! permissionMode is bypassPermissions: Claude Code will run ANY command and edit ANY file on this computer without asking. !!!"
@@ -5281,6 +6751,15 @@ async function start(opts) {
5281
6751
  );
5282
6752
  return 1;
5283
6753
  }
6754
+ if (process.platform === "win32") {
6755
+ void startJobHelper().then((ok) => {
6756
+ if (!ok) {
6757
+ logger.warn(
6758
+ "Could not set up Windows job objects (PowerShell unavailable?); processes a run leaves behind are found by parent process id instead."
6759
+ );
6760
+ }
6761
+ });
6762
+ }
5284
6763
  const daemon = new RunnerDaemon({ config, logger });
5285
6764
  let signals = 0;
5286
6765
  const onSignal = (sig) => {
@@ -5335,7 +6814,7 @@ async function status() {
5335
6814
  }
5336
6815
  console.log("Daemon: not running");
5337
6816
  try {
5338
- const agent = await probeAgent();
6817
+ const agent = await agentDriver().probe();
5339
6818
  const res = await api.heartbeat({
5340
6819
  protocolVersion: RUNNER_PROTOCOL_VERSION,
5341
6820
  runnerVersion: RUNNER_VERSION,
@@ -5365,7 +6844,7 @@ async function status() {
5365
6844
  return 1;
5366
6845
  }
5367
6846
  }
5368
- async function doctor() {
6847
+ async function doctor4() {
5369
6848
  const checks = await runDoctor();
5370
6849
  console.log(formatChecks(checks));
5371
6850
  const failed = checks.some((c) => c.level === "fail");