@discovery-tree/runner 0.1.5 → 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 +16 -1
  2. package/dist/cli.js +955 -841
  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.5" : "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,734 +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
- }
280
- var MODEL_NAME = /^[A-Za-z0-9][\w.:@/[\]-]{0,199}$/;
281
- function isValidModelName(model) {
282
- return MODEL_NAME.test(model);
283
290
  }
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
- "For screenshots of a user-visible change, save the images (PNG, JPEG, GIF or WebP) in",
342
- "`.dt-evidence/` at the root of this worktree, named for what they show",
343
- "(`settings-dark.png`), for example with `npx playwright screenshot <url> .dt-evidence/<name>.png`.",
344
- "Do not commit them, upload them or link them yourself: at the end of the turn the runner",
345
- "publishes them on a branch of their own and adds them, linked, under your final message,",
346
- "so they appear in the pull request description. The folder is ignored by git."
347
- ].join(" ");
348
- }
349
-
350
- // src/config.ts
351
- import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
352
- import { homedir } from "node:os";
353
- import { dirname, join as join2 } from "node:path";
354
-
355
- // src/invocation.ts
356
- var RUNNER_PACKAGE = "@discovery-tree/runner";
357
- function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
358
- if (env.npm_command === "exec") return true;
359
- return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
360
302
  }
361
- function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
362
- 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;
363
313
  }
364
-
365
- // src/config.ts
366
- function runnerPaths(env = process.env) {
367
- const home = homedir();
368
- if (process.platform === "win32") {
369
- const roaming = env.APPDATA || join2(home, "AppData", "Roaming");
370
- const local = env.LOCALAPPDATA || join2(home, "AppData", "Local");
371
- return {
372
- configFile: join2(roaming, "discovery-tree", "runner.json"),
373
- dataDir: join2(local, "discovery-tree", "runner"),
374
- stateDir: join2(local, "discovery-tree", "runner", "state")
375
- };
314
+ async function exists(p) {
315
+ try {
316
+ await stat(p);
317
+ return true;
318
+ } catch {
319
+ return false;
376
320
  }
377
- const config = env.XDG_CONFIG_HOME || join2(home, ".config");
378
- const data = env.XDG_DATA_HOME || join2(home, ".local", "share");
379
- const state = env.XDG_STATE_HOME || join2(home, ".local", "state");
380
- return {
381
- configFile: join2(config, "discovery-tree", "runner.json"),
382
- dataDir: join2(data, "discovery-tree", "runner"),
383
- stateDir: join2(state, "discovery-tree", "runner")
384
- };
385
321
  }
386
- var PERMISSION_MODES = [
387
- "acceptEdits",
388
- "auto",
389
- "default",
390
- "manual",
391
- "dontAsk",
392
- "plan",
393
- "bypassPermissions"
394
- ];
395
- var DEFAULT_ALLOWED_TOOLS = [
396
- "Read",
397
- "Edit",
398
- "MultiEdit",
399
- "Write",
400
- "Glob",
401
- "Grep",
402
- "LS",
403
- "NotebookEdit",
404
- "TodoWrite",
405
- "Task",
406
- "Bash(git status *)",
407
- "Bash(git diff *)",
408
- "Bash(git log *)",
409
- "Bash(git show *)",
410
- "Bash(git add *)",
411
- "Bash(git commit *)",
412
- "Bash(git restore *)",
413
- "Bash(git rm *)",
414
- "Bash(git mv *)",
415
- "Bash(git stash *)",
416
- "Bash(git blame *)",
417
- "Bash(git grep *)",
418
- "Bash(gh pr view *)",
419
- "Bash(gh pr diff *)",
420
- "Bash(gh pr checks *)",
421
- "Bash(gh pr list *)",
422
- "Bash(gh pr status *)",
423
- "Bash(gh run view *)",
424
- "Bash(gh run list *)",
425
- "Bash(gh issue view *)",
426
- "Bash(gh issue list *)",
427
- "Bash(gh repo view *)",
428
- "Bash(npm *)",
429
- "Bash(npx *)",
430
- "Bash(pnpm *)",
431
- "Bash(yarn *)",
432
- "Bash(node *)",
433
- "Bash(tsc *)",
434
- "Bash(python *)",
435
- "Bash(python3 *)",
436
- "Bash(pip *)",
437
- "Bash(pytest *)",
438
- "Bash(make *)",
439
- "Bash(cargo *)",
440
- "Bash(go *)",
441
- "Bash(ls *)",
442
- "Bash(cat *)",
443
- "Bash(head *)",
444
- "Bash(tail *)",
445
- "Bash(wc *)",
446
- "Bash(grep *)",
447
- "Bash(rg *)",
448
- "Bash(echo *)",
449
- "Bash(pwd)",
450
- "Bash(mkdir *)",
451
- "Bash(touch *)",
452
- "Bash(diff *)",
453
- "Bash(sort *)",
454
- "Bash(uniq *)",
455
- "Bash(which *)",
456
- "Bash(true)"
457
- ];
458
- var PROTECTED_PATHS = [
459
- "~/.ssh/**",
460
- "~/.aws/**",
461
- "~/.config/gcloud/**",
462
- "~/.azure/**",
463
- "~/.gnupg/**",
464
- "~/.netrc",
465
- "~/.git-credentials",
466
- "~/.config/gh/**",
467
- "~/.docker/config.json",
468
- "~/.kube/**",
469
- "~/.npmrc",
470
- "~/.pypirc",
471
- // The runner's own token.
472
- "~/.config/discovery-tree/**",
473
- // Claude Code's sign-in and account file.
474
- "~/.claude/.credentials.json",
475
- "~/.claude.json"
476
- ];
477
- var PROTECTED_FROM_EDIT = [
478
- "~/.claude/**",
479
- // Shell startup files and git config: an edit there runs, or changes what runs, in every
480
- // later shell or git command the person uses outside the agent.
481
- "~/.bashrc",
482
- "~/.bash_profile",
483
- "~/.profile",
484
- "~/.zshrc",
485
- "~/.zprofile",
486
- "~/.zshenv",
487
- "~/.config/fish/**",
488
- "~/.gitconfig",
489
- "~/.config/git/**"
490
- ];
491
- var DEFAULT_DISALLOWED_TOOLS = [
492
- ...PROTECTED_PATHS.map((p) => `Read(${p})`),
493
- ...[...PROTECTED_PATHS, ...PROTECTED_FROM_EDIT].map((p) => `Edit(${p})`)
494
- ];
495
- function configDirRules(configFile, platform = process.platform) {
496
- if (platform === "win32") return [];
497
- const dir = dirname(configFile);
498
- if (!dir.startsWith("/")) return [];
499
- 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
+ });
452
+ }
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;
474
+ try {
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
+ }
492
+ } catch (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
+ };
512
+ }
500
513
  }
