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