@discovery-tree/runner 0.0.0-stage → 0.1.1

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 +263 -2
  2. package/dist/cli.js +2639 -0
  3. package/package.json +27 -4
package/dist/cli.js ADDED
@@ -0,0 +1,2639 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { hostname } from "node:os";
5
+ import { createInterface as createInterface2 } from "node:readline/promises";
6
+ import { parseArgs } from "node:util";
7
+
8
+ // ../contracts/src/ui-evidence.ts
9
+ var UI_EVIDENCE_EXPECTATION = [
10
+ "Visual evidence (required for user-visible changes): if your change alters anything a person sees or interacts with \u2014 a component, layout, styling, copy, empty state, or navigation \u2014 capture a screenshot of the change and embed it in the pull request description using markdown image syntax. Attach one image per state you changed, including before/after when the change modifies existing UI, and both themes when the product has light and dark.",
11
+ "Prefer uploading images to the pull request itself (drag-and-drop or the GitHub attachment endpoint) so they are served from GitHub. If your platform hosts the screenshots it captures and cannot upload them, embed its own artifact address instead of dropping the evidence \u2014 that is shown to reviewers too, provided the host is one the workspace already trusts. An image on some other third-party host is not shown, so do not settle for one. Write a short caption in the alt text saying what the image shows.",
12
+ "If you cannot capture a screenshot \u2014 the app will not start, or the change is not reachable in a running build \u2014 say so explicitly in the pull request description and explain what a reviewer should check instead. Do not silently omit it."
13
+ ].join("\n");
14
+
15
+ // ../contracts/src/agent-prompt.ts
16
+ var DEFAULT_AGENT_SYSTEM_PROMPT = [
17
+ "You are assisting with a workstream task tracked in Discovery Tree. Discovery Tree is what dispatched this run; do not take it for the subject of the work.",
18
+ "The task below gives the workstream and the repository this work belongs to. Take the subject of the work from those and from what the task says, never from the tooling around it \u2014 and if they do not make the subject clear, say so in your response rather than guessing at it.",
19
+ "Working expectations: prefer small, focused changes; run tests when relevant; open a PR when the workflow expects it.",
20
+ "Reporting: summarize progress in short, concrete steps (what changed, what is next, blockers). The product UI shows orchestration milestones alongside provider status.",
21
+ UI_EVIDENCE_EXPECTATION
22
+ ].join("\n");
23
+
24
+ // ../contracts/src/agent-runs.ts
25
+ var AGENT_RUN_MAX_WALL_MS = 6 * 60 * 60 * 1e3;
26
+ var AGENT_RUN_ABANDONED_GRACE_MS = 30 * 60 * 1e3;
27
+
28
+ // ../contracts/src/agent-runner.ts
29
+ var RUNNER_PROTOCOL_VERSION = 1;
30
+ var RUNNER_COMMAND_POLL_MAX_WAIT_MS = 25e3;
31
+ var RUNNER_EVENTS_MAX_BATCH = 200;
32
+ var RUNNER_EVENT_TEXT_MAX_LENGTH = 64e3;
33
+ var RUNNER_EVENTS_MAX_BODY_BYTES = 8 * 1024 * 1024;
34
+
35
+ // src/version.ts
36
+ var RUNNER_VERSION = true ? "0.1.1" : "0.0.0-dev";
37
+ var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
38
+
39
+ // src/api.ts
40
+ var ApiError = class extends Error {
41
+ constructor(status2, path, body, retryAfterMs = null) {
42
+ super(`${path} answered ${status2}${body ? `: ${body.slice(0, 200)}` : ""}`);
43
+ this.status = status2;
44
+ this.path = path;
45
+ this.body = body;
46
+ this.retryAfterMs = retryAfterMs;
47
+ this.name = "ApiError";
48
+ }
49
+ };
50
+ function parseRetryAfter(value, now = Date.now()) {
51
+ if (!value) return null;
52
+ const trimmed = value.trim();
53
+ let ms;
54
+ if (/^\d+(\.\d+)?$/.test(trimmed)) ms = Number(trimmed) * 1e3;
55
+ else {
56
+ const at = Date.parse(trimmed);
57
+ if (Number.isNaN(at)) return null;
58
+ ms = at - now;
59
+ }
60
+ return Math.min(Math.max(0, Math.round(ms)), 5 * 6e4);
61
+ }
62
+ var UnauthorizedError = class extends ApiError {
63
+ constructor(path, body) {
64
+ super(401, path, body);
65
+ this.name = "UnauthorizedError";
66
+ }
67
+ };
68
+ function isRetryable(err) {
69
+ if (err instanceof UnauthorizedError) return false;
70
+ if (err instanceof ApiError) return err.status >= 500 || err.status === 429 || err.status === 408;
71
+ return true;
72
+ }
73
+ var RunnerApi = class {
74
+ constructor(opts) {
75
+ this.opts = opts;
76
+ this.base = `${opts.server.replace(/\/+$/, "")}/api`;
77
+ this.fetchImpl = opts.fetch ?? fetch;
78
+ this.timeoutMs = opts.timeoutMs ?? 3e4;
79
+ }
80
+ base;
81
+ fetchImpl;
82
+ timeoutMs;
83
+ startPairing(body) {
84
+ return this.request("POST", "/runner/pair/start", body, { auth: false });
85
+ }
86
+ pollPairing(deviceCode) {
87
+ return this.request("POST", "/runner/pair/poll", { deviceCode }, { auth: false });
88
+ }
89
+ heartbeat(body) {
90
+ return this.request("POST", "/runner/heartbeat", body);
91
+ }
92
+ /** Long poll: the server holds the request up to `waitMs` when there is nothing to do. */
93
+ pollCommands(waitMs, signal) {
94
+ return this.request("GET", `/runner/commands?waitMs=${waitMs}`, void 0, {
95
+ timeoutMs: waitMs + this.timeoutMs,
96
+ signal
97
+ });
98
+ }
99
+ ackCommand(commandId, body) {
100
+ return this.request("POST", `/runner/commands/${encodeURIComponent(commandId)}/ack`, body);
101
+ }
102
+ postEvents(sessionId, body) {
103
+ return this.request("POST", `/runner/sessions/${encodeURIComponent(sessionId)}/events`, body);
104
+ }
105
+ /** Unauthenticated reachability check (`dt-runner status`). */
106
+ async health() {
107
+ try {
108
+ await this.request("GET", "/health", void 0, { auth: false, timeoutMs: 1e4 });
109
+ return true;
110
+ } catch {
111
+ return false;
112
+ }
113
+ }
114
+ async request(method, path, body, opts = {}) {
115
+ const headers = {
116
+ accept: "application/json",
117
+ "user-agent": `dt-runner/${RUNNER_VERSION}`
118
+ };
119
+ if (body !== void 0) headers["content-type"] = "application/json";
120
+ if (opts.auth !== false) {
121
+ if (!this.opts.token) throw new UnauthorizedError(path, "no runner token");
122
+ headers.authorization = `Bearer ${this.opts.token}`;
123
+ }
124
+ const timeout = AbortSignal.timeout(opts.timeoutMs ?? this.timeoutMs);
125
+ const signal = opts.signal ? AbortSignal.any([timeout, opts.signal]) : timeout;
126
+ const res = await this.fetchImpl(`${this.base}${path}`, {
127
+ method,
128
+ headers,
129
+ body: body === void 0 ? void 0 : JSON.stringify(body),
130
+ signal
131
+ });
132
+ const text = await res.text();
133
+ if (res.status === 401) throw new UnauthorizedError(path, text);
134
+ if (!res.ok) {
135
+ throw new ApiError(res.status, path, text, parseRetryAfter(res.headers.get("retry-after")));
136
+ }
137
+ if (!text) return void 0;
138
+ try {
139
+ return JSON.parse(text);
140
+ } catch {
141
+ throw new ApiError(res.status, path, "response was not JSON");
142
+ }
143
+ }
144
+ };
145
+
146
+ // src/exec.ts
147
+ import { spawn } from "node:child_process";
148
+ import { access, constants } from "node:fs/promises";
149
+ import { delimiter, isAbsolute, join } from "node:path";
150
+ function exec(cmd, args, opts = {}) {
151
+ return new Promise((resolve, reject) => {
152
+ const child = spawn(cmd, args, {
153
+ cwd: opts.cwd,
154
+ env: opts.env ?? process.env,
155
+ stdio: ["pipe", "pipe", "pipe"],
156
+ windowsHide: true
157
+ });
158
+ let stdout = "";
159
+ let stderr = "";
160
+ let timer;
161
+ if (opts.timeoutMs) {
162
+ timer = setTimeout(() => child.kill("SIGKILL"), opts.timeoutMs);
163
+ }
164
+ child.stdout.setEncoding("utf8").on("data", (d) => stdout += d);
165
+ child.stderr.setEncoding("utf8").on("data", (d) => stderr += d);
166
+ child.on("error", (err) => {
167
+ if (timer) clearTimeout(timer);
168
+ reject(err);
169
+ });
170
+ child.on("close", (code) => {
171
+ if (timer) clearTimeout(timer);
172
+ resolve({ code, stdout, stderr });
173
+ });
174
+ child.stdin.on("error", () => void 0);
175
+ child.stdin.end(opts.input ?? "");
176
+ });
177
+ }
178
+ async function which(name, env = process.env) {
179
+ if (isAbsolute(name) || name.includes("/")) {
180
+ return await isExecutable(name) ? name : null;
181
+ }
182
+ const dirs = (env.PATH ?? env.Path ?? "").split(delimiter).filter(Boolean);
183
+ const exts = process.platform === "win32" ? [".exe", ""] : [""];
184
+ for (const dir of dirs) {
185
+ for (const ext of exts) {
186
+ const candidate = join(dir, name + ext);
187
+ if (await isExecutable(candidate)) return candidate;
188
+ }
189
+ }
190
+ return null;
191
+ }
192
+ async function isExecutable(file) {
193
+ try {
194
+ await access(file, process.platform === "win32" ? constants.F_OK : constants.X_OK);
195
+ return true;
196
+ } catch {
197
+ return false;
198
+ }
199
+ }
200
+
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
+ }
215
+ }
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
+ }
228
+ }
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
+ }
239
+ }
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
+ };
264
+ }
265
+ return { claudeVersion: version, claudeReady: auth.loggedIn, claudeProblem: null };
266
+ }
267
+ var MODEL_NAME = /^[A-Za-z0-9][\w.:@/[\]-]{0,199}$/;
268
+ function isValidModelName(model) {
269
+ return MODEL_NAME.test(model);
270
+ }
271
+ function assertValidModel(model) {
272
+ if (model && !isValidModelName(model)) {
273
+ throw new Error(
274
+ `The model "${model.slice(0, 80)}" is not a valid Claude Code model name; the runner refused to start it.`
275
+ );
276
+ }
277
+ }
278
+ function claudeArgs(launch) {
279
+ const args = [
280
+ "-p",
281
+ "--input-format",
282
+ "stream-json",
283
+ "--output-format",
284
+ "stream-json",
285
+ "--verbose",
286
+ "--include-partial-messages"
287
+ ];
288
+ if (launch.permissionMode === "bypassPermissions") {
289
+ args.push("--dangerously-skip-permissions");
290
+ } else {
291
+ args.push("--permission-mode", launch.permissionMode);
292
+ }
293
+ if (launch.features.permissionPrompts) args.push("--permission-prompts", "none");
294
+ if (launch.features.settingSources && !launch.loadProjectSettings) {
295
+ args.push("--setting-sources", "user");
296
+ }
297
+ if (launch.model) {
298
+ assertValidModel(launch.model);
299
+ args.push(`--model=${launch.model}`);
300
+ }
301
+ if (launch.resume) args.push("--resume", launch.resume);
302
+ if (launch.appendSystemPrompt) args.push("--append-system-prompt", launch.appendSystemPrompt);
303
+ if (launch.disallowedTools?.length) args.push("--disallowedTools", ...launch.disallowedTools);
304
+ if (launch.allowedTools.length) args.push("--allowedTools", ...launch.allowedTools);
305
+ return args;
306
+ }
307
+ function runnerSystemPrompt(input) {
308
+ if (!input.workBranch) {
309
+ return [
310
+ "You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
311
+ "Your working directory is a scratch directory created for this task; it is not a git repository."
312
+ ].join(" ");
313
+ }
314
+ return [
315
+ "You are running a Discovery Tree task through the person\u2019s local Discovery Tree runner.",
316
+ `Your working directory is a git worktree managed by the runner, on branch \`${input.workBranch}\``,
317
+ input.baseRef ? `(created from \`${input.baseRef}\`).` : ".",
318
+ "Commit your work to this branch as you go, with clear, descriptive commit messages.",
319
+ "Do not push, do not switch, create or delete branches, and do not rewrite commits that may",
320
+ "already be pushed: the runner commits anything left over and pushes this branch for you",
321
+ "at the end of every turn."
322
+ ].join(" ");
323
+ }
324
+
325
+ // src/config.ts
326
+ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
327
+ import { homedir } from "node:os";
328
+ import { dirname, join as join2 } from "node:path";
329
+ function runnerPaths(env = process.env) {
330
+ const home = homedir();
331
+ if (process.platform === "win32") {
332
+ const roaming = env.APPDATA || join2(home, "AppData", "Roaming");
333
+ const local = env.LOCALAPPDATA || join2(home, "AppData", "Local");
334
+ return {
335
+ configFile: join2(roaming, "discovery-tree", "runner.json"),
336
+ dataDir: join2(local, "discovery-tree", "runner"),
337
+ stateDir: join2(local, "discovery-tree", "runner", "state")
338
+ };
339
+ }
340
+ const config = env.XDG_CONFIG_HOME || join2(home, ".config");
341
+ const data = env.XDG_DATA_HOME || join2(home, ".local", "share");
342
+ const state = env.XDG_STATE_HOME || join2(home, ".local", "state");
343
+ return {
344
+ configFile: join2(config, "discovery-tree", "runner.json"),
345
+ dataDir: join2(data, "discovery-tree", "runner"),
346
+ stateDir: join2(state, "discovery-tree", "runner")
347
+ };
348
+ }
349
+ var PERMISSION_MODES = [
350
+ "acceptEdits",
351
+ "auto",
352
+ "default",
353
+ "manual",
354
+ "dontAsk",
355
+ "plan",
356
+ "bypassPermissions"
357
+ ];
358
+ var DEFAULT_ALLOWED_TOOLS = [
359
+ "Read",
360
+ "Edit",
361
+ "MultiEdit",
362
+ "Write",
363
+ "Glob",
364
+ "Grep",
365
+ "LS",
366
+ "NotebookEdit",
367
+ "TodoWrite",
368
+ "Task",
369
+ "Bash(git status *)",
370
+ "Bash(git diff *)",
371
+ "Bash(git log *)",
372
+ "Bash(git show *)",
373
+ "Bash(git add *)",
374
+ "Bash(git commit *)",
375
+ "Bash(git restore *)",
376
+ "Bash(git rm *)",
377
+ "Bash(git mv *)",
378
+ "Bash(git stash *)",
379
+ "Bash(git blame *)",
380
+ "Bash(git grep *)",
381
+ "Bash(npm *)",
382
+ "Bash(npx *)",
383
+ "Bash(pnpm *)",
384
+ "Bash(yarn *)",
385
+ "Bash(node *)",
386
+ "Bash(tsc *)",
387
+ "Bash(python *)",
388
+ "Bash(python3 *)",
389
+ "Bash(pip *)",
390
+ "Bash(pytest *)",
391
+ "Bash(make *)",
392
+ "Bash(cargo *)",
393
+ "Bash(go *)",
394
+ "Bash(ls *)",
395
+ "Bash(cat *)",
396
+ "Bash(head *)",
397
+ "Bash(tail *)",
398
+ "Bash(wc *)",
399
+ "Bash(grep *)",
400
+ "Bash(rg *)",
401
+ "Bash(echo *)",
402
+ "Bash(pwd)",
403
+ "Bash(mkdir *)",
404
+ "Bash(touch *)",
405
+ "Bash(diff *)",
406
+ "Bash(sort *)",
407
+ "Bash(uniq *)",
408
+ "Bash(which *)",
409
+ "Bash(true)"
410
+ ];
411
+ var PROTECTED_PATHS = [
412
+ "~/.ssh/**",
413
+ "~/.aws/**",
414
+ "~/.config/gcloud/**",
415
+ "~/.azure/**",
416
+ "~/.gnupg/**",
417
+ "~/.netrc",
418
+ "~/.git-credentials",
419
+ "~/.config/gh/**",
420
+ "~/.docker/config.json",
421
+ "~/.kube/**",
422
+ "~/.npmrc",
423
+ "~/.pypirc",
424
+ // The runner's own token.
425
+ "~/.config/discovery-tree/**",
426
+ // Claude Code's sign-in and account file.
427
+ "~/.claude/.credentials.json",
428
+ "~/.claude.json"
429
+ ];
430
+ var PROTECTED_FROM_EDIT = [
431
+ "~/.claude/**",
432
+ // Shell startup files and git config: an edit there runs, or changes what runs, in every
433
+ // later shell or git command the person uses outside the agent.
434
+ "~/.bashrc",
435
+ "~/.bash_profile",
436
+ "~/.profile",
437
+ "~/.zshrc",
438
+ "~/.zprofile",
439
+ "~/.zshenv",
440
+ "~/.config/fish/**",
441
+ "~/.gitconfig",
442
+ "~/.config/git/**"
443
+ ];
444
+ var DEFAULT_DISALLOWED_TOOLS = [
445
+ ...PROTECTED_PATHS.map((p) => `Read(${p})`),
446
+ ...[...PROTECTED_PATHS, ...PROTECTED_FROM_EDIT].map((p) => `Edit(${p})`)
447
+ ];
448
+ function configDirRules(configFile, platform = process.platform) {
449
+ if (platform === "win32") return [];
450
+ const dir = dirname(configFile);
451
+ if (!dir.startsWith("/")) return [];
452
+ return [`Read(/${dir}/**)`, `Edit(/${dir}/**)`];
453
+ }
454
+ var DEFAULT_SERVER_URL = "https://discovery-tree-backend.onrender.com";
455
+ var DEFAULT_MAX_SESSIONS = 2;
456
+ var DEFAULT_IDLE_TIMEOUT_MINUTES = 15;
457
+ async function readConfigFile(file) {
458
+ let raw;
459
+ try {
460
+ raw = await readFile(file, "utf8");
461
+ } catch (err) {
462
+ if (err.code === "ENOENT") return null;
463
+ throw err;
464
+ }
465
+ try {
466
+ return JSON.parse(raw);
467
+ } catch {
468
+ throw new Error(`${file} is not valid JSON; fix it or run \`dt-runner logout\` to start over.`);
469
+ }
470
+ }
471
+ async function writeConfigFile(file, config) {
472
+ await mkdir(dirname(file), { recursive: true, mode: 448 });
473
+ await writeFile(file, JSON.stringify(config, null, 2) + "\n", { mode: 384 });
474
+ await chmod(file, 384).catch(() => void 0);
475
+ }
476
+ async function deleteConfigFile(file) {
477
+ try {
478
+ await rm(file);
479
+ return true;
480
+ } catch (err) {
481
+ if (err.code === "ENOENT") return false;
482
+ throw err;
483
+ }
484
+ }
485
+ function normalizeServerUrl(url) {
486
+ const trimmed = url.trim().replace(/\/+$/, "");
487
+ return trimmed.replace(/\/api(\/health)?$/, "");
488
+ }
489
+ var MAX_SESSIONS_LIMIT = 64;
490
+ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPaths(env)) {
491
+ const mode = file?.permissionMode ?? "acceptEdits";
492
+ if (!PERMISSION_MODES.includes(mode)) {
493
+ throw new Error(
494
+ `permissionMode "${mode}" in ${paths.configFile} is not one of ${PERMISSION_MODES.join(", ")}.`
495
+ );
496
+ }
497
+ const maxSessions = overrides.maxSessions ?? file?.maxSessions ?? DEFAULT_MAX_SESSIONS;
498
+ if (!Number.isInteger(maxSessions) || maxSessions < 1 || maxSessions > MAX_SESSIONS_LIMIT) {
499
+ throw new Error(
500
+ `maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
501
+ );
502
+ }
503
+ const allowed = [
504
+ ...file?.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
505
+ ...file?.extraAllowedTools ?? []
506
+ ];
507
+ const disallowed = [
508
+ ...file?.disallowedTools ?? [
509
+ ...DEFAULT_DISALLOWED_TOOLS,
510
+ ...configDirRules(paths.configFile)
511
+ ],
512
+ ...file?.extraDisallowedTools ?? []
513
+ ];
514
+ return {
515
+ server: normalizeServerUrl(env.DT_SERVER_URL || file?.server || DEFAULT_SERVER_URL),
516
+ runnerId: file?.runnerId ?? null,
517
+ token: env.DT_RUNNER_TOKEN || file?.token || null,
518
+ name: file?.name ?? null,
519
+ maxSessions,
520
+ reposDir: overrides.reposDir ?? file?.reposDir ?? join2(paths.dataDir, "repos"),
521
+ worktreesDir: file?.worktreesDir ?? join2(paths.dataDir, "worktrees"),
522
+ permissionMode: mode,
523
+ allowedTools: [...new Set(allowed)],
524
+ disallowedTools: [...new Set(disallowed)],
525
+ loadProjectSettings: file?.loadProjectSettings === true,
526
+ gitProtocol: file?.gitProtocol === "ssh" ? "ssh" : "https",
527
+ idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
528
+ stateDir: paths.stateDir,
529
+ configFile: paths.configFile
530
+ };
531
+ }
532
+
533
+ // src/backoff.ts
534
+ function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
535
+ const ceiling = Math.min(maxMs, baseMs * 2 ** Math.min(attempt, 20));
536
+ return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
537
+ }
538
+ function sleep(ms, signal) {
539
+ return new Promise((resolve) => {
540
+ if (signal?.aborted) return resolve();
541
+ const timer = setTimeout(done, ms);
542
+ function done() {
543
+ clearTimeout(timer);
544
+ signal?.removeEventListener("abort", done);
545
+ resolve();
546
+ }
547
+ signal?.addEventListener("abort", done, { once: true });
548
+ });
549
+ }
550
+
551
+ // src/session-manager.ts
552
+ import { mkdir as mkdir5, rm as rm4 } from "node:fs/promises";
553
+
554
+ // src/git.ts
555
+ import { mkdir as mkdir2, rm as rm2, stat } from "node:fs/promises";
556
+ import { dirname as dirname2, join as join3 } from "node:path";
557
+
558
+ // src/log.ts
559
+ function createLogger(opts = {}) {
560
+ const write = opts.write ?? ((line) => process.stdout.write(line + "\n"));
561
+ const emit = (level, msg, fields) => {
562
+ if (level === "debug" && !opts.verbose) return;
563
+ const safe = fields ? redactFields(fields) : void 0;
564
+ if (opts.json) {
565
+ write(JSON.stringify({ time: (/* @__PURE__ */ new Date()).toISOString(), level, msg, ...safe }));
566
+ return;
567
+ }
568
+ const time = (/* @__PURE__ */ new Date()).toISOString().slice(11, 19);
569
+ const tag = level === "info" ? "" : ` ${level.toUpperCase()}`;
570
+ 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(" ") : "";
571
+ write(`${time}${tag} ${msg}${extra.trimEnd() === "" ? "" : extra}`);
572
+ };
573
+ return {
574
+ debug: (m, f) => emit("debug", m, f),
575
+ info: (m, f) => emit("info", m, f),
576
+ warn: (m, f) => emit("warn", m, f),
577
+ error: (m, f) => emit("error", m, f)
578
+ };
579
+ }
580
+ var SECRET_KEY = /token|secret|password|authorization/i;
581
+ function redactFields(fields) {
582
+ const out = {};
583
+ for (const [k, v] of Object.entries(fields)) out[k] = SECRET_KEY.test(k) ? "[redacted]" : v;
584
+ return out;
585
+ }
586
+ function scrubSecrets(text) {
587
+ 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, "***");
588
+ }
589
+
590
+ // src/git.ts
591
+ var GitError = class extends Error {
592
+ constructor(args, result) {
593
+ super(gitErrorMessage(args, result));
594
+ this.args = args;
595
+ this.result = result;
596
+ this.name = "GitError";
597
+ }
598
+ };
599
+ function gitErrorMessage(args, result) {
600
+ const detail = (result.stderr || result.stdout).trim().split("\n").filter(Boolean).slice(-3).join(" ");
601
+ return scrubSecrets(`git ${args[0]} failed${detail ? `: ${detail}` : ""}`).slice(0, 500);
602
+ }
603
+ var gitEnv = () => ({
604
+ ...process.env,
605
+ GIT_TERMINAL_PROMPT: "0",
606
+ GCM_INTERACTIVE: "never",
607
+ GIT_ASKPASS: process.env.GIT_ASKPASS ?? ""
608
+ });
609
+ async function git(cwd, args, timeoutMs = 10 * 6e4) {
610
+ const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs });
611
+ if (res.code !== 0) throw new GitError(args, res);
612
+ return res.stdout.trim();
613
+ }
614
+ async function gitOk(cwd, args) {
615
+ const res = await exec("git", args, { cwd, env: gitEnv(), timeoutMs: 6e4 });
616
+ return res.code === 0;
617
+ }
618
+ var REPOSITORY_HOST = "github.com";
619
+ function parseRepoUrl(url) {
620
+ try {
621
+ const u = new URL(url);
622
+ if (u.protocol !== "https:" || u.hostname.toLowerCase() !== REPOSITORY_HOST) return null;
623
+ if (u.port || u.username || u.password || u.search || u.hash) return null;
624
+ const parts = u.pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "").split("/");
625
+ if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
626
+ if (!/^[\w.-]+$/.test(parts[0]) || !/^[\w.-]+$/.test(parts[1])) return null;
627
+ if (parts.some((p) => p === "." || p === "..")) return null;
628
+ return { host: REPOSITORY_HOST, owner: parts[0], repo: parts[1] };
629
+ } catch {
630
+ return null;
631
+ }
632
+ }
633
+ function repositoryUrlError(url) {
634
+ return `Repository URL ${scrubSecrets(url).slice(0, 200)} is not a https://github.com/<owner>/<repo> URL; this runner only works on GitHub repositories.`;
635
+ }
636
+ function cloneUrl(ref, protocol) {
637
+ return protocol === "ssh" ? `git@${ref.host}:${ref.owner}/${ref.repo}.git` : `https://${ref.host}/${ref.owner}/${ref.repo}.git`;
638
+ }
639
+ var UNSAFE_REF = /[\s~^:?*[\\\x00-\x1f]|\.\.|@\{|\/\/|\.lock$|\/$/;
640
+ function assertSafeRef(name, what) {
641
+ if (!name || name.startsWith("-") || UNSAFE_REF.test(name)) {
642
+ throw new Error(`${what} "${name}" is not a valid branch name.`);
643
+ }
644
+ }
645
+ var repoLocks = /* @__PURE__ */ new Map();
646
+ function withRepoLock(dir, fn) {
647
+ const prev = repoLocks.get(dir) ?? Promise.resolve();
648
+ const next = prev.catch(() => void 0).then(fn);
649
+ repoLocks.set(dir, next);
650
+ const release = () => {
651
+ if (repoLocks.get(dir) === next) repoLocks.delete(dir);
652
+ };
653
+ next.then(release, release);
654
+ return next;
655
+ }
656
+ async function exists(p) {
657
+ try {
658
+ await stat(p);
659
+ return true;
660
+ } catch {
661
+ return false;
662
+ }
663
+ }
664
+ async function prepareWorktree(input) {
665
+ const ref = parseRepoUrl(input.url);
666
+ if (!ref) throw new Error(repositoryUrlError(input.url));
667
+ assertSafeRef(input.workBranch, "Work branch");
668
+ if (input.baseRef) assertSafeRef(input.baseRef, "Base branch");
669
+ const repoDir = join3(input.reposDir, ref.owner, ref.repo);
670
+ const worktree = join3(input.worktreesDir, input.sessionId);
671
+ return withRepoLock(repoDir, async () => {
672
+ if (!await exists(join3(repoDir, ".git"))) {
673
+ await mkdir2(dirname2(repoDir), { recursive: true });
674
+ await rm2(repoDir, { recursive: true, force: true });
675
+ await git(dirname2(repoDir), [
676
+ "clone",
677
+ "--no-checkout",
678
+ cloneUrl(ref, input.protocol),
679
+ repoDir
680
+ ]);
681
+ } else {
682
+ const wanted = cloneUrl(ref, input.protocol);
683
+ const current = await exec("git", ["config", "--get", "remote.origin.url"], {
684
+ cwd: repoDir,
685
+ env: gitEnv()
686
+ });
687
+ if (current.stdout.trim() !== wanted) {
688
+ await git(repoDir, ["remote", "set-url", "origin", wanted]);
689
+ }
690
+ await git(repoDir, ["fetch", "--prune", "origin"]);
691
+ }
692
+ const baseRef = input.baseRef ?? await defaultBranch(repoDir);
693
+ let start2 = `origin/${baseRef}`;
694
+ if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${start2}^{commit}`])) {
695
+ if (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${baseRef}^{commit}`])) {
696
+ throw new Error(`Base branch ${baseRef} was not found on origin.`);
697
+ }
698
+ start2 = baseRef;
699
+ }
700
+ const baseSha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
701
+ if (await exists(worktree)) {
702
+ await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
703
+ await rm2(worktree, { recursive: true, force: true });
704
+ }
705
+ await gitOk(repoDir, ["worktree", "prune"]);
706
+ await mkdir2(input.worktreesDir, { recursive: true });
707
+ await git(repoDir, ["worktree", "add", "--no-track", "-B", input.workBranch, worktree, start2]);
708
+ return { repoDir, worktree, baseRef, baseSha };
709
+ });
710
+ }
711
+ async function defaultBranch(repoDir) {
712
+ const read = async () => {
713
+ const res = await exec("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], {
714
+ cwd: repoDir,
715
+ env: gitEnv()
716
+ });
717
+ return res.code === 0 ? res.stdout.trim().replace(/^origin\//, "") : null;
718
+ };
719
+ const known = await read();
720
+ if (known) return known;
721
+ await gitOk(repoDir, ["remote", "set-head", "origin", "--auto"]);
722
+ return await read() ?? "main";
723
+ }
724
+ async function commitAndPush(input) {
725
+ const { worktree } = input;
726
+ let committed = false;
727
+ try {
728
+ const dirty = (await git(worktree, ["status", "--porcelain"])).length > 0;
729
+ if (dirty) {
730
+ await git(worktree, ["add", "-A"]);
731
+ const identity = await gitOk(worktree, ["config", "user.email"]) ? [] : [
732
+ "-c",
733
+ "user.name=Discovery Tree runner",
734
+ "-c",
735
+ "user.email=dt-runner@users.noreply.local"
736
+ ];
737
+ await git(worktree, [...identity, "commit", "--no-verify", "-q", "-m", input.message]);
738
+ committed = true;
739
+ }
740
+ } catch (err) {
741
+ return {
742
+ committed,
743
+ pushed: false,
744
+ error: errorText(err, "Committing the work failed"),
745
+ failedAt: "commit"
746
+ };
747
+ }
748
+ try {
749
+ const ahead = Number(await git(worktree, ["rev-list", "--count", `${input.baseSha}..HEAD`]));
750
+ if (!ahead) return { committed, pushed: false, error: null };
751
+ await git(worktree, ["push", "--quiet", "-u", "origin", `HEAD:refs/heads/${input.workBranch}`]);
752
+ return { committed, pushed: true, error: null };
753
+ } catch (err) {
754
+ return {
755
+ committed,
756
+ pushed: false,
757
+ error: errorText(err, "Pushing the work branch failed"),
758
+ failedAt: "push"
759
+ };
760
+ }
761
+ }
762
+ async function removeWorktree(repoDir, worktree) {
763
+ if (repoDir && await exists(repoDir)) {
764
+ await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
765
+ }
766
+ await rm2(worktree, { recursive: true, force: true });
767
+ if (repoDir && await exists(repoDir)) await gitOk(repoDir, ["worktree", "prune"]);
768
+ }
769
+ function errorText(err, prefix) {
770
+ const msg = err instanceof Error ? err.message : String(err);
771
+ return scrubSecrets(`${prefix}: ${msg}`).slice(0, 600);
772
+ }
773
+
774
+ // src/fsutil.ts
775
+ import { mkdir as mkdir3, readFile as readFile2, rename, writeFile as writeFile2 } from "node:fs/promises";
776
+ import { dirname as dirname3 } from "node:path";
777
+ async function writeJsonAtomic(file, value) {
778
+ await mkdir3(dirname3(file), { recursive: true });
779
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
780
+ await writeFile2(tmp, JSON.stringify(value), { mode: 384 });
781
+ await rename(tmp, file);
782
+ }
783
+ async function readJson(file) {
784
+ try {
785
+ return JSON.parse(await readFile2(file, "utf8"));
786
+ } catch (err) {
787
+ if (err.code === "ENOENT") return null;
788
+ if (err instanceof SyntaxError) return null;
789
+ throw err;
790
+ }
791
+ }
792
+
793
+ // src/outbox.ts
794
+ var MAX_REJECTED_ATTEMPTS = 3;
795
+ var SessionOutbox = class _SessionOutbox {
796
+ constructor(opts) {
797
+ this.opts = opts;
798
+ }
799
+ nextSeq = 1;
800
+ pending = [];
801
+ /** Highest seq in the batch being posted; entries up to it must not change. */
802
+ inFlightUpTo = 0;
803
+ pumping = false;
804
+ pumpTimer = null;
805
+ stopped = false;
806
+ closed = false;
807
+ stopController = new AbortController();
808
+ persistChain = Promise.resolve();
809
+ persistQueued = false;
810
+ idleWaiters = [];
811
+ /** Loads what a previous run left unsent, and resumes posting it. */
812
+ static async open(opts) {
813
+ const box = new _SessionOutbox(opts);
814
+ const saved = await readJson(opts.file);
815
+ if (saved) {
816
+ box.pending = Array.isArray(saved.pending) ? saved.pending : [];
817
+ const lastPending = box.pending.at(-1)?.seq ?? 0;
818
+ box.nextSeq = Math.max(saved.nextSeq || 1, lastPending + 1);
819
+ }
820
+ if (box.pending.length) box.schedulePump();
821
+ return box;
822
+ }
823
+ get size() {
824
+ return this.pending.length;
825
+ }
826
+ get isClosed() {
827
+ return this.closed;
828
+ }
829
+ /** The seq the next event will get (for tests and status). */
830
+ get upcomingSeq() {
831
+ return this.nextSeq;
832
+ }
833
+ enqueue(...events) {
834
+ if (this.closed) return;
835
+ for (const event of events) {
836
+ if (!this.coalesce(event)) this.pending.push({ seq: this.nextSeq++, event });
837
+ }
838
+ this.persist();
839
+ this.schedulePump();
840
+ }
841
+ /** Resolves once everything queued so far is posted (or the timeout passes). */
842
+ async flush(timeoutMs) {
843
+ if (this.stopped) return this.pending.length === 0;
844
+ if (this.pumpTimer) {
845
+ clearTimeout(this.pumpTimer);
846
+ this.pumpTimer = null;
847
+ }
848
+ if (this.pending.length && !this.closed) void this.pump();
849
+ const drained = this.pending.length === 0 || this.closed ? Promise.resolve(true) : new Promise((resolve) => this.idleWaiters.push(() => resolve(true)));
850
+ const result = await Promise.race([drained, sleep(timeoutMs).then(() => false)]);
851
+ await this.persistChain;
852
+ return result || this.pending.length === 0;
853
+ }
854
+ /** Resolves once no snapshot write is in progress. */
855
+ settled() {
856
+ return this.persistChain;
857
+ }
858
+ /** Stops posting (shutdown); what is unsent stays on disk for the next run. */
859
+ async stop() {
860
+ this.stopped = true;
861
+ this.stopController.abort();
862
+ if (this.pumpTimer) clearTimeout(this.pumpTimer);
863
+ this.pumpTimer = null;
864
+ this.persist();
865
+ await this.persistChain;
866
+ }
867
+ /** The session is gone: drop everything, post nothing more. */
868
+ discard() {
869
+ this.closed = true;
870
+ this.pending = [];
871
+ this.stopController.abort();
872
+ if (this.pumpTimer) clearTimeout(this.pumpTimer);
873
+ this.pumpTimer = null;
874
+ this.notifyIdle();
875
+ }
876
+ coalesce(event) {
877
+ if (event.type !== "assistant_delta") return false;
878
+ const last = this.pending.at(-1);
879
+ if (!last || last.seq <= this.inFlightUpTo) return false;
880
+ const prev = last.event;
881
+ if (prev.type !== "assistant_delta" || prev.providerEventId !== event.providerEventId) {
882
+ return false;
883
+ }
884
+ if (prev.offset === void 0 || event.offset === void 0) return false;
885
+ if (prev.offset + prev.text.length !== event.offset) return false;
886
+ if (prev.text.length + event.text.length > RUNNER_EVENT_TEXT_MAX_LENGTH) return false;
887
+ last.event = { ...prev, text: prev.text + event.text };
888
+ return true;
889
+ }
890
+ /** Once discarded, nothing is written: the session's folder is about to be removed. */
891
+ persist() {
892
+ if (this.persistQueued || this.closed) return;
893
+ this.persistQueued = true;
894
+ this.persistChain = this.persistChain.then(async () => {
895
+ this.persistQueued = false;
896
+ if (this.closed) return;
897
+ const snapshot = { nextSeq: this.nextSeq, pending: this.pending };
898
+ try {
899
+ await writeJsonAtomic(this.opts.file, snapshot);
900
+ } catch (err) {
901
+ this.opts.logger.warn("could not save the event outbox", {
902
+ session: this.opts.sessionId,
903
+ error: err.message
904
+ });
905
+ }
906
+ });
907
+ }
908
+ schedulePump() {
909
+ if (this.pumping || this.pumpTimer || this.stopped || this.closed) return;
910
+ this.pumpTimer = setTimeout(() => {
911
+ this.pumpTimer = null;
912
+ void this.pump();
913
+ }, this.opts.batchDelayMs ?? 100);
914
+ }
915
+ async pump() {
916
+ if (this.pumping) return;
917
+ this.pumping = true;
918
+ let attempt = 0;
919
+ let rejected = 0;
920
+ try {
921
+ while (this.pending.length && !this.stopped && !this.closed) {
922
+ const batch = takeBatch(this.pending);
923
+ const maxSeq = batch[batch.length - 1].seq;
924
+ this.inFlightUpTo = maxSeq;
925
+ try {
926
+ const res = await this.opts.poster.postEvents(this.opts.sessionId, {
927
+ events: batch.map(({ seq, event }) => ({ seq, event }))
928
+ });
929
+ const lastSeq = typeof res?.lastSeq === "number" ? res.lastSeq : maxSeq;
930
+ this.pending = this.pending.filter((e) => e.seq > lastSeq);
931
+ this.persist();
932
+ if (res?.closed) {
933
+ this.markClosed("the server closed the session");
934
+ break;
935
+ }
936
+ if (lastSeq < maxSeq) {
937
+ await sleep(
938
+ backoffDelay(attempt++, this.opts.retryBaseMs ?? 1e3),
939
+ this.stopController.signal
940
+ );
941
+ } else {
942
+ attempt = 0;
943
+ rejected = 0;
944
+ }
945
+ } catch (err) {
946
+ if (err instanceof UnauthorizedError) {
947
+ this.stopped = true;
948
+ this.opts.onUnauthorized?.(err);
949
+ break;
950
+ }
951
+ if (err instanceof ApiError && (err.status === 404 || err.status === 410)) {
952
+ this.markClosed(`the server does not know this session (${err.status})`);
953
+ break;
954
+ }
955
+ if (err instanceof ApiError && err.status === 413) {
956
+ this.opts.logger.warn("the server refused session events as too large; dropping them", {
957
+ session: this.opts.sessionId,
958
+ events: batch.length,
959
+ seqs: `${batch[0].seq}-${maxSeq}`
960
+ });
961
+ this.pending = this.pending.filter((e) => e.seq > maxSeq);
962
+ this.persist();
963
+ rejected = 0;
964
+ continue;
965
+ }
966
+ if (!isRetryable(err)) {
967
+ rejected++;
968
+ this.opts.logger.warn("the server refused session events", {
969
+ session: this.opts.sessionId,
970
+ error: err.message,
971
+ attempt: rejected
972
+ });
973
+ if (rejected >= MAX_REJECTED_ATTEMPTS) {
974
+ this.pending = this.pending.filter((e) => e.seq > maxSeq);
975
+ this.persist();
976
+ rejected = 0;
977
+ continue;
978
+ }
979
+ } else {
980
+ this.opts.logger.debug("posting session events failed; will retry", {
981
+ session: this.opts.sessionId,
982
+ error: err.message
983
+ });
984
+ }
985
+ await sleep(
986
+ backoffDelay(attempt++, this.opts.retryBaseMs ?? 1e3),
987
+ this.stopController.signal
988
+ );
989
+ } finally {
990
+ this.inFlightUpTo = 0;
991
+ }
992
+ }
993
+ } finally {
994
+ this.pumping = false;
995
+ }
996
+ if (!this.pending.length || this.closed) this.notifyIdle();
997
+ else if (!this.stopped) this.schedulePump();
998
+ }
999
+ markClosed(reason) {
1000
+ this.opts.logger.info(`session ${this.opts.sessionId}: ${reason}`);
1001
+ this.discard();
1002
+ this.opts.onClosed?.();
1003
+ }
1004
+ notifyIdle() {
1005
+ const waiters = this.idleWaiters;
1006
+ this.idleWaiters = [];
1007
+ for (const w of waiters) w();
1008
+ }
1009
+ };
1010
+ function takeBatch(pending) {
1011
+ const budget = RUNNER_EVENTS_MAX_BODY_BYTES / 2;
1012
+ let bytes = 0;
1013
+ let n = 0;
1014
+ while (n < pending.length && n < RUNNER_EVENTS_MAX_BATCH) {
1015
+ const size = Buffer.byteLength(JSON.stringify(pending[n]));
1016
+ if (n > 0 && bytes + size > budget) break;
1017
+ bytes += size;
1018
+ n++;
1019
+ }
1020
+ return pending.slice(0, n);
1021
+ }
1022
+
1023
+ // src/session.ts
1024
+ import { spawn as spawn2 } from "node:child_process";
1025
+ import { createInterface } from "node:readline";
1026
+
1027
+ // src/session-store.ts
1028
+ import { mkdir as mkdir4, readdir, rm as rm3 } from "node:fs/promises";
1029
+ import { join as join4 } from "node:path";
1030
+ var HANDLED_COMMAND_IDS_KEPT = 100;
1031
+ var SessionStore = class {
1032
+ constructor(stateDir) {
1033
+ this.stateDir = stateDir;
1034
+ }
1035
+ dir(sessionId) {
1036
+ return join4(this.stateDir, "sessions", sessionId);
1037
+ }
1038
+ outboxFile(sessionId) {
1039
+ return join4(this.dir(sessionId), "outbox.json");
1040
+ }
1041
+ async save(record) {
1042
+ record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1043
+ await writeJsonAtomic(join4(this.dir(record.sessionId), "session.json"), record);
1044
+ }
1045
+ async list() {
1046
+ const root = join4(this.stateDir, "sessions");
1047
+ await mkdir4(root, { recursive: true });
1048
+ const out = [];
1049
+ for (const entry of await readdir(root, { withFileTypes: true })) {
1050
+ if (!entry.isDirectory()) continue;
1051
+ const rec = await readJson(join4(root, entry.name, "session.json"));
1052
+ if (rec?.sessionId === entry.name) out.push(rec);
1053
+ }
1054
+ return out;
1055
+ }
1056
+ async remove(sessionId) {
1057
+ await rm3(this.dir(sessionId), { recursive: true, force: true });
1058
+ }
1059
+ /** Scratch working directory for a session without a repository. */
1060
+ scratchDir(sessionId) {
1061
+ return join4(this.stateDir, "scratch", sessionId);
1062
+ }
1063
+ };
1064
+ function assertSafeSessionId(id) {
1065
+ if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(id) || id.includes("..")) {
1066
+ throw new Error(`Session id "${id}" is not usable as a directory name.`);
1067
+ }
1068
+ }
1069
+
1070
+ // src/stream-mapper.ts
1071
+ function capText(text, max = RUNNER_EVENT_TEXT_MAX_LENGTH) {
1072
+ if (text.length <= max) return { text, truncated: false };
1073
+ const marker = "\n\u2026 [truncated by dt-runner]";
1074
+ return { text: text.slice(0, max - marker.length) + marker, truncated: true };
1075
+ }
1076
+ var ClaudeStreamMapper = class {
1077
+ /** Running offset of each live text block, by providerEventId. */
1078
+ deltaOffsets = /* @__PURE__ */ new Map();
1079
+ /** Stream block index → providerEventId for text blocks of the message streaming now. */
1080
+ streamTextKeys = /* @__PURE__ */ new Map();
1081
+ streamMessageId = null;
1082
+ streamTextCount = 0;
1083
+ /** Text blocks already seen in completed `assistant` lines, per message id. */
1084
+ completedTextCount = /* @__PURE__ */ new Map();
1085
+ /** Tool calls by id, for the name/input a result line does not repeat. */
1086
+ calls = /* @__PURE__ */ new Map();
1087
+ lastAssistantText = null;
1088
+ running = false;
1089
+ /** A new turn is starting (we wrote a user message); the next activity is not news. */
1090
+ markRunning() {
1091
+ this.running = true;
1092
+ }
1093
+ map(line) {
1094
+ const out = { events: [] };
1095
+ if (line.parent_tool_use_id) return out;
1096
+ switch (line.type) {
1097
+ case "system":
1098
+ if (line.subtype === "init" && typeof line.session_id === "string") {
1099
+ out.claudeSessionId = line.session_id;
1100
+ this.ensureRunning(out);
1101
+ }
1102
+ break;
1103
+ case "stream_event":
1104
+ this.mapStreamEvent(line, out);
1105
+ break;
1106
+ case "assistant":
1107
+ this.mapAssistant(line, out);
1108
+ break;
1109
+ case "user":
1110
+ this.mapUser(line, out);
1111
+ break;
1112
+ case "result": {
1113
+ const resultText = typeof line.result === "string" && line.result ? line.result : null;
1114
+ out.turnEnd = {
1115
+ text: resultText ?? this.lastAssistantText,
1116
+ isError: line.is_error === true || (line.subtype ?? "success") !== "success",
1117
+ subtype: typeof line.subtype === "string" ? line.subtype : null
1118
+ };
1119
+ this.endTurn();
1120
+ break;
1121
+ }
1122
+ case "control_response": {
1123
+ const res = line.response ?? {};
1124
+ if (typeof res.request_id === "string") {
1125
+ out.controlResponse = { requestId: res.request_id, ok: res.subtype === "success" };
1126
+ }
1127
+ break;
1128
+ }
1129
+ }
1130
+ return out;
1131
+ }
1132
+ ensureRunning(out) {
1133
+ if (!this.running) {
1134
+ this.running = true;
1135
+ out.turnStarted = true;
1136
+ out.events.push({ type: "status", status: "running" });
1137
+ }
1138
+ }
1139
+ mapStreamEvent(line, out) {
1140
+ const ev = line.event ?? {};
1141
+ switch (ev.type) {
1142
+ case "message_start": {
1143
+ this.ensureRunning(out);
1144
+ const id = ev.message?.id ?? line.api_message_id ?? null;
1145
+ this.beginStreamMessage(typeof id === "string" ? id : null);
1146
+ break;
1147
+ }
1148
+ case "content_block_start": {
1149
+ const id = this.streamMessageIdFor(line);
1150
+ if (ev.content_block?.type === "text" && id && typeof ev.index === "number") {
1151
+ const key = textKey(id, this.streamTextCount++);
1152
+ this.streamTextKeys.set(ev.index, key);
1153
+ const initial = typeof ev.content_block.text === "string" ? ev.content_block.text : "";
1154
+ this.deltaOffsets.set(key, 0);
1155
+ if (initial) this.pushDelta(out, key, initial);
1156
+ }
1157
+ break;
1158
+ }
1159
+ case "content_block_delta": {
1160
+ if (ev.delta?.type !== "text_delta" || typeof ev.delta.text !== "string") break;
1161
+ if (!ev.delta.text) break;
1162
+ const key = this.streamTextKeys.get(ev.index);
1163
+ if (key) this.pushDelta(out, key, ev.delta.text);
1164
+ break;
1165
+ }
1166
+ }
1167
+ }
1168
+ streamMessageIdFor(line) {
1169
+ const id = typeof line.api_message_id === "string" ? line.api_message_id : null;
1170
+ if (id && id !== this.streamMessageId) this.beginStreamMessage(id);
1171
+ return this.streamMessageId;
1172
+ }
1173
+ beginStreamMessage(id) {
1174
+ if (id === this.streamMessageId) return;
1175
+ this.streamMessageId = id;
1176
+ this.streamTextKeys.clear();
1177
+ this.streamTextCount = 0;
1178
+ }
1179
+ pushDelta(out, key, text) {
1180
+ const offset = this.deltaOffsets.get(key) ?? 0;
1181
+ this.deltaOffsets.set(key, offset + text.length);
1182
+ out.events.push({ type: "assistant_delta", providerEventId: key, text, offset });
1183
+ }
1184
+ mapAssistant(line, out) {
1185
+ const msg = line.message ?? {};
1186
+ const id = typeof msg.id === "string" ? msg.id : `msg_${line.uuid ?? Date.now()}`;
1187
+ const content = Array.isArray(msg.content) ? msg.content : [];
1188
+ this.ensureRunning(out);
1189
+ for (const block of content) {
1190
+ switch (block?.type) {
1191
+ case "text": {
1192
+ const n = this.completedTextCount.get(id) ?? 0;
1193
+ this.completedTextCount.set(id, n + 1);
1194
+ const text = typeof block.text === "string" ? block.text : "";
1195
+ if (!text.trim()) break;
1196
+ const key = textKey(id, n);
1197
+ this.deltaOffsets.delete(key);
1198
+ this.lastAssistantText = text;
1199
+ out.events.push({
1200
+ type: "assistant_message",
1201
+ providerEventId: key,
1202
+ text: capText(text).text
1203
+ });
1204
+ break;
1205
+ }
1206
+ case "thinking":
1207
+ case "redacted_thinking": {
1208
+ const text = typeof block.thinking === "string" && block.thinking.trim() ? block.thinking : null;
1209
+ out.events.push({
1210
+ type: "thinking",
1211
+ providerEventId: `${id}:thinking:${this.thinkingIndex(id)}`,
1212
+ text: text === null ? null : capText(text).text
1213
+ });
1214
+ break;
1215
+ }
1216
+ case "tool_use":
1217
+ case "server_tool_use":
1218
+ case "mcp_tool_use": {
1219
+ if (typeof block.id !== "string") break;
1220
+ const name = block.type === "mcp_tool_use" && block.server_name ? `${block.server_name}.${block.name}` : String(block.name ?? "tool");
1221
+ this.calls.set(block.id, { name, input: block.input });
1222
+ out.events.push({
1223
+ type: "tool_call",
1224
+ providerEventId: block.id,
1225
+ tool: { callId: block.id, name, status: "running", input: block.input }
1226
+ });
1227
+ break;
1228
+ }
1229
+ }
1230
+ }
1231
+ }
1232
+ thinkingCounts = /* @__PURE__ */ new Map();
1233
+ thinkingIndex(id) {
1234
+ const n = this.thinkingCounts.get(id) ?? 0;
1235
+ this.thinkingCounts.set(id, n + 1);
1236
+ return n;
1237
+ }
1238
+ mapUser(line, out) {
1239
+ const content = line.message?.content;
1240
+ if (!Array.isArray(content)) return;
1241
+ for (const block of content) {
1242
+ if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
1243
+ const known = this.calls.get(block.tool_use_id);
1244
+ const { text, truncated } = capText(toolResultText(block.content));
1245
+ const tool = {
1246
+ callId: block.tool_use_id,
1247
+ name: known?.name ?? "tool",
1248
+ status: block.is_error ? "failed" : "completed",
1249
+ ...known ? { input: known.input } : {},
1250
+ output: text,
1251
+ ...truncated ? { truncated: true } : {}
1252
+ };
1253
+ out.events.push({ type: "tool_call", providerEventId: block.tool_use_id, tool });
1254
+ }
1255
+ }
1256
+ endTurn() {
1257
+ this.running = false;
1258
+ this.lastAssistantText = null;
1259
+ this.deltaOffsets.clear();
1260
+ this.streamTextKeys.clear();
1261
+ this.streamMessageId = null;
1262
+ this.streamTextCount = 0;
1263
+ this.completedTextCount.clear();
1264
+ this.thinkingCounts.clear();
1265
+ if (this.calls.size > 500) this.calls.clear();
1266
+ }
1267
+ };
1268
+ function textKey(messageId, n) {
1269
+ return n === 0 ? messageId : `${messageId}:${n}`;
1270
+ }
1271
+ function toolResultText(content) {
1272
+ if (typeof content === "string") return content;
1273
+ if (!Array.isArray(content)) return content == null ? "" : JSON.stringify(content);
1274
+ return content.map((b) => {
1275
+ if (b?.type === "text" && typeof b.text === "string") return b.text;
1276
+ if (b?.type === "image") return "[image]";
1277
+ return "";
1278
+ }).filter(Boolean).join("\n");
1279
+ }
1280
+
1281
+ // src/session.ts
1282
+ var AgentSession = class {
1283
+ constructor(record, deps) {
1284
+ this.record = record;
1285
+ this.deps = deps;
1286
+ }
1287
+ child = null;
1288
+ mapper = new ClaudeStreamMapper();
1289
+ /** stdout lines are handled one at a time, in order, including the async turn end. */
1290
+ lineChain = Promise.resolve();
1291
+ stopping = null;
1292
+ interruptRequested = false;
1293
+ interruptTimer = null;
1294
+ controlSeq = 0;
1295
+ stderrTail = "";
1296
+ sawResultSinceSpawn = false;
1297
+ exitWaiters = [];
1298
+ lastActivity = Date.now();
1299
+ get sessionId() {
1300
+ return this.record.sessionId;
1301
+ }
1302
+ get outbox() {
1303
+ return this.deps.outbox;
1304
+ }
1305
+ get alive() {
1306
+ return this.child !== null;
1307
+ }
1308
+ get turnActive() {
1309
+ return this.record.turnActive;
1310
+ }
1311
+ emit(...events) {
1312
+ this.deps.outbox.enqueue(...events);
1313
+ }
1314
+ /** Starts the process on the session's task (first turn). */
1315
+ async startFirstTurn(prompt) {
1316
+ await this.beginTurn(prompt);
1317
+ }
1318
+ /** The `send_message` command was already delivered (its ack was lost on the way back). */
1319
+ hasHandled(commandId) {
1320
+ return this.record.handledCommandIds?.includes(commandId) ?? false;
1321
+ }
1322
+ /**
1323
+ * Delivers a person's message: written to the live process (mid-turn is fine), or the
1324
+ * process is started again with `--resume` first.
1325
+ */
1326
+ async sendMessage(text, commandId) {
1327
+ await this.ensureProcess();
1328
+ const ids = this.record.handledCommandIds ??= [];
1329
+ ids.push(commandId);
1330
+ if (ids.length > HANDLED_COMMAND_IDS_KEPT) ids.splice(0, ids.length - HANDLED_COMMAND_IDS_KEPT);
1331
+ await this.deps.store.save(this.record);
1332
+ try {
1333
+ await this.beginTurn(text, {
1334
+ type: "user_message_echo",
1335
+ providerEventId: commandId,
1336
+ text,
1337
+ delivered: true
1338
+ });
1339
+ } catch (err) {
1340
+ const at = this.record.handledCommandIds?.lastIndexOf(commandId) ?? -1;
1341
+ if (at >= 0) this.record.handledCommandIds.splice(at, 1);
1342
+ await this.deps.store.save(this.record).catch(() => void 0);
1343
+ throw err;
1344
+ }
1345
+ }
1346
+ /**
1347
+ * Stops the current turn. Claude Code takes an `interrupt` control request on stdin (as
1348
+ * the Agent SDK sends it) and ends the turn with an `error_during_execution` result; if it
1349
+ * has not answered within the grace period, SIGINT does the same the hard way.
1350
+ */
1351
+ interrupt() {
1352
+ const child = this.child;
1353
+ if (!child || !this.record.turnActive) return false;
1354
+ this.interruptRequested = true;
1355
+ this.write({
1356
+ type: "control_request",
1357
+ request_id: `dt_interrupt_${++this.controlSeq}`,
1358
+ request: { subtype: "interrupt" }
1359
+ });
1360
+ if (this.interruptTimer) clearTimeout(this.interruptTimer);
1361
+ this.interruptTimer = setTimeout(() => {
1362
+ this.interruptTimer = null;
1363
+ if (this.child === child && this.record.turnActive) {
1364
+ this.deps.logger.warn(`session ${this.sessionId}: no answer to interrupt; sending SIGINT`);
1365
+ child.kill("SIGINT");
1366
+ }
1367
+ }, this.deps.interruptGraceMs ?? 5e3);
1368
+ return true;
1369
+ }
1370
+ /** Ends the process (closing stdin first, so Claude Code saves its session and exits). */
1371
+ async stop(reason, graceMs = 5e3) {
1372
+ const child = this.child;
1373
+ if (!child) return;
1374
+ this.stopping = reason;
1375
+ const exited = new Promise((resolve) => this.exitWaiters.push(resolve));
1376
+ child.stdin.end();
1377
+ const timedOut = await Promise.race([
1378
+ exited.then(() => false),
1379
+ delay(graceMs).then(() => true)
1380
+ ]);
1381
+ if (timedOut && this.child === child) {
1382
+ child.kill("SIGTERM");
1383
+ const again = await Promise.race([exited.then(() => false), delay(graceMs).then(() => true)]);
1384
+ if (again && this.child === child) child.kill("SIGKILL");
1385
+ await Promise.race([exited, delay(graceMs)]);
1386
+ }
1387
+ await this.lineChain;
1388
+ }
1389
+ /** Waits until every stdout line seen so far (and any turn end it caused) is handled. */
1390
+ async settled() {
1391
+ let chain;
1392
+ do {
1393
+ chain = this.lineChain;
1394
+ await chain;
1395
+ } while (chain !== this.lineChain);
1396
+ }
1397
+ /**
1398
+ * Writes a user message to a running process that is not being stopped (starting it, or
1399
+ * waiting out a stop in progress and starting it again, first). The turn counts as active
1400
+ * only once the message is written: a write that fails leaves no turn waiting for a
1401
+ * result that will never come.
1402
+ */
1403
+ async beginTurn(text, before) {
1404
+ while (!this.child || this.stopping) await this.ensureProcess();
1405
+ this.write({ type: "user", message: { role: "user", content: text } });
1406
+ this.lastActivity = Date.now();
1407
+ if (before) this.emit(before);
1408
+ if (!this.record.turnActive) {
1409
+ this.record.turnActive = true;
1410
+ this.mapper.markRunning();
1411
+ this.emit({ type: "status", status: "running" });
1412
+ await this.deps.store.save(this.record);
1413
+ }
1414
+ }
1415
+ write(message) {
1416
+ if (!this.child || this.stopping || this.child.stdin.writableEnded) {
1417
+ throw new Error("Claude Code is not running for this session.");
1418
+ }
1419
+ this.child.stdin.write(JSON.stringify(message) + "\n");
1420
+ }
1421
+ /** Resolves once the current process has exited (and its exit has been handled). */
1422
+ waitForExit() {
1423
+ if (!this.child) return Promise.resolve();
1424
+ return new Promise((resolve) => this.exitWaiters.push(resolve));
1425
+ }
1426
+ async ensureProcess() {
1427
+ while (this.child && this.stopping) await this.waitForExit();
1428
+ if (this.child) return;
1429
+ const { bin, features } = await this.deps.claude();
1430
+ const args = claudeArgs({
1431
+ permissionMode: this.deps.permissionMode,
1432
+ allowedTools: this.deps.allowedTools,
1433
+ disallowedTools: this.deps.disallowedTools,
1434
+ loadProjectSettings: this.deps.loadProjectSettings,
1435
+ model: this.record.model,
1436
+ resume: this.record.claudeSessionId,
1437
+ appendSystemPrompt: runnerSystemPrompt({
1438
+ workBranch: this.record.workBranch,
1439
+ baseRef: this.record.baseRef
1440
+ }),
1441
+ features
1442
+ });
1443
+ const child = spawn2(bin, args, {
1444
+ cwd: this.record.cwd,
1445
+ env: process.env,
1446
+ stdio: ["pipe", "pipe", "pipe"],
1447
+ windowsHide: true
1448
+ });
1449
+ await new Promise((resolve, reject) => {
1450
+ child.once("spawn", () => resolve());
1451
+ child.once(
1452
+ "error",
1453
+ (err) => reject(new Error(`Could not start Claude Code (${bin}): ${err.message}`))
1454
+ );
1455
+ });
1456
+ this.child = child;
1457
+ this.stopping = null;
1458
+ this.stderrTail = "";
1459
+ this.sawResultSinceSpawn = false;
1460
+ this.deps.logger.info(
1461
+ `session ${this.sessionId}: Claude Code started${this.record.claudeSessionId ? " (resumed)" : ""}`,
1462
+ { pid: child.pid }
1463
+ );
1464
+ child.stdin.on("error", () => void 0);
1465
+ child.stderr.setEncoding("utf8").on("data", (d) => {
1466
+ this.stderrTail = (this.stderrTail + d).slice(-4e3);
1467
+ });
1468
+ const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
1469
+ rl.on("line", (line) => {
1470
+ if (!line.trim()) return;
1471
+ let parsed;
1472
+ try {
1473
+ parsed = JSON.parse(line);
1474
+ } catch {
1475
+ this.deps.logger.debug(`session ${this.sessionId}: non-JSON output from claude`);
1476
+ return;
1477
+ }
1478
+ this.lineChain = this.lineChain.then(() => this.handleLine(parsed)).catch((err) => {
1479
+ this.deps.logger.error(`session ${this.sessionId}: ${err.message}`);
1480
+ });
1481
+ });
1482
+ child.on("close", (code, signal) => {
1483
+ rl.close();
1484
+ this.lineChain = this.lineChain.then(() => this.handleExit(child, code, signal)).catch(
1485
+ (err) => this.deps.logger.error(`session ${this.sessionId}: ${err.message}`)
1486
+ );
1487
+ });
1488
+ }
1489
+ async handleLine(line) {
1490
+ this.lastActivity = Date.now();
1491
+ const mapped = this.mapper.map(line);
1492
+ let dirty = false;
1493
+ if (mapped.claudeSessionId && mapped.claudeSessionId !== this.record.claudeSessionId) {
1494
+ this.record.claudeSessionId = mapped.claudeSessionId;
1495
+ dirty = true;
1496
+ }
1497
+ if (mapped.turnStarted && !this.record.turnActive) {
1498
+ this.record.turnActive = true;
1499
+ dirty = true;
1500
+ }
1501
+ if (dirty) await this.deps.store.save(this.record);
1502
+ if (mapped.events.length) this.emit(...mapped.events);
1503
+ if (mapped.turnEnd) {
1504
+ this.sawResultSinceSpawn = true;
1505
+ await this.endTurn(mapped.turnEnd);
1506
+ }
1507
+ }
1508
+ async endTurn(turn) {
1509
+ const interrupted = this.interruptRequested;
1510
+ this.interruptRequested = false;
1511
+ if (this.interruptTimer) clearTimeout(this.interruptTimer);
1512
+ this.interruptTimer = null;
1513
+ const turnFailed = turn.isError && !interrupted;
1514
+ if (turnFailed) {
1515
+ this.emit({
1516
+ type: "error",
1517
+ message: turnErrorMessage(turn),
1518
+ retryable: true
1519
+ });
1520
+ }
1521
+ const push = await this.pushWork();
1522
+ this.record.turnActive = false;
1523
+ await this.deps.store.save(this.record);
1524
+ const failed = turnFailed || push.failed;
1525
+ this.emit({
1526
+ type: "result",
1527
+ status: failed ? "failed" : "idle",
1528
+ text: interrupted ? turn.isError ? null : turn.text : turn.text,
1529
+ branch: push.branch
1530
+ });
1531
+ this.lastActivity = Date.now();
1532
+ this.deps.logger.info(
1533
+ `session ${this.sessionId}: turn ${interrupted ? "interrupted" : turnFailed ? "ended with an error" : push.failed ? "finished, but its work was not pushed" : "finished"}`,
1534
+ { pushed: push.branch ?? void 0 }
1535
+ );
1536
+ }
1537
+ /**
1538
+ * Commits leftovers, then pushes. `branch` is the work branch when it was pushed; `failed`
1539
+ * when committing or pushing failed (reported as an error saying where the work is kept).
1540
+ */
1541
+ async pushWork() {
1542
+ const { workBranch, baseSha, cwd, repoDir } = this.record;
1543
+ if (!workBranch || !baseSha) return { branch: null, failed: false };
1544
+ const res = await commitAndPush({
1545
+ worktree: cwd,
1546
+ workBranch,
1547
+ baseSha,
1548
+ message: "Uncommitted changes from the agent\u2019s turn\n\nCommitted by dt-runner at the end of a Discovery Tree agent turn."
1549
+ });
1550
+ if (!res.error) return { branch: res.pushed ? workBranch : null, failed: false };
1551
+ const kept = res.failedAt === "commit" ? ` The changes are still uncommitted in the worktree ${cwd}; closing the session removes it, so commit them there first.` : ` The work is kept on the local branch ${workBranch} in ${repoDir ?? cwd} (closing the session keeps that branch); push it from there.`;
1552
+ const message = `${res.error}${kept}`;
1553
+ this.deps.logger.warn(`session ${this.sessionId}: ${message}`);
1554
+ this.emit({ type: "error", message, retryable: false });
1555
+ return { branch: null, failed: true };
1556
+ }
1557
+ async handleExit(child, code, signal) {
1558
+ if (this.child !== child) return;
1559
+ this.child = null;
1560
+ const reason = this.stopping;
1561
+ this.stopping = null;
1562
+ const waiters = this.exitWaiters;
1563
+ this.exitWaiters = [];
1564
+ try {
1565
+ if (reason) {
1566
+ this.deps.logger.info(`session ${this.sessionId}: Claude Code stopped (${reason})`);
1567
+ if (reason !== "shutdown" && this.record.turnActive) {
1568
+ this.emit({
1569
+ type: "error",
1570
+ message: "Claude Code was stopped in the middle of this turn. Send a message to continue.",
1571
+ retryable: true
1572
+ });
1573
+ this.record.turnActive = false;
1574
+ await this.deps.store.save(this.record);
1575
+ this.emit({ type: "result", status: "idle", text: null });
1576
+ }
1577
+ return;
1578
+ }
1579
+ if (!this.record.turnActive) {
1580
+ this.deps.logger.info(`session ${this.sessionId}: Claude Code exited while idle`, {
1581
+ code,
1582
+ signal
1583
+ });
1584
+ return;
1585
+ }
1586
+ if (this.interruptRequested) {
1587
+ await this.endTurn({ text: null, isError: true, subtype: "interrupted" });
1588
+ return;
1589
+ }
1590
+ const tail = scrubSecrets(this.stderrTail.trim().split("\n").slice(-3).join(" ")).slice(
1591
+ 0,
1592
+ 400
1593
+ );
1594
+ const how = signal ? `was killed (${signal})` : `exited with code ${code}`;
1595
+ const hint = this.sawResultSinceSpawn ? "" : startupHint(this.stderrTail);
1596
+ this.emit({
1597
+ type: "error",
1598
+ message: `Claude Code ${how} in the middle of a turn.${hint}${tail ? ` ${tail}` : ""}`,
1599
+ retryable: true
1600
+ });
1601
+ this.record.turnActive = false;
1602
+ await this.deps.store.save(this.record);
1603
+ this.emit({ type: "result", status: "failed", text: null });
1604
+ this.deps.logger.warn(`session ${this.sessionId}: Claude Code ${how}`);
1605
+ } finally {
1606
+ for (const w of waiters) w();
1607
+ }
1608
+ }
1609
+ };
1610
+ function turnErrorMessage(turn) {
1611
+ switch (turn.subtype) {
1612
+ case "error_max_turns":
1613
+ return "Claude Code stopped: it reached its maximum number of turns.";
1614
+ case "error_max_budget_usd":
1615
+ return "Claude Code stopped: it reached its spending limit.";
1616
+ default:
1617
+ return turn.text ? `Claude Code reported an error: ${turn.text.slice(0, 500)}` : `Claude Code ended the turn with an error (${turn.subtype ?? "unknown"}).`;
1618
+ }
1619
+ }
1620
+ function startupHint(stderr) {
1621
+ if (/log ?in|not logged|authenticat|\/login/i.test(stderr)) {
1622
+ return " Claude Code does not seem to be signed in on the runner\u2019s computer: run `claude` there and sign in.";
1623
+ }
1624
+ if (/No conversation found|session.*not found/i.test(stderr)) {
1625
+ return " The Claude Code conversation to resume was not found on this computer.";
1626
+ }
1627
+ return "";
1628
+ }
1629
+ function delay(ms) {
1630
+ return new Promise((r) => setTimeout(r, ms));
1631
+ }
1632
+
1633
+ // src/session-manager.ts
1634
+ var SessionManager = class {
1635
+ constructor(opts) {
1636
+ this.opts = opts;
1637
+ this.store = new SessionStore(opts.config.stateDir);
1638
+ }
1639
+ sessions = /* @__PURE__ */ new Map();
1640
+ starting = /* @__PURE__ */ new Map();
1641
+ closing = /* @__PURE__ */ new Map();
1642
+ /**
1643
+ * Slots taken by dormant sessions being resumed. Counted from the (synchronous) capacity
1644
+ * check on, so two resumes in flight cannot both see a free slot while their processes
1645
+ * are still spawning.
1646
+ */
1647
+ reserved = 0;
1648
+ /**
1649
+ * Sessions whose process is being started again for a message, from the slot
1650
+ * reservation until the message is written. Their process may already be up while the
1651
+ * turn has not begun yet, so they look idle; they must not be stopped as idle meanwhile.
1652
+ */
1653
+ resuming = /* @__PURE__ */ new Set();
1654
+ store;
1655
+ shuttingDown = false;
1656
+ /** Loads sessions a previous run left, ends turns it was in the middle of, resumes posting. */
1657
+ async restore() {
1658
+ for (const record of await this.store.list()) {
1659
+ const session = await this.openSession(record);
1660
+ this.sessions.set(record.sessionId, session);
1661
+ if (record.turnActive) {
1662
+ session.emit(
1663
+ {
1664
+ type: "error",
1665
+ message: "The runner stopped in the middle of this turn. Send a message to continue.",
1666
+ retryable: true
1667
+ },
1668
+ { type: "result", status: "idle", text: null }
1669
+ );
1670
+ record.turnActive = false;
1671
+ await this.store.save(record);
1672
+ }
1673
+ this.opts.logger.info(`session ${record.sessionId}: restored`, {
1674
+ branch: record.workBranch ?? void 0
1675
+ });
1676
+ }
1677
+ }
1678
+ /** Sessions the runner has a live process or resumable state for (the heartbeat's list). */
1679
+ activeSessionIds() {
1680
+ return [...this.sessions.keys(), ...this.starting.keys()].filter(
1681
+ (id, i, all) => all.indexOf(id) === i
1682
+ );
1683
+ }
1684
+ /** Sessions using a Claude Code process now (or about to), counted against the limit. */
1685
+ liveCount() {
1686
+ let n = this.starting.size + this.reserved;
1687
+ for (const s of this.sessions.values()) if (s.alive) n++;
1688
+ return n;
1689
+ }
1690
+ get(sessionId) {
1691
+ return this.sessions.get(sessionId);
1692
+ }
1693
+ async handle(cmd) {
1694
+ try {
1695
+ assertSafeSessionId(cmd.sessionId);
1696
+ switch (cmd.type) {
1697
+ case "start_session":
1698
+ return await this.start(cmd);
1699
+ case "send_message":
1700
+ return await this.send(cmd.sessionId, cmd.text, cmd.id);
1701
+ case "interrupt":
1702
+ return this.interrupt(cmd.sessionId);
1703
+ case "close_session":
1704
+ await this.close(cmd.sessionId);
1705
+ return { ok: true };
1706
+ default:
1707
+ return {
1708
+ ok: false,
1709
+ error: `This runner does not know the command "${cmd.type}". Update dt-runner.`
1710
+ };
1711
+ }
1712
+ } catch (err) {
1713
+ return { ok: false, error: safeError(err) };
1714
+ }
1715
+ }
1716
+ async start(cmd) {
1717
+ if (this.sessions.has(cmd.sessionId)) return { ok: true };
1718
+ const inFlight = this.starting.get(cmd.sessionId);
1719
+ if (inFlight) return inFlight;
1720
+ if (this.shuttingDown) {
1721
+ return { ok: false, retryable: true, error: "The runner is shutting down." };
1722
+ }
1723
+ if (cmd.repository && !parseRepoUrl(cmd.repository.url)) {
1724
+ return { ok: false, error: repositoryUrlError(cmd.repository.url) };
1725
+ }
1726
+ assertValidModel(cmd.model);
1727
+ const max = this.opts.config.maxSessions;
1728
+ if (this.liveCount() >= max) {
1729
+ await this.stopOldestIdle(cmd.sessionId);
1730
+ if (this.sessions.has(cmd.sessionId)) return { ok: true };
1731
+ const again = this.starting.get(cmd.sessionId);
1732
+ if (again) return again;
1733
+ if (this.shuttingDown) {
1734
+ return { ok: false, retryable: true, error: "The runner is shutting down." };
1735
+ }
1736
+ }
1737
+ if (this.liveCount() >= max) {
1738
+ return {
1739
+ ok: false,
1740
+ retryable: true,
1741
+ error: `The runner is busy: it is already running ${max} session(s).`
1742
+ };
1743
+ }
1744
+ const promise = this.startSession(cmd).finally(() => this.starting.delete(cmd.sessionId));
1745
+ this.starting.set(cmd.sessionId, promise);
1746
+ return promise;
1747
+ }
1748
+ async startSession(cmd) {
1749
+ const label = cmd.title ? `"${cmd.title.slice(0, 80)}"` : `run ${cmd.runId}`;
1750
+ this.opts.logger.info(`session ${cmd.sessionId}: starting ${label}`, {
1751
+ repo: cmd.repository?.url,
1752
+ branch: cmd.repository?.workBranch
1753
+ });
1754
+ await this.opts.claude();
1755
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1756
+ const record = {
1757
+ sessionId: cmd.sessionId,
1758
+ runId: cmd.runId,
1759
+ title: cmd.title,
1760
+ model: cmd.model,
1761
+ cwd: "",
1762
+ repoDir: null,
1763
+ workBranch: null,
1764
+ baseRef: null,
1765
+ baseSha: null,
1766
+ claudeSessionId: null,
1767
+ turnActive: false,
1768
+ createdAt: now,
1769
+ updatedAt: now
1770
+ };
1771
+ try {
1772
+ if (cmd.repository) {
1773
+ const wt = await prepareWorktree({
1774
+ url: cmd.repository.url,
1775
+ baseRef: cmd.repository.baseRef,
1776
+ workBranch: cmd.repository.workBranch,
1777
+ reposDir: this.opts.config.reposDir,
1778
+ worktreesDir: this.opts.config.worktreesDir,
1779
+ sessionId: cmd.sessionId,
1780
+ protocol: this.opts.config.gitProtocol
1781
+ });
1782
+ Object.assign(record, {
1783
+ cwd: wt.worktree,
1784
+ repoDir: wt.repoDir,
1785
+ workBranch: cmd.repository.workBranch,
1786
+ baseRef: wt.baseRef,
1787
+ baseSha: wt.baseSha
1788
+ });
1789
+ } else {
1790
+ record.cwd = this.store.scratchDir(cmd.sessionId);
1791
+ await mkdir5(record.cwd, { recursive: true });
1792
+ }
1793
+ await this.store.save(record);
1794
+ } catch (err) {
1795
+ this.opts.logger.error(`session ${cmd.sessionId}: could not prepare the workspace`, {
1796
+ error: safeError(err)
1797
+ });
1798
+ await this.store.remove(cmd.sessionId).catch(() => void 0);
1799
+ return { ok: false, error: safeError(err) };
1800
+ }
1801
+ const session = await this.openSession(record);
1802
+ this.sessions.set(cmd.sessionId, session);
1803
+ try {
1804
+ await session.startFirstTurn(cmd.prompt);
1805
+ } catch (err) {
1806
+ const message = safeError(err);
1807
+ this.opts.logger.error(`session ${cmd.sessionId}: ${message}`);
1808
+ session.emit(
1809
+ { type: "error", message, retryable: false },
1810
+ { type: "result", status: "failed", text: null }
1811
+ );
1812
+ return { ok: false, error: message };
1813
+ }
1814
+ return { ok: true };
1815
+ }
1816
+ async send(sessionId, text, commandId) {
1817
+ const session = this.sessions.get(sessionId);
1818
+ if (!session) {
1819
+ return {
1820
+ ok: false,
1821
+ error: "This runner has no such session (it may have been closed or removed)."
1822
+ };
1823
+ }
1824
+ if (session.hasHandled(commandId)) {
1825
+ return { ok: true, providerEventId: commandId };
1826
+ }
1827
+ const max = this.opts.config.maxSessions;
1828
+ if (!session.alive && this.liveCount() >= max) {
1829
+ await this.stopOldestIdle(sessionId);
1830
+ }
1831
+ let reserved = false;
1832
+ if (!session.alive) {
1833
+ if (this.liveCount() >= max) {
1834
+ return {
1835
+ ok: false,
1836
+ retryable: true,
1837
+ error: `The runner is busy: it is running ${max} session(s) and none of them is idle.`
1838
+ };
1839
+ }
1840
+ this.reserved++;
1841
+ this.resuming.add(sessionId);
1842
+ reserved = true;
1843
+ }
1844
+ try {
1845
+ await session.sendMessage(text, commandId);
1846
+ } finally {
1847
+ if (reserved) {
1848
+ this.reserved--;
1849
+ this.resuming.delete(sessionId);
1850
+ }
1851
+ }
1852
+ this.opts.logger.info(`session ${sessionId}: message delivered`);
1853
+ return { ok: true, providerEventId: commandId };
1854
+ }
1855
+ interrupt(sessionId) {
1856
+ const session = this.sessions.get(sessionId);
1857
+ if (!session) return { ok: true };
1858
+ if (session.interrupt()) this.opts.logger.info(`session ${sessionId}: interrupting`);
1859
+ return { ok: true };
1860
+ }
1861
+ /** Stops the agent, removes the worktree (the branch stays), forgets the session. */
1862
+ close(sessionId) {
1863
+ const existing = this.closing.get(sessionId);
1864
+ if (existing) return existing;
1865
+ const work = this.closeSession(sessionId).finally(() => this.closing.delete(sessionId));
1866
+ this.closing.set(sessionId, work);
1867
+ return work;
1868
+ }
1869
+ async closeSession(sessionId) {
1870
+ await this.starting.get(sessionId)?.catch(() => void 0);
1871
+ const session = this.sessions.get(sessionId);
1872
+ if (!session) return;
1873
+ this.sessions.delete(sessionId);
1874
+ session.outbox.discard();
1875
+ await session.stop("close");
1876
+ const { record } = session;
1877
+ if (record.repoDir) {
1878
+ await removeWorktree(record.repoDir, record.cwd).catch(
1879
+ (err) => this.opts.logger.warn(`session ${sessionId}: could not remove the worktree`, {
1880
+ error: safeError(err)
1881
+ })
1882
+ );
1883
+ } else if (record.cwd) {
1884
+ await rm4(record.cwd, { recursive: true, force: true }).catch(() => void 0);
1885
+ }
1886
+ await session.outbox.settled();
1887
+ await this.store.remove(sessionId);
1888
+ this.opts.logger.info(`session ${sessionId}: closed`);
1889
+ }
1890
+ /** Ends Claude Code processes that have been idle too long; their sessions stay resumable. */
1891
+ async stopIdle(now = Date.now()) {
1892
+ for (const session of this.sessions.values()) {
1893
+ if (this.stoppable(session) && now - session.lastActivity > this.opts.config.idleTimeoutMs) {
1894
+ await session.stop("idle");
1895
+ }
1896
+ }
1897
+ }
1898
+ async stopOldestIdle(except) {
1899
+ const idle = [...this.sessions.values()].filter((s) => s.sessionId !== except && this.stoppable(s)).sort((a, b) => a.lastActivity - b.lastActivity);
1900
+ if (idle[0]) await idle[0].stop("idle");
1901
+ }
1902
+ /** A live process with no turn running and none about to begin. */
1903
+ stoppable(session) {
1904
+ return session.alive && !session.turnActive && !this.resuming.has(session.sessionId) && !this.starting.has(session.sessionId);
1905
+ }
1906
+ /**
1907
+ * Graceful stop: end every Claude Code process, tell the server about turns cut short,
1908
+ * give the outboxes a few seconds to drain, and leave the rest on disk for next time.
1909
+ */
1910
+ async shutdown(flushMs = 5e3) {
1911
+ this.shuttingDown = true;
1912
+ await Promise.allSettled([...this.starting.values()]);
1913
+ const sessions = [...this.sessions.values()];
1914
+ await Promise.all(
1915
+ sessions.map(async (s) => {
1916
+ await s.stop("shutdown");
1917
+ if (s.turnActive) {
1918
+ s.emit(
1919
+ {
1920
+ type: "error",
1921
+ message: "The runner was stopped in the middle of this turn. Send a message to continue.",
1922
+ retryable: true
1923
+ },
1924
+ { type: "result", status: "idle", text: null }
1925
+ );
1926
+ s.record.turnActive = false;
1927
+ await this.store.save(s.record).catch(() => void 0);
1928
+ }
1929
+ })
1930
+ );
1931
+ await Promise.all(sessions.map((s) => s.outbox.flush(flushMs)));
1932
+ await Promise.all(sessions.map((s) => s.outbox.stop()));
1933
+ }
1934
+ async openSession(record) {
1935
+ const outbox = await SessionOutbox.open({
1936
+ sessionId: record.sessionId,
1937
+ file: this.store.outboxFile(record.sessionId),
1938
+ poster: this.opts.poster,
1939
+ logger: this.opts.logger,
1940
+ batchDelayMs: this.opts.outboxBatchDelayMs,
1941
+ retryBaseMs: this.opts.outboxRetryBaseMs,
1942
+ onUnauthorized: (err) => this.opts.onUnauthorized?.(err),
1943
+ onClosed: () => {
1944
+ void this.close(record.sessionId);
1945
+ }
1946
+ });
1947
+ return new AgentSession(record, {
1948
+ store: this.store,
1949
+ outbox,
1950
+ logger: this.opts.logger,
1951
+ claude: this.opts.claude,
1952
+ permissionMode: this.opts.config.permissionMode,
1953
+ allowedTools: this.opts.config.allowedTools,
1954
+ disallowedTools: this.opts.config.disallowedTools ?? [],
1955
+ loadProjectSettings: this.opts.config.loadProjectSettings ?? false,
1956
+ interruptGraceMs: this.opts.interruptGraceMs
1957
+ });
1958
+ }
1959
+ };
1960
+ function safeError(err) {
1961
+ return scrubSecrets(err instanceof Error ? err.message : String(err)).slice(0, 600);
1962
+ }
1963
+
1964
+ // src/daemon.ts
1965
+ var RunnerDaemon = class {
1966
+ constructor(opts) {
1967
+ this.opts = opts;
1968
+ this.api = opts.api ?? new RunnerApi({ server: opts.config.server, token: opts.config.token });
1969
+ this.manager = new SessionManager({
1970
+ config: opts.config,
1971
+ poster: this.api,
1972
+ logger: opts.logger,
1973
+ claude: () => this.resolveClaude(),
1974
+ onUnauthorized: (err) => this.unauthorized(err),
1975
+ ...opts.managerOverrides
1976
+ });
1977
+ }
1978
+ api;
1979
+ manager;
1980
+ controller = new AbortController();
1981
+ exitReason = "stopped";
1982
+ agentInfo = null;
1983
+ claudeCache = null;
1984
+ inFlight = /* @__PURE__ */ new Set();
1985
+ /** The tail of each session's command queue (see `inSessionOrder`); never rejects. */
1986
+ sessionQueues = /* @__PURE__ */ new Map();
1987
+ upgradeWarnedAt = 0;
1988
+ get signal() {
1989
+ return this.controller.signal;
1990
+ }
1991
+ /** Runs until stopped (signal) or the token is refused. */
1992
+ async run() {
1993
+ const { logger, config } = this.opts;
1994
+ await this.manager.restore();
1995
+ logger.info(`dt-runner ${RUNNER_VERSION} connected to ${config.server}`, {
1996
+ maxSessions: config.maxSessions,
1997
+ permissionMode: config.permissionMode
1998
+ });
1999
+ const loops = [this.heartbeatLoop(), this.commandLoop(), this.idleLoop()];
2000
+ await Promise.all(loops);
2001
+ await Promise.allSettled([...this.inFlight]);
2002
+ await this.manager.shutdown();
2003
+ return this.exitReason;
2004
+ }
2005
+ /** Begins a graceful stop; `run()` resolves once sessions are wound down. */
2006
+ stop() {
2007
+ this.controller.abort();
2008
+ }
2009
+ unauthorized(err) {
2010
+ if (this.exitReason === "unauthorized") return;
2011
+ this.exitReason = "unauthorized";
2012
+ this.opts.logger.error(
2013
+ `Discovery Tree refused this runner's token (${err.path}). The runner may have been removed. Run \`dt-runner login\` to pair it again.`
2014
+ );
2015
+ this.stop();
2016
+ }
2017
+ async resolveClaude() {
2018
+ const ttl = this.opts.agentProbeTtlMs ?? 5 * 6e4;
2019
+ if (this.claudeCache && Date.now() - this.claudeCache.at < ttl) return this.claudeCache;
2020
+ const bin = await findClaude();
2021
+ if (!bin) {
2022
+ throw new Error(
2023
+ "Claude Code is not installed on the runner\u2019s computer (no `claude` on PATH)."
2024
+ );
2025
+ }
2026
+ this.claudeCache = { bin, features: await claudeFeatures(bin), at: Date.now() };
2027
+ return this.claudeCache;
2028
+ }
2029
+ async agent() {
2030
+ const ttl = this.opts.agentProbeTtlMs ?? 5 * 6e4;
2031
+ if (!this.agentInfo || Date.now() - this.agentInfo.at > ttl) {
2032
+ const info = await probeAgent();
2033
+ if (info.claudeProblem && info.claudeProblem !== this.agentInfo?.info.claudeProblem) {
2034
+ this.opts.logger.warn(info.claudeProblem);
2035
+ }
2036
+ this.agentInfo = { info, at: Date.now() };
2037
+ }
2038
+ return this.agentInfo.info;
2039
+ }
2040
+ async heartbeatLoop() {
2041
+ let failures = 0;
2042
+ while (!this.signal.aborted) {
2043
+ try {
2044
+ const res = await this.api.heartbeat({
2045
+ protocolVersion: RUNNER_PROTOCOL_VERSION,
2046
+ runnerVersion: RUNNER_VERSION,
2047
+ platform: RUNNER_PLATFORM,
2048
+ agent: await this.agent(),
2049
+ activeSessionIds: this.manager.activeSessionIds(),
2050
+ maxConcurrentSessions: this.opts.config.maxSessions
2051
+ });
2052
+ if (failures) this.opts.logger.info("reconnected to Discovery Tree");
2053
+ failures = 0;
2054
+ for (const id of res?.closeSessionIds ?? []) {
2055
+ if (this.manager.get(id)) {
2056
+ this.opts.logger.info(`session ${id}: the server closed it`);
2057
+ this.track(this.manager.close(id));
2058
+ }
2059
+ }
2060
+ if (res?.upgradeRequired && Date.now() - this.upgradeWarnedAt > 10 * 6e4) {
2061
+ this.upgradeWarnedAt = Date.now();
2062
+ this.opts.logger.warn(
2063
+ "Discovery Tree needs a newer dt-runner. Update it (`npx @discovery-tree/runner@latest start`) and restart."
2064
+ );
2065
+ }
2066
+ } catch (err) {
2067
+ if (err instanceof UnauthorizedError) return this.unauthorized(err);
2068
+ failures++;
2069
+ if (failures === 1 || failures % 10 === 0) {
2070
+ this.opts.logger.warn("heartbeat failed; retrying", { error: err.message });
2071
+ }
2072
+ }
2073
+ await sleep(this.opts.heartbeatMs ?? 15e3, this.signal);
2074
+ }
2075
+ }
2076
+ async commandLoop() {
2077
+ let attempt = 0;
2078
+ let limited = 0;
2079
+ const wait = this.opts.pollWaitMs ?? RUNNER_COMMAND_POLL_MAX_WAIT_MS;
2080
+ const base = this.opts.retryBaseMs ?? 1e3;
2081
+ while (!this.signal.aborted) {
2082
+ try {
2083
+ const res = await this.api.pollCommands(wait, this.signal);
2084
+ attempt = 0;
2085
+ limited = 0;
2086
+ for (const cmd of res?.commands ?? []) this.track(this.dispatch(cmd));
2087
+ } catch (err) {
2088
+ if (this.signal.aborted) break;
2089
+ if (err instanceof UnauthorizedError) return this.unauthorized(err);
2090
+ if (err instanceof ApiError && err.status === 429) {
2091
+ const delay3 = Math.max(err.retryAfterMs ?? 0, backoffDelay(limited++, base * 5, 6e4));
2092
+ this.opts.logger[limited === 1 ? "warn" : "debug"](
2093
+ "Discovery Tree is limiting this runner\u2019s command polls (429); waiting before polling again. Is another dt-runner running with the same token?",
2094
+ { retryInMs: delay3 }
2095
+ );
2096
+ await sleep(delay3, this.signal);
2097
+ continue;
2098
+ }
2099
+ const delay2 = backoffDelay(attempt++, base);
2100
+ this.opts.logger[attempt === 1 ? "warn" : "debug"](
2101
+ "waiting for commands failed; retrying",
2102
+ {
2103
+ error: err.message,
2104
+ retryInMs: delay2
2105
+ }
2106
+ );
2107
+ await sleep(delay2, this.signal);
2108
+ }
2109
+ }
2110
+ }
2111
+ async idleLoop() {
2112
+ while (!this.signal.aborted) {
2113
+ await sleep(3e4, this.signal);
2114
+ if (!this.signal.aborted) await this.manager.stopIdle().catch(() => void 0);
2115
+ }
2116
+ }
2117
+ track(p) {
2118
+ const tracked = p.then(
2119
+ () => void 0,
2120
+ (err) => this.opts.logger.error(`command failed: ${err.message}`)
2121
+ );
2122
+ this.inFlight.add(tracked);
2123
+ void tracked.finally(() => this.inFlight.delete(tracked));
2124
+ }
2125
+ /**
2126
+ * Runs `work` after every earlier command for the same session has been handled. A
2127
+ * `send_message` or `interrupt` claimed while that session's `start_session` is still
2128
+ * preparing the workspace would otherwise find no session and be refused for good.
2129
+ */
2130
+ inSessionOrder(sessionId, work) {
2131
+ const previous = this.sessionQueues.get(sessionId) ?? Promise.resolve();
2132
+ const result = previous.then(work);
2133
+ const tail = result.then(
2134
+ () => void 0,
2135
+ () => void 0
2136
+ );
2137
+ this.sessionQueues.set(sessionId, tail);
2138
+ void tail.then(() => {
2139
+ if (this.sessionQueues.get(sessionId) === tail) this.sessionQueues.delete(sessionId);
2140
+ });
2141
+ return result;
2142
+ }
2143
+ async dispatch(cmd) {
2144
+ this.opts.logger.debug(`command ${cmd.type}`, { id: cmd.id, session: cmd.sessionId });
2145
+ const ack = await this.inSessionOrder(cmd.sessionId, () => this.manager.handle(cmd));
2146
+ if (!ack.ok) {
2147
+ this.opts.logger.warn(`${cmd.type} for session ${cmd.sessionId} refused`, {
2148
+ error: ack.error
2149
+ });
2150
+ }
2151
+ await this.ack(cmd.id, ack);
2152
+ }
2153
+ /** Acks are retried a few times; a lost one means a redelivery, which handlers absorb. */
2154
+ async ack(commandId, body) {
2155
+ for (let attempt = 0; attempt < 5; attempt++) {
2156
+ try {
2157
+ await this.api.ackCommand(commandId, body);
2158
+ return;
2159
+ } catch (err) {
2160
+ if (err instanceof UnauthorizedError) return this.unauthorized(err);
2161
+ if (!isRetryable(err)) {
2162
+ this.opts.logger.warn("the server refused a command ack", {
2163
+ error: err.message
2164
+ });
2165
+ return;
2166
+ }
2167
+ await sleep(backoffDelay(attempt, this.opts.retryBaseMs ?? 1e3, 1e4));
2168
+ }
2169
+ }
2170
+ this.opts.logger.warn("could not acknowledge a command; the server will redeliver it", {
2171
+ id: commandId
2172
+ });
2173
+ }
2174
+ };
2175
+
2176
+ // src/doctor.ts
2177
+ async function runDoctor(env = process.env) {
2178
+ const checks = [];
2179
+ const major = Number(process.versions.node.split(".")[0]);
2180
+ checks.push({
2181
+ name: "Node.js",
2182
+ level: major >= 22 ? "ok" : "fail",
2183
+ detail: major >= 22 ? `v${process.versions.node}` : `v${process.versions.node}; dt-runner needs Node.js 22 or newer`
2184
+ });
2185
+ try {
2186
+ const res = await exec("git", ["--version"], { timeoutMs: 1e4 });
2187
+ checks.push({
2188
+ name: "git",
2189
+ level: res.code === 0 ? "ok" : "fail",
2190
+ detail: res.code === 0 ? res.stdout.trim() : "git --version failed"
2191
+ });
2192
+ } catch {
2193
+ checks.push({ name: "git", level: "fail", detail: "git is not installed (or not on PATH)" });
2194
+ }
2195
+ const bin = await findClaude(env);
2196
+ if (!bin) {
2197
+ checks.push({
2198
+ name: "Claude Code",
2199
+ level: "fail",
2200
+ detail: env.DT_RUNNER_CLAUDE_BIN ? `DT_RUNNER_CLAUDE_BIN=${env.DT_RUNNER_CLAUDE_BIN} was not found` : "not installed: see https://docs.claude.com/en/docs/claude-code (no `claude` on PATH)"
2201
+ });
2202
+ } else {
2203
+ const version = await claudeVersion(bin);
2204
+ checks.push({
2205
+ name: "Claude Code",
2206
+ level: version ? "ok" : "fail",
2207
+ detail: version ? `${version} (${bin})` : `${bin} --version failed`
2208
+ });
2209
+ if (version) {
2210
+ const auth = await claudeAuthStatus(bin);
2211
+ checks.push(
2212
+ auth.loggedIn === true ? {
2213
+ name: "Claude sign-in",
2214
+ level: "ok",
2215
+ detail: `signed in${auth.authMethod ? ` (${auth.authMethod})` : ""}`
2216
+ } : auth.loggedIn === false ? {
2217
+ name: "Claude sign-in",
2218
+ level: "fail",
2219
+ detail: "not signed in: run `claude` and sign in with your Claude account"
2220
+ } : {
2221
+ name: "Claude sign-in",
2222
+ level: "warn",
2223
+ detail: "could not tell (this Claude Code has no `claude auth status`); update Claude Code"
2224
+ }
2225
+ );
2226
+ }
2227
+ }
2228
+ if (env.ANTHROPIC_API_KEY) {
2229
+ checks.push({
2230
+ name: "ANTHROPIC_API_KEY",
2231
+ level: "warn",
2232
+ detail: "is set: Claude Code will bill that API key instead of your Claude subscription. Unset it before `dt-runner start` unless that is what you want."
2233
+ });
2234
+ }
2235
+ return checks;
2236
+ }
2237
+ function formatChecks(checks) {
2238
+ const mark = { ok: "\u2713", warn: "!", fail: "\u2717" };
2239
+ return checks.map((c) => `${mark[c.level]} ${c.name}: ${c.detail}`).join("\n");
2240
+ }
2241
+
2242
+ // src/lock.ts
2243
+ import { mkdir as mkdir6, open, readFile as readFile3, rm as rm5 } from "node:fs/promises";
2244
+ import { join as join5 } from "node:path";
2245
+ function lockFile(stateDir) {
2246
+ return join5(stateDir, "daemon.pid");
2247
+ }
2248
+ function pidAlive(pid) {
2249
+ if (!Number.isInteger(pid) || pid <= 0) return false;
2250
+ try {
2251
+ process.kill(pid, 0);
2252
+ return true;
2253
+ } catch (err) {
2254
+ return err.code === "EPERM";
2255
+ }
2256
+ }
2257
+ async function lockHolder(stateDir) {
2258
+ let raw;
2259
+ try {
2260
+ raw = await readFile3(lockFile(stateDir), "utf8");
2261
+ } catch {
2262
+ return null;
2263
+ }
2264
+ const pid = Number.parseInt(raw.trim(), 10);
2265
+ return pidAlive(pid) && pid !== process.pid ? pid : null;
2266
+ }
2267
+ async function acquireDaemonLock(stateDir, pid = process.pid) {
2268
+ await mkdir6(stateDir, { recursive: true, mode: 448 });
2269
+ const file = lockFile(stateDir);
2270
+ for (let attempt = 0; attempt < 3; attempt++) {
2271
+ try {
2272
+ const handle = await open(file, "wx", 384);
2273
+ try {
2274
+ await handle.writeFile(`${pid}
2275
+ `);
2276
+ } finally {
2277
+ await handle.close();
2278
+ }
2279
+ return {
2280
+ ok: true,
2281
+ lock: {
2282
+ file,
2283
+ async release() {
2284
+ const current = await readFile3(file, "utf8").catch(() => "");
2285
+ if (Number.parseInt(current.trim(), 10) === pid) await rm5(file, { force: true });
2286
+ }
2287
+ }
2288
+ };
2289
+ } catch (err) {
2290
+ if (err.code !== "EEXIST") throw err;
2291
+ }
2292
+ const raw = await readFile3(file, "utf8").catch(() => null);
2293
+ if (raw === null) continue;
2294
+ const holder = Number.parseInt(raw.trim(), 10);
2295
+ if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
2296
+ await rm5(file, { force: true });
2297
+ }
2298
+ return { ok: false, pid: null };
2299
+ }
2300
+
2301
+ // src/pairing.ts
2302
+ import { spawn as spawn3 } from "node:child_process";
2303
+ async function pair(api, opts) {
2304
+ const start2 = await api.startPairing({ name: opts.name, platform: RUNNER_PLATFORM });
2305
+ opts.ui.showCode(start2.userCode, start2.verificationUrl, start2.expiresInSeconds);
2306
+ if (opts.openBrowser !== false) openUrl(start2.verificationUrl);
2307
+ const deadline = Date.now() + start2.expiresInSeconds * 1e3;
2308
+ const interval = Math.max(opts.minIntervalMs ?? 1e3, start2.intervalSeconds * 1e3);
2309
+ let failures = 0;
2310
+ while (Date.now() < deadline) {
2311
+ await sleep(interval, opts.signal);
2312
+ if (opts.signal?.aborted) throw new Error("Pairing cancelled.");
2313
+ let res;
2314
+ try {
2315
+ res = await api.pollPairing(start2.deviceCode);
2316
+ failures = 0;
2317
+ } catch (err) {
2318
+ if (!isRetryable(err)) throw err;
2319
+ if (++failures === 1)
2320
+ opts.ui.note?.(`Could not reach Discovery Tree (${err.message}); still trying\u2026`);
2321
+ continue;
2322
+ }
2323
+ switch (res.status) {
2324
+ case "pending":
2325
+ continue;
2326
+ case "approved":
2327
+ return { runnerId: res.runnerId, token: res.token, userLabel: res.userLabel };
2328
+ case "denied":
2329
+ throw new Error("Pairing was denied in Discovery Tree.");
2330
+ case "expired":
2331
+ throw new Error("The pairing code expired. Run `dt-runner login` again.");
2332
+ }
2333
+ }
2334
+ throw new Error("The pairing code expired. Run `dt-runner login` again.");
2335
+ }
2336
+ async function confirmAccount(result, opts) {
2337
+ const { io } = opts;
2338
+ if (opts.yes) {
2339
+ io.print(`Paired as ${result.userLabel}.`);
2340
+ return true;
2341
+ }
2342
+ if (!io.isTTY) {
2343
+ io.print("");
2344
+ io.print("==================================================================");
2345
+ io.print(` PAIRED AS: ${result.userLabel}`);
2346
+ io.print(" If this is not your Discovery Tree account, remove this runner in");
2347
+ io.print(" Discovery Tree (Account settings \u2192 Local runners) and run");
2348
+ io.print(" `dt-runner logout` on this computer.");
2349
+ io.print("==================================================================");
2350
+ io.print("");
2351
+ return true;
2352
+ }
2353
+ io.print(`Paired as ${result.userLabel}.`);
2354
+ const answer = (await io.ask("Is this your Discovery Tree account? [y/N] ")).trim();
2355
+ if (/^y(es)?$/i.test(answer)) return true;
2356
+ io.print("Nothing was saved on this computer.");
2357
+ io.print(
2358
+ `The pairing did create a runner on ${result.userLabel}'s account: if that is your account, remove it in Discovery Tree under Account settings \u2192 Local runners; if it is not, tell its owner.`
2359
+ );
2360
+ return false;
2361
+ }
2362
+ function openUrl(url) {
2363
+ if (!/^https?:\/\//i.test(url)) return;
2364
+ const [cmd, args] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : ["xdg-open", [url]];
2365
+ try {
2366
+ const child = spawn3(cmd, args, { stdio: "ignore", detached: true, windowsHide: true });
2367
+ child.on("error", () => void 0);
2368
+ child.unref();
2369
+ } catch {
2370
+ }
2371
+ }
2372
+
2373
+ // src/cli.ts
2374
+ var HELP = `dt-runner ${RUNNER_VERSION} \u2014 run Discovery Tree agent sessions on this computer
2375
+ with your own signed-in Claude Code (your Claude subscription; Discovery Tree never sees
2376
+ your Claude credentials).
2377
+
2378
+ Usage:
2379
+ dt-runner login [--server <url>] [--name <name>] [--no-browser] [--yes]
2380
+ Pair this computer with your Discovery Tree account.
2381
+ --yes skips the "is this your account?" question.
2382
+ dt-runner start [--max-sessions <n>] [--repos-dir <dir>] [--json] [--verbose]
2383
+ Run: wait for agent sessions and run them with Claude Code.
2384
+ dt-runner status Show the configuration and check the connection.
2385
+ dt-runner doctor Check Node.js, git and Claude Code on this computer.
2386
+ dt-runner logout Forget this runner's token (deletes the config file).
2387
+
2388
+ Options:
2389
+ -h, --help Show this help.
2390
+ -v, --version Print the version.
2391
+
2392
+ Environment:
2393
+ DT_SERVER_URL Discovery Tree server (default ${DEFAULT_SERVER_URL}).
2394
+ DT_RUNNER_TOKEN Runner token (overrides the config file).
2395
+ DT_RUNNER_CLAUDE_BIN Claude Code binary to run (default: \`claude\` on PATH).
2396
+
2397
+ Config: ${runnerPaths().configFile}
2398
+ `;
2399
+ async function main(argv) {
2400
+ const { values, positionals } = parseArgs({
2401
+ args: argv,
2402
+ allowPositionals: true,
2403
+ strict: true,
2404
+ options: {
2405
+ server: { type: "string" },
2406
+ name: { type: "string" },
2407
+ "no-browser": { type: "boolean" },
2408
+ yes: { type: "boolean", short: "y" },
2409
+ "max-sessions": { type: "string" },
2410
+ "repos-dir": { type: "string" },
2411
+ json: { type: "boolean" },
2412
+ verbose: { type: "boolean" },
2413
+ help: { type: "boolean", short: "h" },
2414
+ version: { type: "boolean", short: "v" }
2415
+ }
2416
+ });
2417
+ if (values.version) {
2418
+ console.log(RUNNER_VERSION);
2419
+ return 0;
2420
+ }
2421
+ const command = positionals[0];
2422
+ if (values.help || !command || command === "help") {
2423
+ console.log(HELP);
2424
+ return command || values.help ? 0 : 1;
2425
+ }
2426
+ switch (command) {
2427
+ case "login":
2428
+ return login(values.server, values.name, !values["no-browser"], values.yes === true);
2429
+ case "start":
2430
+ return start({
2431
+ maxSessions: values["max-sessions"] !== void 0 ? Number(values["max-sessions"]) : void 0,
2432
+ reposDir: values["repos-dir"],
2433
+ json: values.json,
2434
+ verbose: values.verbose
2435
+ });
2436
+ case "status":
2437
+ return status();
2438
+ case "doctor":
2439
+ return doctor();
2440
+ case "logout":
2441
+ return logout();
2442
+ default:
2443
+ console.error(`Unknown command "${command}". Run \`dt-runner --help\`.`);
2444
+ return 1;
2445
+ }
2446
+ }
2447
+ async function login(server, name, openBrowser, yes) {
2448
+ const paths = runnerPaths();
2449
+ const existing = await readConfigFile(paths.configFile);
2450
+ const serverUrl = normalizeServerUrl(
2451
+ server ?? process.env.DT_SERVER_URL ?? existing?.server ?? DEFAULT_SERVER_URL
2452
+ );
2453
+ const runnerName = name ?? existing?.name ?? hostname();
2454
+ const api = new RunnerApi({ server: serverUrl });
2455
+ console.log(`Pairing "${runnerName}" with ${serverUrl} \u2026`);
2456
+ const controller = new AbortController();
2457
+ process.once("SIGINT", () => controller.abort());
2458
+ const result = await pair(api, {
2459
+ name: runnerName,
2460
+ openBrowser,
2461
+ signal: controller.signal,
2462
+ ui: {
2463
+ showCode(userCode, url, expires) {
2464
+ const line = ` ${userCode} `;
2465
+ console.log("");
2466
+ console.log(` \u250C${"\u2500".repeat(line.length)}\u2510`);
2467
+ console.log(` \u2502${line}\u2502`);
2468
+ console.log(` \u2514${"\u2500".repeat(line.length)}\u2518`);
2469
+ console.log("");
2470
+ console.log(` Open ${url} and type this code.`);
2471
+ console.log(" Type it yourself. Never enter a code somebody else sent you.");
2472
+ console.log("");
2473
+ console.log(`Waiting for approval (the code expires in ${Math.round(expires / 60)} min) \u2026`);
2474
+ },
2475
+ note: (msg) => console.log(msg)
2476
+ }
2477
+ });
2478
+ const save = await confirmAccount(result, {
2479
+ yes,
2480
+ io: {
2481
+ isTTY: process.stdin.isTTY === true,
2482
+ print: (line) => console.log(line),
2483
+ async ask(question) {
2484
+ const rl = createInterface2({ input: process.stdin, output: process.stdout });
2485
+ try {
2486
+ return await rl.question(question);
2487
+ } finally {
2488
+ rl.close();
2489
+ }
2490
+ }
2491
+ }
2492
+ });
2493
+ if (!save) return 1;
2494
+ await writeConfigFile(paths.configFile, {
2495
+ ...existing ?? {},
2496
+ server: serverUrl,
2497
+ runnerId: result.runnerId,
2498
+ token: result.token,
2499
+ name: runnerName
2500
+ });
2501
+ console.log(`Saved to ${paths.configFile}.`);
2502
+ console.log("Run `dt-runner doctor` to check this computer, then `dt-runner start`.");
2503
+ return 0;
2504
+ }
2505
+ async function start(opts) {
2506
+ const logger = createLogger({ json: opts.json, verbose: opts.verbose });
2507
+ const paths = runnerPaths();
2508
+ const config = resolveConfig(await readConfigFile(paths.configFile), {
2509
+ maxSessions: opts.maxSessions,
2510
+ reposDir: opts.reposDir
2511
+ });
2512
+ if (!config.token) {
2513
+ logger.error("This computer is not paired yet. Run `dt-runner login` first.");
2514
+ return 1;
2515
+ }
2516
+ if (process.env.ANTHROPIC_API_KEY) {
2517
+ logger.warn(
2518
+ "ANTHROPIC_API_KEY is set: Claude Code will bill that API key, not your Claude subscription. Unset it unless that is what you want."
2519
+ );
2520
+ }
2521
+ if (config.permissionMode === "bypassPermissions") {
2522
+ logger.warn(
2523
+ "!!! permissionMode is bypassPermissions: Claude Code will run ANY command and edit ANY file on this computer without asking. !!!"
2524
+ );
2525
+ logger.warn(
2526
+ '!!! Only use this on a disposable machine or container. Remove "permissionMode" from the config to go back to acceptEdits. !!!'
2527
+ );
2528
+ }
2529
+ const locked = await acquireDaemonLock(config.stateDir);
2530
+ if (!locked.ok) {
2531
+ logger.error(
2532
+ locked.pid ? `Another dt-runner is already running for this configuration (pid ${locked.pid}). Stop it first; two runners with one token would fail each other's sessions. (If no dt-runner is running, delete ${lockFile(config.stateDir)}.)` : `Could not take the runner lock ${lockFile(config.stateDir)}; is another dt-runner starting?`
2533
+ );
2534
+ return 1;
2535
+ }
2536
+ const daemon = new RunnerDaemon({ config, logger });
2537
+ let signals = 0;
2538
+ const onSignal = (sig) => {
2539
+ signals++;
2540
+ if (signals === 1) {
2541
+ logger.info(
2542
+ `${sig}: stopping (Claude Code processes end, sessions stay resumable). Press Ctrl+C again to force.`
2543
+ );
2544
+ daemon.stop();
2545
+ } else {
2546
+ process.exit(130);
2547
+ }
2548
+ };
2549
+ process.on("SIGINT", onSignal);
2550
+ process.on("SIGTERM", onSignal);
2551
+ let exit;
2552
+ try {
2553
+ exit = await daemon.run();
2554
+ } finally {
2555
+ await locked.lock.release().catch(() => void 0);
2556
+ }
2557
+ logger.info("dt-runner stopped");
2558
+ return exit === "unauthorized" ? 1 : 0;
2559
+ }
2560
+ async function status() {
2561
+ const paths = runnerPaths();
2562
+ const file = await readConfigFile(paths.configFile);
2563
+ const config = resolveConfig(file);
2564
+ console.log(`Config: ${paths.configFile}${file ? "" : " (not found)"}`);
2565
+ console.log(`Server: ${config.server}`);
2566
+ console.log(
2567
+ `Runner: ${config.name ?? "(unnamed)"}${config.runnerId ? ` (${config.runnerId})` : ""}`
2568
+ );
2569
+ console.log(
2570
+ `Token: ${config.token ? `set${process.env.DT_RUNNER_TOKEN ? " (from DT_RUNNER_TOKEN)" : ""}` : "not set \u2014 run `dt-runner login`"}`
2571
+ );
2572
+ console.log(
2573
+ `Sessions: up to ${config.maxSessions} at once, permission mode ${config.permissionMode}`
2574
+ );
2575
+ console.log(`Repos: ${config.reposDir}`);
2576
+ console.log(`Worktrees: ${config.worktreesDir}`);
2577
+ console.log(`State: ${config.stateDir}`);
2578
+ const api = new RunnerApi({ server: config.server, token: config.token });
2579
+ const reachable = await api.health();
2580
+ console.log(`Reachable: ${reachable ? "yes" : "no"}`);
2581
+ if (!config.token) return 1;
2582
+ const daemonPid = await lockHolder(config.stateDir);
2583
+ if (daemonPid) {
2584
+ console.log(`Daemon: running (pid ${daemonPid}); it reports to the server itself`);
2585
+ return 0;
2586
+ }
2587
+ console.log("Daemon: not running");
2588
+ try {
2589
+ const agent = await probeAgent();
2590
+ const res = await api.heartbeat({
2591
+ protocolVersion: RUNNER_PROTOCOL_VERSION,
2592
+ runnerVersion: RUNNER_VERSION,
2593
+ platform: RUNNER_PLATFORM,
2594
+ agent,
2595
+ // The sessions on disk: the same list a running daemon reports, so this check never
2596
+ // makes the server think a session was lost.
2597
+ activeSessionIds: (await new SessionStore(config.stateDir).list()).map((r) => r.sessionId),
2598
+ maxConcurrentSessions: config.maxSessions
2599
+ });
2600
+ console.log(
2601
+ `Heartbeat: ok (runner ${res.runnerId})${res.upgradeRequired ? " \u2014 an update is required" : ""}`
2602
+ );
2603
+ console.log(
2604
+ `Claude Code: ${agent.claudeVersion ?? "not found"}${agent.claudeProblem ? ` \u2014 ${agent.claudeProblem}` : ""}`
2605
+ );
2606
+ return 0;
2607
+ } catch (err) {
2608
+ if (err instanceof UnauthorizedError) {
2609
+ console.log("Heartbeat: token refused \u2014 run `dt-runner login` again");
2610
+ } else {
2611
+ console.log(`Heartbeat: failed (${err.message})`);
2612
+ }
2613
+ return 1;
2614
+ }
2615
+ }
2616
+ async function doctor() {
2617
+ const checks = await runDoctor();
2618
+ console.log(formatChecks(checks));
2619
+ const failed = checks.some((c) => c.level === "fail");
2620
+ console.log(failed ? "\nSome checks failed; sessions will not run until they pass." : "\nReady.");
2621
+ return failed ? 1 : 0;
2622
+ }
2623
+ async function logout() {
2624
+ const { configFile } = runnerPaths();
2625
+ const removed = await deleteConfigFile(configFile);
2626
+ console.log(removed ? `Removed ${configFile}.` : "Not logged in.");
2627
+ if (removed)
2628
+ console.log("To revoke the runner itself, remove it from your runners in Discovery Tree.");
2629
+ return 0;
2630
+ }
2631
+ main(process.argv.slice(2)).then(
2632
+ (code) => {
2633
+ process.exitCode = code;
2634
+ },
2635
+ (err) => {
2636
+ console.error(`dt-runner: ${err instanceof Error ? err.message : String(err)}`);
2637
+ process.exitCode = 1;
2638
+ }
2639
+ );