@discovery-tree/runner 0.1.7 → 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.
- package/README.md +16 -0
- package/dist/cli.js +291 -26
- 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.
|
|
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 {
|
|
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
|
|
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
|
|
1545
|
-
import { join as
|
|
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
|
|
1660
|
+
return join7(this.stateDir, "sessions", sessionId);
|
|
1553
1661
|
}
|
|
1554
1662
|
outboxFile(sessionId) {
|
|
1555
|
-
return
|
|
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(
|
|
1667
|
+
await writeJsonAtomic(join7(this.dir(record.sessionId), "session.json"), record);
|
|
1560
1668
|
}
|
|
1561
1669
|
async list() {
|
|
1562
|
-
const root =
|
|
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(
|
|
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
|
|
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
|
|
1685
|
+
return join7(this.stateDir, "scratch", sessionId);
|
|
1578
1686
|
}
|
|
1579
1687
|
};
|
|
1580
1688
|
function assertSafeSessionId(id) {
|
|
@@ -1821,6 +1929,11 @@ var AgentSession = class {
|
|
|
1821
1929
|
* conversation, with the preface the continuation brought.
|
|
1822
1930
|
*/
|
|
1823
1931
|
resumeRetry = null;
|
|
1932
|
+
/**
|
|
1933
|
+
* The process failed to resume before any turn began (its error result came while a
|
|
1934
|
+
* message was still being delivered): it is ending, so no message may be written to it.
|
|
1935
|
+
*/
|
|
1936
|
+
resumeDoomed = false;
|
|
1824
1937
|
exitWaiters = [];
|
|
1825
1938
|
/** Settles once the current process has exited and what it left in its group is gone. */
|
|
1826
1939
|
groupReaped = Promise.resolve();
|
|
@@ -1939,7 +2052,7 @@ var AgentSession = class {
|
|
|
1939
2052
|
* result that will never come.
|
|
1940
2053
|
*/
|
|
1941
2054
|
async beginTurn(text, before) {
|
|
1942
|
-
while (!this.child || this.stopping) await this.ensureProcess();
|
|
2055
|
+
while (!this.child || this.stopping || this.resumeDoomed) await this.ensureProcess();
|
|
1943
2056
|
let content = text;
|
|
1944
2057
|
const preface = this.record.freshPreface;
|
|
1945
2058
|
if (preface && !this.spawnedWithResume) {
|
|
@@ -1974,7 +2087,7 @@ ${text}`;
|
|
|
1974
2087
|
return new Promise((resolve) => this.exitWaiters.push(resolve));
|
|
1975
2088
|
}
|
|
1976
2089
|
async ensureProcess() {
|
|
1977
|
-
while (this.child && this.stopping) await this.waitForExit();
|
|
2090
|
+
while (this.child && (this.stopping || this.resumeDoomed)) await this.waitForExit();
|
|
1978
2091
|
if (this.child) return;
|
|
1979
2092
|
await this.prepareEvidenceDir();
|
|
1980
2093
|
const { bin, features } = await this.deps.claude();
|
|
@@ -2013,6 +2126,7 @@ ${text}`;
|
|
|
2013
2126
|
});
|
|
2014
2127
|
this.child = child;
|
|
2015
2128
|
this.stopping = null;
|
|
2129
|
+
this.resumeDoomed = false;
|
|
2016
2130
|
this.reapGraceMs = void 0;
|
|
2017
2131
|
this.stderrTail = "";
|
|
2018
2132
|
this.sawResultSinceSpawn = false;
|
|
@@ -2087,6 +2201,16 @@ ${text}`;
|
|
|
2087
2201
|
this.child?.stdin.end();
|
|
2088
2202
|
return;
|
|
2089
2203
|
}
|
|
2204
|
+
if (mapped.turnEnd && this.resumeFailedBeforeTurn(mapped.turnEnd.isError)) {
|
|
2205
|
+
this.deps.logger.warn(
|
|
2206
|
+
`session ${this.sessionId}: the Claude Code conversation to resume was not found; starting a fresh one`
|
|
2207
|
+
);
|
|
2208
|
+
this.record.claudeSessionId = null;
|
|
2209
|
+
this.resumeDoomed = true;
|
|
2210
|
+
await this.deps.store.save(this.record);
|
|
2211
|
+
this.child?.stdin.end();
|
|
2212
|
+
return;
|
|
2213
|
+
}
|
|
2090
2214
|
if (mapped.turnEnd) {
|
|
2091
2215
|
this.sawResultSinceSpawn = true;
|
|
2092
2216
|
await this.endTurn(mapped.turnEnd);
|
|
@@ -2097,7 +2221,10 @@ ${text}`;
|
|
|
2097
2221
|
* (no `system/init`): Claude Code did not find the conversation on this computer.
|
|
2098
2222
|
*/
|
|
2099
2223
|
resumeNotFound(isError) {
|
|
2100
|
-
return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && this.turnText !== null;
|
|
2224
|
+
return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && this.record.turnActive && this.turnText !== null;
|
|
2225
|
+
}
|
|
2226
|
+
resumeFailedBeforeTurn(isError) {
|
|
2227
|
+
return isError && this.spawnedWithResume && !this.sawInitSinceSpawn && !this.interruptRequested && !this.record.turnActive;
|
|
2101
2228
|
}
|
|
2102
2229
|
planFreshRetry() {
|
|
2103
2230
|
this.deps.logger.warn(
|
|
@@ -2389,6 +2516,7 @@ ${screenshots}`;
|
|
|
2389
2516
|
var SCREENSHOTS_TEXT_BUDGET = 59e3;
|
|
2390
2517
|
|
|
2391
2518
|
// src/session-manager.ts
|
|
2519
|
+
var MAX_REFUSED_STARTS = 100;
|
|
2392
2520
|
var SessionManager = class {
|
|
2393
2521
|
constructor(opts) {
|
|
2394
2522
|
this.opts = opts;
|
|
@@ -2397,6 +2525,13 @@ var SessionManager = class {
|
|
|
2397
2525
|
sessions = /* @__PURE__ */ new Map();
|
|
2398
2526
|
starting = /* @__PURE__ */ new Map();
|
|
2399
2527
|
closing = /* @__PURE__ */ new Map();
|
|
2528
|
+
/**
|
|
2529
|
+
* Why a session's last `start_session` was refused, kept so a message that follows it
|
|
2530
|
+
* (handled right after, in the same session order) is answered with that reason — and,
|
|
2531
|
+
* when the start will be delivered again, as retryable, so the message goes again with
|
|
2532
|
+
* it — rather than as a message to a session this runner never heard of. Bounded.
|
|
2533
|
+
*/
|
|
2534
|
+
refusedStarts = /* @__PURE__ */ new Map();
|
|
2400
2535
|
/**
|
|
2401
2536
|
* Slots taken by dormant sessions being resumed. Counted from the (synchronous) capacity
|
|
2402
2537
|
* check on, so two resumes in flight cannot both see a free slot while their processes
|
|
@@ -2453,7 +2588,7 @@ var SessionManager = class {
|
|
|
2453
2588
|
assertSafeSessionId(cmd.sessionId);
|
|
2454
2589
|
switch (cmd.type) {
|
|
2455
2590
|
case "start_session":
|
|
2456
|
-
return await this.start(cmd);
|
|
2591
|
+
return this.noteStart(cmd.sessionId, await this.start(cmd));
|
|
2457
2592
|
case "send_message":
|
|
2458
2593
|
return await this.send(cmd.sessionId, cmd.text, cmd.id);
|
|
2459
2594
|
case "interrupt":
|
|
@@ -2468,8 +2603,23 @@ var SessionManager = class {
|
|
|
2468
2603
|
};
|
|
2469
2604
|
}
|
|
2470
2605
|
} catch (err) {
|
|
2471
|
-
|
|
2606
|
+
const refused = { ok: false, error: safeError(err) };
|
|
2607
|
+
return cmd.type === "start_session" ? this.noteStart(cmd.sessionId, refused) : refused;
|
|
2608
|
+
}
|
|
2609
|
+
}
|
|
2610
|
+
noteStart(sessionId, ack) {
|
|
2611
|
+
this.refusedStarts.delete(sessionId);
|
|
2612
|
+
if (!ack.ok) {
|
|
2613
|
+
this.refusedStarts.set(sessionId, {
|
|
2614
|
+
error: ack.error || "no reason given",
|
|
2615
|
+
retryable: ack.retryable === true
|
|
2616
|
+
});
|
|
2617
|
+
while (this.refusedStarts.size > MAX_REFUSED_STARTS) {
|
|
2618
|
+
const oldest = this.refusedStarts.keys().next().value;
|
|
2619
|
+
this.refusedStarts.delete(oldest);
|
|
2620
|
+
}
|
|
2472
2621
|
}
|
|
2622
|
+
return ack;
|
|
2473
2623
|
}
|
|
2474
2624
|
async start(cmd) {
|
|
2475
2625
|
if (this.sessions.has(cmd.sessionId)) return { ok: true };
|
|
@@ -2605,6 +2755,17 @@ var SessionManager = class {
|
|
|
2605
2755
|
async send(sessionId, text, commandId) {
|
|
2606
2756
|
const session = this.sessions.get(sessionId);
|
|
2607
2757
|
if (!session) {
|
|
2758
|
+
const refused = this.refusedStarts.get(sessionId);
|
|
2759
|
+
if (refused) {
|
|
2760
|
+
return refused.retryable ? {
|
|
2761
|
+
ok: false,
|
|
2762
|
+
retryable: true,
|
|
2763
|
+
error: `The agent has not started yet, so the message will go when it does: ${refused.error}`
|
|
2764
|
+
} : {
|
|
2765
|
+
ok: false,
|
|
2766
|
+
error: `The agent could not be started, so the message was not sent: ${refused.error}`
|
|
2767
|
+
};
|
|
2768
|
+
}
|
|
2608
2769
|
return {
|
|
2609
2770
|
ok: false,
|
|
2610
2771
|
error: "This runner has no such session (it may have been closed or removed)."
|
|
@@ -2675,7 +2836,7 @@ var SessionManager = class {
|
|
|
2675
2836
|
})
|
|
2676
2837
|
);
|
|
2677
2838
|
} else if (record.cwd) {
|
|
2678
|
-
await
|
|
2839
|
+
await rm6(record.cwd, { recursive: true, force: true }).catch(() => void 0);
|
|
2679
2840
|
}
|
|
2680
2841
|
await session.outbox.settled();
|
|
2681
2842
|
await this.store.remove(sessionId);
|
|
@@ -2808,6 +2969,11 @@ var RunnerDaemon = class {
|
|
|
2808
2969
|
/** The tail of each session's command queue (see `inSessionOrder`); never rejects. */
|
|
2809
2970
|
sessionQueues = /* @__PURE__ */ new Map();
|
|
2810
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 = [];
|
|
2811
2977
|
get signal() {
|
|
2812
2978
|
return this.controller.signal;
|
|
2813
2979
|
}
|
|
@@ -2889,11 +3055,17 @@ var RunnerDaemon = class {
|
|
|
2889
3055
|
agent: {
|
|
2890
3056
|
...await this.agent(),
|
|
2891
3057
|
resumesClosedSessions: true,
|
|
2892
|
-
opensPullRequests: true
|
|
3058
|
+
opensPullRequests: true,
|
|
3059
|
+
// And answers one-off requests, such as planning, outside any session.
|
|
3060
|
+
answersCompletions: true
|
|
2893
3061
|
},
|
|
2894
3062
|
activeSessionIds: this.manager.activeSessionIds(),
|
|
2895
|
-
maxConcurrentSessions: this.opts.config.maxSessions
|
|
3063
|
+
maxConcurrentSessions: this.opts.config.maxSessions,
|
|
3064
|
+
activeCompletionIds: [...this.completionControllers.keys()]
|
|
2896
3065
|
});
|
|
3066
|
+
for (const id of res?.cancelCompletionIds ?? []) {
|
|
3067
|
+
this.completionControllers.get(id)?.abort();
|
|
3068
|
+
}
|
|
2897
3069
|
if (failures) this.opts.logger.info("reconnected to Discovery Tree");
|
|
2898
3070
|
failures = 0;
|
|
2899
3071
|
for (const id of res?.closeSessionIds ?? []) {
|
|
@@ -2929,6 +3101,7 @@ var RunnerDaemon = class {
|
|
|
2929
3101
|
attempt = 0;
|
|
2930
3102
|
limited = 0;
|
|
2931
3103
|
for (const cmd of res?.commands ?? []) this.track(this.dispatch(cmd));
|
|
3104
|
+
for (const req of res?.completions ?? []) this.track(this.answer(req));
|
|
2932
3105
|
} catch (err) {
|
|
2933
3106
|
if (this.signal.aborted) break;
|
|
2934
3107
|
if (err instanceof UnauthorizedError) return this.unauthorized(err);
|
|
@@ -2995,6 +3168,98 @@ var RunnerDaemon = class {
|
|
|
2995
3168
|
}
|
|
2996
3169
|
await this.ack(cmd.id, ack);
|
|
2997
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
|
+
}
|
|
2998
3263
|
/** Acks are retried a few times; a lost one means a redelivery, which handlers absorb. */
|
|
2999
3264
|
async ack(commandId, body) {
|
|
3000
3265
|
for (let attempt = 0; attempt < 5; attempt++) {
|
|
@@ -3099,10 +3364,10 @@ function formatChecks(checks) {
|
|
|
3099
3364
|
}
|
|
3100
3365
|
|
|
3101
3366
|
// src/lock.ts
|
|
3102
|
-
import { mkdir as mkdir7, open, readFile as readFile4, rm as
|
|
3103
|
-
import { join as
|
|
3367
|
+
import { mkdir as mkdir7, open, readFile as readFile4, rm as rm7 } from "node:fs/promises";
|
|
3368
|
+
import { join as join8 } from "node:path";
|
|
3104
3369
|
function lockFile(stateDir) {
|
|
3105
|
-
return
|
|
3370
|
+
return join8(stateDir, "daemon.pid");
|
|
3106
3371
|
}
|
|
3107
3372
|
function pidAlive(pid) {
|
|
3108
3373
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
@@ -3141,7 +3406,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
|
3141
3406
|
file,
|
|
3142
3407
|
async release() {
|
|
3143
3408
|
const current = await readFile4(file, "utf8").catch(() => "");
|
|
3144
|
-
if (Number.parseInt(current.trim(), 10) === pid) await
|
|
3409
|
+
if (Number.parseInt(current.trim(), 10) === pid) await rm7(file, { force: true });
|
|
3145
3410
|
}
|
|
3146
3411
|
}
|
|
3147
3412
|
};
|
|
@@ -3152,7 +3417,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
|
3152
3417
|
if (raw === null) continue;
|
|
3153
3418
|
const holder = Number.parseInt(raw.trim(), 10);
|
|
3154
3419
|
if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
|
|
3155
|
-
await
|
|
3420
|
+
await rm7(file, { force: true });
|
|
3156
3421
|
}
|
|
3157
3422
|
return { ok: false, pid: null };
|
|
3158
3423
|
}
|
package/package.json
CHANGED