@discovery-tree/runner 0.1.0 → 0.1.2

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 +317 -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.0" : "0.0.0-dev";
36
+ var RUNNER_VERSION = true ? "0.1.2" : "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,6 +1626,7 @@ 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;
1493
1630
  if (mapped.claudeSessionId && mapped.claudeSessionId !== this.record.claudeSessionId) {
1494
1631
  this.record.claudeSessionId = mapped.claudeSessionId;
1495
1632
  dirty = true;
@@ -1500,17 +1637,38 @@ var AgentSession = class {
1500
1637
  }
1501
1638
  if (dirty) await this.deps.store.save(this.record);
1502
1639
  if (mapped.events.length) this.emit(...mapped.events);
1640
+ if (mapped.turnEnd && this.resumeNotFound(mapped.turnEnd.isError)) {
1641
+ this.planFreshRetry();
1642
+ this.child?.stdin.end();
1643
+ return;
1644
+ }
1503
1645
  if (mapped.turnEnd) {
1504
1646
  this.sawResultSinceSpawn = true;
1505
1647
  await this.endTurn(mapped.turnEnd);
1506
1648
  }
1507
1649
  }
1650
+ /**
1651
+ * The process was started to resume a conversation and failed before it said it had it
1652
+ * (no `system/init`): Claude Code did not find the conversation on this computer.
1653
+ */
1654
+ resumeNotFound(isError) {
1655
+ return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && this.turnText !== null;
1656
+ }
1657
+ planFreshRetry() {
1658
+ this.deps.logger.warn(
1659
+ `session ${this.sessionId}: the Claude Code conversation to resume was not found; starting a fresh one`
1660
+ );
1661
+ this.resumeRetry = this.turnText;
1662
+ this.record.claudeSessionId = null;
1663
+ }
1508
1664
  async endTurn(turn) {
1509
1665
  const interrupted = this.interruptRequested;
1510
1666
  this.interruptRequested = false;
1511
1667
  if (this.interruptTimer) clearTimeout(this.interruptTimer);
1512
1668
  this.interruptTimer = null;
1513
1669
  const turnFailed = turn.isError && !interrupted;
1670
+ if (turnFailed && turnFailedToSignIn(turn)) this.deps.onClaudeSignIn?.(false);
1671
+ else if (!turn.isError) this.deps.onClaudeSignIn?.(true);
1514
1672
  if (turnFailed) {
1515
1673
  this.emit({
1516
1674
  type: "error",
@@ -1526,7 +1684,13 @@ var AgentSession = class {
1526
1684
  type: "result",
1527
1685
  status: failed ? "failed" : "idle",
1528
1686
  text: interrupted ? turn.isError ? null : turn.text : turn.text,
1529
- branch: push.branch
1687
+ branch: push.branch,
1688
+ // The turn's work is only on this computer (committing or pushing it failed): a
1689
+ // continuation of the run must come back to this runner to find it.
1690
+ ...push.failed ? { unpushedWork: true } : {},
1691
+ // So the server can have a later session resume this conversation (a run continued
1692
+ // after it ended).
1693
+ ...this.record.claudeSessionId ? { claudeSessionId: this.record.claudeSessionId } : {}
1530
1694
  });
1531
1695
  this.lastActivity = Date.now();
1532
1696
  this.deps.logger.info(
@@ -1547,8 +1711,13 @@ var AgentSession = class {
1547
1711
  baseSha,
1548
1712
  message: "Uncommitted changes from the agent\u2019s turn\n\nCommitted by dt-runner at the end of a Discovery Tree agent turn."
1549
1713
  });
1714
+ const uncommitted = res.failedAt === "commit";
1715
+ if (!!this.record.keepWorktree !== uncommitted) {
1716
+ this.record.keepWorktree = uncommitted;
1717
+ await this.deps.store.save(this.record);
1718
+ }
1550
1719
  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.`;
1720
+ 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
1721
  const message = `${res.error}${kept}`;
1553
1722
  this.deps.logger.warn(`session ${this.sessionId}: ${message}`);
1554
1723
  this.emit({ type: "error", message, retryable: false });
@@ -1562,6 +1731,28 @@ var AgentSession = class {
1562
1731
  const waiters = this.exitWaiters;
1563
1732
  this.exitWaiters = [];
1564
1733
  try {
1734
+ if (this.resumeRetry === null && !reason && this.record.turnActive && this.resumeNotFound(true) && /No conversation found/i.test(this.stderrTail)) {
1735
+ this.planFreshRetry();
1736
+ }
1737
+ if (this.resumeRetry !== null) {
1738
+ const text = this.resumeRetry;
1739
+ this.resumeRetry = null;
1740
+ this.record.turnActive = false;
1741
+ await this.deps.store.save(this.record);
1742
+ try {
1743
+ await this.beginTurn(text);
1744
+ } catch (err) {
1745
+ this.emit(
1746
+ {
1747
+ type: "error",
1748
+ message: `Claude Code could not be started again for this message: ${err.message}`,
1749
+ retryable: true
1750
+ },
1751
+ { type: "result", status: "failed", text: null }
1752
+ );
1753
+ }
1754
+ return;
1755
+ }
1565
1756
  if (reason) {
1566
1757
  this.deps.logger.info(`session ${this.sessionId}: Claude Code stopped (${reason})`);
1567
1758
  if (reason !== "shutdown" && this.record.turnActive) {
@@ -1593,6 +1784,9 @@ var AgentSession = class {
1593
1784
  );
1594
1785
  const how = signal ? `was killed (${signal})` : `exited with code ${code}`;
1595
1786
  const hint = this.sawResultSinceSpawn ? "" : startupHint(this.stderrTail);
1787
+ if (!this.sawResultSinceSpawn && looksLikeSignInFailure(this.stderrTail)) {
1788
+ this.deps.onClaudeSignIn?.(false);
1789
+ }
1596
1790
  this.emit({
1597
1791
  type: "error",
1598
1792
  message: `Claude Code ${how} in the middle of a turn.${hint}${tail ? ` ${tail}` : ""}`,
@@ -1614,12 +1808,15 @@ function turnErrorMessage(turn) {
1614
1808
  case "error_max_budget_usd":
1615
1809
  return "Claude Code stopped: it reached its spending limit.";
1616
1810
  default:
1811
+ if (turnFailedToSignIn(turn)) {
1812
+ return `Claude Code could not sign in to Claude (${turn.text.slice(0, 200)}). ${signInFix()} Then send a message here to try again.`;
1813
+ }
1617
1814
  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
1815
  }
1619
1816
  }
1620
1817
  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.";
1818
+ if (looksLikeSignInFailure(stderr)) {
1819
+ return ` Claude Code does not seem to be signed in on the runner\u2019s computer. ${signInFix()}`;
1623
1820
  }
1624
1821
  if (/No conversation found|session.*not found/i.test(stderr)) {
1625
1822
  return " The Claude Code conversation to resume was not found on this computer.";
@@ -1752,6 +1949,18 @@ var SessionManager = class {
1752
1949
  branch: cmd.repository?.workBranch
1753
1950
  });
1754
1951
  await this.opts.claude();
1952
+ const resume = cmd.resume ?? null;
1953
+ if (resume) {
1954
+ for (const other of [...this.sessions.values()]) {
1955
+ if (other.record.runId === cmd.runId && other.sessionId !== cmd.sessionId) {
1956
+ await this.close(other.sessionId);
1957
+ }
1958
+ }
1959
+ await Promise.allSettled([...this.closing.values()]);
1960
+ this.opts.logger.info(`session ${cmd.sessionId}: continuing run ${cmd.runId}`, {
1961
+ resume: resume.claudeSessionId ? "conversation" : "fresh"
1962
+ });
1963
+ }
1755
1964
  const now = (/* @__PURE__ */ new Date()).toISOString();
1756
1965
  const record = {
1757
1966
  sessionId: cmd.sessionId,
@@ -1777,19 +1986,35 @@ var SessionManager = class {
1777
1986
  reposDir: this.opts.config.reposDir,
1778
1987
  worktreesDir: this.opts.config.worktreesDir,
1779
1988
  sessionId: cmd.sessionId,
1780
- protocol: this.opts.config.gitProtocol
1989
+ protocol: this.opts.config.gitProtocol,
1990
+ continueBranch: !!resume,
1991
+ worktreeKey: resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : null
1781
1992
  });
1782
1993
  Object.assign(record, {
1783
1994
  cwd: wt.worktree,
1784
1995
  repoDir: wt.repoDir,
1785
1996
  workBranch: cmd.repository.workBranch,
1786
1997
  baseRef: wt.baseRef,
1787
- baseSha: wt.baseSha
1998
+ baseSha: wt.baseSha,
1999
+ // A reused kept worktree still holds the uncommitted changes it was kept for: keep
2000
+ // protecting it until a turn commits them, or a close before then would delete them.
2001
+ ...wt.continuedFrom === "worktree" ? { keepWorktree: true } : {}
1788
2002
  });
2003
+ if (wt.setAside) {
2004
+ this.opts.logger.warn(
2005
+ `session ${cmd.sessionId}: an earlier working copy with uncommitted changes could not be reused; it was moved to ${wt.setAside}`
2006
+ );
2007
+ }
1789
2008
  } else {
1790
- record.cwd = this.store.scratchDir(cmd.sessionId);
2009
+ record.cwd = this.store.scratchDir(
2010
+ resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : cmd.sessionId
2011
+ );
1791
2012
  await mkdir5(record.cwd, { recursive: true });
1792
2013
  }
2014
+ if (resume) {
2015
+ record.claudeSessionId = resume.claudeSessionId?.trim() || null;
2016
+ record.freshPreface = continuationPreface(cmd);
2017
+ }
1793
2018
  await this.store.save(record);
1794
2019
  } catch (err) {
1795
2020
  this.opts.logger.error(`session ${cmd.sessionId}: could not prepare the workspace`, {
@@ -1800,6 +2025,7 @@ var SessionManager = class {
1800
2025
  }
1801
2026
  const session = await this.openSession(record);
1802
2027
  this.sessions.set(cmd.sessionId, session);
2028
+ if (resume) return { ok: true };
1803
2029
  try {
1804
2030
  await session.startFirstTurn(cmd.prompt);
1805
2031
  } catch (err) {
@@ -1873,8 +2099,13 @@ var SessionManager = class {
1873
2099
  this.sessions.delete(sessionId);
1874
2100
  session.outbox.discard();
1875
2101
  await session.stop("close");
2102
+ await this.opts.beforeWorktreeRemoved?.(sessionId);
1876
2103
  const { record } = session;
1877
- if (record.repoDir) {
2104
+ if (record.repoDir && record.keepWorktree) {
2105
+ this.opts.logger.warn(
2106
+ `session ${sessionId}: keeping the worktree ${record.cwd}, which holds changes that could not be committed`
2107
+ );
2108
+ } else if (record.repoDir) {
1878
2109
  await removeWorktree(record.repoDir, record.cwd).catch(
1879
2110
  (err) => this.opts.logger.warn(`session ${sessionId}: could not remove the worktree`, {
1880
2111
  error: safeError(err)
@@ -1953,10 +2184,31 @@ var SessionManager = class {
1953
2184
  allowedTools: this.opts.config.allowedTools,
1954
2185
  disallowedTools: this.opts.config.disallowedTools ?? [],
1955
2186
  loadProjectSettings: this.opts.config.loadProjectSettings ?? false,
1956
- interruptGraceMs: this.opts.interruptGraceMs
2187
+ interruptGraceMs: this.opts.interruptGraceMs,
2188
+ onClaudeSignIn: this.opts.onClaudeSignIn
1957
2189
  });
1958
2190
  }
1959
2191
  };
2192
+ function safeWorktreeKey(key, fallback) {
2193
+ if (!key) return fallback;
2194
+ try {
2195
+ assertSafeSessionId(key);
2196
+ return key;
2197
+ } catch {
2198
+ return fallback;
2199
+ }
2200
+ }
2201
+ function continuationPreface(cmd) {
2202
+ const branch = cmd.repository?.workBranch;
2203
+ const task = cmd.prompt.trim();
2204
+ return [
2205
+ 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.",
2206
+ task ? `The original task was:
2207
+
2208
+ ${task.slice(0, 2e4)}` : "",
2209
+ "The person\u2019s message follows."
2210
+ ].filter(Boolean).join("\n\n");
2211
+ }
1960
2212
  function safeError(err) {
1961
2213
  return scrubSecrets(err instanceof Error ? err.message : String(err)).slice(0, 600);
1962
2214
  }
@@ -1972,6 +2224,7 @@ var RunnerDaemon = class {
1972
2224
  logger: opts.logger,
1973
2225
  claude: () => this.resolveClaude(),
1974
2226
  onUnauthorized: (err) => this.unauthorized(err),
2227
+ onClaudeSignIn: (ok) => this.claudeSignIn(ok),
1975
2228
  ...opts.managerOverrides
1976
2229
  });
1977
2230
  }
@@ -1980,6 +2233,12 @@ var RunnerDaemon = class {
1980
2233
  controller = new AbortController();
1981
2234
  exitReason = "stopped";
1982
2235
  agentInfo = null;
2236
+ /**
2237
+ * A turn's Claude Code could not sign in to Claude. `claude auth status` may still say it
2238
+ * is signed in (an expired sign-in it cannot refresh), so this outranks the probe until a
2239
+ * later turn finishes.
2240
+ */
2241
+ signInFailed = false;
1983
2242
  claudeCache = null;
1984
2243
  inFlight = /* @__PURE__ */ new Set();
1985
2244
  /** The tail of each session's command queue (see `inSessionOrder`); never rejects. */
@@ -2010,7 +2269,7 @@ var RunnerDaemon = class {
2010
2269
  if (this.exitReason === "unauthorized") return;
2011
2270
  this.exitReason = "unauthorized";
2012
2271
  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.`
2272
+ `Discovery Tree refused this runner's token (${err.path}). The runner may have been removed. Run \`${runnerCommand("login")}\` to pair it again.`
2014
2273
  );
2015
2274
  this.stop();
2016
2275
  }
@@ -2029,13 +2288,29 @@ var RunnerDaemon = class {
2029
2288
  async agent() {
2030
2289
  const ttl = this.opts.agentProbeTtlMs ?? 5 * 6e4;
2031
2290
  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);
2291
+ const info2 = await probeAgent();
2292
+ if (info2.claudeProblem && info2.claudeProblem !== this.agentInfo?.info.claudeProblem) {
2293
+ this.opts.logger.warn(info2.claudeProblem);
2035
2294
  }
2036
- this.agentInfo = { info, at: Date.now() };
2295
+ this.agentInfo = { info: info2, at: Date.now() };
2296
+ }
2297
+ const { info } = this.agentInfo;
2298
+ if (!this.signInFailed || !info.claudeVersion || info.claudeReady === false) return info;
2299
+ return {
2300
+ ...info,
2301
+ claudeReady: false,
2302
+ claudeProblem: `A run could not sign in to Claude. ${signInFix()}`
2303
+ };
2304
+ }
2305
+ claudeSignIn(ok) {
2306
+ if (ok && this.agentInfo?.info.claudeReady === false && this.agentInfo.info.claudeVersion) {
2307
+ this.agentInfo.info = { ...this.agentInfo.info, claudeReady: true, claudeProblem: null };
2308
+ }
2309
+ if (ok === !this.signInFailed) return;
2310
+ this.signInFailed = !ok;
2311
+ if (!ok) {
2312
+ this.opts.logger.warn(`Claude Code could not sign in to Claude. ${signInFix()}`);
2037
2313
  }
2038
- return this.agentInfo.info;
2039
2314
  }
