@discovery-tree/runner 0.1.6 → 0.1.8

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 +6 -1
  2. package/dist/cli.js +230 -14
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -207,7 +207,12 @@ url."git@my-alias:".insteadOf "git@github.com:"`), which git applies after the r
207
207
  4. At the end of every turn the runner commits anything left uncommitted
208
208
  (`git add -A && git commit`, only if the worktree is dirty) and runs
209
209
  `git push -u origin HEAD:<workBranch>` when the branch has commits on top of its base. Discovery
210
- Tree opens the pull request from that branch.
210
+ Tree opens the pull request from that branch with its GitHub App. When the app is not installed
211
+ on the repository, Discovery Tree asks the runner to open it instead, as you: after the push the
212
+ runner runs `gh pr create` (or finds the pull request already open with `gh pr list`), titled
213
+ after the task, with the agent's final message as its description. That needs the
214
+ [GitHub CLI](https://cli.github.com) signed in (`gh auth login`); without it the turn says why,
215
+ and you open the pull request from the branch yourself.
211
216
  5. When Discovery Tree closes the session, the worktree is removed (`git worktree remove --force`).
212
217
  The branch stays, locally and on the remote.
213
218
 
package/dist/cli.js CHANGED
@@ -5,6 +5,19 @@ import { hostname } from "node:os";
5
5
  import { createInterface as createInterface2 } from "node:readline/promises";
6
6
  import { parseArgs } from "node:util";
7
7
 
8
+ // ../contracts/src/agent-config.ts
9
+ var KEYED_AGENT_PROVIDER_TYPES = [
10
+ "cursor_cloud",
11
+ "openai",
12
+ "anthropic",
13
+ "webhook"
14
+ ];
15
+ var WORKSPACE_ONLY_KEY_PROVIDERS = ["voyage"];
16
+ var WORKSPACE_KEY_PROVIDER_TYPES = [
17
+ ...KEYED_AGENT_PROVIDER_TYPES,
18
+ ...WORKSPACE_ONLY_KEY_PROVIDERS
19
+ ];
20
+
8
21
  // ../contracts/src/ui-evidence.ts
9
22
  var UI_EVIDENCE_EXPECTATION = [
10
23
  "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.",
@@ -24,6 +37,7 @@ var DEFAULT_AGENT_SYSTEM_PROMPT = [
24
37
  // ../contracts/src/agent-runs.ts
25
38
  var AGENT_RUN_MAX_WALL_MS = 6 * 60 * 60 * 1e3;
26
39
  var AGENT_RUN_ABANDONED_GRACE_MS = 30 * 60 * 1e3;
40
+ var AGENT_RUN_AUTO_RECOVER_MAX_MS = 5 * 6e4;
27
41
 
28
42
  // ../contracts/src/agent-work.ts
29
43
  var AGENT_WORK_IDLE_AFTER_MS = 24 * 60 * 60 * 1e3;
@@ -36,7 +50,7 @@ var RUNNER_EVENT_TEXT_MAX_LENGTH = 64e3;
36
50
  var RUNNER_EVENTS_MAX_BODY_BYTES = 8 * 1024 * 1024;
37
51
 
38
52
  // src/version.ts
39
- var RUNNER_VERSION = true ? "0.1.6" : "0.0.0-dev";
53
+ var RUNNER_VERSION = true ? "0.1.8" : "0.0.0-dev";
40
54
  var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
41
55
 
42
56
  // src/api.ts
@@ -1375,6 +1389,94 @@ import { spawn as spawn3 } from "node:child_process";
1375
1389
  import { basename, dirname as dirname4 } from "node:path";
1376
1390
  import { createInterface } from "node:readline";
1377
1391
 
1392
+ // src/pull-request.ts
1393
+ var PULL_REQUEST_BODY_MAX_CHARS = 6e4;
1394
+ var GH_TIMEOUT_MS = 6e4;
1395
+ var PR_URL_RE = /https:\/\/github\.com\/[^/\s]+\/[^/\s]+\/pull\/\d+/;
1396
+ async function openPullRequest(input, exec2 = exec) {
1397
+ try {
1398
+ const listed = await exec2(
1399
+ "gh",
1400
+ [
1401
+ "pr",
1402
+ "list",
1403
+ "--repo",
1404
+ input.repo,
1405
+ "--head",
1406
+ input.head,
1407
+ "--state",
1408
+ "open",
1409
+ "--json",
1410
+ "url",
1411
+ "--limit",
1412
+ "1"
1413
+ ],
1414
+ { timeoutMs: GH_TIMEOUT_MS }
1415
+ );
1416
+ if (listed.code !== 0) return { status: "failed", error: ghError("pr list", listed) };
1417
+ const existing = PR_URL_RE.exec(listed.stdout)?.[0];
1418
+ if (existing) {
1419
+ const appendError = input.appendIfExisting ? await appendToDescription(existing, input.appendIfExisting, exec2) : null;
1420
+ return { status: "existing", url: existing, ...appendError ? { appendError } : {} };
1421
+ }
1422
+ const created = await exec2(
1423
+ "gh",
1424
+ [
1425
+ "pr",
1426
+ "create",
1427
+ "--repo",
1428
+ input.repo,
1429
+ "--head",
1430
+ input.head,
1431
+ ...input.base ? ["--base", input.base] : [],
1432
+ "--title",
1433
+ input.title,
1434
+ "--body-file",
1435
+ "-"
1436
+ ],
1437
+ { timeoutMs: GH_TIMEOUT_MS, input: input.body.slice(0, PULL_REQUEST_BODY_MAX_CHARS) }
1438
+ );
1439
+ const url = PR_URL_RE.exec(created.stdout)?.[0];
1440
+ if (created.code === 0 && url) return { status: "opened", url };
1441
+ if (/no commits between/i.test(created.stderr)) return { status: "no_changes" };
1442
+ return { status: "failed", error: ghError("pr create", created) };
1443
+ } catch (err) {
1444
+ const missing = err?.code === "ENOENT";
1445
+ return {
1446
+ status: "failed",
1447
+ error: missing ? "the GitHub CLI (`gh`) is not installed on this computer; see https://cli.github.com" : scrubSecrets(err instanceof Error ? err.message : String(err)).slice(0, 300)
1448
+ };
1449
+ }
1450
+ }
1451
+ async function appendToDescription(url, addition, exec2) {
1452
+ const images = [...addition.matchAll(/\]\((https?:\/\/[^)\s]+)\)/g)].map((m) => m[1]);
1453
+ if (!images.length) return null;
1454
+ const viewed = await exec2("gh", ["pr", "view", url, "--json", "body", "--jq", ".body"], {
1455
+ timeoutMs: GH_TIMEOUT_MS
1456
+ });
1457
+ if (viewed.code !== 0) return ghError("pr view", viewed);
1458
+ const body = viewed.stdout.replace(/\n$/, "");
1459
+ if (images.every((u) => body.includes(u))) return null;
1460
+ const text = addition.replace(/^## Screenshots$/m, "## Screenshots from a later turn");
1461
+ const next = body ? `${body.trimEnd()}
1462
+
1463
+ ${text}` : text;
1464
+ if (next.length > PULL_REQUEST_BODY_MAX_CHARS)
1465
+ return "the description is too long to add them to";
1466
+ const edited = await exec2("gh", ["pr", "edit", url, "--body-file", "-"], {
1467
+ timeoutMs: GH_TIMEOUT_MS,
1468
+ input: next
1469
+ });
1470
+ return edited.code === 0 ? null : ghError("pr edit", edited);
1471
+ }
1472
+ function ghError(command, res) {
1473
+ const detail = (res.stderr || res.stdout).trim().split("\n").slice(-3).join(" ");
1474
+ if (/gh auth login|not logged in|authentication/i.test(detail)) {
1475
+ return "the GitHub CLI is not signed in; run `gh auth login` on this computer";
1476
+ }
1477
+ return scrubSecrets(`gh ${command} failed${detail ? `: ${detail}` : ""}`).slice(0, 300);
1478
+ }
1479
+
1378
1480
  // src/process-tree.ts
1379
1481
  import { spawn as spawn2 } from "node:child_process";
1380
1482
  var OWN_PROCESS_GROUP = process.platform !== "win32";
@@ -1719,6 +1821,11 @@ var AgentSession = class {
1719
1821
  * conversation, with the preface the continuation brought.
1720
1822
  */
1721
1823
  resumeRetry = null;
1824
+ /**
1825
+ * The process failed to resume before any turn began (its error result came while a
1826
+ * message was still being delivered): it is ending, so no message may be written to it.
1827
+ */
1828
+ resumeDoomed = false;
1722
1829
  exitWaiters = [];
1723
1830
  /** Settles once the current process has exited and what it left in its group is gone. */
1724
1831
  groupReaped = Promise.resolve();
@@ -1837,7 +1944,7 @@ var AgentSession = class {
1837
1944
  * result that will never come.
1838
1945
  */
1839
1946
  async beginTurn(text, before) {
1840
- while (!this.child || this.stopping) await this.ensureProcess();
1947
+ while (!this.child || this.stopping || this.resumeDoomed) await this.ensureProcess();
1841
1948
  let content = text;
1842
1949
  const preface = this.record.freshPreface;
1843
1950
  if (preface && !this.spawnedWithResume) {
@@ -1872,7 +1979,7 @@ ${text}`;
1872
1979
  return new Promise((resolve) => this.exitWaiters.push(resolve));
