@discovery-tree/runner 0.1.1 → 0.1.3

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 +12 -0
  2. package/dist/cli.js +334 -32
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -199,8 +199,20 @@ worktree.
199
199
 
200
200
  ## Troubleshooting
201
201
 
202
+ - **`dt-runner: command not found`** — `dt-runner` exists only once installed
203
+ (`npm install -g @discovery-tree/runner`). Under `npx`, type `npx @discovery-tree/runner@latest`
204
+ in its place; the runner's own hints are written that way when it was started with `npx` (or
205
+ `pnpm dlx`).
202
206
  - **`dt-runner doctor` says Claude Code is not signed in** — run `claude` in a terminal and sign in,
203
207
  then try again.
208
+ - **"Claude Code could not sign in to Claude" (for example "OAuth session expired and could not
209
+ be refreshed")** — Claude Code's saved sign-in ran out. `claude auth status` (and so `doctor`)
210
+ can still say it is signed in. Run `claude`, type `/login`, check that `claude -p "say ok"`
211
+ answers, then send a message in the run to try again. Until a later turn succeeds the runner
212
+ reports Claude Code as not ready, so the Local runners list shows it too.
213
+ - **"Claude Code (your computer)" is not offered for a run** — the runner must be running
214
+ (`start`, not just `login`), the task must produce code, and you must be a member of the
215
+ workspace, not an invited collaborator.
204
216
  - **Turns fail with "Claude Code exited …"** — run `dt-runner start --verbose`. Check that
205
217
  `claude -p "say ok"` works in a terminal as the same user.
206
218
  - **Pushing the work branch failed** — the turn fails with the git error and says where the work
package/dist/cli.js CHANGED
@@ -33,7 +33,7 @@ var RUNNER_EVENT_TEXT_MAX_LENGTH = 64e3;
33
33
  var RUNNER_EVENTS_MAX_BODY_BYTES = 8 * 1024 * 1024;
34
34
 
35
35
  // src/version.ts
36
- var RUNNER_VERSION = true ? "0.1.1" : "0.0.0-dev";
36
+ var RUNNER_VERSION = true ? "0.1.3" : "0.0.0-dev";
37
37
  var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
38
38
 
39
39
  // src/api.ts
@@ -264,6 +264,19 @@ async function probeAgent(env = process.env) {
264
264
  }
265
265
  return { claudeVersion: version, claudeReady: auth.loggedIn, claudeProblem: null };
266
266
  }
267
+ var SIGN_IN_FAILURE = /failed to authenticate|oauth (session|token)\b[^.]*\bexpired|invalid (x-)?api[ -]key|authentication_error|please run \/login/i;
268
+ function looksLikeSignInFailure(text) {
269
+ return !!text && SIGN_IN_FAILURE.test(text);
270
+ }
271
+ function turnFailedToSignIn(turn) {
272
+ return (turn.subtype ?? "success") === "success" && looksLikeSignInFailure(turn.text);
273
+ }
274
+ function signInFix(env = process.env) {
275
+ if (env.ANTHROPIC_API_KEY) {
276
+ return "`ANTHROPIC_API_KEY` is set where the runner runs, so Claude Code signs in with that key instead of your Claude subscription. Unset it (or replace it with a working key) and restart the runner.";
277
+ }
278
+ return 'On the runner\u2019s computer, run `claude`, type `/login` and sign in again, and check that `claude -p "say ok"` answers.';
279
+ }
267
280
  var MODEL_NAME = /^[A-Za-z0-9][\w.:@/[\]-]{0,199}$/;
