Configuration includes project settings, environment variables, frontmatter, SDK modes, and checkpoint/resume for continuing an interrupted run.

Config Files

mlld uses dual configuration:

  • mlld-config.json - Your project settings (edit manually)
  • mlld-lock.json - Auto-generated locks (don't edit)

mlld validate warning suppression lives in mlld-config.json:

{
  "validate": {
    "suppressWarnings": ["deprecated-json-transform"]
  }
}

Use suppression when a warning is intentional and reviewed.

The llm harness profile

The command in an llm executable's body (a claude or pi CLI call, say) is the harness that talks to the model. It runs under its own fence, and llm.harness declares what that fence allows. Inside a box the box also limits it: see Inside a box below.

{
  "llm": {
    "harness": {
      "home": "~/.agents/planner",
      "write": ["./tmp/transcripts"],
      "net": "open"
    }
  }
}
  • home is where the harness keeps its state. mlld lets the harness write there, and points it there by setting CLAUDE_CONFIG_DIR (the claude CLI), CODEX_HOME (codex) and PI_CODING_AGENT_DIR (pi) to it; each harness reads only its own. The directory must exist when a call that uses the profile starts. claude keeps its conversations in its home, so claude --resume finds an earlier conversation only when the same home is used again: give each agent a stable home of its own. A harness that starts a different provider passes it the same home; if that matters, set that provider's variable in the command yourself. With no home, mlld sets none of the three variables, and the harness uses its own default home, which write must then cover.
  • write lists the directories and files the harness may write. ~/ is your home directory, and a relative path is relative to the project folder. Everything else is read-only to the harness, including the project folder. Each path must exist when a call that uses the profile starts: a missing one refuses that call, naming the path, while a module that declares the profile still imports. The project folder itself (".") may be listed: the harness can then edit the project's files, but not its .llm/ or .mlld/ folders, mlld-config.json or mlld-lock.json, even ones that do not exist yet, so it cannot rewrite its own profile. A path inside one of those, or a folder above the project that contains it, is refused. The harness's own log folder, .llm/sessions/<provider>/, needs no entry: mlld makes it and lets the harness write there when its module's @conversation adapter names that provider (see tape-conversation). When it cannot be given safely (.llm or the folder is a link, or something other than a folder is in its place), the call runs without it: mlld prints mlld: llm @<name> runs without its sessions folder … and --trace effects records a box.llm.sessions_folder_dropped event. Inside a box the harness gets no such folder, and box.llm.harness_capped lists it under droppedWrites.
  • net is "none", "loopback" or "open", and "open" when left out, as the network is for any command outside a box. It cannot name hosts. A harness reaches its own call's tools under any tier: the fence lets it connect to that call's tool socket and to nothing else on the network the tier refuses. A node body still needs "open", because it reports its result over a separate local socket that the fence counts as network. A project policy's capabilities.network can lower this tier, never raise it.
  • egress lists the hosts the harness itself needs, such as its model API and its sign-in endpoints: egress: ["api.anthropic.com", "console.anthropic.com"]. Each entry is an exact host, *.name for its subdomains, or an IP address, with an optional :port (443 when left out). It only matters inside a box: there the harness may reach these hosts even when the box's network is closed, and a policy can still remove them. Outside a box net alone decides. egress belongs on the harness module's llm definition, not in this file: llm.harness in mlld-config.json refuses it, because a list of allowed hosts is policy rather than project setup. A malformed host refuses when the definition loads.

An llm definition can declare its own profile with using { harness: { home: "…", write: [...], net: "open" } }, with the same keys; it replaces this one for that definition, and nothing is merged (see as-with-overloads). Without a profile, an llm call inside a box is refused, naming the missing profile. Outside a box it runs under the default fence, which lets it write only inside the project folder; if it fails, the error says so. See box-blocks for what runs inside a box and what does not. mlld-config.json is itself out of reach of fenced commands, so a program cannot widen its harness's profile.

Inside a box. The harness still gets a fence of its own, and the box limits it:

  • Network: the profile's net, met with the box's network and then the policy's. The hosts in the profile's egress are added to what the box allows, so a harness reaches its model API even from a box with a closed network; anything else the box does not allow is refused. Unless the result is fully open, the harness reaches the network only through the box's egress proxy, so a refused connection prints mlld: box.net.denied: … naming what refused it (see "Host lists" in box-config). The hosts each harness needs are measured in llm-modules ("Network hosts each harness needs").
  • Writes: home stays writable. A write entry the box does not let its own commands write is dropped for that call: a vfs box and a sealed kernel box allow none, and a box a policy rule starts allows what the command it wraps could write. The box.llm.harness_capped trace event names what was dropped (see runtime-tracing).
  • Harness settings: inside home, the files a harness runs code from cannot be changed: settings.json and .claude.json (claude's hooks and MCP servers), config.toml (codex), settings.json and models.json in the agent folder (pi), and opencode.jsonc, opencode.json and package.json (opencode). The harness's commands cannot create, overwrite, rename over or delete them, so an agent in a box cannot leave behind a hook or a server that runs outside the box in your next session. The same names are protected in every home, whichever harness uses it. Change them yourself, outside a box. If home has no agent folder, the harness cannot create one while boxed, so the files inside it cannot appear either. Folders of the same kind (plugins, skills, extensions) are not protected. On Linux the fence can protect a file only by granting everything around it one entry at a time, so inside a box the harness also cannot create a new file directly in home or in home/agent/, or replace a file there by renaming another over it; existing files there stay writable, and so does everything in the folders below them.
  • node bodies: a node body reports its result over a local socket, which the harness fence lets it reach under any network setting, so it runs inside a closed box too. Its own connections still follow the box's network.
  • Signing in: a box cannot reach the macOS keychain, so a harness that signs in from it (claude does) cannot sign in inside a box. Pass it an API key instead, through a policy secret on the definition that runs it (see "An agent in a box signs in with an API key" in box-blocks).

A single call can narrow the profile through its config, never widen it, because config is a value the program builds at run time, possibly from data or model output: @planner("Summarize the notes", { harness: { net: "none" } }), where @planner is an llm executable. In config.harness, net may name the same tier or a lower one, egress may keep some of the profile's hosts but add none, and each write entry must be a path the profile already grants (one of its write paths or its home, or a folder inside one); the call then writes only there and in its home. home cannot be set from config. Anything wider refuses before the harness starts, naming the definition. A config.harness that is not an object (a provider name, say) is left to the provider. @agent from @mlld/multi-harness is one such provider: it reads config.harness as the name of the tool to run and fails with multi-harness: unknown harness when given an object, so a call to it cannot narrow the profile this way.

Malformed config refuses the run

Only a truly absent mlld-config.json is silently treated as defaults. If the file exists in any shape but cannot be used, the run refuses with an error that names the file and says which shape is wrong — it does not warn and continue. This is deliberate: policy.import lives in this file, so a config that cannot be read hides whether a policy exists at all, and running anyway could mean running unpoliced.

Shapes that refuse, each with its own message:

  • Unparseable JSON — names the file and the parse failure.
  • Present but unreadable (permissions, IO) — names the file and the reason it could not be opened.
  • Valid JSON that isn't an object (an array, a bare string) — names the file and what it found.
  • Empty or whitespace-only — says the file is empty. A 0-byte config is indistinguishable from one truncated after it declared policy, so it refuses rather than silently applying defaults; a deliberately empty file costs one rm.
  • A symlink whose target is missing — says so. The path is present, so the run cannot treat it as absent; restore the target or remove the link.

A config with a leading UTF-8 BOM (some editors write one by default) is fine — the BOM is stripped, not refused. A symlink to a real config file works normally.

To proceed from any refusal: fix the file, or remove it to run with defaults.

Paths and URLs

Paths can be literal, interpolated, or resolver-based.

const @dir = "./docs"
const @username = "ada"
const @userFile = `data/${@username}/profile.json`   >> interpolated: data/ada/profile.json
const @template = "templates/@var.html"              >> literal: quotes never interpolate

>> URLs as sources
show <https://raw.githubusercontent.com/org/repo/main/README.md>
const @remote = <https://example.com/README.md>

Quoted strings are always literal, so an @ in one is ordinary text. Inside <…>, a variable is filled in: <@dir/guide.md>, <@root/@file>. For a path string to pass around, use a backtick template and ${…}. A quoted path argument (output … to, append … to, file, files) may still open with a resolver ("@root/out.json"), and a template file may open with @root/ (template "@root/prompts/review.att"), as a quoted import path does; opening it with a variable instead ("@dir/out.json") is an error that names the backtick spelling, `${@dir}/out.json`.

URL fetch safety (SSRF posture): remote loads walk redirects manually and re-check every hop. Only http:/https: targets are fetchable — a redirect to file: or any other scheme is refused. Targets in private or reserved ranges (loopback, RFC1918, link-local including the cloud metadata endpoint 169.254.169.254, CGNAT) are refused by default, checked on the DNS answer at each hop so a redirect or a rebound DNS answer can't smuggle one in. Redirects cap at 5 hops and the whole chain shares one deadline. To let @http reach one internal service, name its exact host and port in the project's policy, * { http: { private_hosts: ["localhost:1234"] } } (see policy-capabilities). To allow every private host for a whole run, set MLLD_URL_ALLOW_PRIVATE_HOSTS=1 (or urlConfig.allowPrivateHosts via the SDK).

@root resolution: @root resolves to the project root. mlld walks up from the current file's directory looking for mlld-config.json, and the nearest one wins, however far up it is. Only when no ancestor has one does it walk again looking for package.json or .git. With no marker at all, @root is the file's own directory. Use <@root/path> for project-absolute paths. See mlld howto builtins-reserved-variables for the full resolution algorithm.

Environment Variables

Import environment variables via @input. No configuration step is needed.

Usage:

import { @MLLD_NODE_ENV, @MLLD_API_KEY } from @input
show `Running in ${@MLLD_NODE_ENV}`

What a script can read

Two sets of variables reach @input, and nothing else does:

  • every variable whose name starts with MLLD_
  • six named variables: NODE_ENV, DEBUG, CI, HOME, USER, PATH

Prefixing a variable with MLLD_ is what makes it visible to a script. A
variable outside both sets is not readable, whether or not it is set.

Values arriving this way are labelled as coming from the environment, so the
usual checks apply when one flows into a command or a request.

policy

A policy is the set of security rules a program runs under. You write it as pattern blocks: each block names some labels, and its entries say what happens when data or an operation carries them.

policy @guardrails = {
  .secret { deny: [.risk:exfil] }
  .risk:exfil { includes: [.net:w] }
}

const .secret @apiKey = "sk-live-123"
exe .net:w @post(body) = `posted: ${@body}`

exe @tryPost(body) = match [
  denied => `refused: ${@mx.denial.reason}`
  * => @post(@body)
]

show @tryPost("hello")
show @tryPost(@apiKey)

Output:

posted: hello
refused: Label '.secret' from argument 'body' cannot flow to '.risk:exfil'

The first block says secret data may not reach anything in the .risk:exfil class. The second puts every .net:w operation in that class. @post carries .net:w, so a secret argument is refused before the call runs. The denied => arm catches the refusal (see security-denied-handlers).

A policy takes effect where it is declared and stays in force for the rest of the run.

How a block reads

A block is a label pattern followed by { … }. A pattern is one label, or several joined with + (all of them must be present). Inside the braces go key: value entries, separated by ; or a new line.

What a block may say depends on the kind of pattern. The kind comes from the label's namespace:

Pattern Example Kind Keys
* * { … } global settings see "Global settings" below
a data label .secret, .src:mcp, .untrusted data deny, allow!, only, block: "reason", locked, apply, transform, check, enrich
an .op: or .risk: label .op:tool:w, .risk:exfil operation deny: true, block: "reason", ask, box, before, after, always, includes, accepts
data + operation .secret+.op:cmd data + operation deny: true, block: "reason", ask, box, before, after, always
a .role: label .role:planner actor can_authorize, lifecycle

block: "reason" refuses with that reason: on a data block, any operation that receives the data; on an operation block, the operation itself.

A key on the wrong kind of block, an unknown key, or a plain allow: in a pattern block is an error when the policy loads. The error names the kind of block and where the key belongs.

Here is a policy that uses most of the keys:

record @txn [
  to: string [ kind "account" ]
]
const @safeDefault = { provider: "vfs" }
exe .op:tool:w @send_email(to) = `sent:${@to}`
exe .risk:exfil:send @notify(recipient) = `notified ${@recipient}`

policy @app = {
  * {
    unlabeled: .untrusted
    self_attestation: { cli: { claims: ["trust"] }, records: [@txn] }
    capabilities: { allow: ["cmd:git:*"], network: { allow: ["none"] } }
    secrets: { claude: "ANTHROPIC_API_KEY" }
    default_box: @safeDefault
  }
  .secret { deny: [.risk:exfil] }
  .untrusted {
    deny: [.op:cmd]
    allow!: [.op:cmd:git:status]
  }
  .src:mcp { only: [.op:tool:r] }
  .secret+.op:cmd { box: { net: "none" } }
  .risk:exfil { includes: [.net:w, .op:cmd:curl] }
  .risk:exfil:send { accepts: { recipient: [.fact:*, .src:user:intent:literal] } }
  .role:worker { lifecycle: "isolated" }
  .role:planner { can_authorize: [@send_email] }
}
  • capabilities: { network: { allow: ["none"] } }: commands run with no network. The list names a tier, "none", "loopback" or "open", or hosts such as ["github.com"], which every command then reaches only through mlld's egress proxy (see "Host lists" in box-config); an empty list means "none". deny takes host names to refuse whatever else is allowed. It only restricts the network: commands and file reads are decided by the other capabilities lists. Write it as an object: a bare string such as network: "none" limits nothing, and mlld validate warns about it.
  • .secret { deny: [.risk:exfil] }: secret data may not reach an exfiltration operation.
  • .untrusted { deny: …; allow!: … }: untrusted data may not reach a shell command, except git status. allow! marks a deliberate exception; see "Deny wins" in policy-label-flow.
  • .src:mcp { only: [.op:tool:r] }: data from an MCP server may reach read tools and nothing else.
  • .secret+.op:cmd { box: … }: a command that receives secret data runs in a box with no network (see box-config).
  • .risk:exfil { includes: … }: puts operations in a risk class (see policy-operations).
  • .risk:exfil:send { accepts: … }: a send's recipient must carry proof (see policy-authorizations).
  • the .role:… blocks: settings for an actor (see policy-authorizations and box-config).

The label an includes: block defines cannot be a proof label: .fact:*, .src:user:intent:*, .mitigates:*, or a trust label (.trusted, .untrusted). Those labels come only from the sources that grant them, so .src:user:intent:literal { includes: [.known] } is refused where the policy loads, and so is a wildcard pattern that could cover one (.src:user:*, *). Proof labels may appear inside the includes: list.

A block can hold another block. The inner pattern joins the outer one, so .src:web { .op:cmd:git { deny: true } } is the rule .src:web+.op:cmd:git.

Labels in a policy are always dotted. Declare every label you use with class unless it is built in (see labels-sensitivity).

Global settings: * { … }

The * block holds settings for the whole run rather than for a label. It stands alone: it is never joined with + and never nested. Settings that grant something (capabilities, credentials, self-attestation) live only here, so a label can never switch one on.

Key What it sets More
unlabeled a label for data that arrives with no label, for example unlabeled: .untrusted below
self_attestation which speakers (CLI flags, piped input, an SDK, an embedding host, an envelope issuer, …) may make which loosening claims, such as marking input trusted below
capabilities which commands, code languages and files may be used, and how far commands reach the network policy-capabilities
allow, deny, danger short forms of the capabilities lists policy-capabilities
secrets, keychain named credentials and keychain access policy-auth
default_box the box to use when no local box is declared box-config
locked true locks every rule in this policy and in every policy composed with it policy-composition
authorizations, requires_pins tools that can never be authorized, and what a grant must pin policy-authorizations
draft_if_denied operations that draft instead of failing when denied mcp-tool-gateway
flowcheck Asks mlld run to check the script with flowcheck before it starts (in this release only a policy naming it does; from 2.2.1 every script is checked). "strict" refuses when flowcheck finds a possible flow, not only a definite one; "default" leaves it advice. Strict wins whenever policies combine. flowcheck
records_require_tool_approval_per_actor true lets a tool with an inputs: record run only for a role whose block in that record grants write: { tools: [submit] } records-basics
urls which URLs may be constructed or fetched security-url-exfiltration
signers the trust root for signed manifests policy-signers

unlabeled gives data that has no label of its own a label. With unlabeled: .untrusted, a file you load counts as untrusted:

policy @strict = {
  * { unlabeled: .untrusted }
  .untrusted { deny: [.op:cmd] }
}

const @note = <README.md>
exe @echo(v) = cmd { echo "$v" }
exe @tryEcho(v) = match [
  denied => "refused"
  * => @echo(@v)
]

show @tryEcho("typed in the script")
show @tryEcho(@note)

Output:

typed in the script
refused

A literal written in the script is the author's own text, so it stays usable. The file's contents arrive with only a source label (.src:file), so they count as unlabeled and become untrusted.

self_attestation is the table of what mlld believes from outside the program. Each row names a speaker, a party that hands mlld values or recorded events with labels attached, and lists the claims that speaker may make. A claim is a label that loosens: it marks a value trusted, supplies proof, or counts as a person's own words or approval. Labels that restrict (.untrusted, .influenced, a .src: label) need no row; anyone may add them.

Speaker Who it is Claims it may be given
cli fields from command-line flags (--report.trusted, --report.labels) trust, proof, intent
stdin fields of piped input trust, proof, intent
env environment variables (@input.env) trust
sdk a field of the payload an SDK caller sends trust, proof, intent
file, net a <file> or <URL> load the script writes .trusted on trust
host a program that embeds mlld and records its user's turns and approvals on the run tape intent, approval, principal, clear, activate, tool
  • trust marks the value trusted, clearing .untrusted.
  • proof lets an input field carry .fact:* or .mitigates:* labels.
  • intent lets an input field carry .src:user:intent:*, and lets a host's recorded user turn count as the user's own words.
  • approval lets a person's answer the host recorded authorize: a host approval, a pick from your own match ask menu, and, when a resumed run is served it from the tape, a security ask's answer. It needs intent in the same row. With intent alone, the host's user turns count but none of these do. A security ask the host answers live needs no row: the request that started the run with host asks ("asks": "host", see config-live-stdio) is what lets the host answer it, and without that opt-in the ask refuses. The approval claim applies when a resumed run would serve that answer from the tape. A pick typed at mlld run's own prompt is opted in by labeling.answers.anonymous instead.
  • principal lets mlld read the account a host writes on a person's answer, so labeling.principals can map it to roles.
  • clear lets a person, through the host, clear a source's influence on an agent session after the fact (see "Clearing a source" in builtins-ambient-mx). It needs principal in the same row and a clear block beside claims saying what may be cleared and by whom:
>> policies/team.mld, listed in mlld-config.json's policy.import
const @config = {
  labeling: {
    self_attestation: {
      host: {
        claims: ["intent", "principal", "clear"],
        clear: { sources: [".src:net"], by: [".role:maintainer"] }
      }
    },
    principals: { "gh:12345678": [".role:maintainer"] }
  }
}
export { @config }

clear.sources lists label patterns; a cause is cleared only when every .src:* label on it matches one. A message another agent delivered to the agent as its prompt carries .src:agent, which mlld adds from the host's sender kind, so list .src:agent to let a person clear one (see builtins-ambient-mx, influence). clear.by lists .role:* labels; a clear counts only from a person whom labeling.principals maps to one of them. Both lists must name something. Like every host row, the block counts only in a policy mlld-config.json's policy.import loads. Where several config policies write it, each list keeps only what all of them allow. across_sessions: true also lets a clear count in every other session that read the same content (the same tool result value, compared by hash), found through the project's clear index; it holds only when every config policy that writes the block sets it, and it is off when left out (see "Clearing a source in every session that read it" in builtins-ambient-mx, which also describes how rolling the index back takes clears back). A clear is only as trustworthy as the host's recording channel, as an approval is: grant clear only to a host whose recording calls and signing key agents cannot reach (see Clears a program records for you).

  • activate lets a person's answer switch on an exception a .priv.sss policy wrote for them (see policy-label-flow, "Exceptions a person switches on"). It needs principal in the same row, because who may switch an exception on is decided by role. It is independent of approval: a host may be trusted for one-call approvals without switching exceptions on, or the reverse.
  • tool lets a host name the tool when it asks check about a harness tool call (see config-live-stdio), so the tool's operation labels decide which rules apply. The row lists the tools it may name, with * standing for any run of characters: host: { claims: ["tool"], tool: { tools: ["harness:claude/*"] } }. The claim and the list come together. A tool outside the list, or a host without the claim, is judged as an unnamed tool: its operation labels can still refuse it (a deny, ask or guard on them applies) but never let it through (an allow! exception, an only or allow list, or a guard's allow on them has no effect). When several policies list tools, a tool must be on every list. A project can instead map tool names to its own exes with hostTools.module in mlld-config.json, and those exes' labels and guards decide; the tool claim still decides whether the host's tool name is believed at all.

The approval claim on cli, stdin, env or sdk, and proof and intent on env, are refused as not yet supported: nothing reads them yet.

policy @inputs = {
  * { self_attestation: { cli: { claims: ["trust", "proof"] }, file: { claims: ["trust"] } } }
}

With this, a CLI flag can mint trust (--report.trusted) or carry proof labels (--report.labels fact:x) on an @input.cli field, whose source is .src:cli. Granting file or net trust lets an author's explicit .trusted on a <file> or <URL> load take effect (const .trusted @website = <https://example.com>); without it that elevation refuses loudly rather than being dropped. An untrusted load stays untrusted either way.

The table is empty by default: with no row, no speaker can make a claim, so an operator's --<field>.trusted flag or an SDK payloadFieldTrust request is ignored and the field stays untrusted. A field that arrives sealed in a verified envelope follows the same rule. Marking input less trusted is always allowed.

issuers lists the holders of keys whose signed envelopes the SDK admits: self_attestation: { issuers: { "ci": { key: "ssh-ed25519 …", scope: { source: "*", user: ["gh:12345678"] }, max_age: "5m" } } }. An issuer only ever supplies proof, never trust, so its row has a scope (the values it may assert for each kind of claim, with "*" for any) instead of a claims list. Only a local policy file that mlld-config.json's policy.import names may declare issuers; a module that file imports, and a registry or remote module, may not. policy-envelopes has the rules.

Where a row may be written. That depends on who the speaker is:

Speakers Where their rows may be written
cli, stdin, env, file, net, and records any policy in your project: the config file's, the script's, or a project file's policy the script adopts with import policy or union()
sdk, host only a policy that mlld-config.json's policy.import loads

The first group are inputs your own setup controls: the flags and piped input whoever starts mlld run chooses, and the files and URLs your script loads. Your script and your config are written by the same person, so either may say what those inputs may claim, every claim included. An SDK caller and an embedding host are outside the program, so only the config may let them make claims. An sdk or host row written anywhere else, in a script's policy, an import policy, a union() or a using { policy } fragment, is refused when it loads, and the error names mlld-config.json. The terminal's opt-in, labeling.answers.anonymous, follows the first group (see The object form below).

A script that trusted its SDK caller from its own policy now needs the config. Move the sdk row into a policy file and list that file in mlld-config.json:

>> policies/sdk.mld, listed in mlld-config.json's policy.import
const @config = { defaults: { self_attestation: { sdk: { claims: ["trust"] } } } }
export { @config }
{ "policy": { "import": ["./policies/sdk.mld"] } }

A policy in the script counts for reads and declarations after it. A module brought in with a plain import can narrow the table but never add a row or name a record, and if the script's own policy says nothing about self_attestation, or there is none, no import turns it on. A registry or remote module's policy can narrow the table but never add a claim or name a record, however it is imported. Write each row, and each record in records, as a literal in the policy: a policy that grants a claim through a spread, a field reference, or a union() of data or of a module's policy is refused, naming where the setting came from. union() of a policy your project declared with a policy directive keeps its table; a const @v = policy { … } value is not one, so write it as policy @v = { … }.

The host row covers a program that embeds mlld and records what its user typed as a user turn on the run tape. With intent, a turn it marks with .src:user:intent:* counts as the user's own words, the same as a user message the run recorded itself: live, and after a restart when a verified seal covers the tape it came from (see checkpoint-resume, Sealed tapes). Without it, or from an unsealed tape, the turn is still in @mx.history.user but can only block, never permit. A turn brought back this way is only as trustworthy as the key that sealed the tape: see When a seal certifies your words. The sdk row is separate: it covers payload fields only, and grants nothing the host records.

The records: list names the records whose trusted fields take effect: self_attestation: { cli: { claims: ["trust"] }, records: [@txn, @contact] }, or records: ["*"] for every record. A trusted field, with or without a kind, marks its value trusted and clears an inherited .untrusted only on a listed record. On a record not in the list the marking has no trust effect: the value keeps the trust it arrived with, and a field with a kind still mints its fact proof, so routing attacker data through a record cannot launder its taint. A parameter check (exe @f(p as record @r)) is not changed by the list. The one exception is a coercion inside a privileged guard (guard!), where a record's trusted fields take effect unlisted. See labels-trust and records-basics for which routes clear.

When policies combine, self_attestation merges by intersection: a row two policies both write keeps only the claims both grant, and records lists intersect, so combining can never widen what a speaker may claim. A policy silent on a row does not narrow it; to narrow, write the row with the claims you keep (cli: { claims: [] } keeps none). "*" intersected with a list of names gives those names, and with "*" gives "*". A using { policy } fragment may only narrow the table in force: a row or claim the policy in force does not grant stays ungranted inside the call, and with no policy in force the fragment's table is refused. A malformed table (an unknown speaker or claim, a claim outside the speaker's list, a row that is not { claims: [...] }, a records that is not a list) is refused when the policy loads. So is the earlier spelling with one boolean per source (cli: true); the error names the row to write instead.