501
- var DEFAULT_SERVER_URL = "https://discovery-tree-backend.onrender.com";
502
- var DEFAULT_MAX_SESSIONS = 2;
503
- var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
504
- async function readConfigFile(file) {
505
- let raw;
506
- try {
507
- raw = await readFile(file, "utf8");
508
- } catch (err) {
509
- if (err.code === "ENOENT") return null;
510
- throw err;
514
+ async function removeWorktree(repoDir, worktree) {
515
+ if (repoDir && await exists(repoDir)) {
516
+ await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
511
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 = "";
512
541
  try {
513
- return JSON.parse(raw);
542
+ current = await readFile(file, "utf8");
514
543
  } catch {
515
- throw new Error(
516
- `${file} is not valid JSON; fix it or run \`${runnerCommand("logout")}\` to start over.`
517
- );
518
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
+ );
519
554
  }
520
- async function writeConfigFile(file, config) {
521
- await mkdir(dirname(file), { recursive: true, mode: 448 });
522
- await writeFile(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
523
- await chmod(file, 384).catch(() => void 0);
524
- }
525
- async function deleteConfigFile(file) {
555
+ async function publishEvidence(input) {
556
+ const dir = join3(input.worktree, EVIDENCE_DIR);
557
+ let found;
526
558
  try {
527
- await rm(file);
528
- return true;
559
+ found = await waitingImages(dir);
529
560
  } catch (err) {
530
- if (err.code === "ENOENT") return false;
531
- 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);
532
626
  }
533
627
  }
534
- function normalizeServerUrl(url) {
535
- const trimmed = url.trim().replace(/\/+$/, "");
536
- return trimmed.replace(/\/api(\/health)?$/, "");
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
+ );
537
633
  }
538
- var MAX_SESSIONS_LIMIT = 64;
539
- function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPaths(env)) {
540
- const mode = file?.permissionMode ?? "acceptEdits";
541
- if (!PERMISSION_MODES.includes(mode)) {
542
- throw new Error(
543
- `permissionMode "${mode}" in ${paths.configFile} is not one of ${PERMISSION_MODES.join(", ")}.`
544
- );
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}`;
637
+ }
638
+ async function waitingImages(dir) {
639
+ let entries;
640
+ try {
641
+ entries = await readdir(dir, { withFileTypes: true });
642
+ } catch {
643
+ return [];
545
644
  }
546
- const maxSessions = overrides.maxSessions ?? file?.maxSessions ?? DEFAULT_MAX_SESSIONS;
547
- if (!Number.isInteger(maxSessions) || maxSessions < 1 || maxSessions > MAX_SESSIONS_LIMIT) {
548
- throw new Error(
549
- `maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
550
- );
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 });
551
652
  }
