@discovery-tree/runner 0.1.10 → 0.1.12
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 -7
- package/dist/cli.js +1131 -116
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -18,6 +18,15 @@ var WORKSPACE_KEY_PROVIDER_TYPES = [
|
|
|
18
18
|
...WORKSPACE_ONLY_KEY_PROVIDERS
|
|
19
19
|
];
|
|
20
20
|
|
|
21
|
+
// ../contracts/src/ai-key-policy.ts
|
|
22
|
+
var AI_CATEGORY_MODEL_MAX_LENGTH = 200;
|
|
23
|
+
|
|
24
|
+
// ../contracts/src/agent-work.ts
|
|
25
|
+
var AGENT_WORK_IDLE_AFTER_MS = 24 * 60 * 60 * 1e3;
|
|
26
|
+
|
|
27
|
+
// ../contracts/src/default-task-model.ts
|
|
28
|
+
var DEFAULT_TASK_MODEL_MAX_LENGTH = 32 + 1 + AI_CATEGORY_MODEL_MAX_LENGTH;
|
|
29
|
+
|
|
21
30
|
// ../contracts/src/ui-evidence.ts
|
|
22
31
|
var UI_EVIDENCE_EXPECTATION = [
|
|
23
32
|
"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.",
|
|
@@ -39,8 +48,8 @@ var AGENT_RUN_MAX_WALL_MS = 6 * 60 * 60 * 1e3;
|
|
|
39
48
|
var AGENT_RUN_ABANDONED_GRACE_MS = 30 * 60 * 1e3;
|
|
40
49
|
var AGENT_RUN_AUTO_RECOVER_MAX_MS = 5 * 6e4;
|
|
41
50
|
|
|
42
|
-
// ../contracts/src/
|
|
43
|
-
var
|
|
51
|
+
// ../contracts/src/automated-review.ts
|
|
52
|
+
var REVIEW_AGENT_ROUND_STALE_MS = 30 * 6e4;
|
|
44
53
|
|
|
45
54
|
// ../contracts/src/agent-runner.ts
|
|
46
55
|
var RUNNER_PROTOCOL_VERSION = 1;
|
|
@@ -48,10 +57,59 @@ var RUNNER_COMMAND_POLL_MAX_WAIT_MS = 25e3;
|
|
|
48
57
|
var RUNNER_EVENTS_MAX_BATCH = 200;
|
|
49
58
|
var RUNNER_EVENT_TEXT_MAX_LENGTH = 64e3;
|
|
50
59
|
var RUNNER_EVENTS_MAX_BODY_BYTES = 8 * 1024 * 1024;
|
|
60
|
+
var RUNNER_SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
61
|
+
function isRunnerSessionId(value) {
|
|
62
|
+
return typeof value === "string" && RUNNER_SESSION_ID_RE.test(value);
|
|
63
|
+
}
|
|
51
64
|
var RUNNER_COMPLETION_MAX_TEXT = 2e5;
|
|
52
65
|
|
|
66
|
+
// ../contracts/src/agent-permissions.ts
|
|
67
|
+
var AGENT_PERMISSION_MESSAGE_MAX_LENGTH = 2e3;
|
|
68
|
+
var AGENT_PERMISSION_INPUT_SUMMARY_MAX_LENGTH = 2e3;
|
|
69
|
+
var RUNNER_PERMISSION_REQUEST_TIMEOUT_MS = 30 * 6e4;
|
|
70
|
+
|
|
71
|
+
// ../contracts/src/agent-tool-grants.ts
|
|
72
|
+
var GRANTABLE_DENIAL = /permission for this tool use was denied|no approval surface|haven'?t granted it yet|permission prompts are not answered on this runner|permission for this tool call was not granted/i;
|
|
73
|
+
var NOT_GRANTABLE = /the person denied permission|has been denied by a (deny )?rule|matches a deny rule/i;
|
|
74
|
+
function isGrantableToolDenial(text) {
|
|
75
|
+
return !!text && GRANTABLE_DENIAL.test(text) && !NOT_GRANTABLE.test(text);
|
|
76
|
+
}
|
|
77
|
+
var TOOL_GRANT_RULE_MAX_LENGTH = 500;
|
|
78
|
+
var RUNNER_TOOL_GRANTS_MAX = 500;
|
|
79
|
+
var RULE_SHAPE = /^([A-Za-z][A-Za-z0-9_.-]*)(?:\(([\s\S]*)\))?$/;
|
|
80
|
+
function toolGrantRuleProblem(rule) {
|
|
81
|
+
if (typeof rule !== "string" || !rule.trim()) return "The rule is empty.";
|
|
82
|
+
const r = rule.trim();
|
|
83
|
+
if (r.length > TOOL_GRANT_RULE_MAX_LENGTH) {
|
|
84
|
+
return `The rule is too long (${r.length} characters; the limit is ${TOOL_GRANT_RULE_MAX_LENGTH}).`;
|
|
85
|
+
}
|
|
86
|
+
if (/[\u0000-\u001f\u007f]/.test(r)) return "The rule must be one line.";
|
|
87
|
+
const m = RULE_SHAPE.exec(r);
|
|
88
|
+
if (!m) {
|
|
89
|
+
return "The rule must be a tool name, optionally with what it may do in parentheses, such as Bash(pnpm test *).";
|
|
90
|
+
}
|
|
91
|
+
const [, tool, spec] = m;
|
|
92
|
+
if (spec === void 0) {
|
|
93
|
+
return tool === "Bash" ? "Bash on its own would allow every shell command; name the command, such as Bash(pnpm test *)." : null;
|
|
94
|
+
}
|
|
95
|
+
if (!spec.trim()) return "Say what the tool may do inside the parentheses, or leave them out.";
|
|
96
|
+
if (/^[\s*:/\\~.]*$/.test(spec.replace(/^domain:/, ""))) {
|
|
97
|
+
return `${tool}(${spec}) would allow everything; narrow it.`;
|
|
98
|
+
}
|
|
99
|
+
if (tool === "Bash" && /^[\s*]/.test(spec)) {
|
|
100
|
+
return "A shell rule must start with the command, such as Bash(pnpm test *).";
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
function toolGrantRepositoryKey(url) {
|
|
105
|
+
if (!url) return null;
|
|
106
|
+
const m = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(url.trim());
|
|
107
|
+
if (!m || m[1] === "." || m[1] === ".." || m[2] === "." || m[2] === "..") return null;
|
|
108
|
+
return `${m[1]}/${m[2]}`.toLowerCase();
|
|
109
|
+
}
|
|
110
|
+
|
|
53
111
|
// src/version.ts
|
|
54
|
-
var RUNNER_VERSION = true ? "0.1.
|
|
112
|
+
var RUNNER_VERSION = true ? "0.1.12" : "0.0.0-dev";
|
|
55
113
|
var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
|
|
56
114
|
|
|
57
115
|
// src/api.ts
|
|
@@ -174,36 +232,234 @@ import { tmpdir } from "node:os";
|
|
|
174
232
|
import { isAbsolute as isAbsolute2, join as join3 } from "node:path";
|
|
175
233
|
|
|
176
234
|
// src/exec.ts
|
|
177
|
-
import { spawn } from "node:child_process";
|
|
235
|
+
import { spawn as spawn2 } from "node:child_process";
|
|
178
236
|
import { access, constants } from "node:fs/promises";
|
|
179
237
|
import { delimiter, isAbsolute, join } from "node:path";
|
|
238
|
+
|
|
239
|
+
// src/process-tree.ts
|
|
240
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
241
|
+
var OWN_PROCESS_GROUP = process.platform !== "win32";
|
|
242
|
+
var liveTrees = /* @__PURE__ */ new Map();
|
|
243
|
+
var exitHookInstalled = false;
|
|
244
|
+
function trackTree(child, cwd) {
|
|
245
|
+
if (!child.pid) return null;
|
|
246
|
+
const tree = {
|
|
247
|
+
pid: child.pid,
|
|
248
|
+
startedAt: Date.now() - 2e3,
|
|
249
|
+
...cwd ? { cwd } : {}
|
|
250
|
+
};
|
|
251
|
+
liveTrees.set(child.pid, { ...tree, child });
|
|
252
|
+
if (!exitHookInstalled) {
|
|
253
|
+
exitHookInstalled = true;
|
|
254
|
+
process.once("exit", () => {
|
|
255
|
+
for (const { pid, child: root } of liveTrees.values()) {
|
|
256
|
+
if (OWN_PROCESS_GROUP) signalGroup(pid, "SIGKILL");
|
|
257
|
+
else if (root.exitCode === null && root.signalCode === null) {
|
|
258
|
+
spawnSync("taskkill", ["/pid", String(pid), "/T", "/F"], {
|
|
259
|
+
stdio: "ignore",
|
|
260
|
+
windowsHide: true,
|
|
261
|
+
timeout: 5e3
|
|
262
|
+
});
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
return tree;
|
|
268
|
+
}
|
|
269
|
+
function signalTree(child, signal) {
|
|
270
|
+
if (!child.pid) return;
|
|
271
|
+
if (OWN_PROCESS_GROUP) {
|
|
272
|
+
if (!signalGroup(child.pid, signal)) child.kill(signal);
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
if (signal === "SIGKILL") {
|
|
276
|
+
const tk = spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
277
|
+
stdio: "ignore",
|
|
278
|
+
windowsHide: true
|
|
279
|
+
});
|
|
280
|
+
let fellBack = false;
|
|
281
|
+
const fallBack = () => {
|
|
282
|
+
if (fellBack) return;
|
|
283
|
+
fellBack = true;
|
|
284
|
+
child.kill(signal);
|
|
285
|
+
};
|
|
286
|
+
tk.on("error", fallBack);
|
|
287
|
+
tk.on("exit", (code) => {
|
|
288
|
+
if (code !== 0) fallBack();
|
|
289
|
+
});
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
child.kill(signal);
|
|
293
|
+
}
|
|
294
|
+
async function reapTree(tree, graceMs = 2e3, deps = {}) {
|
|
295
|
+
if (!tree) return;
|
|
296
|
+
try {
|
|
297
|
+
if (OWN_PROCESS_GROUP) {
|
|
298
|
+
if (!signalGroup(tree.pid, "SIGTERM")) return;
|
|
299
|
+
const deadline = Date.now() + graceMs;
|
|
300
|
+
while (Date.now() < deadline) {
|
|
301
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
302
|
+
if (!signalGroup(tree.pid, 0)) return;
|
|
303
|
+
}
|
|
304
|
+
signalGroup(tree.pid, "SIGKILL");
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
const rows = await (deps.listProcesses ?? listWindowsProcesses)();
|
|
308
|
+
const orphans = descendantsOf(tree, rows);
|
|
309
|
+
if (orphans.length) await (deps.kill ?? taskkillTrees)(orphans);
|
|
310
|
+
} catch {
|
|
311
|
+
} finally {
|
|
312
|
+
if (liveTrees.get(tree.pid)?.startedAt === tree.startedAt) liveTrees.delete(tree.pid);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
function descendantsOf(tree, rows) {
|
|
316
|
+
const byParent = /* @__PURE__ */ new Map();
|
|
317
|
+
const byPid = /* @__PURE__ */ new Map();
|
|
318
|
+
for (const row of rows) {
|
|
319
|
+
byPid.set(row.pid, row);
|
|
320
|
+
const list = byParent.get(row.ppid);
|
|
321
|
+
if (list) list.push(row);
|
|
322
|
+
else byParent.set(row.ppid, [row]);
|
|
323
|
+
}
|
|
324
|
+
const reused = byPid.get(tree.pid);
|
|
325
|
+
const reusedAt = reused && reused.createdAt > tree.startedAt + 2e3 ? reused.createdAt : null;
|
|
326
|
+
const out = [];
|
|
327
|
+
const seen = /* @__PURE__ */ new Set([tree.pid]);
|
|
328
|
+
const queue = [
|
|
329
|
+
{ pid: tree.pid, since: tree.startedAt, until: reusedAt }
|
|
330
|
+
];
|
|
331
|
+
if (tree.cwd) {
|
|
332
|
+
for (const row of rows) {
|
|
333
|
+
if (row.pid === tree.pid || row.createdAt < tree.startedAt) continue;
|
|
334
|
+
const parent = byPid.get(row.ppid);
|
|
335
|
+
const orphaned = !parent || parent.createdAt > row.createdAt;
|
|
336
|
+
if (orphaned && namesPathIn(row.commandLine, tree.cwd)) {
|
|
337
|
+
seen.add(row.pid);
|
|
338
|
+
out.push(row.pid);
|
|
339
|
+
queue.push({ pid: row.pid, since: row.createdAt - 1e3, until: null });
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
while (queue.length) {
|
|
344
|
+
const { pid, since, until } = queue.shift();
|
|
345
|
+
for (const child of byParent.get(pid) ?? []) {
|
|
346
|
+
if (seen.has(child.pid)) continue;
|
|
347
|
+
if (child.createdAt < since) continue;
|
|
348
|
+
if (until !== null && child.createdAt >= until) continue;
|
|
349
|
+
seen.add(child.pid);
|
|
350
|
+
out.push(child.pid);
|
|
351
|
+
queue.push({ pid: child.pid, since: child.createdAt - 1e3, until: null });
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return out;
|
|
355
|
+
}
|
|
356
|
+
function namesPathIn(commandLine, dir) {
|
|
357
|
+
if (!commandLine) return false;
|
|
358
|
+
const norm = (s) => s.replace(/\//g, "\\").toLowerCase();
|
|
359
|
+
const line = norm(commandLine);
|
|
360
|
+
const needle = norm(dir).replace(/\\+$/, "");
|
|
361
|
+
if (needle.length < 4) return false;
|
|
362
|
+
for (let at = line.indexOf(needle); at >= 0; at = line.indexOf(needle, at + 1)) {
|
|
363
|
+
const next = line[at + needle.length];
|
|
364
|
+
if (next === void 0 || next === "\\" || next === '"' || next === "'" || next === " ") {
|
|
365
|
+
return true;
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
return false;
|
|
369
|
+
}
|
|
370
|
+
function listWindowsProcesses() {
|
|
371
|
+
const script = `$ErrorActionPreference='SilentlyContinue';Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { "$($_.ProcessId) $($_.ParentProcessId) $(([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()) $($_.CommandLine -replace "[\\r\\n]", " ")" } }`;
|
|
372
|
+
return new Promise((resolve, reject) => {
|
|
373
|
+
const ps = spawn(
|
|
374
|
+
"powershell.exe",
|
|
375
|
+
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
|
|
376
|
+
{ stdio: ["ignore", "pipe", "ignore"], windowsHide: true }
|
|
377
|
+
);
|
|
378
|
+
let out = "";
|
|
379
|
+
const timer = setTimeout(() => ps.kill(), 3e4);
|
|
380
|
+
ps.stdout.setEncoding("utf8").on("data", (d) => out += d);
|
|
381
|
+
ps.on("error", (err) => {
|
|
382
|
+
clearTimeout(timer);
|
|
383
|
+
reject(err);
|
|
384
|
+
});
|
|
385
|
+
ps.on("close", () => {
|
|
386
|
+
clearTimeout(timer);
|
|
387
|
+
resolve(parseProcessRows(out));
|
|
388
|
+
});
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
function parseProcessRows(text) {
|
|
392
|
+
const rows = [];
|
|
393
|
+
for (const line of text.split(/\r?\n/)) {
|
|
394
|
+
const m = /^\s*(\d+)\s+(\d+)\s+(-?\d+)(?:\s(.*))?$/.exec(line);
|
|
395
|
+
if (!m) continue;
|
|
396
|
+
const commandLine = m[4]?.trim();
|
|
397
|
+
rows.push({
|
|
398
|
+
pid: Number(m[1]),
|
|
399
|
+
ppid: Number(m[2]),
|
|
400
|
+
createdAt: Number(m[3]),
|
|
401
|
+
...commandLine ? { commandLine } : {}
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
return rows;
|
|
405
|
+
}
|
|
406
|
+
async function taskkillTrees(pids) {
|
|
407
|
+
for (let i = 0; i < pids.length; i += 50) {
|
|
408
|
+
const args = pids.slice(i, i + 50).flatMap((p) => ["/pid", String(p)]);
|
|
409
|
+
await new Promise((resolve) => {
|
|
410
|
+
const tk = spawn("taskkill", [...args, "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
411
|
+
tk.on("error", () => resolve());
|
|
412
|
+
tk.on("close", () => resolve());
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
function signalGroup(pgid, signal) {
|
|
417
|
+
try {
|
|
418
|
+
process.kill(-pgid, signal);
|
|
419
|
+
return true;
|
|
420
|
+
} catch {
|
|
421
|
+
return false;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// src/exec.ts
|
|
180
426
|
function exec(cmd, args, opts = {}) {
|
|
181
427
|
return new Promise((resolve, reject) => {
|
|
182
|
-
const child =
|
|
428
|
+
const child = spawn2(cmd, args, {
|
|
183
429
|
cwd: opts.cwd,
|
|
184
430
|
env: opts.env ?? process.env,
|
|
185
431
|
stdio: ["pipe", "pipe", "pipe"],
|
|
186
|
-
windowsHide: true
|
|
432
|
+
windowsHide: true,
|
|
433
|
+
// A process group of its own (POSIX), so what it starts can be ended with it.
|
|
434
|
+
detached: !!opts.ownTree && OWN_PROCESS_GROUP
|
|
187
435
|
});
|
|
436
|
+
let tree = null;
|
|
437
|
+
let reaped = Promise.resolve();
|
|
438
|
+
if (opts.ownTree) {
|
|
439
|
+
child.once("spawn", () => tree = trackTree(child, opts.cwd));
|
|
440
|
+
reaped = new Promise((r) => child.once("exit", () => void reapTree(tree).then(r)));
|
|
441
|
+
}
|
|
188
442
|
let stdout = "";
|
|
189
443
|
let stderr = "";
|
|
190
444
|
let timer;
|
|
445
|
+
const kill = () => opts.ownTree ? signalTree(child, "SIGKILL") : child.kill("SIGKILL");
|
|
191
446
|
if (opts.timeoutMs) {
|
|
192
|
-
timer = setTimeout(
|
|
447
|
+
timer = setTimeout(kill, opts.timeoutMs);
|
|
193
448
|
}
|
|
194
|
-
const onAbort = () =>
|
|
449
|
+
const onAbort = () => kill();
|
|
195
450
|
if (opts.signal?.aborted) onAbort();
|
|
196
451
|
else opts.signal?.addEventListener("abort", onAbort, { once: true });
|
|
197
452
|
child.stdout.setEncoding("utf8").on("data", (d) => stdout += d);
|
|
198
453
|
child.stderr.setEncoding("utf8").on("data", (d) => stderr += d);
|
|
199
454
|
child.on("error", (err) => {
|
|
200
455
|
if (timer) clearTimeout(timer);
|
|
456
|
+
opts.signal?.removeEventListener("abort", onAbort);
|
|
201
457
|
reject(err);
|
|
202
458
|
});
|
|
203
459
|
child.on("close", (code) => {
|
|
204
460
|
if (timer) clearTimeout(timer);
|
|
205
461
|
opts.signal?.removeEventListener("abort", onAbort);
|
|
206
|
-
resolve({ code, stdout, stderr });
|
|
462
|
+
void reaped.then(() => resolve({ code, stdout, stderr }));
|
|
207
463
|
});
|
|
208
464
|
child.stdin.on("error", () => void 0);
|
|
209
465
|
child.stdin.end(opts.input ?? "");
|
|
@@ -793,14 +1049,16 @@ async function claudeFeatures(bin) {
|
|
|
793
1049
|
permissionPrompts: res.stdout.includes("--permission-prompts"),
|
|
794
1050
|
settingSources: res.stdout.includes("--setting-sources"),
|
|
795
1051
|
maxTurns: res.stdout.includes("--max-turns"),
|
|
796
|
-
strictMcpConfig: res.stdout.includes("--strict-mcp-config")
|
|
1052
|
+
strictMcpConfig: res.stdout.includes("--strict-mcp-config"),
|
|
1053
|
+
permissionPromptTool: res.stdout.includes("--permission-prompt-tool")
|
|
797
1054
|
};
|
|
798
1055
|
} catch {
|
|
799
1056
|
return {
|
|
800
1057
|
permissionPrompts: false,
|
|
801
1058
|
settingSources: false,
|
|
802
1059
|
maxTurns: false,
|
|
803
|
-
strictMcpConfig: false
|
|
1060
|
+
strictMcpConfig: false,
|
|
1061
|
+
permissionPromptTool: false
|
|
804
1062
|
};
|
|
805
1063
|
}
|
|
806
1064
|
}
|
|
@@ -855,6 +1113,9 @@ function assertValidModel(model) {
|
|
|
855
1113
|
);
|
|
856
1114
|
}
|
|
857
1115
|
}
|
|
1116
|
+
function relaysPermissions(launch) {
|
|
1117
|
+
return !!launch.relayPermissions && !!launch.features.permissionPromptTool && launch.permissionMode !== "bypassPermissions";
|
|
1118
|
+
}
|
|
858
1119
|
function claudeArgs(launch) {
|
|
859
1120
|
const args = [
|
|
860
1121
|
"-p",
|
|
@@ -870,7 +1131,11 @@ function claudeArgs(launch) {
|
|
|
870
1131
|
} else {
|
|
871
1132
|
args.push("--permission-mode", launch.permissionMode);
|
|
872
1133
|
}
|
|
873
|
-
if (launch
|
|
1134
|
+
if (relaysPermissions(launch)) {
|
|
1135
|
+
args.push("--permission-prompt-tool", "stdio");
|
|
1136
|
+
} else if (launch.features.permissionPrompts) {
|
|
1137
|
+
args.push("--permission-prompts", "none");
|
|
1138
|
+
}
|
|
874
1139
|
if (launch.features.settingSources && !launch.loadProjectSettings) {
|
|
875
1140
|
args.push("--setting-sources", "user");
|
|
876
1141
|
}
|
|
@@ -1166,6 +1431,9 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1166
1431
|
};
|
|
1167
1432
|
}
|
|
1168
1433
|
|
|
1434
|
+
// src/daemon.ts
|
|
1435
|
+
import { join as join9 } from "node:path";
|
|
1436
|
+
|
|
1169
1437
|
// src/backoff.ts
|
|
1170
1438
|
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
1171
1439
|
const ceiling = Math.min(maxMs, baseMs * 2 ** Math.min(attempt, 20));
|
|
@@ -1236,7 +1504,7 @@ async function answerCompletion(req, deps) {
|
|
|
1236
1504
|
const { bin, features } = await deps.claude();
|
|
1237
1505
|
const args = completionArgs(req, features);
|
|
1238
1506
|
cwd = await mkdtemp2(join6(tmpdir2(), "dt-runner-completion-"));
|
|
1239
|
-
const run = deps.run ?? ((b, a, o) => exec(b, a, o));
|
|
1507
|
+
const run = deps.run ?? ((b, a, o) => exec(b, a, { ...o, ownTree: true }));
|
|
1240
1508
|
const input = req.systemPrompt ? `<instructions>
|
|
1241
1509
|
${req.systemPrompt}
|
|
1242
1510
|
</instructions>
|
|
@@ -1276,6 +1544,16 @@ function readResult(res) {
|
|
|
1276
1544
|
};
|
|
1277
1545
|
}
|
|
1278
1546
|
|
|
1547
|
+
// src/heartbeat-ids.ts
|
|
1548
|
+
function reportableSessionIds(ids, onDropped = () => void 0) {
|
|
1549
|
+
const out = /* @__PURE__ */ new Set();
|
|
1550
|
+
for (const id of ids) {
|
|
1551
|
+
if (isRunnerSessionId(id)) out.add(id);
|
|
1552
|
+
else onDropped(id);
|
|
1553
|
+
}
|
|
1554
|
+
return [...out];
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1279
1557
|
// src/session-manager.ts
|
|
1280
1558
|
import { mkdir as mkdir6, rm as rm6 } from "node:fs/promises";
|
|
1281
1559
|
|
|
@@ -1530,9 +1808,394 @@ function takeBatch(pending) {
|
|
|
1530
1808
|
|
|
1531
1809
|
// src/session.ts
|
|
1532
1810
|
import { spawn as spawn3 } from "node:child_process";
|
|
1533
|
-
import {
|
|
1811
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1812
|
+
import { basename, dirname as dirname5 } from "node:path";
|
|
1534
1813
|
import { createInterface } from "node:readline";
|
|
1535
1814
|
|
|
1815
|
+
// src/permissions.ts
|
|
1816
|
+
import { randomUUID } from "node:crypto";
|
|
1817
|
+
function parseCanUseTool(line) {
|
|
1818
|
+
if (line?.type !== "control_request") return null;
|
|
1819
|
+
const req = line.request;
|
|
1820
|
+
if (!req || req.subtype !== "can_use_tool") return null;
|
|
1821
|
+
if (typeof line.request_id !== "string" || !line.request_id) return null;
|
|
1822
|
+
const toolName = typeof req.tool_name === "string" && req.tool_name ? req.tool_name : "tool";
|
|
1823
|
+
return { controlRequestId: line.request_id, toolName, input: req.input ?? {} };
|
|
1824
|
+
}
|
|
1825
|
+
function parseControlCancel(line) {
|
|
1826
|
+
if (line?.type !== "control_cancel_request") return null;
|
|
1827
|
+
return typeof line.request_id === "string" ? line.request_id : null;
|
|
1828
|
+
}
|
|
1829
|
+
function summarizeToolInput(toolName, input) {
|
|
1830
|
+
const i = input && typeof input === "object" ? input : {};
|
|
1831
|
+
const s = (v) => typeof v === "string" && v.trim() ? v : null;
|
|
1832
|
+
let summary = null;
|
|
1833
|
+
switch (toolName) {
|
|
1834
|
+
case "Bash":
|
|
1835
|
+
summary = s(i.command);
|
|
1836
|
+
break;
|
|
1837
|
+
case "WebFetch":
|
|
1838
|
+
summary = s(i.url);
|
|
1839
|
+
break;
|
|
1840
|
+
case "WebSearch":
|
|
1841
|
+
summary = s(i.query);
|
|
1842
|
+
break;
|
|
1843
|
+
case "Read":
|
|
1844
|
+
case "Edit":
|
|
1845
|
+
case "MultiEdit":
|
|
1846
|
+
case "Write":
|
|
1847
|
+
summary = s(i.file_path);
|
|
1848
|
+
break;
|
|
1849
|
+
case "NotebookEdit":
|
|
1850
|
+
summary = s(i.notebook_path);
|
|
1851
|
+
break;
|
|
1852
|
+
case "Glob":
|
|
1853
|
+
case "Grep":
|
|
1854
|
+
summary = s(i.pattern) ? `${i.pattern}${s(i.path) ? ` in ${i.path}` : ""}` : null;
|
|
1855
|
+
break;
|
|
1856
|
+
}
|
|
1857
|
+
if (summary === null) {
|
|
1858
|
+
try {
|
|
1859
|
+
summary = JSON.stringify(input) ?? "";
|
|
1860
|
+
} catch {
|
|
1861
|
+
summary = "";
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
return cut(summary, AGENT_PERMISSION_INPUT_SUMMARY_MAX_LENGTH);
|
|
1865
|
+
}
|
|
1866
|
+
function cut(text, max) {
|
|
1867
|
+
return text.length > max ? `${text.slice(0, max - 1)}\u2026` : text;
|
|
1868
|
+
}
|
|
1869
|
+
var PERMISSION_EXPIRED_TURN_ENDED = "The turn ended before anyone answered.";
|
|
1870
|
+
var PERMISSION_EXPIRED_INTERRUPTED = "The turn was interrupted before anyone answered.";
|
|
1871
|
+
var PERMISSION_EXPIRED_STOPPED = "Claude Code stopped before anyone answered.";
|
|
1872
|
+
var PERMISSION_EXPIRED_TIMEOUT = `Nobody answered within ${Math.round(
|
|
1873
|
+
RUNNER_PERMISSION_REQUEST_TIMEOUT_MS / 6e4
|
|
1874
|
+
)} minutes.`;
|
|
1875
|
+
var PERMISSION_EXPIRED_CANCELLED = "Claude Code stopped waiting for an answer.";
|
|
1876
|
+
var PERMISSION_EXPIRED_UNKNOWN = "The runner no longer has this request (it may have restarted), so the answer could not be applied.";
|
|
1877
|
+
var DENIED_MESSAGE = "The person denied permission for this tool call in Discovery Tree.";
|
|
1878
|
+
var SETTLED_KEPT = 200;
|
|
1879
|
+
var PermissionRelay = class {
|
|
1880
|
+
constructor(deps) {
|
|
1881
|
+
this.deps = deps;
|
|
1882
|
+
}
|
|
1883
|
+
pending = /* @__PURE__ */ new Map();
|
|
1884
|
+
byControlId = /* @__PURE__ */ new Map();
|
|
1885
|
+
settled = /* @__PURE__ */ new Map();
|
|
1886
|
+
get pendingCount() {
|
|
1887
|
+
return this.pending.size;
|
|
1888
|
+
}
|
|
1889
|
+
/** Claude Code asks; returns whether it was allowed at once or relayed. */
|
|
1890
|
+
request(req) {
|
|
1891
|
+
if (this.deps.alwaysAllowed().includes(req.toolName) || this.deps.grantedByRule?.(req.toolName, req.input)) {
|
|
1892
|
+
this.deps.respond(req.controlRequestId, { behavior: "allow", updatedInput: req.input });
|
|
1893
|
+
return "auto_allowed";
|
|
1894
|
+
}
|
|
1895
|
+
const id = (this.deps.newId ?? randomUUID)();
|
|
1896
|
+
const requestedAt = (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
|
|
1897
|
+
const timer = setTimeout(
|
|
1898
|
+
() => this.expire(id, PERMISSION_EXPIRED_TIMEOUT, true),
|
|
1899
|
+
this.deps.timeoutMs ?? RUNNER_PERMISSION_REQUEST_TIMEOUT_MS
|
|
1900
|
+
);
|
|
1901
|
+
timer.unref?.();
|
|
1902
|
+
const pending = {
|
|
1903
|
+
id,
|
|
1904
|
+
controlRequestId: req.controlRequestId,
|
|
1905
|
+
toolName: req.toolName,
|
|
1906
|
+
input: req.input,
|
|
1907
|
+
inputSummary: summarizeToolInput(req.toolName, req.input),
|
|
1908
|
+
requestedAt,
|
|
1909
|
+
timer
|
|
1910
|
+
};
|
|
1911
|
+
this.pending.set(id, pending);
|
|
1912
|
+
this.byControlId.set(req.controlRequestId, id);
|
|
1913
|
+
const suggestedRule = this.deps.suggestRule?.(req.toolName, req.input) ?? null;
|
|
1914
|
+
this.deps.emit({
|
|
1915
|
+
type: "permission_request",
|
|
1916
|
+
request: {
|
|
1917
|
+
id,
|
|
1918
|
+
toolName: pending.toolName,
|
|
1919
|
+
inputSummary: pending.inputSummary,
|
|
1920
|
+
...suggestedRule ? { suggestedRule } : {},
|
|
1921
|
+
requestedAt,
|
|
1922
|
+
status: "pending"
|
|
1923
|
+
}
|
|
1924
|
+
});
|
|
1925
|
+
return "relayed";
|
|
1926
|
+
}
|
|
1927
|
+
/** A person's decision, from the server. */
|
|
1928
|
+
decide(requestId, decision) {
|
|
1929
|
+
const pending = this.pending.get(requestId);
|
|
1930
|
+
if (!pending) {
|
|
1931
|
+
const settled = this.settled.get(requestId);
|
|
1932
|
+
if (settled === "decided") return "already_applied";
|
|
1933
|
+
if (settled === void 0) {
|
|
1934
|
+
this.settle(requestId, "expired");
|
|
1935
|
+
this.deps.emit({
|
|
1936
|
+
type: "permission_request",
|
|
1937
|
+
request: {
|
|
1938
|
+
id: requestId,
|
|
1939
|
+
toolName: "tool",
|
|
1940
|
+
inputSummary: "",
|
|
1941
|
+
requestedAt: (this.deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString(),
|
|
1942
|
+
status: "expired",
|
|
1943
|
+
expiredReason: PERMISSION_EXPIRED_UNKNOWN
|
|
1944
|
+
}
|
|
1945
|
+
});
|
|
1946
|
+
}
|
|
1947
|
+
return "not_pending";
|
|
1948
|
+
}
|
|
1949
|
+
this.forget(pending);
|
|
1950
|
+
this.settle(requestId, "decided");
|
|
1951
|
+
if (decision.behavior === "allow") {
|
|
1952
|
+
if (decision.alwaysAllowTool && !this.deps.alwaysAllowed().includes(pending.toolName)) {
|
|
1953
|
+
this.deps.rememberAlwaysAllowed(pending.toolName);
|
|
1954
|
+
}
|
|
1955
|
+
const rule = decision.alwaysAllowRule?.trim();
|
|
1956
|
+
if (rule && toolGrantRuleProblem(rule) === null) this.deps.rememberRule?.(rule);
|
|
1957
|
+
this.deps.respond(pending.controlRequestId, {
|
|
1958
|
+
behavior: "allow",
|
|
1959
|
+
updatedInput: pending.input
|
|
1960
|
+
});
|
|
1961
|
+
} else {
|
|
1962
|
+
const message = decision.message?.trim();
|
|
1963
|
+
this.deps.respond(pending.controlRequestId, {
|
|
1964
|
+
behavior: "deny",
|
|
1965
|
+
message: message ? `${DENIED_MESSAGE} Their message: ${cut(message, AGENT_PERMISSION_MESSAGE_MAX_LENGTH)}` : DENIED_MESSAGE
|
|
1966
|
+
});
|
|
1967
|
+
}
|
|
1968
|
+
return "applied";
|
|
1969
|
+
}
|
|
1970
|
+
/** Claude Code withdrew a request (it stopped waiting): expired, nothing to answer. */
|
|
1971
|
+
cancel(controlRequestId) {
|
|
1972
|
+
const id = this.byControlId.get(controlRequestId);
|
|
1973
|
+
if (id) this.expire(id, PERMISSION_EXPIRED_CANCELLED, false);
|
|
1974
|
+
}
|
|
1975
|
+
/** Expire everything still waiting, answering Claude Code with a denial. */
|
|
1976
|
+
expireAll(reason) {
|
|
1977
|
+
for (const id of [...this.pending.keys()]) this.expire(id, reason, true);
|
|
1978
|
+
}
|
|
1979
|
+
expire(id, reason, answerClaude) {
|
|
1980
|
+
const pending = this.pending.get(id);
|
|
1981
|
+
if (!pending) return;
|
|
1982
|
+
this.forget(pending);
|
|
1983
|
+
this.settle(id, "expired");
|
|
1984
|
+
if (answerClaude) {
|
|
1985
|
+
this.deps.respond(pending.controlRequestId, {
|
|
1986
|
+
behavior: "deny",
|
|
1987
|
+
message: `Permission for this tool call was not granted: ${reason}`
|
|
1988
|
+
});
|
|
1989
|
+
}
|
|
1990
|
+
this.deps.emit({
|
|
1991
|
+
type: "permission_request",
|
|
1992
|
+
request: {
|
|
1993
|
+
id,
|
|
1994
|
+
toolName: pending.toolName,
|
|
1995
|
+
inputSummary: pending.inputSummary,
|
|
1996
|
+
requestedAt: pending.requestedAt,
|
|
1997
|
+
status: "expired",
|
|
1998
|
+
expiredReason: reason
|
|
1999
|
+
}
|
|
2000
|
+
});
|
|
2001
|
+
}
|
|
2002
|
+
forget(pending) {
|
|
2003
|
+
clearTimeout(pending.timer);
|
|
2004
|
+
this.pending.delete(pending.id);
|
|
2005
|
+
this.byControlId.delete(pending.controlRequestId);
|
|
2006
|
+
}
|
|
2007
|
+
settle(id, how) {
|
|
2008
|
+
this.settled.set(id, how);
|
|
2009
|
+
while (this.settled.size > SETTLED_KEPT) {
|
|
2010
|
+
this.settled.delete(this.settled.keys().next().value);
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
};
|
|
2014
|
+
|
|
2015
|
+
// src/tool-grants.ts
|
|
2016
|
+
import { dirname as dirname4, join as join7 } from "node:path";
|
|
2017
|
+
var isGrantableDenial = isGrantableToolDenial;
|
|
2018
|
+
var FILE_TOOLS = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
2019
|
+
var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
2020
|
+
function suggestRules(toolName, input, allowedTools = []) {
|
|
2021
|
+
const i = input && typeof input === "object" ? input : {};
|
|
2022
|
+
const str = (v) => typeof v === "string" && v.trim() ? v.trim() : null;
|
|
2023
|
+
let out = null;
|
|
2024
|
+
if (toolName === "Bash") {
|
|
2025
|
+
const command = str(i.command);
|
|
2026
|
+
if (command) out = bashRules(command, allowedTools);
|
|
2027
|
+
} else if (toolName === "WebFetch") {
|
|
2028
|
+
const host = hostOf(str(i.url));
|
|
2029
|
+
if (host) out = same(`WebFetch(domain:${host})`);
|
|
2030
|
+
} else if (FILE_TOOLS.has(toolName)) {
|
|
2031
|
+
const file = str(i.file_path) ?? str(i.notebook_path);
|
|
2032
|
+
const ruleTool = EDIT_TOOLS.has(toolName) ? "Edit" : "Read";
|
|
2033
|
+
if (file) {
|
|
2034
|
+
const path = rulePath(file);
|
|
2035
|
+
const dir = path.replace(/\/[^/]*$/, "");
|
|
2036
|
+
out = {
|
|
2037
|
+
suggestedRule: dir && dir !== "/" && dir !== "//" ? `${ruleTool}(${dir}/**)` : `${ruleTool}(${path})`,
|
|
2038
|
+
onceRule: `${ruleTool}(${path})`
|
|
2039
|
+
};
|
|
2040
|
+
}
|
|
2041
|
+
} else {
|
|
2042
|
+
out = same(toolName);
|
|
2043
|
+
}
|
|
2044
|
+
if (!out) return null;
|
|
2045
|
+
const onceOk = toolGrantRuleProblem(out.onceRule) === null;
|
|
2046
|
+
const suggestedOk = toolGrantRuleProblem(out.suggestedRule) === null;
|
|
2047
|
+
if (!onceOk && !suggestedOk) return null;
|
|
2048
|
+
return {
|
|
2049
|
+
suggestedRule: suggestedOk ? out.suggestedRule : out.onceRule,
|
|
2050
|
+
onceRule: onceOk ? out.onceRule : out.suggestedRule
|
|
2051
|
+
};
|
|
2052
|
+
}
|
|
2053
|
+
function same(rule) {
|
|
2054
|
+
return { suggestedRule: rule, onceRule: rule };
|
|
2055
|
+
}
|
|
2056
|
+
function shellSegments(command) {
|
|
2057
|
+
return command.split(/\s*(?:&&|\|\||;|\||\n)\s*/).map((s) => s.trim()).filter(Boolean);
|
|
2058
|
+
}
|
|
2059
|
+
var WORD = /^[A-Za-z][\w:.@/-]*$/;
|
|
2060
|
+
var RUNNER_WORDS = /* @__PURE__ */ new Set(["run", "exec", "x", "dlx"]);
|
|
2061
|
+
function bashRules(command, allowedTools) {
|
|
2062
|
+
const segments = shellSegments(command);
|
|
2063
|
+
const segment = segments.find((s) => !allowedTools.some((rule) => ruleAllows(rule, "Bash", { command: s }))) ?? segments[0];
|
|
2064
|
+
if (!segment) return null;
|
|
2065
|
+
const words = segment.split(/\s+/);
|
|
2066
|
+
let at = 0;
|
|
2067
|
+
while (at < words.length - 1 && /^[A-Za-z_]\w*=/.test(words[at])) at++;
|
|
2068
|
+
const w = words.slice(at);
|
|
2069
|
+
const head = [w[0]];
|
|
2070
|
+
if (w[1] && WORD.test(w[1]) && !w[1].includes("/")) {
|
|
2071
|
+
head.push(w[1]);
|
|
2072
|
+
if (RUNNER_WORDS.has(w[1]) && w[2] && WORD.test(w[2]) && !w[2].includes("/")) head.push(w[2]);
|
|
2073
|
+
}
|
|
2074
|
+
const once = segment.length <= 400 ? `Bash(${segment})` : `Bash(${head.join(" ")} *)`;
|
|
2075
|
+
return { suggestedRule: `Bash(${head.join(" ")} *)`, onceRule: once };
|
|
2076
|
+
}
|
|
2077
|
+
function hostOf(url) {
|
|
2078
|
+
if (!url) return null;
|
|
2079
|
+
try {
|
|
2080
|
+
const host = new URL(url).hostname.toLowerCase();
|
|
2081
|
+
return /^[a-z0-9.-]+$/.test(host) ? host : null;
|
|
2082
|
+
} catch {
|
|
2083
|
+
return null;
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
function rulePath(path) {
|
|
2087
|
+
const win = /^([A-Za-z]):[\\/](.*)$/.exec(path);
|
|
2088
|
+
if (win) return `//${win[1].toLowerCase()}/${win[2].replace(/\\/g, "/")}`;
|
|
2089
|
+
if (path.startsWith("/")) return `/${path}`;
|
|
2090
|
+
return path;
|
|
2091
|
+
}
|
|
2092
|
+
function parseRule(rule) {
|
|
2093
|
+
const m = /^([A-Za-z][A-Za-z0-9_.-]*)(?:\(([\s\S]*)\))?$/.exec(rule.trim());
|
|
2094
|
+
return m ? { tool: m[1], spec: m[2] ?? null } : null;
|
|
2095
|
+
}
|
|
2096
|
+
function ruleAllows(rule, toolName, input) {
|
|
2097
|
+
const parsed = parseRule(rule);
|
|
2098
|
+
if (!parsed) return false;
|
|
2099
|
+
const ruleTool = parsed.tool === "Edit" && EDIT_TOOLS.has(toolName) ? toolName : parsed.tool;
|
|
2100
|
+
if (ruleTool !== toolName) return false;
|
|
2101
|
+
const i = input && typeof input === "object" ? input : {};
|
|
2102
|
+
if (parsed.spec === null) return toolName !== "Bash";
|
|
2103
|
+
if (toolName === "Bash") {
|
|
2104
|
+
const command = typeof i.command === "string" ? i.command.trim() : "";
|
|
2105
|
+
const segments = shellSegments(command);
|
|
2106
|
+
return segments.length > 0 && segments.every((s) => shellPatternMatches(parsed.spec, s));
|
|
2107
|
+
}
|
|
2108
|
+
if (toolName === "WebFetch" && parsed.spec.startsWith("domain:")) {
|
|
2109
|
+
return hostOf(typeof i.url === "string" ? i.url : null) === parsed.spec.slice(7).toLowerCase();
|
|
2110
|
+
}
|
|
2111
|
+
return false;
|
|
2112
|
+
}
|
|
2113
|
+
function shellPatternMatches(spec, command) {
|
|
2114
|
+
let pattern = spec.trim();
|
|
2115
|
+
if (pattern.endsWith(":*")) pattern = `${pattern.slice(0, -2)} *`;
|
|
2116
|
+
const optionalTail = pattern.endsWith(" *");
|
|
2117
|
+
const body = optionalTail ? pattern.slice(0, -2) : pattern;
|
|
2118
|
+
const re = body.split("*").map((part) => part.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join(".*");
|
|
2119
|
+
return new RegExp(`^${re}${optionalTail ? "(?: .*)?" : ""}$`, "s").test(command);
|
|
2120
|
+
}
|
|
2121
|
+
function toolGrantsFile(configFile) {
|
|
2122
|
+
return join7(dirname4(configFile), "tool-grants.json");
|
|
2123
|
+
}
|
|
2124
|
+
var ToolGrantStore = class {
|
|
2125
|
+
constructor(file) {
|
|
2126
|
+
this.file = file;
|
|
2127
|
+
}
|
|
2128
|
+
cache = null;
|
|
2129
|
+
chain = Promise.resolve();
|
|
2130
|
+
async list() {
|
|
2131
|
+
if (!this.cache) {
|
|
2132
|
+
const stored = await readJson(this.file);
|
|
2133
|
+
this.cache = Array.isArray(stored?.grants) ? stored.grants.filter(isUsableGrant) : [];
|
|
2134
|
+
}
|
|
2135
|
+
return [...this.cache];
|
|
2136
|
+
}
|
|
2137
|
+
/** The rules saved for a repository URL; none for a session without a repository. */
|
|
2138
|
+
async rulesFor(repositoryUrl) {
|
|
2139
|
+
const key = toolGrantRepositoryKey(repositoryUrl);
|
|
2140
|
+
if (!key) return [];
|
|
2141
|
+
return [...new Set((await this.list()).filter((g) => g.repository === key).map((g) => g.rule))];
|
|
2142
|
+
}
|
|
2143
|
+
/** Saves a rule; a grant id already held is a no-op. Throws when the rule is refused. */
|
|
2144
|
+
add(grant) {
|
|
2145
|
+
return this.change(async (grants) => {
|
|
2146
|
+
const problem = toolGrantRuleProblem(grant.rule);
|
|
2147
|
+
if (problem) throw new Error(problem);
|
|
2148
|
+
if (!toolGrantRepositoryKey(`https://github.com/${grant.repository}`)) {
|
|
2149
|
+
throw new Error(`"${grant.repository}" is not a repository.`);
|
|
2150
|
+
}
|
|
2151
|
+
if (grants.some((g) => g.id === grant.id)) return grants;
|
|
2152
|
+
const next = grants.filter(
|
|
2153
|
+
(g) => !(g.repository === grant.repository && g.rule === grant.rule.trim())
|
|
2154
|
+
);
|
|
2155
|
+
next.push({ ...grant, rule: grant.rule.trim(), repository: grant.repository.toLowerCase() });
|
|
2156
|
+
return next.slice(-RUNNER_TOOL_GRANTS_MAX);
|
|
2157
|
+
});
|
|
2158
|
+
}
|
|
2159
|
+
/** Removes a rule; true when it was there. */
|
|
2160
|
+
async revoke(id) {
|
|
2161
|
+
let removed = false;
|
|
2162
|
+
await this.change(async (grants) => {
|
|
2163
|
+
const next = grants.filter((g) => g.id !== id);
|
|
2164
|
+
removed = next.length !== grants.length;
|
|
2165
|
+
return next;
|
|
2166
|
+
});
|
|
2167
|
+
return removed;
|
|
2168
|
+
}
|
|
2169
|
+
/** Applies the changes a heartbeat answer handed over; each failure is returned, not thrown. */
|
|
2170
|
+
async apply(changes) {
|
|
2171
|
+
const problems = [];
|
|
2172
|
+
for (const c of changes) {
|
|
2173
|
+
try {
|
|
2174
|
+
if (c?.op === "add" && c.grant) await this.add(c.grant);
|
|
2175
|
+
else if (c?.op === "revoke" && typeof c.id === "string") await this.revoke(c.id);
|
|
2176
|
+
} catch (err) {
|
|
2177
|
+
problems.push(err.message);
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
return problems;
|
|
2181
|
+
}
|
|
2182
|
+
change(fn) {
|
|
2183
|
+
const run = this.chain.then(async () => {
|
|
2184
|
+
const current = await this.list();
|
|
2185
|
+
const next = await fn(current);
|
|
2186
|
+
if (next === current) return;
|
|
2187
|
+
await writeJsonAtomic(this.file, { version: 1, grants: next });
|
|
2188
|
+
this.cache = next;
|
|
2189
|
+
});
|
|
2190
|
+
this.chain = run.catch(() => void 0);
|
|
2191
|
+
return run;
|
|
2192
|
+
}
|
|
2193
|
+
};
|
|
2194
|
+
function isUsableGrant(g) {
|
|
2195
|
+
const x = g;
|
|
2196
|
+
return !!x && typeof x.id === "string" && typeof x.repository === "string" && typeof x.rule === "string" && toolGrantRuleProblem(x.rule) === null;
|
|
2197
|
+
}
|
|
2198
|
+
|
|
1536
2199
|
// src/pull-request.ts
|
|
1537
2200
|
var PULL_REQUEST_BODY_MAX_CHARS = 6e4;
|
|
1538
2201
|
var GH_TIMEOUT_MS = 6e4;
|
|
@@ -1621,94 +2284,31 @@ function ghError(command, res) {
|
|
|
1621
2284
|
return scrubSecrets(`gh ${command} failed${detail ? `: ${detail}` : ""}`).slice(0, 300);
|
|
1622
2285
|
}
|
|
1623
2286
|
|
|
1624
|
-
// src/process-tree.ts
|
|
1625
|
-
import { spawn as spawn2 } from "node:child_process";
|
|
1626
|
-
var OWN_PROCESS_GROUP = process.platform !== "win32";
|
|
1627
|
-
var liveGroups = /* @__PURE__ */ new Set();
|
|
1628
|
-
var exitHookInstalled = false;
|
|
1629
|
-
function trackGroup(child) {
|
|
1630
|
-
if (!OWN_PROCESS_GROUP || !child.pid) return;
|
|
1631
|
-
liveGroups.add(child.pid);
|
|
1632
|
-
if (!exitHookInstalled) {
|
|
1633
|
-
exitHookInstalled = true;
|
|
1634
|
-
process.once("exit", () => {
|
|
1635
|
-
for (const pgid of liveGroups) signalGroup(pgid, "SIGKILL");
|
|
1636
|
-
});
|
|
1637
|
-
}
|
|
1638
|
-
}
|
|
1639
|
-
function signalTree(child, signal) {
|
|
1640
|
-
if (!child.pid) return;
|
|
1641
|
-
if (OWN_PROCESS_GROUP) {
|
|
1642
|
-
if (!signalGroup(child.pid, signal)) child.kill(signal);
|
|
1643
|
-
return;
|
|
1644
|
-
}
|
|
1645
|
-
if (signal === "SIGKILL") {
|
|
1646
|
-
const tk = spawn2("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
1647
|
-
stdio: "ignore",
|
|
1648
|
-
windowsHide: true
|
|
1649
|
-
});
|
|
1650
|
-
let fellBack = false;
|
|
1651
|
-
const fallBack = () => {
|
|
1652
|
-
if (fellBack) return;
|
|
1653
|
-
fellBack = true;
|
|
1654
|
-
child.kill(signal);
|
|
1655
|
-
};
|
|
1656
|
-
tk.on("error", fallBack);
|
|
1657
|
-
tk.on("exit", (code) => {
|
|
1658
|
-
if (code !== 0) fallBack();
|
|
1659
|
-
});
|
|
1660
|
-
return;
|
|
1661
|
-
}
|
|
1662
|
-
child.kill(signal);
|
|
1663
|
-
}
|
|
1664
|
-
async function reapGroup(pgid, graceMs = 2e3) {
|
|
1665
|
-
if (!OWN_PROCESS_GROUP || !pgid) return;
|
|
1666
|
-
try {
|
|
1667
|
-
if (!signalGroup(pgid, "SIGTERM")) return;
|
|
1668
|
-
const deadline = Date.now() + graceMs;
|
|
1669
|
-
while (Date.now() < deadline) {
|
|
1670
|
-
await new Promise((r) => setTimeout(r, 50));
|
|
1671
|
-
if (!signalGroup(pgid, 0)) return;
|
|
1672
|
-
}
|
|
1673
|
-
signalGroup(pgid, "SIGKILL");
|
|
1674
|
-
} finally {
|
|
1675
|
-
liveGroups.delete(pgid);
|
|
1676
|
-
}
|
|
1677
|
-
}
|
|
1678
|
-
function signalGroup(pgid, signal) {
|
|
1679
|
-
try {
|
|
1680
|
-
process.kill(-pgid, signal);
|
|
1681
|
-
return true;
|
|
1682
|
-
} catch {
|
|
1683
|
-
return false;
|
|
1684
|
-
}
|
|
1685
|
-
}
|
|
1686
|
-
|
|
1687
2287
|
// src/session-store.ts
|
|
1688
2288
|
import { mkdir as mkdir5, readdir as readdir2, rm as rm5 } from "node:fs/promises";
|
|
1689
|
-
import { join as
|
|
2289
|
+
import { join as join8 } from "node:path";
|
|
1690
2290
|
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
1691
2291
|
var SessionStore = class {
|
|
1692
2292
|
constructor(stateDir) {
|
|
1693
2293
|
this.stateDir = stateDir;
|
|
1694
2294
|
}
|
|
1695
2295
|
dir(sessionId) {
|
|
1696
|
-
return
|
|
2296
|
+
return join8(this.stateDir, "sessions", sessionId);
|
|
1697
2297
|
}
|
|
1698
2298
|
outboxFile(sessionId) {
|
|
1699
|
-
return
|
|
2299
|
+
return join8(this.dir(sessionId), "outbox.json");
|
|
1700
2300
|
}
|
|
1701
2301
|
async save(record) {
|
|
1702
2302
|
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1703
|
-
await writeJsonAtomic(
|
|
2303
|
+
await writeJsonAtomic(join8(this.dir(record.sessionId), "session.json"), record);
|
|
1704
2304
|
}
|
|
1705
2305
|
async list() {
|
|
1706
|
-
const root =
|
|
2306
|
+
const root = join8(this.stateDir, "sessions");
|
|
1707
2307
|
await mkdir5(root, { recursive: true });
|
|
1708
2308
|
const out = [];
|
|
1709
2309
|
for (const entry of await readdir2(root, { withFileTypes: true })) {
|
|
1710
2310
|
if (!entry.isDirectory()) continue;
|
|
1711
|
-
const rec = await readJson(
|
|
2311
|
+
const rec = await readJson(join8(root, entry.name, "session.json"));
|
|
1712
2312
|
if (rec?.sessionId === entry.name) out.push(rec);
|
|
1713
2313
|
}
|
|
1714
2314
|
return out;
|
|
@@ -1718,7 +2318,7 @@ var SessionStore = class {
|
|
|
1718
2318
|
}
|
|
1719
2319
|
/** Scratch working directory for a session without a repository. */
|
|
1720
2320
|
scratchDir(sessionId) {
|
|
1721
|
-
return
|
|
2321
|
+
return join8(this.stateDir, "scratch", sessionId);
|
|
1722
2322
|
}
|
|
1723
2323
|
};
|
|
1724
2324
|
function assertSafeSessionId(id) {
|
|
@@ -1776,6 +2376,12 @@ var ClaudeStreamMapper = class {
|
|
|
1776
2376
|
isError: line.is_error === true || (line.subtype ?? "success") !== "success",
|
|
1777
2377
|
subtype: typeof line.subtype === "string" ? line.subtype : null
|
|
1778
2378
|
};
|
|
2379
|
+
const denials = Array.isArray(line.permission_denials) ? line.permission_denials.filter((d) => d && typeof d.tool_name === "string").map((d) => ({
|
|
2380
|
+
callId: typeof d.tool_use_id === "string" ? d.tool_use_id : null,
|
|
2381
|
+
name: d.tool_name,
|
|
2382
|
+
input: d.tool_input ?? {}
|
|
2383
|
+
})) : [];
|
|
2384
|
+
if (denials.length) out.turnEnd.permissionDenials = denials;
|
|
1779
2385
|
this.endTurn();
|
|
1780
2386
|
break;
|
|
1781
2387
|
}
|
|
@@ -1901,7 +2507,16 @@ var ClaudeStreamMapper = class {
|
|
|
1901
2507
|
for (const block of content) {
|
|
1902
2508
|
if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
|
|
1903
2509
|
const known = this.calls.get(block.tool_use_id);
|
|
1904
|
-
const
|
|
2510
|
+
const full = toolResultText(block.content);
|
|
2511
|
+
const { text, truncated } = capText(full);
|
|
2512
|
+
if (block.is_error) {
|
|
2513
|
+
(out.failedTools ??= []).push({
|
|
2514
|
+
callId: block.tool_use_id,
|
|
2515
|
+
name: known?.name ?? "tool",
|
|
2516
|
+
input: known?.input ?? {},
|
|
2517
|
+
text: full
|
|
2518
|
+
});
|
|
2519
|
+
}
|
|
1905
2520
|
const tool = {
|
|
1906
2521
|
callId: block.tool_use_id,
|
|
1907
2522
|
name: known?.name ?? "tool",
|
|
@@ -1939,10 +2554,33 @@ function toolResultText(content) {
|
|
|
1939
2554
|
}
|
|
1940
2555
|
|
|
1941
2556
|
// src/session.ts
|
|
2557
|
+
var DENIALS_KEPT = 200;
|
|
1942
2558
|
var AgentSession = class {
|
|
1943
2559
|
constructor(record, deps) {
|
|
1944
2560
|
this.record = record;
|
|
1945
2561
|
this.deps = deps;
|
|
2562
|
+
this.permissions = new PermissionRelay({
|
|
2563
|
+
respond: (controlRequestId, response) => this.answerPermission(controlRequestId, response),
|
|
2564
|
+
emit: (event) => this.emit(event),
|
|
2565
|
+
alwaysAllowed: () => this.record.alwaysAllowedTools ?? [],
|
|
2566
|
+
rememberAlwaysAllowed: (tool) => {
|
|
2567
|
+
this.record.alwaysAllowedTools = [...this.record.alwaysAllowedTools ?? [], tool];
|
|
2568
|
+
void this.deps.store.save(this.record).catch(() => void 0);
|
|
2569
|
+
},
|
|
2570
|
+
grantedByRule: (tool, input) => [...this.record.grantRules ?? [], ...this.savedRulesNow].some(
|
|
2571
|
+
(rule) => ruleAllows(rule, tool, input)
|
|
2572
|
+
),
|
|
2573
|
+
// Only with a repository to save a rule for.
|
|
2574
|
+
suggestRule: (tool, input) => toolGrantRepositoryKey(this.record.repository) ? suggestRules(tool, input, this.deps.allowedTools)?.suggestedRule ?? null : null,
|
|
2575
|
+
rememberRule: (rule) => {
|
|
2576
|
+
const rules = this.record.grantRules ??= [];
|
|
2577
|
+
if (rules.includes(rule)) return;
|
|
2578
|
+
rules.push(rule);
|
|
2579
|
+
void this.deps.store.save(this.record).catch(() => void 0);
|
|
2580
|
+
this.deps.logger.info(`session ${this.sessionId}: allowed ${rule} for this repository`);
|
|
2581
|
+
},
|
|
2582
|
+
timeoutMs: deps.permissionTimeoutMs
|
|
2583
|
+
});
|
|
1946
2584
|
}
|
|
1947
2585
|
child = null;
|
|
1948
2586
|
mapper = new ClaudeStreamMapper();
|
|
@@ -1971,11 +2609,177 @@ var AgentSession = class {
|
|
|
1971
2609
|
*/
|
|
1972
2610
|
resumeDoomed = false;
|
|
1973
2611
|
exitWaiters = [];
|
|
1974
|
-
/** Settles once the current process has exited and what it left in its
|
|
1975
|
-
|
|
2612
|
+
/** Settles once the current process has exited and what it left in its tree is gone. */
|
|
2613
|
+
treeReaped = Promise.resolve();
|
|
1976
2614
|
/** How long what is left in the group gets after SIGTERM: a stop's grace, or the default. */
|
|
1977
2615
|
reapGraceMs;
|
|
1978
2616
|
lastActivity = Date.now();
|
|
2617
|
+
/** Permission prompts waiting on a person (sessions with `relayPermissionRequests`). */
|
|
2618
|
+
permissions;
|
|
2619
|
+
/** Denials reported, by id, so a grant's outcome can be reported on the same row. */
|
|
2620
|
+
denials = /* @__PURE__ */ new Map();
|
|
2621
|
+
/** Tool calls already reported as denied, or whose failed result was already looked at. */
|
|
2622
|
+
seenFailedCalls = /* @__PURE__ */ new Set();
|
|
2623
|
+
/**
|
|
2624
|
+
* A rule was granted mid-turn that the running Claude Code cannot pick up (it does not
|
|
2625
|
+
* relay prompts): once the turn ends the process is restarted with it, and the messages
|
|
2626
|
+
* that arrived meanwhile (the person's "retry") are sent then rather than to the old one.
|
|
2627
|
+
*/
|
|
2628
|
+
restartAfterTurn = false;
|
|
2629
|
+
deferredMessages = [];
|
|
2630
|
+
/** The repository's saved rules, read again before each relayed prompt. */
|
|
2631
|
+
savedRulesNow = [];
|
|
2632
|
+
/** The repository's saved rules, as the store holds them now; the last read if it fails. */
|
|
2633
|
+
async readSavedRules() {
|
|
2634
|
+
try {
|
|
2635
|
+
return await this.deps.savedRules?.(this.record.repository) ?? [];
|
|
2636
|
+
} catch {
|
|
2637
|
+
return this.savedRulesNow;
|
|
2638
|
+
}
|
|
2639
|
+
}
|
|
2640
|
+
/**
|
|
2641
|
+
* Carries out a grant a person made on one of this session's denials: the rule joins the
|
|
2642
|
+
* session's allowed tools (a rule saved for the repository was saved by the caller), and
|
|
2643
|
+
* Claude Code gets it as soon as it can — at once when the session relays prompts, else by
|
|
2644
|
+
* restarting the process with it (`--resume` keeps the conversation): now when no turn is
|
|
2645
|
+
* running, or when the current one ends. Reports the outcome on the denial's row.
|
|
2646
|
+
*/
|
|
2647
|
+
async grantTool(denialId, scope, rule) {
|
|
2648
|
+
const rules = this.record.grantRules ??= [];
|
|
2649
|
+
if (!rules.includes(rule)) rules.push(rule);
|
|
2650
|
+
await this.deps.store.save(this.record);
|
|
2651
|
+
const saved = scope === "always" ? "Saved on your runner for this repository, and allowed" : "Allowed";
|
|
2652
|
+
let outcome;
|
|
2653
|
+
if (!this.child) {
|
|
2654
|
+
outcome = `${saved} from the agent\u2019s next turn.`;
|
|
2655
|
+
} else if (!this.record.turnActive) {
|
|
2656
|
+
await this.stop("idle");
|
|
2657
|
+
outcome = `${saved} from the agent\u2019s next turn.`;
|
|
2658
|
+
} else if (this.record.relayPermissionRequests) {
|
|
2659
|
+
outcome = `${saved} now: the agent may use it in this turn.`;
|
|
2660
|
+
} else {
|
|
2661
|
+
this.restartAfterTurn = true;
|
|
2662
|
+
outcome = `${saved}. Claude Code cannot change its permissions in the middle of a turn, so it takes effect when this turn ends.`;
|
|
2663
|
+
}
|
|
2664
|
+
this.deps.logger.info(`session ${this.sessionId}: granted ${rule} (${scope})`);
|
|
2665
|
+
const denial = this.denials.get(denialId);
|
|
2666
|
+
if (denial) this.emit({ type: "tool_denied", denial: { ...denial, outcome } });
|
|
2667
|
+
return outcome;
|
|
2668
|
+
}
|
|
2669
|
+
/**
|
|
2670
|
+
* Reports a tool call that was denied because nobody could answer for it, with the rules
|
|
2671
|
+
* a person could grant. Each call once; nothing for sessions not asked to report them.
|
|
2672
|
+
*/
|
|
2673
|
+
reportDenial(callId, toolName, input) {
|
|
2674
|
+
if (!this.record.reportToolDenials) return;
|
|
2675
|
+
if (callId) {
|
|
2676
|
+
if (this.seenFailedCalls.size > 1e3) this.seenFailedCalls.clear();
|
|
2677
|
+
this.seenFailedCalls.add(callId);
|
|
2678
|
+
}
|
|
2679
|
+
const rules = suggestRules(toolName, input, this.deps.allowedTools);
|
|
2680
|
+
if (!rules) return;
|
|
2681
|
+
const denial = {
|
|
2682
|
+
id: randomUUID2(),
|
|
2683
|
+
toolName,
|
|
2684
|
+
inputSummary: summarizeToolInput(toolName, input),
|
|
2685
|
+
...rules,
|
|
2686
|
+
deniedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
2687
|
+
};
|
|
2688
|
+
this.denials.set(denial.id, denial);
|
|
2689
|
+
if (this.denials.size > DENIALS_KEPT) {
|
|
2690
|
+
this.denials.delete(this.denials.keys().next().value);
|
|
2691
|
+
}
|
|
2692
|
+
this.deps.logger.info(
|
|
2693
|
+
`session ${this.sessionId}: ${toolName} was denied; Discovery Tree offers ${rules.suggestedRule}`
|
|
2694
|
+
);
|
|
2695
|
+
this.emit({ type: "tool_denied", denial });
|
|
2696
|
+
}
|
|
2697
|
+
/** Failed tool results that are denials a grant could fix. */
|
|
2698
|
+
reportFailedTools(failed) {
|
|
2699
|
+
for (const f of failed) {
|
|
2700
|
+
if (this.seenFailedCalls.has(f.callId)) continue;
|
|
2701
|
+
if (isGrantableDenial(f.text)) this.reportDenial(f.callId, f.name, f.input);
|
|
2702
|
+
else this.seenFailedCalls.add(f.callId);
|
|
2703
|
+
}
|
|
2704
|
+
}
|
|
2705
|
+
/** Restarts Claude Code with the rules granted mid-turn, then sends what waited for it. */
|
|
2706
|
+
async restartWithGrants() {
|
|
2707
|
+
const texts = this.deferredMessages.splice(0);
|
|
2708
|
+
try {
|
|
2709
|
+
await this.stop("idle");
|
|
2710
|
+
if (texts.length) await this.beginTurn(texts.join("\n\n"));
|
|
2711
|
+
} catch (err) {
|
|
2712
|
+
this.emit(
|
|
2713
|
+
{
|
|
2714
|
+
type: "error",
|
|
2715
|
+
message: `Claude Code could not be started again with the permission you granted: ${err.message}`,
|
|
2716
|
+
retryable: true
|
|
2717
|
+
},
|
|
2718
|
+
{ type: "result", status: "failed", text: null }
|
|
2719
|
+
);
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
/**
|
|
2723
|
+
* Carries out a person's decision on one of this session's permission requests. Not on
|
|
2724
|
+
* the line chain: the turn is blocked on the tool, waiting for exactly this.
|
|
2725
|
+
*/
|
|
2726
|
+
decidePermission(requestId, decision) {
|
|
2727
|
+
const outcome = this.permissions.decide(requestId, decision);
|
|
2728
|
+
if (outcome === "applied") {
|
|
2729
|
+
this.lastActivity = Date.now();
|
|
2730
|
+
this.deps.logger.info(
|
|
2731
|
+
`session ${this.sessionId}: permission request ${requestId} ${decision.behavior === "allow" ? "allowed" : "denied"}`
|
|
2732
|
+
);
|
|
2733
|
+
}
|
|
2734
|
+
return outcome;
|
|
2735
|
+
}
|
|
2736
|
+
/** Claude Code's answer to a `can_use_tool`; dropped when the process is already gone. */
|
|
2737
|
+
answerPermission(controlRequestId, response) {
|
|
2738
|
+
try {
|
|
2739
|
+
this.write({
|
|
2740
|
+
type: "control_response",
|
|
2741
|
+
response: { subtype: "success", request_id: controlRequestId, response }
|
|
2742
|
+
});
|
|
2743
|
+
} catch {
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
/**
|
|
2747
|
+
* A control request from Claude Code: a permission prompt is relayed (or, for a session
|
|
2748
|
+
* not set up to relay, denied, which is what `--permission-prompts none` would have done).
|
|
2749
|
+
* Anything else is answered as unsupported, so Claude Code never waits on it.
|
|
2750
|
+
*/
|
|
2751
|
+
async handleControlRequest(line) {
|
|
2752
|
+
const ask = parseCanUseTool(line);
|
|
2753
|
+
if (ask) {
|
|
2754
|
+
if (!this.record.relayPermissionRequests) {
|
|
2755
|
+
this.answerPermission(ask.controlRequestId, {
|
|
2756
|
+
behavior: "deny",
|
|
2757
|
+
message: "Permission prompts are not answered on this runner."
|
|
2758
|
+
});
|
|
2759
|
+
return;
|
|
2760
|
+
}
|
|
2761
|
+
this.savedRulesNow = await this.readSavedRules();
|
|
2762
|
+
if (this.permissions.request(ask) === "relayed") {
|
|
2763
|
+
this.deps.logger.info(
|
|
2764
|
+
`session ${this.sessionId}: Claude Code asks permission for ${ask.toolName}; waiting for an answer in Discovery Tree`
|
|
2765
|
+
);
|
|
2766
|
+
}
|
|
2767
|
+
return;
|
|
2768
|
+
}
|
|
2769
|
+
if (typeof line.request_id === "string") {
|
|
2770
|
+
try {
|
|
2771
|
+
this.write({
|
|
2772
|
+
type: "control_response",
|
|
2773
|
+
response: {
|
|
2774
|
+
subtype: "error",
|
|
2775
|
+
request_id: line.request_id,
|
|
2776
|
+
error: "dt-runner does not handle this control request."
|
|
2777
|
+
}
|
|
2778
|
+
});
|
|
2779
|
+
} catch {
|
|
2780
|
+
}
|
|
2781
|
+
}
|
|
2782
|
+
}
|
|
1979
2783
|
get sessionId() {
|
|
1980
2784
|
return this.record.sessionId;
|
|
1981
2785
|
}
|
|
@@ -2004,6 +2808,16 @@ var AgentSession = class {
|
|
|
2004
2808
|
* process is started again with `--resume` first.
|
|
2005
2809
|
*/
|
|
2006
2810
|
async sendMessage(text, commandId) {
|
|
2811
|
+
if (this.restartAfterTurn && this.record.turnActive) {
|
|
2812
|
+
const ids2 = this.record.handledCommandIds ??= [];
|
|
2813
|
+
ids2.push(commandId);
|
|
2814
|
+
if (ids2.length > HANDLED_COMMAND_IDS_KEPT)
|
|
2815
|
+
ids2.splice(0, ids2.length - HANDLED_COMMAND_IDS_KEPT);
|
|
2816
|
+
await this.deps.store.save(this.record);
|
|
2817
|
+
this.deferredMessages.push(text);
|
|
2818
|
+
this.emit({ type: "user_message_echo", providerEventId: commandId, text, delivered: true });
|
|
2819
|
+
return;
|
|
2820
|
+
}
|
|
2007
2821
|
await this.ensureProcess();
|
|
2008
2822
|
const ids = this.record.handledCommandIds ??= [];
|
|
2009
2823
|
ids.push(commandId);
|
|
@@ -2032,6 +2846,7 @@ var AgentSession = class {
|
|
|
2032
2846
|
const child = this.child;
|
|
2033
2847
|
if (!child || !this.record.turnActive) return false;
|
|
2034
2848
|
this.interruptRequested = true;
|
|
2849
|
+
this.permissions.expireAll(PERMISSION_EXPIRED_INTERRUPTED);
|
|
2035
2850
|
this.write({
|
|
2036
2851
|
type: "control_request",
|
|
2037
2852
|
request_id: `dt_interrupt_${++this.controlSeq}`,
|
|
@@ -2055,20 +2870,17 @@ var AgentSession = class {
|
|
|
2055
2870
|
async stop(reason, graceMs = 5e3) {
|
|
2056
2871
|
const child = this.child;
|
|
2057
2872
|
if (!child) return;
|
|
2058
|
-
const reaped = this.
|
|
2873
|
+
const reaped = this.treeReaped;
|
|
2059
2874
|
this.stopping = reason;
|
|
2060
2875
|
this.reapGraceMs = graceMs;
|
|
2061
2876
|
const exited = new Promise((resolve) => this.exitWaiters.push(resolve));
|
|
2062
2877
|
child.stdin.end();
|
|
2063
|
-
const timedOut = await
|
|
2064
|
-
exited.then(() => false),
|
|
2065
|
-
delay(graceMs).then(() => true)
|
|
2066
|
-
]);
|
|
2878
|
+
const timedOut = await raceTimeout(exited, graceMs);
|
|
2067
2879
|
if (timedOut && this.child === child) {
|
|
2068
2880
|
signalTree(child, "SIGTERM");
|
|
2069
|
-
const again = await
|
|
2881
|
+
const again = await raceTimeout(exited, graceMs);
|
|
2070
2882
|
if (again && this.child === child) signalTree(child, "SIGKILL");
|
|
2071
|
-
await
|
|
2883
|
+
await raceTimeout(exited, graceMs);
|
|
2072
2884
|
}
|
|
2073
2885
|
if (child.exitCode !== null || child.signalCode !== null) await reaped;
|
|
2074
2886
|
await this.lineChain;
|
|
@@ -2127,13 +2939,18 @@ ${text}`;
|
|
|
2127
2939
|
if (this.child) return;
|
|
2128
2940
|
await this.prepareEvidenceDir();
|
|
2129
2941
|
const { bin, features } = await this.deps.claude();
|
|
2942
|
+
const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
|
|
2943
|
+
const allowedTools = [
|
|
2944
|
+
.../* @__PURE__ */ new Set([...this.deps.allowedTools, ...savedRules, ...this.record.grantRules ?? []])
|
|
2945
|
+
];
|
|
2130
2946
|
const args = claudeArgs({
|
|
2131
2947
|
permissionMode: this.deps.permissionMode,
|
|
2132
|
-
allowedTools
|
|
2948
|
+
allowedTools,
|
|
2133
2949
|
disallowedTools: this.deps.disallowedTools,
|
|
2134
2950
|
loadProjectSettings: this.deps.loadProjectSettings,
|
|
2135
2951
|
model: this.record.model,
|
|
2136
2952
|
resume: this.record.claudeSessionId,
|
|
2953
|
+
relayPermissions: !!this.record.relayPermissionRequests,
|
|
2137
2954
|
appendSystemPrompt: runnerSystemPrompt({
|
|
2138
2955
|
workBranch: this.record.workBranch,
|
|
2139
2956
|
baseRef: this.record.baseRef,
|
|
@@ -2150,9 +2967,10 @@ ${text}`;
|
|
|
2150
2967
|
// the terminal's Ctrl+C no longer reaches it: the runner's shutdown stops it.
|
|
2151
2968
|
detached: OWN_PROCESS_GROUP
|
|
2152
2969
|
});
|
|
2970
|
+
let tree = null;
|
|
2153
2971
|
await new Promise((resolve, reject) => {
|
|
2154
2972
|
child.once("spawn", () => {
|
|
2155
|
-
|
|
2973
|
+
tree = trackTree(child, this.record.cwd || void 0);
|
|
2156
2974
|
resolve();
|
|
2157
2975
|
});
|
|
2158
2976
|
child.once(
|
|
@@ -2172,8 +2990,8 @@ ${text}`;
|
|
|
2172
2990
|
`session ${this.sessionId}: Claude Code started${this.record.claudeSessionId ? " (resumed)" : ""}`,
|
|
2173
2991
|
{ pid: child.pid }
|
|
2174
2992
|
);
|
|
2175
|
-
this.
|
|
2176
|
-
(resolve) => child.once("exit", () => void
|
|
2993
|
+
this.treeReaped = new Promise(
|
|
2994
|
+
(resolve) => child.once("exit", () => void reapTree(tree, this.reapGraceMs, this.deps.reap).then(resolve))
|
|
2177
2995
|
);
|
|
2178
2996
|
child.stdin.on("error", () => void 0);
|
|
2179
2997
|
child.stderr.setEncoding("utf8").on("data", (d) => {
|
|
@@ -2202,6 +3020,15 @@ ${text}`;
|
|
|
2202
3020
|
}
|
|
2203
3021
|
async handleLine(line) {
|
|
2204
3022
|
this.lastActivity = Date.now();
|
|
3023
|
+
if (line.type === "control_request") {
|
|
3024
|
+
await this.handleControlRequest(line);
|
|
3025
|
+
return;
|
|
3026
|
+
}
|
|
3027
|
+
const cancelled = parseControlCancel(line);
|
|
3028
|
+
if (cancelled) {
|
|
3029
|
+
this.permissions.cancel(cancelled);
|
|
3030
|
+
return;
|
|
3031
|
+
}
|
|
2205
3032
|
const mapped = this.mapper.map(line);
|
|
2206
3033
|
let dirty = false;
|
|
2207
3034
|
if (mapped.claudeSessionId) this.sawInitSinceSpawn = true;
|
|
@@ -2232,6 +3059,7 @@ ${text}`;
|
|
|
2232
3059
|
}
|
|
2233
3060
|
}
|
|
2234
3061
|
if (mapped.events.length) this.emit(...mapped.events);
|
|
3062
|
+
if (mapped.failedTools) this.reportFailedTools(mapped.failedTools);
|
|
2235
3063
|
if (mapped.turnEnd && this.resumeNotFound(mapped.turnEnd.isError)) {
|
|
2236
3064
|
this.planFreshRetry();
|
|
2237
3065
|
this.child?.stdin.end();
|
|
@@ -2270,6 +3098,11 @@ ${text}`;
|
|
|
2270
3098
|
this.record.claudeSessionId = null;
|
|
2271
3099
|
}
|
|
2272
3100
|
async endTurn(turn) {
|
|
3101
|
+
this.permissions.expireAll(PERMISSION_EXPIRED_TURN_ENDED);
|
|
3102
|
+
for (const d of turn.permissionDenials ?? []) {
|
|
3103
|
+
if (d.callId && this.seenFailedCalls.has(d.callId)) continue;
|
|
3104
|
+
this.reportDenial(d.callId, d.name, d.input);
|
|
3105
|
+
}
|
|
2273
3106
|
const interrupted = this.interruptRequested;
|
|
2274
3107
|
this.interruptRequested = false;
|
|
2275
3108
|
if (this.interruptTimer) clearTimeout(this.interruptTimer);
|
|
@@ -2313,6 +3146,10 @@ ${text}`;
|
|
|
2313
3146
|
...this.record.claudeSessionId ? { claudeSessionId: this.record.claudeSessionId } : {}
|
|
2314
3147
|
});
|
|
2315
3148
|
this.lastActivity = Date.now();
|
|
3149
|
+
if (this.restartAfterTurn) {
|
|
3150
|
+
this.restartAfterTurn = false;
|
|
3151
|
+
setTimeout(() => void this.restartWithGrants(), 0);
|
|
3152
|
+
}
|
|
2316
3153
|
this.deps.logger.info(
|
|
2317
3154
|
`session ${this.sessionId}: turn ${interrupted ? "interrupted" : turnFailed ? "ended with an error" : push.failed ? "finished, but its work was not pushed" : "finished"}`,
|
|
2318
3155
|
{ pushed: push.branch ?? void 0 }
|
|
@@ -2382,7 +3219,7 @@ ${text}`;
|
|
|
2382
3219
|
async publishScreenshots() {
|
|
2383
3220
|
const { workBranch, repoDir, cwd, repository } = this.record;
|
|
2384
3221
|
const repo = parseRepoUrl(
|
|
2385
|
-
repository ?? (repoDir ? `https://github.com/${basename(
|
|
3222
|
+
repository ?? (repoDir ? `https://github.com/${basename(dirname5(repoDir))}/${basename(repoDir)}` : "")
|
|
2386
3223
|
);
|
|
2387
3224
|
if (!workBranch || !repoDir || !repo) return "";
|
|
2388
3225
|
const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
|
|
@@ -2440,6 +3277,13 @@ ${text}`;
|
|
|
2440
3277
|
async handleExit(child, code, signal) {
|
|
2441
3278
|
if (this.child !== child) return;
|
|
2442
3279
|
this.child = null;
|
|
3280
|
+
if (this.interruptTimer) clearTimeout(this.interruptTimer);
|
|
3281
|
+
this.interruptTimer = null;
|
|
3282
|
+
this.permissions.expireAll(PERMISSION_EXPIRED_STOPPED);
|
|
3283
|
+
if (this.restartAfterTurn) {
|
|
3284
|
+
this.restartAfterTurn = false;
|
|
3285
|
+
if (this.deferredMessages.length) setTimeout(() => void this.restartWithGrants(), 0);
|
|
3286
|
+
}
|
|
2443
3287
|
const reason = this.stopping;
|
|
2444
3288
|
this.stopping = null;
|
|
2445
3289
|
const waiters = this.exitWaiters;
|
|
@@ -2537,8 +3381,16 @@ function startupHint(stderr) {
|
|
|
2537
3381
|
}
|
|
2538
3382
|
return "";
|
|
2539
3383
|
}
|
|
2540
|
-
function
|
|
2541
|
-
|
|
3384
|
+
async function raceTimeout(done, ms) {
|
|
3385
|
+
let timer;
|
|
3386
|
+
const timeout = new Promise((resolve) => {
|
|
3387
|
+
timer = setTimeout(() => resolve(true), ms);
|
|
3388
|
+
});
|
|
3389
|
+
try {
|
|
3390
|
+
return await Promise.race([done.then(() => false), timeout]);
|
|
3391
|
+
} finally {
|
|
3392
|
+
clearTimeout(timer);
|
|
3393
|
+
}
|
|
2542
3394
|
}
|
|
2543
3395
|
function withScreenshots(text, screenshots) {
|
|
2544
3396
|
if (!screenshots) return text;
|
|
@@ -2632,6 +3484,10 @@ var SessionManager = class {
|
|
|
2632
3484
|
case "close_session":
|
|
2633
3485
|
await this.close(cmd.sessionId);
|
|
2634
3486
|
return { ok: true };
|
|
3487
|
+
case "permission_decision":
|
|
3488
|
+
return this.decidePermission(cmd);
|
|
3489
|
+
case "grant_tool":
|
|
3490
|
+
return await this.grantTool(cmd);
|
|
2635
3491
|
default:
|
|
2636
3492
|
return {
|
|
2637
3493
|
ok: false,
|
|
@@ -2721,6 +3577,10 @@ var SessionManager = class {
|
|
|
2721
3577
|
baseSha: null,
|
|
2722
3578
|
claudeSessionId: null,
|
|
2723
3579
|
turnActive: false,
|
|
3580
|
+
...cmd.relayPermissionRequests === true ? { relayPermissionRequests: true } : {},
|
|
3581
|
+
...alwaysAllowTools(cmd).length ? { alwaysAllowedTools: alwaysAllowTools(cmd) } : {},
|
|
3582
|
+
...cmd.reportToolDenials === true ? { reportToolDenials: true } : {},
|
|
3583
|
+
...grantRules(cmd).length ? { grantRules: grantRules(cmd) } : {},
|
|
2724
3584
|
createdAt: now,
|
|
2725
3585
|
updatedAt: now
|
|
2726
3586
|
};
|
|
@@ -2789,6 +3649,11 @@ var SessionManager = class {
|
|
|
2789
3649
|
{ type: "error", message, retryable: false },
|
|
2790
3650
|
{ type: "result", status: "failed", text: null }
|
|
2791
3651
|
);
|
|
3652
|
+
await this.forgetFailedStart(session).catch(
|
|
3653
|
+
(e) => this.opts.logger.warn(`session ${cmd.sessionId}: could not clean up the failed start`, {
|
|
3654
|
+
error: safeError(e)
|
|
3655
|
+
})
|
|
3656
|
+
);
|
|
2792
3657
|
return { ok: false, error: message };
|
|
2793
3658
|
}
|
|
2794
3659
|
return { ok: true };
|
|
@@ -2843,6 +3708,53 @@ var SessionManager = class {
|
|
|
2843
3708
|
this.opts.logger.info(`session ${sessionId}: message delivered`);
|
|
2844
3709
|
return { ok: true, providerEventId: commandId };
|
|
2845
3710
|
}
|
|
3711
|
+
/**
|
|
3712
|
+
* A person's answer to a permission request: handed to the session holding the tool call.
|
|
3713
|
+
* A redelivered answer is acknowledged again; one for a request no longer waiting (it
|
|
3714
|
+
* expired, or this runner never had it) is refused, and the session reports it expired.
|
|
3715
|
+
*/
|
|
3716
|
+
decidePermission(cmd) {
|
|
3717
|
+
const session = this.sessions.get(cmd.sessionId);
|
|
3718
|
+
if (!session) {
|
|
3719
|
+
return {
|
|
3720
|
+
ok: false,
|
|
3721
|
+
error: "This runner has no such session, so the answer was not applied."
|
|
3722
|
+
};
|
|
3723
|
+
}
|
|
3724
|
+
const behavior = cmd.decision?.behavior;
|
|
3725
|
+
if (typeof cmd.requestId !== "string" || behavior !== "allow" && behavior !== "deny") {
|
|
3726
|
+
return { ok: false, error: "The permission decision is malformed." };
|
|
3727
|
+
}
|
|
3728
|
+
const outcome = session.decidePermission(cmd.requestId, cmd.decision);
|
|
3729
|
+
if (outcome === "not_pending") {
|
|
3730
|
+
return {
|
|
3731
|
+
ok: false,
|
|
3732
|
+
error: "The agent is no longer waiting for this permission request, so the answer was not applied."
|
|
3733
|
+
};
|
|
3734
|
+
}
|
|
3735
|
+
return { ok: true };
|
|
3736
|
+
}
|
|
3737
|
+
/**
|
|
3738
|
+
* A person granted a rule on one of the session's denials: the session's Claude Code gets
|
|
3739
|
+
* it. An "Always allow" is saved for the repository through the heartbeat's
|
|
3740
|
+
* `toolGrantChanges` (so it is saved even when no session is left to take a command).
|
|
3741
|
+
*/
|
|
3742
|
+
async grantTool(cmd) {
|
|
3743
|
+
const problem = toolGrantRuleProblem(cmd.rule);
|
|
3744
|
+
if (problem) return { ok: false, error: `The rule was refused: ${problem}` };
|
|
3745
|
+
if (cmd.scope !== "once" && cmd.scope !== "always") {
|
|
3746
|
+
return { ok: false, error: "The grant is malformed." };
|
|
3747
|
+
}
|
|
3748
|
+
const session = this.sessions.get(cmd.sessionId);
|
|
3749
|
+
if (!session) {
|
|
3750
|
+
return {
|
|
3751
|
+
ok: false,
|
|
3752
|
+
error: "This runner has no such session, so the rule applies from the next run."
|
|
3753
|
+
};
|
|
3754
|
+
}
|
|
3755
|
+
await session.grantTool(cmd.denialId, cmd.scope, cmd.rule.trim());
|
|
3756
|
+
return { ok: true };
|
|
3757
|
+
}
|
|
2846
3758
|
interrupt(sessionId) {
|
|
2847
3759
|
const session = this.sessions.get(sessionId);
|
|
2848
3760
|
if (!session) return { ok: true };
|
|
@@ -2859,6 +3771,25 @@ var SessionManager = class {
|
|
|
2859
3771
|
}
|
|
2860
3772
|
async closeSession(sessionId) {
|
|
2861
3773
|
await this.starting.get(sessionId)?.catch(() => void 0);
|
|
3774
|
+
await this.removeSession(sessionId);
|
|
3775
|
+
}
|
|
3776
|
+
/**
|
|
3777
|
+
* A start whose Claude Code could not be launched: no process holds the session and the
|
|
3778
|
+
* server was told the start failed, so the runner must stop reporting it as active. The
|
|
3779
|
+
* failure events get a bounded chance to reach the server first (they live in the
|
|
3780
|
+
* session's folder), then the session is removed as a close would remove it. Called from
|
|
3781
|
+
* inside the start, so it does not wait for the start as `close` does.
|
|
3782
|
+
*/
|
|
3783
|
+
async forgetFailedStart(session) {
|
|
3784
|
+
const { sessionId } = session;
|
|
3785
|
+
await session.outbox.flush(this.opts.failedStartFlushMs ?? 5e3);
|
|
3786
|
+
const existing = this.closing.get(sessionId);
|
|
3787
|
+
if (existing) return existing;
|
|
3788
|
+
const work = this.removeSession(sessionId).finally(() => this.closing.delete(sessionId));
|
|
3789
|
+
this.closing.set(sessionId, work);
|
|
3790
|
+
await work;
|
|
3791
|
+
}
|
|
3792
|
+
async removeSession(sessionId) {
|
|
2862
3793
|
const session = this.sessions.get(sessionId);
|
|
2863
3794
|
if (!session) return;
|
|
2864
3795
|
this.sessions.delete(sessionId);
|
|
@@ -2951,10 +3882,30 @@ var SessionManager = class {
|
|
|
2951
3882
|
loadProjectSettings: this.opts.config.loadProjectSettings ?? false,
|
|
2952
3883
|
interruptGraceMs: this.opts.interruptGraceMs,
|
|
2953
3884
|
onClaudeSignIn: this.opts.onClaudeSignIn,
|
|
2954
|
-
openPullRequest: this.opts.openPullRequest
|
|
3885
|
+
openPullRequest: this.opts.openPullRequest,
|
|
3886
|
+
permissionTimeoutMs: this.opts.permissionTimeoutMs,
|
|
3887
|
+
savedRules: async (url) => this.opts.grants ? await this.opts.grants.rulesFor(url) : []
|
|
2955
3888
|
});
|
|
2956
3889
|
}
|
|
2957
3890
|
};
|
|
3891
|
+
function grantRules(cmd) {
|
|
3892
|
+
if (cmd.reportToolDenials !== true || !Array.isArray(cmd.toolGrantRules)) return [];
|
|
3893
|
+
return [
|
|
3894
|
+
...new Set(
|
|
3895
|
+
cmd.toolGrantRules.filter((r) => toolGrantRuleProblem(r) === null).map((r) => r.trim())
|
|
3896
|
+
)
|
|
3897
|
+
];
|
|
3898
|
+
}
|
|
3899
|
+
function alwaysAllowTools(cmd) {
|
|
3900
|
+
if (cmd.relayPermissionRequests !== true || !Array.isArray(cmd.alwaysAllowTools)) return [];
|
|
3901
|
+
return [
|
|
3902
|
+
...new Set(
|
|
3903
|
+
cmd.alwaysAllowTools.filter(
|
|
3904
|
+
(t) => typeof t === "string" && /^[A-Za-z0-9_.:-]{1,200}$/.test(t)
|
|
3905
|
+
)
|
|
3906
|
+
)
|
|
3907
|
+
];
|
|
3908
|
+
}
|
|
2958
3909
|
function safeWorktreeKey(key, fallback) {
|
|
2959
3910
|
if (!key) return fallback;
|
|
2960
3911
|
try {
|
|
@@ -2980,10 +3931,16 @@ function safeError(err) {
|
|
|
2980
3931
|
}
|
|
2981
3932
|
|
|
2982
3933
|
// src/daemon.ts
|
|
3934
|
+
var HEARTBEAT_MAX_BACKOFF_MS = 2 * 6e4;
|
|
3935
|
+
function heartbeatRetryDelay(failures, intervalMs, maxMs = HEARTBEAT_MAX_BACKOFF_MS, retryAfterMs) {
|
|
3936
|
+
const backoff = backoffDelay(failures - 1, intervalMs, Math.max(intervalMs, maxMs));
|
|
3937
|
+
return Math.max(retryAfterMs ?? 0, backoff);
|
|
3938
|
+
}
|
|
2983
3939
|
var RunnerDaemon = class {
|
|
2984
3940
|
constructor(opts) {
|
|
2985
3941
|
this.opts = opts;
|
|
2986
3942
|
this.api = opts.api ?? new RunnerApi({ server: opts.config.server, token: opts.config.token });
|
|
3943
|
+
this.grants = opts.grants ?? new ToolGrantStore(toolGrantsFile(opts.config.configFile));
|
|
2987
3944
|
this.manager = new SessionManager({
|
|
2988
3945
|
config: opts.config,
|
|
2989
3946
|
poster: this.api,
|
|
@@ -2991,6 +3948,7 @@ var RunnerDaemon = class {
|
|
|
2991
3948
|
claude: () => this.resolveClaude(),
|
|
2992
3949
|
onUnauthorized: (err) => this.unauthorized(err),
|
|
2993
3950
|
onClaudeSignIn: (ok) => this.claudeSignIn(ok),
|
|
3951
|
+
grants: this.grants,
|
|
2994
3952
|
...opts.managerOverrides
|
|
2995
3953
|
});
|
|
2996
3954
|
}
|
|
@@ -3015,6 +3973,20 @@ var RunnerDaemon = class {
|
|
|
3015
3973
|
/** Each planning request held (answering or queued), to cancel it when Discovery Tree says. */
|
|
3016
3974
|
completionControllers = /* @__PURE__ */ new Map();
|
|
3017
3975
|
completionWaiters = [];
|
|
3976
|
+
/** Held ids already warned about as not session ids, so each is logged once, not per beat. */
|
|
3977
|
+
droppedSessionIds = /* @__PURE__ */ new Set();
|
|
3978
|
+
grants;
|
|
3979
|
+
/** The saved rules for the heartbeat; none (rather than no heartbeat) if unreadable. */
|
|
3980
|
+
async toolGrants() {
|
|
3981
|
+
try {
|
|
3982
|
+
return await this.grants.list();
|
|
3983
|
+
} catch (err) {
|
|
3984
|
+
this.opts.logger.warn("could not read the saved tool permissions", {
|
|
3985
|
+
error: err.message
|
|
3986
|
+
});
|
|
3987
|
+
return [];
|
|
3988
|
+
}
|
|
3989
|
+
}
|
|
3018
3990
|
get signal() {
|
|
3019
3991
|
return this.controller.signal;
|
|
3020
3992
|
}
|
|
@@ -3083,7 +4055,13 @@ var RunnerDaemon = class {
|
|
|
3083
4055
|
this.opts.logger.warn(`Claude Code could not sign in to Claude. ${signInFix()}`);
|
|
3084
4056
|
}
|
|
3085
4057
|
}
|
|
4058
|
+
/**
|
|
4059
|
+
* The runner's one heartbeat, for all of its sessions (each session's state rides in it).
|
|
4060
|
+
* Failures back off with jitter from the interval up to a few minutes, so a server that
|
|
4061
|
+
* is down is not hit every 15 s by every runner at once.
|
|
4062
|
+
*/
|
|
3086
4063
|
async heartbeatLoop() {
|
|
4064
|
+
const interval = this.opts.heartbeatMs ?? 15e3;
|
|
3087
4065
|
let failures = 0;
|
|
3088
4066
|
while (!this.signal.aborted) {
|
|
3089
4067
|
try {
|
|
@@ -3098,12 +4076,25 @@ var RunnerDaemon = class {
|
|
|
3098
4076
|
resumesClosedSessions: true,
|
|
3099
4077
|
opensPullRequests: true,
|
|
3100
4078
|
// And answers one-off requests, such as planning, outside any session.
|
|
3101
|
-
answersCompletions: true
|
|
4079
|
+
answersCompletions: true,
|
|
4080
|
+
// And relays Claude Code's permission prompts (`relayPermissionRequests`).
|
|
4081
|
+
relaysPermissionRequests: true,
|
|
4082
|
+
// And reports denied tool calls, takes grants on them, and keeps saved rules.
|
|
4083
|
+
grantsToolPermissions: true
|
|
3102
4084
|
},
|
|
3103
|
-
activeSessionIds: this.
|
|
4085
|
+
activeSessionIds: this.heartbeatSessionIds(),
|
|
3104
4086
|
maxConcurrentSessions: this.opts.config.maxSessions,
|
|
3105
|
-
activeCompletionIds: [...this.completionControllers.keys()]
|
|
4087
|
+
activeCompletionIds: [...this.completionControllers.keys()],
|
|
4088
|
+
toolGrants: await this.toolGrants()
|
|
3106
4089
|
});
|
|
4090
|
+
if (res?.toolGrantChanges?.length) {
|
|
4091
|
+
for (const problem of await this.grants.apply(res.toolGrantChanges)) {
|
|
4092
|
+
this.opts.logger.warn(`a saved tool permission was not applied: ${problem}`);
|
|
4093
|
+
}
|
|
4094
|
+
this.opts.logger.info(
|
|
4095
|
+
`saved tool permissions updated (${res.toolGrantChanges.length} change(s) from Discovery Tree)`
|
|
4096
|
+
);
|
|
4097
|
+
}
|
|
3107
4098
|
for (const id of res?.cancelCompletionIds ?? []) {
|
|
3108
4099
|
this.completionControllers.get(id)?.abort();
|
|
3109
4100
|
}
|
|
@@ -3124,11 +4115,22 @@ var RunnerDaemon = class {
|
|
|
3124
4115
|
} catch (err) {
|
|
3125
4116
|
if (err instanceof UnauthorizedError) return this.unauthorized(err);
|
|
3126
4117
|
failures++;
|
|
4118
|
+
const delay = heartbeatRetryDelay(
|
|
4119
|
+
failures,
|
|
4120
|
+
interval,
|
|
4121
|
+
this.opts.heartbeatMaxBackoffMs ?? HEARTBEAT_MAX_BACKOFF_MS,
|
|
4122
|
+
err instanceof ApiError ? err.retryAfterMs : void 0
|
|
4123
|
+
);
|
|
3127
4124
|
if (failures === 1 || failures % 10 === 0) {
|
|
3128
|
-
this.opts.logger.warn("heartbeat failed; retrying", {
|
|
4125
|
+
this.opts.logger.warn("heartbeat failed; retrying", {
|
|
4126
|
+
error: err.message,
|
|
4127
|
+
retryInMs: delay
|
|
4128
|
+
});
|
|
3129
4129
|
}
|
|
4130
|
+
await sleep(delay, this.signal);
|
|
4131
|
+
continue;
|
|
3130
4132
|
}
|
|
3131
|
-
await sleep(
|
|
4133
|
+
await sleep(interval, this.signal);
|
|
3132
4134
|
}
|
|
3133
4135
|
}
|
|
3134
4136
|
async commandLoop() {
|
|
@@ -3147,23 +4149,23 @@ var RunnerDaemon = class {
|
|
|
3147
4149
|
if (this.signal.aborted) break;
|
|
3148
4150
|
if (err instanceof UnauthorizedError) return this.unauthorized(err);
|
|
3149
4151
|
if (err instanceof ApiError && err.status === 429) {
|
|
3150
|
-
const
|
|
4152
|
+
const delay2 = Math.max(err.retryAfterMs ?? 0, backoffDelay(limited++, base * 5, 6e4));
|
|
3151
4153
|
this.opts.logger[limited === 1 ? "warn" : "debug"](
|
|
3152
4154
|
"Discovery Tree is limiting this runner\u2019s command polls (429); waiting before polling again. Is another dt-runner running with the same token?",
|
|
3153
|
-
{ retryInMs:
|
|
4155
|
+
{ retryInMs: delay2 }
|
|
3154
4156
|
);
|
|
3155
|
-
await sleep(
|
|
4157
|
+
await sleep(delay2, this.signal);
|
|
3156
4158
|
continue;
|
|
3157
4159
|
}
|
|
3158
|
-
const
|
|
4160
|
+
const delay = backoffDelay(attempt++, base);
|
|
3159
4161
|
this.opts.logger[attempt === 1 ? "warn" : "debug"](
|
|
3160
4162
|
"waiting for commands failed; retrying",
|
|
3161
4163
|
{
|
|
3162
4164
|
error: err.message,
|
|
3163
|
-
retryInMs:
|
|
4165
|
+
retryInMs: delay
|
|
3164
4166
|
}
|
|
3165
4167
|
);
|
|
3166
|
-
await sleep(
|
|
4168
|
+
await sleep(delay, this.signal);
|
|
3167
4169
|
}
|
|
3168
4170
|
}
|
|
3169
4171
|
}
|
|
@@ -3181,6 +4183,16 @@ var RunnerDaemon = class {
|
|
|
3181
4183
|
this.inFlight.add(tracked);
|
|
3182
4184
|
void tracked.finally(() => this.inFlight.delete(tracked));
|
|
3183
4185
|
}
|
|
4186
|
+
/** The manager's sessions as the heartbeat reports them: server session ids only. */
|
|
4187
|
+
heartbeatSessionIds() {
|
|
4188
|
+
return reportableSessionIds(this.manager.activeSessionIds(), (id) => {
|
|
4189
|
+
if (this.droppedSessionIds.has(id)) return;
|
|
4190
|
+
this.droppedSessionIds.add(id);
|
|
4191
|
+
this.opts.logger.warn(
|
|
4192
|
+
`session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${join9(this.opts.config.stateDir, "sessions", id)})`
|
|
4193
|
+
);
|
|
4194
|
+
});
|
|
4195
|
+
}
|
|
3184
4196
|
/**
|
|
3185
4197
|
* Runs `work` after every earlier command for the same session has been handled. A
|
|
3186
4198
|
* `send_message` or `interrupt` claimed while that session's `start_session` is still
|
|
@@ -3406,9 +4418,9 @@ function formatChecks(checks) {
|
|
|
3406
4418
|
|
|
3407
4419
|
// src/lock.ts
|
|
3408
4420
|
import { mkdir as mkdir7, open, readFile as readFile4, rm as rm7 } from "node:fs/promises";
|
|
3409
|
-
import { join as
|
|
4421
|
+
import { join as join10 } from "node:path";
|
|
3410
4422
|
function lockFile(stateDir) {
|
|
3411
|
-
return
|
|
4423
|
+
return join10(stateDir, "daemon.pid");
|
|
3412
4424
|
}
|
|
3413
4425
|
function pidAlive(pid) {
|
|
3414
4426
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
@@ -3769,7 +4781,10 @@ async function status() {
|
|
|
3769
4781
|
agent,
|
|
3770
4782
|
// The sessions on disk: the same list a running daemon reports, so this check never
|
|
3771
4783
|
// makes the server think a session was lost.
|
|
3772
|
-
activeSessionIds: (
|
|
4784
|
+
activeSessionIds: reportableSessionIds(
|
|
4785
|
+
(await new SessionStore(config.stateDir).list()).map((r) => r.sessionId),
|
|
4786
|
+
(id) => console.log(`Skipped: ${id} is not a Discovery Tree session id`)
|
|
4787
|
+
),
|
|
3773
4788
|
maxConcurrentSessions: config.maxSessions
|
|
3774
4789
|
});
|
|
3775
4790
|
console.log(
|