268
281
  function isValidModelName(model) {
269
282
  return MODEL_NAME.test(model);
@@ -326,6 +339,18 @@ function runnerSystemPrompt(input) {
326
339
  import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
327
340
  import { homedir } from "node:os";
328
341
  import { dirname, join as join2 } from "node:path";
342
+
343
+ // src/invocation.ts
344
+ var RUNNER_PACKAGE = "@discovery-tree/runner";
345
+ function launchedByNpx(env = process.env, argv1 = process.argv[1]) {
346
+ if (env.npm_command === "exec") return true;
347
+ return /[\\/](_npx|dlx)[\\/]/.test(argv1 ?? "");
348
+ }
349
+ function runnerCommand(subcommand, viaNpx = launchedByNpx()) {
350
+ return viaNpx ? `npx ${RUNNER_PACKAGE}@latest ${subcommand}` : `dt-runner ${subcommand}`;
351
+ }
352
+
353
+ // src/config.ts
329
354
  function runnerPaths(env = process.env) {
330
355
  const home = homedir();
331
356
  if (process.platform === "win32") {
@@ -465,7 +490,9 @@ async function readConfigFile(file) {
465
490
  try {
466
491
  return JSON.parse(raw);
467
492
  } catch {
468
- throw new Error(`${file} is not valid JSON; fix it or run \`dt-runner logout\` to start over.`);
493
+ throw new Error(
494
+ `${file} is not valid JSON; fix it or run \`${runnerCommand("logout")}\` to start over.`
495
+ );
469
496
  }
470
497
  }
471
498
  async function writeConfigFile(file, config) {
@@ -667,7 +694,7 @@ async function prepareWorktree(input) {
667
694
  assertSafeRef(input.workBranch, "Work branch");
668
695
  if (input.baseRef) assertSafeRef(input.baseRef, "Base branch");
669
696
  const repoDir = join3(input.reposDir, ref.owner, ref.repo);
670
- const worktree = join3(input.worktreesDir, input.sessionId);
697
+ const worktree = join3(input.worktreesDir, input.worktreeKey || input.sessionId);
671
698
  return withRepoLock(repoDir, async () => {
672
699
  if (!await exists(join3(repoDir, ".git"))) {
673
700
  await mkdir2(dirname2(repoDir), { recursive: true });
@@ -697,15 +724,99 @@ async function prepareWorktree(input) {
697
724
  }
698
725
  start2 = baseRef;
699
726
  }
700
- const baseSha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
727
+ let baseSha = await git(repoDir, ["rev-parse", `${start2}^{commit}`]);
728
+ let checkout = start2;
729
+ let continuedFrom;
730
+ let setAside;
731
+ const remoteWork = `refs/remotes/origin/${input.workBranch}`;
732
+ if (input.continueBranch && await exists(worktree) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
733
+ cwd: worktree,
734
+ env: gitEnv(),
735
+ timeoutMs: 6e4
736
+ }).then((r) => r.code === 0 && r.stdout.trim() === input.workBranch) && // Only when it already has everything pushed to the work branch since: one that fell
737
+ // behind (the run went on elsewhere) would have the agent work on stale code.
738
+ (!await gitOk(repoDir, ["rev-parse", "--verify", "--quiet", `${remoteWork}^{commit}`]) || await exec("git", ["merge-base", "--is-ancestor", remoteWork, "HEAD"], {
739
+ cwd: worktree,
740
+ env: gitEnv(),
741
+ timeoutMs: 6e4
742
+ }).then((r) => r.code === 0))) {
743
+ const forkPoint = await exec("git", ["merge-base", "HEAD", start2], {
744
+ cwd: worktree,
745
+ env: gitEnv(),
746
+ timeoutMs: 6e4
747
+ });
748
+ if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
749
+ return { repoDir, worktree, baseRef, baseSha, continuedFrom: "worktree" };
750
+ }
751
+ if (input.continueBranch) {
752
+ const remote = `refs/remotes/origin/${input.workBranch}`;
753
+ const local = `refs/heads/${input.workBranch}`;
754
+ const hasRemote = await gitOk(repoDir, [
755
+ "rev-parse",
756
+ "--verify",
757
+ "--quiet",
758
+ `${remote}^{commit}`
759
+ ]);
760
+ const hasLocal = await gitOk(repoDir, [
761
+ "rev-parse",
762
+ "--verify",
763
+ "--quiet",
764
+ `${local}^{commit}`
765
+ ]);
766
+ const localAhead = hasLocal && (!hasRemote || await gitOk(repoDir, ["merge-base", "--is-ancestor", remote, local]));
767
+ if (localAhead) {
768
+ checkout = local;
769
+ continuedFrom = "local";
770
+ } else if (hasRemote) {
771
+ checkout = remote;
772
+ continuedFrom = "remote";
773
+ } else {
774
+ continuedFrom = "base";
775
+ }
776
+ if (continuedFrom !== "base") {
777
+ const forkPoint = await exec("git", ["merge-base", checkout, start2], {
778
+ cwd: repoDir,
779
+ env: gitEnv(),
780
+ timeoutMs: 6e4
781
+ });
782
+ if (forkPoint.code === 0 && forkPoint.stdout.trim()) baseSha = forkPoint.stdout.trim();
783
+ checkout = await git(repoDir, ["rev-parse", `${checkout}^{commit}`]);
784
+ }
785
+ }
786
+ if (input.continueBranch && await exists(worktree)) {
787
+ const dirty = await exec("git", ["status", "--porcelain"], {
788
+ cwd: worktree,
789
+ env: gitEnv(),
790
+ timeoutMs: 6e4
791
+ });
792
+ if (dirty.code === 0 && dirty.stdout.trim()) {
793
+ const aside = `${worktree}.kept-${Date.now()}`;
794
+ if (await gitOk(repoDir, ["worktree", "move", worktree, aside])) setAside = aside;
795
+ }
796
+ }
701
797
  if (await exists(worktree)) {
702
798
  await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
703
799
  await rm2(worktree, { recursive: true, force: true });
704
800
  }
705
801
  await gitOk(repoDir, ["worktree", "prune"]);
706
802
  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 };
803
+ await git(repoDir, [
804
+ "worktree",
805
+ "add",
806
+ "--no-track",
807
+ "-B",
808
+ input.workBranch,
809
+ worktree,
810
+ checkout
811
+ ]);
812
+ return {
813
+ repoDir,
814
+ worktree,
815
+ baseRef,
816
+ baseSha,
817
+ ...continuedFrom ? { continuedFrom } : {},
818
+ ...setAside ? { setAside } : {}
819
+ };
709
820
  });
710
821
  }
711
822
  async function defaultBranch(repoDir) {
@@ -1294,6 +1405,17 @@ var AgentSession = class {
1294
1405
  controlSeq = 0;
1295
1406
  stderrTail = "";
1296
1407
  sawResultSinceSpawn = false;
1408
+ /** The process was started with `--resume`, and has not yet said it has the conversation. */
1409
+ spawnedWithResume = false;
1410
+ sawInitSinceSpawn = false;
1411
+ /** The message that began the current turn, as the person wrote it (before any preface). */
1412
+ turnText = null;
1413
+ /**
1414
+ * Set when `--resume` found no conversation (Claude Code keeps them per computer and per
1415
+ * directory): once the process has exited, the turn's message is sent again to a fresh
1416
+ * conversation, with the preface the continuation brought.
1417
+ */
1418
+ resumeRetry = null;
1297
1419
  exitWaiters = [];
1298
1420
  lastActivity = Date.now();
1299
1421
  get sessionId() {
@@ -1402,7 +1524,19 @@ var AgentSession = class {
1402
1524
  */
1403
1525
  async beginTurn(text, before) {
1404
1526
  while (!this.child || this.stopping) await this.ensureProcess();
1405
- this.write({ type: "user", message: { role: "user", content: text } });
1527
+ let content = text;
1528
+ const preface = this.record.freshPreface;
1529
+ if (preface && !this.spawnedWithResume) {
1530
+ content = `${preface}
1531
+
1532
+ ---
1533
+
1534
+ ${text}`;
1535
+ this.record.freshPreface = null;
1536
+ await this.deps.store.save(this.record);
1537
+ }
1538
+ this.write({ type: "user", message: { role: "user", content } });
1539
+ if (!this.record.turnActive) this.turnText = text;
1406
1540
  this.lastActivity = Date.now();
1407
1541
  if (before) this.emit(before);
1408
1542
  if (!this.record.turnActive) {
@@ -1457,6 +1591,8 @@ var AgentSession = class {
1457
1591
  this.stopping = null;
1458
1592
  this.stderrTail = "";
1459
1593
  this.sawResultSinceSpawn = false;
1594
+ this.spawnedWithResume = !!this.record.claudeSessionId;
1595
+ this.sawInitSinceSpawn = false;
1460
1596
  this.deps.logger.info(
1461
1597
  `session ${this.sessionId}: Claude Code started${this.record.claudeSessionId ? " (resumed)" : ""}`,
1462
1598
  { pid: child.pid }
@@ -1490,8 +1626,11 @@ var AgentSession = class {
1490
1626
  this.lastActivity = Date.now();
1491
1627
  const mapped = this.mapper.map(line);
1492
1628
  let dirty = false;
1629
+ if (mapped.claudeSessionId) this.sawInitSinceSpawn = true;
1630
+ let learnedSessionId = null;
1493
1631
  if (mapped.claudeSessionId && mapped.claudeSessionId !== this.record.claudeSessionId) {
1494
1632
  this.record.claudeSessionId = mapped.claudeSessionId;
1633
+ learnedSessionId = mapped.claudeSessionId;
1495
1634
  dirty = true;
1496
1635
  }
1497
1636
  if (mapped.turnStarted && !this.record.turnActive) {
@@ -1499,18 +1638,54 @@ var AgentSession = class {
1499
1638
  dirty = true;
1500
1639
  }
1501
1640
  if (dirty) await this.deps.store.save(this.record);
1641
+ if (learnedSessionId) {
1642
+ const at = mapped.events.findIndex((e) => e.type === "status");
1643
+ if (at >= 0) {
1644
+ mapped.events[at] = {
1645
+ ...mapped.events[at],
1646
+ claudeSessionId: learnedSessionId
1647
+ };
1648
+ } else {
1649
+ mapped.events.push({
1650
+ type: "status",
1651
+ status: "running",
1652
+ claudeSessionId: learnedSessionId
1653
+ });
1654
+ }
1655
+ }
1502
1656
  if (mapped.events.length) this.emit(...mapped.events);
1657
+ if (mapped.turnEnd && this.resumeNotFound(mapped.turnEnd.isError)) {
1658
+ this.planFreshRetry();
1659
+ this.child?.stdin.end();
1660
+ return;
1661
+ }
1503
1662
  if (mapped.turnEnd) {
1504
1663
  this.sawResultSinceSpawn = true;
1505
1664
  await this.endTurn(mapped.turnEnd);
1506
1665
  }
1507
1666
  }
1667
+ /**
1668
+ * The process was started to resume a conversation and failed before it said it had it
1669
+ * (no `system/init`): Claude Code did not find the conversation on this computer.
1670
+ */
1671
+ resumeNotFound(isError) {
1672
+ return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && this.turnText !== null;
1673
+ }
1674
+ planFreshRetry() {
1675
+ this.deps.logger.warn(
1676
+ `session ${this.sessionId}: the Claude Code conversation to resume was not found; starting a fresh one`
1677
+ );
1678
+ this.resumeRetry = this.turnText;
1679
+ this.record.claudeSessionId = null;
1680
+ }
1508
1681
  async endTurn(turn) {
1509
1682
  const interrupted = this.interruptRequested;
1510
1683
  this.interruptRequested = false;
1511
1684
  if (this.interruptTimer) clearTimeout(this.interruptTimer);
1512
1685
  this.interruptTimer = null;
1513
1686
  const turnFailed = turn.isError && !interrupted;
1687
+ if (turnFailed && turnFailedToSignIn(turn)) this.deps.onClaudeSignIn?.(false);
1688
+ else if (!turn.isError) this.deps.onClaudeSignIn?.(true);
1514
1689
  if (turnFailed) {
1515
1690
  this.emit({
1516
1691
  type: "error",
@@ -1526,7 +1701,13 @@ var AgentSession = class {
1526
1701
  type: "result",
1527
1702
  status: failed ? "failed" : "idle",
1528
1703
  text: interrupted ? turn.isError ? null : turn.text : turn.text,
1529
- branch: push.branch
1704
+ branch: push.branch,
1705
+ // The turn's work is only on this computer (committing or pushing it failed): a
1706
+ // continuation of the run must come back to this runner to find it.
1707
+ ...push.failed ? { unpushedWork: true } : {},
1708
+ // So the server can have a later session resume this conversation (a run continued
1709
+ // after it ended).
1710
+ ...this.record.claudeSessionId ? { claudeSessionId: this.record.claudeSessionId } : {}
1530
1711
  });
1531
1712
  this.lastActivity = Date.now();
1532
1713
  this.deps.logger.info(
@@ -1547,8 +1728,13 @@ var AgentSession = class {
1547
1728
  baseSha,
1548
1729
  message: "Uncommitted changes from the agent\u2019s turn\n\nCommitted by dt-runner at the end of a Discovery Tree agent turn."
1549
1730
  });
1731
+ const uncommitted = res.failedAt === "commit";
1732
+ if (!!this.record.keepWorktree !== uncommitted) {
1733
+ this.record.keepWorktree = uncommitted;
1734
+ await this.deps.store.save(this.record);
1735
+ }
1550
1736
  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.`;
1737
+ const kept = uncommitted ? ` The changes are still uncommitted in the worktree ${cwd}, which is kept when the session closes: continuing the run on this computer picks them up, or commit them there.` : ` The work is kept on the local branch ${workBranch} in ${repoDir ?? cwd} (closing the session keeps that branch); push it from there.`;
1552
1738
  const message = `${res.error}${kept}`;
1553
1739
  this.deps.logger.warn(`session ${this.sessionId}: ${message}`);
1554
1740
  this.emit({ type: "error", message, retryable: false });
@@ -1562,6 +1748,28 @@ var AgentSession = class {
1562
1748
  const waiters = this.exitWaiters;
1563
1749
  this.exitWaiters = [];
1564
1750
  try {
1751
+ if (this.resumeRetry === null && !reason && this.record.turnActive && this.resumeNotFound(true) && /No conversation found/i.test(this.stderrTail)) {
1752
+ this.planFreshRetry();
1753
+ }
1754
+ if (this.resumeRetry !== null) {
1755
+ const text = this.resumeRetry;
1756
+ this.resumeRetry = null;
1757
+ this.record.turnActive = false;
1758
+ await this.deps.store.save(this.record);
1759
+ try {
1760
+ await this.beginTurn(text);
1761
+ } catch (err) {
1762
+ this.emit(
1763
+ {
1764
+ type: "error",
1765
+ message: `Claude Code could not be started again for this message: ${err.message}`,
1766
+ retryable: true
1767
+ },
1768
+ { type: "result", status: "failed", text: null }
1769
+ );
1770
+ }
1771
+ return;
1772
+ }
1565
1773
  if (reason) {
1566
1774
  this.deps.logger.info(`session ${this.sessionId}: Claude Code stopped (${reason})`);
1567
1775
  if (reason !== "shutdown" && this.record.turnActive) {
@@ -1593,6 +1801,9 @@ var AgentSession = class {
1593
1801
  );
1594
1802
  const how = signal ? `was killed (${signal})` : `exited with code ${code}`;
1595
1803
  const hint = this.sawResultSinceSpawn ? "" : startupHint(this.stderrTail);
1804
+ if (!this.sawResultSinceSpawn && looksLikeSignInFailure(this.stderrTail)) {
1805
+ this.deps.onClaudeSignIn?.(false);
1806
+ }
1596
1807
  this.emit({
1597
1808
  type: "error",
1598
1809
  message: `Claude Code ${how} in the middle of a turn.${hint}${tail ? ` ${tail}` : ""}`,
@@ -1614,12 +1825,15 @@ function turnErrorMessage(turn) {
1614
1825
  case "error_max_budget_usd":
1615
1826
  return "Claude Code stopped: it reached its spending limit.";
1616
1827
  default:
1828
+ if (turnFailedToSignIn(turn)) {
1829
+ return `Claude Code could not sign in to Claude (${turn.text.slice(0, 200)}). ${signInFix()} Then send a message here to try again.`;
1830
+ }
1617
1831
  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
1832
  }
1619
1833
  }
1620
1834
  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.";
1835
+ if (looksLikeSignInFailure(stderr)) {
1836
+ return ` Claude Code does not seem to be signed in on the runner\u2019s computer. ${signInFix()}`;
1623
1837
  }
1624
1838
  if (/No conversation found|session.*not found/i.test(stderr)) {
1625
1839
  return " The Claude Code conversation to resume was not found on this computer.";
@@ -1752,6 +1966,18 @@ var SessionManager = class {
1752
1966
  branch: cmd.repository?.workBranch
1753
1967
  });
1754
1968
  await this.opts.claude();
1969
+ const resume = cmd.resume ?? null;
1970
+ if (resume) {
1971
+ for (const other of [...this.sessions.values()]) {
1972
+ if (other.record.runId === cmd.runId && other.sessionId !== cmd.sessionId) {
1973
+ await this.close(other.sessionId);
1974
+ }
1975
+ }
1976
+ await Promise.allSettled([...this.closing.values()]);
1977
+ this.opts.logger.info(`session ${cmd.sessionId}: continuing run ${cmd.runId}`, {
1978
+ resume: resume.claudeSessionId ? "conversation" : "fresh"
1979
+ });
1980
+ }
1755
1981
  const now = (/* @__PURE__ */ new Date()).toISOString();
1756
1982
  const record = {
1757
1983
  sessionId: cmd.sessionId,
@@ -1777,19 +2003,35 @@ var SessionManager = class {
1777
2003
  reposDir: this.opts.config.reposDir,
1778
2004
  worktreesDir: this.opts.config.worktreesDir,
1779
2005
  sessionId: cmd.sessionId,
1780
- protocol: this.opts.config.gitProtocol
2006
+ protocol: this.opts.config.gitProtocol,
2007
+ continueBranch: !!resume,
2008
+ worktreeKey: resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : null
1781
2009
  });
1782
2010
  Object.assign(record, {
1783
2011
  cwd: wt.worktree,
1784
2012
  repoDir: wt.repoDir,
1785
2013
  workBranch: cmd.repository.workBranch,
1786
2014
  baseRef: wt.baseRef,
1787
- baseSha: wt.baseSha
2015
+ baseSha: wt.baseSha,
2016
+ // A reused kept worktree still holds the uncommitted changes it was kept for: keep
2017
+ // protecting it until a turn commits them, or a close before then would delete them.
2018
+ ...wt.continuedFrom === "worktree" ? { keepWorktree: true } : {}
1788
2019
  });
2020
+ if (wt.setAside) {
2021
+ this.opts.logger.warn(
2022
+ `session ${cmd.sessionId}: an earlier working copy with uncommitted changes could not be reused; it was moved to ${wt.setAside}`
2023
+ );
2024
+ }
1789
2025
  } else {
1790
- record.cwd = this.store.scratchDir(cmd.sessionId);
2026
+ record.cwd = this.store.scratchDir(
2027
+ resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : cmd.sessionId
2028
+ );
1791
2029
  await mkdir5(record.cwd, { recursive: true });
1792
2030
  }
2031
+ if (resume) {
2032
+ record.claudeSessionId = resume.claudeSessionId?.trim() || null;
2033
+ record.freshPreface = continuationPreface(cmd);
2034
+ }
1793
2035
  await this.store.save(record);
1794
2036
  } catch (err) {
1795
2037
  this.opts.logger.error(`session ${cmd.sessionId}: could not prepare the workspace`, {
@@ -1800,6 +2042,7 @@ var SessionManager = class {
1800
2042
  }
1801
2043
  const session = await this.openSession(record);
1802
2044
  this.sessions.set(cmd.sessionId, session);
2045
+ if (resume) return { ok: true };
1803
2046
  try {
1804
2047
  await session.startFirstTurn(cmd.prompt);
1805
2048
  } catch (err) {
@@ -1873,8 +2116,13 @@ var SessionManager = class {
1873
2116
  this.sessions.delete(sessionId);
1874
2117
  session.outbox.discard();
1875
2118
  await session.stop("close");
2119
+ await this.opts.beforeWorktreeRemoved?.(sessionId);
1876
2120
  const { record } = session;
1877
- if (record.repoDir) {
2121
+ if (record.repoDir && record.keepWorktree) {
2122
+ this.opts.logger.warn(
2123
+ `session ${sessionId}: keeping the worktree ${record.cwd}, which holds changes that could not be committed`
2124
+ );
2125
+ } else if (record.repoDir) {
1878
2126
  await removeWorktree(record.repoDir, record.cwd).catch(
1879
2127
  (err) => this.opts.logger.warn(`session ${sessionId}: could not remove the worktree`, {
1880
2128
  error: safeError(err)
@@ -1953,10 +2201,31 @@ var SessionManager = class {
1953
2201
  allowedTools: this.opts.config.allowedTools,
1954
2202
  disallowedTools: this.opts.config.disallowedTools ?? [],
1955
2203
  loadProjectSettings: this.opts.config.loadProjectSettings ?? false,
1956
- interruptGraceMs: this.opts.interruptGraceMs
2204
+ interruptGraceMs: this.opts.interruptGraceMs,
2205
+ onClaudeSignIn: this.opts.onClaudeSignIn
1957
2206
  });
1958
2207
  }
1959
2208
  };
2209
+ function safeWorktreeKey(key, fallback) {
2210
+ if (!key) return fallback;
2211
+ try {
2212
+ assertSafeSessionId(key);
2213
+ return key;
2214
+ } catch {
2215
+ return fallback;
2216
+ }
2217
+ }
2218
+ function continuationPreface(cmd) {
2219
+ const branch = cmd.repository?.workBranch;
2220
+ const task = cmd.prompt.trim();
2221
+ return [
2222
+ branch ? `You are continuing earlier work on the branch ${branch}, which is checked out here with everything done so far. The earlier conversation could not be restored; read the branch's commits (git log, git diff against the base) for what was done.` : "You are continuing earlier work in this directory. The earlier conversation could not be restored.",
2223
+ task ? `The original task was:
2224
+
2225
+ ${task.slice(0, 2e4)}` : "",
2226
+ "The person\u2019s message follows."
2227
+ ].filter(Boolean).join("\n\n");
2228
+ }
1960
2229
  function safeError(err) {
1961
2230
  return scrubSecrets(err instanceof Error ? err.message : String(err)).slice(0, 600);
1962
2231
  }
@@ -1972,6 +2241,7 @@ var RunnerDaemon = class {
1972
2241
  logger: opts.logger,
1973
2242
  claude: () => this.resolveClaude(),
1974
2243
  onUnauthorized: (err) => this.unauthorized(err),
2244
+ onClaudeSignIn: (ok) => this.claudeSignIn(ok),
1975
2245
  ...opts.managerOverrides
1976
2246
  });
1977
2247
  }
@@ -1980,6 +2250,12 @@ var RunnerDaemon = class {
1980
2250
  controller = new AbortController();
1981
2251
  exitReason = "stopped";
1982
2252
  agentInfo = null;
2253
+ /**
2254
+ * A turn's Claude Code could not sign in to Claude. `claude auth status` may still say it
2255
+ * is signed in (an expired sign-in it cannot refresh), so this outranks the probe until a
2256
+ * later turn finishes.
2257
+ */
2258
+ signInFailed = false;
1983
2259
  claudeCache = null;
1984
2260
  inFlight = /* @__PURE__ */ new Set();
1985
2261
  /** The tail of each session's command queue (see `inSessionOrder`); never rejects. */
@@ -2010,7 +2286,7 @@ var RunnerDaemon = class {
2010
2286
  if (this.exitReason === "unauthorized") return;
2011
2287
  this.exitReason = "unauthorized";
2012
2288
  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.`
2289
+ `Discovery Tree refused this runner's token (${err.path}). The runner may have been removed. Run \`${runnerCommand("login")}\` to pair it again.`
2014
2290
  );
2015
2291
  this.stop();
2016
2292
  }
@@ -2029,13 +2305,29 @@ var RunnerDaemon = class {
2029
2305
  async agent() {
2030
2306
  const ttl = this.opts.agentProbeTtlMs ?? 5 * 6e4;
2031
2307
  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);
2308
+ const info2 = await probeAgent();
2309
+ if (info2.claudeProblem && info2.claudeProblem !== this.agentInfo?.info.claudeProblem) {
2310
+ this.opts.logger.warn(info2.claudeProblem);
2035
2311
  }
2036
- this.agentInfo = { info, at: Date.now() };
2312
+ this.agentInfo = { info: info2, at: Date.now() };
2313
+ }
2314
+ const { info } = this.agentInfo;
2315
+ if (!this.signInFailed || !info.claudeVersion || info.claudeReady === false) return info;
2316
+ return {
2317
+ ...info,
2318
+ claudeReady: false,
2319
+ claudeProblem: `A run could not sign in to Claude. ${signInFix()}`
2320
+ };
2321
+ }
2322
+ claudeSignIn(ok) {
2323
+ if (ok && this.agentInfo?.info.claudeReady === false && this.agentInfo.info.claudeVersion) {
2324
+ this.agentInfo.info = { ...this.agentInfo.info, claudeReady: true, claudeProblem: null };
2325
+ }
2326
+ if (ok === !this.signInFailed) return;
2327
+ this.signInFailed = !ok;
2328
+ if (!ok) {
2329
+ this.opts.logger.warn(`Claude Code could not sign in to Claude. ${signInFix()}`);
2037
2330
  }
2038
- return this.agentInfo.info;
2039
2331
  }
2040
2332
  async heartbeatLoop() {
2041
2333
  let failures = 0;
@@ -2045,7 +2337,8 @@ var RunnerDaemon = class {
2045
2337
  protocolVersion: RUNNER_PROTOCOL_VERSION,
2046
2338
  runnerVersion: RUNNER_VERSION,
2047
2339
  platform: RUNNER_PLATFORM,
2048
- agent: await this.agent(),
2340
+ // This runner continues closed sessions (`start_session` with `resume`).
2341
+ agent: { ...await this.agent(), resumesClosedSessions: true },
2049
2342
  activeSessionIds: this.manager.activeSessionIds(),
2050
2343
  maxConcurrentSessions: this.opts.config.maxSessions
2051
2344
  });
@@ -2229,7 +2522,7 @@ async function runDoctor(env = process.env) {
2229
2522
  checks.push({
2230
2523
  name: "ANTHROPIC_API_KEY",
2231
2524
  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."
2525
+ detail: `is set: Claude Code will bill that API key instead of your Claude subscription. Unset it before \`${runnerCommand("start")}\` unless that is what you want.`
2233
2526
  });
2234
2527
  }
2235
2528
  return checks;
@@ -2328,10 +2621,10 @@ async function pair(api, opts) {
2328
2621
  case "denied":
2329
2622
  throw new Error("Pairing was denied in Discovery Tree.");
2330
2623
  case "expired":
2331
- throw new Error("The pairing code expired. Run `dt-runner login` again.");
2624
+ throw new Error(`The pairing code expired. Run \`${runnerCommand("login")}\` again.`);
2332
2625
  }
2333
2626
  }
2334
- throw new Error("The pairing code expired. Run `dt-runner login` again.");
2627
+ throw new Error(`The pairing code expired. Run \`${runnerCommand("login")}\` again.`);
2335
2628
  }
2336
2629
  async function confirmAccount(result, opts) {
2337
2630
  const { io } = opts;
@@ -2345,7 +2638,7 @@ async function confirmAccount(result, opts) {
2345
2638
  io.print(` PAIRED AS: ${result.userLabel}`);
2346
2639
  io.print(" If this is not your Discovery Tree account, remove this runner in");
2347
2640
  io.print(" Discovery Tree (Account settings \u2192 Local runners) and run");
2348
- io.print(" `dt-runner logout` on this computer.");
2641
+ io.print(` \`${runnerCommand("logout")}\` on this computer.`);
2349
2642
  io.print("==================================================================");
2350
2643
  io.print("");
2351
2644
  return true;
@@ -2395,7 +2688,10 @@ Environment:
2395
2688
  DT_RUNNER_CLAUDE_BIN Claude Code binary to run (default: \`claude\` on PATH).
2396
2689
 
2397
2690
  Config: ${runnerPaths().configFile}
2398
- `;
2691
+ ${launchedByNpx() ? `
2692
+ Started with npx, so there is no \`dt-runner\` command: type \`npx ${RUNNER_PACKAGE}@latest\` in its
2693
+ place, or install it once with \`npm install -g ${RUNNER_PACKAGE}\`.
2694
+ ` : ""}`;
2399
2695
  async function main(argv) {
2400
2696
  const { values, positionals } = parseArgs({
2401
2697
  args: argv,
@@ -2499,7 +2795,13 @@ async function login(server, name, openBrowser, yes) {
2499
2795
  name: runnerName
2500
2796
  });
2501
2797
  console.log(`Saved to ${paths.configFile}.`);
2502
- console.log("Run `dt-runner doctor` to check this computer, then `dt-runner start`.");
2798
+ console.log("");
2799
+ console.log("Next:");
2800
+ console.log(` 1. \`${runnerCommand("doctor")}\` checks Node.js, git and Claude Code here.`);
2801
+ console.log(
2802
+ ` 2. \`${runnerCommand("start")}\` runs the runner. Keep it running: Discovery Tree`
2803
+ );
2804
+ console.log(' offers "Claude Code (your computer)" for a run only while it is.');
2503
2805
  return 0;
2504
2806
  }
2505
2807
  async function start(opts) {
@@ -2510,7 +2812,7 @@ async function start(opts) {
2510
2812
  reposDir: opts.reposDir
2511
2813
  });
2512
2814
  if (!config.token) {
2513
- logger.error("This computer is not paired yet. Run `dt-runner login` first.");
2815
+ logger.error(`This computer is not paired yet. Run \`${runnerCommand("login")}\` first.`);
2514
2816
  return 1;
2515
2817
  }
2516
2818
  if (process.env.ANTHROPIC_API_KEY) {
@@ -2567,7 +2869,7 @@ async function status() {
2567
2869
  `Runner: ${config.name ?? "(unnamed)"}${config.runnerId ? ` (${config.runnerId})` : ""}`
2568
2870
  );
2569
2871
  console.log(
2570
- `Token: ${config.token ? `set${process.env.DT_RUNNER_TOKEN ? " (from DT_RUNNER_TOKEN)" : ""}` : "not set \u2014 run `dt-runner login`"}`
2872
+ `Token: ${config.token ? `set${process.env.DT_RUNNER_TOKEN ? " (from DT_RUNNER_TOKEN)" : ""}` : `not set \u2014 run \`${runnerCommand("login")}\``}`
2571
2873
  );
2572
2874
  console.log(
2573
2875
  `Sessions: up to ${config.maxSessions} at once, permission mode ${config.permissionMode}`
@@ -2606,7 +2908,7 @@ async function status() {
2606
2908
  return 0;
2607
2909
  } catch (err) {
2608
2910
  if (err instanceof UnauthorizedError) {
2609
- console.log("Heartbeat: token refused \u2014 run `dt-runner login` again");
2911
+ console.log(`Heartbeat: token refused \u2014 run \`${runnerCommand("login")}\` again`);
2610
2912
  } else {
2611
2913
  console.log(`Heartbeat: failed (${err.message})`);
2612
2914
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@discovery-tree/runner",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
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": {