552
- const allowed = [
553
- ...file?.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
554
- ...file?.extraAllowedTools ?? []
555
- ];
556
- const disallowed = [
557
- ...file?.disallowedTools ?? [
558
- ...DEFAULT_DISALLOWED_TOOLS,
559
- ...configDirRules(paths.configFile)
560
- ],
561
- ...file?.extraDisallowedTools ?? []
562
- ];
563
- return {
564
- server: normalizeServerUrl(env.DT_SERVER_URL || file?.server || DEFAULT_SERVER_URL),
565
- runnerId: file?.runnerId ?? null,
566
- token: env.DT_RUNNER_TOKEN || file?.token || null,
567
- name: file?.name ?? null,
568
- maxSessions,
569
- reposDir: overrides.reposDir ?? file?.reposDir ?? join2(paths.dataDir, "repos"),
570
- worktreesDir: file?.worktreesDir ?? join2(paths.dataDir, "worktrees"),
571
- permissionMode: mode,
572
- allowedTools: [...new Set(allowed)],
573
- disallowedTools: [...new Set(disallowed)],
574
- loadProjectSettings: file?.loadProjectSettings === true,
575
- gitProtocol: file?.gitProtocol === "ssh" ? "ssh" : "https",
576
- idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
577
- stateDir: paths.stateDir,
578
- configFile: paths.configFile
579
- };
580
- }
581
-
582
- // src/backoff.ts
583
- function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
584
- const ceiling = Math.min(maxMs, baseMs * 2 ** Math.min(attempt, 20));
585
- return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
586
- }
587
- function sleep(ms, signal) {
588
- return new Promise((resolve) => {
589
- if (signal?.aborted) return resolve();
590
- const timer = setTimeout(done, ms);
591
- function done() {
592
- clearTimeout(timer);
593
- signal?.removeEventListener("abort", done);
594
- resolve();
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}`);
595
659
  }
596
- signal?.addEventListener("abort", done, { once: true });
597
- });
660
+ taken.add(path.toLowerCase());
661
+ f.path = path;
662
+ }
663
+ return out;
598
664
  }
599
-
600
- // src/session-manager.ts
601
- import { mkdir as mkdir6, rm as rm5 } from "node:fs/promises";
602
-
603
- // src/git.ts
604
- import { mkdir as mkdir2, rm as rm2, stat } from "node:fs/promises";
605
- import { dirname as dirname2, join as join3 } from "node:path";
606
-
607
- // src/log.ts
608
- function createLogger(opts = {}) {
609
- const write = opts.write ?? ((line) => process.stdout.write(line + "\n"));
610
- const emit = (level, msg, fields) => {
611
- if (level === "debug" && !opts.verbose) return;
612
- const safe = fields ? redactFields(fields) : void 0;
613
- if (opts.json) {
614
- write(JSON.stringify({ time: (/* @__PURE__ */ new Date()).toISOString(), level, msg, ...safe }));
615
- return;
616
- }
617
- const time = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
618
- const tag = level === "info" ? "" : ` ${level.toUpperCase()}`;
619
- 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(" ") : "";
620
- write(`${time}${tag} ${msg}${extra.trimEnd() === "" ? "" : extra}`);
621
- };
622
- return {
623
- debug: (m, f) => emit("debug", m, f),
624
- info: (m, f) => emit("info", m, f),
625
- warn: (m, f) => emit("warn", m, f),
626
- error: (m, f) => emit("error", m, f)
627
- };
665
+ function safeName(name) {
666
+ const cleaned = name.replace(/[^\w.-]+/g, "-").replace(/^[.-]+/, "");
667
+ return cleaned || "screenshot.png";
628
668
  }
629
- var SECRET_KEY = /token|secret|password|authorization/i;
630
- function redactFields(fields) {
631
- const out = {};
632
- for (const [k, v] of Object.entries(fields)) out[k] = SECRET_KEY.test(k) ? "[redacted]" : v;
633
- return out;
669
+ function captionFor(name) {
670
+ return name.replace(/\.[^.]+$/, "").replace(/[-_]+/g, " ").replace(/[[\]]/g, "").trim();
634
671
  }
635
- function scrubSecrets(text) {
636
- 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;
637
675
  }
638
-
639
- // src/git.ts
640
- var GitError = class extends Error {
641
- constructor(args, result) {
642
- super(gitErrorMessage(args, result));
643
- this.args = args;
644
- this.result = result;
645
- this.name = "GitError";
646
- }
647
- };
648
- function gitErrorMessage(args, result) {
649
- const detail = (result.stderr || result.stdout).trim().split("\n").filter(Boolean).slice(-3).join(" ");
650
- 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;
651
683
  }
652
- var gitEnv = () => ({
653
- ...process.env,
654
- GIT_TERMINAL_PROMPT: "0",
655
- GCM_INTERACTIVE: "never",
656
- GIT_ASKPASS: process.env.GIT_ASKPASS ?? ""
657
- });
658
- async function git(cwd, args, timeoutMs = 10 * 6e4) {
659
- 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
+ });
660
690
  if (res.code !== 0) throw new GitError(args, res);
661
691
  return res.stdout.trim();
662
692
  }
663
- async function gitOk(cwd, args) {
664
- const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs: 6e4 });
665
- 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"];
666
700
  }
667
- var REPOSITORY_HOST = "github.com";
668
- 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) {
669
709
  try {
670
- const u = new URL(url);
671
- if (u.protocol !== "https:" || u.hostname.toLowerCase() !== REPOSITORY_HOST) return null;
672
- if (u.port || u.username || u.password || u.search || u.hash) return null;
673
- const parts = u.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "").split("/");
674
- if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
675
- if (!/^[\w.-]+$/.test(parts[0]) || !/^[\w.-]+$/.test(parts[1])) return null;
676
- if (parts.some((p) => p === "." || p === "..")) return null;
677
- 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;
678
713
  } catch {
679
714
  return null;
680
715
  }
681
716
  }
682
- function repositoryUrlError(url) {
683
- return `Repository URL ${scrubSecrets(url).slice(0, 200)} is not a https://github.com/<owner>/<repo> URL; this runner only works on GitHub repositories.`;
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
+ }
684
729
  }
685
- function cloneUrl(ref, protocol) {
686
- return protocol === "ssh" ? `git@${ref.host}:${ref.owner}/${ref.repo}.git` : `https://${ref.host}/${ref.owner}/${ref.repo}.git`;
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
+ }
687
740
  }
688
- var UNSAFE_REF = /[\s~^:?*[\\\x00-\x1f]|\.\.|@\{|\/\/|\.lock$|\/$/;
689
- function assertSafeRef(name, what) {
690
- if (!name || name.startsWith("-") || UNSAFE_REF.test(name)) {
691
- throw new Error(`${what} "${name}" is not a valid branch name.`);
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
+ };
692
765
  }
766
+ return { claudeVersion: version, claudeReady: auth.loggedIn, claudeProblem: null };
693
767
  }
694
- var repoLocks = /* @__PURE__ */ new Map();
695
- function withRepoLock(dir, fn) {
696
- const prev = repoLocks.get(dir) ?? Promise.resolve();
697
- const next = prev.catch(() => void 0).then(fn);
698
- repoLocks.set(dir, next);
699
- const release = () => {
700
- if (repoLocks.get(dir) === next) repoLocks.delete(dir);
701
- };
702
- next.then(release, release);
703
- return next;
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);
704
771
  }