2040
2315
  async heartbeatLoop() {
2041
2316
  let failures = 0;
@@ -2045,7 +2320,8 @@ var RunnerDaemon = class {
2045
2320
  protocolVersion: RUNNER_PROTOCOL_VERSION,
2046
2321
  runnerVersion: RUNNER_VERSION,
2047
2322
  platform: RUNNER_PLATFORM,
2048
- agent: await this.agent(),
2323
+ // This runner continues closed sessions (`start_session` with `resume`).
2324
+ agent: { ...await this.agent(), resumesClosedSessions: true },
2049
2325
  activeSessionIds: this.manager.activeSessionIds(),
2050
2326
  maxConcurrentSessions: this.opts.config.maxSessions
2051
2327
  });
@@ -2229,7 +2505,7 @@ async function runDoctor(env = process.env) {
2229
2505
  checks.push({
2230
2506
  name: "ANTHROPIC_API_KEY",
2231
2507
  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."
2508
+ 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
2509
  });
2234
2510
  }
2235
2511
  return checks;
@@ -2328,10 +2604,10 @@ async function pair(api, opts) {
2328
2604
  case "denied":
2329
2605
  throw new Error("Pairing was denied in Discovery Tree.");
2330
2606
  case "expired":
2331
- throw new Error("The pairing code expired. Run `dt-runner login` again.");
2607
+ throw new Error(`The pairing code expired. Run \`${runnerCommand("login")}\` again.`);
2332
2608
  }
