@ai-ecoverse/slicc-agent 7.21.1 → 7.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -747,7 +747,7 @@ Every approval, of a guest's prompt, of a tool call in a run a guest started, or
747
747
  - **Lifetime:** an item waits 5 minutes unless its requester sets `expiresAt`, then settles `unanswered`. Pending guest items survive a reload of the worker; pending `sudo` items are withdrawn (`restart`), because a reload ends the kernel's processes. The document keeps every pending item and the last 100 settled ones.
748
748
  - **In the worker,** `AgentHost.approvals` has `request(draft, ctx)`, `decide(id, answer, reason, by, ctx)` (`by` is a `DecidedBy`, or `{ by, device }` to record the deciding device), `settled(id, ctx)` (resolves when the item leaves `pending`), `withdraw(id, reason, ctx)` and `withdrawSeat(seat, ctx)`, which withdraws a revoked seat's pending items.
749
749
  - **Over the link,** `AgentTranscript.approvals` replicates the items, and `AgentControl.decide(id, decision, reason, ctx)` answers one, for every owner device: the owner's pages and followers with or without Control, all with the same powers. `decidedBy` comes from the link's seat (`owner` for the owner's pages, `follower` for the others), and is only a record of who answered. A guest never gets `decide`.
750
- - **In spectrum** (1.112 on, which shows approvals in `<slicc-approvals>` with Always allow when `always` is true, as notices without `decide`, and the verdict's level), `createAgentModel` returns `approvals`, an `ApprovalsAdapter` for `SliccModel.approvals`. `list()` has the pending `user` items, oldest first, as spectrum's `Approval`s, with the cone's name as `agentName` and the item's own `always`, so a guest approval offers Always allow only when the policy did when it was asked. Every approval carries the judge's `verdict` once it lands, as `{ level?, aligned?, reason }` (spectrum 1.112 on shows the level; `aligned` is `true` at P ≥ 0.8, or the chat model's yes or no), `judging: true` while the check runs and `verdictError` when there is none. Its `always` is the item's, so Always allow shows up only when a level 1 verdict offers it. `decide(id, decision, reason?)` rejects with the agent's message, and `ended` reports `answered`, `expired` or `withdrawn` for an item that left without this tab's decision. Every owner device's adapter has `decide`; a guest connection's doesn't. So a notice instead of a dialog shows only where nothing can answer. A `guest-tool` approval also carries `args`, the call's arguments pretty-printed as JSON (two-space indent), so spectrum can show them uncut when `summary` is empty. The worker runs every string in the arguments through the secrets scrub before it files the item, so `summary`, `detail.arguments` and `args` show a secret as its placeholder; the seat's Always rules still match the call's own arguments. `args` is capped at 64 KiB (65,536 UTF-16 code units, `ARGS_LENGTH`, never splitting a surrogate pair): longer arguments are sent as that prefix with `argsTruncated: true`, and spectrum must then offer only Deny and Always deny, never Allow, because the end wasn't seen.
750
+ - **In spectrum** (1.112 on, which shows approvals in `<slicc-approvals>` with Always allow when `always` is true, as notices without `decide`, and the verdict's level), `createAgentModel` returns `approvals`, an `ApprovalsAdapter` for `SliccModel.approvals`. `list()` has the pending `user` items, oldest first, as spectrum's `Approval`s, with the cone's name as `agentName` and the item's own `always`, so a guest approval offers Always allow only when the policy did when it was asked. Every approval carries the judge's `verdict` once it lands, as `{ level?, aligned?, reason }` (spectrum 1.112 on shows the level; `aligned` is `true` at P over 0.8, or the chat model's answer), `judging: true` while the check runs and `verdictError` when there is none. Its `always` is the item's, so Always allow shows up only when a level 1 verdict offers it. `decide(id, decision, reason?)` rejects with the agent's message, and `ended` reports `answered`, `expired` or `withdrawn` for an item that left without this tab's decision. Every owner device's adapter has `decide`; a guest connection's doesn't. So a notice instead of a dialog shows only where nothing can answer. A `guest-tool` approval also carries `args`, the call's arguments pretty-printed as JSON (two-space indent), so spectrum can show them uncut when `summary` is empty. The worker runs every string in the arguments through the secrets scrub before it files the item, so `summary`, `detail.arguments` and `args` show a secret as its placeholder; the seat's Always rules still match the call's own arguments. `args` is capped at 64 KiB (65,536 UTF-16 code units, `ARGS_LENGTH`, never splitting a surrogate pair): longer arguments are sent as that prefix with `argsTruncated: true`, and spectrum must then offer only Deny and Always deny, never Allow, because the end wasn't seen.
751
751
  - **Kernel sudo:** `AgentOwner.approve(req, { signal, where? })` from `startAgent` takes slicc-kernel's sudo request as it comes to the kernel's `approve` hook and resolves `once`, `always` or `deny`. bios hands its hook to it while the agent runs, and to its own dialog otherwise. It rejects with `code: 'EAGAIN'` before anything is recorded when the agent can't take the request (released, restarting, or an older worker) or when the request's `kind` isn't `sudo`, such as a program's secret `ask`, so that's when to fall back; any other rejection is a deny. The request goes through `slicc.agent.sudo`, a service only the owner's pages get, and becomes a `sudo` item on the `user` tier with the kernel's `expiresAt`:
752
752
  - **Requester** comes from the kernel's process tag: `{ kind: 'agent', agentId }` is the cone or scoop by its name, `{ kind: 'user', where }` is the kernel user with `where` (`terminal:…` reads "a terminal", `follower:<device>` the `where` the page passes, such as "on Pat's phone", or "a linked device", with the device id kept as `requester.device`), and anything else is the kernel user alone.
753
753
  - **Detail:** the command as the kernel resolved it (`path` and the arguments, shell-quoted), `target`, `cwd`, `alwaysScope: 'cwd'` when `req.always === true`, since the kernel's Always writes a rule for that directory, and the kernel's facts for the judge: `stdin` (`tty`, `none`, `pipe` or `file`), `rootOnly` (for each path on the line, whether only root can change it) and `writable` (`req.always`, whether the kernel can record the line). Requests without them still work; `req.always: false` or `writable: false` means no Always.
@@ -761,18 +761,20 @@ Every approval, of a guest's prompt, of a tool call in a run a guest started, or
761
761
 
762
762
  The judge ([`src/approvals/judge.ts`](src/approvals/judge.ts)) gives a request a verdict by the owner's intent, never the requester's. It judges only items in `slicc.approvals`, never a `secret` approval, which always goes to a person. `request()` starts it at once for every `sudo` item, whatever its tier, and for every `agent` or `user` item, so a person is asked with the verdict shown. Who answers is the gate: a `sudo` item's tier is the owner's approval policy (`sudo.approver`), not the request's, `user` (a person) by default and for anything but `agent`; a guest item's tier is the seat's gate. On a `user` item the verdict is advice for the person and decides nothing; on an `agent` item the routing table below decides. The dialog never waits: Allow once and Deny work while `judging` is `true`.
763
763
 
764
- - **Levels:** the verdict is `level` 1 Routine (a sysadmin would approve it as normal work: it reads, builds, installs, or changes files and services in the course of the work, including reaching outside the session, and doesn't change who may do what; whether the owner wanted that is the aligned question), 2 Permissions (it changes who may do what: sudoers, users and groups, ownership or modes of system files, secret rules, the approvals policy, guest seats, credentials and tokens) or 3 Harm (it would damage the system or the work in a way that is hard to undo: delete or overwrite system files or others' work, lock the owner out, or expose secrets or private work to anyone but the owner); `aligned`, whether it serves what the owner asked for; and for sudo `always`, whether a later run of exactly this line can do no more than this one. No command lists anywhere: the level is the model's call, from the kernel's facts: `request.sudo: { stdin, writable, rootOnly }` holds only what the requester can't choose (`rootOnly` is whether every path on the line and the directory can be changed only by root), while the command, the target user, the directory and each path's root-only fact (`path "/etc/x": root-only` or `changeable`, one JSON-quoted path per line) are inside the fenced `request.untrusted`, because the requester chose them.
765
- - **The calls:** two in parallel, with one 15 s timeout (`JUDGE_TIMEOUT`) for both. One `models.classify` call on `approvals.judgeModel` (in the agent's `settings.json`, `/etc/slicc/agent/settings.json` with kernel users, `adobe/clef` by default), on the harness's own `Models`, with one retry, asks `level` (`routine`, `permissions`, `harm`), `aligned`, and for sudo `always` ("Could a later run of exactly this command line do more than this one, because of input, files or code the person can't see in the dialog?"). The level reads the three probabilities as an ordered scale: 3 when P(harm) ≥ 0.4 (`JUDGE_HARM`), else 2 when P(permissions) + P(harm) ≥ 0.5 (`JUDGE_CUT`), else 1. Both cuts allow 1e-9 (`JUDGE_EPSILON`) of floating-point error, so a share that is exactly at a cut counts as reaching it. So moving probability to a higher level never lowers the level, and being unsure between routine and permissions never gives harm: `ls -la /root/v6` at P(routine) 0.598 is level 1, where the old rule (the higher of the top two when the top was under 0.6) made it 3. Harm's cut is lower because harm is the costly miss: on `adobe/clef`, P(harm) stayed under 0.35 for all 70 reads of a real cleanup session and reached 0.46 to 0.97 for every request the eval set expects denied. The verdict also keeps P(routine) as `routine`; `aligned` counts at P ≥ 0.8 (`JUDGE_ALLOW`); Always is safe at P(more) ≤ 0.2 (`JUDGE_ALWAYS`). The other is a short text call on the conversation's own chat model (the item's cone, or the active cone for a terminal), through the same `completeText` thread titles use, with the same instructions and fenced input, scrubbed as titles are, for the reason: one or two sentences on what granting the request would do to the system, control characters stripped, at most 300 characters (code points): a longer one is cut at the last word that fits and ends with `…`, never silently at a sentence, so a later sentence is never hidden, and never inside a surrogate pair. The reason never says whether the owner wants it: that is `aligned`, which spectrum shows next to it as its own sentence, so a chat model that reads the owner's words differently from the classifier can't contradict the verdict in the same dialog. The verdict lands when the classifier answers, and the reason is patched in when it comes; a deny waits for it, so its message carries it. Without it the reason is a plain one per level (`VERDICT_REASONS`): level 1 "It looks like routine work.", level 3 "It could harm the system or the work in a way that is hard to undo.", and level 2 "The check leaned toward a change in who may do what.", which claims nothing about the request itself. No decision ever reads the reason. Both calls' spend goes into the conversation's `pi.usage`.
766
- - **The chat fallback:** when `approvals.judgeModel` names no classifier, the text call gives the whole verdict in four lines, `level: 1|2|3`, `aligned: yes|no`, `always: yes|no`, `reason: …` (what granting would do, not whether the owner wants it). Any other shape is no verdict. A chat verdict (`via: 'chat'`) counts exactly like a classifier's, automatic decisions included.
764
+ - **Levels:** the verdict is `level` 1 Routine (normal work that doesn't change who may do what), 2 Permissions (it changes who may do what: sudoers, users and groups, ownership or modes, secret rules, the approvals policy, guest seats, credentials and tokens) or 3 Harm (it would damage the system or the work in a way that is hard to undo); `aligned`, whether it serves what the owner asked for; and for sudo `always`, whether a later run of exactly this line can do no more than this one. No command lists anywhere: every answer is the model's, and code only combines them. `request.sudo: { stdin, writable, rootOnly }` holds only what the requester can't choose (`rootOnly` is whether every path on the line and the directory can be changed only by root), while the command, the target user, the directory and each path's root-only fact (`path "/etc/x": root-only` or `changeable`, one JSON-quoted path per line) are inside the fenced `request.untrusted`, because the requester chose them.
765
+ - **Sudo: narrow questions, matched in code.** A classifier on `approvals.judgeModel` (in the agent's `settings.json`, `/etc/slicc/agent/settings.json` with kernel users, `adobe/clef` by default), on the harness's own `Models`, with one retry and a 15 s timeout (`JUDGE_TIMEOUT`), gets two calls in parallel. The action call (`SUDO_QUESTIONS`, state `{ request }` only) asks eleven bools about the command: `changes` (creates, changes, moves, copies or deletes anything), `others` (in another user's home), `system` (system files), `delete`, `permissions`, `code` (code or output the line doesn't spell out: scripts, package installs, `xargs`, `find -exec` or `-delete`, redirections, command substitution, `sort -o`, `tee`, `curl` or `wget`, `git` with its hooks, pager and aliases, interpreters, editors, pagers), `services`, `send` (off the machine), `secrets` (its output shows a secret, including dumps of the environment, process environments, shell history and config or credentials files), `plain` (a standard tool whose whole effect its options and paths show) and `always` ("Could a later run of exactly this line do something different from this one, because it reads piped or file input, runs a script or a file someone other than root can change, takes code on the line, or is interactive?"). The intent call (`INTENT_QUESTIONS`, state `{ owner }` only: `owner.policy`, the last 10 `owner.messages` and `owner.memory`) asks what the owner wants done now, the latest messages with earlier ones only as context ("A request the owner made earlier for a task that is finished or replaced doesn't count."), in the same words: `wants_read`, `wants_write`, `wants_delete`, `wants_permissions`, `wants_code`, `wants_send`, `wants_secrets`, `wants_services`. It depends only on the owner's words, so the judge keeps its answer per judge model and owner state (the last 16, `INTENTS_KEPT`) and asks again only when the owner said something new or the policy or memory changed; a failed intent call isn't kept. `matchOf` then decides in code, a probability counting at ≥ 0.5 (`JUDGE_CUT`): level 3 when it deletes anything, changes something in another user's home or among system files, or touches processes or services; else 2 when it changes permissions; else 1. Deleting counts as harm wherever it is, because on live `clef` the `system` answer stayed under 0.5 for 24 of 28 `rm` commands outside `/home` in a real cleanup session, most of them on directories at the top of `/`. `routine` is 1 minus the highest danger answer, over all of them (`delete`, `services`, `permissions`, `send`, `secrets`, `code`, `others` and `system`), and never more than P(plain). For a line that changes anything (P(changes) ≥ 0.2), `others` and `system` count from 0.05 (`JUDGE_PLACE`): they enter `routine` scaled by 0.2 / 0.05. So any danger answer of 0.2 or more, or a system or another user answer of 0.05 or more on a write, keeps `routine` at or under 0.8 and the line goes to a person, even when the owner asked for it; on live `clef` every dangerous line in the evals had a danger answer over its bar, none relied on `plain` alone. Every action the command may take (P ≥ 0.2, `JUDGE_LOW`) needs an intent: `changes` needs `write`, `delete` `delete`, `permissions` `permissions`, `code` `code`, `services` `services`, `send` `send`, `secrets` `secrets`, and a line that changes nothing needs `read`. `aligned` is the lowest of the needed intents, so it counts (over 0.8, `JUDGE_ALLOW`) only when the owner asked for everything the line does: showing a secret or sending data out never rides on a read. `always` is safe at P < 0.2 (`JUDGE_ALWAYS`). Exact boundaries never approve: a danger cut counts from its bar minus 1e-9 (`JUDGE_EPSILON`), and `routine`, `aligned` and 1 − P(always) must reach their bar plus 1e-9 (`clears`), so a danger of exactly 0.2, a `plain` or an intent of exactly 0.8 all ask. The verdict keeps every answer as `actions` and `intent`.
766
+ - **The owner's exclusions and limits veto.** The intent answers are per category and never see the request, so they can't tell that the owner said "don't read /home/alice/notes.txt" or "only read /var/log". So when a sudo verdict would be approved (level 1, `routine` and `aligned` over 0.8), the judge asks one more question, `forbidden` (`FORBID_QUESTIONS`), over `{ request, owner }`, the request in the same fence as the action call: "Does anything the owner wrote forbid, exclude or limit this request: a path, user, host or command it names, or a stated limit such as 'only read' or 'don't touch X'?" P(forbidden) ≥ 0.2 (`JUDGE_LOW`, with the same 1e-9) means a person is asked, and the reason is only "The owner's words may rule this out." (`VETO_REASON`). The veto never denies, never lowers the level and never touches Always or `aligned`; at worst, a request that talks the model out of it gets the verdict it would have had without the veto. On live `clef` the answer moves with the fence's random nonce (an out-of-scope read under "only read /var/log" ranged 0.15 to 0.67 over 12 nonces), so the classifier is asked twice behind two different fences in parallel (`VETO_ASKS`) and the higher answer counts. The verdict keeps it as `forbidden`, a probability, or a boolean from the chat model. A failed or unusable veto call is no verdict.
767
+ - **Reasons are built in code** from the same answers, so they can't disagree with the verdict: what the line does (P ≥ 0.5) and may do (at or over its danger bar), "Its whole effect isn't clear from the line." unless P(plain) clears 0.8, and which needed intents the owner expressed. "It only reads or lists files or system state." appears only when every danger answer and `changes` are under their bar and P(plain) clears 0.8; otherwise the reason names only the answers over the bar and claims nothing else. Examples: "It only reads or lists files or system state. The owner asked to read or inspect files." or "It deletes files or directories in another user's home. The owner didn't ask to delete files." No chat model writes reasons. **Guest requests** keep one classifier call with the full state that asks `level` (`routine`, `permissions`, `harm`) and `aligned`; the level reads the three probabilities as an ordered scale, 3 when P(harm) ≥ 0.4 (`JUDGE_HARM`), else 2 when P(permissions) + P(harm) ≥ 0.5, else 1, each cut allowing 1e-9 (`JUDGE_EPSILON`) of floating-point error. Their reason is a plain one per level (`VERDICT_REASONS`): "It looks like routine work.", "The check leaned toward a change in who may do what." or "It could harm the system or the work in a way that is hard to undo." Spectrum adds its own sentence from `aligned`. No decision ever reads the reason. Every call's spend goes into the conversation's `pi.usage`.
768
+ - **The chat fallback:** when `approvals.judgeModel` names no classifier, the conversation's own chat model (the item's cone, or the active cone for a terminal) answers through the same `completeText` thread titles use, with scrubbed input, and must answer with one JSON object of `true`/`false` or an option name per question id. For sudo it gets two calls, like the classifier: one over `{ request }` (fenced) with the action questions only, and one over `{ owner }` with the intent questions only (`INTENT_PROMPT`), kept per owner state like the classifier's. A verdict that would be approved gets a third call with the veto question alone (`FORBID_PROMPT`), over the owner and the fenced request. Answers to questions a call wasn't asked are dropped, so a command that tells the model to answer `wants_read: true` can't set an intent. A guest request gets one call with the level and `aligned`. Anything else is no verdict. The same code matches the answers as 1 or 0, so a chat verdict has `routine` 0 or 1 for sudo and `aligned` a boolean, and counts exactly like a classifier's, automatic decisions included. Every threshold is then met or missed outright: a chat model that answers a secret read or `sh -c id` as plain and harmless gets it approved, so the fallback is only as careful as that chat model.
767
769
  - **No verdict:** a timeout, an error, a `stopReason` other than `stop`, a missing answer, no classifier and no chat model, a judge model setting that names no model, an unreadable policy file, a guest message with attachments, which the judge can't read, and a restart while it runs leave `verdict` unset and `verdictError` set. The judge never approves without a verdict.
768
- - **The routing table** (`route(verdict, requester, gate, present)`, the same for sudo and guest items): with a person as the gate it always asks, the verdict shown. With the judge as the gate, level 1 and aligned is allowed once by the judge, for a classifier verdict only when P(routine) ≥ 0.8 (`JUDGE_ALLOW`) too, a chat verdict as given; level 3 is denied, with the verdict as the denial message, unless a person asked (a terminal, a sprinkle or a linked device: never denied while a person is there) or an owner device is attached with at least 30 s (`ASK_MIN_MS`) of the request left, the owner's cone, its scoops and guest runs alike; everything else, and no verdict, goes to a person (the tier becomes `user`). A sudo item nobody is there to answer stays pending until it times out, and a follower device can still answer it. A command a sudoers rule allows `NOPASSWD` never reaches the judge (the kernel grants it without asking).
770
+ - **The routing table** (`route(verdict, requester, gate, present)`, the same for sudo and guest items): with a person as the gate it always asks, the verdict shown. With the judge as the gate, level 1 and aligned (over 0.8) is allowed once by the judge, only when its `routine` is over 0.8 (`JUDGE_ALLOW`) too and nothing the owner wrote vetoes it (`approvable`, `vetoed`); a chat verdict for a guest has no `routine` and counts as given; level 3 is denied, with the verdict as the denial message, unless a person asked (a terminal, a sprinkle or a linked device: never denied while a person is there) or an owner device is attached with at least 30 s (`ASK_MIN_MS`) of the request left, the owner's cone, its scoops and guest runs alike; everything else, and no verdict, goes to a person (the tier becomes `user`). A sudo item nobody is there to answer stays pending until it times out, and a follower device can still answer it. A command a sudoers rule allows `NOPASSWD` never reaches the judge (the kernel grants it without asking).
769
771
  - **Always** has one meaning on both paths: `true` only when a later run of exactly this line can do no more than this one. The classifier is asked the opposite question (`true` is "a later run could do more"), so its `always` is P(more) ≤ 0.2; the chat model answers `always: yes` for the same case. A test pins that both give the same `always` and the same offer.
770
772
  - **Always offer:** a `sudo` item offers Always only when a person answers it (`user` tier), the verdict is level 1 with `always`, and the kernel can write the line (`writable` isn't `false`). It starts `false` and turns `true` when such a verdict lands. A guest item's Always stays under `guests.always`.
771
773
  - **The owner's intent:** the policy file `/etc/slicc/APPROVALS.md` (up to 4,000 characters), the owner's last 10 messages in the item's cone (each up to 1,000), and the global and cone memory (up to 4,000 in all), as `owner` in the classifier's state and, scrubbed, in the chat model's input. The worker seeds the policy when it's missing, owned by root with mode 644, so it's written without a prompt and a kernel user can change it only with sudo. It's read again for every request. The owner's messages are the cone's `pi.user` entries without a `slicc.from` note and that aren't licks, so a guest's `slicc.guest-input` never counts.
772
774
  - **The requester's text**, and for sudo every path, the directory and the target it chose, is only in `request.untrusted`, inside a fence with a new nonce each call. Any copy of the fence in the text is removed.
773
- - **Recording:** `decidedBy` is `judge`, and `verdict` on the item is `{ level, routine?, aligned, always?, reason, via, model }` (`routine` only from a classifier), `aligned` the probability from a classifier or a boolean from the chat model. A verdict that lands after the item timed out stays on it. A model-less `slicc.approval-verdict` entry in the item's conversation records each outcome (`approved`, `rejected`, `escalated` or `unanswered`), with the error when the judge failed.
775
+ - **Recording:** `decidedBy` is `judge`, and `verdict` on the item is `{ level, routine?, aligned, always?, reason, via, model, actions?, intent?, forbidden? }`, `aligned` the probability from a classifier or a boolean from the chat model, and `actions` and `intent` the sudo answers. A verdict that lands after the item timed out stays on it. A model-less `slicc.approval-verdict` entry in the item's conversation records each outcome (`approved`, `rejected`, `escalated` or `unanswered`), with the error when the judge failed.
774
776
  - **Abort:** the judge of an `agent` item runs with the request context's signal. When the request is aborted, the item is withdrawn (`aborted`) and a late verdict is dropped. After a reload, a pending `agent` item goes to a person.
775
- - **Evals:** [`evals/judge.json`](evals/judge.json) holds guest prompts, tool calls and sudo requests with their expected routing and, for some sudo cases, whether Always should be offered. A case brings `present`, whether an owner device is attached, and a sudo case its own owner messages and the kernel's facts. `SLICC_ADOBE_IMS_TOKEN=… npm run eval:judge -- --model adobe/clef --model adobe/clef-flash` runs them against Adobe's classifiers; `CLOUDFLARE_API_KEY=… CLOUDFLARE_ACCOUNT_ID=… npm run eval:judge -- --model cloudflare-workers-ai/@cf/cloudflare/clef` runs the same cases on Workers AI. Run either before changing the thresholds, questions or default policy. `--record` saves the probabilities it saw, and CI replays those through the approvals surface. A non-blocking nightly (and `workflow_dispatch`) job runs the Cloudflare reference model.
777
+ - **Evals:** [`evals/judge.json`](evals/judge.json) holds guest prompts, tool calls and sudo requests with their expected routing and, for some sudo cases, whether Always should be offered. A case brings `present`, whether an owner device is attached, and a sudo case its own owner messages and the kernel's facts. `SLICC_ADOBE_IMS_TOKEN=… npm run eval:judge -- --model adobe/clef --model adobe/clef-flash` runs them against Adobe's classifiers; `CLOUDFLARE_API_KEY=… CLOUDFLARE_ACCOUNT_ID=… npm run eval:judge -- --model cloudflare-workers-ai/@cf/cloudflare/clef` runs the same cases on Workers AI. Sudo cases run through `approvalJudge`, so they ask the action and intent calls as the agent does. Run either before changing the thresholds, questions or default policy. `--record` saves the probabilities it saw (`level` and `aligned` for a guest case, `actions` and `intent` for a sudo case), and CI replays those through the approvals surface. A non-blocking nightly (and `workflow_dispatch`) job runs the Cloudflare reference model.
776
778
 
777
779
  ### Approval policy
778
780
 
@@ -1,7 +1,15 @@
1
1
  const JUDGE_ALLOW = 0.8;
2
- const fits = (aligned) => aligned === true || typeof aligned === "number" && aligned >= JUDGE_ALLOW;
2
+ const JUDGE_LOW = 0.2;
3
+ const JUDGE_EPSILON = 1e-9;
4
+ const clears = (p, bar) => p >= bar + JUDGE_EPSILON;
5
+ const reaches = (p, bar) => p >= bar - JUDGE_EPSILON;
6
+ const fits = (aligned) => aligned === true || typeof aligned === "number" && clears(aligned, JUDGE_ALLOW);
3
7
  export {
4
8
  JUDGE_ALLOW,
5
- fits
9
+ JUDGE_EPSILON,
10
+ JUDGE_LOW,
11
+ clears,
12
+ fits,
13
+ reaches
6
14
  };
7
15
  //# sourceMappingURL=aligned.js.map
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/approvals/aligned.ts"],
4
- "sourcesContent": ["export const JUDGE_ALLOW = 0.8;\n\nexport const fits = (aligned: number | boolean | undefined): boolean =>\n aligned === true || (typeof aligned === 'number' && aligned >= JUDGE_ALLOW);\n"],
5
- "mappings": "AAAO,MAAM,cAAc;AAEpB,MAAM,OAAO,CAAC,YACnB,YAAY,QAAS,OAAO,YAAY,YAAY,WAAW;",
4
+ "sourcesContent": ["export const JUDGE_ALLOW = 0.8;\nexport const JUDGE_LOW = 0.2;\nexport const JUDGE_EPSILON = 1e-9;\n\nexport const clears = (p: number, bar: number): boolean => p >= bar + JUDGE_EPSILON;\n\nexport const reaches = (p: number, bar: number): boolean => p >= bar - JUDGE_EPSILON;\n\nexport const fits = (aligned: number | boolean | undefined): boolean =>\n aligned === true || (typeof aligned === 'number' && clears(aligned, JUDGE_ALLOW));\n"],
5
+ "mappings": "AAAO,MAAM,cAAc;AACpB,MAAM,YAAY;AAClB,MAAM,gBAAgB;AAEtB,MAAM,SAAS,CAAC,GAAW,QAAyB,KAAK,MAAM;AAE/D,MAAM,UAAU,CAAC,GAAW,QAAyB,KAAK,MAAM;AAEhE,MAAM,OAAO,CAAC,YACnB,YAAY,QAAS,OAAO,YAAY,YAAY,OAAO,SAAS,WAAW;",
6
6
  "names": []
7
7
  }
@@ -2,10 +2,7 @@ import {
2
2
  replicatedState
3
3
  } from "@earendil-works/chord";
4
4
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
5
- import {
6
- ASK_MIN_MS,
7
- JUDGE_RESTARTED
8
- } from "./judge.js";
5
+ import { ASK_MIN_MS, JUDGE_RESTARTED } from "./judge.js";
9
6
  import {
10
7
  APPROVAL_MS,
11
8
  ApprovalsDoc,
@@ -92,15 +89,6 @@ const judgedIn = (id, judged, now) => (doc) => {
92
89
  if (ruling.settle) mark(item, ruling.settle, at);
93
90
  return copy([item])[0];
94
91
  };
95
- const reasonIn = (id, reasoned) => (doc) => {
96
- const item = doc.items.find((entry) => entry.id === id);
97
- if (item?.verdict && reasoned.reason) item.verdict.reason = reasoned.reason;
98
- };
99
- const withReason = (judgement, reasoned) => ({
100
- ...judgement,
101
- ...judgement.verdict && reasoned.reason ? { verdict: { ...judgement.verdict, reason: reasoned.reason } } : {},
102
- cost: judgement.cost == null && reasoned.cost == null ? null : (judgement.cost ?? 0) + (reasoned.cost ?? 0)
103
- });
104
92
  async function judgedBy(judge, present, item, using, now) {
105
93
  const judgement = await judge.judge(item, using).catch((error) => ({ error: String(error) }));
106
94
  if (judgement.verdict?.level !== 3 || !present || item.tier !== "agent")
@@ -122,23 +110,14 @@ function judgeRunner(run) {
122
110
  };
123
111
  if (signal?.aborted) return abort();
124
112
  signal?.addEventListener("abort", abort, { once: true });
125
- let judged = await judgedBy(judge, run.present, item, using, now);
126
- const pending = judged.judgement.reason;
127
- const ready = pending ? await Promise.race([pending, Promise.resolve(void 0)]) : void 0;
128
- const early = ready ?? (pending && routeOf(item, judged) === "deny" ? await pending : void 0);
129
- if (early) judged = { ...judged, judgement: withReason(judged.judgement, early) };
113
+ const judged = await judgedBy(judge, run.present, item, using, now);
130
114
  signal?.removeEventListener("abort", abort);
131
115
  if (gone || run.closed()) return;
132
116
  const after = await serial(judgedIn(item.id, judged, now), BACKGROUND_CONTEXT).catch(
133
117
  () => void 0
134
118
  );
135
119
  if (!after) return;
136
- const reasoned = early ? {} : await pending ?? {};
137
- const final = withReason(judged.judgement, reasoned);
138
- if (reasoned.reason && !run.closed())
139
- await serial(reasonIn(item.id, reasoned), BACKGROUND_CONTEXT).catch(() => void 0);
140
- const recorded = final.verdict ? { ...after, verdict: final.verdict } : after;
141
- await judge.record?.(recorded, final, BACKGROUND_CONTEXT).catch(() => void 0);
120
+ await judge.record?.(after, judged.judgement, BACKGROUND_CONTEXT).catch(() => void 0);
142
121
  };
143
122
  }
144
123
  function following(watch, changed) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../src/approvals/index.ts"],
4
- "sourcesContent": ["import {\n type Context,\n type ReplicatedState,\n replicatedState,\n type WatchHandle,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Harness } from '@earendil-works/pi-durable';\nimport type { Clock } from '../clock.ts';\nimport {\n type ApprovalJudge,\n ASK_MIN_MS,\n JUDGE_RESTARTED,\n type Judgement,\n type Reasoned,\n} from './judge.ts';\nimport {\n APPROVAL_MS,\n type Approval,\n type ApprovalDraft,\n type ApprovalKind,\n type ApprovalState,\n ApprovalsDoc,\n type ApprovalsState,\n alwaysOffered,\n cleanReason,\n type DecidedBy,\n gateOf,\n guestKind,\n knownTier,\n MAX_DELAY,\n prune,\n REASONS,\n type Routed,\n routable,\n route,\n ruled,\n type Settle,\n scoopTier,\n sudoApprover,\n tierOf,\n} from './record.ts';\n\nexport * from './intent.ts';\nexport * from './judge.ts';\nexport * from './present.ts';\nexport * from './record.ts';\n\nexport type ApprovalDecided =\n | { done: true; state: ApprovalState; error: null }\n | { done: false; state: null; error: string };\n\nexport type Decider = DecidedBy | { by: DecidedBy; device?: string };\n\nconst deciderOf = (decider: Decider) => (typeof decider === 'string' ? { by: decider } : decider);\n\nexport interface Approvals {\n readonly state: ReplicatedState<Approval[]>;\n request(draft: ApprovalDraft & { id?: string }, context: Context): Promise<Approval>;\n decide(\n id: string,\n answer: unknown,\n reason: string | null,\n by: Decider,\n context: Context\n ): Promise<ApprovalDecided>;\n settled(id: string, context: Context): Promise<Approval>;\n assign(id: string, reviewer: string, context: Context): Promise<Approval | undefined>;\n withdraw(id: string, reason: string | null, context: Context): Promise<Approval | undefined>;\n withdrawSeat(seat: string, context: Context): Promise<number>;\n expire(id: string, context: Context): Promise<Approval | undefined>;\n close(): void;\n}\n\nexport interface ScoopRouter {\n route(item: Approval): Promise<void>;\n}\n\nexport interface ApprovalsAttach {\n harness: Pick<Harness, 'commit' | 'watchDoc'>;\n now?: () => number;\n setTimer?: Clock['setTimer'];\n ttlMs?: number;\n judge?: ApprovalJudge;\n scoops?: ScoopRouter;\n guestAlways?: (kind: ApprovalKind) => boolean;\n sudoApprover?: () => unknown;\n present?: (item: Approval, context: Context) => Promise<boolean>;\n}\n\nconst copy = (items: readonly Approval[]): Approval[] => JSON.parse(JSON.stringify(items));\n\nfunction mark(item: Approval, how: Settle, at: number) {\n item.state = how.state;\n item.decidedBy = how.by;\n item.decidedAt = at;\n delete item.judging;\n if (how.reason) item.reason = how.reason;\n}\n\nconst offered = (options: ApprovalsAttach, draft: ApprovalDraft): boolean =>\n guestKind(draft.kind) ? options.guestAlways?.(draft.kind) === true : false;\n\nconst judgedKind = (kind: ApprovalKind, tier: string) =>\n kind === 'sudo' || tier === 'agent' || tier === 'user';\n\nfunction detailOf(draft: ApprovalDraft): ApprovalDraft['detail'] {\n if (draft.kind !== 'sudo' || draft.always !== false) return draft.detail;\n return { ...draft.detail, writable: false };\n}\n\nfunction fresh(\n draft: ApprovalDraft & { id?: string },\n at: number,\n ttl: number,\n options: ApprovalsAttach\n): Approval {\n const tier = tierOf(draft.kind, draft.tier, sudoApprover(options.sudoApprover?.()));\n const item = {\n ...draft,\n detail: detailOf(draft),\n tier,\n id: draft.id ?? `apr-${crypto.randomUUID()}`,\n state: 'pending',\n decidedBy: null,\n always: offered(options, draft),\n ...(options.judge && judgedKind(draft.kind, tier) ? { judging: true } : {}),\n createdAt: at,\n expiresAt: draft.expiresAt ?? at + ttl,\n } as Approval;\n if (!knownTier(item.tier))\n mark(item, { state: 'unanswered', by: 'host', reason: REASONS.unknownTier }, at);\n else if (!routable(draft.kind, item.tier))\n mark(item, { state: 'unanswered', by: 'host', reason: REASONS.unroutable }, at);\n return item;\n}\n\nconst withdrawIn =\n (match: (item: Approval) => boolean, reason: string | undefined, now: () => number) =>\n (doc: ApprovalsState) => {\n const hit = doc.items.filter((item) => item.state === 'pending' && match(item));\n for (const item of hit)\n mark(item, { state: 'withdrawn', by: 'host', ...(reason ? { reason } : {}) }, now());\n return hit.map((item) => copy([item])[0] as Approval);\n };\n\ntype Judged = { judgement: Judgement; present: boolean };\n\nconst routeOf = (item: Approval, { judgement, present }: Judged): Routed =>\n route(judgement.verdict, item.requester, gateOf(item.tier), present);\n\nconst judgedIn = (id: string, judged: Judged, now: () => number) => (doc: ApprovalsState) => {\n const { judgement } = judged;\n const item = doc.items.find((entry) => entry.id === id);\n if (!item) return undefined;\n const late = item.state === 'unanswered' && item.reason === REASONS.timeout && !item.verdict;\n if (item.state !== 'pending' && !(late && judgement.verdict)) return undefined;\n delete item.judging;\n if (judgement.verdict) item.verdict = judgement.verdict;\n else item.verdictError = judgement.error ?? 'the judge gave no verdict';\n if (late) return copy([item])[0] as Approval;\n const routed = routeOf(item, judged);\n if (routed === 'ask') {\n item.tier = 'user';\n if (item.kind === 'sudo') item.always = alwaysOffered(item);\n return copy([item])[0] as Approval;\n }\n const at = now();\n const ruling = ruled(item, routed === 'approve' ? 'once' : 'deny', null, 'judge', at);\n if (ruling.answer) item.answer = ruling.answer;\n if (ruling.settle) mark(item, ruling.settle, at);\n return copy([item])[0] as Approval;\n};\n\nconst reasonIn = (id: string, reasoned: Reasoned) => (doc: ApprovalsState) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.verdict && reasoned.reason) item.verdict.reason = reasoned.reason;\n};\n\nconst withReason = (judgement: Judgement, reasoned: Reasoned): Judgement => ({\n ...judgement,\n ...(judgement.verdict && reasoned.reason\n ? { verdict: { ...judgement.verdict, reason: reasoned.reason } }\n : {}),\n cost:\n judgement.cost == null && reasoned.cost == null\n ? null\n : (judgement.cost ?? 0) + (reasoned.cost ?? 0),\n});\n\nasync function judgedBy(\n judge: ApprovalJudge,\n present: ApprovalsAttach['present'],\n item: Approval,\n using: Context,\n now: () => number\n): Promise<Judged> {\n const judgement = await judge\n .judge(item, using)\n .catch((error: unknown): Judgement => ({ error: String(error) }));\n if (judgement.verdict?.level !== 3 || !present || item.tier !== 'agent')\n return { judgement, present: false };\n const there = await present(item, using).catch(() => false);\n return { judgement, present: there && item.expiresAt - now() >= ASK_MIN_MS };\n}\n\ntype Serial = <R>(change: (doc: ApprovalsState) => R, using: Context) => Promise<R>;\n\nfunction judgeRunner(run: {\n serial: Serial;\n present: ApprovalsAttach['present'];\n now: () => number;\n closed: () => boolean;\n}) {\n const { serial, now } = run;\n return async (judge: ApprovalJudge, item: Approval, using: Context) => {\n const signal = using.abortSignal;\n let gone = false;\n const abort = () => {\n gone = true;\n void serial(\n withdrawIn((entry) => entry.id === item.id && entry.tier === 'agent', REASONS.aborted, now),\n BACKGROUND_CONTEXT\n ).catch(() => undefined);\n };\n if (signal?.aborted) return abort();\n signal?.addEventListener('abort', abort, { once: true });\n let judged = await judgedBy(judge, run.present, item, using, now);\n const pending = judged.judgement.reason;\n const ready = pending ? await Promise.race([pending, Promise.resolve(undefined)]) : undefined;\n const early =\n ready ?? (pending && routeOf(item, judged) === 'deny' ? await pending : undefined);\n if (early) judged = { ...judged, judgement: withReason(judged.judgement, early) };\n signal?.removeEventListener('abort', abort);\n if (gone || run.closed()) return;\n const after = await serial(judgedIn(item.id, judged, now), BACKGROUND_CONTEXT).catch(\n () => undefined\n );\n if (!after) return;\n const reasoned = early ? {} : ((await pending) ?? {});\n const final = withReason(judged.judgement, reasoned);\n if (reasoned.reason && !run.closed())\n await serial(reasonIn(item.id, reasoned), BACKGROUND_CONTEXT).catch(() => undefined);\n const recorded = final.verdict ? { ...after, verdict: final.verdict } : after;\n await judge.record?.(recorded, final, BACKGROUND_CONTEXT).catch(() => undefined);\n };\n}\n\nfunction following(\n watch: WatchHandle<Readonly<ApprovalsState>>,\n changed: (using: Context, items: Approval[]) => void\n) {\n const items = () => watch.value.items;\n let shown = items();\n return (using: Context) => {\n const now = items();\n if (now === shown) return;\n shown = now;\n changed(using, copy(now));\n };\n}\n\nfunction settledIn(\n state: ReplicatedState<Approval[]>,\n id: string,\n using: Context\n): Promise<Approval> {\n return new Promise((resolve, reject) => {\n const signal = using.abortSignal;\n let done = false;\n let off: (() => void) | undefined;\n const finish = (end: () => void) => {\n done = true;\n off?.();\n signal?.removeEventListener('abort', abort);\n end();\n };\n const abort = () => finish(() => reject(signal?.reason));\n const check = (items: readonly Approval[] | undefined) => {\n const item = items?.find((entry) => entry.id === id);\n if (!item) finish(() => reject(new Error(`There is no approval ${id}.`)));\n else if (item.state !== 'pending') finish(() => resolve(item));\n };\n if (signal?.aborted) return abort();\n check(state.value);\n if (done) return;\n signal?.addEventListener('abort', abort, { once: true });\n off = state.subscribe((items) => check(items));\n });\n}\n\nconst systemTimer: Clock['setTimer'] = (callback, delayMs) => {\n const timer = setTimeout(callback, delayMs);\n return () => clearTimeout(timer);\n};\n\nexport async function attachApprovals(\n options: ApprovalsAttach,\n context: Context = BACKGROUND_CONTEXT\n): Promise<Approvals> {\n const { harness } = options;\n const now = options.now ?? Date.now;\n const ttl = options.ttlMs ?? APPROVAL_MS;\n const setTimer = options.setTimer ?? systemTimer;\n const timers = new Map<string, () => void>();\n let line: Promise<unknown> = Promise.resolve();\n let closed = false;\n const settle = (item: Approval, how: Settle) => mark(item, how, now());\n const write = <R>(\n change: (doc: ApprovalsState) => R,\n using: Context\n ): Promise<{ result: R; items: Approval[] }> =>\n harness.commit(async (tx) => {\n const doc = await tx.doc(ApprovalsDoc);\n const result = change(doc);\n doc.items = prune(doc.items);\n return { result, items: copy(doc.items) };\n }, using);\n const startup = await write((doc) => {\n for (const item of doc.items) {\n if (item.state !== 'pending') continue;\n if (item.kind === 'sudo')\n settle(item, { state: 'withdrawn', by: 'host', reason: REASONS.restart });\n else if (item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n else if (options.judge && item.tier === 'agent') item.tier = 'user';\n if (item.state === 'pending' && item.judging) {\n delete item.judging;\n item.verdictError = JUDGE_RESTARTED;\n }\n }\n }, context);\n const state = replicatedState<Approval[]>(startup.items);\n const watch = await harness.watchDoc(ApprovalsDoc, context);\n if (!watch) throw new Error('approvals document is missing');\n const follow = following(watch, (using, items) => {\n state.replace(using, items);\n arm(items);\n });\n follow(context);\n watch.start(async (call, using) => {\n if (call.kind === 'value') follow(using);\n });\n const serial = <R>(change: (doc: ApprovalsState) => R, using: Context): Promise<R> => {\n const run = line.then(async () => {\n const { result } = await write(change, using);\n follow(using);\n return result;\n });\n line = run.catch(() => undefined);\n return run;\n };\n const expire = (id: string) => {\n timers.delete(id);\n const due = (state.value as Approval[]).find((entry) => entry.id === id);\n if (due?.state === 'pending' && due.expiresAt > now()) return arm(state.value as Approval[]);\n void serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n }, BACKGROUND_CONTEXT).catch(() => undefined);\n };\n function arm(items: readonly Approval[]) {\n const pending = new Set<string>();\n for (const item of items) {\n if (item.state !== 'pending') continue;\n pending.add(item.id);\n if (timers.has(item.id) || closed) continue;\n timers.set(\n item.id,\n setTimer(() => expire(item.id), Math.min(MAX_DELAY, Math.max(0, item.expiresAt - now())))\n );\n }\n for (const [id, timer] of timers)\n if (!pending.has(id)) {\n timer();\n timers.delete(id);\n }\n }\n arm(startup.items);\n const toScoop = (item: Approval) => {\n if (options.scoops && item.state === 'pending' && scoopTier(item.tier))\n void options.scoops.route(item).catch(() => undefined);\n };\n for (const item of startup.items) toScoop(item);\n const withdrawWhere = (match: (item: Approval) => boolean, reason: string | undefined) =>\n withdrawIn(match, reason, now);\n const judging = judgeRunner({\n serial,\n present: options.present,\n now,\n closed: () => closed,\n });\n return {\n state,\n async request(draft, using) {\n let created = true;\n const made = await serial((doc) => {\n const kept = draft.id && doc.items.find((entry) => entry.id === draft.id);\n if (kept) {\n created = false;\n return copy([kept])[0] as Approval;\n }\n const item = fresh(draft, now(), ttl, options);\n doc.items.push(item);\n return copy([item])[0] as Approval;\n }, using);\n if (created && options.judge && made.state === 'pending' && judgedKind(made.kind, made.tier))\n void judging(options.judge, made, made.tier === 'agent' ? using : BACKGROUND_CONTEXT);\n if (created) toScoop(made);\n return made;\n },\n decide(id, answer, reason, decider, using) {\n const { by, device } = deciderOf(decider);\n return serial((doc): ApprovalDecided => {\n const item = doc.items.find((entry) => entry.id === id);\n const ruling = item\n ? ruled(item, answer, reason, by, now())\n : { error: `There is no approval ${id}.` };\n if (item && ruling.settle) {\n if (ruling.answer) item.answer = ruling.answer;\n if (device && ruling.settle.by === by) item.device = device;\n settle(item, ruling.settle);\n }\n if ('error' in ruling && ruling.error)\n return { done: false, state: null, error: ruling.error };\n return { done: true, state: (item as Approval).state, error: null };\n }, using);\n },\n settled: (id, using) => settledIn(state, id, using),\n assign(id, reviewer, using) {\n return serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && scoopTier(item.tier)) item.reviewer ??= reviewer;\n return item ? (copy([item])[0] as Approval) : undefined;\n }, using);\n },\n async withdraw(id, reason, using) {\n const [hit] = await serial(\n withdrawWhere((item) => item.id === id, cleanReason(reason)),\n using\n );\n return hit;\n },\n async withdrawSeat(seat, using) {\n return (\n await serial(\n withdrawWhere((item) => item.seat === seat, REASONS.revoked),\n using\n )\n ).length;\n },\n async expire(id, using) {\n return serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n return item ? (copy([item])[0] as Approval) : undefined;\n }, using);\n },\n close() {\n closed = true;\n for (const timer of timers.values()) timer();\n timers.clear();\n void watch.stop();\n },\n };\n}\n"],
5
- "mappings": "AAAA;AAAA,EAGE;AAAA,OAEK;AACP,SAAS,0BAA0B;AAGnC;AAAA,EAEE;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EAKA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAQd,MAAM,YAAY,CAAC,YAAsB,OAAO,YAAY,WAAW,EAAE,IAAI,QAAQ,IAAI;AAoCzF,MAAM,OAAO,CAAC,UAA2C,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAEzF,SAAS,KAAK,MAAgB,KAAa,IAAY;AACrD,OAAK,QAAQ,IAAI;AACjB,OAAK,YAAY,IAAI;AACrB,OAAK,YAAY;AACjB,SAAO,KAAK;AACZ,MAAI,IAAI,OAAQ,MAAK,SAAS,IAAI;AACpC;AAEA,MAAM,UAAU,CAAC,SAA0B,UACzC,UAAU,MAAM,IAAI,IAAI,QAAQ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C;AAC3E,eAAO,OAAQ,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,IAAiB;AAAA,MAChD,GAAG,KAAK;AAAA,IACV;AAAA,IACA,QAAQ;AACN,eAAS;AACT,iBAAW,SAAS,OAAO,OAAO,EAAG,OAAM;AAC3C,aAAO,MAAM;AACb,WAAK,MAAM,KAAK;AAAA,IAClB;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import {\n type Context,\n type ReplicatedState,\n replicatedState,\n type WatchHandle,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Harness } from '@earendil-works/pi-durable';\nimport type { Clock } from '../clock.ts';\nimport { type ApprovalJudge, ASK_MIN_MS, JUDGE_RESTARTED, type Judgement } from './judge.ts';\nimport {\n APPROVAL_MS,\n type Approval,\n type ApprovalDraft,\n type ApprovalKind,\n type ApprovalState,\n ApprovalsDoc,\n type ApprovalsState,\n alwaysOffered,\n cleanReason,\n type DecidedBy,\n gateOf,\n guestKind,\n knownTier,\n MAX_DELAY,\n prune,\n REASONS,\n type Routed,\n routable,\n route,\n ruled,\n type Settle,\n scoopTier,\n sudoApprover,\n tierOf,\n} from './record.ts';\n\nexport * from './intent.ts';\nexport * from './judge.ts';\nexport * from './present.ts';\nexport * from './record.ts';\n\nexport type ApprovalDecided =\n | { done: true; state: ApprovalState; error: null }\n | { done: false; state: null; error: string };\n\nexport type Decider = DecidedBy | { by: DecidedBy; device?: string };\n\nconst deciderOf = (decider: Decider) => (typeof decider === 'string' ? { by: decider } : decider);\n\nexport interface Approvals {\n readonly state: ReplicatedState<Approval[]>;\n request(draft: ApprovalDraft & { id?: string }, context: Context): Promise<Approval>;\n decide(\n id: string,\n answer: unknown,\n reason: string | null,\n by: Decider,\n context: Context\n ): Promise<ApprovalDecided>;\n settled(id: string, context: Context): Promise<Approval>;\n assign(id: string, reviewer: string, context: Context): Promise<Approval | undefined>;\n withdraw(id: string, reason: string | null, context: Context): Promise<Approval | undefined>;\n withdrawSeat(seat: string, context: Context): Promise<number>;\n expire(id: string, context: Context): Promise<Approval | undefined>;\n close(): void;\n}\n\nexport interface ScoopRouter {\n route(item: Approval): Promise<void>;\n}\n\nexport interface ApprovalsAttach {\n harness: Pick<Harness, 'commit' | 'watchDoc'>;\n now?: () => number;\n setTimer?: Clock['setTimer'];\n ttlMs?: number;\n judge?: ApprovalJudge;\n scoops?: ScoopRouter;\n guestAlways?: (kind: ApprovalKind) => boolean;\n sudoApprover?: () => unknown;\n present?: (item: Approval, context: Context) => Promise<boolean>;\n}\n\nconst copy = (items: readonly Approval[]): Approval[] => JSON.parse(JSON.stringify(items));\n\nfunction mark(item: Approval, how: Settle, at: number) {\n item.state = how.state;\n item.decidedBy = how.by;\n item.decidedAt = at;\n delete item.judging;\n if (how.reason) item.reason = how.reason;\n}\n\nconst offered = (options: ApprovalsAttach, draft: ApprovalDraft): boolean =>\n guestKind(draft.kind) ? options.guestAlways?.(draft.kind) === true : false;\n\nconst judgedKind = (kind: ApprovalKind, tier: string) =>\n kind === 'sudo' || tier === 'agent' || tier === 'user';\n\nfunction detailOf(draft: ApprovalDraft): ApprovalDraft['detail'] {\n if (draft.kind !== 'sudo' || draft.always !== false) return draft.detail;\n return { ...draft.detail, writable: false };\n}\n\nfunction fresh(\n draft: ApprovalDraft & { id?: string },\n at: number,\n ttl: number,\n options: ApprovalsAttach\n): Approval {\n const tier = tierOf(draft.kind, draft.tier, sudoApprover(options.sudoApprover?.()));\n const item = {\n ...draft,\n detail: detailOf(draft),\n tier,\n id: draft.id ?? `apr-${crypto.randomUUID()}`,\n state: 'pending',\n decidedBy: null,\n always: offered(options, draft),\n ...(options.judge && judgedKind(draft.kind, tier) ? { judging: true } : {}),\n createdAt: at,\n expiresAt: draft.expiresAt ?? at + ttl,\n } as Approval;\n if (!knownTier(item.tier))\n mark(item, { state: 'unanswered', by: 'host', reason: REASONS.unknownTier }, at);\n else if (!routable(draft.kind, item.tier))\n mark(item, { state: 'unanswered', by: 'host', reason: REASONS.unroutable }, at);\n return item;\n}\n\nconst withdrawIn =\n (match: (item: Approval) => boolean, reason: string | undefined, now: () => number) =>\n (doc: ApprovalsState) => {\n const hit = doc.items.filter((item) => item.state === 'pending' && match(item));\n for (const item of hit)\n mark(item, { state: 'withdrawn', by: 'host', ...(reason ? { reason } : {}) }, now());\n return hit.map((item) => copy([item])[0] as Approval);\n };\n\ntype Judged = { judgement: Judgement; present: boolean };\n\nconst routeOf = (item: Approval, { judgement, present }: Judged): Routed =>\n route(judgement.verdict, item.requester, gateOf(item.tier), present);\n\nconst judgedIn = (id: string, judged: Judged, now: () => number) => (doc: ApprovalsState) => {\n const { judgement } = judged;\n const item = doc.items.find((entry) => entry.id === id);\n if (!item) return undefined;\n const late = item.state === 'unanswered' && item.reason === REASONS.timeout && !item.verdict;\n if (item.state !== 'pending' && !(late && judgement.verdict)) return undefined;\n delete item.judging;\n if (judgement.verdict) item.verdict = judgement.verdict;\n else item.verdictError = judgement.error ?? 'the judge gave no verdict';\n if (late) return copy([item])[0] as Approval;\n const routed = routeOf(item, judged);\n if (routed === 'ask') {\n item.tier = 'user';\n if (item.kind === 'sudo') item.always = alwaysOffered(item);\n return copy([item])[0] as Approval;\n }\n const at = now();\n const ruling = ruled(item, routed === 'approve' ? 'once' : 'deny', null, 'judge', at);\n if (ruling.answer) item.answer = ruling.answer;\n if (ruling.settle) mark(item, ruling.settle, at);\n return copy([item])[0] as Approval;\n};\n\nasync function judgedBy(\n judge: ApprovalJudge,\n present: ApprovalsAttach['present'],\n item: Approval,\n using: Context,\n now: () => number\n): Promise<Judged> {\n const judgement = await judge\n .judge(item, using)\n .catch((error: unknown): Judgement => ({ error: String(error) }));\n if (judgement.verdict?.level !== 3 || !present || item.tier !== 'agent')\n return { judgement, present: false };\n const there = await present(item, using).catch(() => false);\n return { judgement, present: there && item.expiresAt - now() >= ASK_MIN_MS };\n}\n\ntype Serial = <R>(change: (doc: ApprovalsState) => R, using: Context) => Promise<R>;\n\nfunction judgeRunner(run: {\n serial: Serial;\n present: ApprovalsAttach['present'];\n now: () => number;\n closed: () => boolean;\n}) {\n const { serial, now } = run;\n return async (judge: ApprovalJudge, item: Approval, using: Context) => {\n const signal = using.abortSignal;\n let gone = false;\n const abort = () => {\n gone = true;\n void serial(\n withdrawIn((entry) => entry.id === item.id && entry.tier === 'agent', REASONS.aborted, now),\n BACKGROUND_CONTEXT\n ).catch(() => undefined);\n };\n if (signal?.aborted) return abort();\n signal?.addEventListener('abort', abort, { once: true });\n const judged = await judgedBy(judge, run.present, item, using, now);\n signal?.removeEventListener('abort', abort);\n if (gone || run.closed()) return;\n const after = await serial(judgedIn(item.id, judged, now), BACKGROUND_CONTEXT).catch(\n () => undefined\n );\n if (!after) return;\n await judge.record?.(after, judged.judgement, BACKGROUND_CONTEXT).catch(() => undefined);\n };\n}\n\nfunction following(\n watch: WatchHandle<Readonly<ApprovalsState>>,\n changed: (using: Context, items: Approval[]) => void\n) {\n const items = () => watch.value.items;\n let shown = items();\n return (using: Context) => {\n const now = items();\n if (now === shown) return;\n shown = now;\n changed(using, copy(now));\n };\n}\n\nfunction settledIn(\n state: ReplicatedState<Approval[]>,\n id: string,\n using: Context\n): Promise<Approval> {\n return new Promise((resolve, reject) => {\n const signal = using.abortSignal;\n let done = false;\n let off: (() => void) | undefined;\n const finish = (end: () => void) => {\n done = true;\n off?.();\n signal?.removeEventListener('abort', abort);\n end();\n };\n const abort = () => finish(() => reject(signal?.reason));\n const check = (items: readonly Approval[] | undefined) => {\n const item = items?.find((entry) => entry.id === id);\n if (!item) finish(() => reject(new Error(`There is no approval ${id}.`)));\n else if (item.state !== 'pending') finish(() => resolve(item));\n };\n if (signal?.aborted) return abort();\n check(state.value);\n if (done) return;\n signal?.addEventListener('abort', abort, { once: true });\n off = state.subscribe((items) => check(items));\n });\n}\n\nconst systemTimer: Clock['setTimer'] = (callback, delayMs) => {\n const timer = setTimeout(callback, delayMs);\n return () => clearTimeout(timer);\n};\n\nexport async function attachApprovals(\n options: ApprovalsAttach,\n context: Context = BACKGROUND_CONTEXT\n): Promise<Approvals> {\n const { harness } = options;\n const now = options.now ?? Date.now;\n const ttl = options.ttlMs ?? APPROVAL_MS;\n const setTimer = options.setTimer ?? systemTimer;\n const timers = new Map<string, () => void>();\n let line: Promise<unknown> = Promise.resolve();\n let closed = false;\n const settle = (item: Approval, how: Settle) => mark(item, how, now());\n const write = <R>(\n change: (doc: ApprovalsState) => R,\n using: Context\n ): Promise<{ result: R; items: Approval[] }> =>\n harness.commit(async (tx) => {\n const doc = await tx.doc(ApprovalsDoc);\n const result = change(doc);\n doc.items = prune(doc.items);\n return { result, items: copy(doc.items) };\n }, using);\n const startup = await write((doc) => {\n for (const item of doc.items) {\n if (item.state !== 'pending') continue;\n if (item.kind === 'sudo')\n settle(item, { state: 'withdrawn', by: 'host', reason: REASONS.restart });\n else if (item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n else if (options.judge && item.tier === 'agent') item.tier = 'user';\n if (item.state === 'pending' && item.judging) {\n delete item.judging;\n item.verdictError = JUDGE_RESTARTED;\n }\n }\n }, context);\n const state = replicatedState<Approval[]>(startup.items);\n const watch = await harness.watchDoc(ApprovalsDoc, context);\n if (!watch) throw new Error('approvals document is missing');\n const follow = following(watch, (using, items) => {\n state.replace(using, items);\n arm(items);\n });\n follow(context);\n watch.start(async (call, using) => {\n if (call.kind === 'value') follow(using);\n });\n const serial = <R>(change: (doc: ApprovalsState) => R, using: Context): Promise<R> => {\n const run = line.then(async () => {\n const { result } = await write(change, using);\n follow(using);\n return result;\n });\n line = run.catch(() => undefined);\n return run;\n };\n const expire = (id: string) => {\n timers.delete(id);\n const due = (state.value as Approval[]).find((entry) => entry.id === id);\n if (due?.state === 'pending' && due.expiresAt > now()) return arm(state.value as Approval[]);\n void serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n }, BACKGROUND_CONTEXT).catch(() => undefined);\n };\n function arm(items: readonly Approval[]) {\n const pending = new Set<string>();\n for (const item of items) {\n if (item.state !== 'pending') continue;\n pending.add(item.id);\n if (timers.has(item.id) || closed) continue;\n timers.set(\n item.id,\n setTimer(() => expire(item.id), Math.min(MAX_DELAY, Math.max(0, item.expiresAt - now())))\n );\n }\n for (const [id, timer] of timers)\n if (!pending.has(id)) {\n timer();\n timers.delete(id);\n }\n }\n arm(startup.items);\n const toScoop = (item: Approval) => {\n if (options.scoops && item.state === 'pending' && scoopTier(item.tier))\n void options.scoops.route(item).catch(() => undefined);\n };\n for (const item of startup.items) toScoop(item);\n const withdrawWhere = (match: (item: Approval) => boolean, reason: string | undefined) =>\n withdrawIn(match, reason, now);\n const judging = judgeRunner({\n serial,\n present: options.present,\n now,\n closed: () => closed,\n });\n return {\n state,\n async request(draft, using) {\n let created = true;\n const made = await serial((doc) => {\n const kept = draft.id && doc.items.find((entry) => entry.id === draft.id);\n if (kept) {\n created = false;\n return copy([kept])[0] as Approval;\n }\n const item = fresh(draft, now(), ttl, options);\n doc.items.push(item);\n return copy([item])[0] as Approval;\n }, using);\n if (created && options.judge && made.state === 'pending' && judgedKind(made.kind, made.tier))\n void judging(options.judge, made, made.tier === 'agent' ? using : BACKGROUND_CONTEXT);\n if (created) toScoop(made);\n return made;\n },\n decide(id, answer, reason, decider, using) {\n const { by, device } = deciderOf(decider);\n return serial((doc): ApprovalDecided => {\n const item = doc.items.find((entry) => entry.id === id);\n const ruling = item\n ? ruled(item, answer, reason, by, now())\n : { error: `There is no approval ${id}.` };\n if (item && ruling.settle) {\n if (ruling.answer) item.answer = ruling.answer;\n if (device && ruling.settle.by === by) item.device = device;\n settle(item, ruling.settle);\n }\n if ('error' in ruling && ruling.error)\n return { done: false, state: null, error: ruling.error };\n return { done: true, state: (item as Approval).state, error: null };\n }, using);\n },\n settled: (id, using) => settledIn(state, id, using),\n assign(id, reviewer, using) {\n return serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && scoopTier(item.tier)) item.reviewer ??= reviewer;\n return item ? (copy([item])[0] as Approval) : undefined;\n }, using);\n },\n async withdraw(id, reason, using) {\n const [hit] = await serial(\n withdrawWhere((item) => item.id === id, cleanReason(reason)),\n using\n );\n return hit;\n },\n async withdrawSeat(seat, using) {\n return (\n await serial(\n withdrawWhere((item) => item.seat === seat, REASONS.revoked),\n using\n )\n ).length;\n },\n async expire(id, using) {\n return serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n return item ? (copy([item])[0] as Approval) : undefined;\n }, using);\n },\n close() {\n closed = true;\n for (const timer of timers.values()) timer();\n timers.clear();\n void watch.stop();\n },\n };\n}\n"],
5
+ "mappings": "AAAA;AAAA,EAGE;AAAA,OAEK;AACP,SAAS,0BAA0B;AAGnC,SAA6B,YAAY,uBAAuC;AAChF;AAAA,EACE;AAAA,EAKA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAQd,MAAM,YAAY,CAAC,YAAsB,OAAO,YAAY,WAAW,EAAE,IAAI,QAAQ,IAAI;AAoCzF,MAAM,OAAO,CAAC,UAA2C,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAEzF,SAAS,KAAK,MAAgB,KAAa,IAAY;AACrD,OAAK,QAAQ,IAAI;AACjB,OAAK,YAAY,IAAI;AACrB,OAAK,YAAY;AACjB,SAAO,KAAK;AACZ,MAAI,IAAI,OAAQ,MAAK,SAAS,IAAI;AACpC;AAEA,MAAM,UAAU,CAAC,SAA0B,UACzC,UAAU,MAAM,IAAI,IAAI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