705
- async function exists(p) {
706
- try {
707
- await stat(p);
708
- return true;
709
- } catch {
710
- return false;
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.";
711
778
  }
779
+ return 'On the runner\u2019s computer, run `claude`, type `/login` and sign in again, and check that `claude -p "say ok"` answers.';
712
780
  }
713
- async function prepareWorktree(input) {
714
- const ref = parseRepoUrl(input.url);
715
- if (!ref) throw new Error(repositoryUrlError(input.url));
716
- assertSafeRef(input.workBranch, "Work branch");
717
- if (input.baseRef) assertSafeRef(input.baseRef, "Base branch");
718
- const repoDir = join3(input.reposDir, ref.owner, ref.repo);
719
- const worktree = join3(input.worktreesDir, input.worktreeKey || input.sessionId);
720
- return withRepoLock(repoDir, async () => {
721
- if (!await exists(join3(repoDir, ".git"))) {
722
- await mkdir2(dirname2(repoDir), { recursive: true });
723
- await rm2(repoDir, { recursive: true, force: true });
724
- await git(dirname2(repoDir), [
725
- "clone",
726
- "--no-checkout",
727
- cloneUrl(ref, input.protocol),
728
- repoDir
729
- ]);
730
- } else {
731
- const wanted = cloneUrl(ref, input.protocol);
732
- const current = await exec("git", ["config", "--get", "remote.origin.url"], {
733
- cwd: repoDir,
734
- env: gitEnv()
735
- });
736
- if (current.stdout.trim() !== wanted) {
737
- await git(repoDir, ["remote", "set-url", "origin", wanted]);
738
- }
739
- await git(repoDir, ["fetch", "--prune", "origin"]);
740
- }
741
- const baseRef = input.baseRef ?? await defaultBranch(repoDir);
742
- let start2 = `origin/${baseRef}`;
743
- if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${start2}^{commit}`])) {
744
- if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`])) {
745
- throw new Error(`Base branch ${baseRef} was not found on origin.`);
746
- }
747
- start2 = baseRef;
748
- }
749
- let baseSha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
750
- let checkout = start2;
751
- let continuedFrom;
752
- let setAside;
753
- const remoteWork = `refs/remotes/origin/${input.workBranch}`;
754
- if (input.continueBranch && await exists(worktree) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
755
- cwd: worktree,
756
- env: gitEnv(),
757
- timeoutMs: 6e4
758
- }).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
759
- // behind (the run went on elsewhere) would have the agent work on stale code.
760
- (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${remoteWork}^{commit}`]) || await exec("git", ["merge-base", "--is-ancestor", remoteWork, "HEAD"], {
761
- cwd: worktree,
762
- env: gitEnv(),
763
- timeoutMs: 6e4
764
- }).then((r) => r.code === 0))) {
765
- const forkPoint = await exec("git", ["merge-base", "HEAD", start2], {
766
- cwd: worktree,
767
- env: gitEnv(),
768
- timeoutMs: 6e4
769
- });
770
- if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
771
- return { repoDir, worktree, baseRef, baseSha, continuedFrom: "worktree" };
772
- }
773
- if (input.continueBranch) {
774
- const remote = `refs/remotes/origin/${input.workBranch}`;
775
- const local = `refs/heads/${input.workBranch}`;
776
- const hasRemote = await gitOk(repoDir, [
777
- "rev-parse",
778
- "--verify",
779
- "--quiet",
780
- `${remote}^{commit}`
781
- ]);
782
- const hasLocal = await gitOk(repoDir, [
783
- "rev-parse",
784
- "--verify",
785
- "--quiet",
786
- `${local}^{commit}`
787
- ]);
788
- const localAhead = hasLocal && (!hasRemote || await gitOk(repoDir, ["merge-base", "--is-ancestor", remote, local]));
789
- if (localAhead) {
790
- checkout = local;
791
- continuedFrom = "local";
792
- } else if (hasRemote) {
793
- checkout = remote;
794
- continuedFrom = "remote";
795
- } else {
796
- continuedFrom = "base";
797
- }
798
- if (continuedFrom !== "base") {
799
- const forkPoint = await exec("git", ["merge-base", checkout, start2], {
800
- cwd: repoDir,
801
- env: gitEnv(),
802
- timeoutMs: 6e4
803
- });
804
- if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
805
- checkout = await git(repoDir, ["rev-parse", `${checkout}^{commit}`]);
806
- }
807
- }
808
- if (input.continueBranch && await exists(worktree)) {
809
- const dirty = await exec("git", ["status", "--porcelain"], {
810
- cwd: worktree,
811
- env: gitEnv(),
812
- timeoutMs: 6e4
813
- });
814
- if (dirty.code === 0 && dirty.stdout.trim()) {
815
- const aside = `${worktree}.kept-${Date.now()}`;
816
- if (await gitOk(repoDir, ["worktree", "move", worktree, aside])) setAside = aside;
817
- }
818
- }
819
- if (await exists(worktree)) {
820
- await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
821
- await rm2(worktree, { recursive: true, force: true });
822
- }
823
- await gitOk(repoDir, ["worktree", "prune"]);
824
- await mkdir2(input.worktreesDir, { recursive: true });
825
- await git(repoDir, [
826
- "worktree",
827
- "add",
828
- "--no-track",
829
- "-B",
830
- input.workBranch,
831
- worktree,
832
- checkout
833
- ]);
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;
820
+ }
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(" ");
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(" ");
860
+ }
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 ?? "");
872
+ }
873
+ function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
874
+ return viaNpx ? `npx ${RUNNER_PACKAGE}@latest ${subcommand}` : `dt-runner ${subcommand}`;
875
+ }
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");
834
883
  return {
835
- repoDir,
836
- worktree,
837
- baseRef,
838
- baseSha,
839
- ...continuedFrom ? { continuedFrom } : {},
840
- ...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")
841
887
  };
842
- });
843
- }
844
- async function defaultBranch(repoDir) {
845
- const read = async () => {
846
- const res = await exec("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
847
- cwd: repoDir,
848
- env: gitEnv()
849
- });
850
- 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")
851
896
  };
852
- const known = await read();
853
- if (known) return known;
854
- await gitOk(repoDir, ["remote", "set-head", "origin", "--auto"]);
855
- return await read() ?? "main";
856
897
  }
857
- async function commitAndPush(input) {
858
- const { worktree } = input;
859
- const exclude = input.exclude ?? [];
860
- const excluded = (line) => {
861
- const path = line.slice(3).replace(/^"|"$/g, "");
862
- return exclude.some((p) => path === p || path.startsWith(`${p}/`));
863
- };
864
- 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;
865
1027
  try {
866
- const status2 = await git(worktree, ["status", "--porcelain"]);
867
- const dirty = status2.split("\n").some((line) => line && !excluded(line));
868
- if (dirty) {
869
- await git(worktree, ["add", "-A"]);
870
- if (exclude.length) await git(worktree, ["reset", "-q", "--", ...exclude]);
871
- }
872
- const staged = dirty && !await gitOk(worktree, ["diff", "--cached", "--quiet"]);
873
- if (staged) {
874
- const identity2 = await gitOk(worktree, ["config", "user.email"]) ? [] : [
875
- "-c",
876
- "user.name=Discovery Tree runner",
877
- "-c",
878
- "user.email=dt-runner@users.noreply.local"
879
- ];
880
- await git(worktree, [...identity2, "commit", "--no-verify", "-q", "-m", input.message]);
881
- committed = true;
882
- }
1028
+ raw = await readFile2(file, "utf8");
883
1029
  } catch (err) {
884
- return {
885
- committed,
886
- pushed: false,
887
- error: errorText(err, "Committing the work failed"),
888
- failedAt: "commit"
889
- };
1030
+ if (err.code === "ENOENT") return null;
1031
+ throw err;
1032
+ }
1033
+ try {
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
+ );
890
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) {
891
1047
  try {
892
- const ahead = Number(await git(worktree, ["rev-list", "--count", `${input.baseSha}..HEAD`]));
893
- if (!ahead) return { committed, pushed: false, error: null };
894
- await git(worktree, ["push", "--quiet", "-u", "origin", `HEAD:refs/heads/${input.workBranch}`]);
895
- return { committed, pushed: true, error: null };
1048
+ await rm3(file);
1049
+ return true;
896
1050
  } catch (err) {
897
- return {
898
- committed,
899
- pushed: false,
900
- error: errorText(err, "Pushing the work branch failed"),
901
- failedAt: "push"
902
- };
1051
+ if (err.code === "ENOENT") return false;
1052
+ throw err;
903
1053
  }
904
1054
  }
905
- async function removeWorktree(repoDir, worktree) {
906
- if (repoDir && await exists(repoDir)) {
907
- 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
+ );
908
1066
  }
909
- await rm2(worktree, { recursive: true, force: true });
910
- 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
+ };
911
1101
  }
912
- function errorText(err, prefix) {
913
- const msg = err instanceof Error ? err.message : String(err);
914
- 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
+ });
915
1119
  }
916
1120
 
1121
+ // src/session-manager.ts
1122
+ import { mkdir as mkdir6, rm as rm5 } from "node:fs/promises";
1123
+
917
1124
  // src/fsutil.ts
918
- 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";
919
1126
  import { dirname as dirname3 } from "node:path";
920
1127
  async function writeJsonAtomic(file, value) {
921
- await mkdir3(dirname3(file), { recursive: true });
1128
+ await mkdir4(dirname3(file), { recursive: true });
922
1129
  const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
923
- await writeFile2(tmp, JSON.stringify(value), { mode: 384 });
924
- await rename(tmp, file);
1130
+ await writeFile3(tmp, JSON.stringify(value), { mode: 384 });
1131
+ await rename2(tmp, file);
925
1132
  }
926
1133
  async function readJson(file) {
927
1134
  try {
928
- return JSON.parse(await readFile2(file, "utf8"));
1135
+ return JSON.parse(await readFile3(file, "utf8"));
929
1136
  } catch (err) {
930
1137
  if (err.code === "ENOENT") return null;
931
1138
  if (err instanceof SyntaxError) return null;
@@ -1164,214 +1371,98 @@ function takeBatch(pending) {
1164
1371
  }
1165
1372
 
1166
1373
  // src/session.ts
1167
- import { spawn as spawn2 } from "node:child_process";
1374
+ import { spawn as spawn3 } from "node:child_process";
1168
1375
  import { basename, dirname as dirname4 } from "node:path";
1169
1376
  import { createInterface } from "node:readline";
1170
1377
 
1171
- // src/evidence.ts
1172
- import { mkdir as mkdir4, mkdtemp, readdir, readFile as readFile3, rename as rename2, rm as rm3, stat as stat2, writeFile as writeFile3 } from "node:fs/promises";
1173
- import { tmpdir } from "node:os";
1174
- import { isAbsolute as isAbsolute2, join as join4 } from "node:path";
1175
- var EVIDENCE_DIR = ".dt-evidence";
1176
- var PUBLISHED_DIR = "published";
1177
- var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set(["png", "jpg", "jpeg", "gif", "webp"]);
1178
- var MAX_EVIDENCE_IMAGES = 12;
1179
- var MAX_EVIDENCE_BYTES = 8 * 1024 * 1024;
1180
- function evidenceBranch(workBranch) {
1181
- return `dt-evidence/${workBranch.replace(/%/g, "%25").replace(/\//g, "%2F")}`;
1182
- }
1183
- async function ensureEvidenceDir(worktree) {
1184
- await mkdir4(join4(worktree, EVIDENCE_DIR), { recursive: true });
1185
- const rel = await git(worktree, ["rev-parse", "--git-path", "info/exclude"]);
1186
- const file = isAbsolute2(rel) ? rel : join4(worktree, rel);
1187
- const line = `/${EVIDENCE_DIR}/`;
1188
- let current = "";
1189
- try {
1190
- current = await readFile3(file, "utf8");
1191
- } catch {
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
+ });
1192
1391
  }
1193
- if (current.split("\n").some((l) => l.trim() === line)) return;
1194
- await mkdir4(join4(file, ".."), { recursive: true });
1195
- const sep = current && !current.endsWith("\n") ? "\n" : "";
1196
- await writeFile3(
1197
- file,
1198
- `${current}${sep}# Screenshots dt-runner publishes on their own branch
1199
- ${line}
1200
- `
1201
- );
1202
1392
  }
