@discovery-tree/runner 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +16 -0
  2. package/dist/cli.js +279 -26
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -188,6 +188,22 @@ The runner only clones from `https://github.com/<owner>/<repo>`: Discovery Tree
188
188
  at another host. It passes Claude Code only a model name that looks like one (`sonnet`,
189
189
  `opus[1m]`, `claude-opus-5-5`, …) and refuses the session otherwise.
190
190
 
191
+ ## Planning on your own Claude Code
192
+
193
+ Turn on **Plan on my own Claude Code** under Account settings → Local runners, and your
194
+ planning in Discovery Tree (breaking a task down, drafting new work, intake, triage) is
195
+ answered by Claude Code on this computer while the runner is online, on your own Claude
196
+ subscription. When the runner is offline or Claude Code cannot answer, your planning falls
197
+ back to your key or the workspace's, as before. Reviews are never sent here: they are the
198
+ workspace's work, not yours.
199
+
200
+ A planning request is not a session: the runner runs `claude -p --output-format json` once,
201
+ in an empty scratch directory it deletes afterwards, with the request on stdin, your own
202
+ settings only (`--setting-sources user`), one turn, and every tool that writes, runs or
203
+ fetches anything denied (`Bash`, `Edit`, `MultiEdit`, `Write`, `NotebookEdit`, `WebFetch`,
204
+ `WebSearch`, `Task`). Only the answer goes back to Discovery Tree. Requires dt-runner 0.1.9
205
+ or later.
206
+
191
207
  ## Repositories, worktrees and branches
192
208
 
193
209
  For a session on `https://github.com/owner/repo`:
package/dist/cli.js CHANGED
@@ -48,9 +48,10 @@ var RUNNER_COMMAND_POLL_MAX_WAIT_MS = 25e3;
48
48
  var RUNNER_EVENTS_MAX_BATCH = 200;
49
49
  var RUNNER_EVENT_TEXT_MAX_LENGTH = 64e3;
50
50
  var RUNNER_EVENTS_MAX_BODY_BYTES = 8 * 1024 * 1024;
51
+ var RUNNER_COMPLETION_MAX_TEXT = 2e5;
51
52
 
52
53
  // src/version.ts
53
- var RUNNER_VERSION = true ? "0.1.8" : "0.0.0-dev";
54
+ var RUNNER_VERSION = true ? "0.1.10" : "0.0.0-dev";
54
55
  var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
55
56
 
56
57
  // src/api.ts
