@discovery-tree/runner 0.1.4 → 0.1.6

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 +40 -1
  2. package/dist/cli.js +1050 -676
  3. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -25,6 +25,9 @@ var DEFAULT_AGENT_SYSTEM_PROMPT = [
25
25
  var AGENT_RUN_MAX_WALL_MS = 6 * 60 * 60 * 1e3;
26
26
  var AGENT_RUN_ABANDONED_GRACE_MS = 30 * 60 * 1e3;
27
27
 
28
+ // ../contracts/src/agent-work.ts
29
+ var AGENT_WORK_IDLE_AFTER_MS = 24 * 60 * 60 * 1e3;
30
+
28
31
  // ../contracts/src/agent-runner.ts
29
32
  var RUNNER_PROTOCOL_VERSION = 1;
30
33
  var RUNNER_COMMAND_POLL_MAX_WAIT_MS = 25e3;
@@ -33,7 +36,7 @@ var RUNNER_EVENT_TEXT_MAX_LENGTH = 64e3;
33
36
  var RUNNER_EVENTS_MAX_BODY_BYTES = 8 * 1024 * 1024;
34
37
 
35
38
  // src/version.ts
36
- var RUNNER_VERSION = true ? "0.1.4" : "0.0.0-dev";
39
+ var RUNNER_VERSION = true ? "0.1.6" : "0.0.0-dev";
37
40
  var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
38
41
 
39
42
  // src/api.ts
@@ -143,6 +146,14 @@ var RunnerApi = class {
143
146
  }
144
147
  };
145
148
 
149
+ // src/claude.ts
150
+ import { join as join4 } from "node:path";
151
+
152
+ // src/evidence.ts
153
+ import { mkdir as mkdir2, mkdtemp, readdir, readFile, rename, rm as rm2, stat as stat2, writeFile } from "node:fs/promises";
154
+ import { tmpdir } from "node:os";
155
+ import { isAbsolute as isAbsolute2, join as join3 } from "node:path";
156
+
146
157
  // src/exec.ts
147
158
  import { spawn } from "node:child_process";
148
159
  import { access, constants } from "node:fs/promises";
@@ -198,718 +209,930 @@ async function isExecutable(file) {
198
209
  }
199
210
  }
200
211
 
201
- // src/claude.ts
202
- async function findClaude(env = process.env) {
203
- const override = env.DT_RUNNER_CLAUDE_BIN?.trim();
204
- if (override) return which(override, env);
205
- return which("claude", env);
206
- }
207
- async function claudeVersion(bin) {
208
- try {
209
- const res = await exec(bin, ["--version"], { timeoutMs: 15e3 });
210
- if (res.code !== 0) return null;
211
- return res.stdout.trim().split("\n")[0] || null;
212
- } catch {
213
- return null;
214
- }
212
+ // src/git.ts
213
+ import { mkdir, rm, stat } from "node:fs/promises";
214
+ import { dirname, join as join2 } from "node:path";
215
+
216
+ // src/log.ts
217
+ function createLogger(opts = {}) {
218
+ const write = opts.write ?? ((line) => process.stdout.write(line + "\n"));
219
+ const emit = (level, msg, fields) => {
220
+ if (level === "debug" && !opts.verbose) return;
221
+ const safe = fields ? redactFields(fields) : void 0;
222
+ if (opts.json) {
223
+ write(JSON.stringify({ time: (/* @__PURE__ */ new Date()).toISOString(), level, msg, ...safe }));
224
+ return;
225
+ }
226
+ const time = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
227
+ const tag = level === "info" ? "" : ` ${level.toUpperCase()}`;
228
+ const extra = safe ? " " + Object.entries(safe).filter(([, v]) => v !== void 0 && v !== null && v !== "").map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ") : "";
229
+ write(`${time}${tag} ${msg}${extra.trimEnd() === "" ? "" : extra}`);
230
+ };
231
+ return {
232
+ debug: (m, f) => emit("debug", m, f),
233
+ info: (m, f) => emit("info", m, f),
234
+ warn: (m, f) => emit("warn", m, f),
235
+ error: (m, f) => emit("error", m, f)
236
+ };
215
237
  }
216
- async function claudeAuthStatus(bin) {
217
- try {
218
- const res = await exec(bin, ["auth", "status", "--json"], { timeoutMs: 2e4 });
219
- const parsed = JSON.parse(res.stdout);
220
- if (typeof parsed.loggedIn !== "boolean") return { loggedIn: null, authMethod: null };
221
- return {
222
- loggedIn: parsed.loggedIn,
223
- authMethod: typeof parsed.authMethod === "string" ? parsed.authMethod : null
224
- };
225
- } catch {
226
- return { loggedIn: null, authMethod: null };
227
- }
238
+ var SECRET_KEY = /token|secret|password|authorization/i;
239
+ function redactFields(fields) {
240
+ const out = {};
241
+ for (const [k, v] of Object.entries(fields)) out[k] = SECRET_KEY.test(k) ? "[redacted]" : v;
242
+ return out;
228
243
  }
229
- async function claudeFeatures(bin) {
230
- try {
231
- const res = await exec(bin, ["--help"], { timeoutMs: 15e3 });
232
- return {
233
- permissionPrompts: res.stdout.includes("--permission-prompts"),
234
- settingSources: res.stdout.includes("--setting-sources")
235
- };
236
- } catch {
237
- return { permissionPrompts: false, settingSources: false };
238
- }
244
+ function scrubSecrets(text) {
245
+ return text.replace(/(https?:\/\/)[^/\s@]+@/gi, "$1***@").replace(/\bdtr_[A-Za-z0-9_-]+/g, "dtr_***").replace(/\b(gh[pousr]_[A-Za-z0-9]{10,})/g, "***");
239
246
  }
240
- async function probeAgent(env = process.env) {
241
- const bin = await findClaude(env);
242
- if (!bin) {
243
- return {
244
- claudeVersion: null,
245
- claudeReady: false,
246
- claudeProblem: "Claude Code is not installed on this computer (no `claude` on PATH)."
247
- };
248
- }
249
- const version = await claudeVersion(bin);
250
- if (!version) {
251
- return {
252
- claudeVersion: null,
253
- claudeReady: false,
254
- claudeProblem: "`claude --version` failed; reinstall or update Claude Code."
255
- };
256
- }
257
- const auth = await claudeAuthStatus(bin);
258
- if (auth.loggedIn === false) {
259
- return {
260
- claudeVersion: version,
261
- claudeReady: false,
262
- claudeProblem: "Claude Code is not signed in. Run `claude` once on this computer and sign in."
263
- };
247
+
248
+ // src/git.ts
249
+ var GitError = class extends Error {
250
+ constructor(args, result) {
251
+ super(gitErrorMessage(args, result));
252
+ this.args = args;
253
+ this.result = result;
254
+ this.name = "GitError";
264
255
  }
265
- return { claudeVersion: version, claudeReady: auth.loggedIn, claudeProblem: null };
256
+ };
257
+ function gitErrorMessage(args, result) {
258
+ const detail = (result.stderr || result.stdout).trim().split("\n").filter(Boolean).slice(-3).join(" ");
259
+ return scrubSecrets(`git ${args[0]} failed${detail ? `: ${detail}` : ""}`).slice(0, 500);
266
260
  }
267
- var SIGN_IN_FAILURE = /failed to authenticate|oauth (session|token)\b[^.]*\bexpired|invalid (x-)?api[ -]key|authentication_error|please run \/login/i;
268
- function looksLikeSignInFailure(text) {
269
- return !!text && SIGN_IN_FAILURE.test(text);
261
+ var gitEnv = () => ({
262
+ ...process.env,
263
+ GIT_TERMINAL_PROMPT: "0",
264
+ GCM_INTERACTIVE: "never",
265
+ GIT_ASKPASS: process.env.GIT_ASKPASS ?? ""
266
+ });
267
+ async function git(cwd, args, timeoutMs = 10 * 6e4) {
268
+ const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs });
269
+ if (res.code !== 0) throw new GitError(args, res);
270
+ return res.stdout.trim();
270
271
  }
271
- function turnFailedToSignIn(turn) {
272
- return (turn.subtype ?? "success") === "success" && looksLikeSignInFailure(turn.text);
272
+ async function gitOk(cwd, args) {
273
+ const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs: 6e4 });
274
+ return res.code === 0;
273
275
  }
274
- function signInFix(env = process.env) {
275
- if (env.ANTHROPIC_API_KEY) {
276
- return "`ANTHROPIC_API_KEY` is set where the runner runs, so Claude Code signs in with that key instead of your Claude subscription. Unset it (or replace it with a working key) and restart the runner.";
276
+ var REPOSITORY_HOST = "github.com";
277
+ function parseRepoUrl(url) {
278
+ try {
279
+ const u = new URL(url);
280
+ if (u.protocol !== "https:" || u.hostname.toLowerCase() !== REPOSITORY_HOST) return null;
281
+ if (u.port || u.username || u.password || u.search || u.hash) return null;
282
+ const parts = u.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "").split("/");
283
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
284
+ if (!/^[\w.-]+$/.test(parts[0]) || !/^[\w.-]+$/.test(parts[1])) return null;
285
+ if (parts.some((p) => p === "." || p === "..")) return null;
286
+ return { host: REPOSITORY_HOST, owner: parts[0], repo: parts[1] };
287
+ } catch {
288
+ return null;
277
289
  }
278
- return 'On the runner\u2019s computer, run `claude`, type `/login` and sign in again, and check that `claude -p "say ok"` answers.';
279
290
  }
280
- var MODEL_NAME = /^[A-Za-z0-9][\w.:@/[\]-]{0,199}$/;
281
- function isValidModelName(model) {
282
- return MODEL_NAME.test(model);
283
- }
284
- function assertValidModel(model) {
285
- if (model && !isValidModelName(model)) {
286
- throw new Error(
287
- `The model "${model.slice(0, 80)}" is not a valid Claude Code model name; the runner refused to start it.`
288
- );
289
- }
291
+ function repositoryUrlError(url) {
292
+ return `Repository URL ${scrubSecrets(url).slice(0, 200)} is not a https://github.com/<owner>/<repo> URL; this runner only works on GitHub repositories.`;
290
293
  }
291
- function claudeArgs(launch) {
292
- const args = [
293
- "-p",
294
- "--input-format",
295
- "stream-json",
296
- "--output-format",
297
- "stream-json",
298
- "--verbose",
299
- "--include-partial-messages"
300
- ];
301
- if (launch.permissionMode === "bypassPermissions") {
302
- args.push("--dangerously-skip-permissions");
303
- } else {
304
- args.push("--permission-mode", launch.permissionMode);
305
- }
306
- if (launch.features.permissionPrompts) args.push("--permission-prompts", "none");
307
- if (launch.features.settingSources && !launch.loadProjectSettings) {
308
- args.push("--setting-sources", "user");
309
- }
310
- if (launch.model) {
311
- assertValidModel(launch.model);
312
- args.push(`--model=${launch.model}`);
313
- }
314
- if (launch.resume) args.push("--resume", launch.resume);
315
- if (launch.appendSystemPrompt) args.push("--append-system-prompt", launch.appendSystemPrompt);
316
- if (launch.disallowedTools?.length) args.push("--disallowedTools", ...launch.disallowedTools);
317
- if (launch.allowedTools.length) args.push("--allowedTools", ...launch.allowedTools);
318
- return args;
294
+ function cloneUrl(ref, protocol) {
295
+ return protocol === "ssh" ? `git@${ref.host}:${ref.owner}/${ref.repo}.git` : `https://${ref.host}/${ref.owner}/${ref.repo}.git`;
319
296
  }
320
- function runnerSystemPrompt(input) {
321
- if (!input.workBranch) {
322
- return [
323
- "You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
324
- "Your working directory is a scratch directory created for this task; it is not a git repository."
325
- ].join(" ");
297
+ var UNSAFE_REF = /[\s~^:?*[\\\x00-\x1f]|\.\.|@\{|\/\/|\.lock$|\/$/;
298
+ function assertSafeRef(name, what) {
299
+ if (!name || name.startsWith("-") || UNSAFE_REF.test(name)) {
300
+ throw new Error(`${what} "${name}" is not a valid branch name.`);
326
301
  }
327
- return [
328
- "You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
329
- `Your working directory is a git worktree managed by the runner, on branch \`${input.workBranch}\``,
330
- input.baseRef ? `(created from \`${input.baseRef}\`).` : ".",
331
- "Commit your work to this branch as you go, with clear, descriptive commit messages.",
332
- "Do not push, do not switch, create or delete branches, and do not rewrite commits that may",
333
- "already be pushed: the runner commits anything left over and pushes this branch for you",
334
- "at the end of every turn.",
335
- "Do not open a pull request either: Discovery Tree opens it from this branch when a turn",
336
- "ends, with that turn\u2019s final message as its description, and later turns add to it.",
337
- "Before then (your first turn) there is none; say so rather than trying to open one.",
338
- `To read it, use \`gh pr view ${input.workBranch}\` (\`--comments\` for the conversation),`,
339
- "`gh pr diff`, `gh pr checks`, and `gh run view` for a check run\u2019s logs. Only `gh` commands",
340
- "that read are allowed; ones that change GitHub (comment, edit, merge, `gh api`) are denied."
341
- ].join(" ");
342
- }
343
-
344
- // src/config.ts
345
- import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
346
- import { homedir } from "node:os";
347
- import { dirname, join as join2 } from "node:path";
348
-
349
- // src/invocation.ts
350
- var RUNNER_PACKAGE = "@discovery-tree/runner";
351
- function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
352
- if (env.npm_command === "exec") return true;
353
- return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
354
302
  }
355
- function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
356
- return viaNpx ? `npx ${RUNNER_PACKAGE}@latest ${subcommand}` : `dt-runner ${subcommand}`;
303
+ var repoLocks = /* @__PURE__ */ new Map();
304
+ function withRepoLock(dir, fn) {
305
+ const prev = repoLocks.get(dir) ?? Promise.resolve();
306
+ const next = prev.catch(() => void 0).then(fn);
307
+ repoLocks.set(dir, next);
308
+ const release = () => {
309
+ if (repoLocks.get(dir) === next) repoLocks.delete(dir);
310
+ };
311
+ next.then(release, release);
312
+ return next;
357
313
  }
358
-
359
- // src/config.ts
360
- function runnerPaths(env = process.env) {
361
- const home = homedir();
362
- if (process.platform === "win32") {
363
- const roaming = env.APPDATA || join2(home, "AppData", "Roaming");
364
- const local = env.LOCALAPPDATA || join2(home, "AppData", "Local");
365
- return {
366
- configFile: join2(roaming, "discovery-tree", "runner.json"),
367
- dataDir: join2(local, "discovery-tree", "runner"),
368
- stateDir: join2(local, "discovery-tree", "runner", "state")
369
- };
314
+ async function exists(p) {
315
+ try {
316
+ await stat(p);
317
+ return true;
318
+ } catch {
319
+ return false;
370
320
  }
371
- const config = env.XDG_CONFIG_HOME || join2(home, ".config");
372
- const data = env.XDG_DATA_HOME || join2(home, ".local", "share");
373
- const state = env.XDG_STATE_HOME || join2(home, ".local", "state");
374
- return {
375
- configFile: join2(config, "discovery-tree", "runner.json"),
376
- dataDir: join2(data, "discovery-tree", "runner"),
377
- stateDir: join2(state, "discovery-tree", "runner")
378
- };
379
321
  }
380
- var PERMISSION_MODES = [
381
- "acceptEdits",
382
- "auto",
383
- "default",
384
- "manual",
385
- "dontAsk",
386
- "plan",
387
- "bypassPermissions"
388
- ];
389
- var DEFAULT_ALLOWED_TOOLS = [
390
- "Read",
391
- "Edit",
392
- "MultiEdit",
393
- "Write",
394
- "Glob",
395
- "Grep",
396
- "LS",
397
- "NotebookEdit",
398
- "TodoWrite",
399
- "Task",
400
- "Bash(git status *)",
401
- "Bash(git diff *)",
402
- "Bash(git log *)",
403
- "Bash(git show *)",
404
- "Bash(git add *)",
405
- "Bash(git commit *)",
406
- "Bash(git restore *)",
407
- "Bash(git rm *)",
408
- "Bash(git mv *)",
409
- "Bash(git stash *)",
410
- "Bash(git blame *)",
411
- "Bash(git grep *)",
412
- "Bash(gh pr view *)",
413
- "Bash(gh pr diff *)",
414
- "Bash(gh pr checks *)",
415
- "Bash(gh pr list *)",
416
- "Bash(gh pr status *)",
417
- "Bash(gh run view *)",
418
- "Bash(gh run list *)",
419
- "Bash(gh issue view *)",
420
- "Bash(gh issue list *)",
421
- "Bash(gh repo view *)",
422
- "Bash(npm *)",
423
- "Bash(npx *)",
424
- "Bash(pnpm *)",
425
- "Bash(yarn *)",
426
- "Bash(node *)",
427
- "Bash(tsc *)",
428
- "Bash(python *)",
429
- "Bash(python3 *)",
430
- "Bash(pip *)",
431
- "Bash(pytest *)",
432
- "Bash(make *)",
433
- "Bash(cargo *)",
434
- "Bash(go *)",
435
- "Bash(ls *)",
436
- "Bash(cat *)",
437
- "Bash(head *)",
438
- "Bash(tail *)",
439
- "Bash(wc *)",
440
- "Bash(grep *)",
441
- "Bash(rg *)",
442
- "Bash(echo *)",
443
- "Bash(pwd)",
444
- "Bash(mkdir *)",
445
- "Bash(touch *)",
446
- "Bash(diff *)",
447
- "Bash(sort *)",
448
- "Bash(uniq *)",
449
- "Bash(which *)",
450
- "Bash(true)"
451
- ];
452
- var PROTECTED_PATHS = [
453
- "~/.ssh/**",
454
- "~/.aws/**",
455
- "~/.config/gcloud/**",
456
- "~/.azure/**",
457
- "~/.gnupg/**",
458
- "~/.netrc",
459
- "~/.git-credentials",
460
- "~/.config/gh/**",
461
- "~/.docker/config.json",
462
- "~/.kube/**",
463
- "~/.npmrc",
464
- "~/.pypirc",
465
- // The runner's own token.
466
- "~/.config/discovery-tree/**",
467
- // Claude Code's sign-in and account file.
468
- "~/.claude/.credentials.json",
469
- "~/.claude.json"
470
- ];
471
- var PROTECTED_FROM_EDIT = [
472
- "~/.claude/**",
473
- // Shell startup files and git config: an edit there runs, or changes what runs, in every
474
- // later shell or git command the person uses outside the agent.
475
- "~/.bashrc",
476
- "~/.bash_profile",
477
- "~/.profile",
478
- "~/.zshrc",
479
- "~/.zprofile",
480
- "~/.zshenv",
481
- "~/.config/fish/**",
482
- "~/.gitconfig",
483
- "~/.config/git/**"
484
- ];
485
- var DEFAULT_DISALLOWED_TOOLS = [
486
- ...PROTECTED_PATHS.map((p) => `Read(${p})`),
487
- ...[...PROTECTED_PATHS, ...PROTECTED_FROM_EDIT].map((p) => `Edit(${p})`)
488
- ];
489
- function configDirRules(configFile, platform = process.platform) {
490
- if (platform === "win32") return [];
491
- const dir = dirname(configFile);
492
- if (!dir.startsWith("/")) return [];
493
- return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
322
+ async function prepareWorktree(input) {
323
+ const ref = parseRepoUrl(input.url);
324
+ if (!ref) throw new Error(repositoryUrlError(input.url));
325
+ assertSafeRef(input.workBranch, "Work branch");
326
+ if (input.baseRef) assertSafeRef(input.baseRef, "Base branch");
327
+ const repoDir = join2(input.reposDir, ref.owner, ref.repo);
328
+ const worktree = join2(input.worktreesDir, input.worktreeKey || input.sessionId);
329
+ return withRepoLock(repoDir, async () => {
330
+ if (!await exists(join2(repoDir, ".git"))) {
331
+ await mkdir(dirname(repoDir), { recursive: true });
332
+ await rm(repoDir, { recursive: true, force: true });
333
+ await git(dirname(repoDir), [
334
+ "clone",
335
+ "--no-checkout",
336
+ cloneUrl(ref, input.protocol),
337
+ repoDir
338
+ ]);
339
+ } else {
340
+ const wanted = cloneUrl(ref, input.protocol);
341
+ const current = await exec("git", ["config", "--get", "remote.origin.url"], {
342
+ cwd: repoDir,
343
+ env: gitEnv()
344
+ });
345
+ if (current.stdout.trim() !== wanted) {
346
+ await git(repoDir, ["remote", "set-url", "origin", wanted]);
347
+ }
348
+ await git(repoDir, ["fetch", "--prune", "origin"]);
349
+ }
350
+ const baseRef = input.baseRef ?? await defaultBranch(repoDir);
351
+ let start2 = `origin/${baseRef}`;
352
+ if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${start2}^{commit}`])) {
353
+ if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`])) {
354
+ throw new Error(`Base branch ${baseRef} was not found on origin.`);
355
+ }
356
+ start2 = baseRef;
357
+ }
358
+ let baseSha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
359
+ let checkout = start2;
360
+ let continuedFrom;
361
+ let setAside;
362
+ const remoteWork = `refs/remotes/origin/${input.workBranch}`;
363
+ if (input.continueBranch && await exists(worktree) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
364
+ cwd: worktree,
365
+ env: gitEnv(),
366
+ timeoutMs: 6e4
367
+ }).then((r) => r.code === 0 && r.stdout.trim() === input.workBranch) && // Only when it already has everything pushed to the work branch since: one that fell
368
+ // behind (the run went on elsewhere) would have the agent work on stale code.
369
+ (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${remoteWork}^{commit}`]) || await exec("git", ["merge-base", "--is-ancestor", remoteWork, "HEAD"], {
370
+ cwd: worktree,
371
+ env: gitEnv(),
372
+ timeoutMs: 6e4
373
+ }).then((r) => r.code === 0))) {
374
+ const forkPoint = await exec("git", ["merge-base", "HEAD", start2], {
375
+ cwd: worktree,
376
+ env: gitEnv(),
377
+ timeoutMs: 6e4
378
+ });
379
+ if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
380
+ return { repoDir, worktree, baseRef, baseSha, continuedFrom: "worktree" };
381
+ }
382
+ if (input.continueBranch) {
383
+ const remote = `refs/remotes/origin/${input.workBranch}`;
384
+ const local = `refs/heads/${input.workBranch}`;
385
+ const hasRemote = await gitOk(repoDir, [
386
+ "rev-parse",
387
+ "--verify",
388
+ "--quiet",
389
+ `${remote}^{commit}`
390
+ ]);
391
+ const hasLocal = await gitOk(repoDir, [
392
+ "rev-parse",
393
+ "--verify",
394
+ "--quiet",
395
+ `${local}^{commit}`
396
+ ]);
397
+ const localAhead = hasLocal && (!hasRemote || await gitOk(repoDir, ["merge-base", "--is-ancestor", remote, local]));
398
+ if (localAhead) {
399
+ checkout = local;
400
+ continuedFrom = "local";
401
+ } else if (hasRemote) {
402
+ checkout = remote;
403
+ continuedFrom = "remote";
404
+ } else {
405
+ continuedFrom = "base";
406
+ }
407
+ if (continuedFrom !== "base") {
408
+ const forkPoint = await exec("git", ["merge-base", checkout, start2], {
409
+ cwd: repoDir,
410
+ env: gitEnv(),
411
+ timeoutMs: 6e4
412
+ });
413
+ if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
414
+ checkout = await git(repoDir, ["rev-parse", `${checkout}^{commit}`]);
415
+ }
416
+ }
417
+ if (input.continueBranch && await exists(worktree)) {
418
+ const dirty = await exec("git", ["status", "--porcelain"], {
419
+ cwd: worktree,
420
+ env: gitEnv(),
421
+ timeoutMs: 6e4
422
+ });
423
+ if (dirty.code === 0 && dirty.stdout.trim()) {
424
+ const aside = `${worktree}.kept-${Date.now()}`;
425
+ if (await gitOk(repoDir, ["worktree", "move", worktree, aside])) setAside = aside;
426
+ }
427
+ }
428
+ if (await exists(worktree)) {
429
+ await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
430
+ await rm(worktree, { recursive: true, force: true });
431
+ }
432
+ await gitOk(repoDir, ["worktree", "prune"]);
433
+ await mkdir(input.worktreesDir, { recursive: true });
434
+ await git(repoDir, [
435
+ "worktree",
436
+ "add",
437
+ "--no-track",
438
+ "-B",
439
+ input.workBranch,
440
+ worktree,
441
+ checkout
442
+ ]);
443
+ return {
444
+ repoDir,
445
+ worktree,
446
+ baseRef,
447
+ baseSha,
448
+ ...continuedFrom ? { continuedFrom } : {},
449
+ ...setAside ? { setAside } : {}
450
+ };
451
+ });
494
452
  }
495
- var DEFAULT_SERVER_URL = "https://discovery-tree-backend.onrender.com";
496
- var DEFAULT_MAX_SESSIONS = 2;
497
- var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
498
- async function readConfigFile(file) {
499
- let raw;
453
+ async function defaultBranch(repoDir) {
454
+ const read = async () => {
455
+ const res = await exec("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
456
+ cwd: repoDir,
457
+ env: gitEnv()
458
+ });
459
+ return res.code === 0 ? res.stdout.trim().replace(/^origin\//, "") : null;
460
+ };
461
+ const known = await read();
462
+ if (known) return known;
463
+ await gitOk(repoDir, ["remote", "set-head", "origin", "--auto"]);
464
+ return await read() ?? "main";
465
+ }
466
+ async function commitAndPush(input) {
467
+ const { worktree } = input;
468
+ const exclude = input.exclude ?? [];
469
+ const excluded = (line) => {
470
+ const path = line.slice(3).replace(/^"|"$/g, "");
471
+ return exclude.some((p) => path === p || path.startsWith(`${p}/`));
472
+ };
473
+ let committed = false;
500
474
  try {
501
- raw = await readFile(file, "utf8");
475
+ const status2 = await git(worktree, ["status", "--porcelain"]);
476
+ const dirty = status2.split("\n").some((line) => line && !excluded(line));
477
+ if (dirty) {
478
+ await git(worktree, ["add", "-A"]);
479
+ if (exclude.length) await git(worktree, ["reset", "-q", "--", ...exclude]);
480
+ }
481
+ const staged = dirty && !await gitOk(worktree, ["diff", "--cached", "--quiet"]);
482
+ if (staged) {
483
+ const identity2 = await gitOk(worktree, ["config", "user.email"]) ? [] : [
484
+ "-c",
485
+ "user.name=Discovery Tree runner",
486
+ "-c",
487
+ "user.email=dt-runner@users.noreply.local"
488
+ ];
489
+ await git(worktree, [...identity2, "commit", "--no-verify", "-q", "-m", input.message]);
490
+ committed = true;
491
+ }
502
492
  } catch (err) {
503
- if (err.code === "ENOENT") return null;
504
- throw err;
493
+ return {
494
+ committed,
495
+ pushed: false,
496
+ error: errorText(err, "Committing the work failed"),
497
+ failedAt: "commit"
498
+ };
499
+ }
500
+ try {
501
+ const ahead = Number(await git(worktree, ["rev-list", "--count", `${input.baseSha}..HEAD`]));
502
+ if (!ahead) return { committed, pushed: false, error: null };
503
+ await git(worktree, ["push", "--quiet", "-u", "origin", `HEAD:refs/heads/${input.workBranch}`]);
504
+ return { committed, pushed: true, error: null };
505
+ } catch (err) {
506
+ return {
507
+ committed,
508
+ pushed: false,
509
+ error: errorText(err, "Pushing the work branch failed"),
510
+ failedAt: "push"
511
+ };
505
512
  }
513
+ }
514
+ async function removeWorktree(repoDir, worktree) {
515
+ if (repoDir && await exists(repoDir)) {
516
+ await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
517
+ }
518
+ await rm(worktree, { recursive: true, force: true });
519
+ if (repoDir && await exists(repoDir)) await gitOk(repoDir, ["worktree", "prune"]);
520
+ }
521
+ function errorText(err, prefix) {
522
+ const msg = err instanceof Error ? err.message : String(err);
523
+ return scrubSecrets(`${prefix}: ${msg}`).slice(0, 600);
524
+ }
525
+
526
+ // src/evidence.ts
527
+ var EVIDENCE_DIR = ".dt-evidence";
528
+ var PUBLISHED_DIR = "published";
529
+ var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "gif", "webp"]);
530
+ var MAX_EVIDENCE_IMAGES = 12;
531
+ var MAX_EVIDENCE_BYTES = 8 * 1024 * 1024;
532
+ function evidenceBranch(workBranch) {
533
+ return `dt-evidence/${workBranch.replace(/%/g, "%25").replace(/\//g, "%2F")}`;
534
+ }
535
+ async function ensureEvidenceDir(worktree) {
536
+ await mkdir2(join3(worktree, EVIDENCE_DIR), { recursive: true });
537
+ const rel = await git(worktree, ["rev-parse", "--git-path", "info/exclude"]);
538
+ const file = isAbsolute2(rel) ? rel : join3(worktree, rel);
539
+ const line = `/${EVIDENCE_DIR}/`;
540
+ let current = "";
506
541
  try {
507
- return JSON.parse(raw);
542
+ current = await readFile(file, "utf8");
508
543
  } catch {
509
- throw new Error(
510
- `${file} is not valid JSON; fix it or run \`${runnerCommand("logout")}\` to start over.`
511
- );
512
544
  }
545
+ if (current.split("\n").some((l) => l.trim() === line)) return;
546
+ await mkdir2(join3(file, ".."), { recursive: true });
547
+ const sep = current && !current.endsWith("\n") ? "\n" : "";
548
+ await writeFile(
549
+ file,
550
+ `${current}${sep}# Screenshots dt-runner publishes on their own branch
551
+ ${line}
552
+ `
553
+ );
513
554
  }
514
- async function writeConfigFile(file, config) {
515
- await mkdir(dirname(file), { recursive: true, mode: 448 });
516
- await writeFile(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
517
- await chmod(file, 384).catch(() => void 0);
518
- }
519
- async function deleteConfigFile(file) {
555
+ async function publishEvidence(input) {
556
+ const dir = join3(input.worktree, EVIDENCE_DIR);
557
+ let found;
520
558
  try {
521
- await rm(file);
522
- return true;
559
+ found = await waitingImages(dir);
523
560
  } catch (err) {
524
- if (err.code === "ENOENT") return false;
525
- throw err;
561
+ const why = err instanceof Error ? err.message : String(err);
562
+ return { images: [], skipped: [], error: `Reading the screenshots failed: ${why}` };
563
+ }
564
+ const skipped = found.filter((f) => f.size > MAX_EVIDENCE_BYTES).map((f) => f.name);
565
+ const fitting = found.filter((f) => f.size <= MAX_EVIDENCE_BYTES);
566
+ skipped.push(...fitting.slice(MAX_EVIDENCE_IMAGES).map((f) => f.name));
567
+ const files = fitting.slice(0, MAX_EVIDENCE_IMAGES);
568
+ if (!files.length) return { images: [], skipped, error: null };
569
+ const branch = evidenceBranch(input.workBranch);
570
+ let scratch = null;
571
+ try {
572
+ assertSafeRef(branch, "Evidence branch");
573
+ scratch = await mkdtemp(join3(tmpdir(), "dt-evidence-"));
574
+ const index = join3(scratch, "index");
575
+ const ref = `refs/heads/${branch}`;
576
+ const build = async () => {
577
+ await gitOk2(input.repoDir, ["fetch", "--quiet", "origin", `+${ref}:${ref}`]);
578
+ const parent = await revParse(input.repoDir, ref);
579
+ const run = (args) => gitWithIndex(input.repoDir, index, args);
580
+ await run(parent ? ["read-tree", parent] : ["read-tree", "--empty"]);
581
+ for (const f of files) {
582
+ const blob = await git(input.repoDir, ["hash-object", "-w", "--", join3(dir, f.name)]);
583
+ await run(["update-index", "--add", "--cacheinfo", `100644,${blob},${f.path}`]);
584
+ }
585
+ const tree = await run(["write-tree"]);
586
+ const parentTree = parent ? await git(input.repoDir, ["rev-parse", `${parent}^{tree}`]) : null;
587
+ if (parent && tree === parentTree) return parent;
588
+ const made = await git(input.repoDir, [
589
+ ...await identity(input.repoDir),
590
+ "commit-tree",
591
+ tree,
592
+ ...parent ? ["-p", parent] : [],
593
+ "-m",
594
+ `Screenshots for ${input.workBranch}
595
+
596
+ Published by dt-runner for the pull request's review; not part of the change.`
597
+ ]);
598
+ await git(input.repoDir, ["update-ref", ref, made]);
599
+ return made;
600
+ };
601
+ let commit = await build();
602
+ try {
603
+ await git(input.repoDir, ["push", "--quiet", "origin", `${commit}:${ref}`]);
604
+ } catch {
605
+ commit = await build();
606
+ await git(input.repoDir, ["push", "--quiet", "origin", `${commit}:${ref}`]);
607
+ }
608
+ await mkdir2(join3(dir, PUBLISHED_DIR), { recursive: true });
609
+ for (const f of files) {
610
+ await rename(join3(dir, f.name), join3(dir, PUBLISHED_DIR, f.name)).catch(() => void 0);
611
+ }
612
+ return {
613
+ images: files.map((f) => ({
614
+ path: f.path,
615
+ caption: captionFor(f.name),
616
+ url: rawFileUrl(input.repo, commit, f.path)
617
+ })),
618
+ skipped,
619
+ error: null
620
+ };
621
+ } catch (err) {
622
+ const why = err instanceof GitError || err instanceof Error ? err.message : String(err);
623
+ return { images: [], skipped, error: `Publishing the screenshots failed: ${why}` };
624
+ } finally {
625
+ if (scratch) await rm2(scratch, { recursive: true, force: true }).catch(() => void 0);
526
626
  }
527
627
  }
528
- function normalizeServerUrl(url) {
529
- const trimmed = url.trim().replace(/\/+$/, "");
530
- return trimmed.replace(/\/api(\/health)?$/, "");
531
- }
532
- var MAX_SESSIONS_LIMIT = 64;
533
- function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPaths(env)) {
534
- const mode = file?.permissionMode ?? "acceptEdits";
535
- if (!PERMISSION_MODES.includes(mode)) {
536
- throw new Error(
537
- `permissionMode "${mode}" in ${paths.configFile} is not one of ${PERMISSION_MODES.join(", ")}.`
538
- );
539
- }
540
- const maxSessions = overrides.maxSessions ?? file?.maxSessions ?? DEFAULT_MAX_SESSIONS;
541
- if (!Number.isInteger(maxSessions) || maxSessions < 1 || maxSessions > MAX_SESSIONS_LIMIT) {
542
- throw new Error(
543
- `maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
544
- );
545
- }
546
- const allowed = [
547
- ...file?.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
548
- ...file?.extraAllowedTools ?? []
549
- ];
550
- const disallowed = [
551
- ...file?.disallowedTools ?? [
552
- ...DEFAULT_DISALLOWED_TOOLS,
553
- ...configDirRules(paths.configFile)
554
- ],
555
- ...file?.extraDisallowedTools ?? []
556
- ];
557
- return {
558
- server: normalizeServerUrl(env.DT_SERVER_URL || file?.server || DEFAULT_SERVER_URL),
559
- runnerId: file?.runnerId ?? null,
560
- token: env.DT_RUNNER_TOKEN || file?.token || null,
561
- name: file?.name ?? null,
562
- maxSessions,
563
- reposDir: overrides.reposDir ?? file?.reposDir ?? join2(paths.dataDir, "repos"),
564
- worktreesDir: file?.worktreesDir ?? join2(paths.dataDir, "worktrees"),
565
- permissionMode: mode,
566
- allowedTools: [...new Set(allowed)],
567
- disallowedTools: [...new Set(disallowed)],
568
- loadProjectSettings: file?.loadProjectSettings === true,
569
- gitProtocol: file?.gitProtocol === "ssh" ? "ssh" : "https",
570
- idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
571
- stateDir: paths.stateDir,
572
- configFile: paths.configFile
573
- };
628
+ function evidenceMarkdown(result) {
629
+ if (!result.images.length) return "";
630
+ return ["## Screenshots", "", ...result.images.map((i) => `![${i.caption}](${i.url})`)].join(
631
+ "\n"
632
+ );
574
633
  }
575
-
576
- // src/backoff.ts
577
- function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
578
- const ceiling = Math.min(maxMs, baseMs * 2 ** Math.min(attempt, 20));
579
- return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
634
+ function rawFileUrl(repo, commit, path) {
635
+ const segments = path.split("/").map(encodeURIComponent).join("/");
636
+ return `https://${repo.host}/${repo.owner}/${repo.repo}/raw/${commit}/${segments}`;
580
637
  }
581
- function sleep(ms, signal) {
582
- return new Promise((resolve) => {
583
- if (signal?.aborted) return resolve();
584
- const timer = setTimeout(done, ms);
585
- function done() {
586
- clearTimeout(timer);
587
- signal?.removeEventListener("abort", done);
588
- resolve();
589
- }
590
- signal?.addEventListener("abort", done, { once: true });
591
- });
638
+ async function waitingImages(dir) {
639
+ let entries;
640
+ try {
641
+ entries = await readdir(dir, { withFileTypes: true });
642
+ } catch {
643
+ return [];
644
+ }
645
+ const out = [];
646
+ for (const e of entries) {
647
+ if (!e.isFile()) continue;
648
+ const ext = e.name.split(".").pop()?.toLowerCase() ?? "";
649
+ if (!e.name.includes(".") || !IMAGE_EXTENSIONS.has(ext)) continue;
650
+ const { size } = await stat2(join3(dir, e.name));
651
+ out.push({ name: e.name, path: safeName(e.name), size });
652
+ }
653
+ out.sort((a, b) => a.name.localeCompare(b.name));
654
+ const taken = /* @__PURE__ */ new Set();
655
+ for (const f of out) {
656
+ let path = f.path;
657
+ for (let n = 2; taken.has(path.toLowerCase()); n++) {
658
+ path = f.path.replace(/(\.[^.]+)?$/, (ext) => `-${n}${ext}`);
659
+ }
660
+ taken.add(path.toLowerCase());
661
+ f.path = path;
662
+ }
663
+ return out;
592
664
  }
593
-
594
- // src/session-manager.ts
595
- import { mkdir as mkdir5, rm as rm4 } from "node:fs/promises";
596
-
597
- // src/git.ts
598
- import { mkdir as mkdir2, rm as rm2, stat } from "node:fs/promises";
599
- import { dirname as dirname2, join as join3 } from "node:path";
600
-
601
- // src/log.ts
602
- function createLogger(opts = {}) {
603
- const write = opts.write ?? ((line) => process.stdout.write(line + "\n"));
604
- const emit = (level, msg, fields) => {
605
- if (level === "debug" && !opts.verbose) return;
606
- const safe = fields ? redactFields(fields) : void 0;
607
- if (opts.json) {
608
- write(JSON.stringify({ time: (/* @__PURE__ */ new Date()).toISOString(), level, msg, ...safe }));
609
- return;
610
- }
611
- const time = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
612
- const tag = level === "info" ? "" : ` ${level.toUpperCase()}`;
613
- const extra = safe ? " " + Object.entries(safe).filter(([, v]) => v !== void 0 && v !== null && v !== "").map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ") : "";
614
- write(`${time}${tag} ${msg}${extra.trimEnd() === "" ? "" : extra}`);
615
- };
616
- return {
617
- debug: (m, f) => emit("debug", m, f),
618
- info: (m, f) => emit("info", m, f),
619
- warn: (m, f) => emit("warn", m, f),
620
- error: (m, f) => emit("error", m, f)
621
- };
665
+ function safeName(name) {
666
+ const cleaned = name.replace(/[^\w.-]+/g, "-").replace(/^[.-]+/, "");
667
+ return cleaned || "screenshot.png";
622
668
  }
623
- var SECRET_KEY = /token|secret|password|authorization/i;
624
- function redactFields(fields) {
625
- const out = {};
626
- for (const [k, v] of Object.entries(fields)) out[k] = SECRET_KEY.test(k) ? "[redacted]" : v;
627
- return out;
669
+ function captionFor(name) {
670
+ return name.replace(/\.[^.]+$/, "").replace(/[-_]+/g, " ").replace(/[[\]]/g, "").trim();
628
671
  }
629
- function scrubSecrets(text) {
630
- return text.replace(/(https?:\/\/)[^/\s@]+@/gi, "$1***@").replace(/\bdtr_[A-Za-z0-9_-]+/g, "dtr_***").replace(/\b(gh[pousr]_[A-Za-z0-9]{10,})/g, "***");
672
+ async function gitOk2(cwd, args) {
673
+ const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs: 5 * 6e4 });
674
+ return res.code === 0;
631
675
  }
632
-
633
- // src/git.ts
634
- var GitError = class extends Error {
635
- constructor(args, result) {
636
- super(gitErrorMessage(args, result));
637
- this.args = args;
638
- this.result = result;
639
- this.name = "GitError";
640
- }
641
- };
642
- function gitErrorMessage(args, result) {
643
- const detail = (result.stderr || result.stdout).trim().split("\n").filter(Boolean).slice(-3).join(" ");
644
- return scrubSecrets(`git ${args[0]} failed${detail ? `: ${detail}` : ""}`).slice(0, 500);
676
+ async function revParse(cwd, ref) {
677
+ const res = await exec("git", ["rev-parse", "--verify", "-q", `${ref}^{commit}`], {
678
+ cwd,
679
+ env: gitEnv(),
680
+ timeoutMs: 6e4
681
+ });
682
+ return res.code === 0 ? res.stdout.trim() : null;
645
683
  }
646
- var gitEnv = () => ({
647
- ...process.env,
648
- GIT_TERMINAL_PROMPT: "0",
649
- GCM_INTERACTIVE: "never",
650
- GIT_ASKPASS: process.env.GIT_ASKPASS ?? ""
651
- });
652
- async function git(cwd, args, timeoutMs = 10 * 6e4) {
653
- const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs });
684
+ async function gitWithIndex(cwd, index, args) {
685
+ const res = await exec("git", args, {
686
+ cwd,
687
+ env: { ...gitEnv(), GIT_INDEX_FILE: index },
688
+ timeoutMs: 6e4
689
+ });
654
690
  if (res.code !== 0) throw new GitError(args, res);
655
691
  return res.stdout.trim();
656
692
  }
657
- async function gitOk(cwd, args) {
658
- const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs: 6e4 });
659
- return res.code === 0;
693
+ async function identity(cwd) {
694
+ const res = await exec("git", ["config", "user.email"], {
695
+ cwd,
696
+ env: gitEnv(),
697
+ timeoutMs: 6e4
698
+ });
699
+ return res.code === 0 && res.stdout.trim() ? [] : ["-c", "user.name=Discovery Tree runner", "-c", "user.email=dt-runner@users.noreply.local"];
660
700
  }
661
- var REPOSITORY_HOST = "github.com";
662
- function parseRepoUrl(url) {
701
+
702
+ // src/claude.ts
703
+ async function findClaude(env = process.env) {
704
+ const override = env.DT_RUNNER_CLAUDE_BIN?.trim();
705
+ if (override) return which(override, env);
706
+ return which("claude", env);
707
+ }
708
+ async function claudeVersion(bin) {
663
709
  try {
664
- const u = new URL(url);
665
- if (u.protocol !== "https:" || u.hostname.toLowerCase() !== REPOSITORY_HOST) return null;
666
- if (u.port || u.username || u.password || u.search || u.hash) return null;
667
- const parts = u.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "").split("/");
668
- if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
669
- if (!/^[\w.-]+$/.test(parts[0]) || !/^[\w.-]+$/.test(parts[1])) return null;
670
- if (parts.some((p) => p === "." || p === "..")) return null;
671
- return { host: REPOSITORY_HOST, owner: parts[0], repo: parts[1] };
710
+ const res = await exec(bin, ["--version"], { timeoutMs: 15e3 });
711
+ if (res.code !== 0) return null;
712
+ return res.stdout.trim().split("\n")[0] || null;
672
713
  } catch {
673
714
  return null;
674
715
  }
675
716
  }
676
- function repositoryUrlError(url) {
677
- return `Repository URL ${scrubSecrets(url).slice(0, 200)} is not a https://github.com/<owner>/<repo> URL; this runner only works on GitHub repositories.`;
678
- }
679
- function cloneUrl(ref, protocol) {
680
- return protocol === "ssh" ? `git@${ref.host}:${ref.owner}/${ref.repo}.git` : `https://${ref.host}/${ref.owner}/${ref.repo}.git`;
717
+ async function claudeAuthStatus(bin) {
718
+ try {
719
+ const res = await exec(bin, ["auth", "status", "--json"], { timeoutMs: 2e4 });
720
+ const parsed = JSON.parse(res.stdout);
721
+ if (typeof parsed.loggedIn !== "boolean") return { loggedIn: null, authMethod: null };
722
+ return {
723
+ loggedIn: parsed.loggedIn,
724
+ authMethod: typeof parsed.authMethod === "string" ? parsed.authMethod : null
725
+ };
726
+ } catch {
727
+ return { loggedIn: null, authMethod: null };
728
+ }
729
+ }
730
+ async function claudeFeatures(bin) {
731
+ try {
732
+ const res = await exec(bin, ["--help"], { timeoutMs: 15e3 });
733
+ return {
734
+ permissionPrompts: res.stdout.includes("--permission-prompts"),
735
+ settingSources: res.stdout.includes("--setting-sources")
736
+ };
737
+ } catch {
738
+ return { permissionPrompts: false, settingSources: false };
739
+ }
740
+ }
741
+ async function probeAgent(env = process.env) {
742
+ const bin = await findClaude(env);
743
+ if (!bin) {
744
+ return {
745
+ claudeVersion: null,
746
+ claudeReady: false,
747
+ claudeProblem: "Claude Code is not installed on this computer (no `claude` on PATH)."
748
+ };
749
+ }
750
+ const version = await claudeVersion(bin);
751
+ if (!version) {
752
+ return {
753
+ claudeVersion: null,
754
+ claudeReady: false,
755
+ claudeProblem: "`claude --version` failed; reinstall or update Claude Code."
756
+ };
757
+ }
758
+ const auth = await claudeAuthStatus(bin);
759
+ if (auth.loggedIn === false) {
760
+ return {
761
+ claudeVersion: version,
762
+ claudeReady: false,
763
+ claudeProblem: "Claude Code is not signed in. Run `claude` once on this computer and sign in."
764
+ };
765
+ }
766
+ return { claudeVersion: version, claudeReady: auth.loggedIn, claudeProblem: null };
767
+ }
768
+ var SIGN_IN_FAILURE = /failed to authenticate|oauth (session|token)\b[^.]*\bexpired|invalid (x-)?api[ -]key|authentication_error|please run \/login/i;
769
+ function looksLikeSignInFailure(text) {
770
+ return !!text && SIGN_IN_FAILURE.test(text);
771
+ }
772
+ function turnFailedToSignIn(turn) {
773
+ return (turn.subtype ?? "success") === "success" && looksLikeSignInFailure(turn.text);
774
+ }
775
+ function signInFix(env = process.env) {
776
+ if (env.ANTHROPIC_API_KEY) {
777
+ return "`ANTHROPIC_API_KEY` is set where the runner runs, so Claude Code signs in with that key instead of your Claude subscription. Unset it (or replace it with a working key) and restart the runner.";
778
+ }
779
+ return 'On the runner\u2019s computer, run `claude`, type `/login` and sign in again, and check that `claude -p "say ok"` answers.';
780
+ }
781
+ var MODEL_NAME = /^[A-Za-z0-9][\w.:@/[\]-]{0,199}$/;
782
+ function isValidModelName(model) {
783
+ return MODEL_NAME.test(model);
784
+ }
785
+ function assertValidModel(model) {
786
+ if (model && !isValidModelName(model)) {
787
+ throw new Error(
788
+ `The model "${model.slice(0, 80)}" is not a valid Claude Code model name; the runner refused to start it.`
789
+ );
790
+ }
791
+ }
792
+ function claudeArgs(launch) {
793
+ const args = [
794
+ "-p",
795
+ "--input-format",
796
+ "stream-json",
797
+ "--output-format",
798
+ "stream-json",
799
+ "--verbose",
800
+ "--include-partial-messages"
801
+ ];
802
+ if (launch.permissionMode === "bypassPermissions") {
803
+ args.push("--dangerously-skip-permissions");
804
+ } else {
805
+ args.push("--permission-mode", launch.permissionMode);
806
+ }
807
+ if (launch.features.permissionPrompts) args.push("--permission-prompts", "none");
808
+ if (launch.features.settingSources && !launch.loadProjectSettings) {
809
+ args.push("--setting-sources", "user");
810
+ }
811
+ if (launch.model) {
812
+ assertValidModel(launch.model);
813
+ args.push(`--model=${launch.model}`);
814
+ }
815
+ if (launch.resume) args.push("--resume", launch.resume);
816
+ if (launch.appendSystemPrompt) args.push("--append-system-prompt", launch.appendSystemPrompt);
817
+ if (launch.disallowedTools?.length) args.push("--disallowedTools", ...launch.disallowedTools);
818
+ if (launch.allowedTools.length) args.push("--allowedTools", ...launch.allowedTools);
819
+ return args;
681
820
  }
682
- var UNSAFE_REF = /[\s~^:?*[\\\x00-\x1f]|\.\.|@\{|\/\/|\.lock$|\/$/;
683
- function assertSafeRef(name, what) {
684
- if (!name || name.startsWith("-") || UNSAFE_REF.test(name)) {
685
- throw new Error(`${what} "${name}" is not a valid branch name.`);
821
+ function runnerSystemPrompt(input) {
822
+ if (!input.workBranch) {
823
+ return [
824
+ "You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
825
+ "Your working directory is a scratch directory created for this task; it is not a git repository."
826
+ ].join(" ");
686
827
  }
828
+ const evidence = join4(input.cwd, EVIDENCE_DIR);
829
+ return [
830
+ "You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
831
+ `Your working directory is a git worktree managed by the runner, on branch \`${input.workBranch}\``,
832
+ input.baseRef ? `(created from \`${input.baseRef}\`).` : ".",
833
+ "Commit your work to this branch as you go, with clear, descriptive commit messages.",
834
+ "Do not push, do not switch, create or delete branches, and do not rewrite commits that may",
835
+ "already be pushed: the runner commits anything left over and pushes this branch for you",
836
+ "at the end of every turn.",
837
+ "Do not open a pull request either: Discovery Tree opens it from this branch when a turn",
838
+ "ends, with that turn\u2019s final message as its description, and later turns add to it.",
839
+ "Before then (your first turn) there is none; say so rather than trying to open one.",
840
+ `To read it, use \`gh pr view ${input.workBranch}\` (\`--comments\` for the conversation),`,
841
+ "`gh pr diff`, `gh pr checks`, and `gh run view` for a check run\u2019s logs. Only `gh` commands",
842
+ "that read are allowed; ones that change GitHub (comment, edit, merge, `gh api`) are denied.",
843
+ "For screenshots of a user-visible change, save the images (PNG, JPEG, GIF or WebP) in",
844
+ `\`${evidence}/\` (the root of this worktree, also after a \`cd\`), named for what they show`,
845
+ `(\`settings-dark.png\`), for example with \`npx playwright screenshot <url> "${evidence}/<name>.png"\`.`,
846
+ "Do not commit them, upload them or link them yourself: at the end of the turn the runner",
847
+ "publishes them on a branch of their own and adds them, linked, under your final message,",
848
+ "so they appear in the pull request description. The folder is ignored by git.",
849
+ "To run a dev server, start it with the Bash tool\u2019s background option (not `&` or",
850
+ "`nohup`), read its output file for the port it is listening on, check it with one command",
851
+ "such as `node -e \"fetch('http://localhost:<port>/', { signal: AbortSignal.timeout(60000) })",
852
+ '.then(r => console.log(r.status), e => console.log(e.cause?.code ?? e.message))"`',
853
+ "(the first request may wait while the page compiles; `curl` is denied; no loops), and stop",
854
+ "it with TaskStop before you finish.",
855
+ "Other runs may share this computer:",
856
+ "if the port is taken, start yours on another port; never stop a process you did not start.",
857
+ "Do not start databases, containers or other services yourself, directly or through a",
858
+ "package script, unless the task asks you to; if one the server needs is not running, say so."
859
+ ].join(" ");
687
860
  }
688
- var repoLocks = /* @__PURE__ */ new Map();
689
- function withRepoLock(dir, fn) {
690
- const prev = repoLocks.get(dir) ?? Promise.resolve();
691
- const next = prev.catch(() => void 0).then(fn);
692
- repoLocks.set(dir, next);
693
- const release = () => {
694
- if (repoLocks.get(dir) === next) repoLocks.delete(dir);
695
- };
696
- next.then(release, release);
697
- return next;
861
+
862
+ // src/config.ts
863
+ import { chmod, mkdir as mkdir3, readFile as readFile2, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
864
+ import { homedir } from "node:os";
865
+ import { dirname as dirname2, join as join5 } from "node:path";
866
+
867
+ // src/invocation.ts
868
+ var RUNNER_PACKAGE = "@discovery-tree/runner";
869
+ function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
870
+ if (env.npm_command === "exec") return true;
871
+ return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
698
872
  }
699
- async function exists(p) {
700
- try {
701
- await stat(p);
702
- return true;
703
- } catch {
704
- return false;
705
- }
873
+ function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
874
+ return viaNpx ? `npx ${RUNNER_PACKAGE}@latest ${subcommand}` : `dt-runner ${subcommand}`;
706
875
  }
707
- async function prepareWorktree(input) {
708
- const ref = parseRepoUrl(input.url);
709
- if (!ref) throw new Error(repositoryUrlError(input.url));
710
- assertSafeRef(input.workBranch, "Work branch");
711
- if (input.baseRef) assertSafeRef(input.baseRef, "Base branch");
712
- const repoDir = join3(input.reposDir, ref.owner, ref.repo);
713
- const worktree = join3(input.worktreesDir, input.worktreeKey || input.sessionId);
714
- return withRepoLock(repoDir, async () => {
715
- if (!await exists(join3(repoDir, ".git"))) {
716
- await mkdir2(dirname2(repoDir), { recursive: true });
717
- await rm2(repoDir, { recursive: true, force: true });
718
- await git(dirname2(repoDir), [
719
- "clone",
720
- "--no-checkout",
721
- cloneUrl(ref, input.protocol),
722
- repoDir
723
- ]);
724
- } else {
725
- const wanted = cloneUrl(ref, input.protocol);
726
- const current = await exec("git", ["config", "--get", "remote.origin.url"], {
727
- cwd: repoDir,
728
- env: gitEnv()
729
- });
730
- if (current.stdout.trim() !== wanted) {
731
- await git(repoDir, ["remote", "set-url", "origin", wanted]);
732
- }
733
- await git(repoDir, ["fetch", "--prune", "origin"]);
734
- }
735
- const baseRef = input.baseRef ?? await defaultBranch(repoDir);
736
- let start2 = `origin/${baseRef}`;
737
- if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${start2}^{commit}`])) {
738
- if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`])) {
739
- throw new Error(`Base branch ${baseRef} was not found on origin.`);
740
- }
741
- start2 = baseRef;
742
- }
743
- let baseSha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
744
- let checkout = start2;
745
- let continuedFrom;
746
- let setAside;
747
- const remoteWork = `refs/remotes/origin/${input.workBranch}`;
748
- if (input.continueBranch && await exists(worktree) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
749
- cwd: worktree,
750
- env: gitEnv(),
751
- timeoutMs: 6e4
752
- }).then((r) => r.code === 0 && r.stdout.trim() === input.workBranch) && // Only when it already has everything pushed to the work branch since: one that fell
753
- // behind (the run went on elsewhere) would have the agent work on stale code.
754
- (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${remoteWork}^{commit}`]) || await exec("git", ["merge-base", "--is-ancestor", remoteWork, "HEAD"], {
755
- cwd: worktree,
756
- env: gitEnv(),
757
- timeoutMs: 6e4
758
- }).then((r) => r.code === 0))) {
759
- const forkPoint = await exec("git", ["merge-base", "HEAD", start2], {
760
- cwd: worktree,
761
- env: gitEnv(),
762
- timeoutMs: 6e4
763
- });
764
- if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
765
- return { repoDir, worktree, baseRef, baseSha, continuedFrom: "worktree" };
766
- }
767
- if (input.continueBranch) {
768
- const remote = `refs/remotes/origin/${input.workBranch}`;
769
- const local = `refs/heads/${input.workBranch}`;
770
- const hasRemote = await gitOk(repoDir, [
771
- "rev-parse",
772
- "--verify",
773
- "--quiet",
774
- `${remote}^{commit}`
775
- ]);
776
- const hasLocal = await gitOk(repoDir, [
777
- "rev-parse",
778
- "--verify",
779
- "--quiet",
780
- `${local}^{commit}`
781
- ]);
782
- const localAhead = hasLocal && (!hasRemote || await gitOk(repoDir, ["merge-base", "--is-ancestor", remote, local]));
783
- if (localAhead) {
784
- checkout = local;
785
- continuedFrom = "local";
786
- } else if (hasRemote) {
787
- checkout = remote;
788
- continuedFrom = "remote";
789
- } else {
790
- continuedFrom = "base";
791
- }
792
- if (continuedFrom !== "base") {
793
- const forkPoint = await exec("git", ["merge-base", checkout, start2], {
794
- cwd: repoDir,
795
- env: gitEnv(),
796
- timeoutMs: 6e4
797
- });
798
- if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
799
- checkout = await git(repoDir, ["rev-parse", `${checkout}^{commit}`]);
800
- }
801
- }
802
- if (input.continueBranch && await exists(worktree)) {
803
- const dirty = await exec("git", ["status", "--porcelain"], {
804
- cwd: worktree,
805
- env: gitEnv(),
806
- timeoutMs: 6e4
807
- });
808
- if (dirty.code === 0 && dirty.stdout.trim()) {
809
- const aside = `${worktree}.kept-${Date.now()}`;
810
- if (await gitOk(repoDir, ["worktree", "move", worktree, aside])) setAside = aside;
811
- }
812
- }
813
- if (await exists(worktree)) {
814
- await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
815
- await rm2(worktree, { recursive: true, force: true });
816
- }
817
- await gitOk(repoDir, ["worktree", "prune"]);
818
- await mkdir2(input.worktreesDir, { recursive: true });
819
- await git(repoDir, [
820
- "worktree",
821
- "add",
822
- "--no-track",
823
- "-B",
824
- input.workBranch,
825
- worktree,
826
- checkout
827
- ]);
876
+
877
+ // src/config.ts
878
+ function runnerPaths(env = process.env) {
879
+ const home = homedir();
880
+ if (process.platform === "win32") {
881
+ const roaming = env.APPDATA || join5(home, "AppData", "Roaming");
882
+ const local = env.LOCALAPPDATA || join5(home, "AppData", "Local");
828
883
  return {
829
- repoDir,
830
- worktree,
831
- baseRef,
832
- baseSha,
833
- ...continuedFrom ? { continuedFrom } : {},
834
- ...setAside ? { setAside } : {}
884
+ configFile: join5(roaming, "discovery-tree", "runner.json"),
885
+ dataDir: join5(local, "discovery-tree", "runner"),
886
+ stateDir: join5(local, "discovery-tree", "runner", "state")
835
887
  };
836
- });
837
- }
838
- async function defaultBranch(repoDir) {
839
- const read = async () => {
840
- const res = await exec("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
841
- cwd: repoDir,
842
- env: gitEnv()
843
- });
844
- return res.code === 0 ? res.stdout.trim().replace(/^origin\//, "") : null;
888
+ }
889
+ const config = env.XDG_CONFIG_HOME || join5(home, ".config");
890
+ const data = env.XDG_DATA_HOME || join5(home, ".local", "share");
891
+ const state = env.XDG_STATE_HOME || join5(home, ".local", "state");
892
+ return {
893
+ configFile: join5(config, "discovery-tree", "runner.json"),
894
+ dataDir: join5(data, "discovery-tree", "runner"),
895
+ stateDir: join5(state, "discovery-tree", "runner")
845
896
  };
846
- const known = await read();
847
- if (known) return known;
848
- await gitOk(repoDir, ["remote", "set-head", "origin", "--auto"]);
849
- return await read() ?? "main";
850
897
  }
851
- async function commitAndPush(input) {
852
- const { worktree } = input;
853
- let committed = false;
898
+ var PERMISSION_MODES = [
899
+ "acceptEdits",
900
+ "auto",
901
+ "default",
902
+ "manual",
903
+ "dontAsk",
904
+ "plan",
905
+ "bypassPermissions"
906
+ ];
907
+ var DEFAULT_ALLOWED_TOOLS = [
908
+ "Read",
909
+ "Edit",
910
+ "MultiEdit",
911
+ "Write",
912
+ "Glob",
913
+ "Grep",
914
+ "LS",
915
+ "NotebookEdit",
916
+ "TodoWrite",
917
+ "Task",
918
+ // Stops a command started with the Bash tool's background option (a dev server); its
919
+ // output is a file the agent reads with Read.
920
+ "TaskStop",
921
+ "Bash(git status *)",
922
+ "Bash(git diff *)",
923
+ "Bash(git log *)",
924
+ "Bash(git show *)",
925
+ "Bash(git add *)",
926
+ "Bash(git commit *)",
927
+ "Bash(git restore *)",
928
+ "Bash(git rm *)",
929
+ "Bash(git mv *)",
930
+ "Bash(git stash *)",
931
+ "Bash(git blame *)",
932
+ "Bash(git grep *)",
933
+ "Bash(gh pr view *)",
934
+ "Bash(gh pr diff *)",
935
+ "Bash(gh pr checks *)",
936
+ "Bash(gh pr list *)",
937
+ "Bash(gh pr status *)",
938
+ "Bash(gh run view *)",
939
+ "Bash(gh run list *)",
940
+ "Bash(gh issue view *)",
941
+ "Bash(gh issue list *)",
942
+ "Bash(gh repo view *)",
943
+ "Bash(npm *)",
944
+ "Bash(npx *)",
945
+ "Bash(pnpm *)",
946
+ "Bash(yarn *)",
947
+ "Bash(node *)",
948
+ "Bash(tsc *)",
949
+ "Bash(python *)",
950
+ "Bash(python3 *)",
951
+ "Bash(pip *)",
952
+ "Bash(pytest *)",
953
+ "Bash(make *)",
954
+ "Bash(cargo *)",
955
+ "Bash(go *)",
956
+ "Bash(ls *)",
957
+ "Bash(cat *)",
958
+ "Bash(head *)",
959
+ "Bash(tail *)",
960
+ "Bash(wc *)",
961
+ "Bash(grep *)",
962
+ "Bash(rg *)",
963
+ "Bash(echo *)",
964
+ "Bash(pwd)",
965
+ "Bash(mkdir *)",
966
+ "Bash(touch *)",
967
+ "Bash(diff *)",
968
+ "Bash(sort *)",
969
+ "Bash(uniq *)",
970
+ "Bash(which *)",
971
+ "Bash(true)",
972
+ // Starting a dev server and checking it: `cd web && npm run dev`, waiting for it, seeing
973
+ // what holds a port. Not `kill`: on the person's own computer the process on a busy port
974
+ // may be theirs (the agent stops its own servers with TaskStop and uses another port).
975
+ "Bash(cd *)",
976
+ "Bash(sleep *)",
977
+ "Bash(lsof *)"
978
+ ];
979
+ var PROTECTED_PATHS = [
980
+ "~/.ssh/**",
981
+ "~/.aws/**",
982
+ "~/.config/gcloud/**",
983
+ "~/.azure/**",
984
+ "~/.gnupg/**",
985
+ "~/.netrc",
986
+ "~/.git-credentials",
987
+ "~/.config/gh/**",
988
+ "~/.docker/config.json",
989
+ "~/.kube/**",
990
+ "~/.npmrc",
991
+ "~/.pypirc",
992
+ // The runner's own token.
993
+ "~/.config/discovery-tree/**",
994
+ // Claude Code's sign-in and account file.
995
+ "~/.claude/.credentials.json",
996
+ "~/.claude.json"
997
+ ];
998
+ var PROTECTED_FROM_EDIT = [
999
+ "~/.claude/**",
1000
+ // Shell startup files and git config: an edit there runs, or changes what runs, in every
1001
+ // later shell or git command the person uses outside the agent.
1002
+ "~/.bashrc",
1003
+ "~/.bash_profile",
1004
+ "~/.profile",
1005
+ "~/.zshrc",
1006
+ "~/.zprofile",
1007
+ "~/.zshenv",
1008
+ "~/.config/fish/**",
1009
+ "~/.gitconfig",
1010
+ "~/.config/git/**"
1011
+ ];
1012
+ var DEFAULT_DISALLOWED_TOOLS = [
1013
+ ...PROTECTED_PATHS.map((p) => `Read(${p})`),
1014
+ ...[...PROTECTED_PATHS, ...PROTECTED_FROM_EDIT].map((p) => `Edit(${p})`)
1015
+ ];
1016
+ function configDirRules(configFile, platform = process.platform) {
1017
+ if (platform === "win32") return [];
1018
+ const dir = dirname2(configFile);
1019
+ if (!dir.startsWith("/")) return [];
1020
+ return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
1021
+ }
1022
+ var DEFAULT_SERVER_URL = "https://discovery-tree-backend.onrender.com";
1023
+ var DEFAULT_MAX_SESSIONS = 2;
1024
+ var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
1025
+ async function readConfigFile(file) {
1026
+ let raw;
854
1027
  try {
855
- const dirty = (await git(worktree, ["status", "--porcelain"])).length > 0;
856
- if (dirty) {
857
- await git(worktree, ["add", "-A"]);
858
- const identity = await gitOk(worktree, ["config", "user.email"]) ? [] : [
859
- "-c",
860
- "user.name=Discovery Tree runner",
861
- "-c",
862
- "user.email=dt-runner@users.noreply.local"
863
- ];
864
- await git(worktree, [...identity, "commit", "--no-verify", "-q", "-m", input.message]);
865
- committed = true;
866
- }
1028
+ raw = await readFile2(file, "utf8");
867
1029
  } catch (err) {
868
- return {
869
- committed,
870
- pushed: false,
871
- error: errorText(err, "Committing the work failed"),
872
- failedAt: "commit"
873
- };
1030
+ if (err.code === "ENOENT") return null;
1031
+ throw err;
874
1032
  }
875
1033
  try {
876
- const ahead = Number(await git(worktree, ["rev-list", "--count", `${input.baseSha}..HEAD`]));
877
- if (!ahead) return { committed, pushed: false, error: null };
878
- await git(worktree, ["push", "--quiet", "-u", "origin", `HEAD:refs/heads/${input.workBranch}`]);
879
- return { committed, pushed: true, error: null };
1034
+ return JSON.parse(raw);
1035
+ } catch {
1036
+ throw new Error(
1037
+ `${file} is not valid JSON; fix it or run \`${runnerCommand("logout")}\` to start over.`
1038
+ );
1039
+ }
1040
+ }
1041
+ async function writeConfigFile(file, config) {
1042
+ await mkdir3(dirname2(file), { recursive: true, mode: 448 });
1043
+ await writeFile2(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
1044
+ await chmod(file, 384).catch(() => void 0);
1045
+ }
1046
+ async function deleteConfigFile(file) {
1047
+ try {
1048
+ await rm3(file);
1049
+ return true;
880
1050
  } catch (err) {
881
- return {
882
- committed,
883
- pushed: false,
884
- error: errorText(err, "Pushing the work branch failed"),
885
- failedAt: "push"
886
- };
1051
+ if (err.code === "ENOENT") return false;
1052
+ throw err;
887
1053
  }
888
1054
  }
889
- async function removeWorktree(repoDir, worktree) {
890
- if (repoDir && await exists(repoDir)) {
891
- await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
1055
+ function normalizeServerUrl(url) {
1056
+ const trimmed = url.trim().replace(/\/+$/, "");
1057
+ return trimmed.replace(/\/api(\/health)?$/, "");
1058
+ }
1059
+ var MAX_SESSIONS_LIMIT = 64;
1060
+ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPaths(env)) {
1061
+ const mode = file?.permissionMode ?? "acceptEdits";
1062
+ if (!PERMISSION_MODES.includes(mode)) {
1063
+ throw new Error(
1064
+ `permissionMode "${mode}" in ${paths.configFile} is not one of ${PERMISSION_MODES.join(", ")}.`
1065
+ );
892
1066
  }
893
- await rm2(worktree, { recursive: true, force: true });
894
- if (repoDir && await exists(repoDir)) await gitOk(repoDir, ["worktree", "prune"]);
1067
+ const maxSessions = overrides.maxSessions ?? file?.maxSessions ?? DEFAULT_MAX_SESSIONS;
1068
+ if (!Number.isInteger(maxSessions) || maxSessions < 1 || maxSessions > MAX_SESSIONS_LIMIT) {
1069
+ throw new Error(
1070
+ `maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
1071
+ );
1072
+ }
1073
+ const allowed = [
1074
+ ...file?.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
1075
+ ...file?.extraAllowedTools ?? []
1076
+ ];
1077
+ const disallowed = [
1078
+ ...file?.disallowedTools ?? [
1079
+ ...DEFAULT_DISALLOWED_TOOLS,
1080
+ ...configDirRules(paths.configFile)
1081
+ ],
1082
+ ...file?.extraDisallowedTools ?? []
1083
+ ];
1084
+ return {
1085
+ server: normalizeServerUrl(env.DT_SERVER_URL || file?.server || DEFAULT_SERVER_URL),
1086
+ runnerId: file?.runnerId ?? null,
1087
+ token: env.DT_RUNNER_TOKEN || file?.token || null,
1088
+ name: file?.name ?? null,
1089
+ maxSessions,
1090
+ reposDir: overrides.reposDir ?? file?.reposDir ?? join5(paths.dataDir, "repos"),
1091
+ worktreesDir: file?.worktreesDir ?? join5(paths.dataDir, "worktrees"),
1092
+ permissionMode: mode,
1093
+ allowedTools: [...new Set(allowed)],
1094
+ disallowedTools: [...new Set(disallowed)],
1095
+ loadProjectSettings: file?.loadProjectSettings === true,
1096
+ gitProtocol: file?.gitProtocol === "ssh" ? "ssh" : "https",
1097
+ idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
1098
+ stateDir: paths.stateDir,
1099
+ configFile: paths.configFile
1100
+ };
895
1101
  }
896
- function errorText(err, prefix) {
897
- const msg = err instanceof Error ? err.message : String(err);
898
- return scrubSecrets(`${prefix}: ${msg}`).slice(0, 600);
1102
+
1103
+ // src/backoff.ts
1104
+ function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
1105
+ const ceiling = Math.min(maxMs, baseMs * 2 ** Math.min(attempt, 20));
1106
+ return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
1107
+ }
1108
+ function sleep(ms, signal) {
1109
+ return new Promise((resolve) => {
1110
+ if (signal?.aborted) return resolve();
1111
+ const timer = setTimeout(done, ms);
1112
+ function done() {
1113
+ clearTimeout(timer);
1114
+ signal?.removeEventListener("abort", done);
1115
+ resolve();
1116
+ }
1117
+ signal?.addEventListener("abort", done, { once: true });
1118
+ });
899
1119
  }
900
1120
 
1121
+ // src/session-manager.ts
1122
+ import { mkdir as mkdir6, rm as rm5 } from "node:fs/promises";
1123
+
901
1124
  // src/fsutil.ts
902
- import { mkdir as mkdir3, readFile as readFile2, rename, writeFile as writeFile2 } from "node:fs/promises";
1125
+ import { mkdir as mkdir4, readFile as readFile3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
903
1126
  import { dirname as dirname3 } from "node:path";
904
1127
  async function writeJsonAtomic(file, value) {
905
- await mkdir3(dirname3(file), { recursive: true });
1128
+ await mkdir4(dirname3(file), { recursive: true });
906
1129
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
907
- await writeFile2(tmp, JSON.stringify(value), { mode: 384 });
908
- await rename(tmp, file);
1130
+ await writeFile3(tmp, JSON.stringify(value), { mode: 384 });
1131
+ await rename2(tmp, file);
909
1132
  }
910
1133
  async function readJson(file) {
911
1134
  try {
912
- return JSON.parse(await readFile2(file, "utf8"));
1135
+ return JSON.parse(await readFile3(file, "utf8"));
913
1136
  } catch (err) {
914
1137
  if (err.code === "ENOENT") return null;
915
1138
  if (err instanceof SyntaxError) return null;
@@ -1148,44 +1371,108 @@ function takeBatch(pending) {
1148
1371
  }
1149
1372
 
1150
1373
  // src/session.ts
1151
- import { spawn as spawn2 } from "node:child_process";
1374
+ import { spawn as spawn3 } from "node:child_process";
1375
+ import { basename, dirname as dirname4 } from "node:path";
1152
1376
  import { createInterface } from "node:readline";
1153
1377
 
1378
+ // src/process-tree.ts
1379
+ import { spawn as spawn2 } from "node:child_process";
1380
+ var OWN_PROCESS_GROUP = process.platform !== "win32";
1381
+ var liveGroups = /* @__PURE__ */ new Set();
1382
+ var exitHookInstalled = false;
1383
+ function trackGroup(child) {
1384
+ if (!OWN_PROCESS_GROUP || !child.pid) return;
1385
+ liveGroups.add(child.pid);
1386
+ if (!exitHookInstalled) {
1387
+ exitHookInstalled = true;
1388
+ process.once("exit", () => {
1389
+ for (const pgid of liveGroups) signalGroup(pgid, "SIGKILL");
1390
+ });
1391
+ }
1392
+ }
1393
+ function signalTree(child, signal) {
1394
+ if (!child.pid) return;
1395
+ if (OWN_PROCESS_GROUP) {
1396
+ if (!signalGroup(child.pid, signal)) child.kill(signal);
1397
+ return;
1398
+ }
1399
+ if (signal === "SIGKILL") {
1400
+ const tk = spawn2("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
1401
+ stdio: "ignore",
1402
+ windowsHide: true
1403
+ });
1404
+ let fellBack = false;
1405
+ const fallBack = () => {
1406
+ if (fellBack) return;
1407
+ fellBack = true;
1408
+ child.kill(signal);
1409
+ };
1410
+ tk.on("error", fallBack);
1411
+ tk.on("exit", (code) => {
1412
+ if (code !== 0) fallBack();
1413
+ });
1414
+ return;
1415
+ }
1416
+ child.kill(signal);
1417
+ }
1418
+ async function reapGroup(pgid, graceMs = 2e3) {
1419
+ if (!OWN_PROCESS_GROUP || !pgid) return;
1420
+ try {
1421
+ if (!signalGroup(pgid, "SIGTERM")) return;
1422
+ const deadline = Date.now() + graceMs;
1423
+ while (Date.now() < deadline) {
1424
+ await new Promise((r) => setTimeout(r, 50));
1425
+ if (!signalGroup(pgid, 0)) return;
1426
+ }
1427
+ signalGroup(pgid, "SIGKILL");
1428
+ } finally {
1429
+ liveGroups.delete(pgid);
1430
+ }
1431
+ }
1432
+ function signalGroup(pgid, signal) {
1433
+ try {
1434
+ process.kill(-pgid, signal);
1435
+ return true;
1436
+ } catch {
1437
+ return false;
1438
+ }
1439
+ }
1440
+
1154
1441
  // src/session-store.ts
1155
- import { mkdir as mkdir4, readdir, rm as rm3 } from "node:fs/promises";
1156
- import { join as join4 } from "node:path";
1442
+ import { mkdir as mkdir5, readdir as readdir2, rm as rm4 } from "node:fs/promises";
1443
+ import { join as join6 } from "node:path";
1157
1444
  var HANDLED_COMMAND_IDS_KEPT = 100;
1158
1445
  var SessionStore = class {
1159
1446
  constructor(stateDir) {
1160
1447
  this.stateDir = stateDir;
1161
1448
  }
1162
1449
  dir(sessionId) {
1163
- return join4(this.stateDir, "sessions", sessionId);
1450
+ return join6(this.stateDir, "sessions", sessionId);
1164
1451
  }
1165
1452
  outboxFile(sessionId) {
1166
- return join4(this.dir(sessionId), "outbox.json");
1453
+ return join6(this.dir(sessionId), "outbox.json");
1167
1454
  }
1168
1455
  async save(record) {
1169
1456
  record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1170
- await writeJsonAtomic(join4(this.dir(record.sessionId), "session.json"), record);
1457
+ await writeJsonAtomic(join6(this.dir(record.sessionId), "session.json"), record);
1171
1458
  }
1172
1459
  async list() {
1173
- const root = join4(this.stateDir, "sessions");
1174
- await mkdir4(root, { recursive: true });
1460
+ const root = join6(this.stateDir, "sessions");
1461
+ await mkdir5(root, { recursive: true });
1175
1462
  const out = [];
1176
- for (const entry of await readdir(root, { withFileTypes: true })) {
1463
+ for (const entry of await readdir2(root, { withFileTypes: true })) {
1177
1464
  if (!entry.isDirectory()) continue;
1178
- const rec = await readJson(join4(root, entry.name, "session.json"));
1465
+ const rec = await readJson(join6(root, entry.name, "session.json"));
1179
1466
  if (rec?.sessionId === entry.name) out.push(rec);
1180
1467
  }
1181
1468
  return out;
1182
1469
  }
1183
1470
  async remove(sessionId) {
1184
- await rm3(this.dir(sessionId), { recursive: true, force: true });
1471
+ await rm4(this.dir(sessionId), { recursive: true, force: true });
1185
1472
  }
1186
1473
  /** Scratch working directory for a session without a repository. */
1187
1474
  scratchDir(sessionId) {
1188
- return join4(this.stateDir, "scratch", sessionId);
1475
+ return join6(this.stateDir, "scratch", sessionId);
1189
1476
  }
1190
1477
  };
1191
1478
  function assertSafeSessionId(id) {
@@ -1433,6 +1720,10 @@ var AgentSession = class {
1433
1720
  */
1434
1721
  resumeRetry = null;
1435
1722
  exitWaiters = [];
1723
+ /** Settles once the current process has exited and what it left in its group is gone. */
1724
+ groupReaped = Promise.resolve();
1725
+ /** How long what is left in the group gets after SIGTERM: a stop's grace, or the default. */
1726
+ reapGraceMs;
1436
1727
  lastActivity = Date.now();
1437
1728
  get sessionId() {
1438
1729
  return this.record.sessionId;
@@ -1505,11 +1796,17 @@ var AgentSession = class {
1505
1796
  }, this.deps.interruptGraceMs ?? 5e3);
1506
1797
  return true;
1507
1798
  }
1508
- /** Ends the process (closing stdin first, so Claude Code saves its session and exits). */
1799
+ /**
1800
+ * Ends the process (closing stdin first, so Claude Code saves its session and exits), and
1801
+ * with it everything it started: the background commands still in its process group are
1802
+ * ended once it has exited, and SIGTERM and SIGKILL go to the whole group.
1803
+ */
1509
1804
  async stop(reason, graceMs = 5e3) {
1510
1805
  const child = this.child;
1511
1806
  if (!child) return;
1807
+ const reaped = this.groupReaped;
1512
1808
  this.stopping = reason;
1809
+ this.reapGraceMs = graceMs;
1513
1810
  const exited = new Promise((resolve) => this.exitWaiters.push(resolve));
1514
1811
  child.stdin.end();
1515
1812
  const timedOut = await Promise.race([
@@ -1517,11 +1814,12 @@ var AgentSession = class {
1517
1814
  delay(graceMs).then(() => true)
1518
1815
  ]);
1519
1816
  if (timedOut && this.child === child) {
1520
- child.kill("SIGTERM");
1817
+ signalTree(child, "SIGTERM");
1521
1818
  const again = await Promise.race([exited.then(() => false), delay(graceMs).then(() => true)]);
1522
- if (again && this.child === child) child.kill("SIGKILL");
1819
+ if (again && this.child === child) signalTree(child, "SIGKILL");
1523
1820
  await Promise.race([exited, delay(graceMs)]);
1524
1821
  }
1822
+ if (child.exitCode !== null || child.signalCode !== null) await reaped;
1525
1823
  await this.lineChain;
1526
1824
  }
1527
1825
  /** Waits until every stdout line seen so far (and any turn end it caused) is handled. */
@@ -1576,6 +1874,7 @@ ${text}`;
1576
1874
  async ensureProcess() {
1577
1875
  while (this.child && this.stopping) await this.waitForExit();
1578
1876
  if (this.child) return;
1877
+ await this.prepareEvidenceDir();
1579
1878
  const { bin, features } = await this.deps.claude();
1580
1879
  const args = claudeArgs({
1581
1880
  permissionMode: this.deps.permissionMode,
@@ -1586,18 +1885,25 @@ ${text}`;
1586
1885
  resume: this.record.claudeSessionId,
1587
1886
  appendSystemPrompt: runnerSystemPrompt({
1588
1887
  workBranch: this.record.workBranch,
1589
- baseRef: this.record.baseRef
1888
+ baseRef: this.record.baseRef,
1889
+ cwd: this.record.cwd
1590
1890
  }),
1591
1891
  features
1592
1892
  });
1593
- const child = spawn2(bin, args, {
1893
+ const child = spawn3(bin, args, {
1594
1894
  cwd: this.record.cwd,
1595
1895
  env: process.env,
1596
1896
  stdio: ["pipe", "pipe", "pipe"],
1597
- windowsHide: true
1897
+ windowsHide: true,
1898
+ // A process group of its own, so what it starts can be ended with it. It also means
1899
+ // the terminal's Ctrl+C no longer reaches it: the runner's shutdown stops it.
1900
+ detached: OWN_PROCESS_GROUP
1598
1901
  });
1599
1902
  await new Promise((resolve, reject) => {
1600
- child.once("spawn", () => resolve());
1903
+ child.once("spawn", () => {
1904
+ trackGroup(child);
1905
+ resolve();
1906
+ });
1601
1907
  child.once(
1602
1908
  "error",
1603
1909
  (err) => reject(new Error(`Could not start Claude Code (${bin}): ${err.message}`))
@@ -1605,6 +1911,7 @@ ${text}`;
1605
1911
  });
1606
1912
  this.child = child;
1607
1913
  this.stopping = null;
1914
+ this.reapGraceMs = void 0;
1608
1915
  this.stderrTail = "";
1609
1916
  this.sawResultSinceSpawn = false;
1610
1917
  this.spawnedWithResume = !!this.record.claudeSessionId;
@@ -1613,6 +1920,9 @@ ${text}`;
1613
1920
  `session ${this.sessionId}: Claude Code started${this.record.claudeSessionId ? " (resumed)" : ""}`,
1614
1921
  { pid: child.pid }
1615
1922
  );
1923
+ this.groupReaped = new Promise(
1924
+ (resolve) => child.once("exit", () => void reapGroup(child.pid, this.reapGraceMs).then(resolve))
1925
+ );
1616
1926
  child.stdin.on("error", () => void 0);
1617
1927
  child.stderr.setEncoding("utf8").on("data", (d) => {
1618
1928
  this.stderrTail = (this.stderrTail + d).slice(-4e3);
@@ -1710,13 +2020,20 @@ ${text}`;
1710
2020
  });
1711
2021
  }
1712
2022
  const push = await this.pushWork();
2023
+ const screenshots = push.failed ? "" : await this.publishScreenshots().catch((err) => {
2024
+ this.deps.logger.warn(`session ${this.sessionId}: publishing screenshots failed`, {
2025
+ error: scrubSecrets(err instanceof Error ? err.message : String(err))
2026
+ });
2027
+ return "";
2028
+ });
1713
2029
  this.record.turnActive = false;
1714
2030
  await this.deps.store.save(this.record);
1715
2031
  const failed = turnFailed || push.failed;
2032
+ const text = interrupted ? turn.isError ? null : turn.text : turn.text;
1716
2033
  this.emit({
1717
2034
  type: "result",
1718
2035
  status: failed ? "failed" : "idle",
1719
- text: interrupted ? turn.isError ? null : turn.text : turn.text,
2036
+ text: withScreenshots(text, screenshots),
1720
2037
  branch: push.branch,
1721
2038
  // The turn's work is only on this computer (committing or pushing it failed): a
1722
2039
  // continuation of the run must come back to this runner to find it.
@@ -1731,6 +2048,48 @@ ${text}`;
1731
2048
  { pushed: push.branch ?? void 0 }
1732
2049
  );
1733
2050
  }
2051
+ /** The screenshot folder exists and is kept out of git before the agent can use it. */
2052
+ async prepareEvidenceDir() {
2053
+ if (!this.record.workBranch || !this.record.repoDir) return;
2054
+ try {
2055
+ await ensureEvidenceDir(this.record.cwd);
2056
+ } catch (err) {
2057
+ this.deps.logger.warn(`session ${this.sessionId}: could not prepare the screenshot folder`, {
2058
+ error: scrubSecrets(err instanceof Error ? err.message : String(err))
2059
+ });
2060
+ }
2061
+ }
2062
+ /** Publishes the turn's screenshots; their markdown, or '' when there were none. */
2063
+ async publishScreenshots() {
2064
+ const { workBranch, repoDir, cwd, repository } = this.record;
2065
+ const repo = parseRepoUrl(
2066
+ repository ?? (repoDir ? `https://github.com/${basename(dirname4(repoDir))}/${basename(repoDir)}` : "")
2067
+ );
2068
+ if (!workBranch || !repoDir || !repo) return "";
2069
+ const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
2070
+ if (res.skipped.length) {
2071
+ this.emit({
2072
+ type: "error",
2073
+ message: `Screenshots not published (over 8 MB each, or past the first ${MAX_EVIDENCE_IMAGES}): ${res.skipped.join(", ").slice(0, 300)}`,
2074
+ retryable: false
2075
+ });
2076
+ }
2077
+ if (res.error) {
2078
+ this.deps.logger.warn(`session ${this.sessionId}: ${res.error}`);
2079
+ this.emit({
2080
+ type: "error",
2081
+ message: `${res.error} They are still in ${EVIDENCE_DIR}/ for the next turn.`,
2082
+ retryable: false
2083
+ });
2084
+ return "";
2085
+ }
2086
+ if (res.images.length) {
2087
+ this.deps.logger.info(
2088
+ `session ${this.sessionId}: published ${res.images.length} screenshot(s) to ${evidenceBranch(workBranch)}`
2089
+ );
2090
+ }
2091
+ return evidenceMarkdown(res);
2092
+ }
1734
2093
  /**
1735
2094
  * Commits leftovers, then pushes. `branch` is the work branch when it was pushed; `failed`
1736
2095
  * when committing or pushing failed (reported as an error saying where the work is kept).
@@ -1738,11 +2097,14 @@ ${text}`;
1738
2097
  async pushWork() {
1739
2098
  const { workBranch, baseSha, cwd, repoDir } = this.record;
1740
2099
  if (!workBranch || !baseSha) return { branch: null, failed: false };
2100
+ await this.prepareEvidenceDir();
1741
2101
  const res = await commitAndPush({
1742
2102
  worktree: cwd,
1743
2103
  workBranch,
1744
2104
  baseSha,
1745
- message: "Uncommitted changes from the agent\u2019s turn\n\nCommitted by dt-runner at the end of a Discovery Tree agent turn."
2105
+ message: "Uncommitted changes from the agent\u2019s turn\n\nCommitted by dt-runner at the end of a Discovery Tree agent turn.",
2106
+ // Also when the folder could not be listed in `info/exclude`.
2107
+ exclude: [EVIDENCE_DIR]
1746
2108
  });
1747
2109
  const uncommitted = res.failedAt === "commit";
1748
2110
  if (!!this.record.keepWorktree !== uncommitted) {
@@ -1859,6 +2221,16 @@ function startupHint(stderr) {
1859
2221
  function delay(ms) {
1860
2222
  return new Promise((r) => setTimeout(r, ms));
1861
2223
  }
2224
+ function withScreenshots(text, screenshots) {
2225
+ if (!screenshots) return text;
2226
+ if (!text) return screenshots;
2227
+ const room = SCREENSHOTS_TEXT_BUDGET - screenshots.length - 4;
2228
+ const body = text.length > room ? `${text.slice(0, Math.max(0, room - 1))}\u2026` : text;
2229
+ return `${body}
2230
+
2231
+ ${screenshots}`;
2232
+ }
2233
+ var SCREENSHOTS_TEXT_BUDGET = 59e3;
1862
2234
 
1863
2235
  // src/session-manager.ts
1864
2236
  var SessionManager = class {
@@ -2026,6 +2398,7 @@ var SessionManager = class {
2026
2398
  Object.assign(record, {
2027
2399
  cwd: wt.worktree,
2028
2400
  repoDir: wt.repoDir,
2401
+ repository: cmd.repository.url,
2029
2402
  workBranch: cmd.repository.workBranch,
2030
2403
  baseRef: wt.baseRef,
2031
2404
  baseSha: wt.baseSha,
@@ -2042,7 +2415,7 @@ var SessionManager = class {
2042
2415
  record.cwd = this.store.scratchDir(
2043
2416
  resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : cmd.sessionId
2044
2417
  );
2045
- await mkdir5(record.cwd, { recursive: true });
2418
+ await mkdir6(record.cwd, { recursive: true });
2046
2419
  }
2047
2420
  if (resume) {
2048
2421
  record.claudeSessionId = resume.claudeSessionId?.trim() || null;
@@ -2145,7 +2518,7 @@ var SessionManager = class {
2145
2518
  })
2146
2519
  );
2147
2520
  } else if (record.cwd) {
2148
- await rm4(record.cwd, { recursive: true, force: true }).catch(() => void 0);
2521
+ await rm5(record.cwd, { recursive: true, force: true }).catch(() => void 0);
2149
2522
  }
2150
2523
  await session.outbox.settled();
2151
2524
  await this.store.remove(sessionId);
@@ -2563,10 +2936,10 @@ function formatChecks(checks) {
2563
2936
  }
2564
2937
 
2565
2938
  // src/lock.ts
2566
- import { mkdir as mkdir6, open, readFile as readFile3, rm as rm5 } from "node:fs/promises";
2567
- import { join as join5 } from "node:path";
2939
+ import { mkdir as mkdir7, open, readFile as readFile4, rm as rm6 } from "node:fs/promises";
2940
+ import { join as join7 } from "node:path";
2568
2941
  function lockFile(stateDir) {
2569
- return join5(stateDir, "daemon.pid");
2942
+ return join7(stateDir, "daemon.pid");
2570
2943
  }
2571
2944
  function pidAlive(pid) {
2572
2945
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -2580,7 +2953,7 @@ function pidAlive(pid) {
2580
2953
  async function lockHolder(stateDir) {
2581
2954
  let raw;
2582
2955
  try {
2583
- raw = await readFile3(lockFile(stateDir), "utf8");
2956
+ raw = await readFile4(lockFile(stateDir), "utf8");
2584
2957
  } catch {
2585
2958
  return null;
2586
2959
  }
@@ -2588,7 +2961,7 @@ async function lockHolder(stateDir) {
2588
2961
  return pidAlive(pid) && pid !== process.pid ? pid : null;
2589
2962
  }
2590
2963
  async function acquireDaemonLock(stateDir, pid = process.pid) {
2591
- await mkdir6(stateDir, { recursive: true, mode: 448 });
2964
+ await mkdir7(stateDir, { recursive: true, mode: 448 });
2592
2965
  const file = lockFile(stateDir);
2593
2966
  for (let attempt = 0; attempt < 3; attempt++) {
2594
2967
  try {
@@ -2604,25 +2977,25 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
2604
2977
  lock: {
2605
2978
  file,
2606
2979
  async release() {
2607
- const current = await readFile3(file, "utf8").catch(() => "");
2608
- if (Number.parseInt(current.trim(), 10) === pid) await rm5(file, { force: true });
2980
+ const current = await readFile4(file, "utf8").catch(() => "");
2981
+ if (Number.parseInt(current.trim(), 10) === pid) await rm6(file, { force: true });
2609
2982
  }
2610
2983
  }
2611
2984
  };
2612
2985
  } catch (err) {
2613
2986
  if (err.code !== "EEXIST") throw err;
2614
2987
  }
2615
- const raw = await readFile3(file, "utf8").catch(() => null);
2988
+ const raw = await readFile4(file, "utf8").catch(() => null);
2616
2989
  if (raw === null) continue;
2617
2990
  const holder = Number.parseInt(raw.trim(), 10);
2618
2991
  if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
2619
- await rm5(file, { force: true });
2992
+ await rm6(file, { force: true });
2620
2993
  }
2621
2994
  return { ok: false, pid: null };
2622
2995
  }
2623
2996
 
2624
2997
  // src/pairing.ts
2625
- import { spawn as spawn3 } from "node:child_process";
2998
+ import { spawn as spawn4 } from "node:child_process";
2626
2999
  async function pair(api, opts) {
2627
3000
  const start2 = await api.startPairing({ name: opts.name, platform: RUNNER_PLATFORM });
2628
3001
  opts.ui.showCode(start2.userCode, start2.verificationUrl, start2.expiresInSeconds);
@@ -2686,7 +3059,7 @@ function openUrl(url) {
2686
3059
  if (!/^https?:\/\//i.test(url)) return;
2687
3060
  const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
2688
3061
  try {
2689
- const child = spawn3(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
3062
+ const child = spawn4(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
2690
3063
  child.on("error", () => void 0);
2691
3064
  child.unref();
2692
3065
  } catch {
@@ -2880,6 +3253,7 @@ async function start(opts) {
2880
3253
  };
2881
3254
  process.on("SIGINT", onSignal);
2882
3255
  process.on("SIGTERM", onSignal);
3256
+ process.on("SIGHUP", onSignal);
2883
3257
  let exit;
2884
3258
  try {
2885
3259
  exit = await daemon.run();