1873
1980
  }
1874
1981
  async ensureProcess() {
1875
- while (this.child && this.stopping) await this.waitForExit();
1982
+ while (this.child && (this.stopping || this.resumeDoomed)) await this.waitForExit();
1876
1983
  if (this.child) return;
1877
1984
  await this.prepareEvidenceDir();
1878
1985
  const { bin, features } = await this.deps.claude();
@@ -1911,6 +2018,7 @@ ${text}`;
1911
2018
  });
1912
2019
  this.child = child;
1913
2020
  this.stopping = null;
2021
+ this.resumeDoomed = false;
1914
2022
  this.reapGraceMs = void 0;
1915
2023
  this.stderrTail = "";
1916
2024
  this.sawResultSinceSpawn = false;
@@ -1985,6 +2093,16 @@ ${text}`;
1985
2093
  this.child?.stdin.end();
1986
2094
  return;
1987
2095
  }
2096
+ if (mapped.turnEnd && this.resumeFailedBeforeTurn(mapped.turnEnd.isError)) {
2097
+ this.deps.logger.warn(
2098
+ `session ${this.sessionId}: the Claude Code conversation to resume was not found; starting a fresh one`
2099
+ );
2100
+ this.record.claudeSessionId = null;
2101
+ this.resumeDoomed = true;
2102
+ await this.deps.store.save(this.record);
2103
+ this.child?.stdin.end();
2104
+ return;
2105
+ }
1988
2106
  if (mapped.turnEnd) {
1989
2107
  this.sawResultSinceSpawn = true;
1990
2108
  await this.endTurn(mapped.turnEnd);
@@ -1995,7 +2113,10 @@ ${text}`;
1995
2113
  * (no `system/init`): Claude Code did not find the conversation on this computer.
1996
2114
  */
1997
2115
  resumeNotFound(isError) {
1998
- return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && this.turnText !== null;
2116
+ return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && this.record.turnActive && this.turnText !== null;
2117
+ }
2118
+ resumeFailedBeforeTurn(isError) {
2119
+ return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && !this.record.turnActive;
1999
2120
  }
2000
2121
  planFreshRetry() {
2001
2122
  this.deps.logger.warn(
@@ -2026,15 +2147,20 @@ ${text}`;
2026
2147
  });