2333
2609
  }
2334
- throw new Error("The pairing code expired. Run `dt-runner login` again.");
2610
+ throw new Error(`The pairing code expired. Run \`${runnerCommand("login")}\` again.`);
2335
2611
  }
2336
2612
  async function confirmAccount(result, opts) {
2337
2613
  const { io } = opts;
@@ -2345,7 +2621,7 @@ async function confirmAccount(result, opts) {
2345
2621
  io.print(` PAIRED AS: ${result.userLabel}`);
2346
2622
  io.print(" If this is not your Discovery Tree account, remove this runner in");
2347
2623
  io.print(" Discovery Tree (Account settings \u2192 Local runners) and run");
2348
- io.print(" `dt-runner logout` on this computer.");
2624
+ io.print(` \`${runnerCommand("logout")}\` on this computer.`);
2349
2625
  io.print("==================================================================");
2350
2626
  io.print("");
2351
2627
  return true;
@@ -2395,7 +2671,10 @@ Environment:
2395
2671
  DT_RUNNER_CLAUDE_BIN Claude Code binary to run (default: \`claude\` on PATH).
2396
2672
 
2397
2673
  Config: ${runnerPaths().configFile}
2398
- `;
2674
+ ${launchedByNpx() ? `
2675
+ Started with npx, so there is no \`dt-runner\` command: type \`npx ${RUNNER_PACKAGE}@latest\` in its
2676
+ place, or install it once with \`npm install -g ${RUNNER_PACKAGE}\`.
2677
+ ` : ""}`;
2399
2678
  async function main(argv) {
2400
2679
  const { values, positionals } = parseArgs({
2401
2680
  args: argv,
@@ -2499,7 +2778,13 @@ async function login(server, name, openBrowser, yes) {
2499
2778
  name: runnerName
2500
2779
  });
2501
2780
  console.log(`Saved to ${paths.configFile}.`);
2502
- console.log("Run `dt-runner doctor` to check this computer, then `dt-runner start`.");
2781
+ console.log("");
2782
+ console.log("Next:");
2783
+ console.log(` 1. \`${runnerCommand("doctor")}\` checks Node.js, git and Claude Code here.`);
2784
+ console.log(
2785
+ ` 2. \`${runnerCommand("start")}\` runs the runner. Keep it running: Discovery Tree`
2786
+ );
2787
+ console.log(' offers "Claude Code (your computer)" for a run only while it is.');
2503
2788
  return 0;
2504
2789
  }
2505
2790
  async function start(opts) {
@@ -2510,7 +2795,7 @@ async function start(opts) {
2510
2795
  reposDir: opts.reposDir
2511
2796
  });
2512
2797
  if (!config.token) {
2513
- logger.error("This computer is not paired yet. Run `dt-runner login` first.");
2798
+ logger.error(`This computer is not paired yet. Run \`${runnerCommand("login")}\` first.`);
2514
2799
  return 1;
2515
2800
  }
2516
2801
  if (process.env.ANTHROPIC_API_KEY) {
@@ -2567,7 +2852,7 @@ async function status() {
2567
2852
  `Runner: ${config.name ?? "(unnamed)"}${config.runnerId ? ` (${config.runnerId})` : ""}`
2568
2853
  );
2569
2854
  console.log(
2570
- `Token: ${config.token ? `set${process.env.DT_RUNNER_TOKEN ? " (from DT_RUNNER_TOKEN)" : ""}` : "not set \u2014 run `dt-runner login`"}`
2855
+ `Token: ${config.token ? `set${process.env.DT_RUNNER_TOKEN ? " (from DT_RUNNER_TOKEN)" : ""}` : `not set \u2014 run \`${runnerCommand("login")}\``}`
2571
2856
  );
2572
2857
  console.log(
2573
2858
  `Sessions: up to ${config.maxSessions} at once, permission mode ${config.permissionMode}`
@@ -2606,7 +2891,7 @@ async function status() {
2606
2891
  return 0;
2607
2892
  } catch (err) {
2608
2893
  if (err instanceof UnauthorizedError) {
2609
- console.log("Heartbeat: token refused \u2014 run `dt-runner login` again");
2894
+ console.log(`Heartbeat: token refused \u2014 run \`${runnerCommand("login")}\` again`);
2610
2895
  } else {
2611
2896
  console.log(`Heartbeat: failed (${err.message})`);
2612
2897
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@discovery-tree/runner",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
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": {