policy
import { checkPolicy } from "std::policy"
const policy = {
"std::read": [{ action: "approve" }],
"std::write": [{ action: "reject", rejectMessage: "Leave files unchanged." }]
}
node main() {
handle {
return read("README.md")
} with (intr) {
return checkPolicy(policy, intr)
}
}Rules match an effect and optional glob patterns over its data. The first matching rule decides. If no effect-specific rule matches, checkPolicy tries the "*" rules, then returns propagate() to request a user decision. Other handlers can still reject an approved interrupt.
Use cliPolicyHandler for a terminal prompt that remembers "always" answers in a JSON policy file. Use the rule-building functions below when your application provides its own approval UI.
For a file read, the prompt offers two broader answers. "Always approve all reads in" (as) saves one rule under every effect in the FileRead set, so approving a read in a folder also approves listing and searching it. When there is more than one folder to choose from, both as and "always approve when" (ap) then ask which folder the rule covers: the folder in the interrupt or one of its parents, up to the launch directory and never the home directory. A rule saved this way sets matchDotFolders, so it also covers folders like .cache below the one chosen.
For a command (std::exec), "always approve when" asks up to two questions. The first is how much of the command the rule covers, from this exact command down to the program and its first argument followed by anything: pnpm run …. The second is the folder, as for a read.
Types
InterruptDataKey
Key of an interrupt's data object (e.g. "dir", "command").
/** Key of an interrupt's `data` object (e.g. `"dir"`, `"command"`). */
export type InterruptDataKey = string(source)
InterruptDataVal
Glob pattern used to match an interrupt-data value. Patterns are picomatch globs. They support *, **, and brace-expansion like {a,b} for unions. A literal string with no glob metacharacters matches only that exact value.
A list of globs matches a list value item by item. A last item of ** stands for any items after it, or none.
/**
Glob pattern used to match an interrupt-data value. Patterns are
picomatch globs. They support `*`, `**`, and brace-expansion like
`{a,b}` for unions. A literal string with no glob metacharacters
matches only that exact value.
A list of globs matches a list value item by item. A last item of `**`
stands for any items after it, or none.
*/
export type InterruptDataVal = string | string[](source)
InterruptEffect
Identifier for an interrupt's effect (e.g. "std::read", "myapp::deploy").
/**
Identifier for an interrupt's effect (e.g. `"std::read"`,
`"myapp::deploy"`).
*/
export type InterruptEffect = string(source)
PolicyRule
One row of a Policy. A rule passes if every key in match is present in the interrupt's data and its value matches the glob pattern. Omit match (or set it to {}) for a catch-all that applies to every interrupt of the parent effect.
When the value is a list, a string pattern matches when the list is not empty and every item matches, and a list pattern matches item by item. For example, { "cwd": "/me/proj", "paths": "src/**", "all": "false" } under std::git::add approves a git add whose paths are all under src, and asks about one that stages everything.
A reject rule may carry a rejectMessage: the message the rejection hands back to whoever raised the interrupt. For a rejected tool call this is what the model reads, so it can steer the next attempt — for example, a rule rejecting std::bash with rejectMessage: "Use safeBash instead".
A rule's globs skip path segments that start with a period: /x/** does not match /x/.cache/y. Set matchDotFolders: true to let them match. The approval prompt sets it on a rule whose folder came from its folder step.
/**
One row of a `Policy`. A rule passes if every key in `match` is
present in the interrupt's `data` and its value matches the glob
pattern. Omit `match` (or set it to `{}`) for a catch-all that
applies to every interrupt of the parent effect.
When the value is a list, a string pattern matches when the list is not
empty and every item matches, and a list pattern matches item by item.
For example, `{ "cwd": "/me/proj", "paths": "src/**", "all": "false" }`
under `std::git::add` approves a `git add` whose paths are all under
`src`, and asks about one that stages everything.
A reject rule may carry a `rejectMessage`: the message the rejection
hands back to whoever raised the interrupt. For a rejected tool call
this is what the model reads, so it can steer the next attempt — for
example, a rule rejecting `std::bash` with
`rejectMessage: "Use safeBash instead"`.
A rule's globs skip path segments that start with a period: `/x/**` does
not match `/x/.cache/y`. Set `matchDotFolders: true` to let them match.
The approval prompt sets it on a rule whose folder came from its folder
step.
*/
export type PolicyRule = {
match?: Record<InterruptDataKey, InterruptDataVal>;
action: "approve" | "reject" | "propagate";
rejectMessage?: string;
matchDotFolders?: boolean
}(source)
Policy
Ordered rules per effect, with optional "*" fallback rules. checkPolicy returns the first matching decision, or propagate() when no rule matches. Propagation requests a user decision unless a handler rejects the interrupt.
/**
Ordered rules per effect, with optional `"*"` fallback rules.
`checkPolicy` returns the first matching decision, or `propagate()`
when no rule matches. Propagation requests a user decision unless a
handler rejects the interrupt.
*/
export type Policy = Record<InterruptEffect, PolicyRule[]>(source)
Decision
CLI approval choices. "approve-always" and "reject-always" save an effect-wide rule. "approve-always-here" saves a rule scoped to selected interrupt data. "approve-always-set" saves that scoped rule under every effect of a file-reading effect set such as FileRead. Questions that need a value offer one-time choices only.
/**
CLI approval choices. "approve-always" and "reject-always" save an
effect-wide rule. "approve-always-here" saves a rule scoped to selected
interrupt data. "approve-always-set" saves that scoped rule under every
effect of a file-reading effect set such as `FileRead`. Questions that need
a value offer one-time choices only.
*/
export type Decision =
| "approve"
| "reject"
| "approve-always"
| "approve-always-here"
| "approve-always-set"
| "reject-always"(source)
ScopedField
One column in a ScopedRuleFields entry — names an interrupt-data field that an "always approve when" rule should pin.
field— the key inintr.datato pin (e.g."dir").matchSubpaths— whentrue, brace-expand the value so the rule matches both the exact value AND any nested path under it. Passtruefor directory-like fields (so approving/tmp/xalso approves/tmp/x/sub/file.txt). Passfalsefor opaque identifiers (commands, IDs, env names) that shouldn't fan out.matchPrefix— whentrue, the field is a list, and the rule pins its leading items. The approval prompt asks how many. Leave it out, or passfalse, for every other field.
/**
One column in a `ScopedRuleFields` entry — names an interrupt-data
field that an "always approve when" rule should pin.
- `field` — the key in `intr.data` to pin (e.g. `"dir"`).
- `matchSubpaths` — when `true`, brace-expand the value so the
rule matches both the exact value AND any nested path under it.
Pass `true` for directory-like fields (so approving `/tmp/x`
also approves `/tmp/x/sub/file.txt`). Pass `false` for opaque
identifiers (commands, IDs, env names) that shouldn't fan out.
- `matchPrefix` — when `true`, the field is a list, and the rule pins its
leading items. The approval prompt asks how many. Leave it out, or
pass `false`, for every other field.
*/
export type ScopedField = {
field: string;
matchSubpaths: boolean;
matchPrefix?: boolean
}(source)
ScopedRuleFields
Per-effect override consumed by buildScopedMatch and the cliPolicyHandler. Maps an interrupt effect to the fields its "always approve when" rule should pin. Effects not present in this map fall back to the scope their effect declaration carries (@always / @alwaysUnder); an empty list turns the (ap) option off for that effect, so the user falls back to (a) / (r) / (aa) / (rr). An override also counts for the set-wide (as) answer: it is offered only when every effect in the set resolves to the same scope.
Example:
const FIELDS: ScopedRuleFields = {
"std::read": [{ field: "dir", matchSubpaths: true }],
"std::exec": [
{ field: "command", matchSubpaths: false },
{ field: "args", matchSubpaths: false, matchPrefix: true },
],
}/**
Per-effect override consumed by `buildScopedMatch` and the
`cliPolicyHandler`. Maps an interrupt effect to the fields its
"always approve when" rule should pin. Effects not present in this
map fall back to the scope their `effect` declaration carries
(`@always` / `@alwaysUnder`); an empty list turns the (ap) option
off for that effect, so the user falls back to (a) / (r) / (aa) / (rr).
An override also counts for the set-wide (as) answer: it is offered only
when every effect in the set resolves to the same scope.
Example:
```ts
const FIELDS: ScopedRuleFields = {
"std::read": [{ field: "dir", matchSubpaths: true }],
"std::exec": [
{ field: "command", matchSubpaths: false },
{ field: "args", matchSubpaths: false, matchPrefix: true },
],
}
```
*/
export type ScopedRuleFields = Record<InterruptEffect, ScopedField[]>(source)
ParsePolicyFailureStatus
export type ParsePolicyFailureStatus =
| "doesnt-exist"
| "read-error"
| "malformed-json"
| "policy-not-valid"(source)
ParsePolicyFailure
export type ParsePolicyFailure = {
status: ParsePolicyFailureStatus
}(source)
Constants
minimalAutoApprovePolicy
The minimal built-in policy used by agency run --policy minimal.
/** The minimal built-in policy used by `agency run --policy minimal`. */
export static const minimalAutoApprovePolicy = _minimalAutoApprovePolicy(source)
recommendedAutoApprovePolicy
The recommended policy, with scoped file reads and service reads.
/** The recommended policy, with scoped file reads and service reads. */
export static const recommendedAutoApprovePolicy = _recommendedAutoApprovePolicy(source)
approveAllPolicy
Approve every effect; value-seeking interrupts still need an answer in the CLI handler.
/** Approve every effect; value-seeking interrupts still need an answer in the CLI handler. */
export static const approveAllPolicy = _approveAllPolicy(source)
BUILTIN_POLICIES
Built-in policy names and their descriptions, shared with the CLI.
/** Built-in policy names and their descriptions, shared with the CLI. */
export static const BUILTIN_POLICIES = _BUILTIN_POLICIES(source)
Functions
withWritesPolicy
withWritesPolicy(baseDir: string)Return the recommended policy with file and Git writes scoped to a directory.
Parameters:
| Name | Type | Default |
|---|---|---|
| baseDir | string |
(source)
builtinPolicy
builtinPolicy(name: string, baseDir: string): Policy | nullResolve a built-in policy name, or return null for an unknown name.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| name | string | ||
| baseDir | string | Directory scope for the with-writes policy. |
Returns: Policy | null
(source)
builtinPolicyNames
builtinPolicyNames(): string[]List the policy names accepted by builtinPolicy and the CLI.
Returns: string[]
(source)
checkPolicy
checkPolicy(policy: Record<string, any>, interrupt: Record<string, any>)Find the first matching approval rule for an interrupt. Return approve, reject, or propagate when no rule matches.
handle {
return read("README.md")
} with (intr) {
return checkPolicy(policy, intr)
}Return this decision directly from a custom handler. A rejection includes the rule's rejectMessage. No matching rule returns propagate(), which requests a user decision even if another handler approves. Use cliPolicyHandler when you also want terminal prompts and saved rules.
Parameters:
| Name | Type | Default |
|---|---|---|
| policy | Record<string, any> | |
| interrupt | Record<string, any> |
(source)
validatePolicy
validatePolicy(policy: Record<string, any>): Result<void>Validate a policy object, returning a failure that describes invalid rules.
Check user-supplied or hand-edited policy data before using it. setPolicy and addPolicyRules also validate before saving.
Parameters:
| Name | Type | Default |
|---|---|---|
| policy | Record<string, any> |
Returns: Result<void>
(source)
alwaysScopeFor
alwaysScopeFor(effect: string): ScopedField[]List the fields declared by an effect's @always and @alwaysUnder tags. Return an empty list when the effect declares no scope.
Parameters:
| Name | Type | Default |
|---|---|---|
| effect | string |
Returns: ScopedField[]
(source)
defaultScopedFields
defaultScopedFields(): ScopedRuleFieldsReturn the declared approval scopes for all effects, keyed by effect name.
Returns: ScopedRuleFields
(source)
buildScopedMatch
buildScopedMatch(
intr: Record<string, any>,
fields: ScopedRuleFields = {},
): Record<InterruptDataKey, InterruptDataVal>Build glob patterns that pin an interrupt's scoped field values. Return {} if there is no scope or a scoped value is missing.
Use this to preview a scoped rule in a custom approval UI:
const match = buildScopedMatch(intr)Directory fields can match the selected directory and its subpaths; other fields match their escaped literal values. Overrides in fields replace declared scopes.
An absent scope or missing scoped value returns {}. Check for an empty result before making a rule: an empty match applies to every interrupt of the effect. recordScopedRule performs that check for you.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| intr | Record<string, any> | ||
| fields | ScopedRuleFields | {} | Per-effect scope overrides, with unlisted effects using their declared scopes. |
Returns: Record<InterruptDataKey, InterruptDataVal>
(source)
recordRule
recordRule(
policy: Policy,
effect: InterruptEffect,
action: "approve" | "reject",
): PolicyAppend an effect-wide approval or rejection rule and return a new policy.
let policy = recordRule({}, "std::read", "reject")
policy = recordRule(policy, "std::read", "approve")The first rule still rejects: evaluation uses the first match, and this function appends rules. Replace or clear an existing rule when changing a previous decision. The input policy remains unchanged.
Parameters:
| Name | Type | Default |
|---|---|---|
| policy | Policy | |
| effect | InterruptEffect | |
| action | "approve" | "reject" |
Returns: Policy
(source)
recordScopedRule
recordScopedRule(
policy: Policy,
intr: Record<string, any>,
fields: ScopedRuleFields = {},
): PolicyPrepend an approval rule scoped to an interrupt's field values. Return the policy unchanged when there is no scope to pin.
Use this for an "always approve when" choice. It prepends an approval, so a matching scoped rule takes precedence over existing catch-all rules. The input policy remains unchanged. If no scope can be built, it returns the input policy without adding a rule. A field tagged @alwaysPrefix is pinned whole, which is the narrowest rule the terminal prompt offers.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| policy | Policy | ||
| intr | Record<string, any> | ||
| fields | ScopedRuleFields | {} | Per-effect scope overrides, with unlisted effects using their declared scopes. |
Returns: Policy
(source)
parsePolicyFile
parsePolicyFile(path: string): Result<Policy, ParsePolicyFailure>Read a JSON policy file and validate its rules, returning a failure on error.
Use the failure's data.status to distinguish a missing file, a failed read, malformed JSON, and an invalid policy. The function prints no warnings. Its inner read uses with approve; an outer handler can still reject it.
Parameters:
| Name | Type | Default |
|---|---|---|
| path | string |
Returns: Result<Policy, ParsePolicyFailure>
Throws: std::read
Needs: fileRead
(source)
setPolicy
setPolicy(path: string, policy: Policy): Result raises <std::write>Save a policy file and install it for the CLI approval handler.
Save a policy to path, then make it the CLI handler's active policy. The save raises std::write, so the caller's handlers decide whether it happens. If the save fails or is rejected, the active policy is unchanged. Later saves of "always" answers still go to the file passed to cliPolicyHandler.
Parameters:
| Name | Type | Default |
|---|---|---|
| path | string | |
| policy | Policy |
Returns: Result
Throws: std::write
Needs: fileRead, fileWrite
(source)
missingPolicyRules
missingPolicyRules(base: Policy): PolicyFind rules in a base policy that the CLI handler's active policy lacks.
Use this to offer updates when a saved policy lacks rules added to a newer built-in policy. Effects already covered by a catch-all are left out. Pass accepted additions to addPolicyRules.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| base | Policy | Policy to compare against, such as recommendedAutoApprovePolicy. |
Returns: Policy
Throws: std::read
Needs: fileRead, terminal
(source)
addPolicyRules
addPolicyRules(additions: Policy) raises <std::read, std::write>Append rules to the CLI handler's active policy and save it immediately.
Append accepted additions without overriding earlier decisions. If saving fails, the active policy stays unchanged.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| additions | Policy | Rules to add, such as the result of missingPolicyRules. |
Throws: std::write, std::read
Needs: fileRead, fileWrite, terminal
(source)
flushPolicy
flushPolicy() raises <std::read, std::write>Write any pending always-rule additions to the policy file now.
Call between user turns or before process exit to persist the last "always" decision. Automatic flushing happens at the next interrupt, so the final decision can otherwise remain unsaved. Does nothing without pending changes. If a handler refuses the save, the answers stay pending and a warning prints.
Throws: std::write, std::read
Needs: fileRead, fileWrite, terminal
(source)
cliPolicyHandler
cliPolicyHandler(
file: string,
fields: ScopedRuleFields = {},
policy: Policy | null = null,
interactive: boolean = true,
answersOnly: boolean = false,
): anyBuild a CLI approval handler that remembers decisions in a policy file. Call once per program and bind the result before installing it.
const handler = cliPolicyHandler(file: "/home/me/.myapp/policy.json")
handle {
return read("README.md")
} with handlerBind the returned function before using it in a with clause. Call once per program: the handler shares module-level policy state, and another call replaces its options and active policy.
It loads the file on the first interrupt unless you supply policy. A missing file starts with an empty policy. Other load errors also start empty and print a warning. Rules approve or reject matching interrupts; questions that need a value still require an answer. Unresolved interrupts prompt when interactive and fail when noninteractive.
"Always" decisions persist at the next interrupt. Call flushPolicy before exiting to save the final decision. Supplying policy skips the initial read; later decisions still save to file. The file's parent directory must already exist.
"Always approve when" uses scopes from effect declarations unless fields overrides them. An empty override disables that choice for the effect.
Parameters:
| Name | Type | Default | Description |
|---|---|---|---|
| file | string | Policy file path whose parent directory already exists. | |
| fields | ScopedRuleFields | {} | Per-effect scope overrides, with [] disabling scoped approval for an effect. |
| policy | Policy | null | null | Initial rules to use instead of reading the file, or null to load it. |
| interactive | boolean | true | Prompt for unresolved interrupts when true, or reject them when false. |
| answersOnly | boolean | false | Save only the rules "always" answers add to the file, never the rest of policy, for a policy layered from more than the file |
Returns: any
(source)