@discovery-tree/runner 0.1.8 → 0.1.9

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 +233 -21
  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.9" : "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);
@@ -746,10 +755,17 @@ async function claudeFeatures(bin) {
746
755
  const res = await exec(bin, ["--help"], { timeoutMs: 15e3 });
747
756
  return {
748
757
  permissionPrompts: res.stdout.includes("--permission-prompts"),
749
- settingSources: res.stdout.includes("--setting-sources")
758
+ settingSources: res.stdout.includes("--setting-sources"),
759
+ maxTurns: res.stdout.includes("--max-turns"),
760
+ strictMcpConfig: res.stdout.includes("--strict-mcp-config")
750
761
  };
751
762
  } catch {
752
- return { permissionPrompts: false, settingSources: false };
763
+ return {
764
+ permissionPrompts: false,
765
+ settingSources: false,
766
+ maxTurns: false,
767
+ strictMcpConfig: false
768
+ };
753
769
  }
754
770
  }
755
771
  async function probeAgent(env = process.env) {
@@ -1132,8 +1148,100 @@ function sleep(ms, signal) {
1132
1148
  });
1133
1149
  }
1134
1150
 
1151
+ // src/completion.ts
1152
+ import { mkdtemp as mkdtemp2, rm as rm4 } from "node:fs/promises";
1153
+ import { tmpdir as tmpdir2 } from "node:os";
1154
+ import { join as join6 } from "node:path";
1155
+ var COMPLETION_DENIED_TOOLS = [
1156
+ "Read",
1157
+ "Glob",
1158
+ "Grep",
1159
+ "LS",
1160
+ "Bash",
1161
+ "Edit",
1162
+ "MultiEdit",
1163
+ "Write",
1164
+ "NotebookEdit",
1165
+ "WebFetch",
1166
+ "WebSearch",
1167
+ "Task"
1168
+ ];
1169
+ var COMPLETION_TIMEOUT_MS = 5 * 60 * 1e3;
1170
+ var COMPLETION_MIN_TIME_MS = 1e4;
1171
+ var CANCELLED_BY_SERVER = "Discovery Tree stopped waiting for this answer.";
1172
+ var RUNNER_STOPPING = "The runner stopped before it could answer.";
1173
+ var EXPIRED_WHILE_QUEUED = "Discovery Tree stopped waiting before this runner had a free slot to answer it.";
1174
+ 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.";
1175
+ var NEEDS_STRICT_MCP = "This Claude Code is too old to answer planning requests safely (it has no --strict-mcp-config). Update Claude Code.";
1176
+ function completionArgs(req, features) {
1177
+ if (!features.strictMcpConfig) throw new Error(NEEDS_STRICT_MCP);
1178
+ const args = [
1179
+ "-p",
1180
+ "--output-format",
1181
+ "json",
1182
+ "--permission-mode",
1183
+ "default",
1184
+ "--strict-mcp-config"
1185
+ ];
1186
+ if (features.permissionPrompts) args.push("--permission-prompts", "none");
1187
+ if (features.settingSources) args.push("--setting-sources", "user");
1188
+ if (features.maxTurns) args.push("--max-turns", "1");
1189
+ if (req.model) {
1190
+ assertValidModel(req.model);
1191
+ args.push(`--model=${req.model}`);
1192
+ }
1193
+ args.push("--append-system-prompt", COMPLETION_SYSTEM_PROMPT);
1194
+ args.push("--disallowedTools", ...COMPLETION_DENIED_TOOLS);
1195
+ return args;
1196
+ }
1197
+ async function answerCompletion(req, deps) {
1198
+ let cwd = null;
1199
+ try {
1200
+ const { bin, features } = await deps.claude();
1201
+ const args = completionArgs(req, features);
1202
+ cwd = await mkdtemp2(join6(tmpdir2(), "dt-runner-completion-"));
1203
+ const run = deps.run ?? ((b, a, o) => exec(b, a, o));
1204
+ const input = req.systemPrompt ? `<instructions>
1205
+ ${req.systemPrompt}
1206
+ </instructions>
1207
+
1208
+ <request>
1209
+ ${req.prompt}
1210
+ </request>` : req.prompt;
1211
+ const timeoutMs = Math.min(COMPLETION_TIMEOUT_MS, deps.timeoutMs ?? COMPLETION_TIMEOUT_MS);
1212
+ if (deps.signal?.aborted) return { ok: false, error: RUNNER_STOPPING };
1213
+ const res = await run(bin, args, { cwd, input, timeoutMs, signal: deps.signal });
1214
+ if (deps.signal?.aborted) return { ok: false, error: RUNNER_STOPPING };
1215
+ return readResult(res);
1216
+ } catch (err) {
1217
+ const message = err instanceof Error ? err.message : String(err);
1218
+ return { ok: false, error: message.slice(0, 2e3) };
1219
+ } finally {
1220
+ if (cwd) await rm4(cwd, { recursive: true, force: true }).catch(() => void 0);
1221
+ }
1222
+ }
1223
+ function readResult(res) {
1224
+ let parsed = null;
1225
+ try {
1226
+ const last = res.stdout.trim().split("\n").pop() ?? "";
1227
+ parsed = JSON.parse(last);
1228
+ } catch {
1229
+ parsed = null;
1230
+ }
1231
+ const text = typeof parsed?.result === "string" ? parsed.result : "";
1232
+ if (parsed?.type === "result" && parsed.is_error !== true && res.code === 0 && text.trim()) {
1233
+ return { ok: true, text: text.slice(0, RUNNER_COMPLETION_MAX_TEXT) };
1234
+ }
1235
+ 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.`);
1236
+ return {
1237
+ ok: false,
1238
+ error: why.slice(0, 2e3),
1239
+ signInFailed: looksLikeSignInFailure(why)
1240
+ };
1241
+ }
1242
+
1135
1243
  // src/session-manager.ts
1136
- import { mkdir as mkdir6, rm as rm5 } from "node:fs/promises";
1244
+ import { mkdir as mkdir6, rm as rm6 } from "node:fs/promises";
1137
1245
 
1138
1246
  // src/fsutil.ts
1139
1247
  import { mkdir as mkdir4, readFile as readFile3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
@@ -1541,40 +1649,40 @@ function signalGroup(pgid, signal) {
1541
1649
  }
1542
1650
 
1543
1651
  // 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";
1652
+ import { mkdir as mkdir5, readdir as readdir2, rm as rm5 } from "node:fs/promises";
1653
+ import { join as join7 } from "node:path";
1546
1654
  var HANDLED_COMMAND_IDS_KEPT = 100;
1547
1655
  var SessionStore = class {
1548
1656
  constructor(stateDir) {
1549
1657
  this.stateDir = stateDir;
1550
1658
  }
1551
1659
  dir(sessionId) {
1552
- return join6(this.stateDir, "sessions", sessionId);
1660
+ return join7(this.stateDir, "sessions", sessionId);
1553
1661
  }
1554
1662
  outboxFile(sessionId) {
1555
- return join6(this.dir(sessionId), "outbox.json");
1663
+ return join7(this.dir(sessionId), "outbox.json");
1556
1664
  }
1557
1665
  async save(record) {
1558
1666
  record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
1559
- await writeJsonAtomic(join6(this.dir(record.sessionId), "session.json"), record);
1667
+ await writeJsonAtomic(join7(this.dir(record.sessionId), "session.json"), record);
1560
1668
  }
1561
1669
  async list() {
1562
- const root = join6(this.stateDir, "sessions");
1670
+ const root = join7(this.stateDir, "sessions");
1563
1671
  await mkdir5(root, { recursive: true });
1564
1672
  const out = [];
1565
1673
  for (const entry of await readdir2(root, { withFileTypes: true })) {
1566
1674
  if (!entry.isDirectory()) continue;
1567
- const rec = await readJson(join6(root, entry.name, "session.json"));
1675
+ const rec = await readJson(join7(root, entry.name, "session.json"));
1568
1676
  if (rec?.sessionId === entry.name) out.push(rec);
1569
1677
  }
1570
1678
  return out;
1571
1679
  }
1572
1680
  async remove(sessionId) {
1573
- await rm4(this.dir(sessionId), { recursive: true, force: true });
1681
+ await rm5(this.dir(sessionId), { recursive: true, force: true });
1574
1682
  }
1575
1683
  /** Scratch working directory for a session without a repository. */
1576
1684
  scratchDir(sessionId) {
1577
- return join6(this.stateDir, "scratch", sessionId);
1685
+ return join7(this.stateDir, "scratch", sessionId);
1578
1686
  }
1579
1687
  };
1580
1688
  function assertSafeSessionId(id) {
@@ -2728,7 +2836,7 @@ var SessionManager = class {
2728
2836
  })
2729
2837
  );
2730
2838
  } else if (record.cwd) {
2731
- await rm5(record.cwd, { recursive: true, force: true }).catch(() => void 0);
2839
+ await rm6(record.cwd, { recursive: true, force: true }).catch(() => void 0);
2732
2840
  }
2733
2841
  await session.outbox.settled();
2734
2842
  await this.store.remove(sessionId);
@@ -2861,6 +2969,11 @@ var RunnerDaemon = class {
2861
2969
  /** The tail of each session's command queue (see `inSessionOrder`); never rejects. */
2862
2970
  sessionQueues = /* @__PURE__ */ new Map();
2863
2971
  upgradeWarnedAt = 0;
2972
+ /** Completions answering now, and those waiting for a turn (see `answer`). */
2973
+ completionsRunning = 0;
2974
+ /** Each planning request held (answering or queued), to cancel it when Discovery Tree says. */
2975
+ completionControllers = /* @__PURE__ */ new Map();
2976
+ completionWaiters = [];
2864
2977
  get signal() {
2865
2978
  return this.controller.signal;
2866
2979
  }
@@ -2942,11 +3055,17 @@ var RunnerDaemon = class {
2942
3055
  agent: {
2943
3056
  ...await this.agent(),
2944
3057
  resumesClosedSessions: true,
2945
- opensPullRequests: true
3058
+ opensPullRequests: true,
3059
+ // And answers one-off requests, such as planning, outside any session.
3060
+ answersCompletions: true
2946
3061
  },
2947
3062
  activeSessionIds: this.manager.activeSessionIds(),
2948
- maxConcurrentSessions: this.opts.config.maxSessions
3063
+ maxConcurrentSessions: this.opts.config.maxSessions,
3064
+ activeCompletionIds: [...this.completionControllers.keys()]
2949
3065
  });
3066
+ for (const id of res?.cancelCompletionIds ?? []) {
3067
+ this.completionControllers.get(id)?.abort();
3068
+ }
2950
3069
  if (failures) this.opts.logger.info("reconnected to Discovery Tree");
2951
3070
  failures = 0;
2952
3071
  for (const id of res?.closeSessionIds ?? []) {
@@ -2982,6 +3101,7 @@ var RunnerDaemon = class {
2982
3101
  attempt = 0;
2983
3102
  limited = 0;
2984
3103
  for (const cmd of res?.commands ?? []) this.track(this.dispatch(cmd));
3104
+ for (const req of res?.completions ?? []) this.track(this.answer(req));
2985
3105
  } catch (err) {
2986
3106
  if (this.signal.aborted) break;
2987
3107
  if (err instanceof UnauthorizedError) return this.unauthorized(err);
@@ -3048,6 +3168,98 @@ var RunnerDaemon = class {
3048
3168
  }
3049
3169
  await this.ack(cmd.id, ack);
3050
3170
  }
3171
+ /**
3172
+ * A slot to run a completion in: at once while fewer than the runner's session limit run,
3173
+ * else after the next one ends. False when `cancelled` fires first: the request leaves
3174
+ * the line without a slot, so it must not give one back.
3175
+ */
3176
+ takeCompletionSlot(cancelled) {
3177
+ if (cancelled.aborted) return Promise.resolve(false);
3178
+ if (this.completionsRunning < Math.max(1, this.opts.config.maxSessions)) {
3179
+ this.completionsRunning++;
3180
+ return Promise.resolve(true);
3181
+ }
3182
+ return new Promise((resolve) => {
3183
+ const handOver = () => {
3184
+ cancelled.removeEventListener("abort", leave);
3185
+ resolve(true);
3186
+ };
3187
+ const leave = () => {
3188
+ const at = this.completionWaiters.indexOf(handOver);
3189
+ if (at >= 0) this.completionWaiters.splice(at, 1);
3190
+ resolve(false);
3191
+ };
3192
+ this.completionWaiters.push(handOver);
3193
+ cancelled.addEventListener("abort", leave, { once: true });
3194
+ });
3195
+ }
3196
+ /** A finished completion's slot goes straight to the next in line, or is freed. */
3197
+ giveBackCompletionSlot() {
3198
+ const next = this.completionWaiters.shift();
3199
+ if (next) next();
3200
+ else this.completionsRunning--;
3201
+ }
3202
+ /**
3203
+ * Answers a one-off request and posts the answer, retried a few times. Discovery Tree
3204
+ * waits for it while the person does, so there is no later redelivery to fall back on.
3205
+ */
3206
+ async answer(req) {
3207
+ const receivedAt = Date.now();
3208
+ const own = new AbortController();
3209
+ this.completionControllers.set(req.id, own);
3210
+ const cancelled = AbortSignal.any([this.signal, own.signal]);
3211
+ const acquired = await this.takeCompletionSlot(cancelled);
3212
+ let result;
3213
+ try {
3214
+ const left = typeof req.timeLeftMs === "number" ? req.timeLeftMs - (Date.now() - receivedAt) : null;
3215
+ if (own.signal.aborted) {
3216
+ result = { ok: false, error: CANCELLED_BY_SERVER };
3217
+ } else if (this.signal.aborted) {
3218
+ result = { ok: false, error: RUNNER_STOPPING };
3219
+ } else if (!acquired) {
3220
+ result = { ok: false, error: RUNNER_STOPPING };
3221
+ } else if (left !== null && left < COMPLETION_MIN_TIME_MS) {
3222
+ this.opts.logger.warn("skipped a planning request that expired while queued", {
3223
+ id: req.id
3224
+ });
3225
+ result = { ok: false, error: EXPIRED_WHILE_QUEUED };
3226
+ } else {
3227
+ this.opts.logger.info("answering a planning request", { id: req.id });
3228
+ result = await answerCompletion(req, {
3229
+ claude: () => this.resolveClaude(),
3230
+ signal: cancelled,
3231
+ ...left !== null ? { timeoutMs: left } : {}
3232
+ });
3233
+ }
3234
+ if (own.signal.aborted) result = { ok: false, error: CANCELLED_BY_SERVER };
3235
+ } finally {
3236
+ this.completionControllers.delete(req.id);
3237
+ if (acquired) this.giveBackCompletionSlot();
3238
+ }
3239
+ if (!result.ok) {
3240
+ this.opts.logger.warn("could not answer a planning request", {
3241
+ id: req.id,
3242
+ error: result.error
3243
+ });
3244
+ }
3245
+ if (result.signInFailed) this.claudeSignIn(false);
3246
+ else if (result.ok) this.claudeSignIn(true);
3247
+ for (let attempt = 0; attempt < 5; attempt++) {
3248
+ try {
3249
+ await this.api.postCompletion(req.id, result);
3250
+ return;
3251
+ } catch (err) {
3252
+ if (err instanceof UnauthorizedError) return this.unauthorized(err);
3253
+ if (!isRetryable(err)) {
3254
+ this.opts.logger.warn("the server refused a planning answer", {
3255
+ error: err.message
3256
+ });
3257
+ return;
3258
+ }
3259
+ await sleep(backoffDelay(attempt, this.opts.retryBaseMs ?? 1e3, 1e4));
3260
+ }
3261
+ }
3262
+ }
3051
3263
  /** Acks are retried a few times; a lost one means a redelivery, which handlers absorb. */
3052
3264
  async ack(commandId, body) {
3053
3265
  for (let attempt = 0; attempt < 5; attempt++) {
@@ -3152,10 +3364,10 @@ function formatChecks(checks) {
3152
3364
  }
3153
3365
 
3154
3366
  // 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";
3367
+ import { mkdir as mkdir7, open, readFile as readFile4, rm as rm7 } from "node:fs/promises";
3368
+ import { join as join8 } from "node:path";
3157
3369
  function lockFile(stateDir) {
3158
- return join7(stateDir, "daemon.pid");
3370
+ return join8(stateDir, "daemon.pid");
3159
3371
  }
3160
3372
  function pidAlive(pid) {
3161
3373
  if (!Number.isInteger(pid) || pid <= 0) return false;
@@ -3194,7 +3406,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
3194
3406
  file,
3195
3407
  async release() {
3196
3408
  const current = await readFile4(file, "utf8").catch(() => "");
3197
- if (Number.parseInt(current.trim(), 10) === pid) await rm6(file, { force: true });
3409
+ if (Number.parseInt(current.trim(), 10) === pid) await rm7(file, { force: true });
3198
3410
  }
3199
3411
  }
3200
3412
  };
@@ -3205,7 +3417,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
3205
3417
  if (raw === null) continue;
3206
3418
  const holder = Number.parseInt(raw.trim(), 10);
3207
3419
  if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
3208
- await rm6(file, { force: true });
3420
+ await rm7(file, { force: true });
3209
3421
  }
3210
3422
  return { ok: false, pid: null };
3211
3423
  }
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.9",
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": {