1203
- async function publishEvidence(input) {
1204
- const dir = join4(input.worktree, EVIDENCE_DIR);
1205
- let found;
1206
- try {
1207
- found = await waitingImages(dir);
1208
- } catch (err) {
1209
- const why = err instanceof Error ? err.message : String(err);
1210
- return { images: [], skipped: [], error: `Reading the screenshots failed: ${why}` };
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;
1211
1398
  }
1212
- const skipped = found.filter((f) => f.size > MAX_EVIDENCE_BYTES).map((f) => f.name);
1213
- const fitting = found.filter((f) => f.size <= MAX_EVIDENCE_BYTES);
1214
- skipped.push(...fitting.slice(MAX_EVIDENCE_IMAGES).map((f) => f.name));
1215
- const files = fitting.slice(0, MAX_EVIDENCE_IMAGES);
1216
- if (!files.length) return { images: [], skipped, error: null };
1217
- const branch = evidenceBranch(input.workBranch);
1218
- let scratch = null;
1219
- try {
1220
- assertSafeRef(branch, "Evidence branch");
1221
- scratch = await mkdtemp(join4(tmpdir(), "dt-evidence-"));
1222
- const index = join4(scratch, "index");
1223
- const ref = `refs/heads/${branch}`;
1224
- const build = async () => {
1225
- await gitOk2(input.repoDir, ["fetch", "--quiet", "origin", `+${ref}:${ref}`]);
1226
- const parent = await revParse(input.repoDir, ref);
1227
- const run = (args) => gitWithIndex(input.repoDir, index, args);
1228
- await run(parent ? ["read-tree", parent] : ["read-tree", "--empty"]);
1229
- for (const f of files) {
1230
- const blob = await git(input.repoDir, ["hash-object", "-w", "--", join4(dir, f.name)]);
1231
- await run(["update-index", "--add", "--cacheinfo", `100644,${blob},${f.path}`]);
1232
- }
1233
- const tree = await run(["write-tree"]);
1234
- const parentTree = parent ? await git(input.repoDir, ["rev-parse", `${parent}^{tree}`]) : null;
1235
- if (parent && tree === parentTree) return parent;
1236
- const made = await git(input.repoDir, [
1237
- ...await identity(input.repoDir),
1238
- "commit-tree",
1239
- tree,
1240
- ...parent ? ["-p", parent] : [],
1241
- "-m",
1242
- `Screenshots for ${input.workBranch}
1243
-
1244
- Published by dt-runner for the pull request's review; not part of the change.`
1245
- ]);
1246
- await git(input.repoDir, ["update-ref", ref, made]);
1247
- return made;
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);
1248
1409
  };
1249
- let commit = await build();
1250
- try {
1251
- await git(input.repoDir, ["push", "--quiet", "origin", `${commit}:${ref}`]);
1252
- } catch {
1253
- commit = await build();
1254
- await git(input.repoDir, ["push", "--quiet", "origin", `${commit}:${ref}`]);
1255
- }
1256
- await mkdir4(join4(dir, PUBLISHED_DIR), { recursive: true });
1257
- for (const f of files) {
1258
- await rename2(join4(dir, f.name), join4(dir, PUBLISHED_DIR, f.name)).catch(() => void 0);
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;
1259
1426
  }
1260
- return {
1261
- images: files.map((f) => ({
1262
- path: f.path,
1263
- caption: captionFor(f.name),
1264
- url: rawFileUrl(input.repo, commit, f.path)
1265
- })),
1266
- skipped,
1267
- error: null
1268
- };
1269
- } catch (err) {
1270
- const why = err instanceof GitError || err instanceof Error ? err.message : String(err);
1271
- return { images: [], skipped, error: `Publishing the screenshots failed: ${why}` };
1427
+ signalGroup(pgid, "SIGKILL");
1272
1428
  } finally {
1273
- if (scratch) await rm3(scratch, { recursive: true, force: true }).catch(() => void 0);
1429
+ liveGroups.delete(pgid);
1274
1430
  }