self_attestation.code limits which approval labels your own declarations may add. By default code may put any label on its own values (const .approved @x, exe .approved @f, a policy's apply, a record's labels). code: false refuses every grant class, attestation label (.fact:*, .mitigates:*, the user-intent labels) and provenance label (.src:*) in those places; code: [.reviewed] allows only the listed labels:

policy @noSelfApproval = {
  * { self_attestation: { code: false } }
}

A declaration it refuses is a load error naming the declaration, the label and the policy that set the lock, including a declaration written before the lock arrived (a later import policy). Every lock in force applies, so a lock from an imported policy binds the importer, and false in one policy beats a list in another. It does not cover .trusted, which keeps the trust claim above, nor a record field written trusted.

Policy strings do not interpolate. Write patterns and names as plain "…" or '…' strings; an @ inside one is ordinary text ("@keychain"). A template (backticks with ${…}) in a policy is refused, because what the policy says and what it grants could then disagree.

Policy values and scoped policy

policy { … } is a policy written as a value. It puts nothing in force where it is written; you use it to combine policies or to narrow one call.

const @noSecretShell = policy { .secret { deny: [.op:cmd] } }

const .secret @token = "tok-123"
exe @echo(v) = cmd { echo "$v" }
exe @tryEcho(v) = match [
  denied => `refused: ${@mx.denial.reason}`
  * => @echo(@v) using { policy: @noSecretShell }
]

show @echo(@token)
show @tryEcho(@token)

Output:

tok-123
refused: Label '.secret' from argument 'v' cannot flow to '.op:cmd'

The plain call runs, because nothing denies it. The call with using { policy: @noSecretShell } runs under that rule and is refused. A scoped policy may only narrow: it can add a deny, a block or an ask, but it cannot grant a capability or add an allow! exception, and it may not carry signers, self_attestation.issuers or requires_pins. policy-composition has the rules.

using { policy } goes on a call, not on a definition: exe @f() using { policy: @x } = … is an error. To scope a call inside a function, put the clause on the call in the body:

const @noSecretShell = policy { .secret { deny: [.op:cmd] } }
exe @tool() = `result`
exe @wrapper() = [
  => @tool() using { policy: @noSecretShell }
]
show @wrapper()

union() combines policy values into one policy:

import { @standard } from "@mlld/policy"

const @mine = policy {
  * { capabilities: { allow: ["fs:r:**"] } }
  .secret { deny: [.op:show] }
}

policy @app = union(@standard, @mine)

@mlld/policy exports baseline fragments: secret and sensitive exfiltration blocks, untrusted .risk:destructive and .risk:privileged blocks, proof floors for send, destroy and extract operations, and the rule that marks LLM output .influenced when its input was untrusted. It also exports @urlOriginDefense (URL-exfiltration rules for network reads, already included in @standard) and @strict (@standard with every network read counted as .risk:exfil); see URL exfiltration.

Combining policies adds only what they say. union(), a second policy directive, or a second import policy combines the fragments, and a fragment that names no capabilities.allow adds no allow-list: fragments that say nothing about files leave file reads alone. An allow-list exists only if some fragment authors one. Once one does, it bounds what runs: an allow-list that names only commands refuses every file read with Filesystem read denied by policy, and two fragments that both name files allow only what both grant. If the program needs files, name them in the fragment that authors the allow-list, as @mine does above ("fs:r:**" and the label spelling ".fs:r:**" both work).

Sharing policies

Export a policy from a module and bring it in with import policy. It is in force from the import on:

>> policies.mld
policy @team = { .secret { deny: [.op:cmd] } }
export { @team }
>> In another file
import policy @team from "./policies.mld"

A .sss file is the usual home for shared policy, next to the class declarations it relies on (see sss-files). policy-composition covers how several policies in force combine.

The object form

Under the pattern blocks, a policy is a plain object ({ labels: { rules: … }, capabilities: … }). That object is still what the SDK takes, what dynamic policies are built from, and what show @policy prints. Its rule keys are pattern strings such as ".secret+.op:cmd". It cannot carry allow! exceptions or guard binds. In .mld and .sss files, write pattern blocks.

Three settings exist only in the object form. Each decides what a person's recorded answer counts for. Two of them, labeling.approvals.restore_window and labeling.principals, may be set only in a policy that mlld-config.json's policy.import loads. The third, labeling.answers.anonymous, may also be set by the project's own policies, as the input rows above may:

>> policies/team.mld, listed in mlld-config.json's policy.import
const @config = {
  labeling: {
    approvals: { restore_window: "2h" },
    self_attestation: { host: { claims: ["intent", "approval", "principal"] } },
    principals: { "gh:12345678": [".role:approver"] },
    answers: { anonymous: ["terminal"] }
  }
}
export { @config }

A script or module policy that sets restore_window or principals, in any form (policy, import policy, union(), using { policy }), is refused when it loads, naming mlld-config.json. answers.anonymous may also be set by the project's own policies. Pattern blocks have no spelling for it, so a script writes it as an object and declares a policy over that object with union():

const @answers = { labeling: { answers: { anonymous: ["terminal"] } } }
policy @answers_policy = union(@answers)

The object must be written out in full in a const, in the file that declares the policy: every key and value literal, with no variable, spread, field reference or call in it. A copy of another value (const @c = @imported), a spread ({ ...@imported }), a field reference ({ labeling: @imported.labeling }), a call result or an imported object may carry a module's data, so a union() of one that sets answers.anonymous is refused when it loads. Another project file may hold the setting the same way, in a policy directive it exports; the script then adopts it with import policy. An import policy of a plain data object, a registry or remote module's policy, and a using { policy } fragment that list a source are refused, and a module brought in with a plain import never adds it to the importer. A using { policy } fragment may still narrow it: anonymous: [] there turns the terminal off for that call, while a fragment that does not mention answers leaves it as it is. self_attestation.issuers is stricter: only a local file policy.import names may set it, not a module that file imports (see policy-envelopes).

A config file's rows are its own words. A self_attestation row or labeling.answers.anonymous in a file policy.import loads counts only when that file writes it: in a policy directive over a literal, or in an object written out in full in a const the file exports. A row the file passes on from a module refuses when the config loads, naming the row, the file and the remedy: a re-exported import, a copy (const @config = @imported), a rename (export { @imported as @config }), a field or namespace member, a spread, a call result, or a template (a backtick string, even one with no variable in it). A union() in a config file takes the same rule. A script that imports one of the config's own policy files again loads its rows as the config does. A registry or remote module named in policy.import can never add a row, of any speaker; write the row in a local policy file instead.

labeling.approvals.restore_window sets how long after you typed an approval a program that embeds mlld may still use it after a restart (see checkpoint-resume). It takes a duration made of a whole number and a unit ("30m", "2h", "7d"; the units are s, m, h, d and w), "never", or 0, which restores nothing. It is one hour when no config policy sets it. If several config policies set it, the shortest wins.

labeling.principals maps the people who answer questions to roles. A key is a principal, the provider-namespaced account id a host writes on an answer (gh:12345678, see match-ask); its value lists .role:* labels. A person's role counts where authority is checked for something made from that person's answer, such as a grant minted from a pick (see policy-authorizations), and never for the run or an agent's tool calls. Key the map by stable account ids, not logins: a login can be renamed and then claimed by someone else. mlld looks nothing up; it trusts the host that writes the principal, and only when the config's host row grants principal (self_attestation: { host: { claims: ["principal"] } }). An entry that is not an object of lists of .role:* labels refuses the policy when it loads. Several config policies combine by union.

labeling.answers.anonymous lists the answer sources whose answers count as proof without a principal. The only source it takes is "terminal", mlld's own prompt in mlld run (see match-ask): a developer-menu pick typed there then carries the same proof a signed-in person's pick does, but no role, since nobody is named. Answers from the other channels carry the host's principal, so any other entry, a value that is not a list, or another key under answers refuses the policy when it loads. It is empty by default. Because a terminal is fed by the same process that starts the run, as CLI flags are, the script's own policy may list it too, written as shown above. A terminal shows who is there, not who they are: any program with a shell can start a pseudo-terminal and type into it, so an agent harness that runs mlld run that way would answer its own questions with that proof. List terminal only where nothing but a person runs mlld run on a terminal.

Settings with other spellings

A policy that uses one of these settings is refused when it loads. Write the setting this way instead:

Setting Write instead
env a box, referenced with * { default_box: @box }
auth * { secrets: { … } }, used with using secret:name
credentials * { secrets: { … } }
operations includes: on a .risk: or .op: block
dataflow a guard bound with before: on an operation block
defaults.rules a fragment imported from @mlld/policy, combined with union()
facts.requirements accepts: on an operation block
envelopes: { issuers: [{ id, key, scope: [...], maxAgeSeconds }] } self_attestation: { issuers: { "<id>": { key, scope: { source: "*", user: "*" }, max_age: "5m" } } }, in a policy mlld-config.json loads (see policy-envelopes)
* { signers: { "<principal>": { key, … } } } * { self_attestation: { signers: { "<principal>": { key, … } } } }, in a policy file mlld-config.json's policy.import names (see policy-signers)
self_attestation: { cli: true } (also stdin) cli: { claims: ["trust"] }; add "proof" and "intent" for the grant labels it also allowed in mlld-config.json
self_attestation: { file: true } (also env, net) file: { claims: ["trust"] }
self_attestation: { sdk: true } two rows, both in a policy mlld-config.json loads: sdk: { claims: ["trust"] } for payload trust (add "proof" and "intent" for grant labels), and host: { claims: ["intent", "approval", "principal"] } for a host's user turns, approvals and principals

needs declarations are module requirement checks. They do not replace capability rules.

Policy Capabilities

The capabilities setting controls what operations can run at all. It is a global setting, so it goes in the policy's * block (see security-policies).

policy @tools = {
  * {
    capabilities: {
      allow: ["cmd:git:*", "cmd:npm:*", ".fs:r:**", ".fs:w:@root/tmp/**"],
      danger: [".fs:r:~/.ssh/*"],
      deny: ["sh"]
    }
  }
}

run cmd { git status }

Entries inside capabilities are an ordinary object, so they are separated by commas. Whether the command succeeds still depends on the current workspace. This policy permits only the git and npm command families; outside a git repository, git status still returns git's normal error.

sh { } blocks are off until a policy switches them on

An sh block, also written bash { }, can run anything at all, and policy rules cannot see the commands inside it. So mlld refuses one unless a policy switches it on:

policy @allow_sh = {
  * { capabilities: { sh: true } }
}

run sh { echo "hello from sh" }

Without that setting, run sh { ... }, a call to an exe whose body is sh { ... }, and an sh pipeline stage each stop with "sh { } blocks are off by default". The check happens when the block would run, not where it is written, so a module can define sh helpers that a program which switches sh on may call. Prefer cmd { } where you can: the policy checks each command a cmd body runs.

  • Who can switch it on. Only the program you run, through its own policy directives, and the project's mlld-config.json policy. A policy written in an imported module, an import policy, a union() of a value no policy directive in this program declared, and a using { policy } fragment on a call all leave sh off, so a dependency cannot switch it on for you.
  • It restricts nothing else. A program whose only policy setting is sh: true runs as if it had no policy, apart from sh blocks: the built-in danger list (see "How allow and danger interact" below) does not come into force for it. A policy you write empty, policy @p = {}, is still a policy in force and does bring the danger list. allow: ["sh"] is not a substitute for the switch: any allow list refuses every command it does not name.
  • deny still wins. deny: ["sh"] in any policy in force refuses sh blocks even when another policy sets sh: true. sh: false means the same as leaving the setting out; it does not undo another policy's true.
  • MLLD_DISABLE_SH=1 still turns sh blocks off for the whole run.
  • cmd { } is not affected. run cmd { bash ./build.sh } runs with no policy. To refuse commands that start a shell by name, deny sh (see below).
  • mlld init writes no policy, so a new project starts with sh blocks off.

Imports from a variable path are off until a policy switches them on

import { @tools } from @path, where the path is a variable, a field or a backtick template, loads code chosen while the program runs. mlld refuses it unless a policy switches it on:

policy @dynamic = { * { capabilities: { dynamic_imports: true } } }

The switch follows the same rules as sh: true above: only your program's own policy directives and the project's mlld-config.json policy can set it, it restricts nothing else, and false means the same as leaving it out. A written-out import path needs no switch. See modules-importing-local for what such an import may name.

Code-language words do not restrict commands

allow and deny take a mix of entry kinds. Two of them look alike and are easy to confuse:

Entry Kind Answers
sh, node, js, py Code-language word May this script contain a code block in that language: run sh { ... }, run node { ... }?
cmd:node:*, cmd:git:push Command pattern May this script run that command: run cmd { node build.js }?

A code-language word switches a language feature on or off. It does not restrict commands. deny: ["sh"] refuses run sh { ... } and leaves run cmd { echo hi } running normally. deny: ["node"] refuses run node { ... } and leaves run cmd { node build.js } running normally. Even deny: ["node", "sh", "js", "py"], which reads like "no code at all", still runs run cmd { node build.js }, because that is a command rather than a code block.

The other direction holds on macOS only: there a command pattern for the program a block runs (cmd:node, cmd:python3) also refuses that block, because the operating system stops the program starting (see "The macOS sandbox" below).

Restricting a command is what a cmd: pattern is for:

policy @noNode = {
  * { capabilities: { deny: ["cmd:node:*"] } }
}

>> Refused: Command 'node' denied by policy
run cmd { node build.js }

Answering one question does not answer the other, so a policy that cares about both says both:

policy @noNodeAtAll = {
  * { capabilities: { deny: ["sh", "node", "cmd:node:*"] } }
}

Command patterns:

Pattern Matches
cmd:git:* git with any subcommands
cmd:npm:install:* npm install with any args
cmd:* any command

Command allow/deny patterns match the words a command runs. A subcommand passed as a shell variable (git "$sub", where sub comes from an exe parameter or using { env }) is judged by the value mlld delivers for it when it is in the first command of the block and nothing before it can change that value. Anywhere else, such as after a |, behind a prefix assignment like X=1 git "$sub", or unquoted with a value that holds a space, the subcommand could be anything, so every deny under that command meets it and an allow that names a subcommand does not cover it. A value delivered through secret is never judged by its content.

Code-language words:

Word Governs
sh run sh { ... } blocks (off until sh: true switches them on)
node run node { ... } blocks
js run js { ... } blocks
py run py { ... } blocks

What denying sh stops, and what it cannot:

deny: ["sh"] (also written deny: { sh: true }) refuses run sh { ... } blocks. It also refuses a command that starts a shell by its name: run cmd { bash -c "…" }, and the same behind a command that runs another one, such as env, nice, nohup, timeout, time or strace (timeout 5 sh -c "…", env -S 'sh -c …'). Where mlld cannot tell which program such a line would start, because a word in it is filled in when the command runs ($SHELL, a * or ? pattern) or an option is one it does not know, it refuses.

The check reads program names, including through programs that run another one (xargs sh …, find -exec sh …; see "What command rules can and can't see" below). It cannot see a command that reaches a shell some other way, and those still run:

  • a link to a shell under another name (./notashell -c "…", where notashell points at /bin/sh);
  • a program that starts a shell from its own code, such as awk 'BEGIN { system("…") }' or a script interpreter.

So denying sh is a way to say "this script does not use the shell", not a wall around commands you do not trust. To contain a command chosen by a model or taken from untrusted content, run it inside a kernel box, where the operating system limits what any process can read, write and reach on the network, whatever program it starts. See box-config and box-sandbox-demo.

Filesystem patterns:

