@buildanagent/harness 0.0.0-bootstrap.0 → 0.1.0-alpha.28
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/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +717 -0
- package/dist/ablation.d.ts +2 -0
- package/dist/ablation.js +3 -0
- package/dist/ablation.js.map +1 -0
- package/dist/completion/check.d.ts +64 -0
- package/dist/completion/check.js +152 -0
- package/dist/completion/check.js.map +1 -0
- package/dist/completion/checks.d.ts +45 -0
- package/dist/completion/checks.js +173 -0
- package/dist/completion/checks.js.map +1 -0
- package/dist/completion/flags.d.ts +25 -0
- package/dist/completion/flags.js +87 -0
- package/dist/completion/flags.js.map +1 -0
- package/dist/completion/index.d.ts +8 -0
- package/dist/completion/index.js +9 -0
- package/dist/completion/index.js.map +1 -0
- package/dist/completion/snapshot.d.ts +33 -0
- package/dist/completion/snapshot.js +83 -0
- package/dist/completion/snapshot.js.map +1 -0
- package/dist/context/cap.d.ts +32 -0
- package/dist/context/cap.js +50 -0
- package/dist/context/cap.js.map +1 -0
- package/dist/context/estimate.d.ts +18 -0
- package/dist/context/estimate.js +20 -0
- package/dist/context/estimate.js.map +1 -0
- package/dist/context/file-spill.d.ts +5 -0
- package/dist/context/file-spill.js +25 -0
- package/dist/context/file-spill.js.map +1 -0
- package/dist/context/index.d.ts +10 -0
- package/dist/context/index.js +10 -0
- package/dist/context/index.js.map +1 -0
- package/dist/context/mask.d.ts +27 -0
- package/dist/context/mask.js +71 -0
- package/dist/context/mask.js.map +1 -0
- package/dist/context/mid-turn.d.ts +40 -0
- package/dist/context/mid-turn.js +82 -0
- package/dist/context/mid-turn.js.map +1 -0
- package/dist/context/policy.d.ts +9 -0
- package/dist/context/policy.js +140 -0
- package/dist/context/policy.js.map +1 -0
- package/dist/context/spill-ledger.d.ts +25 -0
- package/dist/context/spill-ledger.js +54 -0
- package/dist/context/spill-ledger.js.map +1 -0
- package/dist/context/spill.d.ts +6 -0
- package/dist/context/spill.js +14 -0
- package/dist/context/spill.js.map +1 -0
- package/dist/context/summarize.d.ts +53 -0
- package/dist/context/summarize.js +204 -0
- package/dist/context/summarize.js.map +1 -0
- package/dist/context/summary-template.d.ts +29 -0
- package/dist/context/summary-template.js +69 -0
- package/dist/context/summary-template.js.map +1 -0
- package/dist/context/types.d.ts +150 -0
- package/dist/context/types.js +2 -0
- package/dist/context/types.js.map +1 -0
- package/dist/context/write-cap.d.ts +19 -0
- package/dist/context/write-cap.js +41 -0
- package/dist/context/write-cap.js.map +1 -0
- package/dist/create-harness.d.ts +7 -0
- package/dist/create-harness.js +21 -0
- package/dist/create-harness.js.map +1 -0
- package/dist/credentials/addresses.d.ts +14 -0
- package/dist/credentials/addresses.js +144 -0
- package/dist/credentials/addresses.js.map +1 -0
- package/dist/credentials/allowlist.d.ts +34 -0
- package/dist/credentials/allowlist.js +77 -0
- package/dist/credentials/allowlist.js.map +1 -0
- package/dist/credentials/egress-proxy.d.ts +70 -0
- package/dist/credentials/egress-proxy.js +482 -0
- package/dist/credentials/egress-proxy.js.map +1 -0
- package/dist/credentials/index.d.ts +9 -0
- package/dist/credentials/index.js +10 -0
- package/dist/credentials/index.js.map +1 -0
- package/dist/credentials/scrub.d.ts +16 -0
- package/dist/credentials/scrub.js +93 -0
- package/dist/credentials/scrub.js.map +1 -0
- package/dist/errors.d.ts +56 -0
- package/dist/errors.js +63 -0
- package/dist/errors.js.map +1 -0
- package/dist/extensions/compose.d.ts +27 -0
- package/dist/extensions/compose.js +83 -0
- package/dist/extensions/compose.js.map +1 -0
- package/dist/extensions/context-files-node.d.ts +28 -0
- package/dist/extensions/context-files-node.js +74 -0
- package/dist/extensions/context-files-node.js.map +1 -0
- package/dist/extensions/context-files.d.ts +68 -0
- package/dist/extensions/context-files.js +214 -0
- package/dist/extensions/context-files.js.map +1 -0
- package/dist/extensions/digest.d.ts +6 -0
- package/dist/extensions/digest.js +68 -0
- package/dist/extensions/digest.js.map +1 -0
- package/dist/extensions/index.d.ts +10 -0
- package/dist/extensions/index.js +10 -0
- package/dist/extensions/index.js.map +1 -0
- package/dist/extensions/load.d.ts +42 -0
- package/dist/extensions/load.js +211 -0
- package/dist/extensions/load.js.map +1 -0
- package/dist/extensions/lock.d.ts +8 -0
- package/dist/extensions/lock.js +95 -0
- package/dist/extensions/lock.js.map +1 -0
- package/dist/extensions/node.d.ts +10 -0
- package/dist/extensions/node.js +11 -0
- package/dist/extensions/node.js.map +1 -0
- package/dist/extensions/project-dirs.d.ts +24 -0
- package/dist/extensions/project-dirs.js +97 -0
- package/dist/extensions/project-dirs.js.map +1 -0
- package/dist/extensions/skills-node.d.ts +34 -0
- package/dist/extensions/skills-node.js +123 -0
- package/dist/extensions/skills-node.js.map +1 -0
- package/dist/extensions/skills.d.ts +51 -0
- package/dist/extensions/skills.js +175 -0
- package/dist/extensions/skills.js.map +1 -0
- package/dist/extensions/trust-file.d.ts +3 -0
- package/dist/extensions/trust-file.js +62 -0
- package/dist/extensions/trust-file.js.map +1 -0
- package/dist/extensions/trust-store-node.d.ts +10 -0
- package/dist/extensions/trust-store-node.js +33 -0
- package/dist/extensions/trust-store-node.js.map +1 -0
- package/dist/extensions/types.d.ts +42 -0
- package/dist/extensions/types.js +2 -0
- package/dist/extensions/types.js.map +1 -0
- package/dist/harness.d.ts +156 -0
- package/dist/harness.js +2 -0
- package/dist/harness.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -0
- package/dist/mcp/connection.d.ts +22 -0
- package/dist/mcp/connection.js +267 -0
- package/dist/mcp/connection.js.map +1 -0
- package/dist/mcp/content.d.ts +27 -0
- package/dist/mcp/content.js +177 -0
- package/dist/mcp/content.js.map +1 -0
- package/dist/mcp/errors.d.ts +19 -0
- package/dist/mcp/errors.js +21 -0
- package/dist/mcp/errors.js.map +1 -0
- package/dist/mcp/index.d.ts +10 -0
- package/dist/mcp/index.js +10 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manager.d.ts +7 -0
- package/dist/mcp/manager.js +173 -0
- package/dist/mcp/manager.js.map +1 -0
- package/dist/mcp/record.d.ts +7 -0
- package/dist/mcp/record.js +20 -0
- package/dist/mcp/record.js.map +1 -0
- package/dist/mcp/stdio.d.ts +39 -0
- package/dist/mcp/stdio.js +382 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/types.d.ts +172 -0
- package/dist/mcp/types.js +2 -0
- package/dist/mcp/types.js.map +1 -0
- package/dist/memory/index.d.ts +2 -0
- package/dist/memory/index.js +3 -0
- package/dist/memory/index.js.map +1 -0
- package/dist/permissions/default-rules.d.ts +7 -0
- package/dist/permissions/default-rules.js +42 -0
- package/dist/permissions/default-rules.js.map +1 -0
- package/dist/permissions/errors.d.ts +11 -0
- package/dist/permissions/errors.js +14 -0
- package/dist/permissions/errors.js.map +1 -0
- package/dist/permissions/index.d.ts +9 -0
- package/dist/permissions/index.js +9 -0
- package/dist/permissions/index.js.map +1 -0
- package/dist/permissions/match.d.ts +33 -0
- package/dist/permissions/match.js +287 -0
- package/dist/permissions/match.js.map +1 -0
- package/dist/permissions/pipeline.d.ts +9 -0
- package/dist/permissions/pipeline.js +235 -0
- package/dist/permissions/pipeline.js.map +1 -0
- package/dist/permissions/rules.d.ts +22 -0
- package/dist/permissions/rules.js +74 -0
- package/dist/permissions/rules.js.map +1 -0
- package/dist/permissions/shadow.d.ts +5 -0
- package/dist/permissions/shadow.js +22 -0
- package/dist/permissions/shadow.js.map +1 -0
- package/dist/permissions/types.d.ts +104 -0
- package/dist/permissions/types.js +2 -0
- package/dist/permissions/types.js.map +1 -0
- package/dist/sandbox/base.d.ts +35 -0
- package/dist/sandbox/base.js +60 -0
- package/dist/sandbox/base.js.map +1 -0
- package/dist/sandbox/docker/index.d.ts +35 -0
- package/dist/sandbox/docker/index.js +448 -0
- package/dist/sandbox/docker/index.js.map +1 -0
- package/dist/sandbox/errors.d.ts +16 -0
- package/dist/sandbox/errors.js +22 -0
- package/dist/sandbox/errors.js.map +1 -0
- package/dist/sandbox/host-files.d.ts +63 -0
- package/dist/sandbox/host-files.js +248 -0
- package/dist/sandbox/host-files.js.map +1 -0
- package/dist/sandbox/index.d.ts +8 -0
- package/dist/sandbox/index.js +8 -0
- package/dist/sandbox/index.js.map +1 -0
- package/dist/sandbox/none.d.ts +17 -0
- package/dist/sandbox/none.js +108 -0
- package/dist/sandbox/none.js.map +1 -0
- package/dist/sandbox/process.d.ts +61 -0
- package/dist/sandbox/process.js +253 -0
- package/dist/sandbox/process.js.map +1 -0
- package/dist/sandbox/spawn-env.d.ts +20 -0
- package/dist/sandbox/spawn-env.js +128 -0
- package/dist/sandbox/spawn-env.js.map +1 -0
- package/dist/sandbox/srt/index.d.ts +35 -0
- package/dist/sandbox/srt/index.js +264 -0
- package/dist/sandbox/srt/index.js.map +1 -0
- package/dist/sandbox/srt/settings.d.ts +48 -0
- package/dist/sandbox/srt/settings.js +31 -0
- package/dist/sandbox/srt/settings.js.map +1 -0
- package/dist/sandbox/types.d.ts +88 -0
- package/dist/sandbox/types.js +6 -0
- package/dist/sandbox/types.js.map +1 -0
- package/dist/server/answers.d.ts +16 -0
- package/dist/server/answers.js +43 -0
- package/dist/server/answers.js.map +1 -0
- package/dist/server/connection.d.ts +99 -0
- package/dist/server/connection.js +309 -0
- package/dist/server/connection.js.map +1 -0
- package/dist/server/dispatcher.d.ts +86 -0
- package/dist/server/dispatcher.js +800 -0
- package/dist/server/dispatcher.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/local-transport.d.ts +44 -0
- package/dist/server/local-transport.js +103 -0
- package/dist/server/local-transport.js.map +1 -0
- package/dist/server/outbox.d.ts +31 -0
- package/dist/server/outbox.js +130 -0
- package/dist/server/outbox.js.map +1 -0
- package/dist/server/params.d.ts +25 -0
- package/dist/server/params.js +112 -0
- package/dist/server/params.js.map +1 -0
- package/dist/server/protocol.schema.json +2448 -0
- package/dist/server/rpc-session.d.ts +43 -0
- package/dist/server/rpc-session.js +167 -0
- package/dist/server/rpc-session.js.map +1 -0
- package/dist/server/stdio-streams.d.ts +67 -0
- package/dist/server/stdio-streams.js +218 -0
- package/dist/server/stdio-streams.js.map +1 -0
- package/dist/server/stdio.d.ts +59 -0
- package/dist/server/stdio.js +189 -0
- package/dist/server/stdio.js.map +1 -0
- package/dist/server/websocket.d.ts +106 -0
- package/dist/server/websocket.js +327 -0
- package/dist/server/websocket.js.map +1 -0
- package/dist/session/approvals.d.ts +81 -0
- package/dist/session/approvals.js +217 -0
- package/dist/session/approvals.js.map +1 -0
- package/dist/session/code-call-log.d.ts +42 -0
- package/dist/session/code-call-log.js +63 -0
- package/dist/session/code-call-log.js.map +1 -0
- package/dist/session/code-call-result.d.ts +19 -0
- package/dist/session/code-call-result.js +95 -0
- package/dist/session/code-call-result.js.map +1 -0
- package/dist/session/code-call.d.ts +49 -0
- package/dist/session/code-call.js +345 -0
- package/dist/session/code-call.js.map +1 -0
- package/dist/session/effect-scope.d.ts +11 -0
- package/dist/session/effect-scope.js +10 -0
- package/dist/session/effect-scope.js.map +1 -0
- package/dist/session/errors.d.ts +19 -0
- package/dist/session/errors.js +27 -0
- package/dist/session/errors.js.map +1 -0
- package/dist/session/file-index.d.ts +8 -0
- package/dist/session/file-index.js +70 -0
- package/dist/session/file-index.js.map +1 -0
- package/dist/session/file-key-store.d.ts +16 -0
- package/dist/session/file-key-store.js +169 -0
- package/dist/session/file-key-store.js.map +1 -0
- package/dist/session/file-lock.d.ts +52 -0
- package/dist/session/file-lock.js +324 -0
- package/dist/session/file-lock.js.map +1 -0
- package/dist/session/index.d.ts +22 -0
- package/dist/session/index.js +20 -0
- package/dist/session/index.js.map +1 -0
- package/dist/session/jsonl-store.d.ts +37 -0
- package/dist/session/jsonl-store.js +386 -0
- package/dist/session/jsonl-store.js.map +1 -0
- package/dist/session/jsonl.d.ts +9 -0
- package/dist/session/jsonl.js +10 -0
- package/dist/session/jsonl.js.map +1 -0
- package/dist/session/lock.d.ts +19 -0
- package/dist/session/lock.js +2 -0
- package/dist/session/lock.js.map +1 -0
- package/dist/session/memory-store.d.ts +12 -0
- package/dist/session/memory-store.js +60 -0
- package/dist/session/memory-store.js.map +1 -0
- package/dist/session/migrate.d.ts +41 -0
- package/dist/session/migrate.js +86 -0
- package/dist/session/migrate.js.map +1 -0
- package/dist/session/pointer.d.ts +15 -0
- package/dist/session/pointer.js +22 -0
- package/dist/session/pointer.js.map +1 -0
- package/dist/session/rebuild.d.ts +53 -0
- package/dist/session/rebuild.js +230 -0
- package/dist/session/rebuild.js.map +1 -0
- package/dist/session/resume.d.ts +26 -0
- package/dist/session/resume.js +128 -0
- package/dist/session/resume.js.map +1 -0
- package/dist/session/retention.d.ts +97 -0
- package/dist/session/retention.js +702 -0
- package/dist/session/retention.js.map +1 -0
- package/dist/session/runner.d.ts +156 -0
- package/dist/session/runner.js +656 -0
- package/dist/session/runner.js.map +1 -0
- package/dist/session/scheduler.d.ts +47 -0
- package/dist/session/scheduler.js +85 -0
- package/dist/session/scheduler.js.map +1 -0
- package/dist/session/secret-key-store.d.ts +47 -0
- package/dist/session/secret-key-store.js +79 -0
- package/dist/session/secret-key-store.js.map +1 -0
- package/dist/session/session.d.ts +106 -0
- package/dist/session/session.js +353 -0
- package/dist/session/session.js.map +1 -0
- package/dist/session/sticky.d.ts +48 -0
- package/dist/session/sticky.js +232 -0
- package/dist/session/sticky.js.map +1 -0
- package/dist/session/store.d.ts +108 -0
- package/dist/session/store.js +163 -0
- package/dist/session/store.js.map +1 -0
- package/dist/telemetry/index.d.ts +2 -0
- package/dist/telemetry/index.js +3 -0
- package/dist/telemetry/index.js.map +1 -0
- package/dist/testing/fake-sandbox.d.ts +34 -0
- package/dist/testing/fake-sandbox.js +221 -0
- package/dist/testing/fake-sandbox.js.map +1 -0
- package/dist/testing/index.d.ts +10 -0
- package/dist/testing/index.js +11 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/testing/key-store-conformance.d.ts +22 -0
- package/dist/testing/key-store-conformance.js +97 -0
- package/dist/testing/key-store-conformance.js.map +1 -0
- package/dist/testing/run-cases.d.ts +21 -0
- package/dist/testing/run-cases.js +20 -0
- package/dist/testing/run-cases.js.map +1 -0
- package/dist/testing/sandbox-conformance.d.ts +64 -0
- package/dist/testing/sandbox-conformance.js +361 -0
- package/dist/testing/sandbox-conformance.js.map +1 -0
- package/dist/testing/scheduler-conformance.d.ts +32 -0
- package/dist/testing/scheduler-conformance.js +72 -0
- package/dist/testing/scheduler-conformance.js.map +1 -0
- package/dist/testing/store-conformance.d.ts +21 -0
- package/dist/testing/store-conformance.js +320 -0
- package/dist/testing/store-conformance.js.map +1 -0
- package/dist/tools/errors.d.ts +13 -0
- package/dist/tools/errors.js +17 -0
- package/dist/tools/errors.js.map +1 -0
- package/dist/tools/index.d.ts +8 -0
- package/dist/tools/index.js +8 -0
- package/dist/tools/index.js.map +1 -0
- package/dist/tools/registry.d.ts +3 -0
- package/dist/tools/registry.js +234 -0
- package/dist/tools/registry.js.map +1 -0
- package/dist/tools/tool-search.d.ts +30 -0
- package/dist/tools/tool-search.js +118 -0
- package/dist/tools/tool-search.js.map +1 -0
- package/dist/tools/types.d.ts +106 -0
- package/dist/tools/types.js +2 -0
- package/dist/tools/types.js.map +1 -0
- package/llms.txt +435 -0
- package/package.json +119 -5
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createPermissionPipeline()`: one ordered, deny-first decision for every tool call. The order is hooks, deny rules,
|
|
3
|
+
* ask rules, the mode, allow rules, the host callback and then the no-match default. A deny at any step ends the
|
|
4
|
+
* decision, and the pipeline fails closed: anything it can't read or run is a denial.
|
|
5
|
+
*/
|
|
6
|
+
import { canonicalInputHash } from "@buildanagent/sdk";
|
|
7
|
+
import { PermissionConfigError } from "./errors.js";
|
|
8
|
+
import { isUnconditional, permits, restricts, targetOf, toolMatches } from "./rules.js";
|
|
9
|
+
import { shadowWrapper } from "./shadow.js";
|
|
10
|
+
const DEFAULT_EDIT_TOOLS = ["write", "edit", "multi_edit", "apply_patch"];
|
|
11
|
+
const DEFAULT_READ_ONLY_TOOLS = ["read", "grep", "glob"];
|
|
12
|
+
const DECISIONS = ["allow", "deny", "ask"];
|
|
13
|
+
const deny = (reason, rule, by) => ({
|
|
14
|
+
decision: "deny",
|
|
15
|
+
reason,
|
|
16
|
+
...(rule === undefined ? {} : { rule }),
|
|
17
|
+
...(by === undefined ? {} : { by }),
|
|
18
|
+
});
|
|
19
|
+
const describe = (error) => (error instanceof Error ? error.message : String(error));
|
|
20
|
+
class Pipeline {
|
|
21
|
+
#config;
|
|
22
|
+
#registry;
|
|
23
|
+
#wrapped = false;
|
|
24
|
+
constructor(config, registry) {
|
|
25
|
+
this.#config = config;
|
|
26
|
+
this.#registry = registry;
|
|
27
|
+
this.#checkAllowRules();
|
|
28
|
+
}
|
|
29
|
+
/** A rule that allows every call to a registered tool leaves the host callback nothing to decide for that tool. */
|
|
30
|
+
#checkAllowRules() {
|
|
31
|
+
if (this.#config.hostCallback === undefined)
|
|
32
|
+
return;
|
|
33
|
+
(this.#config.allow ?? []).forEach((rule, index) => {
|
|
34
|
+
if (!isUnconditional(rule))
|
|
35
|
+
return;
|
|
36
|
+
const shadowed = this.#registry.list().find((tool) => toolMatches(rule.tool, this.#namesOf(tool.canonicalName)));
|
|
37
|
+
if (shadowed !== undefined) {
|
|
38
|
+
throw new PermissionConfigError(`allow[${index}] allows every call to ${shadowed.canonicalName}, so the host callback could never decide one; narrow the rule with paths or a commandPrefix, or remove it`);
|
|
39
|
+
}
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
#namesOf(tool) {
|
|
43
|
+
const registered = this.#registry.get(tool);
|
|
44
|
+
if (registered === undefined)
|
|
45
|
+
return [tool];
|
|
46
|
+
return registered.alias === undefined ? [registered.canonicalName] : [registered.canonicalName, registered.alias];
|
|
47
|
+
}
|
|
48
|
+
async decide(call, input) {
|
|
49
|
+
const ctx = { ...input, mode: this.#config.mode, policyVersion: this.#config.policyVersion };
|
|
50
|
+
const hashed = await this.#hash(call.input);
|
|
51
|
+
const decision = hashed.error === undefined ? await this.#settle(call, ctx) : deny(hashed.error, "unreadable_call");
|
|
52
|
+
await this.#record(call, ctx, decision, hashed.hash);
|
|
53
|
+
return decision;
|
|
54
|
+
}
|
|
55
|
+
/** The hash of an input. One with no canonical form can't be compared on resume, so it is denied under a marker hash. */
|
|
56
|
+
async #hash(value) {
|
|
57
|
+
try {
|
|
58
|
+
return { hash: await canonicalInputHash(value) };
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
return {
|
|
62
|
+
hash: await canonicalInputHash("unhashable"),
|
|
63
|
+
error: `the input could not be checked: ${describe(error)}`,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/** `#evaluate()` with a failure turned into a denial, which is logged like any other decision. */
|
|
68
|
+
async #settle(call, ctx) {
|
|
69
|
+
try {
|
|
70
|
+
if (ctx.mode === "shadow" && !this.#wrapped) {
|
|
71
|
+
return deny("shadow mode needs the tools wrapped by this pipeline's shadowWrapper(), so the call was refused", "shadow_unwrapped");
|
|
72
|
+
}
|
|
73
|
+
return await this.#evaluate(call, ctx);
|
|
74
|
+
}
|
|
75
|
+
catch (error) {
|
|
76
|
+
const rule = error instanceof PermissionConfigError ? "invalid_config" : "evaluation_failed";
|
|
77
|
+
return deny(`the call could not be decided, so it was refused: ${describe(error)}`, rule);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
shadowWrapper(session) {
|
|
81
|
+
this.#wrapped = true;
|
|
82
|
+
return shadowWrapper(session, this.#config.mode);
|
|
83
|
+
}
|
|
84
|
+
gate(context) {
|
|
85
|
+
return {
|
|
86
|
+
beforeToolCall: async (event) => {
|
|
87
|
+
try {
|
|
88
|
+
const call = { callId: event.callId, tool: event.tool, input: event.input, initiator: "model" };
|
|
89
|
+
const decision = await this.decide(call, await context(event));
|
|
90
|
+
if (decision.decision === "ask") {
|
|
91
|
+
return { decision: "ask", reason: decision.reason, policyVersion: this.#config.policyVersion };
|
|
92
|
+
}
|
|
93
|
+
return decision.decision === "allow"
|
|
94
|
+
? { decision: "allow", reason: decision.reason }
|
|
95
|
+
: { decision: "deny", reason: decision.reason };
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
return {
|
|
99
|
+
decision: "deny",
|
|
100
|
+
reason: `the permission check failed, so the call was refused: ${describe(error)}`,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
async #record(call, ctx, decision, inputHash) {
|
|
107
|
+
await ctx.session.append({
|
|
108
|
+
type: "permission_decision",
|
|
109
|
+
callId: call.callId,
|
|
110
|
+
tool: this.#registry.get(call.tool)?.canonicalName ?? call.tool,
|
|
111
|
+
decision: decision.decision,
|
|
112
|
+
...(decision.rule === undefined ? {} : { rule: decision.rule }),
|
|
113
|
+
...(decision.by === undefined ? {} : { by: decision.by }),
|
|
114
|
+
policyVersion: ctx.policyVersion,
|
|
115
|
+
inputHash,
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
async #evaluate(call, ctx) {
|
|
119
|
+
const target = targetOf(this.#namesOf(call.tool), call.input);
|
|
120
|
+
const hook = await this.#runHooks(call, ctx);
|
|
121
|
+
if (hook?.decision === "deny")
|
|
122
|
+
return hook;
|
|
123
|
+
const denied = this.#firstMatch("deny", this.#config.deny, target);
|
|
124
|
+
if (denied !== undefined)
|
|
125
|
+
return denied;
|
|
126
|
+
// Read-only mode is a limit, so no approval may widen it.
|
|
127
|
+
const readOnly = ctx.mode === "read_only" ? this.#byMode(target, ctx.mode) : undefined;
|
|
128
|
+
if (readOnly?.decision === "deny")
|
|
129
|
+
return readOnly;
|
|
130
|
+
// Nothing runs in shadow mode, so a question to a person would have no call to wait for.
|
|
131
|
+
const shadow = ctx.mode === "shadow";
|
|
132
|
+
if (hook !== undefined && !shadow)
|
|
133
|
+
return hook;
|
|
134
|
+
const asked = shadow ? undefined : this.#firstMatch("ask", this.#config.ask, target);
|
|
135
|
+
if (asked !== undefined)
|
|
136
|
+
return asked;
|
|
137
|
+
return (this.#byMode(target, ctx.mode) ??
|
|
138
|
+
this.#byAllowRule(target) ??
|
|
139
|
+
(await this.#byHostCallback(call, ctx)) ??
|
|
140
|
+
this.#noMatch());
|
|
141
|
+
}
|
|
142
|
+
/** Runs every hook in order. The first deny ends the run of hooks, and the first ask is held in case a later step denies. */
|
|
143
|
+
async #runHooks(call, ctx) {
|
|
144
|
+
let held;
|
|
145
|
+
for (const [index, hook] of (this.#config.hooks ?? []).entries()) {
|
|
146
|
+
const result = await this.#runHook(hook, index, call, ctx);
|
|
147
|
+
if (result?.decision === "deny")
|
|
148
|
+
return result;
|
|
149
|
+
held ??= result;
|
|
150
|
+
}
|
|
151
|
+
return held;
|
|
152
|
+
}
|
|
153
|
+
async #runHook(hook, index, call, ctx) {
|
|
154
|
+
const rule = `hook[${index}]`;
|
|
155
|
+
try {
|
|
156
|
+
const result = await hook(call, ctx);
|
|
157
|
+
if (result === undefined)
|
|
158
|
+
return undefined;
|
|
159
|
+
const { decision, reason } = result;
|
|
160
|
+
if ((decision !== "deny" && decision !== "ask") || typeof reason !== "string") {
|
|
161
|
+
return deny(`${rule} returned ${JSON.stringify(decision)}, and a hook may only deny or ask`, rule, "hook");
|
|
162
|
+
}
|
|
163
|
+
return { decision, reason, rule: result.rule ?? rule, by: "hook" };
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
return deny(`${rule} failed, so the call was refused: ${describe(error)}`, rule, "hook");
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
#firstMatch(list, rules, target) {
|
|
170
|
+
const index = (rules ?? []).findIndex((rule) => restricts(rule, target));
|
|
171
|
+
const rule = rules?.[index];
|
|
172
|
+
if (rule === undefined)
|
|
173
|
+
return undefined;
|
|
174
|
+
return { decision: list, reason: rule.reason ?? `${list}[${index}] matched`, rule: `${list}[${index}]` };
|
|
175
|
+
}
|
|
176
|
+
#byMode(target, mode) {
|
|
177
|
+
const named = (tools) => tools.some((tool) => toolMatches(tool, target.names));
|
|
178
|
+
const allow = () => ({
|
|
179
|
+
decision: "allow",
|
|
180
|
+
reason: `${mode} mode allows this`,
|
|
181
|
+
rule: `mode:${mode}`,
|
|
182
|
+
by: "mode",
|
|
183
|
+
});
|
|
184
|
+
if (mode === "bypass" || mode === "shadow")
|
|
185
|
+
return allow();
|
|
186
|
+
if (mode === "accept_edits")
|
|
187
|
+
return named(this.#config.editTools ?? DEFAULT_EDIT_TOOLS) ? allow() : undefined;
|
|
188
|
+
if (mode !== "read_only")
|
|
189
|
+
return undefined;
|
|
190
|
+
return named(this.#config.readOnlyTools ?? DEFAULT_READ_ONLY_TOOLS)
|
|
191
|
+
? allow()
|
|
192
|
+
: deny("read_only mode allows only read-only tools", "mode:read_only", "mode");
|
|
193
|
+
}
|
|
194
|
+
#byAllowRule(target) {
|
|
195
|
+
const rules = this.#config.allow ?? [];
|
|
196
|
+
const index = permits(rules, target);
|
|
197
|
+
const rule = index === undefined ? undefined : rules[index];
|
|
198
|
+
if (index === undefined || rule === undefined)
|
|
199
|
+
return undefined;
|
|
200
|
+
if (this.#config.hostCallback !== undefined && isUnconditional(rule)) {
|
|
201
|
+
throw new PermissionConfigError(`allow[${index}] allows every call to a tool the host callback should decide`);
|
|
202
|
+
}
|
|
203
|
+
return { decision: "allow", reason: rule.reason ?? `allow[${index}] matched`, rule: `allow[${index}]` };
|
|
204
|
+
}
|
|
205
|
+
async #byHostCallback(call, ctx) {
|
|
206
|
+
const callback = this.#config.hostCallback;
|
|
207
|
+
if (callback === undefined)
|
|
208
|
+
return undefined;
|
|
209
|
+
try {
|
|
210
|
+
const result = await callback(call, ctx);
|
|
211
|
+
if (!DECISIONS.includes(result?.decision) || typeof result.reason !== "string") {
|
|
212
|
+
return deny("the host callback returned something that is not a decision, so the call was refused", "host_callback", "host");
|
|
213
|
+
}
|
|
214
|
+
return { ...result, by: result.by ?? "host" };
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
return deny(`the host callback failed, so the call was refused: ${describe(error)}`, "host_callback", "host");
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
#noMatch() {
|
|
221
|
+
return this.#config.interactive
|
|
222
|
+
? { decision: "ask", reason: "No rule covers this call, so a person decides.", rule: "no_match" }
|
|
223
|
+
: deny("No rule covers this call and nobody can be asked, so it is refused.", "no_match");
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Creates the pipeline. It throws a `PermissionConfigError` when an allow rule covers every call to a registered tool
|
|
228
|
+
* while a host callback is set. Deny rules, hooks and a host callback with no allow rules never throw it.
|
|
229
|
+
*
|
|
230
|
+
* With no host callback, a call that no rule settles asks when `interactive` is true and is denied when it is false.
|
|
231
|
+
*/
|
|
232
|
+
export function createPermissionPipeline(config, registry) {
|
|
233
|
+
return new Pipeline(config, registry);
|
|
234
|
+
}
|
|
235
|
+
//# sourceMappingURL=pipeline.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pipeline.js","sourceRoot":"","sources":["../../src/permissions/pipeline.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAEvD,OAAO,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,eAAe,EAAE,OAAO,EAAE,SAAS,EAAe,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACrG,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAa5C,MAAM,kBAAkB,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,aAAa,CAAC,CAAC;AAC1E,MAAM,uBAAuB,GAAG,CAAC,MAAM,EA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MAAM,UAAU,wBAAwB,CAAC,MAAwB,EAAE,QAAsB;IACvF,OAAO,IAAI,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;AACxC,CAAC","sourcesContent":["/**\n * `createPermissionPipeline()`: one ordered, deny-first decision for every tool call. The order is hooks, deny rules,\n * ask rules, the mode, allow rules, the host callback and then the no-match default. A deny at any step ends the\n * decision, and the pipeline fails closed: anything it can't read or run is a denial.\n */\nimport { canonicalInputHash } from \"@buildanagent/sdk\";\nimport type { ToolRegistry } from \"../tools/types.js\";\nimport { PermissionConfigError } from \"./errors.js\";\nimport { isUnconditional, permits, restricts, type Target, targetOf, toolMatches } from \"./rules.js\";\nimport { shadowWrapper } from \"./shadow.js\";\nimport type {\n Decision,\n PermissionConfig,\n PermissionHook,\n PermissionPipeline,\n PolicyContext,\n PolicyInput,\n PolicySession,\n Rule,\n ToolCall,\n} from \"./types.js\";\n\nconst DEFAULT_EDIT_TOOLS = [\"write\", \"edit\", \"multi_edit\", \"apply_patch\"];\nconst DEFAULT_READ_ONLY_TOOLS = [\"read\", \"grep\", \"glob\"];\nconst DECISIONS: readonly string[] = [\"allow\", \"deny\", \"ask\"];\n\nconst deny = (reason: string, rule?: string, by?: string): Decision => ({\n decision: \"deny\",\n reason,\n ...(rule === undefined ? {} : { rule }),\n ...(by === undefined ? {} : { by }),\n});\n\nconst describe = (error: unknown): string => (error instanceof Error ? error.message : String(error));\n\nclass Pipeline implements PermissionPipeline {\n readonly #config: PermissionConfig;\n readonly #registry: ToolRegistry;\n #wrapped = false;\n\n constructor(config: PermissionConfig, registry: ToolRegistry) {\n this.#config = config;\n this.#registry = registry;\n this.#checkAllowRules();\n }\n\n /** A rule that allows every call to a registered tool leaves the host callback nothing to decide for that tool. */\n #checkAllowRules(): void {\n if (this.#config.hostCallback === undefined) return;\n (this.#config.allow ?? []).forEach((rule, index) => {\n if (!isUnconditional(rule)) return;\n const shadowed = this.#registry.list().find((tool) => toolMatches(rule.tool, this.#namesOf(tool.canonicalName)));\n if (shadowed !== undefined) {\n throw new PermissionConfigError(\n `allow[${index}] allows every call to ${shadowed.canonicalName}, so the host callback could never decide one; narrow the rule with paths or a commandPrefix, or remove it`,\n );\n }\n });\n }\n\n #namesOf(tool: string): string[] {\n const registered = this.#registry.get(tool);\n if (registered === undefined) return [tool];\n return registered.alias === undefined ? [registered.canonicalName] : [registered.canonicalName, registered.alias];\n }\n\n async decide(call: ToolCall, input: PolicyInput): Promise<Decision> {\n const ctx: PolicyContext = { ...input, mode: this.#config.mode, policyVersion: this.#config.policyVersion };\n const hashed = await this.#hash(call.input);\n const decision = hashed.error === undefined ? await this.#settle(call, ctx) : deny(hashed.error, \"unreadable_call\");\n await this.#record(call, ctx, decision, hashed.hash);\n return decision;\n }\n\n /** The hash of an input. One with no canonical form can't be compared on resume, so it is denied under a marker hash. */\n async #hash(value: unknown): Promise<{ hash: string; error?: string }> {\n try {\n return { hash: await canonicalInputHash(value) };\n } catch (error) {\n return {\n hash: await canonicalInputHash(\"unhashable\"),\n error: `the input could not be checked: ${describe(error)}`,\n };\n }\n }\n\n /** `#evaluate()` with a failure turned into a denial, which is logged like any other decision. */\n async #settle(call: ToolCall, ctx: PolicyContext): Promise<Decision> {\n try {\n if (ctx.mode === \"shadow\" && !this.#wrapped) {\n return deny(\n \"shadow mode needs the tools wrapped by this pipeline's shadowWrapper(), so the call was refused\",\n \"shadow_unwrapped\",\n );\n }\n return await this.#evaluate(call, ctx);\n } catch (error) {\n const rule = error instanceof PermissionConfigError ? \"invalid_config\" : \"evaluation_failed\";\n return deny(`the call could not be decided, so it was refused: ${describe(error)}`, rule);\n }\n }\n\n shadowWrapper(session: PolicySession): ReturnType<PermissionPipeline[\"shadowWrapper\"]> {\n this.#wrapped = true;\n return shadowWrapper(session, this.#config.mode);\n }\n\n gate(context: Parameters<PermissionPipeline[\"gate\"]>[0]): ReturnType<PermissionPipeline[\"gate\"]> {\n return {\n beforeToolCall: async (event) => {\n try {\n const call: ToolCall = { callId: event.callId, tool: event.tool, input: event.input, initiator: \"model\" };\n const decision = await this.decide(call, await context(event));\n if (decision.decision === \"ask\") {\n return { decision: \"ask\", reason: decision.reason, policyVersion: this.#config.policyVersion };\n }\n return decision.decision === \"allow\"\n ? { decision: \"allow\", reason: decision.reason }\n : { decision: \"deny\", reason: decision.reason };\n } catch (error) {\n return {\n decision: \"deny\",\n reason: `the permission check failed, so the call was refused: ${describe(error)}`,\n };\n }\n },\n };\n }\n\n async #record(call: ToolCall, ctx: PolicyContext, decision: Decision, inputHash: string): Promise<void> {\n await ctx.session.append({\n type: \"permission_decision\",\n callId: call.callId,\n tool: this.#registry.get(call.tool)?.canonicalName ?? call.tool,\n decision: decision.decision,\n ...(decision.rule === undefined ? {} : { rule: decision.rule }),\n ...(decision.by === undefined ? {} : { by: decision.by }),\n policyVersion: ctx.policyVersion,\n inputHash,\n });\n }\n\n async #evaluate(call: ToolCall, ctx: PolicyContext): Promise<Decision> {\n const target = targetOf(this.#namesOf(call.tool), call.input);\n const hook = await this.#runHooks(call, ctx);\n if (hook?.decision === \"deny\") return hook;\n const denied = this.#firstMatch(\"deny\", this.#config.deny, target);\n if (denied !== undefined) return denied;\n // Read-only mode is a limit, so no approval may widen it.\n const readOnly = ctx.mode === \"read_only\" ? this.#byMode(target, ctx.mode) : undefined;\n if (readOnly?.decision === \"deny\") return readOnly;\n // Nothing runs in shadow mode, so a question to a person would have no call to wait for.\n const shadow = ctx.mode === \"shadow\";\n if (hook !== undefined && !shadow) return hook;\n const asked = shadow ? undefined : this.#firstMatch(\"ask\", this.#config.ask, target);\n if (asked !== undefined) return asked;\n return (\n this.#byMode(target, ctx.mode) ??\n this.#byAllowRule(target) ??\n (await this.#byHostCallback(call, ctx)) ??\n this.#noMatch()\n );\n }\n\n /** Runs every hook in order. The first deny ends the run of hooks, and the first ask is held in case a later step denies. */\n async #runHooks(call: ToolCall, ctx: PolicyContext): Promise<Decision | undefined> {\n let held: Decision | undefined;\n for (const [index, hook] of (this.#config.hooks ?? []).entries()) {\n const result = await this.#runHook(hook, index, call, ctx);\n if (result?.decision === \"deny\") return result;\n held ??= result;\n }\n return held;\n }\n\n async #runHook(hook: PermissionHook, index: number, call: ToolCall, ctx: PolicyContext) {\n const rule = `hook[${index}]`;\n try {\n const result = await hook(call, ctx);\n if (result === undefined) return undefined;\n const { decision, reason } = result as { decision?: unknown; reason?: unknown };\n if ((decision !== \"deny\" && decision !== \"ask\") || typeof reason !== \"string\") {\n return deny(`${rule} returned ${JSON.stringify(decision)}, and a hook may only deny or ask`, rule, \"hook\");\n }\n return { decision, reason, rule: result.rule ?? rule, by: \"hook\" } satisfies Decision;\n } catch (error) {\n return deny(`${rule} failed, so the call was refused: ${describe(error)}`, rule, \"hook\");\n }\n }\n\n #firstMatch(list: \"deny\" | \"ask\", rules: readonly Rule[] | undefined, target: Target): Decision | undefined {\n const index = (rules ?? []).findIndex((rule) => restricts(rule, target));\n const rule = rules?.[index];\n if (rule === undefined) return undefined;\n return { decision: list, reason: rule.reason ?? `${list}[${index}] matched`, rule: `${list}[${index}]` };\n }\n\n #byMode(target: Target, mode: PermissionConfig[\"mode\"]): Decision | undefined {\n const named = (tools: readonly string[]) => tools.some((tool) => toolMatches(tool, target.names));\n const allow = (): Decision => ({\n decision: \"allow\",\n reason: `${mode} mode allows this`,\n rule: `mode:${mode}`,\n by: \"mode\",\n });\n if (mode === \"bypass\" || mode === \"shadow\") return allow();\n if (mode === \"accept_edits\") return named(this.#config.editTools ?? DEFAULT_EDIT_TOOLS) ? allow() : undefined;\n if (mode !== \"read_only\") return undefined;\n return named(this.#config.readOnlyTools ?? DEFAULT_READ_ONLY_TOOLS)\n ? allow()\n : deny(\"read_only mode allows only read-only tools\", \"mode:read_only\", \"mode\");\n }\n\n #byAllowRule(target: Target): Decision | undefined {\n const rules = this.#config.allow ?? [];\n const index = permits(rules, target);\n const rule = index === undefined ? undefined : rules[index];\n if (index === undefined || rule === undefined) return undefined;\n if (this.#config.hostCallback !== undefined && isUnconditional(rule)) {\n throw new PermissionConfigError(`allow[${index}] allows every call to a tool the host callback should decide`);\n }\n return { decision: \"allow\", reason: rule.reason ?? `allow[${index}] matched`, rule: `allow[${index}]` };\n }\n\n async #byHostCallback(call: ToolCall, ctx: PolicyContext): Promise<Decision | undefined> {\n const callback = this.#config.hostCallback;\n if (callback === undefined) return undefined;\n try {\n const result = await callback(call, ctx);\n if (!DECISIONS.includes(result?.decision) || typeof result.reason !== \"string\") {\n return deny(\n \"the host callback returned something that is not a decision, so the call was refused\",\n \"host_callback\",\n \"host\",\n );\n }\n return { ...result, by: result.by ?? \"host\" };\n } catch (error) {\n return deny(`the host callback failed, so the call was refused: ${describe(error)}`, \"host_callback\", \"host\");\n }\n }\n\n #noMatch(): Decision {\n return this.#config.interactive\n ? { decision: \"ask\", reason: \"No rule covers this call, so a person decides.\", rule: \"no_match\" }\n : deny(\"No rule covers this call and nobody can be asked, so it is refused.\", \"no_match\");\n }\n}\n\n/**\n * Creates the pipeline. It throws a `PermissionConfigError` when an allow rule covers every call to a registered tool\n * while a host callback is set. Deny rules, hooks and a host callback with no allow rules never throw it.\n *\n * With no host callback, a call that no rule settles asks when `interactive` is true and is denied when it is false.\n */\nexport function createPermissionPipeline(config: PermissionConfig, registry: ToolRegistry): PermissionPipeline {\n return new Pipeline(config, registry);\n}\n"]}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** Rule matching: whether a rule covers a call, for a rule that restricts (deny, ask) and one that permits (allow). */
|
|
2
|
+
import { type ParsedCommand } from "./match.js";
|
|
3
|
+
import type { Rule } from "./types.js";
|
|
4
|
+
/** What the rules read from one call. */
|
|
5
|
+
export interface Target {
|
|
6
|
+
/** The tool's canonical name and its alias. */
|
|
7
|
+
readonly names: readonly string[];
|
|
8
|
+
readonly paths: readonly string[];
|
|
9
|
+
readonly command: ParsedCommand | undefined;
|
|
10
|
+
}
|
|
11
|
+
export declare function targetOf(names: readonly string[], input: unknown): Target;
|
|
12
|
+
export declare function toolMatches(tool: string | RegExp, names: readonly string[]): boolean;
|
|
13
|
+
/** True for a rule with no `paths` and no `commandPrefix`, which covers every call to its tool. */
|
|
14
|
+
export declare function isUnconditional(rule: Rule): boolean;
|
|
15
|
+
/** A deny or ask rule matches when the tool matches and any path and any command part it names is in the call. */
|
|
16
|
+
export declare function restricts(rule: Rule, target: Target): boolean;
|
|
17
|
+
/**
|
|
18
|
+
* The index of the allow rule that allows the whole call, or `undefined`. A rule with no command prefix allows the call
|
|
19
|
+
* when its tool and paths match. Otherwise every command part must start with the prefix of some rule, and a command
|
|
20
|
+
* that hides commands in a substitution is never allowed, because its parts can't all be read.
|
|
21
|
+
*/
|
|
22
|
+
export declare function permits(rules: readonly Rule[], target: Target): number | undefined;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/** Rule matching: whether a rule covers a call, for a rule that restricts (deny, ask) and one that permits (allow). */
|
|
2
|
+
import { commandOf, globToRegExp, nameMatches, pathsOf, startsWithWords, strippedWords, } from "./match.js";
|
|
3
|
+
export function targetOf(names, input) {
|
|
4
|
+
return { names, paths: pathsOf(input), command: commandOf(input) };
|
|
5
|
+
}
|
|
6
|
+
export function toolMatches(tool, names) {
|
|
7
|
+
if (typeof tool === "string")
|
|
8
|
+
return names.some((name) => nameMatches(tool, name));
|
|
9
|
+
return names.some((name) => {
|
|
10
|
+
tool.lastIndex = 0;
|
|
11
|
+
return tool.test(name);
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
/** True for a rule with no `paths` and no `commandPrefix`, which covers every call to its tool. */
|
|
15
|
+
export function isUnconditional(rule) {
|
|
16
|
+
return rule.paths === undefined && rule.commandPrefix === undefined;
|
|
17
|
+
}
|
|
18
|
+
// A deny or ask rule matches a relative glob below any directory, and an allow rule only from the workspace root.
|
|
19
|
+
const pathHits = (rule, path, anywhere) => (rule.paths ?? []).some((glob) => globToRegExp(glob, anywhere).test(path));
|
|
20
|
+
/** A deny or ask rule matches when the tool matches and any path and any command part it names is in the call. */
|
|
21
|
+
export function restricts(rule, target) {
|
|
22
|
+
if (!toolMatches(rule.tool, target.names))
|
|
23
|
+
return false;
|
|
24
|
+
if (rule.paths !== undefined && !target.paths.some((path) => pathHits(rule, path, true)))
|
|
25
|
+
return false;
|
|
26
|
+
const prefix = rule.commandPrefix;
|
|
27
|
+
if (prefix === undefined)
|
|
28
|
+
return true;
|
|
29
|
+
// A command the parser couldn't read, or that is in no field it knows, may be anything, so a restriction applies.
|
|
30
|
+
if (target.command === undefined || target.command.unreadable)
|
|
31
|
+
return true;
|
|
32
|
+
return target.command.parts.some((words) => startsWithWords(words, prefix) || startsWithWords(strippedWords(words), prefix));
|
|
33
|
+
}
|
|
34
|
+
const SAFE_REDIRECT = /^(?:\d*>&\d+|(?:\d*|&)>>?\/dev\/null)$/;
|
|
35
|
+
const REDIRECT_OPERATOR = /^(?:\d*|&)>>?$/;
|
|
36
|
+
/**
|
|
37
|
+
* Whether a command part redirects input or output to a file. A rule for a command prefix covers the command and not
|
|
38
|
+
* the file it writes or reads, so only a copy of one stream to another and a redirect to /dev/null are let through.
|
|
39
|
+
*/
|
|
40
|
+
function writesOrReadsFiles(words) {
|
|
41
|
+
return words.some((word, index) => {
|
|
42
|
+
if (!/[<>]/.test(word) || SAFE_REDIRECT.test(word))
|
|
43
|
+
return false;
|
|
44
|
+
return !(REDIRECT_OPERATOR.test(word) && words[index + 1] === "/dev/null");
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
/** Whether `rule` could allow this part of a call: its tool, its paths (all of the call's) and its command prefix. */
|
|
48
|
+
function permitsPart(rule, target, words) {
|
|
49
|
+
if (!toolMatches(rule.tool, target.names))
|
|
50
|
+
return false;
|
|
51
|
+
if (rule.paths !== undefined &&
|
|
52
|
+
!(target.paths.length > 0 && target.paths.every((path) => pathHits(rule, path, false)))) {
|
|
53
|
+
return false;
|
|
54
|
+
}
|
|
55
|
+
if (rule.commandPrefix === undefined)
|
|
56
|
+
return true;
|
|
57
|
+
return words !== undefined && startsWithWords(words, rule.commandPrefix) && !writesOrReadsFiles(words);
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The index of the allow rule that allows the whole call, or `undefined`. A rule with no command prefix allows the call
|
|
61
|
+
* when its tool and paths match. Otherwise every command part must start with the prefix of some rule, and a command
|
|
62
|
+
* that hides commands in a substitution is never allowed, because its parts can't all be read.
|
|
63
|
+
*/
|
|
64
|
+
export function permits(rules, target) {
|
|
65
|
+
const whole = rules.findIndex((rule) => rule.commandPrefix === undefined && permitsPart(rule, target, undefined));
|
|
66
|
+
if (whole >= 0)
|
|
67
|
+
return whole;
|
|
68
|
+
const command = target.command;
|
|
69
|
+
if (command === undefined || command.opaque || command.parts.length === 0)
|
|
70
|
+
return undefined;
|
|
71
|
+
const used = command.parts.map((words) => rules.findIndex((rule) => permitsPart(rule, target, words)));
|
|
72
|
+
return used.every((index) => index >= 0) ? used[0] : undefined;
|
|
73
|
+
}
|
|
74
|
+
//# sourceMappingURL=rules.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rules.js","sourceRoot":"","sources":["../../src/permissions/rules.ts"],"names":[],"mappings":"AAAA,uHAAuH;AACvH,OAAO,EACL,SAAS,EACT,YAAY,EACZ,WAAW,EAEX,OAAO,EACP,eAAe,EACf,aAAa,GACd,MAAM,YAAY,CAAC;AAWpB,MAAM,UAAU,QAAQ,CAAC,KAAwB,EAAE,KAAc;IAC/D,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;AACrE,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,IAAqB,EAAE,KAAwB;IACzE,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;IACnF,OAAO,KAAK,CAAC,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I,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAC;AACzG,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,OAAO,CAAC,KAAsB,EAAE,MAAc;IAC5D,MAAM,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,KAAK,SAAS,IAAI,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,CAAC,CAAC,CAAC;IAClH,IAAI,KAAK,IAAI,CAAC;QAAE,OAAO,KAAK,CAAC;IAC7B,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC;IAC/B,IAAI,OAAO,KAAK,SAAS,IAAI,OAAO,CAAC,MAAM,IAAI,OAAO,CAAC,KAAK,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IAC5F,MAAM,IAAI,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;IACvG,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;AACjE,CAAC","sourcesContent":["/** Rule matching: whether a rule covers a call, for a rule that restricts (deny, ask) and one that permits (allow). */\nimport {\n commandOf,\n globToRegExp,\n nameMatches,\n type ParsedCommand,\n pathsOf,\n startsWithWords,\n strippedWords,\n} from \"./match.js\";\nimport type { Rule } from \"./types.js\";\n\n/** What the rules read from one call. */\nexport interface Target {\n /** The tool's canonical name and its alias. */\n readonly names: readonly string[];\n readonly paths: readonly string[];\n readonly command: ParsedCommand | undefined;\n}\n\nexport function targetOf(names: readonly string[], input: unknown): Target {\n return { names, paths: pathsOf(input), command: commandOf(input) };\n}\n\nexport function toolMatches(tool: string | RegExp, names: readonly string[]): boolean {\n if (typeof tool === \"string\") return names.some((name) => nameMatches(tool, name));\n return names.some((name) => {\n tool.lastIndex = 0;\n return tool.test(name);\n });\n}\n\n/** True for a rule with no `paths` and no `commandPrefix`, which covers every call to its tool. */\nexport function isUnconditional(rule: Rule): boolean {\n return rule.paths === undefined && rule.commandPrefix === undefined;\n}\n\n// A deny or ask rule matches a relative glob below any directory, and an allow rule only from the workspace root.\nconst pathHits = (rule: Rule, path: string, anywhere: boolean): boolean =>\n (rule.paths ?? []).some((glob) => globToRegExp(glob, anywhere).test(path));\n\n/** A deny or ask rule matches when the tool matches and any path and any command part it names is in the call. */\nexport function restricts(rule: Rule, target: Target): boolean {\n if (!toolMatches(rule.tool, target.names)) return false;\n if (rule.paths !== undefined && !target.paths.some((path) => pathHits(rule, path, true))) return false;\n const prefix = rule.commandPrefix;\n if (prefix === undefined) return true;\n // A command the parser couldn't read, or that is in no field it knows, may be anything, so a restriction applies.\n if (target.command === undefined || target.command.unreadable) return true;\n return target.command.parts.some(\n (words) => startsWithWords(words, prefix) || startsWithWords(strippedWords(words), prefix),\n );\n}\n\nconst SAFE_REDIRECT = /^(?:\\d*>&\\d+|(?:\\d*|&)>>?\\/dev\\/null)$/;\nconst REDIRECT_OPERATOR = /^(?:\\d*|&)>>?$/;\n\n/**\n * Whether a command part redirects input or output to a file. A rule for a command prefix covers the command and not\n * the file it writes or reads, so only a copy of one stream to another and a redirect to /dev/null are let through.\n */\nfunction writesOrReadsFiles(words: readonly string[]): boolean {\n return words.some((word, index) => {\n if (!/[<>]/.test(word) || SAFE_REDIRECT.test(word)) return false;\n return !(REDIRECT_OPERATOR.test(word) && words[index + 1] === \"/dev/null\");\n });\n}\n\n/** Whether `rule` could allow this part of a call: its tool, its paths (all of the call's) and its command prefix. */\nfunction permitsPart(rule: Rule, target: Target, words: readonly string[] | undefined): boolean {\n if (!toolMatches(rule.tool, target.names)) return false;\n if (\n rule.paths !== undefined &&\n !(target.paths.length > 0 && target.paths.every((path) => pathHits(rule, path, false)))\n ) {\n return false;\n }\n if (rule.commandPrefix === undefined) return true;\n return words !== undefined && startsWithWords(words, rule.commandPrefix) && !writesOrReadsFiles(words);\n}\n\n/**\n * The index of the allow rule that allows the whole call, or `undefined`. A rule with no command prefix allows the call\n * when its tool and paths match. Otherwise every command part must start with the prefix of some rule, and a command\n * that hides commands in a substitution is never allowed, because its parts can't all be read.\n */\nexport function permits(rules: readonly Rule[], target: Target): number | undefined {\n const whole = rules.findIndex((rule) => rule.commandPrefix === undefined && permitsPart(rule, target, undefined));\n if (whole >= 0) return whole;\n const command = target.command;\n if (command === undefined || command.opaque || command.parts.length === 0) return undefined;\n const used = command.parts.map((words) => rules.findIndex((rule) => permitsPart(rule, target, words)));\n return used.every((index) => index >= 0) ? used[0] : undefined;\n}\n"]}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type ToolDefinition } from "@buildanagent/sdk";
|
|
2
|
+
import type { RegisteredTool } from "../tools/types.js";
|
|
3
|
+
import type { PermissionMode, PolicySession } from "./types.js";
|
|
4
|
+
/** The wrapper behind `PermissionPipeline.shadowWrapper()`, which owns the mode it is given. */
|
|
5
|
+
export declare function shadowWrapper(session: PolicySession, mode: PermissionMode): (tool: RegisteredTool) => ToolDefinition<unknown, unknown, unknown>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { canonicalInputHash } from "@buildanagent/sdk";
|
|
2
|
+
const SHADOW_RESULT = "Shadow mode: this call was recorded and not run.";
|
|
3
|
+
/** The wrapper behind `PermissionPipeline.shadowWrapper()`, which owns the mode it is given. */
|
|
4
|
+
export function shadowWrapper(session, mode) {
|
|
5
|
+
return (tool) => {
|
|
6
|
+
if (mode !== "shadow")
|
|
7
|
+
return tool.definition;
|
|
8
|
+
return {
|
|
9
|
+
...tool.definition,
|
|
10
|
+
async execute(input, ctx) {
|
|
11
|
+
await session.append({
|
|
12
|
+
type: "shadow_call",
|
|
13
|
+
callId: ctx.callId,
|
|
14
|
+
tool: tool.canonicalName,
|
|
15
|
+
inputHash: await canonicalInputHash(input),
|
|
16
|
+
});
|
|
17
|
+
return { content: [{ type: "text", text: SHADOW_RESULT }] };
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=shadow.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"shadow.js","sourceRoot":"","sources":["../../src/permissions/shadow.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAuB,MAAM,mBAAmB,CAAC;AAI5E,MAAM,aAAa,GAAG,kDAAkD,CAAC;AAEzE,gGAAgG;AAChG,MAAM,UAAU,aAAa,CAC3B,OAAsB,EACtB,IAAoB;IAEpB,OAAO,CAAC,IAAI,EAAE,EAAE;QACd,IAAI,IAAI,KAAK,QAAQ;YAAE,OAAO,IAAI,CAAC,UAAU,CAAC;QAC9C,OAAO;YACL,GAAG,IAAI,CAAC,UAAU;YAClB,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG;gBACtB,MAAM,OAAO,CAAC,MAAM,CAAC;oBACnB,IAAI,EAAE,aAAa;oBACnB,MAAM,EAAE,GAAG,CAAC,MAAM;oBAClB,IAAI,EAAE,IAAI,CAAC,aAAa;oBACxB,SAAS,EAAE,MAAM,kBAAkB,CAAC,KAAK,CAAC;iBAC3C,CAAC,CAAC;gBACH,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,EAAE,CAAC,EAAE,CAAC;YAC9D,CAAC;SACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { canonicalInputHash, type ToolDefinition } from \"@buildanagent/sdk\";\nimport type { RegisteredTool } from \"../tools/types.js\";\nimport type { PermissionMode, PolicySession } from \"./types.js\";\n\nconst SHADOW_RESULT = \"Shadow mode: this call was recorded and not run.\";\n\n/** The wrapper behind `PermissionPipeline.shadowWrapper()`, which owns the mode it is given. */\nexport function shadowWrapper(\n session: PolicySession,\n mode: PermissionMode,\n): (tool: RegisteredTool) => ToolDefinition<unknown, unknown, unknown> {\n return (tool) => {\n if (mode !== \"shadow\") return tool.definition;\n return {\n ...tool.definition,\n async execute(input, ctx) {\n await session.append({\n type: \"shadow_call\",\n callId: ctx.callId,\n tool: tool.canonicalName,\n inputHash: await canonicalInputHash(input),\n });\n return { content: [{ type: \"text\", text: SHADOW_RESULT }] };\n },\n };\n };\n}\n"]}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/** The types of `@buildanagent/harness/permissions`. */
|
|
2
|
+
import type { PermissionDecisionEntry, PermissionMode, SessionEntry, ShadowCallEntry } from "@buildanagent/protocol";
|
|
3
|
+
import type { Interceptors, ToolCallEvent, ToolDefinition } from "@buildanagent/sdk";
|
|
4
|
+
import type { RegisteredTool } from "../tools/types.js";
|
|
5
|
+
export type { PermissionMode };
|
|
6
|
+
/** The entries the permission code writes. The session's store fills in the id, parent, sequence, time and origin. */
|
|
7
|
+
export type RecordedEntry = PermissionDecisionEntry | ShadowCallEntry;
|
|
8
|
+
/** The part of a session the permission code needs: somewhere to append the entries it writes. */
|
|
9
|
+
export interface PolicySession {
|
|
10
|
+
/** Appends one entry to the session's log. A rejection fails the call that wrote it, so nothing runs unrecorded. */
|
|
11
|
+
append(entry: RecordedEntry): Promise<unknown>;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A rule that matches tool calls. `tool` is a name or alias (a `*` in a string matches any run of characters) or a
|
|
15
|
+
* `RegExp` tested against the name and the alias. `paths` are globs (`*`, `**`, `?`) matched against the path
|
|
16
|
+
* fields of the input, and `commandPrefix` is the leading words of a shell command. A rule with neither covers every
|
|
17
|
+
* call to the tool.
|
|
18
|
+
*/
|
|
19
|
+
export interface Rule {
|
|
20
|
+
readonly tool: string | RegExp;
|
|
21
|
+
readonly paths?: readonly string[];
|
|
22
|
+
readonly commandPrefix?: readonly string[];
|
|
23
|
+
/** What the model and the approver read when this rule decides. */
|
|
24
|
+
readonly reason?: string;
|
|
25
|
+
}
|
|
26
|
+
/** One tool call to decide. `initiator` is `code` for a call the host's own code chose to make. */
|
|
27
|
+
export interface ToolCall {
|
|
28
|
+
readonly callId: string;
|
|
29
|
+
readonly tool: string;
|
|
30
|
+
readonly input: unknown;
|
|
31
|
+
readonly initiator: "model" | "code";
|
|
32
|
+
}
|
|
33
|
+
/** What a decision may read: the session, the turn's host context and the session's entries. */
|
|
34
|
+
export interface PolicyInput {
|
|
35
|
+
readonly session: PolicySession;
|
|
36
|
+
readonly hostContext: unknown;
|
|
37
|
+
readonly entries: readonly SessionEntry[];
|
|
38
|
+
}
|
|
39
|
+
/** What a hook or the host callback receives: `PolicyInput` plus the pipeline's own mode and policy version. */
|
|
40
|
+
export interface PolicyContext extends PolicyInput {
|
|
41
|
+
readonly mode: PermissionMode;
|
|
42
|
+
readonly policyVersion: string;
|
|
43
|
+
}
|
|
44
|
+
/** What a hook may return: a refusal or a question, never an allow. */
|
|
45
|
+
export interface HookDecision {
|
|
46
|
+
readonly decision: "deny" | "ask";
|
|
47
|
+
readonly reason: string;
|
|
48
|
+
readonly rule?: string;
|
|
49
|
+
}
|
|
50
|
+
/** A hook that can deny or ask about a call and cannot allow it, by type and at run time. */
|
|
51
|
+
export type PermissionHook = (call: ToolCall, ctx: PolicyContext) => Promise<HookDecision | undefined>;
|
|
52
|
+
/** The pipeline's decision on one call. */
|
|
53
|
+
export interface Decision {
|
|
54
|
+
readonly decision: "allow" | "deny" | "ask";
|
|
55
|
+
readonly reason: string;
|
|
56
|
+
/** The rule that decided, such as `deny[0]`, `mode:bypass` or `no_match`, or the one a hook named. */
|
|
57
|
+
readonly rule?: string;
|
|
58
|
+
/** Who decided, when it was not a rule: `hook`, `mode`, or what the host callback gave. */
|
|
59
|
+
readonly by?: string;
|
|
60
|
+
}
|
|
61
|
+
/** The pipeline's settings. */
|
|
62
|
+
export interface PermissionConfig {
|
|
63
|
+
/**
|
|
64
|
+
* `default` adds nothing. `accept_edits` allows `editTools`. `read_only` allows `readOnlyTools` and denies every
|
|
65
|
+
* other tool. `bypass` allows what no hook, deny rule or ask rule stopped. `shadow` allows the same calls, because
|
|
66
|
+
* the shadow wrapper runs nothing.
|
|
67
|
+
*/
|
|
68
|
+
readonly mode: PermissionMode;
|
|
69
|
+
/** Run first, in order. A hook may deny or ask, never allow. A hook that throws denies the call. */
|
|
70
|
+
readonly hooks?: readonly PermissionHook[];
|
|
71
|
+
readonly deny?: readonly Rule[];
|
|
72
|
+
readonly ask?: readonly Rule[];
|
|
73
|
+
readonly allow?: readonly Rule[];
|
|
74
|
+
/** Decides, last, what no rule settled. */
|
|
75
|
+
readonly hostCallback?: (call: ToolCall, ctx: PolicyContext) => Promise<Decision>;
|
|
76
|
+
/** Whether a person can answer. With no `hostCallback`, a call no rule settles asks when true and is denied when false. */
|
|
77
|
+
readonly interactive: boolean;
|
|
78
|
+
/** Carried on every ask, so a later change of policy shows when an approval is checked against it. */
|
|
79
|
+
readonly policyVersion: string;
|
|
80
|
+
/** The tools `accept_edits` allows, by name or alias. Default `write`, `edit`, `multi_edit` and `apply_patch`. */
|
|
81
|
+
readonly editTools?: readonly string[];
|
|
82
|
+
/** The tools `read_only` allows, by name or alias. Default `read`, `grep` and `glob`. */
|
|
83
|
+
readonly readOnlyTools?: readonly string[];
|
|
84
|
+
}
|
|
85
|
+
/** The pipeline `createPermissionPipeline()` returns. */
|
|
86
|
+
export interface PermissionPipeline {
|
|
87
|
+
/**
|
|
88
|
+
* Decides one call and writes one `permission_decision` entry for it, allows included. It fails closed: a hook or
|
|
89
|
+
* host callback that throws, or returns something unusable, denies the call. An entry that can't be written rejects.
|
|
90
|
+
*/
|
|
91
|
+
decide(call: ToolCall, input: PolicyInput): Promise<Decision>;
|
|
92
|
+
/**
|
|
93
|
+
* The SDK's `beforeToolCall` gate. `context` supplies the session, host context and entries for each call, and the
|
|
94
|
+
* gate denies a call when `context` or `decide()` throws. An `ask` carries the config's `policyVersion`.
|
|
95
|
+
*/
|
|
96
|
+
gate(context: (event: ToolCallEvent) => PolicyInput | Promise<PolicyInput>): Pick<Interceptors, "beforeToolCall">;
|
|
97
|
+
/**
|
|
98
|
+
* A `ToolWrapper` for `registry.definitions()`. In `shadow` mode it replaces each tool's `execute` with one that
|
|
99
|
+
* writes a `shadow_call` entry to `session` and returns a fixed result, so the tool never runs. In every other mode
|
|
100
|
+
* it returns the tool as registered. A pipeline in `shadow` mode refuses every call until this has been called, so a
|
|
101
|
+
* host can't shadow by mode alone and run the tools for real.
|
|
102
|
+
*/
|
|
103
|
+
shadowWrapper(session: PolicySession): (tool: RegisteredTool) => ToolDefinition<unknown, unknown, unknown>;
|
|
104
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/permissions/types.ts"],"names":[],"mappings":"","sourcesContent":["/** The types of `@buildanagent/harness/permissions`. */\nimport type { PermissionDecisionEntry, PermissionMode, SessionEntry, ShadowCallEntry } from \"@buildanagent/protocol\";\nimport type { Interceptors, ToolCallEvent, ToolDefinition } from \"@buildanagent/sdk\";\nimport type { RegisteredTool } from \"../tools/types.js\";\n\nexport type { PermissionMode };\n\n/** The entries the permission code writes. The session's store fills in the id, parent, sequence, time and origin. */\nexport type RecordedEntry = PermissionDecisionEntry | ShadowCallEntry;\n\n/** The part of a session the permission code needs: somewhere to append the entries it writes. */\nexport interface PolicySession {\n /** Appends one entry to the session's log. A rejection fails the call that wrote it, so nothing runs unrecorded. */\n append(entry: RecordedEntry): Promise<unknown>;\n}\n\n/**\n * A rule that matches tool calls. `tool` is a name or alias (a `*` in a string matches any run of characters) or a\n * `RegExp` tested against the name and the alias. `paths` are globs (`*`, `**`, `?`) matched against the path\n * fields of the input, and `commandPrefix` is the leading words of a shell command. A rule with neither covers every\n * call to the tool.\n */\nexport interface Rule {\n readonly tool: string | RegExp;\n readonly paths?: readonly string[];\n readonly commandPrefix?: readonly string[];\n /** What the model and the approver read when this rule decides. */\n readonly reason?: string;\n}\n\n/** One tool call to decide. `initiator` is `code` for a call the host's own code chose to make. */\nexport interface ToolCall {\n readonly callId: string;\n readonly tool: string;\n readonly input: unknown;\n readonly initiator: \"model\" | \"code\";\n}\n\n/** What a decision may read: the session, the turn's host context and the session's entries. */\nexport interface PolicyInput {\n readonly session: PolicySession;\n readonly hostContext: unknown;\n readonly entries: readonly SessionEntry[];\n}\n\n/** What a hook or the host callback receives: `PolicyInput` plus the pipeline's own mode and policy version. */\nexport interface PolicyContext extends PolicyInput {\n readonly mode: PermissionMode;\n readonly policyVersion: string;\n}\n\n/** What a hook may return: a refusal or a question, never an allow. */\nexport interface HookDecision {\n readonly decision: \"deny\" | \"ask\";\n readonly reason: string;\n readonly rule?: string;\n}\n\n/** A hook that can deny or ask about a call and cannot allow it, by type and at run time. */\nexport type PermissionHook = (call: ToolCall, ctx: PolicyContext) => Promise<HookDecision | undefined>;\n\n/** The pipeline's decision on one call. */\nexport interface Decision {\n readonly decision: \"allow\" | \"deny\" | \"ask\";\n readonly reason: string;\n /** The rule that decided, such as `deny[0]`, `mode:bypass` or `no_match`, or the one a hook named. */\n readonly rule?: string;\n /** Who decided, when it was not a rule: `hook`, `mode`, or what the host callback gave. */\n readonly by?: string;\n}\n\n/** The pipeline's settings. */\nexport interface PermissionConfig {\n /**\n * `default` adds nothing. `accept_edits` allows `editTools`. `read_only` allows `readOnlyTools` and denies every\n * other tool. `bypass` allows what no hook, deny rule or ask rule stopped. `shadow` allows the same calls, because\n * the shadow wrapper runs nothing.\n */\n readonly mode: PermissionMode;\n /** Run first, in order. A hook may deny or ask, never allow. A hook that throws denies the call. */\n readonly hooks?: readonly PermissionHook[];\n readonly deny?: readonly Rule[];\n readonly ask?: readonly Rule[];\n readonly allow?: readonly Rule[];\n /** Decides, last, what no rule settled. */\n readonly hostCallback?: (call: ToolCall, ctx: PolicyContext) => Promise<Decision>;\n /** Whether a person can answer. With no `hostCallback`, a call no rule settles asks when true and is denied when false. */\n readonly interactive: boolean;\n /** Carried on every ask, so a later change of policy shows when an approval is checked against it. */\n readonly policyVersion: string;\n /** The tools `accept_edits` allows, by name or alias. Default `write`, `edit`, `multi_edit` and `apply_patch`. */\n readonly editTools?: readonly string[];\n /** The tools `read_only` allows, by name or alias. Default `read`, `grep` and `glob`. */\n readonly readOnlyTools?: readonly string[];\n}\n\n/** The pipeline `createPermissionPipeline()` returns. */\nexport interface PermissionPipeline {\n /**\n * Decides one call and writes one `permission_decision` entry for it, allows included. It fails closed: a hook or\n * host callback that throws, or returns something unusable, denies the call. An entry that can't be written rejects.\n */\n decide(call: ToolCall, input: PolicyInput): Promise<Decision>;\n /**\n * The SDK's `beforeToolCall` gate. `context` supplies the session, host context and entries for each call, and the\n * gate denies a call when `context` or `decide()` throws. An `ask` carries the config's `policyVersion`.\n */\n gate(context: (event: ToolCallEvent) => PolicyInput | Promise<PolicyInput>): Pick<Interceptors, \"beforeToolCall\">;\n /**\n * A `ToolWrapper` for `registry.definitions()`. In `shadow` mode it replaces each tool's `execute` with one that\n * writes a `shadow_call` entry to `session` and returns a fixed result, so the tool never runs. In every other mode\n * it returns the tool as registered. A pipeline in `shadow` mode refuses every call until this has been called, so a\n * host can't shadow by mode alone and run the tools for real.\n */\n shadowWrapper(session: PolicySession): (tool: RegisteredTool) => ToolDefinition<unknown, unknown, unknown>;\n}\n"]}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { type HostFiles } from "./host-files.js";
|
|
2
|
+
import { type NodeModules } from "./process.js";
|
|
3
|
+
import type { ExecOptions, ExecResult, Sandbox } from "./types.js";
|
|
4
|
+
/** The state a backend's sandbox is built on. */
|
|
5
|
+
export interface BackendBase {
|
|
6
|
+
readonly modules: NodeModules;
|
|
7
|
+
/** The workspace's real root. */
|
|
8
|
+
readonly root: string;
|
|
9
|
+
readonly files: HostFiles;
|
|
10
|
+
}
|
|
11
|
+
/** A sandbox that checks a command the same way, reads and writes files in the host, and disposes once. */
|
|
12
|
+
export declare abstract class BackendSandbox implements Sandbox {
|
|
13
|
+
private disposed;
|
|
14
|
+
private disposing;
|
|
15
|
+
private readonly base;
|
|
16
|
+
protected constructor(base: BackendBase);
|
|
17
|
+
/** Throws `sandbox_disposed` once `dispose()` has been called. */
|
|
18
|
+
protected live(): void;
|
|
19
|
+
/**
|
|
20
|
+
* Checks a command and its options, and finds its working directory. It returns the real working directory to run in,
|
|
21
|
+
* or the result that settles the call without running anything: a denial for a directory outside the workspace, and
|
|
22
|
+
* exit code 127 for a first word with `=`, which `env` would read as an assignment, as `none` answers a program it
|
|
23
|
+
* can't find.
|
|
24
|
+
*/
|
|
25
|
+
protected prepare(command: readonly string[], options: ExecOptions): Promise<{
|
|
26
|
+
readonly cwd: string;
|
|
27
|
+
} | ExecResult>;
|
|
28
|
+
abstract exec(command: readonly string[], options: ExecOptions): Promise<ExecResult>;
|
|
29
|
+
readFile(path: string): Promise<Uint8Array>;
|
|
30
|
+
writeFile(path: string, data: Uint8Array): Promise<void>;
|
|
31
|
+
/** Stops what is running and cleans up. Every call gets the first call's promise, so a second caller waits too. */
|
|
32
|
+
dispose(): Promise<void>;
|
|
33
|
+
/** Ends the commands still running and removes what the sandbox made. It runs once. */
|
|
34
|
+
protected abstract shutDown(): Promise<void>;
|
|
35
|
+
}
|