@discovery-tree/runner 0.1.9 → 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 +1176 -121
- 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 ?? "");
|
|
@@ -342,13 +593,22 @@ async function exists(p) {
|
|
|
342
593
|
return false;
|
|
343
594
|
}
|
|
344
595
|
}
|
|
596
|
+
var LOCKED_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "EACCES", "ENOTEMPTY"]);
|
|
597
|
+
function isLocked(err) {
|
|
598
|
+
return LOCKED_CODES.has(err?.code ?? "");
|
|
599
|
+
}
|
|
600
|
+
function removeDir(path) {
|
|
601
|
+
return rm(path, { recursive: true, force: true, maxRetries: 8, retryDelay: 250 });
|
|
602
|
+
}
|
|
345
603
|
async function prepareWorktree(input) {
|
|
346
604
|
const ref = parseRepoUrl(input.url);
|
|
347
605
|
if (!ref) throw new Error(repositoryUrlError(input.url));
|
|
348
606
|
assertSafeRef(input.workBranch, "Work branch");
|
|
349
607
|
if (input.baseRef) assertSafeRef(input.baseRef, "Base branch");
|
|
350
608
|
const repoDir = join2(input.reposDir, ref.owner, ref.repo);
|
|
351
|
-
const
|
|
609
|
+
const ownWorktree = join2(input.worktreesDir, input.sessionId);
|
|
610
|
+
let worktree = join2(input.worktreesDir, input.worktreeKey || input.sessionId);
|
|
611
|
+
const remove = input.removeDir ?? removeDir;
|
|
352
612
|
return withRepoLock(repoDir, async () => {
|
|
353
613
|
if (!await exists(join2(repoDir, ".git"))) {
|
|
354
614
|
await mkdir(dirname(repoDir), { recursive: true });
|
|
@@ -382,6 +642,8 @@ async function prepareWorktree(input) {
|
|
|
382
642
|
let checkout = start2;
|
|
383
643
|
let continuedFrom;
|
|
384
644
|
let setAside;
|
|
645
|
+
let leftInPlace;
|
|
646
|
+
let dirtyKept = false;
|
|
385
647
|
const remoteWork = `refs/remotes/origin/${input.workBranch}`;
|
|
386
648
|
if (input.continueBranch && await exists(worktree) && await exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], {
|
|
387
649
|
cwd: worktree,
|
|
@@ -446,11 +708,33 @@ async function prepareWorktree(input) {
|
|
|
446
708
|
if (dirty.code === 0 && dirty.stdout.trim()) {
|
|
447
709
|
const aside = `${worktree}.kept-${Date.now()}`;
|
|
448
710
|
if (await gitOk(repoDir, ["worktree", "move", worktree, aside])) setAside = aside;
|
|
711
|
+
else dirtyKept = true;
|
|
449
712
|
}
|
|
450
713
|
}
|
|
451
714
|
if (await exists(worktree)) {
|
|
452
|
-
|
|
453
|
-
|
|
715
|
+
let failure = null;
|
|
716
|
+
if (!dirtyKept) {
|
|
717
|
+
await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
|
|
718
|
+
failure = await remove(worktree).then(
|
|
719
|
+
() => null,
|
|
720
|
+
(err) => {
|
|
721
|
+
if (!isLocked(err)) throw err;
|
|
722
|
+
return err;
|
|
723
|
+
}
|
|
724
|
+
);
|
|
725
|
+
}
|
|
726
|
+
if (dirtyKept || failure) {
|
|
727
|
+
if (worktree === ownWorktree) {
|
|
728
|
+
throw failure ?? new Error(`The working copy at ${worktree} could not be replaced.`);
|
|
729
|
+
}
|
|
730
|
+
leftInPlace = worktree;
|
|
731
|
+
await gitOk(repoDir, ["-C", leftInPlace, "checkout", "--quiet", "--detach"]);
|
|
732
|
+
worktree = ownWorktree;
|
|
733
|
+
if (await exists(worktree)) {
|
|
734
|
+
await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
|
|
735
|
+
await remove(worktree);
|
|
736
|
+
}
|
|
737
|
+
}
|
|
454
738
|
}
|
|
455
739
|
await gitOk(repoDir, ["worktree", "prune"]);
|
|
456
740
|
await mkdir(input.worktreesDir, { recursive: true });
|
|
@@ -458,6 +742,8 @@ async function prepareWorktree(input) {
|
|
|
458
742
|
"worktree",
|
|
459
743
|
"add",
|
|
460
744
|
"--no-track",
|
|
745
|
+
// A folder left in place may still be registered with the work branch checked out.
|
|
746
|
+
...leftInPlace ? ["--force"] : [],
|
|
461
747
|
"-B",
|
|
462
748
|
input.workBranch,
|
|
463
749
|
worktree,
|
|
@@ -469,7 +755,8 @@ async function prepareWorktree(input) {
|
|
|
469
755
|
baseRef,
|
|
470
756
|
baseSha,
|
|
471
757
|
...continuedFrom ? { continuedFrom } : {},
|
|
472
|
-
...setAside ? { setAside } : {}
|
|
758
|
+
...setAside ? { setAside } : {},
|
|
759
|
+
...leftInPlace ? { leftInPlace } : {}
|
|
473
760
|
};
|
|
474
761
|
});
|
|
475
762
|
}
|
|
@@ -538,7 +825,7 @@ async function removeWorktree(repoDir, worktree) {
|
|
|
538
825
|
if (repoDir && await exists(repoDir)) {
|
|
539
826
|
await gitOk(repoDir, ["worktree", "remove", "--force", worktree]);
|
|
540
827
|
}
|
|
541
|
-
await
|
|
828
|
+
await removeDir(worktree);
|
|
542
829
|
if (repoDir && await exists(repoDir)) await gitOk(repoDir, ["worktree", "prune"]);
|
|
543
830
|
}
|
|
544
831
|
function errorText(err, prefix) {
|
|
@@ -757,14 +1044,16 @@ async function claudeFeatures(bin) {
|
|
|
757
1044
|
permissionPrompts: res.stdout.includes("--permission-prompts"),
|
|
758
1045
|
settingSources: res.stdout.includes("--setting-sources"),
|
|
759
1046
|
maxTurns: res.stdout.includes("--max-turns"),
|
|
760
|
-
strictMcpConfig: res.stdout.includes("--strict-mcp-config")
|
|
1047
|
+
strictMcpConfig: res.stdout.includes("--strict-mcp-config"),
|
|
1048
|
+
permissionPromptTool: res.stdout.includes("--permission-prompt-tool")
|
|
761
1049
|
};
|
|
762
1050
|
} catch {
|
|
763
1051
|
return {
|
|
764
1052
|
permissionPrompts: false,
|
|
765
1053
|
settingSources: false,
|
|
766
1054
|
maxTurns: false,
|
|
767
|
-
strictMcpConfig: false
|
|
1055
|
+
strictMcpConfig: false,
|
|
1056
|
+
permissionPromptTool: false
|
|
768
1057
|
};
|
|
769
1058
|
}
|
|
770
1059
|
}
|
|
@@ -819,6 +1108,9 @@ function assertValidModel(model) {
|
|
|
819
1108
|
);
|
|
820
1109
|
}
|
|
821
1110
|
}
|
|
1111
|
+
function relaysPermissions(launch) {
|
|
1112
|
+
return !!launch.relayPermissions && !!launch.features.permissionPromptTool && launch.permissionMode !== "bypassPermissions";
|
|
1113
|
+
}
|
|
822
1114
|
function claudeArgs(launch) {
|
|
823
1115
|
const args = [
|
|
824
1116
|
"-p",
|
|
@@ -834,7 +1126,11 @@ function claudeArgs(launch) {
|
|
|
834
1126
|
} else {
|
|
835
1127
|
args.push("--permission-mode", launch.permissionMode);
|
|
836
1128
|
}
|
|
837
|
-
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
|
+
}
|
|
838
1134
|
if (launch.features.settingSources && !launch.loadProjectSettings) {
|
|
839
1135
|
args.push("--setting-sources", "user");
|
|
840
1136
|
}
|
|
@@ -1130,6 +1426,9 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1130
1426
|
};
|
|
1131
1427
|
}
|
|
1132
1428
|
|
|
1429
|
+
// src/daemon.ts
|
|
1430
|
+
import { join as join9 } from "node:path";
|
|
1431
|
+
|
|
1133
1432
|
// src/backoff.ts
|
|
1134
1433
|
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
1135
1434
|
const ceiling = Math.min(maxMs, baseMs * 2 ** Math.min(attempt, 20));
|
|
@@ -1200,7 +1499,7 @@ async function answerCompletion(req, deps) {
|
|
|
1200
1499
|
const { bin, features } = await deps.claude();
|
|
1201
1500
|
const args = completionArgs(req, features);
|
|
1202
1501
|
cwd = await mkdtemp2(join6(tmpdir2(), "dt-runner-completion-"));
|
|
1203
|
-
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 }));
|
|
1204
1503
|
const input = req.systemPrompt ? `<instructions>
|
|
1205
1504
|
${req.systemPrompt}
|
|
1206
1505
|
</instructions>
|
|
@@ -1240,6 +1539,16 @@ function readResult(res) {
|
|
|
1240
1539
|
};
|
|
1241
1540
|
}
|
|
1242
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
|
+
|
|
1243
1552
|
// src/session-manager.ts
|
|
1244
1553
|
import { mkdir as mkdir6, rm as rm6 } from "node:fs/promises";
|
|
1245
1554
|
|
|
@@ -1494,9 +1803,398 @@ function takeBatch(pending) {
|
|
|
1494
1803
|
|
|
1495
1804
|
// src/session.ts
|
|
1496
1805
|
import { spawn as spawn3 } from "node:child_process";
|
|
1497
|
-
import {
|
|
1806
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1807
|
+
import { basename, dirname as dirname5 } from "node:path";
|
|
1498
1808
|
import { createInterface } from "node:readline";
|
|
1499
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
|
+
|
|
1500
2198
|
// src/pull-request.ts
|
|
1501
2199
|
var PULL_REQUEST_BODY_MAX_CHARS = 6e4;
|
|
1502
2200
|
var GH_TIMEOUT_MS = 6e4;
|
|
@@ -1585,94 +2283,31 @@ function ghError(command, res) {
|
|
|
1585
2283
|
return scrubSecrets(`gh ${command} failed${detail ? `: ${detail}` : ""}`).slice(0, 300);
|
|
1586
2284
|
}
|
|
1587
2285
|
|
|
1588
|
-
// src/process-tree.ts
|
|
1589
|
-
import { spawn as spawn2 } from "node:child_process";
|
|
1590
|
-
var OWN_PROCESS_GROUP = process.platform !== "win32";
|
|
1591
|
-
var liveGroups = /* @__PURE__ */ new Set();
|
|
1592
|
-
var exitHookInstalled = false;
|
|
1593
|
-
function trackGroup(child) {
|
|
1594
|
-
if (!OWN_PROCESS_GROUP || !child.pid) return;
|
|
1595
|
-
liveGroups.add(child.pid);
|
|
1596
|
-
if (!exitHookInstalled) {
|
|
1597
|
-
exitHookInstalled = true;
|
|
1598
|
-
process.once("exit", () => {
|
|
1599
|
-
for (const pgid of liveGroups) signalGroup(pgid, "SIGKILL");
|
|
1600
|
-
});
|
|
1601
|
-
}
|
|
1602
|
-
}
|
|
1603
|
-
function signalTree(child, signal) {
|
|
1604
|
-
if (!child.pid) return;
|
|
1605
|
-
if (OWN_PROCESS_GROUP) {
|
|
1606
|
-
if (!signalGroup(child.pid, signal)) child.kill(signal);
|
|
1607
|
-
return;
|
|
1608
|
-
}
|
|
1609
|
-
if (signal === "SIGKILL") {
|
|
1610
|
-
const tk = spawn2("taskkill", ["/pid", String(child.pid), "/T", "/F"], {
|
|
1611
|
-
stdio: "ignore",
|
|
1612
|
-
windowsHide: true
|
|
1613
|
-
});
|
|
1614
|
-
let fellBack = false;
|
|
1615
|
-
const fallBack = () => {
|
|
1616
|
-
if (fellBack) return;
|
|
1617
|
-
fellBack = true;
|
|
1618
|
-
child.kill(signal);
|
|
1619
|
-
};
|
|
1620
|
-
tk.on("error", fallBack);
|
|
1621
|
-
tk.on("exit", (code) => {
|
|
1622
|
-
if (code !== 0) fallBack();
|
|
1623
|
-
});
|
|
1624
|
-
return;
|
|
1625
|
-
}
|
|
1626
|
-
child.kill(signal);
|
|
1627
|
-
}
|
|
1628
|
-
async function reapGroup(pgid, graceMs = 2e3) {
|
|
1629
|
-
if (!OWN_PROCESS_GROUP || !pgid) return;
|
|
1630
|
-
try {
|
|
1631
|
-
if (!signalGroup(pgid, "SIGTERM")) return;
|
|
1632
|
-
const deadline = Date.now() + graceMs;
|
|
1633
|
-
while (Date.now() < deadline) {
|
|
1634
|
-
await new Promise((r) => setTimeout(r, 50));
|
|
1635
|
-
if (!signalGroup(pgid, 0)) return;
|
|
1636
|
-
}
|
|
1637
|
-
signalGroup(pgid, "SIGKILL");
|
|
1638
|
-
} finally {
|
|
1639
|
-
liveGroups.delete(pgid);
|
|
1640
|
-
}
|
|
1641
|
-
}
|
|
1642
|
-
function signalGroup(pgid, signal) {
|
|
1643
|
-
try {
|
|
1644
|
-
process.kill(-pgid, signal);
|
|
1645
|
-
return true;
|
|
1646
|
-
} catch {
|
|
1647
|
-
return false;
|
|
1648
|
-
}
|
|
1649
|
-
}
|
|
1650
|
-
|
|
1651
2286
|
// src/session-store.ts
|
|
1652
2287
|
import { mkdir as mkdir5, readdir as readdir2, rm as rm5 } from "node:fs/promises";
|
|
1653
|
-
import { join as
|
|
2288
|
+
import { join as join8 } from "node:path";
|
|
1654
2289
|
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
1655
2290
|
var SessionStore = class {
|
|
1656
2291
|
constructor(stateDir) {
|
|
1657
2292
|
this.stateDir = stateDir;
|
|
1658
2293
|
}
|
|
1659
2294
|
dir(sessionId) {
|
|
1660
|
-
return
|
|
2295
|
+
return join8(this.stateDir, "sessions", sessionId);
|
|
1661
2296
|
}
|
|
1662
2297
|
outboxFile(sessionId) {
|
|
1663
|
-
return
|
|
2298
|
+
return join8(this.dir(sessionId), "outbox.json");
|
|
1664
2299
|
}
|
|
1665
2300
|
async save(record) {
|
|
1666
2301
|
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
1667
|
-
await writeJsonAtomic(
|
|
2302
|
+
await writeJsonAtomic(join8(this.dir(record.sessionId), "session.json"), record);
|
|
1668
2303
|
}
|
|
1669
2304
|
async list() {
|
|
1670
|
-
const root =
|
|
2305
|
+
const root = join8(this.stateDir, "sessions");
|
|
1671
2306
|
await mkdir5(root, { recursive: true });
|
|
1672
2307
|
const out = [];
|
|
1673
2308
|
for (const entry of await readdir2(root, { withFileTypes: true })) {
|
|
1674
2309
|
if (!entry.isDirectory()) continue;
|
|
1675
|
-
const rec = await readJson(
|
|
2310
|
+
const rec = await readJson(join8(root, entry.name, "session.json"));
|
|
1676
2311
|
if (rec?.sessionId === entry.name) out.push(rec);
|
|
1677
2312
|
}
|
|
1678
2313
|
return out;
|
|
@@ -1682,7 +2317,7 @@ var SessionStore = class {
|
|
|
1682
2317
|
}
|
|
1683
2318
|
/** Scratch working directory for a session without a repository. */
|
|
1684
2319
|
scratchDir(sessionId) {
|
|
1685
|
-
return
|
|
2320
|
+
return join8(this.stateDir, "scratch", sessionId);
|
|
1686
2321
|
}
|
|
1687
2322
|
};
|
|
1688
2323
|
function assertSafeSessionId(id) {
|
|
@@ -1740,6 +2375,12 @@ var ClaudeStreamMapper = class {
|
|
|
1740
2375
|
isError: line.is_error === true || (line.subtype ?? "success") !== "success",
|
|
1741
2376
|
subtype: typeof line.subtype === "string" ? line.subtype : null
|
|
1742
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;
|
|
1743
2384
|
this.endTurn();
|
|
1744
2385
|
break;
|
|
1745
2386
|
}
|
|
@@ -1865,7 +2506,16 @@ var ClaudeStreamMapper = class {
|
|
|
1865
2506
|
for (const block of content) {
|
|
1866
2507
|
if (block?.type !== "tool_result" || typeof block.tool_use_id !== "string") continue;
|
|
1867
2508
|
const known = this.calls.get(block.tool_use_id);
|
|
1868
|
-
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
|
+
}
|
|
1869
2519
|
const tool = {
|
|
1870
2520
|
callId: block.tool_use_id,
|
|
1871
2521
|
name: known?.name ?? "tool",
|
|
@@ -1903,10 +2553,33 @@ function toolResultText(content) {
|
|
|
1903
2553
|
}
|
|
1904
2554
|
|
|
1905
2555
|
// src/session.ts
|
|
2556
|
+
var DENIALS_KEPT = 200;
|
|
1906
2557
|
var AgentSession = class {
|
|
1907
2558
|
constructor(record, deps) {
|
|
1908
2559
|
this.record = record;
|
|
1909
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
|
+
});
|
|
1910
2583
|
}
|
|
1911
2584
|
child = null;
|
|
1912
2585
|
mapper = new ClaudeStreamMapper();
|
|
@@ -1935,11 +2608,177 @@ var AgentSession = class {
|
|
|
1935
2608
|
*/
|
|
1936
2609
|
resumeDoomed = false;
|
|
1937
2610
|
exitWaiters = [];
|
|
1938
|
-
/** Settles once the current process has exited and what it left in its
|
|
1939
|
-
|
|
2611
|
+
/** Settles once the current process has exited and what it left in its tree is gone. */
|
|
2612
|
+
treeReaped = Promise.resolve();
|
|
1940
2613
|
/** How long what is left in the group gets after SIGTERM: a stop's grace, or the default. */
|
|
1941
2614
|
reapGraceMs;
|
|
1942
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
|
+
}
|
|
1943
2782
|
get sessionId() {
|
|
1944
2783
|
return this.record.sessionId;
|
|
1945
2784
|
}
|
|
@@ -1968,6 +2807,16 @@ var AgentSession = class {
|
|
|
1968
2807
|
* process is started again with `--resume` first.
|
|
1969
2808
|
*/
|
|
1970
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
|
+
}
|
|
1971
2820
|
await this.ensureProcess();
|
|
1972
2821
|
const ids = this.record.handledCommandIds ??= [];
|
|
1973
2822
|
ids.push(commandId);
|
|
@@ -1996,6 +2845,7 @@ var AgentSession = class {
|
|
|
1996
2845
|
const child = this.child;
|
|
1997
2846
|
if (!child || !this.record.turnActive) return false;
|
|
1998
2847
|
this.interruptRequested = true;
|
|
2848
|
+
this.permissions.expireAll(PERMISSION_EXPIRED_INTERRUPTED);
|
|
1999
2849
|
this.write({
|
|
2000
2850
|
type: "control_request",
|
|
2001
2851
|
request_id: `dt_interrupt_${++this.controlSeq}`,
|
|
@@ -2019,20 +2869,17 @@ var AgentSession = class {
|
|
|
2019
2869
|
async stop(reason, graceMs = 5e3) {
|
|
2020
2870
|
const child = this.child;
|
|
2021
2871
|
if (!child) return;
|
|
2022
|
-
const reaped = this.
|
|
2872
|
+
const reaped = this.treeReaped;
|
|
2023
2873
|
this.stopping = reason;
|
|
2024
2874
|
this.reapGraceMs = graceMs;
|
|
2025
2875
|
const exited = new Promise((resolve) => this.exitWaiters.push(resolve));
|
|
2026
2876
|
child.stdin.end();
|
|
2027
|
-
const timedOut = await
|
|
2028
|
-
exited.then(() => false),
|
|
2029
|
-
delay(graceMs).then(() => true)
|
|
2030
|
-
]);
|
|
2877
|
+
const timedOut = await raceTimeout(exited, graceMs);
|
|
2031
2878
|
if (timedOut && this.child === child) {
|
|
2032
2879
|
signalTree(child, "SIGTERM");
|
|
2033
|
-
const again = await
|
|
2880
|
+
const again = await raceTimeout(exited, graceMs);
|
|
2034
2881
|
if (again && this.child === child) signalTree(child, "SIGKILL");
|
|
2035
|
-
await
|
|
2882
|
+
await raceTimeout(exited, graceMs);
|
|
2036
2883
|
}
|
|
2037
2884
|
if (child.exitCode !== null || child.signalCode !== null) await reaped;
|
|
2038
2885
|
await this.lineChain;
|
|
@@ -2091,13 +2938,18 @@ ${text}`;
|
|
|
2091
2938
|
if (this.child) return;
|
|
2092
2939
|
await this.prepareEvidenceDir();
|
|
2093
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
|
+
];
|
|
2094
2945
|
const args = claudeArgs({
|
|
2095
2946
|
permissionMode: this.deps.permissionMode,
|
|
2096
|
-
allowedTools
|
|
2947
|
+
allowedTools,
|
|
2097
2948
|
disallowedTools: this.deps.disallowedTools,
|
|
2098
2949
|
loadProjectSettings: this.deps.loadProjectSettings,
|
|
2099
2950
|
model: this.record.model,
|
|
2100
2951
|
resume: this.record.claudeSessionId,
|
|
2952
|
+
relayPermissions: !!this.record.relayPermissionRequests,
|
|
2101
2953
|
appendSystemPrompt: runnerSystemPrompt({
|
|
2102
2954
|
workBranch: this.record.workBranch,
|
|
2103
2955
|
baseRef: this.record.baseRef,
|
|
@@ -2114,9 +2966,10 @@ ${text}`;
|
|
|
2114
2966
|
// the terminal's Ctrl+C no longer reaches it: the runner's shutdown stops it.
|
|
2115
2967
|
detached: OWN_PROCESS_GROUP
|
|
2116
2968
|
});
|
|
2969
|
+
let tree = null;
|
|
2117
2970
|
await new Promise((resolve, reject) => {
|
|
2118
2971
|
child.once("spawn", () => {
|
|
2119
|
-
|
|
2972
|
+
tree = trackTree(child, this.record.cwd || void 0);
|
|
2120
2973
|
resolve();
|
|
2121
2974
|
});
|
|
2122
2975
|
child.once(
|
|
@@ -2136,8 +2989,8 @@ ${text}`;
|
|
|
2136
2989
|
`session ${this.sessionId}: Claude Code started${this.record.claudeSessionId ? " (resumed)" : ""}`,
|
|
2137
2990
|
{ pid: child.pid }
|
|
2138
2991
|
);
|
|
2139
|
-
this.
|
|
2140
|
-
(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))
|
|
2141
2994
|
);
|
|
2142
2995
|
child.stdin.on("error", () => void 0);
|
|
2143
2996
|
child.stderr.setEncoding("utf8").on("data", (d) => {
|
|
@@ -2166,6 +3019,15 @@ ${text}`;
|
|
|
2166
3019
|
}
|
|
2167
3020
|
async handleLine(line) {
|
|
2168
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
|
+
}
|
|
2169
3031
|
const mapped = this.mapper.map(line);
|
|
2170
3032
|
let dirty = false;
|
|
2171
3033
|
if (mapped.claudeSessionId) this.sawInitSinceSpawn = true;
|
|
@@ -2196,6 +3058,7 @@ ${text}`;
|
|
|
2196
3058
|
}
|
|
2197
3059
|
}
|
|
2198
3060
|
if (mapped.events.length) this.emit(...mapped.events);
|
|
3061
|
+
if (mapped.failedTools) this.reportFailedTools(mapped.failedTools);
|
|
2199
3062
|
if (mapped.turnEnd && this.resumeNotFound(mapped.turnEnd.isError)) {
|
|
2200
3063
|
this.planFreshRetry();
|
|
2201
3064
|
this.child?.stdin.end();
|
|
@@ -2234,6 +3097,11 @@ ${text}`;
|
|
|
2234
3097
|
this.record.claudeSessionId = null;
|
|
2235
3098
|
}
|
|
2236
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
|
+
}
|
|
2237
3105
|
const interrupted = this.interruptRequested;
|
|
2238
3106
|
this.interruptRequested = false;
|
|
2239
3107
|
if (this.interruptTimer) clearTimeout(this.interruptTimer);
|
|
@@ -2277,6 +3145,10 @@ ${text}`;
|
|
|
2277
3145
|
...this.record.claudeSessionId ? { claudeSessionId: this.record.claudeSessionId } : {}
|
|
2278
3146
|
});
|
|
2279
3147
|
this.lastActivity = Date.now();
|
|
3148
|
+
if (this.restartAfterTurn) {
|
|
3149
|
+
this.restartAfterTurn = false;
|
|
3150
|
+
setTimeout(() => void this.restartWithGrants(), 0);
|
|
3151
|
+
}
|
|
2280
3152
|
this.deps.logger.info(
|
|
2281
3153
|
`session ${this.sessionId}: turn ${interrupted ? "interrupted" : turnFailed ? "ended with an error" : push.failed ? "finished, but its work was not pushed" : "finished"}`,
|
|
2282
3154
|
{ pushed: push.branch ?? void 0 }
|
|
@@ -2346,7 +3218,7 @@ ${text}`;
|
|
|
2346
3218
|
async publishScreenshots() {
|
|
2347
3219
|
const { workBranch, repoDir, cwd, repository } = this.record;
|
|
2348
3220
|
const repo = parseRepoUrl(
|
|
2349
|
-
repository ?? (repoDir ? `https://github.com/${basename(
|
|
3221
|
+
repository ?? (repoDir ? `https://github.com/${basename(dirname5(repoDir))}/${basename(repoDir)}` : "")
|
|
2350
3222
|
);
|
|
2351
3223
|
if (!workBranch || !repoDir || !repo) return "";
|
|
2352
3224
|
const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
|
|
@@ -2404,6 +3276,13 @@ ${text}`;
|
|
|
2404
3276
|
async handleExit(child, code, signal) {
|
|
2405
3277
|
if (this.child !== child) return;
|
|
2406
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
|
+
}
|
|
2407
3286
|
const reason = this.stopping;
|
|
2408
3287
|
this.stopping = null;
|
|
2409
3288
|
const waiters = this.exitWaiters;
|
|
@@ -2501,8 +3380,16 @@ function startupHint(stderr) {
|
|
|
2501
3380
|
}
|
|
2502
3381
|
return "";
|
|
2503
3382
|
}
|
|
2504
|
-
function
|
|
2505
|
-
|
|
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
|
+
}
|
|
2506
3393
|
}
|
|
2507
3394
|
function withScreenshots(text, screenshots) {
|
|
2508
3395
|
if (!screenshots) return text;
|
|
@@ -2596,6 +3483,10 @@ var SessionManager = class {
|
|
|
2596
3483
|
case "close_session":
|
|
2597
3484
|
await this.close(cmd.sessionId);
|
|
2598
3485
|
return { ok: true };
|
|
3486
|
+
case "permission_decision":
|
|
3487
|
+
return this.decidePermission(cmd);
|
|
3488
|
+
case "grant_tool":
|
|
3489
|
+
return await this.grantTool(cmd);
|
|
2599
3490
|
default:
|
|
2600
3491
|
return {
|
|
2601
3492
|
ok: false,
|
|
@@ -2685,6 +3576,10 @@ var SessionManager = class {
|
|
|
2685
3576
|
baseSha: null,
|
|
2686
3577
|
claudeSessionId: null,
|
|
2687
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) } : {},
|
|
2688
3583
|
createdAt: now,
|
|
2689
3584
|
updatedAt: now
|
|
2690
3585
|
};
|
|
@@ -2713,6 +3608,11 @@ var SessionManager = class {
|
|
|
2713
3608
|
// protecting it until a turn commits them, or a close before then would delete them.
|
|
2714
3609
|
...wt.continuedFrom === "worktree" ? { keepWorktree: true } : {}
|
|
2715
3610
|
});
|
|
3611
|
+
if (wt.leftInPlace) {
|
|
3612
|
+
this.opts.logger.warn(
|
|
3613
|
+
`session ${cmd.sessionId}: the earlier working copy at ${wt.leftInPlace} is in use (close any terminal, editor or program open in it) and was left as it is; this session works in ${wt.worktree}`
|
|
3614
|
+
);
|
|
3615
|
+
}
|
|
2716
3616
|
if (wt.setAside) {
|
|
2717
3617
|
this.opts.logger.warn(
|
|
2718
3618
|
`session ${cmd.sessionId}: an earlier working copy with uncommitted changes could not be reused; it was moved to ${wt.setAside}`
|
|
@@ -2748,6 +3648,11 @@ var SessionManager = class {
|
|
|
2748
3648
|
{ type: "error", message, retryable: false },
|
|
2749
3649
|
{ type: "result", status: "failed", text: null }
|
|
2750
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
|
+
);
|
|
2751
3656
|
return { ok: false, error: message };
|
|
2752
3657
|
}
|
|
2753
3658
|
return { ok: true };
|
|
@@ -2802,6 +3707,53 @@ var SessionManager = class {
|
|
|
2802
3707
|
this.opts.logger.info(`session ${sessionId}: message delivered`);
|
|
2803
3708
|
return { ok: true, providerEventId: commandId };
|
|
2804
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
|
+
}
|
|
2805
3757
|
interrupt(sessionId) {
|
|
2806
3758
|
const session = this.sessions.get(sessionId);
|
|
2807
3759
|
if (!session) return { ok: true };
|
|
@@ -2818,6 +3770,25 @@ var SessionManager = class {
|
|
|
2818
3770
|
}
|
|
2819
3771
|
async closeSession(sessionId) {
|
|
2820
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) {
|
|
2821
3792
|
const session = this.sessions.get(sessionId);
|
|
2822
3793
|
if (!session) return;
|
|
2823
3794
|
this.sessions.delete(sessionId);
|
|
@@ -2910,10 +3881,30 @@ var SessionManager = class {
|
|
|
2910
3881
|
loadProjectSettings: this.opts.config.loadProjectSettings ?? false,
|
|
2911
3882
|
interruptGraceMs: this.opts.interruptGraceMs,
|
|
2912
3883
|
onClaudeSignIn: this.opts.onClaudeSignIn,
|
|
2913
|
-
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) : []
|
|
2914
3887
|
});
|
|
2915
3888
|
}
|
|
2916
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
|
+
}
|
|
2917
3908
|
function safeWorktreeKey(key, fallback) {
|
|
2918
3909
|
if (!key) return fallback;
|
|
2919
3910
|
try {
|
|
@@ -2939,10 +3930,16 @@ function safeError(err) {
|
|
|
2939
3930
|
}
|
|
2940
3931
|
|
|
2941
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
|
+
}
|
|
2942
3938
|
var RunnerDaemon = class {
|
|
2943
3939
|
constructor(opts) {
|
|
2944
3940
|
this.opts = opts;
|
|
2945
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));
|
|
2946
3943
|
this.manager = new SessionManager({
|
|
2947
3944
|
config: opts.config,
|
|
2948
3945
|
poster: this.api,
|
|
@@ -2950,6 +3947,7 @@ var RunnerDaemon = class {
|
|
|
2950
3947
|
claude: () => this.resolveClaude(),
|
|
2951
3948
|
onUnauthorized: (err) => this.unauthorized(err),
|
|
2952
3949
|
onClaudeSignIn: (ok) => this.claudeSignIn(ok),
|
|
3950
|
+
grants: this.grants,
|
|
2953
3951
|
...opts.managerOverrides
|
|
2954
3952
|
});
|
|
2955
3953
|
}
|
|
@@ -2974,6 +3972,20 @@ var RunnerDaemon = class {
|
|
|
2974
3972
|
/** Each planning request held (answering or queued), to cancel it when Discovery Tree says. */
|
|
2975
3973
|
completionControllers = /* @__PURE__ */ new Map();
|
|
2976
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
|
+
}
|
|
2977
3989
|
get signal() {
|
|
2978
3990
|
return this.controller.signal;
|
|
2979
3991
|
}
|
|
@@ -3042,7 +4054,13 @@ var RunnerDaemon = class {
|
|
|
3042
4054
|
this.opts.logger.warn(`Claude Code could not sign in to Claude. ${signInFix()}`);
|
|
3043
4055
|
}
|
|
3044
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
|
+
*/
|
|
3045
4062
|
async heartbeatLoop() {
|
|
4063
|
+
const interval = this.opts.heartbeatMs ?? 15e3;
|
|
3046
4064
|
let failures = 0;
|
|
3047
4065
|
while (!this.signal.aborted) {
|
|
3048
4066
|
try {
|
|
@@ -3057,12 +4075,25 @@ var RunnerDaemon = class {
|
|
|
3057
4075
|
resumesClosedSessions: true,
|
|
3058
4076
|
opensPullRequests: true,
|
|
3059
4077
|
// And answers one-off requests, such as planning, outside any session.
|
|
3060
|
-
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
|
|
3061
4083
|
},
|
|
3062
|
-
activeSessionIds: this.
|
|
4084
|
+
activeSessionIds: this.heartbeatSessionIds(),
|
|
3063
4085
|
maxConcurrentSessions: this.opts.config.maxSessions,
|
|
3064
|
-
activeCompletionIds: [...this.completionControllers.keys()]
|
|
4086
|
+
activeCompletionIds: [...this.completionControllers.keys()],
|
|
4087
|
+
toolGrants: await this.toolGrants()
|
|
3065
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
|
+
}
|
|
3066
4097
|
for (const id of res?.cancelCompletionIds ?? []) {
|
|
3067
4098
|
this.completionControllers.get(id)?.abort();
|
|
3068
4099
|
}
|
|
@@ -3083,11 +4114,22 @@ var RunnerDaemon = class {
|
|
|
3083
4114
|
} catch (err) {
|
|
3084
4115
|
if (err instanceof UnauthorizedError) return this.unauthorized(err);
|
|
3085
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
|
+
);
|
|
3086
4123
|
if (failures === 1 || failures % 10 === 0) {
|
|
3087
|
-
this.opts.logger.warn("heartbeat failed; retrying", {
|
|
4124
|
+
this.opts.logger.warn("heartbeat failed; retrying", {
|
|
4125
|
+
error: err.message,
|
|
4126
|
+
retryInMs: delay
|
|
4127
|
+
});
|
|
3088
4128
|
}
|
|
4129
|
+
await sleep(delay, this.signal);
|
|
4130
|
+
continue;
|
|
3089
4131
|
}
|
|
3090
|
-
await sleep(
|
|
4132
|
+
await sleep(interval, this.signal);
|
|
3091
4133
|
}
|
|
3092
4134
|
}
|
|
3093
4135
|
async commandLoop() {
|
|
@@ -3106,23 +4148,23 @@ var RunnerDaemon = class {
|
|
|
3106
4148
|
if (this.signal.aborted) break;
|
|
3107
4149
|
if (err instanceof UnauthorizedError) return this.unauthorized(err);
|
|
3108
4150
|
if (err instanceof ApiError && err.status === 429) {
|
|
3109
|
-
const
|
|
4151
|
+
const delay2 = Math.max(err.retryAfterMs ?? 0, backoffDelay(limited++, base * 5, 6e4));
|
|
3110
4152
|
this.opts.logger[limited === 1 ? "warn" : "debug"](
|
|
3111
4153
|
"Discovery Tree is limiting this runner\u2019s command polls (429); waiting before polling again. Is another dt-runner running with the same token?",
|
|
3112
|
-
{ retryInMs:
|
|
4154
|
+
{ retryInMs: delay2 }
|
|
3113
4155
|
);
|
|
3114
|
-
await sleep(
|
|
4156
|
+
await sleep(delay2, this.signal);
|
|
3115
4157
|
continue;
|
|
3116
4158
|
}
|
|
3117
|
-
const
|
|
4159
|
+
const delay = backoffDelay(attempt++, base);
|
|
3118
4160
|
this.opts.logger[attempt === 1 ? "warn" : "debug"](
|
|
3119
4161
|
"waiting for commands failed; retrying",
|
|
3120
4162
|
{
|
|
3121
4163
|
error: err.message,
|
|
3122
|
-
retryInMs:
|
|
4164
|
+
retryInMs: delay
|
|
3123
4165
|
}
|
|
3124
4166
|
);
|
|
3125
|
-
await sleep(
|
|
4167
|
+
await sleep(delay, this.signal);
|
|
3126
4168
|
}
|
|
3127
4169
|
}
|
|
3128
4170
|
}
|
|
@@ -3140,6 +4182,16 @@ var RunnerDaemon = class {
|
|
|
3140
4182
|
this.inFlight.add(tracked);
|
|
3141
4183
|
void tracked.finally(() => this.inFlight.delete(tracked));
|
|
3142
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
|
+
}
|
|
3143
4195
|
/**
|
|
3144
4196
|
* Runs `work` after every earlier command for the same session has been handled. A
|
|
3145
4197
|
* `send_message` or `interrupt` claimed while that session's `start_session` is still
|
|
@@ -3365,9 +4417,9 @@ function formatChecks(checks) {
|
|
|
3365
4417
|
|
|
3366
4418
|
// src/lock.ts
|
|
3367
4419
|
import { mkdir as mkdir7, open, readFile as readFile4, rm as rm7 } from "node:fs/promises";
|
|
3368
|
-
import { join as
|
|
4420
|
+
import { join as join10 } from "node:path";
|
|
3369
4421
|
function lockFile(stateDir) {
|
|
3370
|
-
return
|
|
4422
|
+
return join10(stateDir, "daemon.pid");
|
|
3371
4423
|
}
|
|
3372
4424
|
function pidAlive(pid) {
|
|
3373
4425
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
@@ -3728,7 +4780,10 @@ async function status() {
|
|
|
3728
4780
|
agent,
|
|
3729
4781
|
// The sessions on disk: the same list a running daemon reports, so this check never
|
|
3730
4782
|
// makes the server think a session was lost.
|
|
3731
|
-
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
|
+
),
|
|
3732
4787
|
maxConcurrentSessions: config.maxSessions
|
|
3733
4788
|
});
|
|
3734
4789
|
console.log(
|