Pattern Access
.fs:r:** Read any path
.fs:w:@root/tmp/** Write under tmp (implies read)
.fs:r:~/.config/* Read home config files

Short form:

policy @echoOnly = {
  * {
    allow: ["cmd:echo:*", ".fs:r:**"]
    deny: { sh: true }
  }
}

Both forms are equivalent. The nested form (capabilities: { ... }) is more explicit; the short form puts allow, deny and danger straight into the * block. These three are global lists of capabilities, so a plain allow is fine here even though a pattern block refuses one.

Wildcard shorthands:

allow and deny accept a wildcard that matches every capability. The boolean true and the string "*" mean the same thing — both at the top level (deny: true denies everything) and per capability (deny: { sh: "*" } denies every sh block):

policy @everythingButSh = {
  * {
    allow: "*"
    deny: { sh: "*" }
  }
}

The spelling "all" is also accepted and means the same as "*". Write "*".

How allow and danger interact:

allow and danger are two independent gates. allow is the general whitelist: it controls whether an operation is permitted at all. danger is a separate opt-in gate for sensitive operations that mlld considers inherently risky — reading SSH keys, force-pushing, running sudo, reading keychain entries your policy did not name, and similar. Both gates must pass for an operation to proceed.

mlld ships with a built-in default danger list covering credential files, .risk:destructive commands, and security-bypass flags. When an operation matches the default danger list, policy blocks it unless the policy's danger array explicitly includes a matching pattern. This check runs independently of allow — an operation that matches allow but falls on the danger list is still blocked.

policy @gitOnly = {
  * {
    allow: ["cmd:git:*", ".fs:r:**"]
    deny: ["sh"]
  }
}

>> allow matches cmd:git:* — but git push --force is on the
>> default danger list. Without danger: ["cmd:git:push:*:--force"],
>> this is blocked with "Dangerous capability: this operation matches
>> the built-in danger entry `cmd:git:push:*:--force`. …".
run cmd { git push origin main --force }

To unblock it, add the matching pattern to danger:

policy @gitWithForce = {
  * {
    allow: ["cmd:git:*", ".fs:r:**"]
    danger: ["cmd:git:push:*:--force"]
    deny: ["sh"]
  }
}

The same double-gate applies to filesystem access. allow: [".fs:r:**"] permits reading all files, but reading ~/.ssh/id_rsa still requires danger: [".fs:r:~/.ssh/*"] because that path matches the default danger list.

Danger list: Operations matching danger require explicit opt-in. The keychain is the exception you rarely need: a keychain entry named in your policy's secrets is its own grant (see policy-auth). danger: ["@keychain"] is only for keychain reads you did not name, which are an imported registry, URL or GitHub module's own credentials.

Keychain allow/deny patterns live under the * block's keychain setting and match service/account paths (with {projectname} from mlld-config.json).

What command rules can and can't see

A command rule (cmd:git, cmd:git:push, .op:cmd:git { deny: true }) is judged against the programs mlld reads in a command's text.

What it reads. Every command in the text: after a |, on each line, and in a host command after ;, && and & and inside groups and if/while. A program that another program runs is judged as itself, and the one running it is judged too. mlld reads through env, nice, nohup, timeout, time, strace, command, exec, builtin, stdbuf, setsid, caffeinate, arch, ionice, chrt, taskset, prlimit, unshare, nsenter, chroot, sudo, doas, xargs, and find/fd with -exec, -execdir, -ok, -okdir, -x or -X. The text given to sh -c, eval and env -S is read as commands as well. So under deny: { cmd: ["git"] }, both run cmd { env nice git --version } and run cmd { sh -c "git --version" } are refused with Command 'git' denied by policy. Under an allow list, the program and every wrapper in front of it must be listed:

policy @gitOnly = { * { allow: ["cmd:git:*", "cmd:time"] } }

run cmd { time git --version }

Without cmd:time in that list, the command is refused with Command 'time' denied by policy.

What it can't read, and what happens. Some text only shows which program it runs when the shell runs it:

  • a command substitution $(…) or backticks, and a process substitution <(…) or >(…);
  • a program named by a variable or an mlld value ($G --version, env "$G" …);
  • a filename pattern in a program's name, or shell text built from a variable (sh -c "$CMD", eval "$(ssh-agent -s)");
  • a wrapper option mlld does not know, or a variable among a wrapper's own words (timeout $T git).

While a policy is in force, a command like this is refused, even when the policy says nothing about commands, because the built-in danger list (see "How allow and danger interact" below) judges programs by name. With no policy it runs. Two policies count as no policy here: the empty {} policy in mlld-config.json, and a policy whose only setting is capabilities: { sh: true }. A policy you write empty, policy @p = {}, does count.

policy @noGit = { * { capabilities: { deny: ["cmd:git"] } } }

>> Refused: A command may not contain a `$(…)` command substitution while a policy
>> is in force: a command there would run without the policy seeing it. Write the
>> program's name in the command text, or use an `sh { }` block once
>> `policy @allow_sh = { * { capabilities: { sh: true } } }` switches sh on.
run cmd { echo "Today is $(date +%A)" }

The fix is to run the inner command on its own, where its program is written out, and pass its result in:

policy @noGit = { * { capabilities: { deny: ["cmd:git"] } } }

const @day = cmd { date +%A }
run cmd { echo "Today is $day" } using { env: { day: @day } }

Subcommand rules. cmd:git:push and .op:cmd:git:push match the subcommand word as it is written. Git can change what a word runs, so mlld is stricter with git:

  • A git command that changes git's own settings could run any program (a ! alias, a pager, an SSH command), so mlld cannot read it, and it is refused while any policy is in force. That covers the options -c (also written -cname=value), --config-env, --exec-path= and --git-dir before the subcommand. It also covers the variables GIT_CONFIG_COUNT, GIT_CONFIG_KEY_*, GIT_CONFIG_VALUE_*, GIT_CONFIG_PARAMETERS, GIT_CONFIG, GIT_CONFIG_GLOBAL, GIT_CONFIG_SYSTEM, GIT_EXEC_PATH, GIT_SSH_COMMAND, GIT_SSH, GIT_PAGER, GIT_EDITOR, GIT_EXTERNAL_DIFF, GIT_ASKPASS, GIT_DIR, HOME and XDG_CONFIG_HOME, set anywhere in the command's text (in front of git, through env, with export or a plain NAME=value statement, or on a command whose shell runs git) or passed in with using { env }. So git -c color.ui=never status is refused under a policy that only denies js, and runs with no policy. -C and --work-tree are fine. A file read in with source or . can set these variables where mlld cannot see them.
  • A subcommand git does not build in may be an alias (from your ~/.gitconfig, the repo's own config or a file it includes) or an external program, so every git subcommand rule meets it. With lg = log in the repo's config, git lg is refused under deny: { cmd: ["git:log"] }. External commands such as git lfs meet every git subcommand deny too; to allow one, name it (allow: ["cmd:git:lfs:*"]).
  • npm run <script> and make <target> run whatever their config file says, and a rule on the script or target name cannot see that.

Deny the whole command (cmd:git, cmd:npm) when it has to be certain.

Deny lists are best effort; an allow list is the sound control. Some programs still run under a deny that names them:

  • code an interpreter runs itself: python3 -c "…", node -e "…", awk 'BEGIN { system("…") }';
  • a program under another name: a renamed copy, or a link to it (on macOS the sandbox below still stops a symbolic link to a program a whole-program deny names);
  • a wrapper mlld does not know, which is judged as the wrapper alone: under deny: ["cmd:git"], the text check lets watch git --version through.

An allow list refuses anything it does not name, so none of these get past one.

The macOS sandbox. On macOS, a whole-program deny (cmd:git, .op:cmd:git { deny: true }) is also enforced by the operating system: the program cannot start, whatever starts it. Under deny: ["cmd:git"], watch git --version and a Python subprocess.run(["git", …]) both fail with Operation not permitted. Inside an sh { } block the program fails as a shell error (/bin/bash: line 1: /usr/bin/git: Operation not permitted), not as an mlld refusal. Denying cmd:node or cmd:python3 also refuses node { } or py { } blocks up front, since those blocks run that program. The sandbox has limits:

  • it enforces whole-program denies only, not subcommand rules or label rules;
  • it covers the program's paths on the PATH mlld started with, and the files they resolve to, so a symbolic link under another name is stopped too; a renamed copy, a hard link under another name (/usr/bin/make shares one file with /usr/bin/git on macOS and still runs under deny: ["cmd:git"]), or a program of another name reached by changing PATH (python3.14 for python3) still runs;
  • on Linux, and when the fence is off ("fence": { "default": "off" } in mlld-config.json, see enforcement-planes), only the text checks above apply;
  • a local MCP server is not a command the policy gates, so neither the denies nor this sandbox apply to the server or to anything it starts: under deny: ["cmd:git"], a server that runs git still runs it (see mcp-policy).

Letting @http reach one private host

@http refuses private and reserved addresses (loopback, RFC1918, link-local, CGNAT) so that a URL built from data cannot reach services on your machine or network. To call one local service, such as a model server on your own machine, name its exact host and port in the * block:

policy @local = {
  * { http: { private_hosts: ["localhost:1234"] } }
}
  • Each entry is an exact host:port. There are no wildcards, schemes or paths, and a URL without a port matches its scheme's default (80 or 443). localhost:1234 does not allow 127.0.0.1:1234: list each spelling you use.
  • Only the project's own policies count: mlld-config.json, the program's own policy directives, and policies imported from files in the project. A registry or remote module's policy that names private_hosts is ignored with a warning, and a using { policy } fragment may not name it. The entry must be written in the policy itself: one that arrives as data (a spread, a field reference, or union() of a value that no policy directive declared) is ignored with a warning, so command output or a model's reply cannot open a host.
  • Every redirect is checked again, on its own host and port. A redirect from an allowed host to any other private address is refused.
  • MLLD_URL_ALLOW_PRIVATE_HOSTS=1 still allows every private host for a whole run; prefer the policy key, which allows only what it names.

Common mistakes:

  • capabilities: { sh: true } and deny: { sh: true } read alike and mean opposite things. The first switches sh blocks on; the second refuses them
  • deny: ["sh"] does not stop commands. It refuses run sh { ... } blocks; run cmd { echo hi } still runs. To stop a command, name it with a cmd: pattern (deny: ["cmd:echo:*"]) or list the commands you permit in allow. A deny is best effort (an interpreter's own code, a renamed program, an unknown wrapper), and a subcommand pattern meets aliases and unreadable git commands as "What command rules can and can't see" describes; an allow list is the sound control
  • deny: ["node"] does not stop run cmd { node build.js } — that is a command, not a node block. Use deny: ["cmd:node:*"]
  • MCP call patterns are spelled mcp:server:tool, and the leading-dot form (.mcp:server:tool) names the same thing. An entry that matches no known pattern form is accepted without complaint and then matches nothing, so check the spelling of any entry you rely on
  • tools in a box config enforces runtime tool access (Bash for shell commands, tool names for MCP calls)
  • capabilities.deny handles command-pattern policy rules (for example cmd:git:push)
  • Keychain access requires projectname in mlld-config.json. Name each keychain entry under secrets rather than adding danger: ["@keychain"]: a named entry needs no danger grant, while danger: ["@keychain"] lets every imported module read any keychain entry it declares
  • A .secret { deny: [.risk:exfil] } rule doesn't block show or log. Add .op:show and .op:log to the deny list if you want that (see policy-auth)
  • Capabilities do not gate starting an MCP server. mcp: and op:mcp: entries are server:tool call patterns, so deny: ["op:mcp:spawn"] restricts a server named spawn, not the act of launching one — and deny: ["node"] does not stop an MCP import either, because the developer writing the server spec is the one choosing the process. Restrict spawning with a pattern block naming the .op:mcp:spawn operation (see mcp-policy).

See policy-auth for credential flow, box-config for environment restrictions.

Operation Risk Labels

Classify operations by risk in two steps: label each exe with what it does, then put those labels into risk classes in the policy.

>> Step 1: operation labels say what each function does
exe .net:w @postToSlack(msg) = cmd { echo "slack: $msg" }
exe .fs:w @deleteFile(file) = cmd { echo "deleting $file" }

>> Step 2: the policy puts those operations into risk classes
policy @risk = {
  .risk:exfil { includes: [.net:w] }
  .risk:destructive { includes: [.fs:w] }
  .secret { deny: [.risk:exfil] }
  .untrusted { deny: [.risk:destructive] }
}

const .secret @token = "tok-123"
const .untrusted @suggested = "/home/me"

exe @tryPost(v) = match [
  denied => `refused: ${@mx.denial.reason}`
  * => @postToSlack(@v)
]
exe @tryDelete(v) = match [
  denied => `refused: ${@mx.denial.reason}`
  * => @deleteFile(@v)
]

show @tryPost("hello")
show @tryPost(@token)
show @tryDelete("/tmp/scratch")
show @tryDelete(@suggested)

Output:

slack: hello
refused: Label '.secret' from argument 'msg' cannot flow to '.risk:exfil'
deleting /tmp/scratch
refused: Label '.untrusted' cannot flow to '.risk:destructive'

Secret data cannot reach @postToSlack (the .risk:exfil rule), and untrusted data cannot reach @deleteFile (the .risk:destructive rule). Each refusal names the label that was blocked and the risk class it could not reach. See policy-label-flow for how rules match and labels-influenced for influenced output.

A guard bound on a risk class fires on the operations the class includes: with .risk:destructive { includes: [.fs:w]; before: @g }, @g runs before every .fs:w operation, as a bind on .fs:w itself would (see security-guards-basics).

The .fs: and .net: labels also limit what the exe's own body may do. A cmd, sh, bash, py or node body of an exe with such a label runs in a box: no network unless a .net: label is present, and no file writes unless .fs:w or .fs:rw is. So @postToSlack above cannot write files, and @deleteFile cannot reach the network. See "A declaration is enforced" in Labels.

Why two steps?

  • Reusability: Many functions share the same operation label (.net:w applies to Slack, email, webhooks). Changing the risk class of .net:w updates all of them at once.
  • Flexibility: The same exe definition works under different policies. A dev policy might leave .net:w alone; a production policy puts it in .risk:exfil.
  • Composability: Operation labels are stable across teams and libraries. Risk classes are a policy decision, not a code decision.

Risk categories:

Category Meaning
.risk:exfil Sends data outside the system
.risk:destructive Deletes or modifies data irreversibly
.risk:privileged Requires elevated permissions

Risk labels are hierarchical. .risk:exfil:send is a child of .risk:exfil, so a rule that denies .risk:exfil also blocks .risk:exfil:send. Use accepts on an operation block to add proof requirements for a class such as .risk:exfil:send or .risk:destructive:targeted (see policy-authorizations).

Starting an MCP server is one of the operations the runtime names for you: it carries .op:mcp:spawn. Deny that operation directly, or put it in a risk class with includes and deny the class (see mcp-policy).

Several labels: Give an operation every label that applies:

exe .net:w,.fs:w @exportAndDelete(payload) = cmd { echo "backup_and_delete $payload" }

policy @risk = {
  .risk:exfil { includes: [.net:w] }
  .risk:destructive { includes: [.fs:w] }
}

Direct risk labels: You can label an exe with a risk class directly and skip the mapping step:

exe .risk:exfil @sendToServer(payload) = cmd { curl -d "$payload" https://api.example.com }
exe .risk:destructive @removeFile(file) = cmd { rm -rf "$file" }

This is simpler but ties the exe definitions to risk classes. The two-step form is easier to maintain.

Calls that must not happen twice: .once marks an operation that --resume must not make again after a crash cut it off part way, such as a payment or a deploy (see checkpoint-resume). Put it on an exe, or put whole families into it with includes:

exe .once @charge(card, amount) = cmd { echo "charging $card $amount" }

policy @once = {
  .once { includes: [.net:w] }
}

Here @charge, and every exe labelled .net:w, stops a resume instead of running again when a crash interrupted it. A call that finished is answered from the run's tape when its result was stored; when its result was secret, or the call failed, the resume stops at it too (see checkpoint-resume). Labelling an exe .net:w to bring it into that family also boxes its body, so it cannot write files unless it also carries .fs:w (see the .fs: and .net: paragraph above).

See policy-authorizations for how operations interact with per-tool authorization.

Record field actions

Operation policy is the cross-value enforcement layer. Record fields can also carry their own actions:

exe @urlDetector(text) = js { return /https?:\/\//.test(text); }

record @send_email_inputs [
  body: string [
    check @urlDetector => deny
  ]
  validate "strict"
]

A field action can call an executable, like check @urlDetector here: the field's value is passed to it, and a true result triggers the action. Coercing { body: "see https://x.y" } to @send_email_inputs stops with Policy check action denied matched value; a body with no URL passes.

A field's enrich, transform, check and apply actions run when the record materializes (as record, => record, or record-backed tool dispatch). They are stamped on the field at .mx.appliedActions, so they do not re-run on the same unchanged value. Use record actions for field-local content contracts; use operation labels and policy blocks for cross-tool flow control.

Policy Label Flow Rules

A data block in a policy says which operations data with those labels may reach.

policy @flow = {
  .secret { deny: [.op:cmd, .op:show, .net:w] }
  .src:mcp {
    deny: [.op:cmd:git]
    allow!: [.op:cmd:git:status, .op:cmd:git:log]
  }
  .secret+.untrusted { deny: [.op:cmd] }
}
  • .secret data may not reach a shell command, show, or a network write.
  • Data from an MCP server may not reach any git command, except git status and git log.
  • Data that is both secret and untrusted may not reach a shell command.

A data block takes these keys:

Key Meaning
deny: [ops] data matching the pattern may not reach these operations
allow!: [ops] a deliberate exception to a broader deny (see "Deny wins" below)
exceptions: { … } named exceptions a person can switch on for a while; .priv.sss only (see "Exceptions a person switches on" below)
only: [ops] data matching the pattern may reach these operations and nothing else
block: "reason" refuse with this reason
locked: true no exception or merge may weaken this rule

A plain allow: is an error in a pattern block. The message says which of allow!: or only: you meant.

What rules match against

A rule matches the labels on the data an operation receives: the value's own labels, plus its trust (.trusted or .untrusted) and whether it is .influenced. A value's sources, URLs and tool history are audit records and never take part in matching.

Matching is hierarchical: .src:mcp matches data labeled .src:mcp:github, and a deny on .op:cmd:git meets every git subcommand mlld reads (.op:cmd:git:push, .op:cmd:git:reset, and so on). What it reads has limits: a program run from an interpreter's own code or under another name is not seen, a command mlld cannot read is refused while a policy is in force, and a git subcommand git does not build in (an alias) meets every rule under .op:cmd:git. See "What command rules can and can't see" in policy-capabilities.

A subcommand passed as a shell variable (git "$sub") carries the label of the value mlld delivers for it when it is the first thing the command runs; anywhere else it meets every deny under the command, as the capability list does (see policy-capabilities).

Targets are operation labels. Some the runtime adds for you (.op:cmd, .op:show, .op:output, .op:file, .op:files, .op:mcp:spawn); others you put on your own exes (.net:w, .op:tool:w) or define as risk classes (.risk:exfil, see policy-operations). The file and files directives write under .op:file / .op:files, so .src:file { deny: [.op:files] } stops a labeled value being written out. Starting an MCP server carries .op:mcp:spawn, so a rule denying that operation refuses a server spec built from the labeled data (see mcp-policy).

.op:var and .op:const are not targets. Binding a value is not an operation, so a rule on one could never match anything; .op:var { deny: true } or deny: [.op:const] is refused when the policy loads, with ".op:const is not an operation filter", and mlld validate reports the same error. Deny the operation the bound value reaches instead (.secret { deny: [.op:cmd] }).

Compound patterns

Join labels with + to match data that carries all of them:

policy @mixed = {
  .secret+.untrusted { deny: [.op:cmd] }
}

exe @echo(v) = cmd { echo "$v" }
exe @tryEcho(v) = match [
  denied => `refused: ${@mx.denial.reason}`
  * => @echo(@v)
]

const .secret @key = "k-1"
const .secret,.untrusted @leaked = "k-2"
show @tryEcho(@key)
show @tryEcho(@leaked)

Output:

k-1
refused: Labels '.secret+.untrusted' cannot flow to '.op:cmd'

The message names .trust:untrusted, the runtime's internal name for the trust token; in source you always write .untrusted.

Extra labels on the data do not stop a match: a compound checks that its labels are present, not that they are the only ones. A compound is more specific than any of its parts.

A pattern has no OR. To cover either of two labels, write two blocks. A + inside a list (deny: [.net:w + .op:cmd]) is an error: list operations with commas.

Excluding a label: :not(…)

.a:not(.b) matches data that has .a and lacks .b:

class .pii = { kind: "data", effect: "restrict", description: "personal data" }
class .reviewed = { kind: "data", effect: "grant", description: "checked by a person" }
record @review [
  body: string [ accepts .reviewed ]
  validate "strict"
]

policy @piiNet = {
  .pii:not(.reviewed) { deny: [.net:w] }
}

exe .net:w @post(body) = `posted ${@body}`
exe @tryPost(v) = match [
  denied => `refused: ${@mx.denial.reason}`
  * => @post(@v)
]

const .pii @raw = "ada@example.com"
const .pii,.reviewed @checked = "ada@example.com"
show @tryPost(@raw)
show @tryPost(@checked)

Output:

refused: Labels '!.reviewed+.pii' from argument 'body' cannot flow to '.net:w'
posted ada@example.com

A rule that lets a label switch it off may only name a label that incoming data cannot carry by itself: a grant class (as .reviewed is here), an attestation, a fact, or a user-intent label. Otherwise data sent into the program could carry .reviewed and turn the rule off, and the policy refuses to load, saying so. A grant class also needs a rule that admits with it, such as the accepts .reviewed field in @review; without one, mlld validate reports an error. See labels-classes for grant classes.

:not(…) holds one label. To exclude several, chain them: .a:not(.b):not(.c). Exclusion is hierarchical too: :not(.src:user:intent:literal) is not satisfied when the data carries .src:user:intent:literal:msg:current.

Exclusion goes in the pattern, never in a list. An entry of deny, allow!, only, includes or apply is one label, so deny: [!.reviewed] or deny: [.x:not(.y)] is refused at load. A policy object built as data (const @cfg = { … }) warns on a ! entry instead, because the entry matches nothing, and loads the rest.

Deny wins

When a deny and an allow! both match an operation, the deny wins, unless the allow! qualifies:

  • it narrows the deny: its pattern falls under the deny's and is more specific (.op:cmd:git:status under a deny of .op:cmd:git), and
  • it comes from the same file as the deny, or from a .priv.sss file brought in with import policy (which may make exceptions to a deny from another file), and
  • the deny is not locked. Nothing qualifies against a locked deny, not even an allow! in the locked rule's own file.
policy @shell = {
  .untrusted {
    deny: [.op:cmd]
    allow!: [.op:cmd:echo]
  }
}

const .untrusted @msg = "hi"
exe @say(v) = cmd { echo "$v" }
exe @print(v) = cmd { printf %s "$v" }
exe @try(f, v) = match [
  denied => `refused: ${@mx.denial.reason}`
  * => @f(@v)
]

show @try(@say, @msg)
show @try(@print, @msg)

Output:

hi
refused: Label '.untrusted' cannot flow to '.op:cmd'

echo is excepted; every other command stays denied. An exception lifts a deny only for the labels it covers, so an operation needs an exception for each label it carries under the deny: with deny: [.op:cmd] and allow!: [.op:cmd:git], an exe labeled both .op:cmd:git and .op:cmd:rm is still refused, because nothing excepts .op:cmd:rm. (.trust:untrusted in the message is how the runtime names .untrusted.) An allow! in your script cannot lift a deny that arrived from an imported policy. Put such an exception in a .priv.sss file and bring it in with import policy, where it is easy to find and review (see sss-files).

allow! exists only in pattern blocks written in a file. A policy object from the SDK, a policy { … } value used in using { policy }, and any other scoped fragment cannot carry one. An allow! that excepts nothing (no broader deny of its pattern in the same file) stops the program before it runs, however you run it (mlld file.mld, mlld run, mlld -e '…' or mlld -e -), and mlld validate reports it. An allow! in a .priv.sss file is the exception: it may lift a deny from any file that imports it, so it is not checked this way. locked: true and allow! in the same block are an error.

Exceptions a person switches on

Sometimes a deny is right by default but a person should be able to relax it for a while: "let the agent message other people for the next two hours". Write that as a named exception inside the rule it relaxes. It starts off, and a person switches it on:

policy @messaging = {
  .influenced {
    deny: [.op:msg:send]
    exceptions: {
      talk_to_others: {
        allow!: [.op:msg:send]
        for: "2h"
        turns: 20
        by: [.role:owner]
        ask: "Let your agent message other people for 2 hours?"
      }
    }
  }
}
Key Meaning
allow!: [ops] the operations it lets through while it is on, judged as allow! is (see "Deny wins")
for: "2h" how long it stays on: a whole number and one of s, m, h, d, w
turns: 20 how many turns it stays on for. A turn is a user message in a chat session the host records, or an LLM call in a script (one call of an llm executable, however many commands its body runs). Both are counted, and whichever reaches the limit first switches it off
by: [roles] the roles that may switch it on. A person's roles come from labeling.principals in mlld-config.json
ask: "…" the question the person is asked. Without it, mlld asks in its own words, naming the exception and its limits

Give it for, turns or both; with both, it switches off at whichever comes first. Entries inside exceptions may be separated by commas, semicolons or new lines.

When a call is about to be refused and an exception that is off would let it through, mlld asks the person through the host that answers the run's questions (see match-ask). The menu is yours: "Switch on talk_to_others for 2h or 20 turns, whichever ends first" or "Keep restricted". If the person who picks "switch on" holds one of the roles in by, the exception is on and the call goes ahead; later calls go ahead without asking until it runs out. Anything else leaves it off: "Keep restricted", no answer, an answer with no signed-in person, or a person without one of the roles. After that, mlld does not ask about the same exception again in that run.

Rules that still hold:

  • It is written only in a .priv.sss file, in a pattern block. Anywhere else, including the script itself, mlld -e, a policy value or a using { policy } fragment, it is refused when the policy loads.
  • An answer recorded in an earlier run is never reused to switch it on: a resumed or replayed run asks again. A resumed run keeps one switched on in the run it continues, until its original limits run out.
  • It never lifts a law (never:) or a locked rule. An exception that overlaps a law on its rule, sits on a locked rule, or sits beside an ask on the same rule is refused when the policy loads.
  • The host's config must allow it: self_attestation: { host: { claims: ["principal", "activate"] } } in mlld-config.json (see policy-basics). Without activate nobody is asked.
  • Switching an exception on is not a one-call approval: it lets through every call its allow! covers until it runs out, and it is not tied to one call's arguments (see policy-authorizations).

The run tape records the switch (activation), and mlld why names who switched it on and what it had left (see why). A later run of the same session keeps it on until its own limits run out, if the host restores it from the session's newest sealed tape.

Whitelists: only:

only: turns a rule around: data matching the pattern may reach the listed operations and every other operation is denied.

class .pii = { kind: "data", effect: "restrict", description: "personal data" }

policy @piiShowOnly = {
  .pii { only: [.op:show] }
}

const .pii @email = "ada@example.com"
exe @echo(v) = cmd { echo "$v" }
exe @tryEcho(v) = match [
  denied => `refused: ${@mx.denial.code}`
  * => @echo(@v)
]

show @tryEcho(@email)
show @email

Output:

refused: POLICY_LABEL_FLOW_DENIED
ada@example.com

A common use is .src:mcp { only: [.op:tool:r] }: data from an MCP server may reach read tools and nothing else.

Rules on operations

A block whose pattern is only an operation label applies to that operation whatever data it receives, including none. A block that joins data and an operation applies only when the data matches too. On these blocks, deny: true refuses the operation, block: "reason" refuses with that reason, and ask asks for review:

exe .ask @approveWrite() = `allow`

policy @ops = {
  .op:cmd:rm { deny: true }
  .untrusted+.op:cmd { block: "no untrusted shell" }
  .op:tool:w { ask: @approveWrite }
}

exe @echo(v) = cmd { echo "$v" }
exe @tryEcho(v) = match [
  denied => `refused: ${@mx.denial.reason}`
  * => @echo(@v)
]

const .untrusted @msg = "hi"
show @tryEcho("clean")
show @tryEcho(@msg)

Output:

clean
refused: no untrusted shell

A deny can be written two ways: .secret { deny: [.op:cmd] } and .secret+.op:cmd { deny: true } are the same rule. deny: true on a data-only block, or deny: [...] on a block that already names the operation, is an error that shows the other spelling.

Operation blocks can also bind guards (before:, after:, always:; see security-guards-basics) and set a box for the call (box:; see box-config).

Asking for review

ask goes on an operation block or a data + operation block. What it points at decides who answers:

  • ask: @handler: mlld calls the exe ask handler and waits for its answer. The handler returns allow or deny; deny, a timeout or an error blocks the call. Use this for a standalone mlld agent that gates itself: the handler is where you run the approval (prompt a person, call an approval API, ask another model).
  • ask: { handler: "@handler", payload: { … } }: the same, and the handler also gets payload. Each of its fields is read inside the handler as @mx.ask.<field>. Only an object payload is passed: any other value (a string, say) is not passed, and the handler sees no fields. ref or exe may name the handler in place of handler.
  • ask: "reason" or ask: { reason, payload }: the review surfaces to the protected executable's own asking => arm. Use this when something around mlld does the asking, for example when mlld runs as a permission hook and the host harness prompts the user.

Any other ask, such as a list of handlers, a number or an empty string, is refused when the policy loads. Each object form takes only its own keys: { reason, payload } takes those two, neither required, and the handler form takes its handler key and payload. Any other key (a misspelt reasn, say) is refused at load, naming it. In the reason form payload can hold any value; in the handler form only an object reaches the handler. To have several handlers approve, give each its own rule (see below).

exe .ask @review() = [
  show `reviewing ticket ${@mx.ask.ticket}`
  => "allow"
]

policy @gate = {
  .secret+.op:tool:w { ask: { handler: "@review", payload: { ticket: "OPS-12" } } }
}

exe .op:tool:w @send(body) = `sent: ${@body}`

const .secret @report = "q3 numbers"
show @send(@report)

Output:

reviewing ticket OPS-12

sent: q3 numbers
policy @review = {
  .secret+.op:tool:w { ask: "review secret send" }
}

exe .op:tool:w @send(body) = match [
  asking => `held for review (${@mx.ask.source})`
  * => `sent: ${@body}`
]

const .secret @report = "q3 numbers"
show @send("hello")
show @send(@report)

Output:

sent: hello
held for review (policy)

@mx.ask.source is "policy" for these asks. An ask from a bare command, show or write has no handler to run, so it refuses the operation.

A deny beats every ask. If any rule denies or blocks the operation, it is refused and nobody is asked.

To let the ask handlers answer those denials, turn on denies_can_ask in the * block:

exe .ask @approve() = `allow`

policy @review = {
  * { denies_can_ask: true }
  .secret { deny: [.op:tool:w] }
  .op:tool:w { ask: @approve }
}

const .secret @report = "q3 numbers"
exe .op:tool:w @send(body) = `sent`
const @sent = @send(@report)
show "done"

Output:

done

With it on, a call refused by a deny list, deny: true, a block or an only: list, which also matches an ask, goes to the ask handlers instead of failing, and runs only if every one of them allows it. A rule's own ask counts, so { deny: [.op:tool:w], ask: @approve } asks about its own deny. The setting changes nothing else:

  • A locked rule (locked: true, or * { locked: true }) never asks: its deny stands.
  • A deny with no matching ask still refuses.
  • After the handlers allow the call, every other check still runs: proof requirements (accepts), capability lists, URL rules and guards can each still refuse it.

It is a * key and takes true or false. Only a policy directive in the program's own file turns it on, by writing denies_can_ask: true there:

  • A using { policy } or with { policy } fragment that sets it to true is refused.
  • An imported module's policy cannot turn it on, whether it arrives by a plain import, by import policy, or by union().
  • A value that carries it does not turn it on either: a const config, a copy of a policy under another name, or a spread ({ ...@cfg, … }).

A false anywhere wins, so any policy in force can switch it off.

When several rules ask about one operation, every handler must allow it. Handlers are asked from the most specific rule to the least, a handler named by two rules is asked once, and the first deny refuses the operation. This holds however the rules were combined: two policies that each put an ask on the same pattern, joined with union() or with using { policy }, keep both asks.

Routing denials to draft handlers

A label-flow denial for a surfaced tool can route to the tool's draft: handler instead of failing the call. List those operations in the * block's draft_if_denied:

policy @taskPolicy = {
  * { draft_if_denied: [.op:named:send_email] }
  .risk:exfil { includes: [.risk:exfil:send] }
  .untrusted { deny: [.risk:exfil] }
}

An entry names a tool (send_email, @send_email and .op:named:send_email all name the same one), an operation label, or a data label. An operation-label entry such as .op:tool:w or .risk:exfil matches the call's operation labels, including those an includes: alias adds, so * { draft_if_denied: [.op:tool:w] } drafts every denied write tool. A data-label entry such as .factsource:draft matches the call's inputs. Only label-flow denials route to a draft; capability denials, schema failures and guard denials stay hard failures. A draft_if_denied that is not a list of such entries is refused at load. See mcp-tool-gateway for draft: handlers on tool entries.

Privileged guard overrides

A privileged guard (guard!, declared in a .priv.sss file) that answers allow can satisfy a proof requirement (accepts) that is not locked. It does not lift a deny: rule: for a deliberate exception to a deny, write allow!: (see above). A locked rule (locked: true, or * { locked: true }) is never overridden.

Composition

Rules from every policy in force combine. A deny from any policy blocks the flow; union() and using { policy } keep every rule and every ask. See policy-composition.

Complete example

policy @noSecretShow = {
  .secret { deny: [.op:show] }
}

const .secret @customerList = "ada,bob"
show @customerList

Error: Label '.secret' cannot flow to '.op:show'. The policy blocks secret data from reaching show.

For per-tool authorization with argument constraints, see policy-authorizations. See labels-sensitivity for declaring labels, labels-source-auto for source labels, and labels-influenced for influenced output.

Policy Authorizations

A policy's authorization settings are the ambient authorization law: the rules that decide which role is allowed to authorize which tools, and which tools are forbidden outright. It is the law your whole run is under — it does not change from call to call.

The per-call side of authorization — consenting to a specific tool call with specific argument values — is a grant, a separate per-step artifact. Grants draw their authority from can_authorize here. Read security-grants for how grants work; this page covers the standing law they attenuate from.

The law has two parts:

  • can_authorize, on an actor block such as .role:planner { … }: the root authority. It grants a role the right to authorize a set of tools.
  • authorizations: { deny: [...] }, in the * block: an absolute block. A denied tool can never be authorized, by anyone.

can_authorize — the root authority

can_authorize goes on an actor block and lists the tools that role may authorize:

exe @sendEmail(to) = `sent:${@to}`
exe @createFile(file) = `created:${@file}`
policy @workspace = {
  .role:planner { can_authorize: [@sendEmail, @createFile] }
}

Rules:

  • The block's pattern is one actor label in .role:* form. Tool identity is the executable reference (@sendEmail), not a string name — so authorization is bound to the actual tool, not a spellable label. (A surfaced tool's collection name is also accepted where the underlying exe is not in local scope.)
  • can_authorize belongs on the base policy. It is standing law, not something a planner produces at runtime. It is refused on any block but an actor block, and an actor block is never joined with data or operation labels.
  • A tool listed in deny can never appear effectively in can_authorize.

can_authorize is itself the root grant of authority. Everything below it can only narrow that set (attenuation), never widen it. A grant minted for a tool outside the role's can_authorize set is refused at mint time — see "Denial routing" below.

deny — the absolute block

import { @noSendToUnknown } from "@mlld/policy"
const @denyRules = policy {
  * { authorizations: { deny: ["update_password", "update_user_info"] } }
}
policy @accountLaw = union(@noSendToUnknown, @denyRules)

deny names tools that can never be authorized. Where can_authorize opens narrow windows, deny guarantees certain windows never open — even if some other policy layer lists the tool under can_authorize.

A deny entry must be a bare tool name, written as a string: deny: ["wire"]. An entry that could never match a tool name is refused rather than silently denying nothing:

  • deny: ["@wire"] is refused: the @ makes it a different name. Write "wire".
  • deny: [@wire], an executable reference, is refused with the bare name to write.
  • An entry that is not a string (a nested list, an object) is refused, and an authorizations value that is not an object is refused rather than ignored.

requires_pins — require a grant to prove specific arguments

can_authorize says which tools a role may authorize. requires_pins says
what a grant for a tool must prove before it may be minted at all.

It is a global setting, so it goes in the * block:

record @contact [
  email: string [ kind "email" ]
]
exe .op:tool:w @send(to) = `sent:${@to}`

policy @law = {
  .role:planner { can_authorize: [@send] }
  * { requires_pins: { send: ["to"] } }
}

const @proven = { email: "ada@example.com" } as record @contact
const @g = { args: { to: @proven.email } } as grant for @send
show @send(@proven.email) using { grant: @g }

Output:

sent:ada@example.com

The grant pins to to a value that carries proof, so it mints and the call runs under it. A grant for @send that does not pin to is refused when it is minted:

const @g = { args: {} } as grant for @send
>> Grant refused: 'send' requires a pin for argument 'to', and this request does not pin it.
The hole it closes

Every entry in a grant request must carry proof. That rule governs the entries a
request has, so a request with no entries has nothing lacking proof. An
empty request satisfies the consent floor while pinning nothing:

const @g = { args: {} } as grant for @sendMoney     >> once minted, proving nothing

That is the one shape where attaching a grant is worse than attaching none: it
looks like consent and constrains nothing. requires_pins is how an author
closes it for the tools that matter.

The author names the fields, and that is deliberate

The rule could have been "a grant must pin something". It is not, because that
is satisfiable by pinning a harmless argument while the dangerous one stays free —
leaving a guard that reads as configured and constrains nothing. Naming the
fields is what makes the requirement mean what it looks like.

What it does not do

A tool you do not name is untouched, including the empty-request mint above.
requires_pins narrows exactly what you list and nothing else.

A name that matches nothing refuses where it is written

A requires_pins entry naming an argument the tool does not have can never be
satisfied and never refuses a grant — the requirement would read as configured
while protecting nothing. So the error fires when the policy is declared, not
at the first grant, and it names both the field and the tool:

exe .op:tool:w @send(to) = `sent:${@to}`
policy @law = { * { requires_pins: { send: ["recipiant"] } } }
>> refused: `@send` has no argument with that name. It accepts: to.

A tool name that resolves to no executable refuses the same way. Because the
check reads the tool's argument list, declare the exe before the policy that
names it
— a policy written above its exe refuses, and the fix is to move the
policy below the definition. This also holds when the requirement names a field
of the tool's input record (the flattened grant form pins by the record's field
names, so those count as arguments); a field outside both the parameters and the
record refuses.

Imported policies: requirements re-bind by bare tool name

A plain import "module" absorbs the imported module's policy — including its
requires_pins. Requirements are keyed by the tool's bare name, and the
absorption path does not re-validate the requirement against the module it
came from. Three consequences:

  • Re-binding. A module's requires_pins: { send: ["to"] } governs whatever
    tool named send exists in the importing program — a different tool,
    written by a different author. Its grants must pin to even though the
    requirement was written for the module's own @send.
  • Unsatisfiable requirements. If the local send has no to argument, the
    inherited requirement can never be satisfied: every grant for the local tool
    is refused demanding a pin for a field the tool does not declare, and the
    import itself succeeds silently.
  • Silent inertness. If the importing program has no tool named send at
    all, the requirement is simply inert — no error at the import, no error later.
    This differs from a requires_pins written in the importing program itself,
    which refuses at authoring time (see above).
Where it may be declared

requires_pins belongs to a policy declaration. It is refused inside a
using { policy: … } fragment on a call, because a per-call clause is not where
standing configuration is established — the same rule that keeps trust roots out
of fragments. Declare it with a policy so it governs the whole run.

When two policy layers both name a tool, the required fields are combined: a
tool required to pin to by one layer and amount by another must pin both.
Requirements accumulate; a layer cannot cancel another layer's.

accepts: proof an operation class requires

accepts on an operation block names the proof each argument of that class of operation must carry. It is a map from argument name to the labels that count as proof; any one of them is enough:

record @contact [
  email: string [ kind "email" ]
]
exe .risk:exfil:send @notify(recipient) = `notified ${@recipient}`

policy @proof = {
  .risk:exfil:send { accepts: { recipient: [.fact:*, .src:user:intent:literal] } }
}

exe @tryNotify(r) = match [
  denied => `refused: ${@mx.denial.reason}`
  * => @notify(@r)
]

const @known = { email: "ada@example.com" } as record @contact
show @tryNotify("eve@evil.example")
show @tryNotify(@known.email)

Output:

refused: Operation '.risk:exfil:send' argument 'recipient' must carry one of the required attestations
notified ada@example.com

The typed-in address carries no proof, so the send is refused. The address that came through the @contact record carries fact proof, so it goes through. mlld validate warns when no operation in the file is in the class, because then the requirement never applies.

How grants attenuate from the law

The flow is:

  1. The base policy declares can_authorize (this page).
  2. A step mints a grant for a specific tool call, carrying proof-bearing argument values (security-grants).
  3. At mint time, the grant's tools must be a subset of what can_authorize allows.
  4. At dispatch, the enforcer checks the call against the grant.

The planner-worker delegation pattern — a planner authorizes a worker for exactly the tools and values it approved — is worked end to end in pattern-planner.

The tool contract

can_authorize names which tools a role may authorize. What each tool accepts is defined by the tool's input record: which arguments are security-relevant (fields with a kind), which are free payload (fields without one), and what proof each argument requires (accepts). See tool-definition.

The input-record contract is enforced at the dispatch floor on every call, and again as part of grant minting. Multi-fact write tools also check correlate (on by default), so all of a tool's fact arguments must come from the same source record — blocking an attack where an authorized call mixes one record's id with another record's recipient. Those record-definition features are covered in tool-definition and records-basics.

Validation

mlld validate does not check that every tool named in can_authorize and authorizations.deny resolves to a known tool. That check needs mlld validate --context tools.mld, which refuses to run.

Ordinary data objects may use a field named authorizations; it stays plain data unless it is used as a policy.

Denial routing

Authorization failures are hard structured denials, catchable by a denied => handler unless the covering rule is locked. Two moments are distinguished so a handler can route them differently (see security-denied-handlers):

  • GRANT_AUTHORITY_DENIED — a mint-time refusal: a grant asked to authorize a tool beyond the role's can_authorize set (the authorizer overreached).
  • GRANT_DENIED — a dispatch-time refusal: a call had no covering grant, or its value did not match the grant's pin (the caller acted without consent).

Composition

When several policies in force carry authorization law, they compose by "most restrictive wins":

Aspect Rule
Authorizable tools Intersection — a role may authorize a tool only if every layer's can_authorize allows it
Tools that need a grant Union — a tool any layer's can_authorize lists keeps needing a grant. A layer that narrows can_authorize never lets a tool run without one: the tool it drops is refused with GRANT_DENIED, and minting a grant for it with GRANT_AUTHORITY_DENIED
Deny Union — any layer's deny forbids the tool everywhere

deny always wins over can_authorize. See policy-composition for general merge rules.

Per-step consent is a grant (security-grants); the user's own words are proven with citations (security-citations); and the values an agent requested are turned into proof-carrying values in userland (pattern-planner). A person can also switch on an exception your .priv.sss policy wrote for a while (policy-label-flow, "Exceptions a person switches on"). That is not a grant: it lets through every call its allow! covers until its time or turns run out, it is not tied to one call's arguments, and it mints no grant. A one-call approval stays pinned to its call and switches nothing on. @policy.build and @policy.validate are retired and raise an error pointing here.

Policy Composition

Every policy you declare or import is in force at once, and their rules combine. You never have to merge them by hand for all of them to apply.

>> Team policy allows echo and git
policy @team = { * { capabilities: { allow: ["cmd:echo:*", "cmd:git:*"] } } }

>> Repo policy allows echo and node
policy @repoRules = { * { capabilities: { allow: ["cmd:echo:*", "cmd:node:*"] } } }

>> Effective: only echo, the one command both allow
run cmd { echo "allowed by both" }

echo runs. run cmd { git status } in the same program is refused with Command 'git' denied by policy, because only one of the two policies allows it.

Import pattern: each imported policy applies as soon as it is imported, and a local one applies too:

import policy @baseline from "./baseline.sss"
import policy @company from "./company.sss"
policy @localPolicy = { * { deny: { sh: true } } }

To combine a module's rules with union(…), have the module export them as a policy { … } value. import policy puts a policy in force but binds the module's namespace to the name, which union(…) cannot take. A value can be combined:

>> in baseline.mld: a value, not a policy directive
const @baselinePolicy = policy { * { deny: ["sh"] } }
export { @baselinePolicy }
>> in the importing file
import { @baselinePolicy } from "./baseline.mld"
const @localPolicy = policy { * { deny: ["cmd:echo:*"] } }
policy @combined = union(@baselinePolicy, @localPolicy)

@combined refuses sh blocks because the imported value says so, and echo because the local value does.

Why the module exports a value and not a policy directive here. A policy directive in an imported module applies the moment you import it, so union(…) would add nothing: delete the union line and the rules are still in force, which makes it easy to believe you have combined something when you have not. A policy { … } value puts nothing in force until something uses it, so the union(…) line does the work: remove it and sh runs again.

Reach for this only when you need one combined policy, to name the result or to combine it further. For simply having several policies in force, the import pattern is enough.

File loads after combining in one file. Once a single file puts two or more policies in force itself (two policy directives, two import policy lines, or a union() of two policies, as in the examples above), every later file load such as <notes.md> in that run is refused with Filesystem read denied by policy. A policy that arrives through a plain import of a module does not count toward this. If the program reads files after combining, keep one policy directive in the file and let the others arrive through imported modules.

Which export becomes the policy: a module imported with import policy resolves its policy by name. An export matching the import alias wins, then an export named config, then a module that exports exactly one policy-shaped value resolves it whatever its name (policy @team = { … } plus export { @team } works). A module exporting two policy-shaped values is refused as ambiguous (POLICY_IMPORT_AMBIGUOUS), and a module exporting none is refused (POLICY_IMPORT_NO_POLICY_EXPORT). Both errors name the fix, because a policy import that silently loaded nothing would leave you unprotected while looking enforced. The same resolution applies to policy.import entries in mlld-config.json.

How settings combine:

Setting Rule Effect
capability allow Intersection Must be allowed by every policy that has an allow list; a policy with none adds none
capability deny Union Denied by any policy
danger Intersection of what is stated Must be opted into by every policy that mentions it; a policy silent about danger withdraws nothing. A module brought in with a plain import can only narrow your own opt-in, never supply one
data rules (deny, only, block) Union Any policy's rule applies
ask Union Every handler must approve
limits Minimum Most restrictive wins

Note: If allow lists have no overlap, the intersection is empty and every operation is blocked. Make sure shared baseline commands appear in every layer.

Rules keep the file they came from through every combination. That is how an allow! exception knows whether it may lift a deny: only an exception from the deny's own file qualifies, or one from a .priv.sss file brought in with import policy (see sss-files and "Deny wins" in policy-label-flow).

Establishing and narrowing

Policies combine in two situations, and they do not carry the same authority.

Establishing: the config file, the CLI, a policy directive, import policy, and union(…) in a policy directive. These set the policy a run is under, so they may grant: a capability, a danger opt-in, an allow! exception to a rule that is not locked.

A plain import of a module only narrows the two opt-ins. Its policy's restrictions apply to you, but its danger list and its self_attestation grant can only take away from what your own policy opted into. If your policy says nothing about danger or self_attestation, or you have no policy, an imported module cannot turn either on for you. To adopt a module's opt-in, bring its policy in with import policy or combine it with union(…); both are your own choice and establish.

Narrowing: a using { policy: @frag } clause on a call, and a box constraint. These combine with a policy already in force, so they may only narrow. A fragment can add a deny, a block, an ask or a box ceiling. It cannot give itself a capability, a danger opt-in or a self_attestation grant the policy in force withheld, and it cannot carry an allow! exception. With no policy in force, a fragment that enables a self_attestation source or record is refused; declare it with policy @p = { … } instead:

policy @echoOnly = { * { capabilities: { allow: ["cmd:echo:*"] } } }
const @widen = policy { * { capabilities: { allow: ["cmd:git:*"] } } }

exe @status() = cmd { git status --short }
show @status() using { policy: @widen }

The call is refused with Command 'git' denied by policy: the fragment's allow cannot add git to what @echoOnly grants.

This is why a module that needs a capability for its own functions declares it in a policy directive rather than attaching it to each call. The directive establishes; the clause only narrows.

Replacing the caller's rules

replace: true on a using { policy } clause runs the call under the fragment instead of your own module's rules:

policy @ownRules = { .secret { deny: [.op:cmd] } }
const @onlyNoRm = policy { .op:cmd:rm { deny: true } }

const .secret @key = "k-1"
exe @echo(v) = cmd { echo "$v" }
show @echo(@key) using { policy: @onlyNoRm, replace: true }

Output:

k-1

replace sheds only rules that came from the calling module. Rules from imported policies survive it, and so do locked rules, along with the includes classes they are written in terms of. Authorization law (can_authorize, authorizations.deny) always narrows nested calls, replace or not.

Locking

locked: true on a rule means no combination may weaken it, at either authority. Lock one rule, or every rule in a policy with * { locked: true }:

policy @floor = {
  .secret { deny: [.risk:exfil]; locked: true }
  .risk:exfil { includes: [.net:w] }
}

A lock written for a whole policy also locks every policy composed with it. union(@fragment, { labels: { locked: true } }) locks the fragment's rules, in either order, and a separate policy @lock = { * { locked: true } } locks the rules of every policy in force. The lock only marks rules locked: on its own it denies nothing. A guard bind is locked only by the policy block that declares it.

A locked rule cannot be given an allow! exception, cannot have its ask removed, and is not shed by replace: true. (A guard's allow, privileged or not, lifts no deny: rule, locked or not.) A denial from a locked rule cannot be caught by a denied => arm either. A later policy can still make a locked rule stricter. locked and allow! in the same block are an error.

An includes: class that arrives over an import or in a using { policy } value cannot loosen a rule already in force, locked or not. It is refused when it would add a label that switches off a rule's negated part (.pii:not(.reviewed) with an imported .reviewed { includes: [.approved] }), widen a rule's allow!, or stop another includes: class from applying. A class that only makes a deny match more, such as the standard library's .risk:* classes, is accepted. The program's own policy directives may adjust an unlocked rule this way, but not a locked one: a class that would loosen a locked rule is refused whichever policy brings it and in either order, because a locked rule can only be narrowed.

Profile selection

Box profile selection considers the combined policy. The first profile whose requires all pass is selected:

policy @noSh = { * { deny: { sh: true } } }

const @cfg = {
  provider: "vfs",
  profiles: {
    full: { requires: { sh: true } },
    readonly: { requires: {} }
  }
}

box @cfg [
  >> Selects "readonly" because sh is denied
  show @mx.profile
]

Patterns combine by meaning

A pattern's labels are put in a fixed order before policies combine, so .a+.b in one policy and .b+.a in another are the same rule. Excluded labels (:not(…)) count toward specificity like any other part. See policy-label-flow for pattern syntax.

Stock policy fragments worth knowing:

  • @standard: the label-flow rules, proof floors and @urlOriginDefense
  • @strict: @standard, plus no network reads at all while .secret or .sensitive data is in context
  • @urlOriginDefense: refuses network reads of made-up or planted URLs while .secret or .sensitive data is in context (bundled into @standard)
  • @untrustedLlmsGetInfluenced: marks LLM output .influenced when its input was untrusted (bundled into @standard)
  • Scoped mitigation is minted by record coercion, not a stock fragment. Use a record's mitigates line plus a privileged record check that attests the mitigation, then admit the exact field with accepts.

urls.allow never widens when policies combine. Allow lists from two policies intersect, and a using { policy } fragment cannot declare urls. See security-url-exfiltration.

Authorizations combine on the same "most restrictive wins" principle. This governs .op:tool:w operations only:

Setting Rule Effect
authorizable tools Intersection Must be authorized by every layer
tools that need a grant Union A tool any layer lists under can_authorize still needs a grant; one no longer authorized by every layer is refused
argument constraints Conjunction All constraints from every layer must pass

true combined with a constrained entry becomes the constrained entry (stricter wins). Incompatible constraints on the same argument remain valid config, but no runtime value can satisfy them, so the call is denied.

See security-policies for writing a policy, policy-capabilities for capability syntax, policy-label-flow for rules, and policy-authorizations for authorization law.

Policy Credentials

using secret:name injects a credential into a command as an environment variable, through a sealed path.

Why sealed paths matter: an injected credential bypasses string interpolation. It is set in the process environment and never passes through template text a prompt could influence.

policy @keys = {
  * {
    secrets: {
      claude: { from: "keychain", as: "ANTHROPIC_API_KEY" },
      github: { from: "env:GH_TOKEN", as: "GH_TOKEN" },
      brave: "BRAVE_API_KEY"
    }
  }
}

run cmd { claude -p "hello" } using secret:claude

secrets in the policy's * block is where credential mappings live. On a call, using secret:name names one; using { secret: "name", policy: @frag } combines it with other using keys. On a definition, the clause goes between the signature and =: exe @f() using secret:claude = ….

Declaring a credential outside policy

The secret directive declares one credential on its own, without a policy. It takes the same from / as fields, and the value is used the same way:

secret @api = { from: "env:MLLD_DEMO_SECRET", as: "API_KEY" }

exe @keyLength() using secret:api = cmd { printf "len=%s" "${#API_KEY}" }
show @keyLength()

With MLLD_DEMO_SECRET=abcdef12345 in the environment, this prints len=11. The command reads the key from its environment; the value never appears in the script.

The same credential can be named on a call instead, for an executable that does not name one itself:

secret @api = { from: "env:MLLD_DEMO_SECRET", as: "API_KEY" }

exe @keyLength() = cmd { printf "len=%s" "${#API_KEY}" }
show @keyLength() using secret:api

A name on a call is looked up where the call is written, so calling an imported executable this way uses your credential, not one its module declared. A call's using adds to the definition's; a variable both set to different values is refused.

The short form (secret @brave = "BRAVE_API_KEY") is a keychain lookup, not an environment one: it expands to from: "keychain:mlld-box-{projectname}/BRAVE_API_KEY", so it needs projectname in mlld-config.json and refuses without it, even when the environment variable is set. The environment is only a fallback once the keychain entry is missing. To read the environment directly, say so: { from: "env:BRAVE_API_KEY", as: "BRAVE_API_KEY" }.

Config forms

Field Purpose
from Source: "keychain:path", "keychain", or "env:VAR"
as Target environment variable name

Short form examples:

policy @keys = {
  * {
    secrets: {
      brave: "BRAVE_API_KEY",
      claude: { from: "keychain", as: "ANTHROPIC_API_KEY" }
    }
  }
}

Expansion rules:

  • "BRAVE_API_KEY" -> { from: "keychain:mlld-box-{projectname}/BRAVE_API_KEY", as: "BRAVE_API_KEY" }
  • { from: "keychain", as: "ANTHROPIC_API_KEY" } -> { from: "keychain:mlld-box-{projectname}/ANTHROPIC_API_KEY", as: "ANTHROPIC_API_KEY" }

Resolution order

For using secret:name, mlld looks in this order:

  1. Credentials captured on the executable where it was defined
  2. The caller's policy secrets

Caller bindings override same-name captured bindings.

A module's secret declarations travel with the functions it defines: an imported function uses its module's credentials wherever it is called from, and neither the importer nor another module can use them. A keychain: credential from a registry, URL or GitHub-resolver module reads the keychain only when the importer's policy grants danger: ["@keychain"]; without the grant, only its environment-variable fallback (the as name) is used. The usual fix is to name the credential in your own policy instead (* { secrets: { typesafe: "TYPESAFE_API_KEY" } }): your binding replaces the module's, reads your project's keychain entry, and needs no danger grant. danger: ["@keychain"] lets every such module read whatever keychain entry it declares.

Keychain behavior

Keychain paths use service/account and support {projectname} from mlld-config.json.

Resolution for from: "keychain:...":

  1. Read the keychain entry
  2. If missing, read the environment variable named by as
  3. If both are missing, fail

Unsupported provider schemes (for example .op.//...) fail with an explicit error.

A keychain entry you name yourself, in your policy's secrets or with a secret directive, needs no other permission: naming it is the grant, and the grant covers that one entry. danger: ["@keychain"] is only for keychain reads you did not name: a registry, URL or GitHub-resolver module's own credentials (see "Resolution order" above), and a secret that only a using { policy } fragment names, since a fragment cannot grant itself access. The keychain setting's allow and deny lists still gate every keychain read, named or not, and a deny match wins.

Linux keychain access uses secret-tool (libsecret). Make sure secret-tool is on PATH.

policy @keys = {
  * {
    secrets: {
      claude: { from: "keychain:mlld-box-{projectname}/claude", as: "ANTHROPIC_API_KEY" }
    }
    keychain: {
      allow: ["mlld-box-{projectname}/*"],
      deny: ["system/*"]
    }
  }
}

run cmd { claude -p "hello" } using secret:claude

Label flow checks for credential injection

Credential injection keeps secrets out of command strings, and policy rules still apply to both injection channels. A credential injected with using secret:name counts as .secret input, and a value injected with using { env: { NAME: @v } } brings its own labels.

One exemption: spending a key at the host it was declared for is not exfiltration, so a credential delivered through using secret:name does NOT fire the receiving operation's own .secret → .risk:exfil deny. Every other secret input (a value in the request body, a secret delivered through using { env }) is still governed by that deny:

policy @keysAndFlow = {
  * { secrets: { api: { from: "env:MLLD_DEMO_SECRET", as: "API_KEY" } } }
  .secret { deny: [.risk:exfil] }
}

>> runs: the credential is exempt from the receiving op's own exfil deny
exe .risk:exfil @send() using secret:api = cmd { printf "sent with a %s-char key" "${#API_KEY}" }
show @send()

>> refused: a secret value passed through `using { env }` still meets the deny
const .secret @token = "computed-value"
exe .risk:exfil @leak() using { env: { TOKEN: @token } } = cmd { printenv TOKEN }
exe @tryLeak() = match [
  denied => `refused: ${@mx.denial.reason}`
  * => @leak()
]
show @tryLeak()

Output (with MLLD_DEMO_SECRET=abcdef12345):

sent with a 11-char key
refused: Label '.secret' cannot flow to '.risk:exfil'

The credential keeps its .secret label for every other rule, including output redaction, destination restrictions, and denies on non-exfil targets.

Explicit variable injection

using { env: { NAME: @v } } puts a value into a command's environment under a name you choose:

const .secret @token = "computed-value"
run cmd { printenv TOOL_KEY } using { env: { TOOL_KEY: @token } }

Direct keychain access in templates or commands is blocked; declare the credential in policy secrets and inject it with using secret:name instead.

A .secret { deny: [.risk:exfil] } rule blocks secrets flowing into .risk:exfil operations. To also block showing or logging a secret, add those operations:

policy @noSecretOutput = {
  .secret { deny: [.op:show, .op:log] }
}

Signer Trust Root

The signers row of self_attestation declares the principals whose keys may sign: the attestation manifest, and the tapes a run or a host records. This is the signer trust root. On verification a signer's entry grants labels minted onto the verified principal.

A signer is a party outside the program, so only the project's config may name one. Write the row in a local policy file that mlld-config.json's policy.import names:

>> policies/signers.mld, listed in mlld-config.json's policy.import
policy @sec = {
  * {
    self_attestation: {
      signers: {
        "me": {
          key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDvFU3H9BZPGk7cJs3n6yY8f5X2QvW1cTz0Hb4Rm9KsP",
          labels: [".sig:approved:me"],
          classes: ["instructions"],
          valid_after: "2026-08-01T00:00:00Z"
        }
      }
    }
  }
}
{ "policy": { "import": ["./policies/signers.mld"] } }

A signers row anywhere else refuses when it loads, and the error names mlld-config.json: a script's policy, a module that file imports, a registry or remote policy, a union() member that did not write the row out, or a using { policy } fragment. The old top-level spelling, * { signers: { … } }, refuses wherever it is written, and the error writes out the row to use instead.

Only key is mandatory — a bare { key: "…" } entry means "this key may sign, with no restriction". Every other field narrows or annotates. The whole surface is static: extraction reads the literalized policy object, a non-static value refuses, and unknown keys refuse rather than being silently dropped.

The signer principal

A principal is the identity a signature belongs to: when verify checks a signed manifest, it reports which principal signed it off. The grammar:

[A-Za-z0-9]([A-Za-z0-9._-]{0,62}[A-Za-z0-9])?

One to sixty-four characters, alphanumeric at both ends, with ., _ and - allowed inside. Principals ride in .sig:approved:<principal> labels granted on verification, so anything that would corrupt label segmentation — :, @, /, whitespace, an empty name — refuses with sig.signers.bad_principal.

The key line

key holds a full OpenSSH public-key line: <algorithm> <base64> [comment]. The base64 must decode and re-encode canonically, and the decoded blob's inner wire-format algorithm must agree with the outer token (an inner ssh-rsa under an outer ssh-ed25519 is refused as the confusion it is). A malformed line refuses with sig.signers.bad_key.

The admitted algorithms are ssh-ed25519 and ecdsa-sha2-nistp256 (P-256). A P-256 key may only certify a tape, because the machine-bound keys an unattended host uses (a Mac's Secure Enclave, a Linux TPM) can only make P-256 keys; a manifest signature and an envelope seal must be ssh-ed25519. A manifest signed by a P-256 key refuses with sig.verify.algorithm_not_allowed, and mlld sig approve skips P-256 principals for that reason. A P-256 key listed as an envelope issuer refuses at policy load with sig.signers.unsupported_algorithm, and an envelope sealed by a P-256 key refuses with sig.envelope.bad_signature. No other NIST curve is admitted. An entry naming an algorithm this build cannot verify refuses at policy load, by name, with sig.signers.unsupported_algorithm — never deferred to verify time. A trust root that silently cannot verify a listed principal would be a config error dressed as a trust root; the refusal says which algorithms this build supports.

Optional fields

Field Rule Rationale
labels array of label strings, sorted and deduplicated Granted on verification, minted onto the verified principal — never the manifest's self-asserted approvedBy. Grammar: leading-dot .seg[:seg]* with segments [A-Za-z0-9._-]+ (max 128 chars); violations refuse with sig.signers.bad_label.
valid_after / valid_before RFC3339 strings; valid_after must be strictly before valid_before Windows bind at verify time, not at load. Extraction validates the shape only; each verification evaluates the window against the verifier's clock, so an expiring window expires when it says it does. A malformed or inverted window refuses with sig.signers.bad_window.
classes array from the closed vocabulary instructions, scripts, policy, skills, binary A principal restricted to a set may sign manifests whose entries touch only those classes. An omitted classes means unrestricted; an empty array refuses — a principal restricted to no classes can sign nothing, so omit the key instead. An unknown class refuses with sig.signers.unknown_class.

Unknown keys refuse with sig.signers.shape rather than being dropped — a typo must not silently discard a constraint. The namespaces restriction from OpenSSH's allowed_signers is refused this way too: it is vacuous here, because the signature namespace is fixed (mlld-sig@v1), so the block admits classes only and says so in the refusal text.

Host-bound signers

An unattended host — a program that records its own sessions, with nobody there to unlock an ssh-agent — can still seal its session tapes with a host-bound signer: a signers entry with a hostKey saying where its private key lives.

policy @sec = {
  * {
    self_attestation: {
      signers: {
        "fray-host": {
          key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDvFU3H9BZPGk7cJs3n6yY8f5X2QvW1cTz0Hb4Rm9KsP",
          hostKey: { file: "/Users/me/.config/mlld/host-keys/fray-host" }
        }
      }
    }
  }
}

hostKey is "enclave" (a Mac's Secure Enclave), "tpm" (a Linux TPM) or { file: "<path>" } (a key file; a relative path is read from the project root). This build signs with a key file anywhere, with the Secure Enclave on macOS and with a TPM on Linux. A host-bound entry takes no labels or classes, and anything else in hostKey refuses with sig.signers.shape.

mlld sig host-key init <principal> --source file makes the key file and prints the entry to paste. --source is required. The file is an OpenSSH ssh-ed25519 private key with no passphrase, mode 0600. A P-256 key file refuses with sig.host_key.file: the library mlld would sign a P-256 key file with does arithmetic that is not constant-time (RUSTSEC-2026-0387), so a host key uses P-256 only inside the Secure Enclave or TPM. A symlink also refuses and names the path, and so, on macOS and Linux, does a file the group or others can read. Windows has no such mode bits, so there the file is protected only by its folder's access settings.

On a Mac: the Secure Enclave

A Mac with a Secure Enclave (Apple silicon, or an Intel Mac with a T2 chip) can hold the host key in the Enclave, where the private key never leaves the chip:

  1. Run mlld sig host-key init fray-host --source enclave. It makes a P-256 key in the Enclave, writes the Enclave's wrapped copy of it to ~/.config/mlld/host-keys/fray-host.enclave (mode 0600), and prints the public key line and the entry to paste.
  2. Paste the entry into self_attestation.signers in a policy file that mlld-config.json's policy.import names. It reads "fray-host": { key: "ecdsa-sha2-nistp256 …", hostKey: "enclave" }; an "enclave" signer finds its file by its principal's name.
  3. Grant the host what its turns may claim in the host row of the same self_attestation table.

The .enclave file is useless on any other machine: only this Mac's Enclave can unwrap it. It signs with no prompt and no fingerprint, so a host running in the background keeps sealing. A Mac with no Secure Enclave says so at step 1; use --source file there. If the Enclave refuses the file later (it was copied from another Mac, it is damaged, or a macOS update stops reading it), or does not answer within 10 seconds, the host's tapes stay unsealed and the reason names the file; enrol a new key and replace the entry. A key file listed beside an Enclave signer does not stand in for it on a Mac: a key file is the fallback only on a machine that has no Enclave, so damaging or deleting the Enclave key cannot hand the seal to a weaker key.

On Linux: the TPM

A Linux machine with a TPM 2.0 can hold the host key in the TPM, where the private key never leaves the chip:

  1. Make sure this user can open /dev/tpmrm0; it is usually owned by the tss group, so add the user to it (sudo usermod -aG tss $USER, then log in again).
  2. Run mlld sig host-key init fray-host --source tpm. It makes a P-256 signing key in the TPM, writes the TPM's wrapped copy of it to ~/.config/mlld/host-keys/fray-host.tpm (mode 0600), and prints the public key line and the entry to paste.
  3. Paste the entry into self_attestation.signers as on a Mac; it reads hostKey: "tpm", and the signer finds its file by its principal's name. Grant the host its claims in the host row.

The .tpm file is useless with any other TPM, but on this machine it is as good as the key: anyone who can read a copy of it (root, a backup, another account it was copied to) and open the TPM can sign with it. Treat it like a private key. mlld uses the TPM's owner hierarchy with no password, which is how most machines ship; if yours has an owner password, step 2 says authorization failed, and --source file is the fallback. Clearing the TPM destroys the key: the host's tapes then stay unsealed, with a reason naming the file, until you enrol again. A machine with no TPM, or a user who cannot open it, is told so at step 2 and pointed at --source file. As on a Mac, a key file listed beside a TPM signer does not stand in for it on a machine that has a TPM: if the TPM key cannot be used, the tapes stay unsealed.

A host-bound signer has far less authority than any other signer:

  • It is never a signer for anything else. mlld sig, manifests, envelopes, granted labels and pins all see only the other signers, as if the entry were not there. A run never seals its own tape with one.
  • It is tried only after the ssh-agent, and only when a host records a session.
  • Its seal covers only the host's own events, read under the host row's granted claims. Every other event in the same tape — mlld calls, the run's own markers, recalled or replayed answers — reads as unsealed.

Same-user processes can ask the key to sign, whether it is in the Enclave, the TPM or a file, and the fallback file can be copied by them. "Host-bound" limits what the signature counts for, not who can make it. See docs/dev/TAPE.md "Sealing" for how a reader applies the limit.

Restatement

Within one signers object:

  • One key, one identity. The same key blob listed under two principals refuses with sig.signers.duplicate_key — verification would be ambiguous about which principal signed off.

Across policy sites (two config files, or both labeling and defaults in one):

  • An identical restatement is one signer. The same principal with the same key and fields at two sites loads, and is kept once.
  • A conflicting one refuses at load. The same principal with another key or other fields refuses with sig.signers.duplicate_principal, and the same key under two principals with sig.signers.duplicate_key. Both errors name both sites.

The sibling trust root self_attestation.issuers (see policy-envelopes) follows the same rule.

Absent and ambient

Fail-closed absence. No signers section (or an empty one) is not an error — Tier 1 (SSHSIG signing) is simply not active, and the Tier 0 mechanics (hash-pinned drift protection) keep working. Declaring the root is what turns signing on; nothing half-declares.

Config only. Every reader of a sealed tape (resume, replay, recall, fork, and a host reading its own tape back) verifies against the config's signers, so they all trust the same keys. A fragment-scoped trust root would let imported code name the key whose signatures the scoped run then believes, so a signers row refuses inside a using { policy } fragment as self_attestation.issuers does. That refusal is a plain runtime error with no refusal code: the fragment is wrong, not the runtime.

How the root is used

Every mlld sig command reads the root as a run does: from the policies mlld-config.json's policy.import names, composed by the rule above. To do that it loads those policy files as a run's start does, so their code runs: a run, an output or an @http call in one of them happens on every mlld sig command, mlld sig hook included.

What those files import is read offline, so mlld sig works without a network:

  • A registry module loads from mlld-lock.json and the local module cache. One the cache lacks stops the command with an error naming it and mlld module install.
  • A URL, a GitHub resolver path, a remote MCP server, or a <url> load is not read at all. The command stops with an error naming the source, even for an optional <url>? load, so a policy read without its page never passes for one written without it. Import such a policy from a local file or an installed registry module instead.

A signer written in some other project file is not used, and mlld sig says so, naming the file. A config whose signers cannot be read (a conflicting row, say) is an error naming the config; for mlld sig hook that is exit code 3. The attest stanzas come from scanning the project's .mld files and from the config's policies, so a shared policy file outside the project counts too; mlld sig info lists it.

The root is consulted before per-file attestation law runs — a wholesale trust consult, never mode-gated:

  • mlld sig drift prints the root as trust root: b3:<digest> naming each principal with its SHA256: fingerprint — the identity is a b3: digest of the sorted OpenSSH fingerprint set, so a root membership change is a root change while editing a field on an unchanged set does not re-derive it.
  • mlld sig hook <path> under a declared root consults the manifest's trust verdict FIRST — before the per-path mode check. A manifest that cannot be verified against the root returns verdict unverifiable and exit 1 even on a path the stanzas exempt as off — an unverifiable manifest under a root is a wholesale refusal, and "the stanza says off" is not a way around it.
  • mlld sig verify refuses a committed-but-unsigned manifest with sig.verify.unsigned_manifest — a Tier-1 repo never accepts an unsigned manifest. A signature whose embedded key is not in the root refuses with sig.verify.untrusted_key: the wrong-key check refuses at the trust root, before any cryptography, and the refusal names the fingerprint the root would need to contain.

Binding the root to this machine

The committed signers block is repo law; the pin is this machine's commitment to a particular root identity, held outside the repo at ~/.config/mlld/sig-pins.json (machine-local by design — it never travels with the clone).

  • First sight is TOFU. The first mlld sig verify against a repo's root runs a first-sight ceremony and acknowledges the root under trust-on-first-use.
  • mlld sig trust pin upgrades that to a committed pin: this machine accepts sign-offs only from exactly that root identity.
  • Rotation is a new trust. If the root identity a verify computes no longer matches the pin, verification refuses with sig.pins.pin_mismatch — the rotated root is a new trust, never a silent continuation. The remedy is the operator reviewing the change in a diff, then re-running mlld sig trust pin with the new root in view.

Envelope Trusted Issuers

The issuers row of the self_attestation table lists the trusted issuers whose signed envelopes mlld may admit. An issuer row is a trust root: it names a key, says which values a holder of that key may assert for each kind of claim, and sets how fresh an envelope must be.

Issuers are outside parties, so only the config policy may declare them: a local policy file that mlld-config.json's policy.import names (see policy-auth). The row goes in the policy's * block:

>> policies/trust.mld, listed in mlld-config.json's policy.import
policy @trust = {
  * {
    self_attestation: {
      issuers: {
        "ci": {
          key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIDEirMBezYU1vzBWFYRQa2y3m8y7M9mQjJ3p5z0l0X0b ci",
          scope: { source: "*", user: ["gh:12345678", "gh:87654321"] },
          max_age: "5m"
        }
      }
    }
  }
}

The row's name ("ci") is the issuer id, and all three fields are mandatory. A malformed row refuses the whole policy at load — nothing here defers to admission time.

Fields

Field Type Purpose
key string An OpenSSH ssh-ed25519 public-key line (the full line, including the ssh-ed25519 prefix).
scope object For each claim kind the issuer may assert (source, user), either "*" for any value or a list of the values it may assert.
max_age duration The freshness window, such as "30s", "5m", "2h" or "7d". An envelope older than this is not fresh enough to admit.

The id and key share one grammar with the signer trust root, including the refusal codes for a malformed value (see policy-signers). The id is fixed by the external signer's keyId, so choose it to match what your signer emits.

A program driving mlld through an SDK builds the envelope to sign with the live method envelope:canonical and signs it with its own key (see config-live-stdio). mlld never signs envelopes.

An issuer row has no claims list. Admitting an issuer's envelope gives the value a proof marker naming that issuer, never trust: the admitted value arrives untrusted. So an issuer may only ever supply proof, and its scope is the whole of what it is granted. A row with a claims key refuses at load.

Scope

scope is mandatory to write but may be broad. The failure being guarded is granting a key everything by not thinking about it, so "*" is how you say "any value" on purpose.

  • Each kind the issuer may assert is written out. A kind left out may not be asserted: an envelope that carries a user claim from an issuer whose scope lists no user refuses with sig.envelope.scope_violation, and the error names "*" as the way to admit any user.
  • Every envelope asserts a source, so a scope without source could admit nothing. It refuses at load with sig.envelope.no_scope, naming "*". An absent scope refuses the same way.
  • A list limits the values. With user: ["gh:12345678"], an envelope claiming user gh:12345678 is admitted and one claiming gh:87654321 refuses with sig.envelope.scope_violation.
  • user values are principals, written <provider>:<stable account id> (for example gh:12345678), the same way a host names a person (see match-ask). A value in another shape refuses at load.
  • An empty list (user: []) refuses as unreadable: leave the kind out, list values, or write "*". A "*" inside a list refuses too, because it would read as a literal value.
  • The vocabulary is closed: a kind other than source and user refuses with sig.envelope.unknown_claim_kind. Lists are sorted and deduplicated at load.

Freshness

max_age is mandatory for the same reason as scope (absent refuses with sig.envelope.no_max_age). A signature proves origin, never freshness, so the window must be explicit. It uses the duration grammar labeling.approvals.restore_window uses: a whole number followed by s, m, h, d or w. A zero window refuses (it admits nothing), and so does "never". A bare number refuses, and the error names the duration to write.

Unknown keys refuse rather than being dropped, with sig.envelope.policy_shape naming the offending key.

Fail-closed absence

Declaring no issuers is not an error — but it means nothing is admitted. No issuers key, a null value, or an empty issuers: {} all yield no trusted issuers, so there is no admission path and no envelope is admitted.

Config only

self_attestation.issuers refuses at load anywhere but a local policy file that mlld-config.json's policy.import names, with an error naming the policy, the file it came from, and that home. That covers a policy directive in a script, and a module a config policy file itself imports, whether by a plain import or by import policy: such a module runs while the config loads, but it is not one of the files the config names. A registry or remote module refuses too, even when policy.import names it directly: write the row in a local policy file and list that file instead. A script that imports one of the config's own policy files again is not refused; the issuer is already in force from the config, and the identical restatement counts once.

The row must also be written in that file. It counts when the file writes it out in full: in a policy directive over a literal (as above), in a policy { … } value or an object bound by a const there with every key and value literal, or in a union() of those. A row the file passes on from somewhere else refuses at load, naming the row, the file and the remedy: an imported value re-exported, a copy (const @config = @imported), a rename, a field or namespace member, a spread, the result of a call, or data loaded from a file. A template counts as not written even with no variable in it: key: `${<k.pub>}` reads the key from a file when the policy loads. One config policy file may pass on another's policy when both are listed in policy.import: the issuer counts because the second file is listed, and the restatement counts once. It also refuses inside a using { policy } fragment, as signers does: a fragment-scoped trust root would let imported code name the key whose envelopes it is then believed through.

Restatement across policy sites

When the same issuer id is declared at two config policy sites (for example, two policy files that each list a shared organization root), the declarations compose at load:

  • Identical restatement composes. The same key, scope (every kind and every listed value) and max_age is accepted and deduplicated, keeping the first declaration. "5m" and "300s" are the same window.
  • Conflicting restatement refuses. The same id with a differing key, scope or max_age refuses with sig.envelope.duplicate_issuer, naming the differing field and both sites. A trust root does not take the shorter window or the narrower list: reconciling the two would derive a trust root neither site authored.

The same rule runs in one place on every channel (CLI and SDK), so a given program composes or refuses identically either way. One key may have only one identity: two rows declaring the same key (matched by fingerprint) under different ids refuse, in one policy or across sites.

The old spelling

envelopes: { issuers: [{ id, key, scope: [...], maxAgeSeconds }] } is the old spelling. It refuses at load with sig.envelope.old_spelling, and the error writes out the row to use instead. A kind in the old scope list becomes "*", which admits what the old entry admitted; replace it with a list to narrow it.

CLI loads the grammar; admission runs at the SDK boundary

The grammar and the merge rule above load, validate and compose on every channel, including the CLI. But the admission door — the component that actually verifies a sealed envelope against a declared issuer and admits it — runs at the SDK boundary. On the CLI a declaration is loaded and validated but no envelope is admitted.

An admitted field arrives untrusted. The host's labels for that field (payloadLabels) still apply to it, as they do to a field sent without an envelope, so a .pii rule sees a sealed .pii field. A trust request for it (payloadFieldTrust) is honored only when self_attestation grants the sdk row trust, the same rule as for any other SDK field.

Who and where an admitted value came from

An admitted field also carries the source and user the issuer vouched for, as a label mlld adds:

#src:envelope[@source="slack"][@user="gh:12345678"]

An envelope with no user claim gets [@user=null]. The values are lower-cased where case carries no meaning: the source, and a user's provider (the part before the first :). The account id keeps its case. Each value is written as a quoted string, so spaces, quotes and brackets stay inside one value.

The label can only restrict. A policy may deny on it:

policy @blocked = {
  #src:envelope[@source][@user="gh:87654321"] { deny: [.op:tool:w] }
  #src:envelope[@source="email"][@user] { deny: [.op:net:w] }
}

Name both slots; leave a slot's value off to match any value. A pattern that writes a value in a form mlld never writes, such as [@source="Slack"], could match nothing, so it refuses at load and names the form to use. .src:envelope matches every envelope-admitted value.

The label never lifts a deny, never satisfies a role or principal check, and never makes a value trusted: the person it names is who the issuer said, not who is acting. mlld registers the #src:envelope[@source][@user] family itself, so a program's own id for it refuses at load. At the input doors only admission writes it: a sealed payload that carries the label, or a host label (payloadLabels) that names it, refuses the field with sig.envelope.origin_label. The same refusal covers the other labels mlld writes only from what it observed itself: .src:tape, .src:selector, .src:host, .src:state and .src:fyi, with anything under them. A host relaying a value can still carry its channel (.src:file, .src:web, .src:cli), which mlld cannot have seen and the relay can truthfully report. The admission record keeps the same two values, as the envelope sent them, for audit.

box

Boxes are mlld's primitive for scoped execution contexts. They encapsulate credentials, isolation, capabilities, and state.

policy @noNetwork = {
  * {
    capabilities: {
      allow: ["cmd:npm:*"],
      network: { allow: [] } >> no hosts
    }
  }
}
const @sandbox = {
  provider: "vfs",
  fs: { read: [".:/app"], write: ["/tmp"] } >> built-in in-memory workspace; read host . as /app, allow writes to /tmp
}

box @sandbox [
  run cmd { npm test }
]

Why boxes matter for security:

  • Credential isolation - Credentials injected via sealed paths, not exposed as strings (scope: declared credentials only — the variables they are read from, env: sources and keychain as names, are scrubbed from child processes; other secrets in your shell environment pass through as any shell passes them — see credentials)
  • Capability restriction - Limit what tools and operations agents can use
  • Blast radius - Contain failures within box boundaries

Boxes are values:

const @task = "Review code"
const @cfg = { provider: "vfs", tools: ["Read", "Write"] }
const @readonly = { ...@cfg, tools: ["Read"] }

box @readonly [ run cmd { claude -p "$task" } using { env: { task: @task } } ]

Compute, compose, and pass boxes like any other value. Here @readonly leaves Bash out of tools, so the command inside is refused: Command execution requires 'Bash' in env.tools.
Use object spread to derive one config from another, and enter the narrower one. A using { tools: [...] } clause on box does not narrow: it replaces the config's tool list, so it can add a tool the config left out (see box-directive).
For enforcement boundaries (what mlld enforces locally vs what requires a sandbox provider), see the table in box-config.

Providers add isolation:

Provider Isolation Use Case
"vfs" In-memory workspace, no host programs Local agent runs
"kernel" Kernel fence Host-isolated local runs
@mlld/env-docker Container Process isolation
@mlld/env-sprites Cloud sandbox Full isolation + state

Every box resolves a provider. A bare box [...] with no provider uses "kernel", and refuses loudly on hosts that cannot fence. See box-config for the full provider rules. A sealed kernel box reads only its base floor, so developer tools installed outside it (such as macOS's git or homebrew programs) cannot run in it unless the box names their folders with fs: { read: [...] }; box-config explains the failure, its note and the folders to name.

Complete sandbox example:

Combine box config with policy to restrict an agent:

policy @agentOnly = {
  * {
    capabilities: {
      allow: ["cmd:claude:*"], >> claude is the only command that may run
      deny: ["sh", "mcp:*"] >> no sh code blocks, no MCP tool calls
    }
  }
}
const @sandbox = {
  provider: "vfs",
  tools: ["Read", "Write", "Bash", "Glob", "Grep"] >> Allow tools for agent use
}

box @sandbox [
  run cmd { claude -p "Analyze code" }
]

The allow list is what restricts commands here: only claude matches it, so every other command is refused. The sh entry is a separate axis — it turns off run sh { ... } code blocks and has no effect on commands. See policy-capabilities.

For a complete working example with Docker isolation, credentials, and guards, see sandbox-demo in llm/run/j2bd/security/impl/sandbox-demo.mld.

Reading order: box-config for configuration fields, box-blocks for scoped execution, policy-capabilities for restrictions, policy-auth for credentials.

Box Directive

The box directive creates scoped execution contexts that combine process isolation, credential management, and capability control.

For concepts and configuration details, see box-overview, box-config, and box-blocks.

Sandboxed execution with credentials:

policy @sandboxed = {
  * {
    capabilities: {
      allow: ["cmd:claude:*"],
      network: { allow: [] },
      deny: [".mcp:*"]
    }
  }
}
const @sandbox = {
  provider: "vfs",
  fs: { read: [".:/app"], write: ["/tmp"] },
  tools: ["Read", "Bash"]
}

secret @claude = { from: "env:ANTHROPIC_API_KEY", as: "ANTHROPIC_API_KEY" }
exe @analyze() using secret:claude = cmd { claude -p "Analyze the codebase" }

box @sandbox [
  run @analyze()
]

provider: "vfs" names the built-in in-memory workspace. fs restricts filesystem access, tools limits runtime tool availability, and policy capabilities gates commands, network and MCP access. Credentials flow through sealed paths with using secret:name, never interpolated into command strings.

Local execution with different credentials:

secret @claudeAlt = { from: "env:ANTHROPIC_API_KEY_ALT", as: "ANTHROPIC_API_KEY" }
const @cfg = { provider: "vfs" }
const @task = "Summarize the changes"

exe @askAlt(prompt) using secret:claudeAlt = cmd { claude -p "$prompt" }

box @cfg [
  run @askAlt(@task)
]

Use this for credential rotation across calls (e.g., multiple API keys to avoid per-account rate limits).

Config fields:

Field Purpose
provider Isolation provider. "vfs" = built-in in-memory workspace, "kernel" = OS fence (the default)
secret Not available: a box config with secret stops with unsupported (unported) construct. Put using secret:name on the call instead
tools Runtime tool allowlist
fs Filesystem access (passed to provider)
limits Resource limits (passed to provider)
profile Explicit profile selection
profiles Profile definitions for policy-based selection

Narrowing a box:

const @sandbox = {
  provider: "vfs",
  tools: ["Read", "Write", "Bash"]
}
const @readOnly = { ...@sandbox, tools: ["Read"] }

box @readOnly [
  >> Only Read is available here
  show "read-only"
]

Derive a config with fewer tools and enter that. A derived config is a new config: nothing compares it with the one it was spread from, so leave out what the box must not reach.

A using { tools: [...] } clause on box does not narrow. It replaces the config's tool list, so it can add a tool the config left out: box @readOnly using { tools: ["Bash"] } [ run cmd { … } ] runs the command. A box nested inside another box is checked against its parent and cannot add tools the parent lacks (Tool scope cannot add tools outside parent: bash).

VFS resolver shorthand:

files <@workspace/> = [{ "task.md": "checklist" }]

box { provider: "vfs", fs: @workspace } [
  run cmd { cat task.md }
]

box { provider: "vfs", fs: @workspace } binds an existing resolver-backed workspace as the box's filesystem (the provider is required — a named-workspace box is not provider-neutral).

Anonymous VFS box:

box { provider: "vfs" } [
  file "task.md" = "inside box"
  run cmd { cat task.md }
]

All box forms provide an in-memory workspace. box { provider: "vfs", tools: ["Read", "Bash"] } [ ... ] additionally restricts tools. Use box { provider: "vfs", fs: @workspace } to bind an existing resolver-backed filesystem instead.

Tool scope formats:

box @config using { tools: ["read", "write"] } [...]
box @config using { tools: "read, write" } [...]
box @config using { tools: "*" } [...]
const @subset = { read: @readTool, write: @writeTool }
box @config using { tools: @subset } [...]

Profile selection:

const @cfg = {
  provider: "vfs",
  profiles: {
    full: { requires: { sh: true } },
    readonly: { requires: {} }
  }
}

box @cfg using box:readonly [
  show @mx.profile
]

using box:readonly names a profile the config declares. When no profile is named, the first profile whose requirements are satisfied by the active policy is selected. Inline configuration in the clause is refused: what a box runs under is declared where the box is configured.

Inside a running box, a single call can select one of that box's declared profiles for its own duration. Selecting does nothing else: the call runs in the same box, with the same settings.

const @cfg = {
  provider: "vfs",
  profiles: {
    full: { requires: { sh: true } },
    readonly: { requires: {} }
  }
}
exe @which() = `profile: ${@mx.profile}`

box @cfg using box:readonly [
  show @which() using box:full
  show @which()
]

Output:

profile: full
profile: readonly

A name the running box does not declare is refused and the refusal lists the declared profiles; using box: on a call outside any box, or in a box that declares no profiles, is refused too.

Return values:

const @config = { provider: "vfs" }
const @result = box @config [
  let @data = cmd { echo fetched }
  => @data
]
show @result

box does not implicitly return the last expression. Without =>, the box returns its workspace object. Use => @some_call(...) to return a call result.

Scoped environment:

The box block creates a child environment. Variables defined inside don't leak out, but the block can access parent scope variables.

const @config = { provider: "vfs" }
const @sample = "test"
exe @shout(text) = js { return text.toUpperCase(); }

const @out = box @config [
  let @processed = @sample | @shout
  => @processed
]
show @out

Box Configuration

Box configuration objects control isolation and credentials. They also carry a limits key that no provider enforces: the kernel provider refuses a box that sets it, and vfs ignores it. See the enforcement table below.

policy @noNetwork = {
  * {
    capabilities: {
      allow: ["cmd:npm:*"],
      network: { allow: [] }
    }
  }
}
const @sandbox = {
  provider: "vfs",
  fs: { read: [".:/app"], write: ["/tmp"] },
  limits: { mem: "512m", cpu: 1.0, timeout: 30000 }
}

box @sandbox [
  run cmd { npm test }
]

A bare box [...] with no provider uses the kernel provider, and refuses loudly on hosts that cannot fence. provider: "vfs" selects the built-in in-memory workspace. An llm executable's own body does not run under either provider: it runs under the harness profile in mlld-config.json (see config-files), and inside a box with no profile the call is refused.

VFS-backed local mode:

files <@workspace/> = [{ "task.md": "todo" }]

box { provider: "vfs", fs: @workspace } [
  run cmd { cat task.md }
]

These forms create a VirtualFS-backed runtime for local execution:

  • box { provider: "vfs", fs: @workspace } [ ... ] (resolver-backed workspace)
  • box { provider: "vfs" } [ ... ] (anonymous workspace)

In VFS mode, defaults are applied unless overridden:

  • tools: ["Bash", "Read", "Write", "Glob", "Grep"]
  • remote git hydration is blocked unless policy capabilities.network allows the host

VFS defaults apply when the box has a workspace (provider: "vfs", with or without an fs: binding) and no explicit tools field is provided. An explicit using { tools: [...] } overrides the defaults. A box with no tools still admits the mlld-function tools an llm call inside it passes (@ask("…", { tools: @t })); the five defaults limit only builtin tools such as "Edit". A function tool it admits still runs inside the box, under the box's file and network limits, and a box nested inside one whose tools excludes the tool still refuses it. An active policy can provide * { default_box: @boxRef } for operations with no box of their own; a local box config replaces that default. Capabilities still apply after box resolution, so command, MCP, and network access are gated by policy even when the box supplies tools.

.new instance mints: a config value (or an object that validates as a box config) supports .new, which eagerly mints a fresh box instance and returns an opaque handle:

const @cfg = { provider: "vfs", lifecycle: "shared" }
exe @writeMarker() = cmd { echo hi | tee marker.txt }
exe @readMarker() = cmd { cat marker.txt }

const @h = @cfg.new                      >> mints eagerly: each `.new` mints its own instance
box @h [ let @a = @writeMarker() ]       >> writes marker.txt in the minted instance
box @h [ show @readMarker() ]            >> re-enters the same instance: prints "hi"

box @handle [...] re-enters the minted instance — the same workspace across entries. A handle is frame-bound: it is usable in the frame that minted it or a descendant; a handle returned out of its frame (e.g. from an exe) refuses loudly. Serialized handles ({ "__box_instance": "bmi-…" }) are inert data — re-reading them never recreates a live instance, and a forged marker object used as a box reference refuses loudly. Durable named instances (name: on a .new config) are not available and are refused.

On an executable, @tool.new() invokes the tool with a fresh instance of its configured box — per-call isolated spelled on the callee. @readMarker needs a full shell for its || fallback, and sh blocks are off by default, so the policy line switches them on:

policy @allow_sh = { * { capabilities: { sh: true } } }
exe @writeMarker() = cmd { echo hi | tee marker.txt }
exe @readMarker() = sh { cat marker.txt 2>/dev/null || echo "absent" }

const @r = box { provider: "vfs" } [
  let @a = @writeMarker()
  let @b = @readMarker.new()  >> fresh instance for this call: marker.txt is absent
  => @b
]
show @r

Outside any box context there is no instance to mint from: a plain with { lifecycle: "isolated" } tail is a no-op there, but the explicit .new() request fails closed — it refuses rather than run the tool unfenced on the host.

Configuration fields:

Field Values Purpose
provider "vfs", "kernel" Isolation provider. With no provider, a box uses "kernel"
fs { read: [...], write: [...] }, and with kernel also hide: [...] Filesystem access
limits { mem, cpu, timeout } Resource limits
secret "credential-name" Not available: a box config with secret stops with unsupported (unported) construct. Put using secret:name on the call instead
tools ["Read", "Write", "Bash", "Glob", "Grep"] Runtime tool allowlist for commands and MCP tools. With no tools, the five defaults limit builtins, and the function tools a call passes are admitted
state { read }, @scope State slots code in the box can read, under @fyi.state
lifecycle "shared", "isolated" Instance lifecycle. shared (the default): one instance per box entry — every call in the block shares it, so one call's writes are visible to the next. isolated: each call mints a fresh instance (vfs: fresh workspace + shell session; kernel: a fresh fenced child), so a file one call writes is absent for the next call. Merges strictest-wins across the config, the exe definition's with clause, the call's with clause, and the policy's role setting (.role:<r> { lifecycle: … }, see below): any isolated wins, nothing relaxes it. A bogus value is an error, never a silent downgrade. On surfaces where nothing consumes it mlld warns rather than silently ignoring it.

Role-forced lifecycle (policy): .role:worker { lifecycle: "isolated" } in a policy forces every tool call made under that role (an exe .role:worker invocation) to run isolated, regardless of program text. A call's with { lifecycle: "shared" } under a forced role is overridden, and the verdict trace records a box.lifecycle.override event naming the role rule. A using { policy } fragment can force isolated on a role but never relax an established one (strictest-wins, intersect-only). A tool whose mcpConfig server entry declares stateful: true cannot honor forced isolation — the call fails loudly naming the role rule rather than silently degrading to shared. Role names are open vocabulary; a bogus lifecycle value is an error naming the role. |

Builtin kernel provider:

box { provider: "kernel" } [
  run cmd { make test }
]

Kernel is the default: a bare box [...] with no provider key resolves to kernel, and on hosts that cannot fence (a Linux host with Landlock absent or below the needed ABI, or Windows) the bare form refuses loudly. Name provider: "vfs" explicitly or run on a capable host.

The block's commands execute inside a real kernel fence (a resident seatbelt-sandboxed instance on macOS, a Landlock-enforced instance on Linux), not the VFS shell. The sealed shape is enforced: filesystem reads are confined to the instance run dir plus the platform read floor, writes are denied everywhere outside the run dir and the folders fs.write names, the network defaults to net: "none", and the mlld control plane (.llm/, mlld-config.json / mlld-lock.json writes) is carve-denied on macOS (on Linux the allow-only Landlock model denies the control plane by construction — nothing outside the scope is allowed). Outside the folders it may read, a command also cannot learn a file's size, owner or times: on macOS stat and ls -l of such a file are refused like cat. It can still tell whether the file exists, because a file that exists is refused ("Operation not permitted") while a missing one is not found ("No such file or directory"). Linux's Landlock does not cover looking a file up, so there a command in the box can still learn a file's size, owner and times as well, without reading its contents. The provider is fail-closed: config it cannot honor refuses with the gap named — limits and a real-path fs jail are refused. The fs settings it takes are folders to read and write and paths to hide (below). sh code blocks, with { stdin } and commands whose environment has declared credentials removed run inside the fence, in the instance's own directory. On a Linux host without Landlock (or below its needed ABI) and on Windows the provider refuses; there is no Windows backend. On Linux each box, and every command mlld runs in its default fence, also gets a private user and mount namespace where the host allows unprivileged user namespaces. File access is the same, but inside it ls -l shows files owned by root or other users as owned by nobody (uid 65534), and id lists fewer groups. Where the host does not allow them, commands run without one; --trace shows a box.ambient.namespace_unavailable event saying why.

A sealed kernel box reads only that base floor, so a tool installed outside it cannot run there: on macOS, git (the Xcode command-line tools' shim) fails with xcode-select: error: unable to read data link at '/var/db/xcode_select_link' ... (Operation not permitted) followed by advice to install developer tools, and programs under homebrew fail with an error ending in (file system sandbox blocked open()). In both cases mlld's failure report adds a note naming the path the fence blocked. A vfs box is not an alternative: it has no host programs at all.

To let a tool run, name the folders it reads with fs: { read: [...] }. The box can then read those folders as well, and still nothing else; it writes nowhere outside its run dir and the fs.write folders. On macOS, git needs Xcode's folder and the record that its license was accepted:

const @noConfig = "/dev/null"
box { provider: "kernel", fs: { read: ["/Applications/Xcode.app/Contents", "/Library/Preferences"] } } [
  let @v = run cmd { git --version } using { env: { GIT_CONFIG_GLOBAL: @noConfig } }
  show @v
]

Your home folder stays unreadable, so git cannot read ~/.gitconfig; setting GIT_CONFIG_GLOBAL to /dev/null tells it not to look. Homebrew programs need /opt/homebrew (on an Apple-silicon Mac). Each entry is a folder, given by its absolute path or relative to the project. The vfs provider's host:alias form is refused, because a kernel box reads each folder where it is, and so is any fs key other than read, write, hide, git and floor.

A policy caps these folders, as it caps the network: when a policy is active, it must let the program read everything inside each folder (for example capabilities: { allow: [".fs:r:/opt/homebrew/**"] }), or the box refuses and says why. That includes what the policy refuses: a folder that holds a path the policy denies, or one a built-in danger entry covers (~/.ssh/* in your home, **/.env in the project), is refused, since the box would read it all. Name a narrower folder, or opt in to the danger entry by writing it under capabilities: { danger: [...] }. With no policy, the folders you name are read. The control plane stays protected inside a named folder: on macOS the same carve-out applies, and on Linux, where the fence cannot carve, a folder holding .llm/ or .mlld/ (the project's, the workspace's or your home's) is refused.

fs: { write: [...] } names folders the box may read and write. Each must exist and be a folder. fs: { hide: [...] } names files or folders the box may not read, list or write at any depth, even inside a read or write folder; hide wins over both, and a link that leads into a hidden path is refused with it. A hidden path must exist when the box starts, or the box refuses (box fs.hide path '…' cannot be hidden: …). The box cannot hide its own run folder. hide works by path: a hard link to a hidden file that was made before the box started, at a path the box may read, still reads the file, so hide the link too or remove it.

box { provider: "kernel", fs: { write: ["./work"], hide: ["./work/.env", "./work/secrets"] } } [
  run cmd { make build }
]

Inside a write folder, every git folder the box can reach stays unwritable except the state git writes in normal use (objects, refs, logs, the index, HEAD, ORIG_HEAD, FETCH_HEAD, merge state, packed-refs, COMMIT_EDITMSG and their lock files), so the box cannot set up a command that a later git run outside the box would execute in a repository that existed when the box started (a repository the box itself creates during the run is not protected yet): hooks, config, config.worktree, commondir, info and the like stay unwritable, as do a linked worktree's .git file and git folder and a submodule's git folder under .git/modules, and the box cannot add a new git folder under .git/modules or .git/worktrees, nor start a rebase's todo list. A commit, a branch switch or a fetch inside the box works; initialising a submodule, adding a worktree, and starting or continuing a rebase do not. fs: { git: "writable" } turns this off for the box. A write folder with more than 200,000 entries is refused, since mlld looks through it for git repositories; name a narrower folder or set git: "writable". On macOS a write folder may hold the project; its .llm/, .mlld/, mlld-config.json and mlld-lock.json stay unwritable. On Linux such a folder is refused, as for read.

A write folder also keeps what the default fence protects (see enforcement-planes) unwritable: the harness folders (.claude, .codex, .pi and the others mlld knows, plus any folder your llm.harness profile names), the script and every .mld module, .priv.sss file and policy file the run loaded before the box started, every file in the signing manifest, and .sig/. The box cannot change them, delete them, move their folders aside, or create a missing one, so a box writing the project cannot create .claude/settings.json. Other files in the folder, a new file beside a loaded module included, stay writable. A write folder that is one of these, or lies inside one (write: [".claude"]), is refused, since nothing in it could be written. fs: { harness: "writable" } turns this off for the box, for a project that edits those files on purpose; .llm/, mlld-config.json and mlld-lock.json stay unwritable, and an active policy still caps the folder (its built-in danger entries cover .claude/ and .codex/, for example).

box { provider: "kernel", fs: { write: ["."], harness: "writable" } } [
  run cmd { ./scripts/update-agent-settings.sh }
]

A policy caps write folders the same way as read folders: the policy must let the program read and write everything inside each one (for example capabilities: { allow: [".fs:w:/path/to/work/**"] }), or the box refuses and says why. hide only takes access away, so no policy check applies to it.

On Linux, Landlock cannot take a path back inside a folder it grants, so mlld mounts an empty, read-only file or folder over each hidden path, and binds each git hooks folder and config file read-only onto itself, in the box's own mount namespace. A hidden folder therefore looks empty there rather than refused. This needs unprivileged user namespaces: on a host without them, a box that hides paths refuses and names the gap. A missing path cannot be mounted over, so on Linux the box cannot stop a new .git/commondir, .git/config.worktree or .git/rebase-merge being created: a box with a write folder that holds a git repository, or is its .git folder, is refused, saying so, unless it sets git: "writable" to accept that. In the same way, a write folder that holds a protected path that does not exist yet (a signed file not created yet, or an import candidate mlld tried before the file it loaded, such as the bare name of an import written without its .mld extension), or a link on the way to a loaded module, is refused on Linux unless it sets harness: "writable". macOS keeps those names from being created. mlld box run on Linux cannot hide or write-lock paths and refuses such a box.

fs: { floor: "dev" } adds the development read floor: the system, package-manager, toolchain and git paths a developer toolchain reads, without your home folder. On macOS it covers TLS roots and /private/etc/hosts, the Command Line Tools and /Applications/Xcode.app/Contents/Developer, /usr/local/go, Nix, and of /opt/homebrew, /usr/local and MacPorts' /opt/local only what they install (bin, sbin, Cellar, opt, lib, libexec, include, share, Frameworks, Caskroom), and the public CA certificates and OpenSSL configuration under their etc (etc/ca-certificates, etc/openssl@3, etc/openssl@1.1, etc/openssl), not the rest of their etc or their var (a Homebrew database's files), and in your home only ~/.cargo/{bin,registry,git}, ~/.rustup/{toolchains,settings.toml,update-hashes}, ~/go/pkg/mod, ~/sdk, ~/Library/Caches/go-build, ~/.bun/{bin,install/cache}, the node version managers' installed nodes, ~/.npm/_cacache, ~/.pyenv/versions, ~/.local/share/uv/python, ~/.local/bin and git's own config files (~/.gitconfig, ~/.config/git/{config,ignore,attributes}). On Linux it covers TLS roots, name lookup, /etc/passwd and /etc/group (not /etc/shadow), /etc/alternatives, the loader's configuration, /proc/cpuinfo, /proc/meminfo, /sys/devices/system/cpu, Linuxbrew (the same folders as Homebrew), Nix, snaps, /usr/local/go, /etc/gitconfig, and the same home entries. /opt is not on the Linux floor, since a vendor installs anything there, data included; name a toolchain under it in fs.read. Everything on the floor is read only. A path that does not exist is skipped. A home entry that is a link (a dotfiles setup) is granted only at the place it leads to, and never when that is your home folder or a folder holding it. The rest of your home (~/.ssh, ~/Documents, other ~/.config files and so on) stays unreadable; open a folder with fs.read when a box needs it. hide wins over the floor, and a policy caps its entries as it caps read folders. ~/.gitconfig is on the floor, and a git config can hold credentials (an http.extraheader token, say): if yours does, add it to hide. The spelling floor: "dev" is provisional. On a Mac with Xcode rather than the Command Line Tools, /usr/bin/git also needs /Applications/Xcode.app/Contents and /Library/Preferences in fs.read.