2027
2148
  return "";
2028
2149
  });
2150
+ const failed = turnFailed || push.failed;
2151
+ const text = withScreenshots(
2152
+ interrupted ? turn.isError ? null : turn.text : turn.text,
2153
+ screenshots
2154
+ );
2155
+ const prUrl = push.branch ? await this.openPullRequest(text, screenshots) : null;
2029
2156
  this.record.turnActive = false;
2030
2157
  await this.deps.store.save(this.record);
2031
- const failed = turnFailed || push.failed;
2032
- const text = interrupted ? turn.isError ? null : turn.text : turn.text;
2033
2158
  this.emit({
2034
2159
  type: "result",
2035
2160
  status: failed ? "failed" : "idle",
2036
- text: withScreenshots(text, screenshots),
2161
+ text,
2037
2162
  branch: push.branch,
2163
+ ...prUrl ? { prUrl } : {},
2038
2164
  // The turn's work is only on this computer (committing or pushing it failed): a
2039
2165
  // continuation of the run must come back to this runner to find it.
2040
2166
  ...push.failed ? { unpushedWork: true } : {},
@@ -2048,6 +2174,55 @@ ${text}`;
2048
2174
  { pushed: push.branch ?? void 0 }
2049
2175
  );
2050
2176
  }
2177
+ /**
2178
+ * When the runner opens this session's pull request (the GitHub App cannot), opens it from
2179
+ * the work branch with the person's `gh`, or finds the one already open; its URL, or null.
2180
+ * A failure is said in the conversation, and the server then shows the branch instead.
2181
+ */
2182
+ async openPullRequest(text, screenshots) {
2183
+ const { pullRequest, workBranch, repository, baseRef } = this.record;
2184
+ const repo = parseRepoUrl(repository ?? "");
2185
+ if (!pullRequest || !workBranch || !repo) return null;
2186
+ const body = [
2187
+ text?.trim() || "Work by the Claude Code (local) agent.",
2188
+ "",
2189
+ "---",
2190
+ pullRequest.footer
2191
+ ].join("\n");
2192
+ const outcome = await (this.deps.openPullRequest ?? openPullRequest)({
2193
+ repo: `${repo.owner}/${repo.repo}`,
2194
+ head: workBranch,
2195
+ base: baseRef,
2196
+ title: pullRequest.title,
2197
+ body,
2198
+ // A pull request already open keeps its description; this turn's screenshots join it.
2199
+ appendIfExisting: screenshots || null
2200
+ });
2201
+ if (outcome.status === "opened" || outcome.status === "existing") {
2202
+ if (outcome.appendError) {
2203
+ this.emit({
2204
+ type: "error",
2205
+ message: `This turn's screenshots were not added to the pull request description: ${outcome.appendError}.`,
2206
+ retryable: false
2207
+ });
2208
+ }
2209
+ if (outcome.status === "opened") {
2210
+ this.deps.logger.info(`session ${this.sessionId}: opened ${outcome.url}`);
2211
+ }
2212
+ return outcome.url;
2213
+ }
2214
+ if (outcome.status === "failed") {
2215
+ this.deps.logger.warn(
2216
+ `session ${this.sessionId}: could not open the pull request: ${outcome.error}`
2217
+ );
2218
+ this.emit({
2219
+ type: "error",
2220
+ message: `The runner could not open the pull request for ${workBranch}: ${outcome.error}.`,
2221
+ retryable: false
2222
+ });
2223
+ }
2224
+ return null;
2225
+ }
2051
2226
  /** The screenshot folder exists and is kept out of git before the agent can use it. */
