@discovery-tree/runner 0.1.13 → 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 +426 -52
- 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
|
@@ -110,7 +110,7 @@ function toolGrantRepositoryKey(url) {
|
|
|
110
110
|
}
|
|
111
111
|
|
|
112
112
|
// src/version.ts
|
|
113
|
-
var RUNNER_VERSION = true ? "0.1.
|
|
113
|
+
var RUNNER_VERSION = true ? "0.1.14" : "0.0.0-dev";
|
|
114
114
|
var RUNNER_PLATFORM = `${process.platform}-${process.arch}`;
|
|
115
115
|
|
|
116
116
|
// src/api.ts
|
|
@@ -370,7 +370,7 @@ function namesPathIn(commandLine, dir) {
|
|
|
370
370
|
}
|
|
371
371
|
function listWindowsProcesses() {
|
|
372
372
|
const script = `$ErrorActionPreference='SilentlyContinue';Get-CimInstance Win32_Process | ForEach-Object { if ($_.CreationDate) { "$($_.ProcessId) $($_.ParentProcessId) $(([DateTimeOffset]$_.CreationDate).ToUnixTimeMilliseconds()) $($_.CommandLine -replace "[\\r\\n]", " ")" } }`;
|
|
373
|
-
return new Promise((
|
|
373
|
+
return new Promise((resolve2, reject) => {
|
|
374
374
|
const ps = spawn(
|
|
375
375
|
"powershell.exe",
|
|
376
376
|
["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script],
|
|
@@ -385,7 +385,7 @@ function listWindowsProcesses() {
|
|
|
385
385
|
});
|
|
386
386
|
ps.on("close", () => {
|
|
387
387
|
clearTimeout(timer);
|
|
388
|
-
|
|
388
|
+
resolve2(parseProcessRows(out));
|
|
389
389
|
});
|
|
390
390
|
});
|
|
391
391
|
}
|
|
@@ -407,10 +407,10 @@ function parseProcessRows(text) {
|
|
|
407
407
|
async function taskkillTrees(pids) {
|
|
408
408
|
for (let i = 0; i < pids.length; i += 50) {
|
|
409
409
|
const args = pids.slice(i, i + 50).flatMap((p) => ["/pid", String(p)]);
|
|
410
|
-
await new Promise((
|
|
410
|
+
await new Promise((resolve2) => {
|
|
411
411
|
const tk = spawn("taskkill", [...args, "/T", "/F"], { stdio: "ignore", windowsHide: true });
|
|
412
|
-
tk.on("error", () =>
|
|
413
|
-
tk.on("close", () =>
|
|
412
|
+
tk.on("error", () => resolve2());
|
|
413
|
+
tk.on("close", () => resolve2());
|
|
414
414
|
});
|
|
415
415
|
}
|
|
416
416
|
}
|
|
@@ -425,7 +425,7 @@ function signalGroup(pgid, signal) {
|
|
|
425
425
|
|
|
426
426
|
// src/exec.ts
|
|
427
427
|
function exec(cmd, args, opts = {}) {
|
|
428
|
-
return new Promise((
|
|
428
|
+
return new Promise((resolve2, reject) => {
|
|
429
429
|
const child = spawn2(cmd, args, {
|
|
430
430
|
cwd: opts.cwd,
|
|
431
431
|
env: opts.env ?? process.env,
|
|
@@ -460,7 +460,7 @@ function exec(cmd, args, opts = {}) {
|
|
|
460
460
|
child.on("close", (code) => {
|
|
461
461
|
if (timer) clearTimeout(timer);
|
|
462
462
|
opts.signal?.removeEventListener("abort", onAbort);
|
|
463
|
-
void reaped.then(() =>
|
|
463
|
+
void reaped.then(() => resolve2({ code, stdout, stderr }));
|
|
464
464
|
});
|
|
465
465
|
child.stdin.on("error", () => void 0);
|
|
466
466
|
child.stdin.end(opts.input ?? "");
|
|
@@ -860,10 +860,10 @@ async function ensureEvidenceDir(worktree) {
|
|
|
860
860
|
}
|
|
861
861
|
if (current.split("\n").some((l) => l.trim() === line)) return;
|
|
862
862
|
await mkdir2(join3(file, ".."), { recursive: true });
|
|
863
|
-
const
|
|
863
|
+
const sep2 = current && !current.endsWith("\n") ? "\n" : "";
|
|
864
864
|
await writeFile(
|
|
865
865
|
file,
|
|
866
|
-
`${current}${
|
|
866
|
+
`${current}${sep2}# Screenshots dt-runner publishes on their own branch
|
|
867
867
|
${line}
|
|
868
868
|
`
|
|
869
869
|
);
|
|
@@ -1051,7 +1051,8 @@ async function claudeFeatures(bin) {
|
|
|
1051
1051
|
settingSources: res.stdout.includes("--setting-sources"),
|
|
1052
1052
|
maxTurns: res.stdout.includes("--max-turns"),
|
|
1053
1053
|
strictMcpConfig: res.stdout.includes("--strict-mcp-config"),
|
|
1054
|
-
permissionPromptTool: res.stdout.includes("--permission-prompt-tool")
|
|
1054
|
+
permissionPromptTool: res.stdout.includes("--permission-prompt-tool"),
|
|
1055
|
+
settingsFlag: /--settings <file-or-json>/.test(res.stdout)
|
|
1055
1056
|
};
|
|
1056
1057
|
} catch {
|
|
1057
1058
|
return {
|
|
@@ -1059,7 +1060,8 @@ async function claudeFeatures(bin) {
|
|
|
1059
1060
|
settingSources: false,
|
|
1060
1061
|
maxTurns: false,
|
|
1061
1062
|
strictMcpConfig: false,
|
|
1062
|
-
permissionPromptTool: false
|
|
1063
|
+
permissionPromptTool: false,
|
|
1064
|
+
settingsFlag: false
|
|
1063
1065
|
};
|
|
1064
1066
|
}
|
|
1065
1067
|
}
|
|
@@ -1146,6 +1148,9 @@ function claudeArgs(launch) {
|
|
|
1146
1148
|
}
|
|
1147
1149
|
if (launch.resume) args.push("--resume", launch.resume);
|
|
1148
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
|
+
}
|
|
1149
1154
|
if (launch.disallowedTools?.length) args.push("--disallowedTools", ...launch.disallowedTools);
|
|
1150
1155
|
if (launch.allowedTools.length) args.push("--allowedTools", ...launch.allowedTools);
|
|
1151
1156
|
return args;
|
|
@@ -1262,6 +1267,31 @@ var DEFAULT_ALLOWED_TOOLS = [
|
|
|
1262
1267
|
"Bash(git stash *)",
|
|
1263
1268
|
"Bash(git blame *)",
|
|
1264
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 *)",
|
|
1265
1295
|
"Bash(gh pr view *)",
|
|
1266
1296
|
"Bash(gh pr diff *)",
|
|
1267
1297
|
"Bash(gh pr checks *)",
|
|
@@ -1285,6 +1315,29 @@ var DEFAULT_ALLOWED_TOOLS = [
|
|
|
1285
1315
|
"Bash(make *)",
|
|
1286
1316
|
"Bash(cargo *)",
|
|
1287
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 *)",
|
|
1288
1341
|
"Bash(ls *)",
|
|
1289
1342
|
"Bash(cat *)",
|
|
1290
1343
|
"Bash(head *)",
|
|
@@ -1300,6 +1353,30 @@ var DEFAULT_ALLOWED_TOOLS = [
|
|
|
1300
1353
|
"Bash(sort *)",
|
|
1301
1354
|
"Bash(uniq *)",
|
|
1302
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 *)",
|
|
1303
1380
|
"Bash(true)",
|
|
1304
1381
|
// Starting a dev server and checking it: `cd web && npm run dev`, waiting for it, seeing
|
|
1305
1382
|
// what holds a port. Not `kill`: on the person's own computer the process on a busy port
|
|
@@ -1402,6 +1479,12 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1402
1479
|
`maxSessions must be a whole number from 1 to ${MAX_SESSIONS_LIMIT} (got ${maxSessions}).`
|
|
1403
1480
|
);
|
|
1404
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
|
+
}
|
|
1405
1488
|
const allowed = [
|
|
1406
1489
|
...file?.allowedTools ?? DEFAULT_ALLOWED_TOOLS,
|
|
1407
1490
|
...file?.extraAllowedTools ?? []
|
|
@@ -1425,6 +1508,8 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1425
1508
|
allowedTools: [...new Set(allowed)],
|
|
1426
1509
|
disallowedTools: [...new Set(disallowed)],
|
|
1427
1510
|
loadProjectSettings: file?.loadProjectSettings === true,
|
|
1511
|
+
// On unless turned off (a value that is not a boolean was refused above).
|
|
1512
|
+
inheritClaudeCodePermissions: inherit !== false,
|
|
1428
1513
|
gitProtocol: file?.gitProtocol === "ssh" ? "ssh" : "https",
|
|
1429
1514
|
idleTimeoutMs: (file?.idleTimeoutMinutes ?? DEFAULT_IDLE_TIMEOUT_MINUTES) * 6e4,
|
|
1430
1515
|
stateDir: paths.stateDir,
|
|
@@ -1433,7 +1518,7 @@ function resolveConfig(file, overrides = {}, env = process.env, paths = runnerPa
|
|
|
1433
1518
|
}
|
|
1434
1519
|
|
|
1435
1520
|
// src/daemon.ts
|
|
1436
|
-
import { join as
|
|
1521
|
+
import { join as join11 } from "node:path";
|
|
1437
1522
|
|
|
1438
1523
|
// src/backoff.ts
|
|
1439
1524
|
function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
@@ -1441,13 +1526,13 @@ function backoffDelay(attempt, baseMs = 1e3, maxMs = 6e4) {
|
|
|
1441
1526
|
return Math.round(ceiling / 2 + Math.random() * ceiling / 2);
|
|
1442
1527
|
}
|
|
1443
1528
|
function sleep(ms, signal) {
|
|
1444
|
-
return new Promise((
|
|
1445
|
-
if (signal?.aborted) return
|
|
1529
|
+
return new Promise((resolve2) => {
|
|
1530
|
+
if (signal?.aborted) return resolve2();
|
|
1446
1531
|
const timer = setTimeout(done, ms);
|
|
1447
1532
|
function done() {
|
|
1448
1533
|
clearTimeout(timer);
|
|
1449
1534
|
signal?.removeEventListener("abort", done);
|
|
1450
|
-
|
|
1535
|
+
resolve2();
|
|
1451
1536
|
}
|
|
1452
1537
|
signal?.addEventListener("abort", done, { once: true });
|
|
1453
1538
|
});
|
|
@@ -1557,7 +1642,7 @@ function reportableSessionIds(ids, onDropped = () => void 0) {
|
|
|
1557
1642
|
|
|
1558
1643
|
// src/session-manager.ts
|
|
1559
1644
|
import { mkdir as mkdir6, rm as rm6, writeFile as writeFile4 } from "node:fs/promises";
|
|
1560
|
-
import { join as
|
|
1645
|
+
import { join as join10 } from "node:path";
|
|
1561
1646
|
|
|
1562
1647
|
// src/fsutil.ts
|
|
1563
1648
|
import { mkdir as mkdir4, readFile as readFile3, rename as rename2, writeFile as writeFile3 } from "node:fs/promises";
|
|
@@ -1634,7 +1719,7 @@ var SessionOutbox = class _SessionOutbox {
|
|
|
1634
1719
|
this.pumpTimer = null;
|
|
1635
1720
|
}
|
|
1636
1721
|
if (this.pending.length && !this.closed) void this.pump();
|
|
1637
|
-
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)));
|
|
1638
1723
|
const result = await Promise.race([drained, sleep(timeoutMs).then(() => false)]);
|
|
1639
1724
|
await this.persistChain;
|
|
1640
1725
|
return result || this.pending.length === 0;
|
|
@@ -1811,7 +1896,7 @@ function takeBatch(pending) {
|
|
|
1811
1896
|
// src/session.ts
|
|
1812
1897
|
import { spawn as spawn3 } from "node:child_process";
|
|
1813
1898
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1814
|
-
import { basename, dirname as
|
|
1899
|
+
import { basename, dirname as dirname6 } from "node:path";
|
|
1815
1900
|
import { createInterface } from "node:readline";
|
|
1816
1901
|
|
|
1817
1902
|
// src/permissions.ts
|
|
@@ -2100,12 +2185,15 @@ function rulePath(path) {
|
|
|
2100
2185
|
return path;
|
|
2101
2186
|
}
|
|
2102
2187
|
function parseRule(rule) {
|
|
2103
|
-
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());
|
|
2104
2189
|
return m ? { tool: m[1], spec: m[2] ?? null } : null;
|
|
2105
2190
|
}
|
|
2106
2191
|
function ruleAllows(rule, toolName, input) {
|
|
2107
2192
|
const parsed = parseRule(rule);
|
|
2108
2193
|
if (!parsed) return false;
|
|
2194
|
+
if (parsed.tool.endsWith("__*")) {
|
|
2195
|
+
return parsed.spec === null && toolName.startsWith(parsed.tool.slice(0, -1));
|
|
2196
|
+
}
|
|
2109
2197
|
const ruleTool = parsed.tool === "Edit" && EDIT_TOOLS.has(toolName) ? toolName : parsed.tool;
|
|
2110
2198
|
if (ruleTool !== toolName) return false;
|
|
2111
2199
|
const i = input && typeof input === "object" ? input : {};
|
|
@@ -2151,6 +2239,59 @@ function grantsCover(granted, base, toolName, input) {
|
|
|
2151
2239
|
}
|
|
2152
2240
|
return byGrant;
|
|
2153
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
|
+
}
|
|
2154
2295
|
function filePatternMatches(spec, file) {
|
|
2155
2296
|
if (!file) return false;
|
|
2156
2297
|
const home = process.env.HOME || process.env.USERPROFILE || "";
|
|
@@ -2255,6 +2396,198 @@ function isUsableGrant(g) {
|
|
|
2255
2396
|
return !!x && typeof x.id === "string" && typeof x.repository === "string" && typeof x.rule === "string" && toolGrantRuleProblem(x.rule) === null;
|
|
2256
2397
|
}
|
|
2257
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
|
+
|
|
2258
2591
|
// src/pull-request.ts
|
|
2259
2592
|
var PULL_REQUEST_BODY_MAX_CHARS = 6e4;
|
|
2260
2593
|
var GH_TIMEOUT_MS = 6e4;
|
|
@@ -2345,29 +2678,29 @@ function ghError(command, res) {
|
|
|
2345
2678
|
|
|
2346
2679
|
// src/session-store.ts
|
|
2347
2680
|
import { mkdir as mkdir5, readdir as readdir2, rm as rm5 } from "node:fs/promises";
|
|
2348
|
-
import { join as
|
|
2681
|
+
import { join as join9 } from "node:path";
|
|
2349
2682
|
var HANDLED_COMMAND_IDS_KEPT = 100;
|
|
2350
2683
|
var SessionStore = class {
|
|
2351
2684
|
constructor(stateDir) {
|
|
2352
2685
|
this.stateDir = stateDir;
|
|
2353
2686
|
}
|
|
2354
2687
|
dir(sessionId) {
|
|
2355
|
-
return
|
|
2688
|
+
return join9(this.stateDir, "sessions", sessionId);
|
|
2356
2689
|
}
|
|
2357
2690
|
outboxFile(sessionId) {
|
|
2358
|
-
return
|
|
2691
|
+
return join9(this.dir(sessionId), "outbox.json");
|
|
2359
2692
|
}
|
|
2360
2693
|
async save(record) {
|
|
2361
2694
|
record.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
2362
|
-
await writeJsonAtomic(
|
|
2695
|
+
await writeJsonAtomic(join9(this.dir(record.sessionId), "session.json"), record);
|
|
2363
2696
|
}
|
|
2364
2697
|
async list() {
|
|
2365
|
-
const root =
|
|
2698
|
+
const root = join9(this.stateDir, "sessions");
|
|
2366
2699
|
await mkdir5(root, { recursive: true });
|
|
2367
2700
|
const out = [];
|
|
2368
2701
|
for (const entry of await readdir2(root, { withFileTypes: true })) {
|
|
2369
2702
|
if (!entry.isDirectory()) continue;
|
|
2370
|
-
const rec = await readJson(
|
|
2703
|
+
const rec = await readJson(join9(root, entry.name, "session.json"));
|
|
2371
2704
|
if (rec?.sessionId === entry.name) out.push(rec);
|
|
2372
2705
|
}
|
|
2373
2706
|
return out;
|
|
@@ -2377,7 +2710,7 @@ var SessionStore = class {
|
|
|
2377
2710
|
}
|
|
2378
2711
|
/** Scratch working directory for a session without a repository. */
|
|
2379
2712
|
scratchDir(sessionId) {
|
|
2380
|
-
return
|
|
2713
|
+
return join9(this.stateDir, "scratch", sessionId);
|
|
2381
2714
|
}
|
|
2382
2715
|
};
|
|
2383
2716
|
function assertSafeSessionId(id) {
|
|
@@ -2628,8 +2961,11 @@ var AgentSession = class {
|
|
|
2628
2961
|
},
|
|
2629
2962
|
// The call as a whole, with the runner's allow-list covering the parts it already
|
|
2630
2963
|
// allows: Claude Code only asks about calls its own rules did not cover.
|
|
2631
|
-
|
|
2632
|
-
|
|
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],
|
|
2633
2969
|
this.deps.allowedTools,
|
|
2634
2970
|
tool,
|
|
2635
2971
|
input
|
|
@@ -2693,6 +3029,26 @@ var AgentSession = class {
|
|
|
2693
3029
|
deferredMessages = [];
|
|
2694
3030
|
/** The repository's saved rules, read again before each relayed prompt. */
|
|
2695
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
|
+
}
|
|
2696
3052
|
/** The repository's saved rules, as the store holds them now; the last read if it fails. */
|
|
2697
3053
|
async readSavedRules() {
|
|
2698
3054
|
try {
|
|
@@ -2823,6 +3179,7 @@ var AgentSession = class {
|
|
|
2823
3179
|
return;
|
|
2824
3180
|
}
|
|
2825
3181
|
this.savedRulesNow = await this.readSavedRules();
|
|
3182
|
+
this.inheritedNow = await this.readInheritedRules();
|
|
2826
3183
|
if (this.permissions.request(ask) === "relayed") {
|
|
2827
3184
|
this.deps.logger.info(
|
|
2828
3185
|
`session ${this.sessionId}: Claude Code asks permission for ${ask.toolName}; waiting for an answer in Discovery Tree`
|
|
@@ -2937,7 +3294,7 @@ var AgentSession = class {
|
|
|
2937
3294
|
const reaped = this.treeReaped;
|
|
2938
3295
|
this.stopping = reason;
|
|
2939
3296
|
this.reapGraceMs = graceMs;
|
|
2940
|
-
const exited = new Promise((
|
|
3297
|
+
const exited = new Promise((resolve2) => this.exitWaiters.push(resolve2));
|
|
2941
3298
|
child.stdin.end();
|
|
2942
3299
|
const timedOut = await raceTimeout(exited, graceMs);
|
|
2943
3300
|
if (timedOut && this.child === child) {
|
|
@@ -2996,7 +3353,7 @@ ${text}`;
|
|
|
2996
3353
|
/** Resolves once the current process has exited (and its exit has been handled). */
|
|
2997
3354
|
waitForExit() {
|
|
2998
3355
|
if (!this.child) return Promise.resolve();
|
|
2999
|
-
return new Promise((
|
|
3356
|
+
return new Promise((resolve2) => this.exitWaiters.push(resolve2));
|
|
3000
3357
|
}
|
|
3001
3358
|
async ensureProcess() {
|
|
3002
3359
|
while (this.child && (this.stopping || this.resumeDoomed)) await this.waitForExit();
|
|
@@ -3004,17 +3361,29 @@ ${text}`;
|
|
|
3004
3361
|
await this.prepareEvidenceDir();
|
|
3005
3362
|
const { bin, features } = await this.deps.claude();
|
|
3006
3363
|
const savedRules = await (this.deps.savedRules?.(this.record.repository) ?? []);
|
|
3007
|
-
|
|
3008
|
-
|
|
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])
|
|
3009
3377
|
];
|
|
3010
3378
|
const args = claudeArgs({
|
|
3011
3379
|
permissionMode: this.deps.permissionMode,
|
|
3012
3380
|
allowedTools,
|
|
3013
|
-
disallowedTools
|
|
3381
|
+
disallowedTools,
|
|
3014
3382
|
loadProjectSettings: this.deps.loadProjectSettings,
|
|
3015
3383
|
model: this.record.model,
|
|
3016
3384
|
resume: this.record.claudeSessionId,
|
|
3017
3385
|
relayPermissions: !!this.record.relayPermissionRequests,
|
|
3386
|
+
askTools: ask,
|
|
3018
3387
|
appendSystemPrompt: runnerSystemPrompt({
|
|
3019
3388
|
workBranch: this.record.workBranch,
|
|
3020
3389
|
baseRef: this.record.baseRef,
|
|
@@ -3032,10 +3401,10 @@ ${text}`;
|
|
|
3032
3401
|
detached: OWN_PROCESS_GROUP
|
|
3033
3402
|
});
|
|
3034
3403
|
let tree = null;
|
|
3035
|
-
await new Promise((
|
|
3404
|
+
await new Promise((resolve2, reject) => {
|
|
3036
3405
|
child.once("spawn", () => {
|
|
3037
3406
|
tree = trackTree(child, this.record.cwd || void 0);
|
|
3038
|
-
|
|
3407
|
+
resolve2();
|
|
3039
3408
|
});
|
|
3040
3409
|
child.once(
|
|
3041
3410
|
"error",
|
|
@@ -3055,7 +3424,7 @@ ${text}`;
|
|
|
3055
3424
|
{ pid: child.pid }
|
|
3056
3425
|
);
|
|
3057
3426
|
this.treeReaped = new Promise(
|
|
3058
|
-
(
|
|
3427
|
+
(resolve2) => child.once("exit", () => void reapTree(tree, this.reapGraceMs, this.deps.reap).then(resolve2))
|
|
3059
3428
|
);
|
|
3060
3429
|
child.stdin.on("error", () => void 0);
|
|
3061
3430
|
child.stderr.setEncoding("utf8").on("data", (d) => {
|
|
@@ -3283,7 +3652,7 @@ ${text}`;
|
|
|
3283
3652
|
async publishScreenshots() {
|
|
3284
3653
|
const { workBranch, repoDir, cwd, repository } = this.record;
|
|
3285
3654
|
const repo = parseRepoUrl(
|
|
3286
|
-
repository ?? (repoDir ? `https://github.com/${basename(
|
|
3655
|
+
repository ?? (repoDir ? `https://github.com/${basename(dirname6(repoDir))}/${basename(repoDir)}` : "")
|
|
3287
3656
|
);
|
|
3288
3657
|
if (!workBranch || !repoDir || !repo) return "";
|
|
3289
3658
|
const res = await publishEvidence({ repoDir, worktree: cwd, workBranch, repo });
|
|
@@ -3447,8 +3816,8 @@ function startupHint(stderr) {
|
|
|
3447
3816
|
}
|
|
3448
3817
|
async function raceTimeout(done, ms) {
|
|
3449
3818
|
let timer;
|
|
3450
|
-
const timeout = new Promise((
|
|
3451
|
-
timer = setTimeout(() =>
|
|
3819
|
+
const timeout = new Promise((resolve2) => {
|
|
3820
|
+
timer = setTimeout(() => resolve2(true), ms);
|
|
3452
3821
|
});
|
|
3453
3822
|
try {
|
|
3454
3823
|
return await Promise.race([done.then(() => false), timeout]);
|
|
@@ -3690,7 +4059,7 @@ var SessionManager = class {
|
|
|
3690
4059
|
await mkdir6(record.cwd, { recursive: true });
|
|
3691
4060
|
const deliverable = resume?.deliverable;
|
|
3692
4061
|
if (typeof deliverable === "string" && deliverable.trim()) {
|
|
3693
|
-
await writeFile4(
|
|
4062
|
+
await writeFile4(join10(record.cwd, RUNNER_DELIVERABLE_FILE), deliverable, "utf8");
|
|
3694
4063
|
}
|
|
3695
4064
|
}
|
|
3696
4065
|
if (resume) {
|
|
@@ -3952,7 +4321,8 @@ var SessionManager = class {
|
|
|
3952
4321
|
onClaudeSignIn: this.opts.onClaudeSignIn,
|
|
3953
4322
|
openPullRequest: this.opts.openPullRequest,
|
|
3954
4323
|
permissionTimeoutMs: this.opts.permissionTimeoutMs,
|
|
3955
|
-
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
|
|
3956
4326
|
});
|
|
3957
4327
|
}
|
|
3958
4328
|
};
|
|
@@ -4018,6 +4388,10 @@ var RunnerDaemon = class {
|
|
|
4018
4388
|
onUnauthorized: (err) => this.unauthorized(err),
|
|
4019
4389
|
onClaudeSignIn: (ok) => this.claudeSignIn(ok),
|
|
4020
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,
|
|
4021
4395
|
...opts.managerOverrides
|
|
4022
4396
|
});
|
|
4023
4397
|
}
|
|
@@ -4260,7 +4634,7 @@ var RunnerDaemon = class {
|
|
|
4260
4634
|
if (this.droppedSessionIds.has(id)) return;
|
|
4261
4635
|
this.droppedSessionIds.add(id);
|
|
4262
4636
|
this.opts.logger.warn(
|
|
4263
|
-
`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)})`
|
|
4264
4638
|
);
|
|
4265
4639
|
});
|
|
4266
4640
|
}
|
|
@@ -4303,15 +4677,15 @@ var RunnerDaemon = class {
|
|
|
4303
4677
|
this.completionsRunning++;
|
|
4304
4678
|
return Promise.resolve(true);
|
|
4305
4679
|
}
|
|
4306
|
-
return new Promise((
|
|
4680
|
+
return new Promise((resolve2) => {
|
|
4307
4681
|
const handOver = () => {
|
|
4308
4682
|
cancelled.removeEventListener("abort", leave);
|
|
4309
|
-
|
|
4683
|
+
resolve2(true);
|
|
4310
4684
|
};
|
|
4311
4685
|
const leave = () => {
|
|
4312
4686
|
const at = this.completionWaiters.indexOf(handOver);
|
|
4313
4687
|
if (at >= 0) this.completionWaiters.splice(at, 1);
|
|
4314
|
-
|
|
4688
|
+
resolve2(false);
|
|
4315
4689
|
};
|
|
4316
4690
|
this.completionWaiters.push(handOver);
|
|
4317
4691
|
cancelled.addEventListener("abort", leave, { once: true });
|
|
@@ -4488,10 +4862,10 @@ function formatChecks(checks) {
|
|
|
4488
4862
|
}
|
|
4489
4863
|
|
|
4490
4864
|
// src/lock.ts
|
|
4491
|
-
import { mkdir as mkdir7, open, readFile as
|
|
4492
|
-
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";
|
|
4493
4867
|
function lockFile(stateDir) {
|
|
4494
|
-
return
|
|
4868
|
+
return join12(stateDir, "daemon.pid");
|
|
4495
4869
|
}
|
|
4496
4870
|
function pidAlive(pid) {
|
|
4497
4871
|
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
@@ -4505,7 +4879,7 @@ function pidAlive(pid) {
|
|
|
4505
4879
|
async function lockHolder(stateDir) {
|
|
4506
4880
|
let raw;
|
|
4507
4881
|
try {
|
|
4508
|
-
raw = await
|
|
4882
|
+
raw = await readFile5(lockFile(stateDir), "utf8");
|
|
4509
4883
|
} catch {
|
|
4510
4884
|
return null;
|
|
4511
4885
|
}
|
|
@@ -4529,7 +4903,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
|
4529
4903
|
lock: {
|
|
4530
4904
|
file,
|
|
4531
4905
|
async release() {
|
|
4532
|
-
const current = await
|
|
4906
|
+
const current = await readFile5(file, "utf8").catch(() => "");
|
|
4533
4907
|
if (Number.parseInt(current.trim(), 10) === pid) await rm7(file, { force: true });
|
|
4534
4908
|
}
|
|
4535
4909
|
}
|
|
@@ -4537,7 +4911,7 @@ async function acquireDaemonLock(stateDir, pid = process.pid) {
|
|
|
4537
4911
|
} catch (err) {
|
|
4538
4912
|
if (err.code !== "EEXIST") throw err;
|
|
4539
4913
|
}
|
|
4540
|
-
const raw = await
|
|
4914
|
+
const raw = await readFile5(file, "utf8").catch(() => null);
|
|
4541
4915
|
if (raw === null) continue;
|
|
4542
4916
|
const holder = Number.parseInt(raw.trim(), 10);
|
|
4543
4917
|
if (pidAlive(holder) && holder !== pid) return { ok: false, pid: holder };
|
package/package.json
CHANGED