A kernel box prints nothing extra by default. To see what each box was granted, set MLLD_BOX_AUDIT=1: mlld then prints one mlld-box-audit line on stderr when a box starts, after each command in it and when it ends, naming the enforcement mechanism and the filesystem, network and pre-opened paths the box was given. It also prints, for each command, the mlld: box.ambient.tmpdir_override: … note saying the command's temporary directory was moved inside the box (on macOS the default one is always outside it). Any other value leaves the lines off. --trace effects shows the same note as a box.ambient.tmpdir_override trace event.

A named workspace (a prior box's implicit-return workspace value) enters via fs: @ws: the workspace files materialize into the fenced instance dir before each command runs and diff back afterwards, so created/modified files land back in the workspace and deletions drop from it. Symlinks created inside the fence refuse loudly (they cannot be represented in the workspace); binary (non-UTF-8) outputs refuse the diff-back rather than silently mangling. Inside such a box, @root names the instance dir; after the box it names the project again. The provider belongs on the config object — box @ws with { provider: ... } is an error (nothing reads provider from a clause on box, so it is never silently dropped).

Important: tools enforces runtime tool access inside box blocks. MCP and network access are policy capabilities, not box fields.

Field Enforced by mlld? Notes
tools Yes mlld restricts available tools
fs With provider: "kernel": yes, kernel-enforced on macOS (Seatbelt) and Linux (Landlock) on a host that cannot fence (a Linux host without Landlock, or Windows) the box refuses to enter rather than run unfenced
net With provider: "kernel": yes "none" (the default), "loopback" or "open", or a host list { allow: [...], deny: [...] } (see Host lists below). "loopback" allows connections to this machine only, on any port: 127.0.0.1, ::1, and on macOS every other address the machine holds, including its address on the local network, so a service listening there is reachable too. Linux cannot fence by address, so a kernel box asking for "loopback" there refuses to start. Any other value, such as "any", is refused with a message naming the three. On macOS, every setting except "open" also blocks the system services that reach the network for a program, including certificate checking, so a signature check such as codesign -v fails inside the box.
limits No — the kernel provider REFUSES a box that sets it limits (mem, cpu, timeout) needs rlimits or cgroups, which entry fencing does not provide, so the provider refuses with the gap named rather than dropping the key silently. Distinct from net, which the fence does honor.

The builtin kernel provider enforces fs through the OS fence (Seatbelt on macOS, Landlock on Linux, probed by kernel ABI), and refuses limits rather than accepting it unenforced. On a host that cannot fence (a Linux host without Landlock or below its needed ABI, or Windows), the box refuses loudly rather than running unfenced.

  • Include Bash in tools to allow run cmd, run sh, and shell-backed command executables.
  • Use capabilities.allow / capabilities.deny for command and MCP rules (for example cmd:git:push or .mcp:github:*).
  • Use capabilities.network in a policy to limit every command's network, with the same tiers and host lists as a box's net.
Host lists

A box's net can name the hosts its commands may reach:

box { net: { allow: ["registry.npmjs.org", "*.npmjs.com"], deny: ["www.npmjs.com"] } } [
  run cmd { npm view mlld version }
]
  • Patterns. An exact host (api.github.com); *.example.com for any subdomain but not example.com itself; an exact IP address (IPv6 in brackets); each with an optional :port. An allow entry with no port means 443; a deny entry with no port means every port. The tiers "none", "loopback" and "open" may stand in allow too: allow: ["loopback", "api.github.com"] adds this machine, and allow: ["open"], deny: [...] means every host but those. IP ranges and a bare * are refused (write "open"). International names are converted to punycode.
  • How it is enforced. The box's commands can connect only to a proxy that mlld runs for that box; their HTTPS_PROXY, HTTP_PROXY and ALL_PROXY point at it, and any NO_PROXY is removed. The proxy lets through only HTTPS (CONNECT) to an allowed host, and checks that the connection's TLS server name is that host. A tool that ignores the proxy variables cannot connect at all.
  • Keys stay outside. A credential whose policy entry has a base_url reaches the box's commands as a stand-in, with a base URL pointing at the proxy. The proxy puts the real key into each request to the credential's for: host, so the program never holds the key. The box must allow that host. See Keeping the key out of a box with base_url in auth.
  • Refusals. A refused connection prints mlld: box.net.denied: <host>:<port> — <reason> on stderr (the first five hosts of a run, then a count) and a box.net.denied trace event; see runtime-tracing.
  • What a deny list can see. Allow and deny match the host name the command asked for. A name that resolves to a private or reserved address is refused, and so is one that resolves only through a corporate proxy, because mlld resolves the name itself before connecting.
  • What it does not limit. mlld's own requests on a tool's behalf (URL imports, @http, MCP servers over HTTP) are outside the box's network setting; label rules govern what data they may carry.
  • What a deny list cannot stop. Deny entries match names. A command that connects to an IP address, to a name with another CNAME, or to a mirror of a denied host is judged by that name or address, not the denied one. Prefer an allow list.
  • Where it runs. Host lists are enforced on macOS, and on Linux where unprivileged user namespaces are allowed (each box gets a private network namespace whose only way out is the proxy). Elsewhere a box with a host list refuses to start and says why. On Linux a host list that also allows "loopback" refuses, because the box's namespace has no route to the machine's loopback. mlld box --box @name <cmd…> honours host lists the same way, for a box a config-imported policy module declares (see cli-box-run). A named long-lived box (mlld box --name) refuses host lists in this release.

State scope:

The state config field decides which state slots code inside the box, such as an agent's llm call, can read. They appear under @fyi.state:

record @contact [
  key id
  id: string [ kind "contact" ]
  name: string
  * { read: [id, name] }
  .role:worker { write: { state: [upsert] } }
]
const @recs = { contact: @contact }
state @book from @recs
exe .role:worker @file(st, r) = [
  let @w = @st.upsert("contact", @r)
  => "stored"
]
const @a = @file(@book, { id: "c1", name: "Ann" } as record @contact)

box { state: { read: [@book.contact as picks] } } [
  show @fyi.state.picks
]

This prints the stored contact. Without as picks the slot appears under its state's name, @fyi.state.book.contact. read also takes an object whose keys become the names (read: { picks: @book.contact }), { name, ref } pairs, or a whole state: read: [@s] opens every slot of @s under its own name (@fyi.state.label). read: @s opens the same slots for a state declared with = { … }; for a state built from @records, write the brackets, since read: @s opens nothing there. Listing @fyi.state before a slot is read shows a placeholder for it, such as "[unread shelf slot: @fyi.state.label]". The whole scope can be held in a variable (state: @plannerScope) and is checked the same way. A value that is not an object opens no slots, and mlld validate reports it as box.state must be an object.

A box grants no write scope: an agent cannot write state. box { state: { write: … } } is refused with "box { state: { write: … } } is not available: an agent cannot write state yet, so a box grants no write scope. Give the box state: { read: [ … ] } and make the write in the program." Code in the box writes state with the state's own operations, such as @book.upsert(…). See State.

Advanced: MCP configuration via @mcpConfig():

Define an @mcpConfig() function to provide profile-based MCP server configuration:

const @cfg = {
  provider: "vfs",
  profiles: {
    full: { requires: { sh: true } },
    readonly: { requires: {} }
  }
}
exe @mcpConfig() = match [
  @mx.profile == "full" => {
    servers: [{ command: "mcp-server", tools: "*" }]
  }
  @mx.profile == "readonly" => {
    servers: [{ command: "mcp-server", tools: ["list", "get"] }]
  }
  * => { servers: [] }
]

box @cfg using box:readonly [
  show @list()
]

The function is called when a box block spawns, with @mx.profile set to the selected profile. using box:name selects a profile by name. When no profile is named, the first profile whose requirements are satisfied by the active policy is selected. Inline configuration in the clause is refused: what a box runs under is declared where the box is configured, not at the point it is entered.

Starting each of those servers is the operation .op:mcp:spawn. A policy block denying that operation to untrusted data does not constrain a box's @mcpConfig(): a config built from untrusted data still starts its servers. The rule does hold for import tools from mcp "@spec", where a spec built from untrusted data is refused and no server process starts. See mcp-policy.

Servers a box declares are scoped to that box: the box gets its own server process (two boxes declaring the same server never share a connection, and a nested box never rides its parent's), and an anonymous box's servers shut down when the box exits. A .new-minted box handle keeps its servers across box @handle re-entries — the instance's lifetime is the interpretation. Tools the config registers bind only inside the box's scope and disappear with it. An isolated call (with { lifecycle: "isolated" } or .new()) mints its own anonymous box scope, so servers started inside the call are closed when the call completes. Calls into a shared box instance are serialized on the instance: parallel iterations queue rather than race the same connection.

A box's servers run under the box's network and write limits; reads stay open. A local server the box declares in @mcpConfig(), and one started by an isolated call inside the box, get the box's network, and may write only where the box lets its own commands write: nowhere but its own run directory in a kernel box, and nowhere on the host in a vfs box. A tool imported at the top level and called inside a box is served by a second process of its server, started for that box under the box's network and write limits; the top-level process keeps running as it was. In every case the server can still read files outside the box's folders, even in a kernel box that limits what its own commands read. A server keeps these limits when it restarts, and keeps them with fence.default: "off" in mlld-config.json, which switches off only the default fence. Outside any box, a local server runs under the default fence described in mcp-import.

A server entry can carry its own box: setting, the same one import tools from mcp … using { box: … } takes (see mcp-import). Here it keeps one server off the network the box allows:

exe @mcpConfig() = {
  servers: [{ command: "mcp-server", box: { net: "none" } }]
}

Inside a box that setting can only narrow the box's limits; to give a server more room, set box: where it is imported outside any box (see mcp-import). A wider network or an extra write folder is dropped, not refused, and the box.mcp.server_capped trace event (shown with --trace effects) names what was dropped; see runtime-tracing. A url entry takes no box:; it is not a process.

Remote servers (url entries): the same scoping holds at the connection level — two boxes over the same remote URL hold two connections with distinct server-side sessions, and an isolated remote call opens a fresh connection per call. The assurance differs from local, though: a local server process is physically per-box, while remote cross-instance isolation is a promise the provider makes. Declare that promise a requirement with requires:

exe @mcpConfig() = `{"servers":[{"name":"vault","url":"https://mcp.example.com/mcp","requires":["instance_isolation"]}]}`

At connect, mlld cross-checks each required capability against the capabilities the provider advertises in the handshake (top-level or under capabilities.experimental). A provider that does not declare a required capability is refused — the error names the capability, and no connection is established. A provider running the stateless MCP revision advertises nothing at the handshake, so it satisfies no requirement.

Package caches (fence.caches)

A command outside any box runs under the default fence, which lets it write only in the project and its own sandbox folder. A package manager that keeps its cache in your home folder (npm's ~/.npm) cannot write there, so without help every install downloads everything again. So each sandbox gets a private cache for each such tool. fence.caches in mlld-config.json, beside fence.default, turns this off or picks tools:

{ "fence": { "caches": false } }
  • true, the default (also when the key or the whole file is absent): every tool mlld knows: npm, pip, yarn 1, bun, Go, sccache, cargo and pnpm.
  • false: no private caches.
  • A list of tool names, such as ["npm"].

With it on, a command gets npm_config_cache (and pip's, yarn's and bun's cache variables) pointing at a cache folder inside its sandbox; box-package-managers covers each tool. On macOS, the first command that runs the tool fills that folder with a copy-on-write copy of your real cache, so installs reuse what you already downloaded and cannot change your real cache. On Linux the folder starts as an overlay of your real cache, with the same effect; where the host does not allow it, it starts empty.

cargo and pnpm record their cache's full path in what they build, so they keep it: on Linux the sandbox sees an overlay there, so they work as usual without changing your real cache; on macOS that cache stays read-only, and a run that needs a download fails with a hint (see box-package-managers). A tool mlld does not know is an error that lists the tools you can name. Commands inside a box never get these caches. An llm harness's own commands outside a box get them the same way, and inside a box they do not. The setting lives only in mlld-config.json: no policy can turn it on where the config turned it off. With fence.default: "off" there is no default fence, and the setting does nothing.

Local daemon sockets (fence.sockets)

A local daemon does whatever a command asks it to, outside the fence: a command that reaches the Docker socket can run any container, with access to the whole machine. So the default fence keeps commands away from local daemon sockets, except the ones fence.sockets in mlld-config.json names:

{ "fence": { "sockets": ["git", "docker", "/run/user/1000/podman/podman.sock"] } }
  • Absent, the default is ["git"]: the ssh agent (SSH_AUTH_SOCK, and each IdentityAgent written as a plain path in ~/.ssh/config, such as 1Password's; files pulled in by Include and values using % or $ tokens are not read) and gpg-agent, so git push over ssh and signed commits keep working.
  • "docker" allows Docker's socket where Docker Desktop, Colima, OrbStack or a Linux install puts it.
  • An absolute path allows that socket. Podman and containerd have no preset; name their socket's path.
  • [] allows none, the git agents included.

On macOS every local unix socket is closed except the named ones, the system name resolver and the sandbox's own folder. On Linux the fence cannot close unix sockets by path, so it hides Docker's, Podman's and containerd's sockets instead, where the host allows unprivileged user namespaces; other sockets stay reachable, and on a host without those namespaces nothing is hidden (--trace shows a box.ambient.namespace_unavailable event). Network ports on this machine (TCP loopback) stay open in both.

Only the default fence does this. A policy that narrows a command's network closes every socket, named ones included. A box whose network is "open" leaves sockets as they are.

When a command fails because the fence refused a socket, mlld prints one line naming the fix, outside the command's output:

mlld: the fence blocked /var/run/docker.sock; to allow it, add "docker" to fence.sockets in mlld-config.json

--trace records the same as a box.net.socket_denied event. mlld learns of the refusal only from the command's own error message, so the line appears when that message names the socket's path (Docker's does, as do most clients' "Operation not permitted" or "Connection refused" errors); a client that fails without naming the path gets no line. A path that came from a secret is never printed, so it gets no line either.

Boxes required by policy

A policy can require a box for an operation, or narrow the box it runs in, with the box key on an operation block or a data + operation block:

policy @boxRules = {
  .secret+.op:cmd { box: { net: "none" } }
  .untrusted+.op:cmd { box: * }
}

const .secret @key = "k-1"
exe @echo(v) = cmd { echo "$v" }
show @echo(@key)

The command receives secret data, so it runs in a box with no network. mlld prints a note naming the rule (note: ran in a box because of policy rule .op:cmd+.secret) and writes the box to the audit record.

  • box: {…} is a ceiling, never a grant. The call runs in the current context narrowed by these attributes; when no box is running, mlld starts one, narrowed the same way. An attribute looser than the current context has no effect. The attributes are net ("none", "loopback", "open" or a host list, as in Host lists above), fs with read and write lists of directories (fs: { read: ["."], write: [] }), lifecycle (only "isolated" on a policy rule) and provider. limits is refused because no provider honors it, box: {} is refused (write box: *), and an unknown attribute is an error.
  • box: * means some box must already be running for the call: an explicit box block, or one another matching rule starts. Otherwise the call is refused: Policy rule .op:cmd+.trust:untrusted requires this operation to run in a box, and none is running.
  • box: @name runs the call in the meet of the named box config and the current box, never a loosening.

A box contains the shell but does not stop exfiltration by itself, so use it next to .secret { deny: [.risk:exfil] }, not instead of it. A using { policy } fragment may add a box: {…} ceiling but not box: @name.

Compose with object spread:

const @sandbox = { provider: "vfs", fs: { read: [".:/app"], write: ["/tmp"] } }
const @readonly = {
  ...@sandbox,
  fs: { ...@sandbox.fs, read: [".:/app"], write: [] }
}

See box-overview for concepts, box-directive for block syntax.

Box Blocks

Execute directives within a scoped environment using box @config [ ... ].

const @sandbox = { provider: "vfs", tools: ["Read", "Write", "Bash"] }

box @sandbox [
  run cmd { echo "inside sandbox" }
]

The environment is active only within the block and released on exit.

Anonymous workspace block:

box { provider: "vfs" } [
  file "task.md" = "inside box"
  run cmd { cat task.md }
]

What a command inside the block can run depends on the provider. A vfs box is an in-memory workspace with a built-in shell of about 80 standard commands (cat, ls, grep, sed and the like). Real programs such as git, node or claude are absent there: they fail with command not found (exit 127) and never start on the host. A kernel box, which a bare box [ ... ] uses, runs host commands inside the kernel fence, within its limits: reads are confined to the box's run directory and the operating system's own files, so a program that loads files from elsewhere (Xcode's git, a Homebrew node) fails to start. run cmd { echo hi }, /bin/ls and run sh code blocks work. See box configuration for what the fence allows. Every box block supports file/files directives.

Named workspace block:

files <@workspace/> = [{ "task.md": "from resolver" }]

box { provider: "vfs", fs: @workspace } [
  run cmd { cat task.md }
]

Use box { provider: "vfs", fs: @workspace } to run in an existing resolver-backed workspace, such as one an earlier box returned. The shorter box @workspace [ … ] is refused: named-workspace box has no provider — declare provider: "vfs" explicitly.

Inspect workspace edits and diffs:

files <@workspace/> = [{ "task.md": "draft" }]

box { provider: "vfs", fs: @workspace } [
  file "notes.md" = "review complete"
]

show @workspace.mx.edits
show <@workspace/notes.md>.mx.diff
  • @workspace.mx.edits — array of {path, type, entity} where type is created/modified/deleted
  • <@workspace/path>.mx.diff — unified diff string for a single file

Neither is available: reading one stops with unsupported (unported) construct: mx projection field 'edits'.

files <@workspace/> = git "…" parses but is not available: running it stops with unsupported (unported) construct: value node 'GitFilesSource'. See the files directive for what to do instead.

Return values and workspace binding:

box does not implicitly return the last expression. Use => to return a value:

const @result = box [
  file "data.txt" = "hello"
  => "completed"
]

show @result                >> "completed"

Without =>, the box returns its workspace object:

exe @plan(step) = `plan: ${@step}`

const @ws = box [
  @plan("next step")              >> runs, but the box ignores its value
]
const @answer = box [
  => @plan("next step")           >> returns the call's result
]
show @answer                      >> "plan: next step"

To access workspace files after the box exits, omit => so the variable binds to the workspace:

const @ws = box [
  file "data.txt" = "hello"
]

show <@ws/data.txt>         >> "hello" — reads from workspace via resolver

The <@name/path> resolver syntax reads from the workspace VFS after the box exits. Inside the box body, use run cmd { cat file.txt } to read via the ShellSession — bare <file.txt> reads from the real filesystem, not the active workspace.

Named child environments:

const @sandbox = { provider: "vfs", tools: ["Read", "Write", "Bash"] }
const @readOnly = { ...@sandbox, tools: ["Read"] }

box @readOnly [
  run cmd { cat README.md }    >> refused: Bash is not in this box's tools
]

A derived config is a new config: nothing compares it with the one it was spread from. A box nested inside another box is checked against its parent and cannot add tools the parent lacks.

Notes:

  • Environment resources are released when the block exits
  • using { … } on a box lends it settings (tools, a profile with box:name); with { … } says how it runs (lifecycle, mode). using { tools } replaces the config's tool list, so it can add tools as well as remove them
  • Ambient @mx.box includes active bridge metadata (mcpConfigPath, socketPath) while inside the box scope
  • See box-overview for concepts, box-config for configuration fields

Per-call tool configuration via config.tools:

When an llm executable is invoked with a config.tools array, the runtime automatically creates MCP bridges and exposes the result on @mx.llm:

llm @claudeHarness(prompt, config) = [
  let @cfg = @config ? @config : {}
  >> @mx.llm.config   — MCP config file path for the explicit tool policy
  >> @mx.llm.allowed  — unified tool names for --allowedTools or equivalent
  >> @mx.llm.native   — native tool names CSV (empty when no native tools requested)
  >> @mx.llm.inBox    — true when an active VFS bridge exists
  >> @mx.llm.hasTools  — true when config.tools was specified
  let @allowed = @mx.llm.allowed
  let @out = run cmd { claude -p --allowedTools "$allowed" "$prompt" } using { env: { allowed: @allowed } }
  => @out
]

Inside a box, an llm call's tools must be mlld executables, passed in a tools collection (tools @t = { … }, then tools: @t). A builtin name like "Read" is not served there and refuses, because passing the name on would hand the model the host's tool instead of the box's. Outside a box, string tools pass through as native CLI tool names. A collection's entries get their own function MCP bridge. A tool the box's tools: list does not allow refuses, naming the tool and the list, so list each entry's name there. The runtime handles all of this — module authors just read @mx.llm.

An llm body runs under its own fence, which the box limits. The body of an llm executable is the harness that talks to the model, so it does not run in the box's own instance. It runs under the harness profile declared as llm.harness in mlld-config.json (see config-files), which lets it read broadly and write only the paths the profile lists, such as its own config directory. Inside a box the box also caps it: its network is the box's (plus the model hosts its definition lists in egress), and a profile write path the box does not allow is dropped for the call, keeping only its home. It cannot write your project folder or the box workspace: a body like sh { … | tee out.txt } fails to write out.txt. What the box contains is also what the model does: every tool call it makes (an exe ref) goes through the bridge and runs inside the box. config-files ("Inside a box") has the details, including signing in with an API key.

A definition can declare its own profile, which replaces the config file's for that definition: llm @planner(prompt, config) using { harness: { home: "~/.agents/planner", net: "open" } } = cmd { … }. It takes the same keys as llm.harness (home, write, net), and must be written in the definition, not passed in a variable. A nested call uses its own definition's profile, never its caller's. An llm call inside a box with no harness profile declared is refused, naming the two places to add one. The examples below assume one, such as { "llm": { "harness": { "write": [], "net": "open" } } }. A harness reaches its call's tools under any net tier: the fence lets it connect to that call's tool socket, and nothing else the tier refuses.

An agent in a box signs in with an API key. A box cannot reach the macOS keychain, where claude keeps its login, so claude inside a box answers Not logged in · Please run /login. Give it an API key through a policy secret on the llm definition that runs claude, a home it can write, and the model's host in egress:

policy @keys = {
  * { secrets: { claude: { from: "keychain", as: "ANTHROPIC_API_KEY" } } }
}
llm @ask(prompt, config) using { secret: "claude", harness: { home: "~/.agents/boxed-claude", egress: ["api.anthropic.com"] } } = cmd { claude -p "$prompt" }

box [
  show @ask("Name three prime numbers", {})
]

Store the key once with mlld keychain add ANTHROPIC_API_KEY (see auth), and create the home folder before the run (mkdir -p ~/.agents/boxed-claude). The home is where claude keeps its state, and it is the one place a box lets the harness write. egress opens api.anthropic.com to this harness only; the box's own commands, and the tools the model calls, still have no network. The secret reaches only the command its own definition runs, so @agent(...) using secret:claude does not pass it on to the claude that @agent starts: @agent and the harness modules cannot take a policy secret yet.

To put an llm result into the workspace, write it from the box body, or have the model write it with a tool. This stand-in harness declares its own profile, which writes nothing and needs no network:

llm @summarize(prompt, config) using { harness: { write: [], net: "none" } } = cmd { echo "result text" }
const @ws = box { provider: "vfs" } [
  let @r = @summarize("Summarize the notes")
  file "out.txt" = @r
]
show <@ws/out.txt>          >> "result text" — from the workspace

A tools collection's entries get their own MCP server. The box's tools: list names the entry, and Bash for the commands the tool and the harness run:

import { @agent } from @mlld/multi-harness

exe @double(n) = cmd { echo $(( n * 2 )) }
tools @math = { double: { mlld: @double } }
const @r = box using { tools: ["double", "Bash"] } [
  let @answer = @agent("Double 21", { tools: @math })
  => @answer
]

The function bridge serves @double from a single MCP config file, exposed via @mx.llm.config.

Box Sandbox Demo

A box runs its commands inside a fence the operating system enforces. This demo tries three things a compromised or confused agent might try, and shows each one refused.

const @r = box [
  run cmd { echo inside-box }
  let @ssh = try [ => cmd { cat ~/.ssh/config } ] catch @e => `refused: ${@e.message}`
  let @net = try [ => cmd { nc -z -w 3 1.1.1.1 80 } ] catch @e => `refused: ${@e.message}`
  let @write = try [ => cmd { touch ~/mlld-box-demo.txt } ] catch @e => `refused: ${@e.message}`
  => [@ssh, @net, @write]
]
show @r

On macOS it prints:

inside-box

[
  "refused: Command execution failed (exit 1): cat ~/.ssh/config\n  stderr: cat: /Users/you/.ssh/config: Operation not permitted",
  "refused: Command execution failed (exit 1): nc -z -w 3 1.1.1.1 80",
  "refused: Command execution failed (exit 1): touch ~/mlld-box-demo.txt\n  stderr: touch: /Users/you/mlld-box-demo.txt: Operation not permitted"
]

inside-box is the control: an ordinary command runs. The other three are refused:

  • Reading ~/.ssh/config — the box reads only its own directory and a small set of system files, so your keys and config are out of reach.
  • Opening a network connection — a box has no network unless its config asks for one (net: "loopback" or "open", see box-config). nc fails with no message of its own; outside a box the same command connects.
  • Writing to your home directory — a box cannot write to your files, and ~/mlld-box-demo.txt does not exist after the run.

A bare box [ … ] uses the kernel provider: Seatbelt on macOS, Landlock on Linux. Because the operating system enforces the fence, it holds whatever runs inside it, including a model that has been talked into trying something it should not. On a host that cannot fence, the box refuses to start rather than running unfenced.

A refusal is a failed command

The fence does not stop the script. A refused command is a command that failed, like any other, so try catches it and hands you the error as data (see try-expression). That is how the demo collects all three refusals.

Without try, mlld prints the failure on stderr (mlld: command failed (exit 1): cat ~/.ssh/config), the script carries on with the next statement, and the run still exits 0. A run that finishes did not necessarily do everything it tried: read the failures, or wrap the commands you need to check in try.

Package managers under mlld

Every command mlld runs outside a box runs inside the default fence, which lets it write only in the project and in its own sandbox folder (see box-config). Package managers keep their download cache in your home folder, which the fence does not let them write, so without help every install downloads everything again, or fails.

So each sandbox gets a private cache for every tool below. fence.caches in mlld-config.json turns that off or picks tools:

{ "fence": { "caches": ["npm", "pip"] } }

true (every tool below) is the default, also when the key or the whole file is absent; a list such as ["npm", "pip"] names the ones you want; false turns them off.

Inside the sandbox, mlld sets the tool's variable to the private cache. A value set in the environment mlld runs in, such as npm_config_cache in your shell, is replaced there. A value the program itself passes to the command (with using { env }, for instance) is kept when it names a folder the command could write anyway, such as one in the project, and replaced otherwise; either way mlld prints a box.cache.layer note saying which.

tool variable mlld sets its real cache
npm (and npx) npm_config_cache ~/.npm
pip PIP_CACHE_DIR ~/Library/Caches/pip on macOS, ~/.cache/pip on Linux
yarn 1 YARN_CACHE_FOLDER ~/Library/Caches/Yarn on macOS, ~/.cache/yarn on Linux
bun (and bunx) BUN_INSTALL_CACHE_DIR ~/.bun/install/cache
Go GOMODCACHE, GOCACHE ~/go/pkg/mod (modules)
sccache (for cargo, rustc) SCCACHE_DIR ~/Library/Caches/Mozilla.sccache on macOS, ~/.cache/sccache on Linux

mlld finds each real cache the way the tool would, from your environment (npm_config_cache, PIP_CACHE_DIR, …) and your own config file (~/.npmrc, pip.conf, ~/.yarnrc, ~/.bunfig.toml, sccache's config), without running the tool and without reading any config file in the project. A setting it cannot read without the tool, such as one that uses $HOME, leaves the private cache empty, and so does an sccache config that uses a remote cache such as Redis.

On macOS, the first command that runs one of these tools fills its private cache with a copy-on-write copy of your real one, so installs reuse what you already downloaded and can never change your real cache. A command that never runs the tool costs nothing. On Linux the private cache starts as a view of your real one (an overlay in the sandbox's own mount table), with the same effect: what you downloaded is there, and every change the command makes lands in the private cache. Where the host does not allow it, the private cache starts empty.

Go works differently: nothing of your module cache is copied. The command gets an empty private module cache, build cache and GOPATH, and mlld points GOPROXY at your real module cache first (Go's own file:// proxy), so a module you already downloaded is read from there, even with no network. GOFLAGS gains -modcacherw so the private copy can be deleted after the run. Go toolchains you have downloaded are copied in on macOS (only the newest, if together they are large), so a module that asks for a newer Go does not download it again. Go's checksum-database state (pkg/sumdb under your GOPATH) is copied in too, so a module with no go.sum can still be verified offline; mlld never turns verification off. Your saved go env -w settings for GOPROXY and GOFLAGS are kept, with the file proxy added in front and -modcacherw added. Because GOPATH is private, go install puts binaries in the private folder too (its default GOBIN), not in your ~/go/bin. Each run builds your dependencies again, because the build cache starts empty; the result is correct, just slower.

With sccache (RUSTC_WRAPPER=sccache), each sandbox already runs its own sccache server inside the fence; with this cache it also reuses your compiled results, through its copy, and never changes your real cache. cargo itself still keeps its own cache where it is (see below).

With pip, install into a virtual environment made outside mlld (python3 -m venv .venv, then .venv/bin/pip install … inside): without one, pip writes to ~/.local, which the fence refuses.

Not moved: cargo and pnpm write their cache's full path into what they build, so moving the cache would make them rebuild or refuse. They keep their real cache path, and fence.caches covers them like the other tools. On Linux the sandbox sees an overlay at that path, so they work as usual and every change lands in the private cache folder, never your real one. On macOS the real cache stays read-only: a build that has everything downloaded works, and one that needs a download fails. mlld then prints a hint naming the cache; run cargo fetch or pnpm fetch outside mlld first, then run the script again. The same holds on a Linux host that does not allow the overlay.

Not supported: uv, whose caches are too large to copy at each run (one measured at 219,000 files), and yarn 2 and later, which read packages from the cache while the project runs, so a private cache that is deleted after the run would break the project.

Commands inside a box never get these caches. An llm harness's own commands outside a box get them the same way, and inside a box they do not. No policy can turn them on.

Credentials

Use policy secrets to declare sealed credential mappings. Call sites and definitions inject them with using secret:name.

Before 2.2.0 these were spelled creds (creds @name, using creds:name) and credentials (the policy section). The old spellings refuse with an error naming the new one, and mlld migrate rewrites them (see the 2.2.0 migration guide).

Policy credentials

policy @keys = {
  * {
    secrets: {
      brave: "BRAVE_API_KEY"
    }
  }
}
exe @search(q) using secret:brave = js { /* uses process.env.BRAVE_API_KEY */ }

Short form expands to:

  • from: "keychain:mlld-box-{projectname}/BRAVE_API_KEY"
  • as: "BRAVE_API_KEY"
  • runtime resolution: keychain first, then process.env.BRAVE_API_KEY

Naming the entry is all the permission it needs. A secret named in your own policy reads its keychain entry without danger: ["@keychain"], and only that entry; danger is for keychain reads you did not name (see policy-auth).

Long forms

policy @keys = {
  * {
    secrets: {
      brave: { from: "keychain", as: "BRAVE_API_KEY" },
      custom: { from: "keychain:custom-service/custom-account", as: "BRAVE_API_KEY" },
      env_backed: { from: "env:SOME_OTHER_VAR", as: "BRAVE_API_KEY" }
    }
  }
}

from: "keychain" expands to keychain:mlld-box-{projectname}/<as>.

A from: with any other scheme (for example op://vault/item) loads, and fails when the credential is used: Unsupported auth source 'op://vault/item'.

Several credentials at once

using { secret: ["brave", "github"] } delivers each credential under its own as name. Two credentials in one list delivered under the same as name refuse, rather than one hiding the other.

Host scoping with for:

A credential sent over the network — to a remote MCP server (see mcp-import) or with @http — can be scoped to the hosts it may be sent to:

policy @keys = {
  * {
    secrets: {
      acme: { from: "env:ACME_MCP_TOKEN", as: "ACME_MCP_TOKEN", for: ["mcp.example.com"] }
    }
  }
}

for: takes a list of exact hostnames (case-insensitive — no wildcards, suffixes, or patterns). Every request carrying the credential checks the destination host against the list before anything is sent; a host outside the list fails the send with an error naming the credential and its scope, never the secret. A malformed for: (anything but a list of strings) makes the whole credential entry invalid rather than silently unscoped, and for: [] refuses every destination.

With @http, the check runs on every redirect hop as well. The credential goes to the first request and to each hop whose host is in the list, on any port; a hop to any other host is still followed, but without the credential. Once a chain has made an https request, a later http hop never carries the credential, even to a listed host, so the secret is not sent unencrypted.

for: applies to remote MCP presentation, @http, and a credential with base_url (below). For plain using secret:name environment injection into your own programs there is no host to check, and it is ignored there.

An unscoped credential (no for:) may be presented only to a destination your program wrote literally. If the server spec or the @http URL was assembled from data — a variable, a function's result, a file's contents, a tool result — the call refuses before any request leaves the process, whether or not that data is labeled untrusted. Scope the credential, or write the destination literally:

>> Sent: the URL is written at the call
const @a = @http.get("https://api.example.com/items") using { secret: "api" }

>> Refused: the URL comes from a variable, so data could pick the host
const @u = "https://api.example.com/items"
const @b = @http.get(@u) using { secret: "api" }

With an unscoped credential, @http sends the credential only to the URL's own origin: the same scheme, host and port (https://h and https://h:443 are the same). A redirect to any other origin, including another port on the same host, is followed without the credential, and an http hop after an https one never carries it.

The credential's name is written at the call too. using { secret: "api" } names it; a computed name, such as a template, is refused before any credential is looked up, so data cannot choose which secret is spent.

Minting a token from a stored key

Some services take a short-lived token, minted from a key you store, rather than the key itself (a GitHub App, a Google service account, OAuth client credentials). A secret with mint does that inside mlld, so the key never reaches the program. See Minted Secrets.

Keeping the key out of a box with base_url

A program you run with using secret:name normally holds the key: it is in the program's environment, so anything that controls the program, such as a prompt-injected agent, can read it and send it somewhere. base_url keeps the key outside. Inside a box, the program gets a stand-in value instead of the key, and mlld's egress proxy puts the real key into each request on its way to the API.

policy @keys = {
  * {
    secrets: {
      claude: {
        from: "env:ANTHROPIC_KEY",
        as: "ANTHROPIC_API_KEY",
        for: ["api.anthropic.com"],
        auth_header: "x-api-key",
        base_url: "ANTHROPIC_BASE_URL"
      }
    }
  }
}

exe @models() = cmd { curl -s -H "x-api-key: $ANTHROPIC_API_KEY" "$ANTHROPIC_BASE_URL/v1/models" }

box { net: { allow: ["api.anthropic.com"] } } [
  show @models() using secret:claude
]

The example is a sketch: any client that takes a base URL works the same way. Inside the box the program sees:

  • ANTHROPIC_API_KEY=mlld-stand-in-…, a random value made for this one command;
  • ANTHROPIC_BASE_URL=http://127.0.0.1:<port>/claude, an address on the box's egress proxy.

A tool that reads a base-URL setting, as the Anthropic and OpenAI clients do, sends its request there in plain HTTP. The proxy checks that the request carries the stand-in, replaces it with the real key, and sends the request over HTTPS to the for: host, checking that host's certificate itself. The answer comes back through the proxy, streamed as it arrives.

  • base_url names the environment variable that gets the proxy's address. It needs a for: of exactly one host, the host the key goes to. Any other shape makes the entry invalid, as a malformed for: does.
  • auth_header names the header that carries the key, as the stand-in alone (x-api-key: <stand-in>) or after Bearer. Without it the header is Authorization.
  • The box must allow the host. The proxy makes the call for the box, so a box whose net does not allow the for: host refuses the command.
  • Only a command in a box with a host list receives the secret. That means a cmd or sh block, or an llm harness, inside a box whose net is a host list (see box-config). Anywhere else the secret is refused rather than delivered: unboxed, in a box whose net is "none", "loopback" or "open", in a js, node or py block, and in a service. A credential that must also work outside a box needs a second entry without base_url.
  • @http and remote MCP servers are not affected: mlld sends those requests itself, and the key never enters a program.

What this does not cover:

  • The program can still use the key. It can send any request to the for: host through the proxy, and the request goes out with the real key. base_url stops the key being taken away, not the API being called.
  • Only keys sent in a header. A key that signs requests, an SSH key, or a database password still has to be delivered to the program.
  • A host that sends the request back. The proxy passes the host's answer to the program unchanged. A host that echoes request headers in its reply (a debugging endpoint, for example) hands the program the real key. Use base_url only with a host that does not. The proxy refuses TRACE, which exists to echo a request.
  • One request per connection. The proxy forwards one request and its body, then closes the connection. A request that asks to upgrade the connection, such as a WebSocket, is refused.
  • Other processes on a Mac. On macOS a boxed program can read the startup environment of other processes of the same user. A key with from: "env:NAME" sits in the environment of mlld's own processes, so on macOS a boxed program can read it there. A key from the keychain (from: "keychain") is in no process's environment. A box that can reach loopback (net: "loopback") can also use another running box's stand-in, which spends that key without revealing it.

What a credential can reach

A credential is only meant to reach the code you select with using secret:name. Two other routes could reach it, and mlld closes both.

Blocks you did not give the credential to cannot read it. A credential declared from: "env:NAME" is read out of mlld's own environment. Programs you run — shell, Python, Node — normally inherit that environment, so without this any block could read NAME directly and get the value without ever asking for it. mlld removes that variable from the environment it hands to your programs. A keychain credential is treated the same way: when its keychain entry is missing, mlld reads the environment variable named by as instead, so that variable is removed too. Only the using secret:name route reaches it.

Three consequences worth knowing:

  • A block that reads that variable without using secret:name sees nothing. Add the using secret:name clause to that block.
  • Only the credential's own variable is removed (the env: source, or a keychain credential's as name). Everything else in your environment — PATH, HOME, your own settings — is untouched. For that reason a secret cannot use PATH, HOME, USER, SHELL or TMPDIR as that variable: removing it would take it from every command in the run, so mlld refuses the declaration with an error.
  • The boundary of that removal is exactly the credentials mlld manages. Only the variables of credentials declared in the run are scrubbed, including those an imported module declares: importing a module that declares secret @openai = "OPENAI_API_KEY" removes OPENAI_API_KEY from every program the run starts. Any OTHER secret already in your environment — AWS_SECRET_ACCESS_KEY, an OPENAI_API_KEY exported in your shell, a .env you sourced before launching mlld — is inherited whole by every program mlld runs, with no label, no gate, and no redaction. That is what every shell does: children get the parent's environment. If your deployment keeps secrets in the environment rather than in declared credentials, they are NOT covered by this isolation — declare them (from: "env:NAME") or keep them out of the environment mlld runs in.

A credential cannot ride out in an error message. When a program fails, the failure text often quotes the value that caused it — int(os.environ["KEY"]) on a non-numeric token puts the token in the traceback. mlld removes the credential from that text before you can see it or catch it, so it does not become an ordinary string that your security rules no longer recognise.

The message itself survives; only the credential is replaced:

ls: /nonexistent/[redacted credential]: No such file or directory

Three limits are worth stating plainly:

  • Very short credentials are not removed. A four-character value occurs constantly in ordinary text, and removing it would corrupt unrelated output. Prefer credentials of reasonable length.
  • A value the program is unable to quote back exactly — split across lines, or shortened by the language runtime — may not be caught.
  • Code that deliberately prints its own credential still prints it. If a block you wrote outputs the value on success, that is your program routing bytes it was given, and the label rules — not this removal — are what govern it.

Composition

secrets entries compose with union():

const @searchCredentials = policy {
  * { secrets: { brave: "BRAVE_API_KEY" } }
}
const @appCredentials = policy {
  * { secrets: { claude: { from: "keychain", as: "ANTHROPIC_API_KEY" } } }
}

policy @app = union(@searchCredentials, @appCredentials)

Two policies that declare a credential with the same name must map it the same way. When they are combined (two policy directives, a union(), or a using { policy } fragment over the policy in force) and the mappings differ in source, as name, for hosts or header, mlld refuses to load and names both policies:

Credential 'brave' is mapped two ways: @a (main.mld:1) maps it from env:A as X, and @b (main.mld:2) maps it from env:B as X. ...

An identical mapping in both is fine. A plainly imported module's credentials stay in that module, so they never conflict with yours.

Keychain CLI

mlld keychain add BRAVE_API_KEY                 # prompts, without showing what you type
mlld keychain add BRAVE_API_KEY --value sk-...  # or pass the value directly
mlld keychain get BRAVE_API_KEY
mlld keychain rm BRAVE_API_KEY
mlld keychain import .env

Entries are stored as service=mlld-box-{projectname} / account=<name>, so
your project needs a projectname in mlld-config.json (mlld init writes
one). Without it these commands refuse rather than guess which project's
entries you mean.

add asks for the value on the terminal and does not echo it. In a script or
CI, where there is no terminal to ask, pass --value — otherwise the command
refuses instead of reading whatever the pipe hands it.

A mistyped flag is an error rather than something quietly ignored:
mlld keychain add KEY --valeu sk-... refuses and stores nothing. --help
still works.

get prints the value and nothing else, so it can be captured:
export BRAVE_API_KEY=$(mlld keychain get BRAVE_API_KEY). It exits non-zero
when there is no such entry.

import reads name=value lines from a .env file, skipping blank lines and
comments and accepting a leading export . A # inside a quoted value is part
of the value; in an unquoted value it starts a comment.

There is no mlld keychain list

macOS offers no way to list one service's entries. The only route its security
tool provides is a dump of the entire keychain — every credential you own, read
to answer a question about one project — and mlld will not make that trade on
your behalf. mlld keychain list says so and exits non-zero.

To see which credentials a project uses, read the secrets block in its
policy: that is the list of names, and mlld keychain get <name> tells you
whether each one is stored.

Auth

Minted Secrets

Many services don't take the key you store. You sign a short request with it, or send it to a token endpoint, and get back a token that lasts an hour or so. A GitHub App works this way, and so do Google service accounts and OAuth client credentials.

A secret with mint does that step inside mlld. You store the key as usual, and every use of the secret gets a token instead of the key. The stored key never becomes a value your script, a shell command or an LLM can read, and neither does a JWT that mlld only sends to a token endpoint.

What a use of the secret receives is the token itself, delivered the way any secret is. @http puts it in the request without the script holding it. A command run with using secret: holds it in its environment, as it would hold any secret (see What a credential can reach). For a recipe with no token endpoint, such as @appstoreconnect, the signed JWT is the token, so a command receives that JWT.

import { @githubapp } from @mlld/tokenmint

secret @gh = {
  from: "keychain:mlld-box-{projectname}/gh-app-key",
  as: "GH_TOKEN",
  mint: { type: @githubapp, app: 123456, installation: 7890 }
}

The secret is used like any other (see Credentials):

const @pulls = @http.get("https://api.github.com/repos/o/r/pulls") using secret:gh
run cmd { gh pr list } using secret:gh

Both receive the installation token. mlld mints it the first time the secret is used, reuses it while it is valid, and mints a new one shortly before it expires.

Recipes

mint.type names a recipe, which says how to turn the key into a token. @mlld/tokenmint ships these:

Recipe The secret holds mint parameters
@githubapp the GitHub App's private key (.pem) app (App ID or Client ID), installation
@googleserviceaccount the service account's JSON key file scope (optional, space-separated; default cloud-platform)
@appstoreconnect the App Store Connect .p8 key key_id, issuer
@azure a Microsoft Entra ID app's client secret tenant, client_id, scope (optional; default Microsoft Graph)
@oauthclient any OAuth 2.0 client secret token_url, client_id, scope and audience (optional)

A missing or misspelled parameter is refused where the secret is declared, not at first use.

A key kept in an environment variable often has its line breaks written as \n. mlld reads those as line breaks.

Where the key may go

  • Only to the recipe's token endpoint, over https. A redirect to another origin is refused, so the endpoint can't forward what it was sent.
  • Only to an endpoint written in mlld, or one the secret names. A secret without for: can mint only through the endpoints of @githubapp, @googleserviceaccount and @azure, whose hosts are fixed. Any other endpoint, such as your own recipe's or an @oauthclient token_url, must be listed in the secret's for: (see host scoping). A token_url can be built from data, and this keeps data from choosing where the secret goes.
  • Inside the secret's for: hosts. If the secret has for:, the token endpoint must be one of those hosts. For a GitHub App, for: ["api.github.com"] covers both the exchange and the API calls. For Google, add oauth2.googleapis.com beside the API hosts you call.
  • Through policy. The exchange is checked as a network write that spends the secret, just like @http spending a credential at its host.
  • Not from untrusted data. A recipe decides where the key's proof is sent, so a mint built from untrusted data, such as an @http response, is refused.

Errors name the secret and the service's reason. They never quote the key, the signed JWT or the token.

Writing a recipe

A recipe is a plain object, so you can write your own for a service the module doesn't cover. A secret minting with it needs for: naming its endpoint's host.

const @myservice = {
  tokenmint: 1,
  name: "myservice",
  params: ["client_id"],
  defaults: { scope: "read" },
  exchange: {
    url: "https://auth.example.com/oauth/token",
    form: {
      grant_type: "client_credentials",
      client_id: "{client_id}",
      client_secret: "{secret}",
      scope: "{scope}"
    }
  },
  token: "access_token",
  expires_in: "expires_in"
}
Field Meaning
tokenmint always 1
name used in error messages
params parameters a mint object must give
defaults optional parameters, with the value used when one is not given
key "text" (the default) or "json" for a JSON key file
jwt sign a JWT: alg (RS256 or ES256), key (default {secret}), header, claims, lifetime and backdate in seconds. mlld sets iat and exp.
exchange send a request: url, method (POST or GET), headers, and a form or json body
token the field of the answer holding the token
expires_at / expires_in the field giving its expiry, as a time or a number of seconds
ttl seconds to keep a token when the service gives no expiry (default 300)

Without an exchange, the signed JWT is the token.

Placeholders in a recipe's strings:

Placeholder Value Allowed in
{name} a mint parameter everywhere except the signing key
{key.field} a field of a JSON key file JWT header, claims and signing key; exchange headers and body
{secret} the stored value signing key; exchange headers and body
{jwt} the signed JWT exchange headers and body

URLs take parameters only, so no key material ends up in a URL. Write {{ and }} for literal braces.

Tool Docs

@fyi.tools() renders the tool metadata mlld already enforces at runtime into prompt-ready text or JSON. Use it when you are assembling a system prompt by hand and need the LLM to see the same tool surface — names, args, record-derived fact/payload sections, input-policy sections, classification, and output fields — that the runtime will validate against.

When a tool returns => record, @fyi.tools() renders its visible output fields through the same read-projection path used at runtime. There is no separate audience switch. The active read selection (using { read: .role:x }, box config, or a matching .role:* label on an llm executable) is the shaping mechanism. Actor identity and read shaping stay separate: the exe's .role:* label determines authorization identity, while read only chooses the projection.

Basic usage

record @send_email_inputs [
  recipient: string [ kind "email" ]
  trusted subject: string
  body: string
  validate "strict"
]

exe .op:execute:w @sendEmail(recipient, subject, body) = cmd {
  email-cli send --to "$recipient" --subject "$subject" --body "$body"
}

tools @writeTools = {
  send_email: {
    call: @sendEmail,
    inputs: @send_email_inputs,
    labels: [.op:execute:w, .risk:exfil:send, .op:comm:w]
  }
}

const @docs = @fyi.tools(@writeTools)
show @docs

Output:

Write tools (require authorization):

#### send_email
Routing: execute (write)
Risk: risk:exfil (send)
Domain: communication (write)
Facts:
- `recipient` (string)
Trusted payload:
- `subject` (string)
Payload:
- `body` (string)

Record-backed tools render fact and payload sections from the input record: fields with a kind are facts, fields marked trusted or untrusted are listed as trusted or untrusted payload, and the rest are listed as plain payload. If the record also declares exact, update, allowlist, or blocklist, those sections are rendered too. Optional fields (name: string?) are listed in an Optional section. Tools are classified read vs write from the active policy (see "Classification" below).

Args render from the bound exe, even without an inputs: record

A catalog entry does not need an inputs: record to expose its arguments. When an
entry has no inputs:, @fyi.tools() still renders an Args: section from the
bound executable's parameter signature, and format: "json" lists those same
parameters under params. The inputs: record adds the record-derived
Facts: and payload sections on top of that base
Args: list — it does not replace it.

exe @search_contacts(query) = cmd { contacts-cli search "$query" }

tools @readTools = {
  search_contacts: { call: @search_contacts }
}

const @docs = @fyi.tools(@readTools)
#### search_contacts
Args:
- `query` (string)

Output fields from a catalog returns: or an exe => record

A catalog entry's returns: @record declares the output record directly, so a
pure pass-through tool needs no wrapper exe to coerce its result. The output
record can come from either source:

  • the catalog entry's returns: @record, or
  • the bound exe's own => record form.

When either is present, @fyi.tools() adds a Returns: section that describes the fields visible under the current read:

record @contact [
  email: string [ kind "email" ]
  name: string
  notes: string
  .role:planner { read: [name, { value: email }] }
  .role:worker { read: [{ mask: email }, name, notes] }
]

exe .op:tool:r @searchContacts(query) = cmd {
  contacts-cli search "$query" --format json
} => contact

Under using { read: .role:planner }, the rendered docs include:

#### search_contacts
Args:
- `query` (string)
Returns:
- `email` (value + handle, fact)
- `name` (value, data)

Under using { read: .role:worker }, the same tool renders:

Returns:
- `email` (preview + handle, fact)
- `name` (value, data)
- `notes` (value, data)

Injected authorization notes

For llm calls, mlld injects two distinct tool-note blocks:

  • <fyi_tools> for tools the LLM can call directly
  • <fyi_authorizations> for tools the LLM can authorize workers to use but cannot call directly

Both blocks use the same tool-metadata and read-projection path. The difference is the source set:

  • <fyi_tools> is shaped from the callable tools: surface
  • <fyi_authorizations> is shaped from the tools the policy lets the caller's immutable exe actor authorize, .role:x { can_authorize: [...] }, for record-backed and plain tools alike

Read overrides still shape visible output fields in both blocks, but they do not change which actor's authorization metadata applies.

Custom fyi blocks

Use fyi = { ... } to define default agent context blocks for later llm calls, or fyi @name = { ... } to define a reusable named set:

fyi @plannerBrief = {
  summary: "Prefer approved transfer workflows.",
  push: [tools, authorizations, summary],
  actors: {
    .role:planner: {
      planning_note: "Do not dispatch directly; authorize the worker.",
      push: [planning_note, {authorizations:false}]
    }
  }
}

show @agent("Plan this", { tools: @writeTools, fyi: @plannerBrief })

(@agent here stands for any llm executable.)

push lists the fyi blocks to inject. Runtime block names are reserved: tools, authorizations, records, actors, state, files, known, and drafts. User-defined fields cannot use those names, nor shelf, which push refuses with a message pointing to state. Suppress a block with {name:false}. files renders as <fyi_files> and lists only project-relative files that pass the active filesystem read policy; the same projected view is available through the pull tool as fyi("files", { path: "/", recursive: true }) or explicit @fyi.files(...).

When fyi is omitted from the call config, mlld uses the unnamed default if one exists; otherwise it injects runtime musts only (tools and authorizations). fyi: @name selects a named definition. fyi: false disables all fyi injection for that call.

Actor sections are selected by the active read/authorization actor, such as .role:planner. Pushed custom fields and runtime blocks are rendered through that active actor; fields from other actor sections are omitted entirely.

A record inside a custom field's value is shown through the reading role's read rules, as a record is anywhere it reaches an LLM (see records-basics). A value already taken out of a record, such as { e: @contact.email }, is plain data and is passed as written. Put the record itself in the field when its rules should decide what each role sees.

JSON output

For programmatic consumers (custom renderers, validators, schema generation), pass format: "json":

const @docs = @fyi.tools(@writeTools, { format: "json", includeOperationLabels: true })

The JSON form is richer than the text form. Per-tool entries include:

  • name, kind ("write" or "read"), description, instructions
  • inputRecord — source record name when the tool uses inputs: @record
  • params — full parameter list
  • output — visible output fields under the current read, when the tool returns => record
  • controlArgs, sourceArgs, dataArgs — effective security partitions derived from the surfaced tool definition; record-backed tools also expose the record-native factArgs, trustedDataArgs, and untrustedDataArgs
  • factArgs, trustedDataArgs, untrustedDataArgs — record-derived input partitions when available
  • inputPolicy — record-derived exact, update, allowlist, and blocklist sections when present
  • multiControlArgCorrelation: true when a record-backed tool derives two or more fact fields (record correlation is on by default at two or more fact fields; write correlate false in the record to override)
  • correlateControlArgs: true when the tool's input record correlates its fact fields (renders the (same source) suffix on the [CONTROL: …] annotation)
  • discoveryCall — the fyi("known", "tool_name") MCP pull-tool call to surface available handles, when applicable
  • operationLabels — populated when includeOperationLabels: true

Top-level JSON also includes helpers.fyi_known and a denied list (tools blocked by the policy's authorizations.deny).

No-argument form

If the current scope already has tools, @fyi.tools() infers them:

record @send_email_inputs [
  recipient: string [ kind "email" ]
  subject: string
  body: string?
  validate "strict"
]

exe .op:execute:w @sendEmail(recipient, subject, body) = "sent"
tools @toolList = {
  send_email: {
    call: @sendEmail,
    inputs: @send_email_inputs,
    labels: [.op:execute:w, .risk:exfil:send]
  }
}

llm @callModel(prompt, config) using { read: .role:planner } = @fyi.tools()

const @docs = @callModel("List tools", { tools: @toolList })

The no-arg form reads scoped tool collections, scoped executable arrays, or active LLM tool metadata.

Classification

A tool renders under "Write tools (require authorization)" if any of:

  1. It has effective control args: the input record's fields with a kind, or, for an exe with no input record and a tool-write label (.op:tool:w), every parameter it takes, since the authorization verdict constrains all of them
  2. Its labels fall in any risk class the active policy defines with includes
  3. It appears in the policy's authorizations.deny

Otherwise it renders under "Read tools". Classification is policy-relative — the same exe can be a write tool under one policy and a freely callable tool under a more permissive policy. The classifier reads the active policy's includes classes; there is no hardcoded label list inside @fyi.tools.

A consequence: when you add a custom write label like .op:iot:trigger and put it in a risk class (.risk:destructive { includes: [.op:iot:trigger] }), @fyi.tools picks it up automatically.

Explicit vs injected docs

@fyi.tools(), the auto-injected <fyi_tools> block, and the auto-injected <fyi_authorizations> block share the same base rendering and classification path. The differences:

  • @fyi.tools() is the explicit form you call from your own prompt template. Use it when you're building system prompts by hand.
  • <fyi_tools> is the injected form mlld appends automatically to the system message of any llm call that surfaces callable tools, for example @agent(...).
  • <fyi_authorizations> is the injected form mlld appends automatically when the caller actor has any tools it can authorize: the tools listed for that actor in the policy's .role:x { can_authorize: [...] }.

All three use the same classification, label summaries, record shaping, and output-field shaping for the same tools under the same policy. Explicit @fyi.tools() includes freeform Description: and Instructions: lines and can opt into format: "json". Injected <fyi_tools> includes each tool's Description: and Instructions: when present. You can disable the injected block for an LLM call with toolNotes: false in the call config; when omitted, toolNotes defaults to true if the call passes tools and false otherwise. When both injected blocks are present, the order is <fyi_tools>, then <fyi_authorizations>.

A <fyi_state> block showing a box's state scope is not available in mlld 2.2.0: pushing state is accepted and renders nothing. Code in the box reads the scope through @fyi.state (see box-config).

Options

Option Default What it does
format "text" "text" for prompt-ready markdown, "json" for programmatic use
includeOperationLabels false Include operationLabels in JSON entries (json mode only)

Labels and policy

Every @fyi result carries a runtime provenance label naming the member it came from — .src:fyi:tools, .src:fyi:known, .src:fyi:actors, and so on (D284). The label is runtime-owned: a custom taxonomy cannot re-role it. A policy can deny the enforcement metadata reaching a sink by name:

policy @p = {
  .src:fyi:actors { deny: [.risk:exfil] }
}
exe .risk:exfil @send(data) = cmd { echo "$data" }
const @actors = @fyi.actors()
show @send(@actors)

See also

  • pattern-planner — the planner-worker authorization pattern uses @fyi.tools for explicit prompt assembly
  • policy-authorizations — the ambient authorization law (can_authorize, authorizations.deny)
  • security-grants — minting a per-step grant for a tool call
  • facts-and-handles — how fact proof, handles, and surfaced tool args flow through tool dispatch

.sss Files

A .sss file (security settings sheet) gathers a project's security settings in one place, so they can be written together and imported wherever you need them. Think of it as the stylesheet for your labels: declare the classes once, next to the guards and the policy that act on them, and import the bundle.

What goes in a .sss file: declarations only.

  • class and id declarations for the labels you use (see labels-classes), and the field and preset declarations records use
  • record declarations
  • guard declarations (guard! only in a .priv.sss)
  • policy @name = { … } declarations
  • const values: data, references and policy { … } values
  • import (every form) and export
  • comments

Anything else is refused when the file is run or imported, before any of it runs, with a message naming the statement and the file kind: exe, llm, run, show, output, append, hook, box, needs, if, for, match and the rest. A const value may not run anything either: const @x = run cmd { … }, const @y = @f() or a pipeline in a .sss is refused. Put executables and the code that runs in a .mld file and import what it produces. A pattern block written on its own, outside policy @name = { … }, is refused too. mlld validate reports every one of these.

>> security.sss
class .pii = { kind: "data", effect: "restrict", description: "personal data" }

guard @noPiiShell = match [
  * => deny "no pii in the shell"
]

policy @piiRules = {
  .pii { deny: [.net:w] }
  .pii+.op:cmd { before: @noPiiShell }
}
export { @piiRules }

Keeping the label, its rules and its guards together means mlld validate can check the whole bundle at once: that every label a rule names is declared, and that every guard is bound by a rule or exported.

Importing a .sss file:

import policy @piiRules from "./security.sss"

const .pii @email = "ada@example.com"
exe @echo(v) = cmd { echo "$v" }
exe @tryEcho(v) = match [
  denied => `refused: ${@mx.denial.reason}`
  * => @echo(@v)
]
show @tryEcho(@email)
show @tryEcho("plain text")

Output:

refused: no pii in the shell
plain text

The import puts the policy in force and makes the .pii class visible to the whole program. Any import of the file does both (import "./security.sss" as @sec, or import { … } from), because a module's policy crosses the import edge.

.priv.sss: privileged settings

A .priv.sss file holds the privileged half of a project's security settings: everything that can weaken the model. That is:

  • privileged guards (guard!) and the label-removal actions only they may use (trusted!, clear!, !.label, remove_labels)
  • allow! exceptions to a deny declared in another file, when the .priv.sss is imported with import policy (below). An allow! in an ordinary file can only lift a deny from that same file; see "Deny wins" in policy-label-flow.
>> exceptions.priv.sss
policy @echoAllowed = {
  .untrusted { allow!: [.op:cmd:echo] }
}
export { @echoAllowed }

Bring it in with import policy:

import policy @echoAllowed from "./exceptions.priv.sss"

With this import, untrusted data may reach echo even when the .untrusted { deny: [.op:cmd] } rule came from a team policy in another file; every other command stays denied. Imported any other way (import { @echoAllowed } from "./exceptions.priv.sss" or import "./exceptions.priv.sss"), the file's allow! does not lift a deny from another file. A locked deny always wins: nothing lifts it.

Concentrating every declassification path in one file makes it a single audit surface. "What can weaken this policy?" is answered by reading one file, and edit permission on that file stands in for permission to declassify.

The boundary is enforced: mlld refuses a guard! declared anywhere except a .priv.sss file, at runtime, in mlld validate, and as an editor diagnostic. Sources with no file at all (mlld -e, stdin) refuse guard! outright, and .priv.sss files are local-only: they cannot be imported from URLs or the registry. Declare privileged guards in a .priv.sss, export them, and import them where needed. Binding a guard! to a rule is itself privileged, so the policy block that binds one also lives in a .priv.sss.

Enforcement covers where privilege may be declared, not file integrity: mlld does not verify that a .priv.sss file is unchanged or signed, so an actor who can write the file holds the declassify capability. Guard that file with filesystem permissions and review.

Why a dedicated file type:

Labels are only useful when a policy acts on them, and a policy is only meaningful against declared labels. A .sss file keeps the two together, so a project's security posture is one importable unit rather than declarations in one place and rules in another. See policy-composition for combining several policy sources, and labels-classes for class declarations.