@@ -116,6 +117,10 @@ var RunnerApi = class {
116
117
  ackCommand(commandId, body) {
117
118
  return this.request("POST", `/runner/commands/${encodeURIComponent(commandId)}/ack`, body);
118
119
  }
120
+ /** The answer to a one-off request (`completions` on a command poll). */
121
+ postCompletion(completionId, body) {
122
+ return this.request("POST", `/runner/completions/${encodeURIComponent(completionId)}`, body);
123
+ }
119
124
  postEvents(sessionId, body) {
120
125
  return this.request("POST", `/runner/sessions/${encodeURIComponent(sessionId)}/events`, body);
121
126
  }
@@ -186,6 +191,9 @@ function exec(cmd, args, opts = {}) {
186
191
  if (opts.timeoutMs) {
187
192
  timer = setTimeout(() => child.kill("SIGKILL"), opts.timeoutMs);
188
193
  }
194
+ const onAbort = () => child.kill("SIGKILL");
195
+ if (opts.signal?.aborted) onAbort();
196
+ else opts.signal?.addEventListener("abort", onAbort, { once: true });
189
197
  child.stdout.setEncoding("utf8").on("data", (d) => stdout += d);
190
198
  child.stderr.setEncoding("utf8").on("data", (d) => stderr += d);
191
199
  child.on("error", (err) => {
@@ -194,6 +202,7 @@ function exec(cmd, args, opts = {}) {
194
202
  });
195
203
  child.on("close", (code) => {
196
204
  if (timer) clearTimeout(timer);
205
+ opts.signal?.removeEventListener("abort", onAbort);
197
206
  resolve({ code, stdout, stderr });
198
207
  });
199
208
  child.stdin.on("error", () => void 0);
@@ -333,13 +342,22 @@ async function exists(p) {
333
342
  return false;
334
343
  }
335
344
  }
345
+ var LOCKED_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES", "ENOTEMPTY"]);
346
+ function isLocked(err) {
347
+ return LOCKED_CODES.has(err?.code ?? "");
348
+ }
349
+ function removeDir(path) {
350
+ return rm(path, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 });
351
+ }
336
352
  async function prepareWorktree(input) {
337
353
  const ref = parseRepoUrl(input.url);
338
354
  if (!ref) throw new Error(repositoryUrlError(input.url));
339
355
  assertSafeRef(input.workBranch, "Work branch");
340
356
  if (input.baseRef) assertSafeRef(input.baseRef, "Base branch");
341
357
  const repoDir = join2(input.reposDir, ref.owner, ref.repo);
342
- const worktree = join2(input.worktreesDir, input.worktreeKey || input.sessionId);
358
+ const ownWorktree = join2(input.worktreesDir, input.sessionId);
359
+ let worktree = join2(input.worktreesDir, input.worktreeKey || input.sessionId);
360
+ const remove = input.removeDir ?? removeDir;
343
361
  return withRepoLock(repoDir, async () => {
344
362
  if (!await exists(join2(repoDir, ".git"))) {
345
363
  await mkdir(dirname(repoDir), { recursive: true });
@@ -373,6 +391,8 @@ async function prepareWorktree(input) {
373
391
  let checkout = start2;
374
392
  let continuedFrom;
375
393
  let setAside;
394
+ let leftInPlace;
395
+ let dirtyKept = false;
376
396
  const remoteWork = `refs/remotes/origin/${input.workBranch}`;
377
397
  if (input.continueBranch && await exists(worktree) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
378
398
  cwd: worktree,
@@ -437,11 +457,33 @@ async function prepareWorktree(input) {
437
457
  if (dirty.code === 0 && dirty.stdout.trim()) {
438
458
  const aside = `${worktree}.kept-${Date.now()}`;
439
459
  if (await gitOk(repoDir, ["worktree", "move", worktree, aside])) setAside = aside;
460
+ else dirtyKept = true;
440
461
  }
441
462
  }
442
463
  if (await exists(worktree)) {
443
- await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
444
- await rm(worktree, { recursive: true, force: true });
464
+ let failure = null;
465
+ if (!dirtyKept) {
466
+ await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
467
+ failure = await remove(worktree).then(
468
+ () => null,
469
+ (err) => {
470
+ if (!isLocked(err)) throw err;
471
+ return err;
472
+ }
473
+ );
474
+ }
475
+ if (dirtyKept || failure) {
476
+ if (worktree === ownWorktree) {
477
+ throw failure ?? new Error(`The working copy at ${worktree} could not be replaced.`);
478
+ }
479
+ leftInPlace = worktree;
480
+ await gitOk(repoDir, ["-C", leftInPlace, "checkout", "--quiet", "--detach"]);
481
+ worktree = ownWorktree;
482
+ if (await exists(worktree)) {
483
+ await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
484
+ await remove(worktree);
485
+ }
486
+ }
445
487
  }
446
488
  await gitOk(repoDir, ["worktree", "prune"]);
447
489
  await mkdir(input.worktreesDir, { recursive: true });
@@ -449,6 +491,8 @@ async function prepareWorktree(input) {
449
491
  "worktree",
450
492
  "add",
451
493
  "--no-track",
494
+ // A folder left in place may still be registered with the work branch checked out.
495
+ ...leftInPlace ? ["--force"] : [],
452
496
  "-B",
453
497
  input.workBranch,
454
498
  worktree,
@@ -460,7 +504,8 @@ async function prepareWorktree(input) {
460
504
  baseRef,
461
505
  baseSha,
462
506
  ...continuedFrom ? { continuedFrom } : {},
463
- ...setAside ? { setAside } : {}
507
+ ...setAside ? { setAside } : {},
508
+ ...leftInPlace ? { leftInPlace } : {}
464
509
  };
465
510
  });
466
511
  }
@@ -529,7 +574,7 @@ async function removeWorktree(repoDir, worktree) {
529
574
  if (repoDir && await exists(repoDir)) {
530
575
  await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
531
576
  }
532
- await rm(worktree, { recursive: true, force: true });
577
+ await removeDir(worktree);
533
578
  if (repoDir && await exists(repoDir)) await gitOk(repoDir, ["worktree", "prune"]);
534
579
  }
535
580
  function errorText(err, prefix) {
@@ -746,10 +791,17 @@ async function claudeFeatures(bin) {
746
791
  const res = await exec(bin, ["--help"], { timeoutMs: 15e3 });
747
792
  return {
748
793
  permissionPrompts: res.stdout.includes("--permission-prompts"),
749
- settingSources: res.stdout.includes("--setting-sources")
794
+ settingSources: res.stdout.includes("--setting-sources"),
795
+ maxTurns: res.stdout.includes("--max-turns"),
796
+ strictMcpConfig: res.stdout.includes("--strict-mcp-config")
750
797
  };
751
798
  } catch {
752
- return { permissionPrompts: false, settingSources: false };
799
+ return {
800
+ permissionPrompts: false,
801
+ settingSources: false,
802
+ maxTurns: false,
803
+ strictMcpConfig: false
804
+ };
753
805
  }
754
806
  }
755
807
  async function probeAgent(env = process.env) {
@@ -1132,8 +1184,100 @@ function sleep(ms, signal) {
1132
1184
  });
1133
1185
  }
1134
1186
 
1187
+ // src/completion.ts
1188
+ import { mkdtemp as mkdtemp2, rm as rm4 } from "node:fs/promises";
1189
+ import { tmpdir as tmpdir2 } from "node:os";
1190
+ import { join as join6 } from "node:path";
1191
+ var COMPLETION_DENIED_TOOLS = [
1192
+ "Read",
1193
+ "Glob",
1194
+ "Grep",
1195
+ "LS",
1196
+ "Bash",
1197
+ "Edit",
1198
+ "MultiEdit",
1199
+ "Write",
1200
+ "NotebookEdit",
1201
+ "WebFetch",
1202
+ "WebSearch",
1203
+ "Task"
1204
+ ];
1205
+ var COMPLETION_TIMEOUT_MS = 5 * 60 * 1e3;
1206
+ var COMPLETION_MIN_TIME_MS = 1e4;
1207
+ var CANCELLED_BY_SERVER = "Discovery Tree stopped waiting for this answer.";
1208
+ var RUNNER_STOPPING = "The runner stopped before it could answer.";
1209
+ var EXPIRED_WHILE_QUEUED = "Discovery Tree stopped waiting before this runner had a free slot to answer it.";
1210
+ var COMPLETION_SYSTEM_PROMPT = "You are answering one request for Discovery Tree through the person\u2019s local runner. There is no repository and you have no tools: answer from the request alone.";
1211
+ var NEEDS_STRICT_MCP = "This Claude Code is too old to answer planning requests safely (it has no --strict-mcp-config). Update Claude Code.";
1212
+ function completionArgs(req, features) {
1213
+ if (!features.strictMcpConfig) throw new Error(NEEDS_STRICT_MCP);
1214
+ const args = [
1215
+ "-p",
1216
+ "--output-format",
1217
+ "json",
1218
+ "--permission-mode",
1219
+ "default",
1220
+ "--strict-mcp-config"
1221
+ ];
1222
+ if (features.permissionPrompts) args.push("--permission-prompts", "none");
1223
+ if (features.settingSources) args.push("--setting-sources", "user");
1224
+ if (features.maxTurns) args.push("--max-turns", "1");
1225
+ if (req.model) {
1226
+ assertValidModel(req.model);
1227
+ args.push(`--model=${req.model}`);
1228
+ }
1229
+ args.push("--append-system-prompt", COMPLETION_SYSTEM_PROMPT);
1230
+ args.push("--disallowedTools", ...COMPLETION_DENIED_TOOLS);
1231
+ return args;
1232
+ }
1233
+ async function answerCompletion(req, deps) {
1234
+ let cwd = null;
1235
+ try {
1236
+ const { bin, features } = await deps.claude();
1237
+ const args = completionArgs(req, features);
1238
+ cwd = await mkdtemp2(join6(tmpdir2(), "dt-runner-completion-"));
1239
+ const run = deps.run ?? ((b, a, o) => exec(b, a, o));
1240
+ const input = req.systemPrompt ? `<instructions>
1241
+ ${req.systemPrompt}
1242
+ </instructions>
1243
+
1244
+ <request>
1245
+ ${req.prompt}
1246
+ </request>` : req.prompt;
1247
+ const timeoutMs = Math.min(COMPLETION_TIMEOUT_MS, deps.timeoutMs ?? COMPLETION_TIMEOUT_MS);
1248
+ if (deps.signal?.aborted) return { ok: false, error: RUNNER_STOPPING };
1249
+ const res = await run(bin, args, { cwd, input, timeoutMs, signal: deps.signal });
1250
+ if (deps.signal?.aborted) return { ok: false, error: RUNNER_STOPPING };
1251
+ return readResult(res);
1252
+ } catch (err) {
1253
+ const message = err instanceof Error ? err.message : String(err);
1254
+ return { ok: false, error: message.slice(0, 2e3) };
1255
+ } finally {
1256
+ if (cwd) await rm4(cwd, { recursive: true, force: true }).catch(() => void 0);
1257
+ }
1258
+ }
1259
+ function readResult(res) {
1260
+ let parsed = null;
1261
+ try {
1262
+ const last = res.stdout.trim().split("\n").pop() ?? "";
1263
+ parsed = JSON.parse(last);
1264
+ } catch {
1265
+ parsed = null;
1266
+ }
1267
+ const text = typeof parsed?.result === "string" ? parsed.result : "";
1268
+ if (parsed?.type === "result" && parsed.is_error !== true && res.code === 0 && text.trim()) {
1269
+ return { ok: true, text: text.slice(0, RUNNER_COMPLETION_MAX_TEXT) };
1270
+ }
1271
+ const why = text.trim() || res.stderr.trim().split("\n").slice(-3).join(" ") || (res.code === null ? `Claude Code did not answer within ${COMPLETION_TIMEOUT_MS / 6e4} minutes.` : `Claude Code exited with code ${res.code} and no answer.`);
1272
+ return {
1273
+ ok: false,
1274
+ error: why.slice(0, 2e3),
1275
+ signInFailed: looksLikeSignInFailure(why)
1276
+ };
1277
+ }
1278
+
1135
1279
  // src/session-manager.ts
1136
- import { mkdir as mkdir6, rm as rm5 } from "node:fs/promises";
1280
+ import { mkdir as mkdir6, rm as rm6 } from "node:fs/promises";
1137
1281
 
1138
1282
  // src/fsutil.ts
1139
1283
  import { mkdir as mkdir4, readFile as readFile3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
@@ -1541,40 +1685,40 @@ function signalGroup(pgid, signal) {
1541
1685
  }
1542
1686
 
1543
1687
  // src/session-store.ts
1544
- import { mkdir as mkdir5, readdir as readdir2, rm as rm4 } from "node:fs/promises";
1545
- import { join as join6 } from "node:path";
1688
+ import { mkdir as mkdir5, readdir as readdir2, rm as rm5 } from "node:fs/promises";
1689
+ import { join as join7 } from "node:path";
1546
1690
  var HANDLED_COMMAND_IDS_KEPT = 100;
1547
1691
  var SessionStore = class {
1548
1692
  constructor(stateDir) {
1549
1693
  this.stateDir = stateDir;
1550
1694
  }
1551
1695
  dir(sessionId) {
1552
- return join6(this.stateDir, "sessions", sessionId);
1696
+ return join7(this.stateDir, "sessions", sessionId);
1553
1697
  }
1554
1698
  outboxFile(sessionId) {
1555
- return join6(this.dir(sessionId), "outbox.json");
1699
+ return join7(this.dir(sessionId), "outbox.json");
1556
1700
  }
1557
1701
  async save(record) {
1558
1702
  record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1559
- await writeJsonAtomic(join6(this.dir(record.sessionId), "session.json"), record);
1703
+ await writeJsonAtomic(join7(this.dir(record.sessionId), "session.json"), record);
1560
1704
  }
1561
1705
  async list() {
1562
- const root = join6(this.stateDir, "sessions");
1706
+ const root = join7(this.stateDir, "sessions");
1563
1707
  await mkdir5(root, { recursive: true });
1564
1708
  const out = [];
1565
1709
  for (const entry of await readdir2(root, { withFileTypes: true })) {
1566
1710
  if (!entry.isDirectory()) continue;
1567
- const rec = await readJson(join6(root, entry.name, "session.json"));
1711
+ const rec = await readJson(join7(root, entry.name, "session.json"));
1568
1712
  if (rec?.sessionId === entry.name) out.push(rec);
1569
1713
  }
1570
1714
  return out;
1571
1715
  }
1572
1716
  async remove(sessionId) {
1573
- await rm4(this.dir(sessionId), { recursive: true, force: true });
1717
+ await rm5(this.dir(sessionId), { recursive: true, force: true });
1574
1718
  }
1575
1719
  /** Scratch working directory for a session without a repository. */
1576
1720
  scratchDir(sessionId) {
1577
- return join6(this.stateDir, "scratch", sessionId);
1721
+ return join7(this.stateDir, "scratch", sessionId);
1578
1722
  }
1579
1723
  };
1580
1724
  function assertSafeSessionId(id) {
@@ -2605,6 +2749,11 @@ var SessionManager = class {
2605
2749
  // protecting it until a turn commits them, or a close before then would delete them.
2606
2750
  ...wt.continuedFrom === "worktree" ? { keepWorktree: true } : {}
2607
2751
  });
2752
+ if (wt.leftInPlace) {
2753
+ this.opts.logger.warn(
2754
+ `session ${cmd.sessionId}: the earlier working copy at ${wt.leftInPlace} is in use (close any terminal, editor or program open in it) and was left as it is; this session works in ${wt.worktree}`
2755
+ );
2756
+ }
2608
2757
  if (wt.setAside) {
2609
2758
  this.opts.logger.warn(
2610
2759
  `session ${cmd.sessionId}: an earlier working copy with uncommitted changes could not be reused; it was moved to ${wt.setAside}`
@@ -2728,7 +2877,7 @@ var SessionManager = class {
2728
2877
  })
2729
2878
  );
2730
2879
  } else if (record.cwd) {
2731
- await rm5(record.cwd, { recursive: true, force: true }).catch(() => void 0);
2880
+ await rm6(record.cwd, { recursive: true, force: true }).catch(() => void 0);
2732
2881
  }
2733
2882
  await session.outbox.settled();
2734
2883
  await this.store.remove(sessionId);
@@ -2861,6 +3010,11 @@ var RunnerDaemon = class {
2861
3010
  /** The tail of each session's command queue (see `inSessionOrder`); never rejects. */
2862
3011
  sessionQueues = /* @__PURE__ */ new Map();
2863
3012
  upgradeWarnedAt = 0;
3013
+ /** Completions answering now, and those waiting for a turn (see `answer`). */
3014
+ completionsRunning = 0;
3015
+ /** Each planning request held (answering or queued), to cancel it when Discovery Tree says. */
3016
+ completionControllers = /* @__PURE__ */ new Map();
3017
+ completionWaiters = [];
2864
3018
  get signal() {
2865
3019
  return this.controller.signal;
2866
3020
  }
@@ -2942,11 +3096,17 @@ var RunnerDaemon = class {
2942
3096
  agent: {
2943
3097
  ...await this.agent(),
2944
3098
  resumesClosedSessions: true,
2945
- opensPullRequests: true
3099
+ opensPullRequests: true,
3100
+ // And answers one-off requests, such as planning, outside any session.
3101
+ answersCompletions: true
2946
3102
  },
2947
3103
  activeSessionIds: this.manager.activeSessionIds(),
2948
- maxConcurrentSessions: this.opts.config.maxSessions
3104
+ maxConcurrentSessions: this.opts.config.maxSessions,
3105
+ activeCompletionIds: [...this.completionControllers.keys()]
2949
3106
  });
3107
+ for (const id of res?.cancelCompletionIds ?? []) {
3108
+ this.completionControllers.get(id)?.abort();
3109
+ }
2950
3110
  if (failures) this.opts.logger.info("reconnected to Discovery Tree");
2951
3111
  failures = 0;
2952
3112
  for (const id of res?.closeSessionIds ?? []) {
@@ -2982,6 +3142,7 @@ var RunnerDaemon = class {
2982
3142
  attempt = 0;
2983
3143
  limited = 0;
2984
3144
  for (const cmd of res?.commands ?? []) this.track(this.dispatch(cmd));
3145
+ for (const req of res?.completions ?? []) this.track(this.answer(req));
2985
3146
  } catch (err) {
2986
3147
  if (this.signal.aborted) break;
2987
3148
  if (err instanceof UnauthorizedError) return this.unauthorized(err);
@@ -3048,6 +3209,98 @@ var RunnerDaemon = class {
3048
3209
  }
3049
3210
  await this.ack(cmd.id, ack);
3050
3211
  }
3212
+ /**
3213
+ * A slot to run a completion in: at once while fewer than the runner's session limit run,
3214
+ * else after the next one ends. False when `cancelled` fires first: the request leaves
3215
+ * the line without a slot, so it must not give one back.
3216
+ */
3217
+ takeCompletionSlot(cancelled) {
3218
+ if (cancelled.aborted) return Promise.resolve(false);
3219
+ if (this.completionsRunning < Math.max(1, this.opts.config.maxSessions)) {
3220
+ this.completionsRunning++;
3221
+ return Promise.resolve(true);
3222
+ }
3223
+ return new Promise((resolve) => {
3224
+ const handOver = () => {
3225
+ cancelled.removeEventListener("abort", leave);
3226
+ resolve(true);
3227
+ };
3228
+ const leave = () => {
3229
+ const at = this.completionWaiters.indexOf(handOver);
3230
+ if (at >= 0) this.completionWaiters.splice(at, 1);
3231
+ resolve(false);
3232
+ };
3233
+ this.completionWaiters.push(handOver);
3234
+ cancelled.addEventListener("abort", leave, { once: true });
3235
+ });
3236
+ }
3237
+ /** A finished completion's slot goes straight to the next in line, or is freed. */
3238
+ giveBackCompletionSlot() {
3239
+ const next = this.completionWaiters.shift();
3240
+ if (next) next();
3241
+ else this.completionsRunning--;
3242
+ }
3243
+ /**
3244
+ * Answers a one-off request and posts the answer, retried a few times. Discovery Tree
3245
+ * waits for it while the person does, so there is no later redelivery to fall back on.
3246
+ */
3247
+ async answer(req) {
3248
+ const receivedAt = Date.now();
3249
+ const own = new AbortController();
3250
+ this.completionControllers.set(req.id, own);
3251
+ const cancelled = AbortSignal.any([this.signal, own.signal]);
3252
+ const acquired = await this.takeCompletionSlot(cancelled);
3253
+ let result;
3254
+ try {
3255
+ const left = typeof req.timeLeftMs === "number" ? req.timeLeftMs - (Date.now() - receivedAt) : null;
3256
+ if (own.signal.aborted) {
3257
+ result = { ok: false, error: CANCELLED_BY_SERVER };
3258
+ } else if (this.signal.aborted) {
3259
+ result = { ok: false, error: RUNNER_STOPPING };
3260
+ } else if (!acquired) {
3261
+ result = { ok: false, error: RUNNER_STOPPING };
3262
+ } else if (left !== null && left < COMPLETION_MIN_TIME_MS) {
3263
+ this.opts.logger.warn("skipped a planning request that expired while queued", {
3264
+ id: req.id
3265
+ });
3266
+ result = { ok: false, error: EXPIRED_WHILE_QUEUED };
3267
+ } else {
3268
+ this.opts.logger.info("answering a planning request", { id: req.id });
3269
+ result = await answerCompletion(req, {
3270
+ claude: () => this.resolveClaude(),
3271
+ signal: cancelled,
3272
+ ...left !== null ? { timeoutMs: left } : {}
3273
+ });
3274
+ }
3275
+ if (own.signal.aborted) result = { ok: false, error: CANCELLED_BY_SERVER };
3276
+ } finally {
3277
+ this.completionControllers.delete(req.id);
3278
+ if (acquired) this.giveBackCompletionSlot();
3279
+ }
3280
+ if (!result.ok) {
3281
+ this.opts.logger.warn("could not answer a planning request", {
3282
+ id: req.id,
3283
+ error: result.error
3284
+ });
3285
+ }
3286
+ if (result.signInFailed) this.claudeSignIn(false);
3287
+ else if (result.ok) this.claudeSignIn(true);
3288
+ for (let attempt = 0; attempt < 5; attempt++) {
3289
+ try {
3290
+ await this.api.postCompletion(req.id, result);
3291
+ return;
3292
+ } catch (err) {
3293
+ if (err instanceof UnauthorizedError) return this.unauthorized(err);
3294
+ if (!isRetryable(err)) {
3295
+ this.opts.logger.warn("the server refused a planning answer", {
3296
+ error: err.message
3297
+ });
3298
+ return;
3299
+ }
3300
+ await sleep(backoffDelay(attempt, this.opts.retryBaseMs ?? 1e3, 1e4));
3301
+ }
3302
+ }
3303
+ }
3051
3304
  /** Acks are retried a few times; a lost one means a redelivery, which handlers absorb. */
3052
3305
  async ack(commandId, body) {
3053
3306
  for (let attempt = 0; attempt < 5; attempt++) {
@@ -3152,10 +3405,10 @@ function formatChecks(checks) {
3152
3405
  }
3153
3406
 
3154
3407
  // src/lock.ts
3155
- import { mkdir as mkdir7, open, readFile as readFile4, rm as rm6 } from "node:fs/promises";
3156
- import { join as join7 } from "node:path";
3408
+ import { mkdir as mkdir7, open, readFile as readFile4, rm as rm7 } from "node:fs/promises";
3409
+ import { join as join8 } from "node:path";
3157
3410
  function lockFile(stateDir) {
3158
- return join7(stateDir, "daemon.pid");
3411
+ return join8(stateDir, "daemon.pid");
3159
3412
  }
3160
3413
  function pidAlive(pid) {
3161
3414
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -3194,7 +3447,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
3194
3447
  file,
3195
3448
  async release() {
3196
3449
  const current = await readFile4(file, "utf8").catch(() => "");
3197
- if (Number.parseInt(current.trim(), 10) === pid) await rm6(file, { force: true });
3450
+ if (Number.parseInt(current.trim(), 10) === pid) await rm7(file, { force: true });
3198
3451
  }
3199
3452
  }
3200
3453
  };
@@ -3205,7 +3458,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
3205
3458
  if (raw === null) continue;
3206
3459
  const holder = Number.parseInt(raw.trim(), 10);
3207
3460
  if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
3208
- await rm6(file, { force: true });
3461
+ await rm7(file, { force: true });
3209
3462
  }
3210
3463
  return { ok: false, pid: null };
3211
3464
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@discovery-tree/runner",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "dt-runner: run Discovery Tree agent sessions on your own computer with your own signed-in Claude Code",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {