@discovery-tree/runner 0.1.12 → 0.1.14
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 +41 -16
- package/dist/cli.js +501 -56
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -86,19 +86,20 @@ readable only by you (mode 0600) because it holds the runner token. `login` writ
|
|
|
86
86
|
}
|
|
87
87
|
```
|
|
88
88
|
|
|
89
|
-
| Option
|
|
90
|
-
|
|
|
91
|
-
| `maxSessions`
|
|
92
|
-
| `reposDir`
|
|
93
|
-
| `worktreesDir`
|
|
94
|
-
| `permissionMode`
|
|
95
|
-
| `allowedTools`
|
|
96
|
-
| `extraAllowedTools`
|
|
97
|
-
| `disallowedTools`
|
|
98
|
-
| `extraDisallowedTools`
|
|
99
|
-
| `loadProjectSettings`
|
|
100
|
-
| `
|
|
101
|
-
| `
|
|
89
|
+
| Option | Default | Meaning |
|
|
90
|
+
| ------------------------------ | ------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
91
|
+
| `maxSessions` | `2` | Sessions with a running Claude Code at once (1 to 64). Further starts are refused as busy and retried by the server. `--max-sessions` overrides it. |
|
|
92
|
+
| `reposDir` | `$XDG_DATA_HOME/discovery-tree/runner/repos` | Clone cache. `--repos-dir` overrides it. |
|
|
93
|
+
| `worktreesDir` | `$XDG_DATA_HOME/discovery-tree/runner/worktrees` | One worktree per session. |
|
|
94
|
+
| `permissionMode` | `acceptEdits` | Claude Code `--permission-mode`. See below. |
|
|
95
|
+
| `allowedTools` | a development allow-list | Replaces the default `--allowedTools` list. |
|
|
96
|
+
| `extraAllowedTools` | `[]` | Added to the allow-list. |
|
|
97
|
+
| `disallowedTools` | credential locations (see below) | Replaces the default `--disallowedTools` deny list. Deny rules win over the allow-list. |
|
|
98
|
+
| `extraDisallowedTools` | `[]` | Added to the deny list. |
|
|
99
|
+
| `loadProjectSettings` | `false` | `true` lets Claude Code load the repository's own `.claude/settings.json` / `settings.local.json` (hooks, permissions). See below. |
|
|
100
|
+
| `inheritClaudeCodePermissions` | `true` | Start each run with the permission rules you approved in your own Claude Code for that repository (see below). `false` turns it off. |
|
|
101
|
+
| `gitProtocol` | `https` | `ssh` clones `git@github.com:owner/repo.git` instead. The cached clone's `origin` URL is rewritten to match on every session start (see below). |
|
|
102
|
+
| `idleTimeoutMinutes` | `15` | An idle Claude Code process is ended after this long; the next message resumes it. |
|
|
102
103
|
|
|
103
104
|
Environment variables: `DT_SERVER_URL` (server), `DT_RUNNER_TOKEN` (token; overrides the file),
|
|
104
105
|
`DT_RUNNER_CLAUDE_BIN` (the `claude` binary to run).
|
|
@@ -108,8 +109,11 @@ Environment variables: `DT_SERVER_URL` (server), `DT_RUNNER_TOKEN` (token; overr
|
|
|
108
109
|
**With the default settings, the agent can run arbitrary code on your computer as you.** The
|
|
109
110
|
runner runs an AI agent with your user's access. Nobody is at the keyboard to answer Claude
|
|
110
111
|
Code's permission prompts, so the runner relays each one to Discovery Tree and holds the tool
|
|
111
|
-
call until you allow or deny it there. Only you, the run's owner, can answer. "Always allow
|
|
112
|
-
allows
|
|
112
|
+
call until you allow or deny it there. Only you, the run's owner, can answer. "Always allow for
|
|
113
|
+
this repo" allows the call and saves the rule it shows (`Bash(docker compose *)`, or the exact
|
|
114
|
+
command when no shorter rule would cover it) on this runner for the repository: later calls it
|
|
115
|
+
covers, in this run and later ones, are not asked about. "Edit rule" changes the rule first;
|
|
116
|
+
Account settings → Local runners lists the saved rules, each with Revoke.
|
|
113
117
|
A request nobody answers is denied when the turn ends, is interrupted, or after 30 minutes. With
|
|
114
118
|
a Claude Code too old to relay prompts (no `--permission-prompt-tool`), or a Discovery Tree
|
|
115
119
|
server that does not ask for it, anything that would prompt is denied and the agent reports that
|
|
@@ -121,7 +125,9 @@ never offered to you. What it may do without asking:
|
|
|
121
125
|
`Edit`, `Write`, `Glob`, `Grep`, …) and the commands an agent needs to build and test a
|
|
122
126
|
change, in Claude Code's `Bash(<prefix> *)` syntax: `git status/diff/log/add/commit …`,
|
|
123
127
|
`npm`, `npx`, `pnpm`, `yarn`, `node`, `tsc`, `python`, `pip`, `pytest`, `make`, `cargo`, `go`,
|
|
124
|
-
`
|
|
128
|
+
`bun`, `uv`, `bundle`, `mvn`, `gradle`, `dotnet`, `jest`, `vitest`, `eslint`, `ruff`, …,
|
|
129
|
+
read-only `git` (`rev-parse`, `ls-files`, `fetch`, `branch --show-current`, …) and read-only
|
|
130
|
+
tools (`ls`, `cat`, `grep`, `jq`, `cut`, `stat`, `du`, `ps`, …). **`npm`, `npx`, `pnpm`, `yarn`, `node`, `python`, `pip`, `make`,
|
|
125
131
|
`cargo` and `go` run code**, from the repository (package scripts, build files, tests) or
|
|
126
132
|
written by the agent, so this list amounts to arbitrary code execution as you. It keeps the
|
|
127
133
|
agent from stalling on every command; it is not a sandbox.
|
|
@@ -161,6 +167,25 @@ never offered to you. What it may do without asking:
|
|
|
161
167
|
Claude Code applies these `Read` rules to the shell commands it knows read files (`cat`,
|
|
162
168
|
`head`, …) too. This closes the obvious paths only: code run through the allow-list
|
|
163
169
|
(`node -e …`, a package script) can still read anything you can.
|
|
170
|
+
- **What you already allow in Claude Code** (`inheritClaudeCodePermissions`, on by default).
|
|
171
|
+
Claude Code saves your "don't ask again" answers in the folder you ran it in
|
|
172
|
+
(`.claude/settings.local.json`), and the runner works in a clone of its own, so it would ask
|
|
173
|
+
again about all of them. Instead, at each start it looks up the folders you trusted in Claude
|
|
174
|
+
Code (`~/.claude.json`) that are checkouts of the run's repository (by their git remote), and
|
|
175
|
+
passes their **permission rules only**: `permissions.allow`, `permissions.ask` and
|
|
176
|
+
`permissions.deny` from `.claude/settings.local.json` and `.claude/settings.json` (read in the
|
|
177
|
+
folder and at the repository's root, the main checkout's for a worktree), and the older
|
|
178
|
+
`allowedTools` list. Your deny rules stay deny rules, and your ask rules still ask (deny, then
|
|
179
|
+
ask, then allow, as in Claude Code; with a Claude Code too old for `--settings`, inherited
|
|
180
|
+
allow rules an ask rule overlaps are left out instead). From the repository's committed `.claude/settings.json`,
|
|
181
|
+
nothing that would allow everything is taken. File-tool approvals (`Read(…)`, `Edit(…)`,
|
|
182
|
+
`Write`, …) are never taken: they name your checkout by path, while the agent reads anything
|
|
183
|
+
and edits in its own worktree anyway, so they could only reach your working copy. File deny and
|
|
184
|
+
ask rules are taken, relative ones too, and apply to the worktree's copy of those files. Hooks,
|
|
185
|
+
environment variables and other settings are not read. The runner logs the rules and the folders they
|
|
186
|
+
came from. Keep in mind that this makes those files part of what the agent's permissions
|
|
187
|
+
depend on: an agent that can run code (anything on the allow-list that runs code can) could
|
|
188
|
+
add a rule there for later runs, as it could for your own Claude Code sessions.
|
|
164
189
|
- **Repository settings are not loaded.** The runner starts Claude Code with
|
|
165
190
|
`--setting-sources user`, so a cloned repository's `.claude/settings.json` and
|
|
166
191
|
`.claude/settings.local.json` (hooks that run shell commands, permission rules, environment
|
package/dist/cli.js
CHANGED
|
@@ -61,6 +61,7 @@ var RUNNER_SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-
|
|
|
61
61
|
function isRunnerSessionId(value) {
|
|
62
62
|
return typeof value === "string" && RUNNER_SESSION_ID_RE.test(value);
|
|
63
63
|
}
|
|
64
|
+
var RUNNER_DELIVERABLE_FILE = "DELIVERABLE.md";
|
|
64
65
|
var RUNNER_COMPLETION_MAX_TEXT = 2e5;
|
|
65
66
|
|
|
66
67
|
// ../contracts/src/agent-permissions.ts
|
|
@@ -109,7 +110,7 @@ function toolGrantRepositoryKey(url) {
|
|
|
109
110
|
}
|
|
110
111
|
|
|
111
112
|
// src/version.ts
|
|
112
|
-
var RUNNER_VERSION = true ? "0.1.
|
|
113
|
+
var RUNNER_VERSION = true ? "0.1.14" : "0.0.0-dev";
|
|
113
114
|
var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
|
|
114
115
|
|
|
115
116
|
// src/api.ts
|
|
@@ -369,7 +370,7 @@ function namesPathIn(commandLine, dir) {
|
|
|
369
370
|
}
|
|
370
371
|
function listWindowsProcesses() {
|
|
371
372
|
const script = `$ErrorActionPreference='SilentlyContinue';Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { "$($_.ProcessId) $($_.ParentProcessId) $(([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()) $($_.CommandLine -replace "[\\r\\n]", " ")" } }`;
|
|
372
|
-
return new Promise((
|
|
373
|
+
return new Promise((resolve2, reject) => {
|
|
373
374
|
const ps = spawn(
|
|
374
375
|
"powershell.exe",
|
|
375
376
|
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
|
|
@@ -384,7 +385,7 @@ function listWindowsProcesses() {
|
|
|
384
385
|
});
|
|
385
386
|
ps.on("close", () => {
|
|
386
387
|
clearTimeout(timer);
|
|
387
|
-
|
|
388
|
+
resolve2(parseProcessRows(out));
|
|
388
389
|
});
|
|
389
390
|
});
|
|
390
391
|
}
|
|
@@ -406,10 +407,10 @@ function parseProcessRows(text) {
|
|
|
406
407
|
async function taskkillTrees(pids) {
|
|
407
408
|
for (let i = 0; i < pids.length; i += 50) {
|
|
408
409
|
const args = pids.slice(i, i + 50).flatMap((p) => ["/pid", String(p)]);
|
|
409
|
-
await new Promise((
|
|
410
|
+
await new Promise((resolve2) => {
|
|
410
411
|
const tk = spawn("taskkill", [...args, "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
411
|
-
tk.on("error", () =>
|
|
412
|
-
tk.on("close", () =>
|
|
412
|
+
tk.on("error", () => resolve2());
|
|
413
|
+
tk.on("close", () => resolve2());
|
|
413
414
|
});
|
|
414
415
|
}
|
|
415
416
|
}
|
|
@@ -424,7 +425,7 @@ function signalGroup(pgid, signal) {
|
|
|
424
425
|
|
|
425
426
|
// src/exec.ts
|
|
426
427
|
function exec(cmd, args, opts = {}) {
|
|
427
|
-
return new Promise((
|
|
428
|
+
return new Promise((resolve2, reject) => {
|
|
428
429
|
const child = spawn2(cmd, args, {
|
|
429
430
|
cwd: opts.cwd,
|
|
430
431
|
env: opts.env ?? process.env,
|
|
@@ -459,7 +460,7 @@ function exec(cmd, args, opts = {}) {
|
|
|
459
460
|
child.on("close", (code) => {
|
|
460
461
|
if (timer) clearTimeout(timer);
|
|
461
462
|
opts.signal?.removeEventListener("abort", onAbort);
|
|
462
|
-
void reaped.then(() =>
|
|
463
|
+
void reaped.then(() => resolve2({ code, stdout, stderr }));
|
|
463
464
|
});
|
|
464
465
|
child.stdin.on("error", () => void 0);
|
|
465
466
|
child.stdin.end(opts.input ?? "");
|
|
@@ -859,10 +860,10 @@ async function ensureEvidenceDir(worktree) {
|
|
|
859
860
|
}
|
|
860
861
|
if (current.split("\n").some((l) => l.trim() === line)) return;
|
|
861
862
|
await mkdir2(join3(file, ".."), { recursive: true });
|
|
862
|
-
const
|
|
863
|
+
const sep2 = current && !current.endsWith("\n") ? "\n" : "";
|
|
863
864
|
await writeFile(
|
|
864
865
|
file,
|
|
865
|
-
`${current}${
|
|
866
|
+
`${current}${sep2}# Screenshots dt-runner publishes on their own branch
|
|
866
867
|
${line}
|
|
867
868
|
`
|
|
868
869
|
);
|
|
@@ -1050,7 +1051,8 @@ async function claudeFeatures(bin) {
|
|
|
1050
1051
|
settingSources: res.stdout.includes("--setting-sources"),
|
|
1051
1052
|
maxTurns: res.stdout.includes("--max-turns"),
|
|
1052
1053
|
strictMcpConfig: res.stdout.includes("--strict-mcp-config"),
|
|
1053
|
-
permissionPromptTool: res.stdout.includes("--permission-prompt-tool")
|
|
1054
|
+
permissionPromptTool: res.stdout.includes("--permission-prompt-tool"),
|
|
1055
|
+
settingsFlag: /--settings <file-or-json>/.test(res.stdout)
|
|
1054
1056
|
};
|
|
1055
1057
|
} catch {
|
|
1056
1058
|
return {
|
|
@@ -1058,7 +1060,8 @@ async function claudeFeatures(bin) {
|
|
|
1058
1060
|
settingSources: false,
|
|
1059
1061
|
maxTurns: false,
|
|
1060
1062
|
strictMcpConfig: false,
|
|
1061
|
-
permissionPromptTool: false
|
|
1063
|
+
permissionPromptTool: false,
|
|
1064
|
+
settingsFlag: false
|
|
1062
1065
|
};
|
|
1063
1066
|
}
|
|
1064
1067
|
}
|
|
@@ -1145,6 +1148,9 @@ function claudeArgs(launch) {
|
|
|
1145
1148
|
}
|
|
1146
1149
|
if (launch.resume) args.push("--resume", launch.resume);
|
|
1147
1150
|
if (launch.appendSystemPrompt) args.push("--append-system-prompt", launch.appendSystemPrompt);
|
|
1151
|
+
if (launch.askTools?.length && launch.features.settingsFlag) {
|
|
1152
|
+
args.push("--settings", JSON.stringify({ permissions: { ask: launch.askTools } }));
|
|
1153
|
+
}
|
|
1148
1154
|
if (launch.disallowedTools?.length) args.push("--disallowedTools", ...launch.disallowedTools);
|
|
1149
1155
|
if (launch.allowedTools.length) args.push("--allowedTools", ...launch.allowedTools);
|
|
1150
1156
|
return args;
|
|
@@ -1261,6 +1267,31 @@ var DEFAULT_ALLOWED_TOOLS = [
|
|
|
1261
1267
|
"Bash(git stash *)",
|
|
1262
1268
|
"Bash(git blame *)",
|
|
1263
1269
|
"Bash(git grep *)",
|
|
1270
|
+
"Bash(git rev-parse *)",
|
|
1271
|
+
"Bash(git ls-files *)",
|
|
1272
|
+
"Bash(git ls-tree *)",
|
|
1273
|
+
"Bash(git cat-file *)",
|
|
1274
|
+
"Bash(git describe *)",
|
|
1275
|
+
"Bash(git shortlog *)",
|
|
1276
|
+
"Bash(git reflog)",
|
|
1277
|
+
"Bash(git reflog show *)",
|
|
1278
|
+
"Bash(git show-ref *)",
|
|
1279
|
+
"Bash(git merge-base *)",
|
|
1280
|
+
// Not read-only on the network, and like `node *` it can run a command
|
|
1281
|
+
// (`--upload-pack`); on the list because agents fetch the base branch to compare with it.
|
|
1282
|
+
"Bash(git fetch *)",
|
|
1283
|
+
"Bash(git remote -v)",
|
|
1284
|
+
"Bash(git branch)",
|
|
1285
|
+
"Bash(git branch --show-current)",
|
|
1286
|
+
"Bash(git branch -a)",
|
|
1287
|
+
"Bash(git branch -r)",
|
|
1288
|
+
"Bash(git branch -v)",
|
|
1289
|
+
"Bash(git branch -vv)",
|
|
1290
|
+
"Bash(git branch --list *)",
|
|
1291
|
+
"Bash(git branch --contains *)",
|
|
1292
|
+
"Bash(git config --get *)",
|
|
1293
|
+
"Bash(git config --list *)",
|
|
1294
|
+
"Bash(git worktree list *)",
|
|
1264
1295
|
"Bash(gh pr view *)",
|
|
1265
1296
|
"Bash(gh pr diff *)",
|
|
1266
1297
|
"Bash(gh pr checks *)",
|
|
@@ -1284,6 +1315,29 @@ var DEFAULT_ALLOWED_TOOLS = [
|
|
|
1284
1315
|
"Bash(make *)",
|
|
1285
1316
|
"Bash(cargo *)",
|
|
1286
1317
|
"Bash(go *)",
|
|
1318
|
+
// The same, for other toolchains: they run the repository's code as npm and make do.
|
|
1319
|
+
"Bash(bun *)",
|
|
1320
|
+
"Bash(deno *)",
|
|
1321
|
+
"Bash(uv *)",
|
|
1322
|
+
"Bash(poetry *)",
|
|
1323
|
+
"Bash(ruby *)",
|
|
1324
|
+
"Bash(bundle *)",
|
|
1325
|
+
"Bash(rake *)",
|
|
1326
|
+
"Bash(rspec *)",
|
|
1327
|
+
"Bash(mvn *)",
|
|
1328
|
+
"Bash(gradle *)",
|
|
1329
|
+
"Bash(./gradlew *)",
|
|
1330
|
+
"Bash(dotnet *)",
|
|
1331
|
+
"Bash(swift *)",
|
|
1332
|
+
"Bash(java *)",
|
|
1333
|
+
"Bash(rustc *)",
|
|
1334
|
+
"Bash(jest *)",
|
|
1335
|
+
"Bash(vitest *)",
|
|
1336
|
+
"Bash(eslint *)",
|
|
1337
|
+
"Bash(prettier *)",
|
|
1338
|
+
"Bash(ruff *)",
|
|
1339
|
+
"Bash(mypy *)",
|
|
1340
|
+
"Bash(black *)",
|
|
1287
1341
|
"Bash(ls *)",
|
|
1288
1342
|
"Bash(cat *)",
|
|
1289
1343
|
"Bash(head *)",
|
|
@@ -1299,6 +1353,30 @@ var DEFAULT_ALLOWED_TOOLS = [
|
|
|
1299
1353
|
"Bash(sort *)",
|
|
1300
1354
|
"Bash(uniq *)",
|
|
1301
1355
|
"Bash(which *)",
|
|
1356
|
+
// Read-only, and none prints a file's contents (which would get around the credential
|
|
1357
|
+
// deny rules below for a command Claude Code does not know reads files): metadata,
|
|
1358
|
+
// hashes, and what is piped to them.
|
|
1359
|
+
"Bash(tr *)",
|
|
1360
|
+
"Bash(stat *)",
|
|
1361
|
+
"Bash(du *)",
|
|
1362
|
+
"Bash(df *)",
|
|
1363
|
+
"Bash(ps *)",
|
|
1364
|
+
"Bash(basename *)",
|
|
1365
|
+
"Bash(dirname *)",
|
|
1366
|
+
"Bash(realpath *)",
|
|
1367
|
+
"Bash(readlink *)",
|
|
1368
|
+
"Bash(md5sum *)",
|
|
1369
|
+
"Bash(sha256sum *)",
|
|
1370
|
+
"Bash(shasum *)",
|
|
1371
|
+
"Bash(seq *)",
|
|
1372
|
+
"Bash(printf *)",
|
|
1373
|
+
"Bash(date *)",
|
|
1374
|
+
"Bash(uname *)",
|
|
1375
|
+
"Bash(whoami)",
|
|
1376
|
+
"Bash(id)",
|
|
1377
|
+
"Bash(type *)",
|
|
1378
|
+
"Bash(command -v *)",
|
|
1379
|
+
"Bash(test *)",
|
|
1302
1380
|
"Bash(true)",
|
|
1303
1381
|
// Starting a dev server and checking it: `cd web && npm run dev`, waiting for it, seeing
|
|
1304
1382
|
// what holds a port. Not `kill`: on the person's own computer the process on a busy port
|
|
@@ -1401,6 +1479,12 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1401
1479
|
`maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
|
|
1402
1480
|
);
|
|
1403
1481
|
}
|
|
1482
|
+
const inherit = file?.inheritClaudeCodePermissions;
|
|
1483
|
+
if (inherit !== void 0 && typeof inherit !== "boolean") {
|
|
1484
|
+
throw new Error(
|
|
1485
|
+
`inheritClaudeCodePermissions in ${paths.configFile} must be true or false (got ${JSON.stringify(inherit)}).`
|
|
1486
|
+
);
|
|
1487
|
+
}
|
|
1404
1488
|
const allowed = [
|
|
1405
1489
|
...file?.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
|
|
1406
1490
|
...file?.extraAllowedTools ?? []
|
|
@@ -1424,6 +1508,8 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1424
1508
|
allowedTools: [...new Set(allowed)],
|
|
1425
1509
|
disallowedTools: [...new Set(disallowed)],
|
|
1426
1510
|
loadProjectSettings: file?.loadProjectSettings === true,
|
|
1511
|
+
// On unless turned off (a value that is not a boolean was refused above).
|
|
1512
|
+
inheritClaudeCodePermissions: inherit !== false,
|
|
1427
1513
|
gitProtocol: file?.gitProtocol === "ssh" ? "ssh" : "https",
|
|
1428
1514
|
idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
|
|
1429
1515
|
stateDir: paths.stateDir,
|
|
@@ -1432,7 +1518,7 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1432
1518
|
}
|
|
1433
1519
|
|
|
1434
1520
|
// src/daemon.ts
|
|
1435
|
-
import { join as
|
|
1521
|
+
import { join as join11 } from "node:path";
|
|
1436
1522
|
|
|
1437
1523
|
// src/backoff.ts
|
|
1438
1524
|
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
@@ -1440,13 +1526,13 @@ function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
|
1440
1526
|
return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
|
|
1441
1527
|
}
|
|
1442
1528
|
function sleep(ms, signal) {
|
|
1443
|
-
return new Promise((
|
|
1444
|
-
if (signal?.aborted) return
|
|
1529
|
+
return new Promise((resolve2) => {
|
|
1530
|
+
if (signal?.aborted) return resolve2();
|
|
1445
1531
|
const timer = setTimeout(done, ms);
|
|
1446
1532
|
function done() {
|
|
1447
1533
|
clearTimeout(timer);
|
|
1448
1534
|
signal?.removeEventListener("abort", done);
|
|
1449
|
-
|
|
1535
|
+
resolve2();
|
|
1450
1536
|
}
|
|
1451
1537
|
signal?.addEventListener("abort", done, { once: true });
|
|
1452
1538
|
});
|
|
@@ -1555,7 +1641,8 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
|
|
|
1555
1641
|
}
|
|
1556
1642
|
|
|
1557
1643
|
// src/session-manager.ts
|
|
1558
|
-
import { mkdir as mkdir6, rm as rm6 } from "node:fs/promises";
|
|
1644
|
+
import { mkdir as mkdir6, rm as rm6, writeFile as writeFile4 } from "node:fs/promises";
|
|
1645
|
+
import { join as join10 } from "node:path";
|
|
1559
1646
|
|
|
1560
1647
|
// src/fsutil.ts
|
|
1561
1648
|
import { mkdir as mkdir4, readFile as readFile3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
|
|
@@ -1632,7 +1719,7 @@ var SessionOutbox = class _SessionOutbox {
|
|
|
1632
1719
|
this.pumpTimer = null;
|
|
1633
1720
|
}
|
|
1634
1721
|
if (this.pending.length && !this.closed) void this.pump();
|
|
1635
|
-
const drained = this.pending.length === 0 || this.closed ? Promise.resolve(true) : new Promise((
|
|
1722
|
+
const drained = this.pending.length === 0 || this.closed ? Promise.resolve(true) : new Promise((resolve2) => this.idleWaiters.push(() => resolve2(true)));
|
|
1636
1723
|
const result = await Promise.race([drained, sleep(timeoutMs).then(() => false)]);
|
|
1637
1724
|
await this.persistChain;
|
|
1638
1725
|
return result || this.pending.length === 0;
|
|
@@ -1809,7 +1896,7 @@ function takeBatch(pending) {
|
|
|
1809
1896
|
// src/session.ts
|
|
1810
1897
|
import { spawn as spawn3 } from "node:child_process";
|
|
1811
1898
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1812
|
-
import { basename, dirname as
|
|
1899
|
+
import { basename, dirname as dirname6 } from "node:path";
|
|
1813
1900
|
import { createInterface } from "node:readline";
|
|
1814
1901
|
|
|
1815
1902
|
// src/permissions.ts
|
|
@@ -2013,7 +2100,7 @@ var PermissionRelay = class {
|
|
|
2013
2100
|
};
|
|
2014
2101
|
|
|
2015
2102
|
// src/tool-grants.ts
|
|
2016
|
-
import { dirname as dirname4, join as join7 } from "node:path";
|
|
2103
|
+
import { dirname as dirname4, join as join7, posix } from "node:path";
|
|
2017
2104
|
var isGrantableDenial = isGrantableToolDenial;
|
|
2018
2105
|
var FILE_TOOLS = /* @__PURE__ */ new Set(["Read", "Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
2019
2106
|
var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);
|
|
@@ -2071,8 +2158,16 @@ function bashRules(command, allowedTools) {
|
|
|
2071
2158
|
head.push(w[1]);
|
|
2072
2159
|
if (RUNNER_WORDS.has(w[1]) && w[2] && WORD.test(w[2]) && !w[2].includes("/")) head.push(w[2]);
|
|
2073
2160
|
}
|
|
2074
|
-
const
|
|
2075
|
-
|
|
2161
|
+
const prefix = `Bash(${head.join(" ")} *)`;
|
|
2162
|
+
const allAllowed = segments.every(
|
|
2163
|
+
(s) => allowedTools.some((rule) => ruleAllows(rule, "Bash", { command: s }))
|
|
2164
|
+
);
|
|
2165
|
+
const exact = command.trim();
|
|
2166
|
+
if ((allAllowed || !grantsCover([prefix], allowedTools, "Bash", { command })) && exact.length <= 400 && !/[\r\n]/.test(exact)) {
|
|
2167
|
+
return same(`Bash(${exact})`);
|
|
2168
|
+
}
|
|
2169
|
+
const once = segment.length <= 400 ? `Bash(${segment})` : prefix;
|
|
2170
|
+
return { suggestedRule: prefix, onceRule: once };
|
|
2076
2171
|
}
|
|
2077
2172
|
function hostOf(url) {
|
|
2078
2173
|
if (!url) return null;
|
|
@@ -2090,26 +2185,131 @@ function rulePath(path) {
|
|
|
2090
2185
|
return path;
|
|
2091
2186
|
}
|
|
2092
2187
|
function parseRule(rule) {
|
|
2093
|
-
const m = /^([A-Za-z][A-Za-z0-9_.-]*)(?:\(([\s\S]*)\))?$/.exec(rule.trim());
|
|
2188
|
+
const m = /^([A-Za-z][A-Za-z0-9_.-]*(?:__\*)?)(?:\(([\s\S]*)\))?$/.exec(rule.trim());
|
|
2094
2189
|
return m ? { tool: m[1], spec: m[2] ?? null } : null;
|
|
2095
2190
|
}
|
|
2096
2191
|
function ruleAllows(rule, toolName, input) {
|
|
2097
2192
|
const parsed = parseRule(rule);
|
|
2098
2193
|
if (!parsed) return false;
|
|
2194
|
+
if (parsed.tool.endsWith("__*")) {
|
|
2195
|
+
return parsed.spec === null && toolName.startsWith(parsed.tool.slice(0, -1));
|
|
2196
|
+
}
|
|
2099
2197
|
const ruleTool = parsed.tool === "Edit" && EDIT_TOOLS.has(toolName) ? toolName : parsed.tool;
|
|
2100
2198
|
if (ruleTool !== toolName) return false;
|
|
2101
2199
|
const i = input && typeof input === "object" ? input : {};
|
|
2102
2200
|
if (parsed.spec === null) return toolName !== "Bash";
|
|
2103
2201
|
if (toolName === "Bash") {
|
|
2104
2202
|
const command = typeof i.command === "string" ? i.command.trim() : "";
|
|
2203
|
+
if (command && parsed.spec.trim() === command) return true;
|
|
2105
2204
|
const segments = shellSegments(command);
|
|
2106
2205
|
return segments.length > 0 && segments.every((s) => shellPatternMatches(parsed.spec, s));
|
|
2107
2206
|
}
|
|
2108
2207
|
if (toolName === "WebFetch" && parsed.spec.startsWith("domain:")) {
|
|
2109
2208
|
return hostOf(typeof i.url === "string" ? i.url : null) === parsed.spec.slice(7).toLowerCase();
|
|
2110
2209
|
}
|
|
2210
|
+
if (FILE_TOOLS.has(toolName)) {
|
|
2211
|
+
const file = typeof i.file_path === "string" ? i.file_path : typeof i.notebook_path === "string" ? i.notebook_path : "";
|
|
2212
|
+
return filePatternMatches(parsed.spec, file);
|
|
2213
|
+
}
|
|
2111
2214
|
return false;
|
|
2112
2215
|
}
|
|
2216
|
+
function hasOpaqueShell(command) {
|
|
2217
|
+
const s = command.replace(/\d*>&\d+/g, " ").replace(/&>\s*\/dev\/null(?![^\s;&|)])/g, " ").replace(/\d*>>?\s*\/dev\/null(?![^\s;&|)])/g, " ").replace(/&&/g, " ");
|
|
2218
|
+
return /\$\(|`|<\(|>\(|>|&/.test(s);
|
|
2219
|
+
}
|
|
2220
|
+
function grantsCover(granted, base, toolName, input) {
|
|
2221
|
+
if (granted.length === 0) return false;
|
|
2222
|
+
if (toolName !== "Bash") return granted.some((rule) => ruleAllows(rule, toolName, input));
|
|
2223
|
+
const i = input && typeof input === "object" ? input : {};
|
|
2224
|
+
const command = typeof i.command === "string" ? i.command.trim() : "";
|
|
2225
|
+
if (!command) return false;
|
|
2226
|
+
const exact = granted.some((rule) => {
|
|
2227
|
+
const parsed = parseRule(rule);
|
|
2228
|
+
return parsed?.tool === "Bash" && parsed.spec !== null && parsed.spec.trim() === command;
|
|
2229
|
+
});
|
|
2230
|
+
if (exact) return true;
|
|
2231
|
+
if (hasOpaqueShell(command)) return false;
|
|
2232
|
+
const segments = shellSegments(command);
|
|
2233
|
+
if (segments.length === 0) return false;
|
|
2234
|
+
let byGrant = false;
|
|
2235
|
+
for (const segment of segments) {
|
|
2236
|
+
const call = { command: segment };
|
|
2237
|
+
if (granted.some((rule) => ruleAllows(rule, "Bash", call))) byGrant = true;
|
|
2238
|
+
else if (!base.some((rule) => ruleAllows(rule, "Bash", call))) return false;
|
|
2239
|
+
}
|
|
2240
|
+
return byGrant;
|
|
2241
|
+
}
|
|
2242
|
+
function askedFor(rules, toolName, input) {
|
|
2243
|
+
if (rules.length === 0) return false;
|
|
2244
|
+
if (rules.some((rule) => rule.trim() === toolName)) return true;
|
|
2245
|
+
if (FILE_TOOLS.has(toolName)) {
|
|
2246
|
+
const family = EDIT_TOOLS.has(toolName) ? "Edit" : toolName;
|
|
2247
|
+
const relative = rules.some((rule) => {
|
|
2248
|
+
const parsed = parseRule(rule);
|
|
2249
|
+
if (!parsed || parsed.spec === null) return false;
|
|
2250
|
+
const tool = EDIT_TOOLS.has(parsed.tool) ? "Edit" : parsed.tool;
|
|
2251
|
+
const spec = parsed.spec.trim();
|
|
2252
|
+
return tool === family && !spec.startsWith("//") && !spec.startsWith("~/");
|
|
2253
|
+
});
|
|
2254
|
+
if (relative) return true;
|
|
2255
|
+
}
|
|
2256
|
+
if (rules.some((rule) => ruleAllows(rule, toolName, input))) return true;
|
|
2257
|
+
if (toolName !== "Bash") return false;
|
|
2258
|
+
const shellRules = rules.filter((rule) => parseRule(rule)?.tool === "Bash");
|
|
2259
|
+
if (shellRules.length === 0) return false;
|
|
2260
|
+
const i = input && typeof input === "object" ? input : {};
|
|
2261
|
+
const command = typeof i.command === "string" ? i.command : "";
|
|
2262
|
+
if (hasOpaqueShell(command) || /\b(?:sh|bash|zsh|dash)\s+-c\b|\beval\b/.test(command)) {
|
|
2263
|
+
return true;
|
|
2264
|
+
}
|
|
2265
|
+
return shellSegments(command).some(
|
|
2266
|
+
(segment) => [segment, unwrapCommand(segment)].some(
|
|
2267
|
+
(cmd) => shellRules.some((rule) => ruleAllows(rule, "Bash", { command: cmd }))
|
|
2268
|
+
)
|
|
2269
|
+
);
|
|
2270
|
+
}
|
|
2271
|
+
var WRAPPERS = {
|
|
2272
|
+
env: /^(?:-\S+|[A-Za-z_]\w*=\S*)$/,
|
|
2273
|
+
nice: /^(?:-n|-\d+|--adjustment=\S+|\d+)$/,
|
|
2274
|
+
timeout: /^(?:-\S+|\d+(?:\.\d+)?[smhd]?)$/,
|
|
2275
|
+
nohup: /^$/,
|
|
2276
|
+
time: /^-\S+$/,
|
|
2277
|
+
command: /^-\S+$/,
|
|
2278
|
+
exec: /^-\S+$/,
|
|
2279
|
+
stdbuf: /^-\S+$/,
|
|
2280
|
+
xargs: /^-\S+$/,
|
|
2281
|
+
sudo: /^-\S+$/
|
|
2282
|
+
};
|
|
2283
|
+
function unwrapCommand(segment) {
|
|
2284
|
+
const words = segment.trim().split(/\s+/);
|
|
2285
|
+
let at = 0;
|
|
2286
|
+
for (; ; ) {
|
|
2287
|
+
while (at < words.length && /^[A-Za-z_]\w*=/.test(words[at])) at++;
|
|
2288
|
+
const wrapper = WRAPPERS[words[at] ?? ""];
|
|
2289
|
+
if (!wrapper) break;
|
|
2290
|
+
at++;
|
|
2291
|
+
while (at < words.length && wrapper.test(words[at])) at++;
|
|
2292
|
+
}
|
|
2293
|
+
return words.slice(at).join(" ");
|
|
2294
|
+
}
|
|
2295
|
+
function filePatternMatches(spec, file) {
|
|
2296
|
+
if (!file) return false;
|
|
2297
|
+
const home = process.env.HOME || process.env.USERPROFILE || "";
|
|
2298
|
+
let pattern = spec.trim();
|
|
2299
|
+
if (pattern.startsWith("~/")) {
|
|
2300
|
+
if (!home) return false;
|
|
2301
|
+
pattern = rulePath(join7(home, pattern.slice(2)).replace(/\\/g, "/"));
|
|
2302
|
+
}
|
|
2303
|
+
if (!pattern.startsWith("//")) return false;
|
|
2304
|
+
const path = rulePath(file);
|
|
2305
|
+
if (!path.startsWith("//")) return false;
|
|
2306
|
+
const normalized = `/${posix.normalize(path.slice(1))}`;
|
|
2307
|
+
if (!normalized.startsWith("//")) return false;
|
|
2308
|
+
const re = pattern.split("**").map(
|
|
2309
|
+
(part) => part.split("*").map((p) => p.replace(/[.+?^${}()|[\]\\]/g, "\\$&")).join("[^/]*")
|
|
2310
|
+
).join(".*");
|
|
2311
|
+
return new RegExp(`^${re}$`, "s").test(normalized);
|
|
2312
|
+
}
|
|
2113
2313
|
function shellPatternMatches(spec, command) {
|
|
2114
2314
|
let pattern = spec.trim();
|
|
2115
2315
|
if (pattern.endsWith(":*")) pattern = `${pattern.slice(0, -2)} *`;
|
|
@@ -2196,6 +2396,198 @@ function isUsableGrant(g) {
|
|
|
2196
2396
|
return !!x && typeof x.id === "string" && typeof x.repository === "string" && typeof x.rule === "string" && toolGrantRuleProblem(x.rule) === null;
|
|
2197
2397
|
}
|
|
2198
2398
|
|
|
2399
|
+
// src/claude-code-rules.ts
|
|
2400
|
+
import { readFile as readFile4, stat as stat3 } from "node:fs/promises";
|
|
2401
|
+
import { homedir as homedir2 } from "node:os";
|
|
2402
|
+
import { dirname as dirname5, isAbsolute as isAbsolute3, join as join8, resolve, sep } from "node:path";
|
|
2403
|
+
var EMPTY = { allow: [], deny: [], ask: [], sources: [] };
|
|
2404
|
+
var RULE_SHAPE2 = /^(?:mcp__[A-Za-z0-9_-]+__\*|[A-Za-z][A-Za-z0-9_.-]*(?:\([\s\S]*\))?)$/;
|
|
2405
|
+
var FILE_TOOLS2 = /* @__PURE__ */ new Set([
|
|
2406
|
+
"Read",
|
|
2407
|
+
"Edit",
|
|
2408
|
+
"Write",
|
|
2409
|
+
"MultiEdit",
|
|
2410
|
+
"NotebookEdit",
|
|
2411
|
+
"Glob",
|
|
2412
|
+
"Grep",
|
|
2413
|
+
"LS"
|
|
2414
|
+
]);
|
|
2415
|
+
function usableRule(raw, kind, committed) {
|
|
2416
|
+
if (typeof raw !== "string") return null;
|
|
2417
|
+
const rule = raw.trim();
|
|
2418
|
+
if (!rule || rule.length > TOOL_GRANT_RULE_MAX_LENGTH) return null;
|
|
2419
|
+
if (/[\u0000-\u001f\u007f]/.test(rule) || !RULE_SHAPE2.test(rule)) return null;
|
|
2420
|
+
const tool = /^([A-Za-z][A-Za-z0-9_.-]*)/.exec(rule)?.[1] ?? "";
|
|
2421
|
+
if (kind === "allow" && FILE_TOOLS2.has(tool)) return null;
|
|
2422
|
+
if (kind === "allow" && committed && toolGrantRuleProblem(rule) !== null) return null;
|
|
2423
|
+
return rule;
|
|
2424
|
+
}
|
|
2425
|
+
function remoteRepositoryKey(url) {
|
|
2426
|
+
const u = url.trim();
|
|
2427
|
+
const ssh = /^(?:ssh:\/\/)?git@github\.com[:/]([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
|
|
2428
|
+
if (ssh) return toolGrantRepositoryKey(`https://github.com/${ssh[1]}/${ssh[2]}`);
|
|
2429
|
+
const https = /^(?:https?|git):\/\/(?:[^@/]+@)?github\.com\/([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/i.exec(u);
|
|
2430
|
+
if (https) return toolGrantRepositoryKey(`https://github.com/${https[1]}/${https[2]}`);
|
|
2431
|
+
return null;
|
|
2432
|
+
}
|
|
2433
|
+
async function readText(file) {
|
|
2434
|
+
try {
|
|
2435
|
+
return await readFile4(file, "utf8");
|
|
2436
|
+
} catch {
|
|
2437
|
+
return null;
|
|
2438
|
+
}
|
|
2439
|
+
}
|
|
2440
|
+
async function readJsonFile(file) {
|
|
2441
|
+
const text = await readText(file);
|
|
2442
|
+
if (text === null) return null;
|
|
2443
|
+
try {
|
|
2444
|
+
return JSON.parse(text);
|
|
2445
|
+
} catch {
|
|
2446
|
+
return null;
|
|
2447
|
+
}
|
|
2448
|
+
}
|
|
2449
|
+
async function isDir(path) {
|
|
2450
|
+
try {
|
|
2451
|
+
return (await stat3(path)).isDirectory();
|
|
2452
|
+
} catch {
|
|
2453
|
+
return false;
|
|
2454
|
+
}
|
|
2455
|
+
}
|
|
2456
|
+
async function gitConfigOf(folder) {
|
|
2457
|
+
let dir = folder;
|
|
2458
|
+
for (let i = 0; i < 6; i++) {
|
|
2459
|
+
const dotGit = join8(dir, ".git");
|
|
2460
|
+
if (await isDir(dotGit)) return { config: join8(dotGit, "config"), roots: [dir] };
|
|
2461
|
+
const pointer = await readText(dotGit);
|
|
2462
|
+
const gitdir = pointer && /^gitdir:\s*(.+)\s*$/m.exec(pointer)?.[1];
|
|
2463
|
+
if (gitdir) {
|
|
2464
|
+
const linked = resolve(dir, gitdir);
|
|
2465
|
+
const common = (await readText(join8(linked, "commondir")))?.trim();
|
|
2466
|
+
const commonDir = common ? resolve(linked, common) : linked;
|
|
2467
|
+
return { config: join8(commonDir, "config"), roots: [dir, dirname5(commonDir)] };
|
|
2468
|
+
}
|
|
2469
|
+
const up = dirname5(dir);
|
|
2470
|
+
if (up === dir) break;
|
|
2471
|
+
dir = up;
|
|
2472
|
+
}
|
|
2473
|
+
return null;
|
|
2474
|
+
}
|
|
2475
|
+
function remoteKeys(config) {
|
|
2476
|
+
const keys = /* @__PURE__ */ new Set();
|
|
2477
|
+
let inRemote = false;
|
|
2478
|
+
for (const line of config.split(/\r?\n/)) {
|
|
2479
|
+
const section = /^\s*\[([^\]]*)\]/.exec(line);
|
|
2480
|
+
if (section) {
|
|
2481
|
+
inRemote = /^remote\s+"/i.test(section[1].trim());
|
|
2482
|
+
continue;
|
|
2483
|
+
}
|
|
2484
|
+
if (!inRemote) continue;
|
|
2485
|
+
const url = /^\s*url\s*=\s*(.+?)\s*$/i.exec(line);
|
|
2486
|
+
const key = url ? remoteRepositoryKey(url[1]) : null;
|
|
2487
|
+
if (key) keys.add(key);
|
|
2488
|
+
}
|
|
2489
|
+
return keys;
|
|
2490
|
+
}
|
|
2491
|
+
function rulesIn(settings, kind, committed) {
|
|
2492
|
+
const perms = settings?.permissions;
|
|
2493
|
+
const list = perms?.[kind];
|
|
2494
|
+
if (!Array.isArray(list)) return [];
|
|
2495
|
+
return list.map((r) => usableRule(r, kind, committed)).filter((r) => r !== null);
|
|
2496
|
+
}
|
|
2497
|
+
var ClaudeCodeRules = class {
|
|
2498
|
+
claudeJson;
|
|
2499
|
+
exclude;
|
|
2500
|
+
cacheMs;
|
|
2501
|
+
cache = /* @__PURE__ */ new Map();
|
|
2502
|
+
constructor(opts = {}) {
|
|
2503
|
+
this.claudeJson = opts.claudeJson ?? (process.env.CLAUDE_CONFIG_DIR ? join8(process.env.CLAUDE_CONFIG_DIR, ".claude.json") : join8(homedir2(), ".claude.json"));
|
|
2504
|
+
this.exclude = (opts.exclude ?? []).map((p) => resolve(p));
|
|
2505
|
+
this.cacheMs = opts.cacheMs ?? 3e4;
|
|
2506
|
+
}
|
|
2507
|
+
/** The rules for a repository URL; none for a session without a GitHub repository. */
|
|
2508
|
+
rulesFor(repositoryUrl) {
|
|
2509
|
+
const key = toolGrantRepositoryKey(repositoryUrl);
|
|
2510
|
+
if (!key) return Promise.resolve(EMPTY);
|
|
2511
|
+
const hit = this.cache.get(key);
|
|
2512
|
+
if (hit && Date.now() - hit.at < this.cacheMs) return hit.rules;
|
|
2513
|
+
const rules = this.read(key).catch(() => EMPTY);
|
|
2514
|
+
this.cache.set(key, { at: Date.now(), rules });
|
|
2515
|
+
return rules;
|
|
2516
|
+
}
|
|
2517
|
+
excluded(folder) {
|
|
2518
|
+
const f = resolve(folder);
|
|
2519
|
+
return this.exclude.some((ex) => f === ex || f.startsWith(ex + sep));
|
|
2520
|
+
}
|
|
2521
|
+
async read(key) {
|
|
2522
|
+
const global = await readJsonFile(this.claudeJson);
|
|
2523
|
+
const projects = global?.projects;
|
|
2524
|
+
if (!projects || typeof projects !== "object") return EMPTY;
|
|
2525
|
+
const allow = /* @__PURE__ */ new Set();
|
|
2526
|
+
const deny = /* @__PURE__ */ new Set();
|
|
2527
|
+
const ask = /* @__PURE__ */ new Set();
|
|
2528
|
+
const sources = [];
|
|
2529
|
+
const checkouts = [];
|
|
2530
|
+
for (const [folder, entry] of Object.entries(projects)) {
|
|
2531
|
+
if (!entry || entry.hasTrustDialogAccepted !== true) continue;
|
|
2532
|
+
if (!isAbsolute3(folder) || this.excluded(folder)) continue;
|
|
2533
|
+
const git2 = await gitConfigOf(folder);
|
|
2534
|
+
const text = git2 ? await readText(git2.config) : null;
|
|
2535
|
+
if (!git2 || !text || !remoteKeys(text).has(key)) continue;
|
|
2536
|
+
const roots = [...new Set([folder, ...git2.roots].map((d) => resolve(d)))];
|
|
2537
|
+
const legacy = Array.isArray(entry.allowedTools) ? entry.allowedTools : [];
|
|
2538
|
+
checkouts.push({ folder, roots, legacy });
|
|
2539
|
+
}
|
|
2540
|
+
for (const { folder, roots, legacy } of checkouts) {
|
|
2541
|
+
const found = [];
|
|
2542
|
+
const denied = [];
|
|
2543
|
+
const asked = [];
|
|
2544
|
+
for (const dir of roots) {
|
|
2545
|
+
const local = await readJsonFile(join8(dir, ".claude", "settings.local.json"));
|
|
2546
|
+
const shared = await readJsonFile(join8(dir, ".claude", "settings.json"));
|
|
2547
|
+
found.push(...rulesIn(local, "allow", false), ...rulesIn(shared, "allow", true));
|
|
2548
|
+
denied.push(...rulesIn(local, "deny", false), ...rulesIn(shared, "deny", false));
|
|
2549
|
+
asked.push(...rulesIn(local, "ask", false), ...rulesIn(shared, "ask", false));
|
|
2550
|
+
}
|
|
2551
|
+
found.push(
|
|
2552
|
+
...legacy.map((r) => usableRule(r, "allow", false)).filter((r) => r !== null)
|
|
2553
|
+
);
|
|
2554
|
+
const kept = found;
|
|
2555
|
+
if (kept.length || denied.length || asked.length) sources.push(folder);
|
|
2556
|
+
for (const r of kept) allow.add(r);
|
|
2557
|
+
for (const r of denied) deny.add(r);
|
|
2558
|
+
for (const r of asked) ask.add(r);
|
|
2559
|
+
}
|
|
2560
|
+
return {
|
|
2561
|
+
allow: [...allow].filter((r) => !deny.has(r) && !ask.has(r)),
|
|
2562
|
+
deny: [...deny],
|
|
2563
|
+
ask: [...ask].filter((r) => !deny.has(r)),
|
|
2564
|
+
sources
|
|
2565
|
+
};
|
|
2566
|
+
}
|
|
2567
|
+
};
|
|
2568
|
+
function ruleHead(rule) {
|
|
2569
|
+
const m = /^([A-Za-z][A-Za-z0-9_.-]*(?:__\*)?)(?:\(([\s\S]*)\))?$/.exec(rule.trim());
|
|
2570
|
+
if (!m) return null;
|
|
2571
|
+
const spec = m[2];
|
|
2572
|
+
if (spec === void 0) return { tool: m[1], head: null };
|
|
2573
|
+
return { tool: m[1], head: spec.replace(/:\*$/, " *").split("*")[0] };
|
|
2574
|
+
}
|
|
2575
|
+
function sameTool(a, b) {
|
|
2576
|
+
if (a === b) return true;
|
|
2577
|
+
const wild = (w, t) => w.endsWith("__*") && t.startsWith(w.slice(0, -1));
|
|
2578
|
+
return wild(a, b) || wild(b, a);
|
|
2579
|
+
}
|
|
2580
|
+
function overlapsAsk(allowRule, askRules) {
|
|
2581
|
+
const a = ruleHead(allowRule);
|
|
2582
|
+
if (!a) return false;
|
|
2583
|
+
return askRules.some((rule) => {
|
|
2584
|
+
const q = ruleHead(rule);
|
|
2585
|
+
if (!q || !sameTool(a.tool, q.tool)) return false;
|
|
2586
|
+
if (a.head === null || q.head === null) return true;
|
|
2587
|
+
return a.head.startsWith(q.head) || q.head.startsWith(a.head);
|
|
2588
|
+
});
|
|
2589
|
+
}
|
|
2590
|
+
|
|
2199
2591
|
// src/pull-request.ts
|
|
2200
2592
|
var PULL_REQUEST_BODY_MAX_CHARS = 6e4;
|
|
2201
2593
|
var GH_TIMEOUT_MS = 6e4;
|
|
@@ -2286,29 +2678,29 @@ function ghError(command, res) {
|
|
|
2286
2678
|
|
|
2287
2679
|
// src/session-store.ts
|
|
2288
2680
|
import { mkdir as mkdir5, readdir as readdir2, rm as rm5 } from "node:fs/promises";
|
|
2289
|
-
import { join as
|
|
2681
|
+
import { join as join9 } from "node:path";
|
|
2290
2682
|
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
2291
2683
|
var SessionStore = class {
|
|
2292
2684
|
constructor(stateDir) {
|
|
2293
2685
|
this.stateDir = stateDir;
|
|
2294
2686
|
}
|
|
2295
2687
|
dir(sessionId) {
|
|
2296
|
-
return
|
|
2688
|
+
return join9(this.stateDir, "sessions", sessionId);
|
|
2297
2689
|
}
|
|
2298
2690
|
outboxFile(sessionId) {
|
|
2299
|
-
return
|
|
2691
|
+
return join9(this.dir(sessionId), "outbox.json");
|
|
2300
2692
|
}
|
|
2301
2693
|
async save(record) {
|
|
2302
2694
|
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2303
|
-
await writeJsonAtomic(
|
|
2695
|
+
await writeJsonAtomic(join9(this.dir(record.sessionId), "session.json"), record);
|
|
2304
2696
|
}
|
|
2305
2697
|
async list() {
|
|
2306
|
-
const root =
|
|
2698
|
+
const root = join9(this.stateDir, "sessions");
|
|
2307
2699
|
await mkdir5(root, { recursive: true });
|
|
2308
2700
|
const out = [];
|
|
2309
2701
|
for (const entry of await readdir2(root, { withFileTypes: true })) {
|
|
2310
2702
|
if (!entry.isDirectory()) continue;
|
|
2311
|
-
const rec = await readJson(
|
|
2703
|
+
const rec = await readJson(join9(root, entry.name, "session.json"));
|
|
2312
2704
|
if (rec?.sessionId === entry.name) out.push(rec);
|
|
2313
2705
|
}
|
|
2314
2706
|
return out;
|
|
@@ -2318,7 +2710,7 @@ var SessionStore = class {
|
|
|
2318
2710
|
}
|
|
2319
2711
|
/** Scratch working directory for a session without a repository. */
|
|
2320
2712
|
scratchDir(sessionId) {
|
|
2321
|
-
return
|
|
2713
|
+
return join9(this.stateDir, "scratch", sessionId);
|
|
2322
2714
|
}
|
|
2323
2715
|
};
|
|
2324
2716
|
function assertSafeSessionId(id) {
|
|
@@ -2567,8 +2959,16 @@ var AgentSession = class {
|
|
|
2567
2959
|
this.record.alwaysAllowedTools = [...this.record.alwaysAllowedTools ?? [], tool];
|
|
2568
2960
|
void this.deps.store.save(this.record).catch(() => void 0);
|
|
2569
2961
|
},
|
|
2570
|
-
|
|
2571
|
-
|
|
2962
|
+
// The call as a whole, with the runner's allow-list covering the parts it already
|
|
2963
|
+
// allows: Claude Code only asks about calls its own rules did not cover.
|
|
2964
|
+
// Never a call the person's own Claude Code says to ask about or deny (`permissions.ask`,
|
|
2965
|
+
// `permissions.deny`), as read now: rules added since Claude Code started are not in its
|
|
2966
|
+
// own lists yet, so such a call is put to the person.
|
|
2967
|
+
grantedByRule: (tool, input) => !askedFor(this.inheritedNow.ask, tool, input) && !askedFor(this.inheritedNow.deny, tool, input) && grantsCover(
|
|
2968
|
+
[...this.record.grantRules ?? [], ...this.savedRulesNow, ...this.inheritedNow.allow],
|
|
2969
|
+
this.deps.allowedTools,
|
|
2970
|
+
tool,
|
|
2971
|
+
input
|
|
2572
2972
|
),
|
|
2573
2973
|
// Only with a repository to save a rule for.
|
|
2574
2974
|
suggestRule: (tool, input) => toolGrantRepositoryKey(this.record.repository) ? suggestRules(tool, input, this.deps.allowedTools)?.suggestedRule ?? null : null,
|
|
@@ -2629,6 +3029,26 @@ var AgentSession = class {
|
|
|
2629
3029
|
deferredMessages = [];
|
|
2630
3030
|
/** The repository's saved rules, read again before each relayed prompt. */
|
|
2631
3031
|
savedRulesNow = [];
|
|
3032
|
+
/** The person's own Claude Code rules for the repository, read again with the saved ones. */
|
|
3033
|
+
inheritedNow = { allow: [], deny: [], ask: [], sources: [] };
|
|
3034
|
+
/** The folders those rules came from, once logged. */
|
|
3035
|
+
loggedInherited = "";
|
|
3036
|
+
/** The person's Claude Code rules for the repository; the last read if it fails. */
|
|
3037
|
+
async readInheritedRules() {
|
|
3038
|
+
try {
|
|
3039
|
+
const rules = await this.deps.inheritedRules?.(this.record.repository) ?? this.inheritedNow;
|
|
3040
|
+
const where = rules.sources.join(", ");
|
|
3041
|
+
if (where && where !== this.loggedInherited) {
|
|
3042
|
+
this.loggedInherited = where;
|
|
3043
|
+
this.deps.logger.info(
|
|
3044
|
+
`session ${this.sessionId}: using your Claude Code permission rules from ${where}: allow ${rules.allow.join(", ") || "none"}; ask ${rules.ask.join(", ") || "none"}; deny ${rules.deny.join(", ") || "none"}`
|
|
3045
|
+
);
|
|
3046
|
+
}
|
|
3047
|
+
return rules;
|
|
3048
|
+
} catch {
|
|
3049
|
+
return this.inheritedNow;
|
|
3050
|
+
}
|
|
3051
|
+
}
|
|
2632
3052
|
/** The repository's saved rules, as the store holds them now; the last read if it fails. */
|
|
2633
3053
|
async readSavedRules() {
|
|
2634
3054
|
try {
|
|
@@ -2759,6 +3179,7 @@ var AgentSession = class {
|
|
|
2759
3179
|
return;
|
|
2760
3180
|
}
|
|
2761
3181
|
this.savedRulesNow = await this.readSavedRules();
|
|
3182
|
+
this.inheritedNow = await this.readInheritedRules();
|
|
2762
3183
|
if (this.permissions.request(ask) === "relayed") {
|
|
2763
3184
|
this.deps.logger.info(
|
|
2764
3185
|
`session ${this.sessionId}: Claude Code asks permission for ${ask.toolName}; waiting for an answer in Discovery Tree`
|
|
@@ -2873,7 +3294,7 @@ var AgentSession = class {
|
|
|
2873
3294
|
const reaped = this.treeReaped;
|
|
2874
3295
|
this.stopping = reason;
|
|
2875
3296
|
this.reapGraceMs = graceMs;
|
|
2876
|
-
const exited = new Promise((
|
|
3297
|
+
const exited = new Promise((resolve2) => this.exitWaiters.push(resolve2));
|
|
2877
3298
|
child.stdin.end();
|
|
2878
3299
|
const timedOut = await raceTimeout(exited, graceMs);
|
|
2879
3300
|
if (timedOut && this.child === child) {
|
|
@@ -2932,7 +3353,7 @@ ${text}`;
|
|
|
2932
3353
|
/** Resolves once the current process has exited (and its exit has been handled). */
|
|
2933
3354
|
waitForExit() {
|
|
2934
3355
|
if (!this.child) return Promise.resolve();
|
|
2935
|
-
return new Promise((
|
|
3356
|
+
return new Promise((resolve2) => this.exitWaiters.push(resolve2));
|
|
2936
3357
|
}
|
|
2937
3358
|
async ensureProcess() {
|
|
2938
3359
|
while (this.child && (this.stopping || this.resumeDoomed)) await this.waitForExit();
|
|
@@ -2940,17 +3361,29 @@ ${text}`;
|
|
|
2940
3361
|
await this.prepareEvidenceDir();
|
|
2941
3362
|
const { bin, features } = await this.deps.claude();
|
|
2942
3363
|
const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
|
|
2943
|
-
|
|
2944
|
-
|
|
3364
|
+
this.inheritedNow = await this.readInheritedRules();
|
|
3365
|
+
const ask = this.inheritedNow.ask;
|
|
3366
|
+
const assembled = [
|
|
3367
|
+
.../* @__PURE__ */ new Set([
|
|
3368
|
+
...this.deps.allowedTools,
|
|
3369
|
+
...this.inheritedNow.allow,
|
|
3370
|
+
...savedRules,
|
|
3371
|
+
...this.record.grantRules ?? []
|
|
3372
|
+
])
|
|
3373
|
+
];
|
|
3374
|
+
const allowedTools = features.settingsFlag || ask.length === 0 ? assembled : assembled.filter((r) => !overlapsAsk(r, ask));
|
|
3375
|
+
const disallowedTools = [
|
|
3376
|
+
.../* @__PURE__ */ new Set([...this.deps.disallowedTools ?? [], ...this.inheritedNow.deny])
|
|
2945
3377
|
];
|
|
2946
3378
|
const args = claudeArgs({
|
|
2947
3379
|
permissionMode: this.deps.permissionMode,
|
|
2948
3380
|
allowedTools,
|
|
2949
|
-
disallowedTools
|
|
3381
|
+
disallowedTools,
|
|
2950
3382
|
loadProjectSettings: this.deps.loadProjectSettings,
|
|
2951
3383
|
model: this.record.model,
|
|
2952
3384
|
resume: this.record.claudeSessionId,
|
|
2953
3385
|
relayPermissions: !!this.record.relayPermissionRequests,
|
|
3386
|
+
askTools: ask,
|
|
2954
3387
|
appendSystemPrompt: runnerSystemPrompt({
|
|
2955
3388
|
workBranch: this.record.workBranch,
|
|
2956
3389
|
baseRef: this.record.baseRef,
|
|
@@ -2968,10 +3401,10 @@ ${text}`;
|
|
|
2968
3401
|
detached: OWN_PROCESS_GROUP
|
|
2969
3402
|
});
|
|
2970
3403
|
let tree = null;
|
|
2971
|
-
await new Promise((
|
|
3404
|
+
await new Promise((resolve2, reject) => {
|
|
2972
3405
|
child.once("spawn", () => {
|
|
2973
3406
|
tree = trackTree(child, this.record.cwd || void 0);
|
|
2974
|
-
|
|
3407
|
+
resolve2();
|
|
2975
3408
|
});
|
|
2976
3409
|
child.once(
|
|
2977
3410
|
"error",
|
|
@@ -2991,7 +3424,7 @@ ${text}`;
|
|
|
2991
3424
|
{ pid: child.pid }
|
|
2992
3425
|
);
|
|
2993
3426
|
this.treeReaped = new Promise(
|
|
2994
|
-
(
|
|
3427
|
+
(resolve2) => child.once("exit", () => void reapTree(tree, this.reapGraceMs, this.deps.reap).then(resolve2))
|
|
2995
3428
|
);
|
|
2996
3429
|
child.stdin.on("error", () => void 0);
|
|
2997
3430
|
child.stderr.setEncoding("utf8").on("data", (d) => {
|
|
@@ -3219,7 +3652,7 @@ ${text}`;
|
|
|
3219
3652
|
async publishScreenshots() {
|
|
3220
3653
|
const { workBranch, repoDir, cwd, repository } = this.record;
|
|
3221
3654
|
const repo = parseRepoUrl(
|
|
3222
|
-
repository ?? (repoDir ? `https://github.com/${basename(
|
|
3655
|
+
repository ?? (repoDir ? `https://github.com/${basename(dirname6(repoDir))}/${basename(repoDir)}` : "")
|
|
3223
3656
|
);
|
|
3224
3657
|
if (!workBranch || !repoDir || !repo) return "";
|
|
3225
3658
|
const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
|
|
@@ -3383,8 +3816,8 @@ function startupHint(stderr) {
|
|
|
3383
3816
|
}
|
|
3384
3817
|
async function raceTimeout(done, ms) {
|
|
3385
3818
|
let timer;
|
|
3386
|
-
const timeout = new Promise((
|
|
3387
|
-
timer = setTimeout(() =>
|
|
3819
|
+
const timeout = new Promise((resolve2) => {
|
|
3820
|
+
timer = setTimeout(() => resolve2(true), ms);
|
|
3388
3821
|
});
|
|
3389
3822
|
try {
|
|
3390
3823
|
return await Promise.race([done.then(() => false), timeout]);
|
|
@@ -3624,6 +4057,10 @@ var SessionManager = class {
|
|
|
3624
4057
|
resume ? safeWorktreeKey(resume.worktreeKey, cmd.sessionId) : cmd.sessionId
|
|
3625
4058
|
);
|
|
3626
4059
|
await mkdir6(record.cwd, { recursive: true });
|
|
4060
|
+
const deliverable = resume?.deliverable;
|
|
4061
|
+
if (typeof deliverable === "string" && deliverable.trim()) {
|
|
4062
|
+
await writeFile4(join10(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
|
|
4063
|
+
}
|
|
3627
4064
|
}
|
|
3628
4065
|
if (resume) {
|
|
3629
4066
|
record.claudeSessionId = resume.claudeSessionId?.trim() || null;
|
|
@@ -3884,7 +4321,8 @@ var SessionManager = class {
|
|
|
3884
4321
|
onClaudeSignIn: this.opts.onClaudeSignIn,
|
|
3885
4322
|
openPullRequest: this.opts.openPullRequest,
|
|
3886
4323
|
permissionTimeoutMs: this.opts.permissionTimeoutMs,
|
|
3887
|
-
savedRules: async (url) => this.opts.grants ? await this.opts.grants.rulesFor(url) : []
|
|
4324
|
+
savedRules: async (url) => this.opts.grants ? await this.opts.grants.rulesFor(url) : [],
|
|
4325
|
+
inheritedRules: this.opts.inherited ? (url) => this.opts.inherited.rulesFor(url) : void 0
|
|
3888
4326
|
});
|
|
3889
4327
|
}
|
|
3890
4328
|
};
|
|
@@ -3918,8 +4356,9 @@ function safeWorktreeKey(key, fallback) {
|
|
|
3918
4356
|
function continuationPreface(cmd) {
|
|
3919
4357
|
const branch = cmd.repository?.workBranch;
|
|
3920
4358
|
const task = cmd.prompt.trim();
|
|
4359
|
+
const deliverable = !branch && !!cmd.resume?.deliverable?.trim();
|
|
3921
4360
|
return [
|
|
3922
|
-
branch ? `You are continuing earlier work on the branch ${branch}, which is checked out here with everything done so far. The earlier conversation could not be restored; read the branch's commits (git log, git diff against the base) for what was done.` : "You are continuing earlier work in this directory. The earlier conversation could not be restored.",
|
|
4361
|
+
branch ? `You are continuing earlier work on the branch ${branch}, which is checked out here with everything done so far. The earlier conversation could not be restored; read the branch's commits (git log, git diff against the base) for what was done.` : deliverable ? `You are continuing earlier work on this task. The earlier conversation could not be restored. What you delivered last is in ${RUNNER_DELIVERABLE_FILE} in this directory, in full: read all of it before you revise it.` : "You are continuing earlier work in this directory. The earlier conversation could not be restored.",
|
|
3923
4362
|
task ? `The original task was:
|
|
3924
4363
|
|
|
3925
4364
|
${task.slice(0, 2e4)}` : "",
|
|
@@ -3949,6 +4388,10 @@ var RunnerDaemon = class {
|
|
|
3949
4388
|
onUnauthorized: (err) => this.unauthorized(err),
|
|
3950
4389
|
onClaudeSignIn: (ok) => this.claudeSignIn(ok),
|
|
3951
4390
|
grants: this.grants,
|
|
4391
|
+
// What the person already allows in their own Claude Code for a repository.
|
|
4392
|
+
inherited: opts.config.inheritClaudeCodePermissions ? new ClaudeCodeRules({
|
|
4393
|
+
exclude: [opts.config.reposDir, opts.config.worktreesDir]
|
|
4394
|
+
}) : void 0,
|
|
3952
4395
|
...opts.managerOverrides
|
|
3953
4396
|
});
|
|
3954
4397
|
}
|
|
@@ -4080,7 +4523,9 @@ var RunnerDaemon = class {
|
|
|
4080
4523
|
// And relays Claude Code's permission prompts (`relayPermissionRequests`).
|
|
4081
4524
|
relaysPermissionRequests: true,
|
|
4082
4525
|
// And reports denied tool calls, takes grants on them, and keeps saved rules.
|
|
4083
|
-
grantsToolPermissions: true
|
|
4526
|
+
grantsToolPermissions: true,
|
|
4527
|
+
// And keeps a continued non-code run's deliverable whole (`resume.deliverable`).
|
|
4528
|
+
receivesDeliverable: true
|
|
4084
4529
|
},
|
|
4085
4530
|
activeSessionIds: this.heartbeatSessionIds(),
|
|
4086
4531
|
maxConcurrentSessions: this.opts.config.maxSessions,
|
|
@@ -4189,7 +4634,7 @@ var RunnerDaemon = class {
|
|
|
4189
4634
|
if (this.droppedSessionIds.has(id)) return;
|
|
4190
4635
|
this.droppedSessionIds.add(id);
|
|
4191
4636
|
this.opts.logger.warn(
|
|
4192
|
-
`session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${
|
|
4637
|
+
`session ${id}: not a Discovery Tree session id, so it is left out of the heartbeat (its state is in ${join11(this.opts.config.stateDir, "sessions", id)})`
|
|
4193
4638
|
);
|
|
4194
4639
|
});
|
|
4195
4640
|
}
|
|
@@ -4232,15 +4677,15 @@ var RunnerDaemon = class {
|
|
|
4232
4677
|
this.completionsRunning++;
|
|
4233
4678
|
return Promise.resolve(true);
|
|
4234
4679
|
}
|
|
4235
|
-
return new Promise((
|
|
4680
|
+
return new Promise((resolve2) => {
|
|
4236
4681
|
const handOver = () => {
|
|
4237
4682
|
cancelled.removeEventListener("abort", leave);
|
|
4238
|
-
|
|
4683
|
+
resolve2(true);
|
|
4239
4684
|
};
|
|
4240
4685
|
const leave = () => {
|
|
4241
4686
|
const at = this.completionWaiters.indexOf(handOver);
|
|
4242
4687
|
if (at >= 0) this.completionWaiters.splice(at, 1);
|
|
4243
|
-
|
|
4688
|
+
resolve2(false);
|
|
4244
4689
|
};
|
|
4245
4690
|
this.completionWaiters.push(handOver);
|
|
4246
4691
|
cancelled.addEventListener("abort", leave, { once: true });
|
|
@@ -4417,10 +4862,10 @@ function formatChecks(checks) {
|
|
|
4417
4862
|
}
|
|
4418
4863
|
|
|
4419
4864
|
// src/lock.ts
|
|
4420
|
-
import { mkdir as mkdir7, open, readFile as
|
|
4421
|
-
import { join as
|
|
4865
|
+
import { mkdir as mkdir7, open, readFile as readFile5, rm as rm7 } from "node:fs/promises";
|
|
4866
|
+
import { join as join12 } from "node:path";
|
|
4422
4867
|
function lockFile(stateDir) {
|
|
4423
|
-
return
|
|
4868
|
+
return join12(stateDir, "daemon.pid");
|
|
4424
4869
|
}
|
|
4425
4870
|
function pidAlive(pid) {
|
|
4426
4871
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
@@ -4434,7 +4879,7 @@ function pidAlive(pid) {
|
|
|
4434
4879
|
async function lockHolder(stateDir) {
|
|
4435
4880
|
let raw;
|
|
4436
4881
|
try {
|
|
4437
|
-
raw = await
|
|
4882
|
+
raw = await readFile5(lockFile(stateDir), "utf8");
|
|
4438
4883
|
} catch {
|
|
4439
4884
|
return null;
|
|
4440
4885
|
}
|
|
@@ -4458,7 +4903,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
|
4458
4903
|
lock: {
|
|
4459
4904
|
file,
|
|
4460
4905
|
async release() {
|
|
4461
|
-
const current = await
|
|
4906
|
+
const current = await readFile5(file, "utf8").catch(() => "");
|
|
4462
4907
|
if (Number.parseInt(current.trim(), 10) === pid) await rm7(file, { force: true });
|
|
4463
4908
|
}
|
|
4464
4909
|
}
|
|
@@ -4466,7 +4911,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
|
4466
4911
|
} catch (err) {
|
|
4467
4912
|
if (err.code !== "EEXIST") throw err;
|
|
4468
4913
|
}
|
|
4469
|
-
const raw = await
|
|
4914
|
+
const raw = await readFile5(file, "utf8").catch(() => null);
|
|
4470
4915
|
if (raw === null) continue;
|
|
4471
4916
|
const holder = Number.parseInt(raw.trim(), 10);
|
|
4472
4917
|
if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
|
package/package.json
CHANGED