1275
1431
  }
1276
- function evidenceMarkdown(result) {
1277
- if (!result.images.length) return "";
1278
- return ["## Screenshots", "", ...result.images.map((i) => `![${i.caption}](${i.url})`)].join(
1279
- "\n"
1280
- );
1281
- }
1282
- function rawFileUrl(repo, commit, path) {
1283
- const segments = path.split("/").map(encodeURIComponent).join("/");
1284
- return `https://${repo.host}/${repo.owner}/${repo.repo}/raw/${commit}/${segments}`;
1285
- }
1286
- async function waitingImages(dir) {
1287
- let entries;
1432
+ function signalGroup(pgid, signal) {
1288
1433
  try {
1289
- entries = await readdir(dir, { withFileTypes: true });
1434
+ process.kill(-pgid, signal);
1435
+ return true;
1290
1436
  } catch {
1291
- return [];
1292
- }
1293
- const out = [];
1294
- for (const e of entries) {
1295
- if (!e.isFile()) continue;
1296
- const ext = e.name.split(".").pop()?.toLowerCase() ?? "";
1297
- if (!e.name.includes(".") || !IMAGE_EXTENSIONS.has(ext)) continue;
1298
- const { size } = await stat2(join4(dir, e.name));
1299
- out.push({ name: e.name, path: safeName(e.name), size });
1300
- }
1301
- out.sort((a, b) => a.name.localeCompare(b.name));
1302
- const taken = /* @__PURE__ */ new Set();
1303
- for (const f of out) {
1304
- let path = f.path;
1305
- for (let n = 2; taken.has(path.toLowerCase()); n++) {
1306
- path = f.path.replace(/(\.[^.]+)?$/, (ext) => `-${n}${ext}`);
1307
- }
1308
- taken.add(path.toLowerCase());
1309
- f.path = path;
1437
+ return false;
1310
1438
  }
1311
- return out;
1312
- }
1313
- function safeName(name) {
1314
- const cleaned = name.replace(/[^\w.-]+/g, "-").replace(/^[.-]+/, "");
1315
- return cleaned || "screenshot.png";
1316
- }
1317
- function captionFor(name) {
1318
- return name.replace(/\.[^.]+$/, "").replace(/[-_]+/g, " ").replace(/[[\]]/g, "").trim();
1319
- }
1320
- async function gitOk2(cwd, args) {
1321
- const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs: 5 * 6e4 });
1322
- return res.code === 0;
1323
- }
1324
- async function revParse(cwd, ref) {
1325
- const res = await exec("git", ["rev-parse", "--verify", "-q", `${ref}^{commit}`], {
1326
- cwd,
1327
- env: gitEnv(),
1328
- timeoutMs: 6e4
1329
- });
1330
- return res.code === 0 ? res.stdout.trim() : null;
1331
- }
1332
- async function gitWithIndex(cwd, index, args) {
1333
- const res = await exec("git", args, {
1334
- cwd,
1335
- env: { ...gitEnv(), GIT_INDEX_FILE: index },
1336
- timeoutMs: 6e4
1337
- });
1338
- if (res.code !== 0) throw new GitError(args, res);
1339
- return res.stdout.trim();
1340
- }
1341
- async function identity(cwd) {
1342
- const res = await exec("git", ["config", "user.email"], {
1343
- cwd,
1344
- env: gitEnv(),
1345
- timeoutMs: 6e4
1346
- });
1347
- return res.code === 0 && res.stdout.trim() ? [] : ["-c", "user.name=Discovery Tree runner", "-c", "user.email=dt-runner@users.noreply.local"];
1348
1439
  }