2052
2227
  async prepareEvidenceDir() {
2053
2228
  if (!this.record.workBranch || !this.record.repoDir) return;
@@ -2233,6 +2408,7 @@ ${screenshots}`;
2233
2408
  var SCREENSHOTS_TEXT_BUDGET = 59e3;
2234
2409
 
2235
2410
  // src/session-manager.ts
2411
+ var MAX_REFUSED_STARTS = 100;
2236
2412
  var SessionManager = class {
2237
2413
  constructor(opts) {
2238
2414
  this.opts = opts;
@@ -2241,6 +2417,13 @@ var SessionManager = class {
2241
2417
  sessions = /* @__PURE__ */ new Map();
2242
2418
  starting = /* @__PURE__ */ new Map();
2243
2419
  closing = /* @__PURE__ */ new Map();
2420
+ /**
2421
+ * Why a session's last `start_session` was refused, kept so a message that follows it
2422
+ * (handled right after, in the same session order) is answered with that reason — and,
2423
+ * when the start will be delivered again, as retryable, so the message goes again with
2424
+ * it — rather than as a message to a session this runner never heard of. Bounded.
2425
+ */
2426
+ refusedStarts = /* @__PURE__ */ new Map();
2244
2427
  /**
2245
2428
  * Slots taken by dormant sessions being resumed. Counted from the (synchronous) capacity
2246
2429
  * check on, so two resumes in flight cannot both see a free slot while their processes
@@ -2297,7 +2480,7 @@ var SessionManager = class {
2297
2480
  assertSafeSessionId(cmd.sessionId);
2298
2481
  switch (cmd.type) {
2299
2482
  case "start_session":
2300
- return await this.start(cmd);
2483
+ return this.noteStart(cmd.sessionId, await this.start(cmd));
2301
2484
  case "send_message":
2302
2485
  return await this.send(cmd.sessionId, cmd.text, cmd.id);
2303
2486
  case "interrupt":
@@ -2312,8 +2495,23 @@ var SessionManager = class {
2312
2495
  };
2313
2496
  }
2314
2497
  } catch (err) {
2315
- return { ok: false, error: safeError(err) };
2498
+ const refused = { ok: false, error: safeError(err) };
2499
+ return cmd.type === "start_session" ? this.noteStart(cmd.sessionId, refused) : refused;
2500
+ }
2501
+ }
2502
+ noteStart(sessionId, ack) {
2503
+ this.refusedStarts.delete(sessionId);
2504
+ if (!ack.ok) {
2505
+ this.refusedStarts.set(sessionId, {
2506
+ error: ack.error || "no reason given",
2507
+ retryable: ack.retryable === true
2508
+ });
2509
+ while (this.refusedStarts.size > MAX_REFUSED_STARTS) {
2510
+ const oldest = this.refusedStarts.keys().next().value;
2511
+ this.refusedStarts.delete(oldest);
2512
+ }
2316
2513
  }
2514
+ return ack;
2317
2515
  }
2318
2516
  async start(cmd) {
2319
2517
  if (this.sessions.has(cmd.sessionId)) return { ok: true };
@@ -2400,6 +2598,7 @@ var SessionManager = class {
2400
2598
  repoDir: wt.repoDir,
2401
2599
  repository: cmd.repository.url,
2402
2600
  workBranch: cmd.repository.workBranch,
2601
+ ...cmd.pullRequest ? { pullRequest: cmd.pullRequest } : {},
2403
2602
  baseRef: wt.baseRef,
2404
2603
  baseSha: wt.baseSha,
2405
2604
  // A reused kept worktree still holds the uncommitted changes it was kept for: keep
@@ -2448,6 +2647,17 @@ var SessionManager = class {
2448
2647
  async send(sessionId, text, commandId) {
2449
2648
  const session = this.sessions.get(sessionId);
2450
2649
  if (!session) {
2650
+ const refused = this.refusedStarts.get(sessionId);
2651
+ if (refused) {
2652
+ return refused.retryable ? {
2653
+ ok: false,
2654
+ retryable: true,
2655
+ error: `The agent has not started yet, so the message will go when it does: ${refused.error}`
2656
+ } : {
2657
+ ok: false,
2658
+ error: `The agent could not be started, so the message was not sent: ${refused.error}`
2659
+ };
2660
+ }
2451
2661
  return {
2452
2662
  ok: false,
2453
2663
  error: "This runner has no such session (it may have been closed or removed)."
@@ -2591,7 +2801,8 @@ var SessionManager = class {
2591
2801
  disallowedTools: this.opts.config.disallowedTools ?? [],
2592
2802
  loadProjectSettings: this.opts.config.loadProjectSettings ?? false,
2593
2803
  interruptGraceMs: this.opts.interruptGraceMs,
2594
- onClaudeSignIn: this.opts.onClaudeSignIn
2804
+ onClaudeSignIn: this.opts.onClaudeSignIn,
2805
+ openPullRequest: this.opts.openPullRequest
2595
2806
  });
2596
2807
  }
2597
2808
  };
@@ -2726,8 +2937,13 @@ var RunnerDaemon = class {
2726
2937
  protocolVersion: RUNNER_PROTOCOL_VERSION,
2727
2938
  runnerVersion: RUNNER_VERSION,
2728
2939
  platform: RUNNER_PLATFORM,
2729
- // This runner continues closed sessions (`start_session` with `resume`).
2730
- agent: { ...await this.agent(), resumesClosedSessions: true },
2940
+ // This runner continues closed sessions (`start_session` with `resume`), and opens
2941
+ // pull requests itself when asked (`start_session` with `pullRequest`).
2942
+ agent: {
2943
+ ...await this.agent(),
2944
+ resumesClosedSessions: true,
2945
+ opensPullRequests: true
2946
+ },
2731
2947
  activeSessionIds: this.manager.activeSessionIds(),
2732
2948
  maxConcurrentSessions: this.opts.config.maxSessions
2733
2949
  });
@@ -2879,13 +3095,13 @@ async function runDoctor(env = process.env) {
2879
3095
  checks.push({
2880
3096
  name: "GitHub CLI",
2881
3097
  level: res.code === 0 ? "ok" : "warn",
2882
- detail: res.code === 0 ? "signed in: the agent can read its pull request, checks and runs" : "not signed in: run `gh auth login` so the agent can read its pull request"
3098
+ detail: res.code === 0 ? "signed in: pull requests can be opened as you, and the agent can read them" : "not signed in: run `gh auth login` so pull requests can be opened as you"
2883
3099
  });
2884
3100
  } catch {
2885
3101
  checks.push({
2886
3102
  name: "GitHub CLI",
2887
3103
  level: "warn",
2888
- detail: "not installed (no `gh` on PATH): the agent cannot read its pull request; see https://cli.github.com"
3104
+ detail: "not installed (no `gh` on PATH): pull requests cannot be opened as you; see https://cli.github.com"
2889
3105
  });
2890
3106
  }
2891
3107
  const bin = await findClaude(env);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@discovery-tree/runner",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
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": {