1349
1440
 
1350
1441
  // src/session-store.ts
1351
1442
  import { mkdir as mkdir5, readdir as readdir2, rm as rm4 } from "node:fs/promises";
1352
- import { join as join5 } from "node:path";
1443
+ import { join as join6 } from "node:path";
1353
1444
  var HANDLED_COMMAND_IDS_KEPT = 100;
1354
1445
  var SessionStore = class {
1355
1446
  constructor(stateDir) {
1356
1447
  this.stateDir = stateDir;
1357
1448
  }
1358
1449
  dir(sessionId) {
1359
- return join5(this.stateDir, "sessions", sessionId);
1450
+ return join6(this.stateDir, "sessions", sessionId);
1360
1451
  }
1361
1452
  outboxFile(sessionId) {
1362
- return join5(this.dir(sessionId), "outbox.json");
1453
+ return join6(this.dir(sessionId), "outbox.json");
1363
1454
  }
1364
1455
  async save(record) {
1365
1456
  record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1366
- await writeJsonAtomic(join5(this.dir(record.sessionId), "session.json"), record);
1457
+ await writeJsonAtomic(join6(this.dir(record.sessionId), "session.json"), record);
1367
1458
  }
1368
1459
  async list() {
1369
- const root = join5(this.stateDir, "sessions");
1460
+ const root = join6(this.stateDir, "sessions");
1370
1461
  await mkdir5(root, { recursive: true });
1371
1462
  const out = [];
1372
1463
  for (const entry of await readdir2(root, { withFileTypes: true })) {
1373
1464
  if (!entry.isDirectory()) continue;
1374
- const rec = await readJson(join5(root, entry.name, "session.json"));
1465
+ const rec = await readJson(join6(root, entry.name, "session.json"));
1375
1466
  if (rec?.sessionId === entry.name) out.push(rec);
1376
1467
  }
1377
1468
  return out;
@@ -1381,7 +1472,7 @@ var SessionStore = class {
1381
1472
  }
1382
1473
  /** Scratch working directory for a session without a repository. */
1383
1474
  scratchDir(sessionId) {
1384
- return join5(this.stateDir, "scratch", sessionId);
1475
+ return join6(this.stateDir, "scratch", sessionId);
1385
1476
  }
1386
1477
  };
1387
1478
  function assertSafeSessionId(id) {
@@ -1629,6 +1720,10 @@ var AgentSession = class {
1629
1720
  */
1630
1721
  resumeRetry = null;
1631
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;
1632
1727
  lastActivity = Date.now();
1633
1728
  get sessionId() {
1634
1729
  return this.record.sessionId;
@@ -1701,11 +1796,17 @@ var AgentSession = class {
1701
1796
  }, this.deps.interruptGraceMs ?? 5e3);
1702
1797
  return true;
1703
1798
  }
1704
- /** 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
+ */
1705
1804
  async stop(reason, graceMs = 5e3) {
1706
1805
  const child = this.child;
1707
1806
  if (!child) return;
1807
+ const reaped = this.groupReaped;
1708
1808
  this.stopping = reason;
1809
+ this.reapGraceMs = graceMs;
1709
1810
  const exited = new Promise((resolve) => this.exitWaiters.push(resolve));
1710
1811
  child.stdin.end();
1711
1812
  const timedOut = await Promise.race([
@@ -1713,11 +1814,12 @@ var AgentSession = class {
1713
1814
  delay(graceMs).then(() => true)
1714
1815
  ]);
1715
1816
  if (timedOut && this.child === child) {
1716
- child.kill("SIGTERM");
1817
+ signalTree(child, "SIGTERM");
1717
1818
  const again = await Promise.race([exited.then(() => false), delay(graceMs).then(() => true)]);
1718
- if (again && this.child === child) child.kill("SIGKILL");
1819
+ if (again && this.child === child) signalTree(child, "SIGKILL");
1719
1820
  await Promise.race([exited, delay(graceMs)]);
1720
1821
  }
1822
+ if (child.exitCode !== null || child.signalCode !== null) await reaped;
1721
1823
  await this.lineChain;
1722
1824
  }
1723
1825
  /** Waits until every stdout line seen so far (and any turn end it caused) is handled. */
@@ -1783,18 +1885,25 @@ ${text}`;
1783
1885
  resume: this.record.claudeSessionId,
1784
1886
  appendSystemPrompt: runnerSystemPrompt({
1785
1887
  workBranch: this.record.workBranch,
1786
- baseRef: this.record.baseRef
1888
+ baseRef: this.record.baseRef,
1889
+ cwd: this.record.cwd
1787
1890
  }),
1788
1891
  features
1789
1892
  });
1790
- const child = spawn2(bin, args, {
1893
+ const child = spawn3(bin, args, {
1791
1894
  cwd: this.record.cwd,
1792
1895
  env: process.env,
1793
1896
  stdio: ["pipe", "pipe", "pipe"],
1794
- 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
1795
1901
  });
1796
1902
  await new Promise((resolve, reject) => {
1797
- child.once("spawn", () => resolve());
1903
+ child.once("spawn", () => {
1904
+ trackGroup(child);
1905
+ resolve();
1906
+ });
1798
1907
  child.once(
1799
1908
  "error",
1800
1909
  (err) => reject(new Error(`Could not start Claude Code (${bin}): ${err.message}`))
@@ -1802,6 +1911,7 @@ ${text}`;
1802
1911
  });
1803
1912
  this.child = child;
1804
1913
  this.stopping = null;
1914
+ this.reapGraceMs = void 0;
1805
1915
  this.stderrTail = "";
1806
1916
  this.sawResultSinceSpawn = false;
1807
1917
  this.spawnedWithResume = !!this.record.claudeSessionId;
@@ -1810,6 +1920,9 @@ ${text}`;
1810
1920
  `session ${this.sessionId}: Claude Code started${this.record.claudeSessionId ? " (resumed)" : ""}`,
1811
1921
  { pid: child.pid }
1812
1922
  );
1923
+ this.groupReaped = new Promise(
1924
+ (resolve) => child.once("exit", () => void reapGroup(child.pid, this.reapGraceMs).then(resolve))
1925
+ );
1813
1926
  child.stdin.on("error", () => void 0);
1814
1927
  child.stderr.setEncoding("utf8").on("data", (d) => {
1815
1928
  this.stderrTail = (this.stderrTail + d).slice(-4e3);
@@ -2824,9 +2937,9 @@ function formatChecks(checks) {
2824
2937
 
2825
2938
  // src/lock.ts
2826
2939
  import { mkdir as mkdir7, open, readFile as readFile4, rm as rm6 } from "node:fs/promises";
2827
- import { join as join6 } from "node:path";
2940
+ import { join as join7 } from "node:path";
2828
2941
  function lockFile(stateDir) {
2829
- return join6(stateDir, "daemon.pid");
2942
+ return join7(stateDir, "daemon.pid");
2830
2943
  }
2831
2944
  function pidAlive(pid) {
2832
2945
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -2882,7 +2995,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
2882
2995
  }
2883
2996
 
2884
2997
  // src/pairing.ts
2885
- import { spawn as spawn3 } from "node:child_process";
2998
+ import { spawn as spawn4 } from "node:child_process";
2886
2999
  async function pair(api, opts) {
2887
3000
  const start2 = await api.startPairing({ name: opts.name, platform: RUNNER_PLATFORM });
2888
3001
  opts.ui.showCode(start2.userCode, start2.verificationUrl, start2.expiresInSeconds);
@@ -2946,7 +3059,7 @@ function openUrl(url) {
2946
3059
  if (!/^https?:\/\//i.test(url)) return;
2947
3060
  const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
2948
3061
  try {
2949
- const child = spawn3(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
3062
+ const child = spawn4(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
2950
3063
  child.on("error", () => void 0);
2951
3064
  child.unref();
2952
3065
  } catch {
@@ -3140,6 +3253,7 @@ async function start(opts) {
3140
3253
  };
3141
3254
  process.on("SIGINT", onSignal);
3142
3255
  process.on("SIGTERM", onSignal);
3256
+ process.on("SIGHUP", onSignal);
3143
3257
  let exit;
3144
3258
  try {
3145
3259
  exit = await daemon.run();