@ai-ecoverse/slicc-agent 7.22.0 → 7.24.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 +24 -11
- package/dist/approvals/attributed.js +13 -0
- package/dist/approvals/attributed.js.map +7 -0
- package/dist/approvals/index.js +7 -3
- package/dist/approvals/index.js.map +2 -2
- package/dist/approvals/judge.js +71 -5
- package/dist/approvals/judge.js.map +2 -2
- package/dist/approvals/policy.js +1 -1
- package/dist/approvals/policy.js.map +2 -2
- package/dist/approvals/record.js +7 -4
- package/dist/approvals/record.js.map +2 -2
- package/dist/approvals/sudo-client.js +32 -1
- package/dist/approvals/sudo-client.js.map +3 -3
- package/dist/approvals/sudo.js +2 -0
- package/dist/approvals/sudo.js.map +2 -2
- package/dist/guests/capture.js +167 -0
- package/dist/guests/capture.js.map +7 -0
- package/dist/guests/index.js +18 -5
- package/dist/guests/index.js.map +2 -2
- package/dist/guests/seats.js.map +2 -2
- package/dist/host.js +8 -0
- package/dist/host.js.map +2 -2
- package/dist/index.js.map +2 -2
- package/dist/owner.js +23 -13
- package/dist/owner.js.map +2 -2
- package/dist/services.js +2 -1
- package/dist/services.js.map +2 -2
- package/dist/spectrum/approvals-port.js +1 -0
- package/dist/spectrum/approvals-port.js.map +2 -2
- package/dist/types/approvals/attributed.d.ts +3 -0
- package/dist/types/approvals/judge.d.ts +20 -4
- package/dist/types/approvals/record.d.ts +19 -3
- package/dist/types/approvals/sudo-client.d.ts +8 -0
- package/dist/types/approvals/sudo.d.ts +3 -1
- package/dist/types/guests/capture.d.ts +33 -0
- package/dist/types/guests/seats.d.ts +8 -1
- package/dist/types/index.d.ts +4 -2
- package/dist/types/owner.d.ts +3 -1
- package/dist/types/services.d.ts +1 -1
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -164,7 +164,7 @@ The first provider is AWS Bedrock with a Bedrock API key as the bearer token; th
|
|
|
164
164
|
|
|
165
165
|
### In slicc-spectrum
|
|
166
166
|
|
|
167
|
-
`@ai-ecoverse/slicc-spectrum` is an optional peer dependency, `^
|
|
167
|
+
`@ai-ecoverse/slicc-spectrum` is an optional peer dependency, `^2.4.1`. 2.4.1 is the first release with a capture approval (`CaptureApproval`), which the agent's approvals list sends. 1.112.0 makes an approval verdict's `decision` optional, which the agent no longer sends. 1.102.0 types a guest tool approval's `args` and `argsTruncated`, and 1.103.0 shows a device sign-in's `signIn` code and link in Settings. 1.107.0 heads the budget with its provider: the tray's `budget.provider` and the Monitor vital's `provider` and `window` (older releases ignore them). 1.94.0 is the first release with the provider picker (`providers()`, `remove`, `vaultName`, `customBase`, a field's `options` and `value`); 1.94.1 shows a field with `options` as an `sp-picker` on its `value`; 1.95.0 shows a `blocked` provider in the picker as unpickable with “Needs the SLICC extension or CLI”; 1.96.0 registers an MCP token's server URL (`Account.url`) with the vault itself, after a “Connect to {url}?” confirm, and offers Reconnect when the URL moves; and 1.98.0 saves a field's value as its `vaultSetting` on the vault record (`VaultPort.settings`, V3). `test/integration/settings-ui.test.mjs` checks each in a real `<slicc-settings>`: Bedrock's region picker on the stored region, a blocked provider that can't be picked until a CORS-free route appears, the moved note once `mcp.json` points a connected server elsewhere, and that adding Cloudflare Workers AI or Azure (by resource name) puts the key with its tenant fields as the record's vault `settings` (`CLOUDFLARE_ACCOUNT_ID`, `AZURE_OPENAI_RESOURCE_NAME`).
|
|
168
168
|
|
|
169
169
|
`@ai-ecoverse/slicc-agent/spectrum` turns an `AgentConnection` into slicc-spectrum's `AgentPort`, so `<slicc-app>` shows the real agent:
|
|
170
170
|
|
|
@@ -181,7 +181,7 @@ The adapter keeps the replicated transcript and maps it on every update. User, a
|
|
|
181
181
|
|
|
182
182
|
**Older messages.** An agent's view is durable's window, its newest 50 to 100 entries, approval verdicts and other entries the chat doesn't show included, so by itself it holds only the last few turns. The adapter keeps each agent's whole transcript in a pi-durable `ConversationTranscript` instead: every view merges into it, so messages the window drops stay, and a window that jumps ahead (a reconnect, a burst) leaves a gap the adapter fills at once, from its newest side, up to 40 pages (4,000 entries) per gap. A bigger jump keeps only the newest entries, contiguous, and the rest comes back through `older()`, so a gap never downloads a whole conversation. `older(agentId, before)` loads earlier pages of 100 entries through `AgentControl.entries` until at least one message older than the message `before` appears, or the conversation starts, and resolves the messages before `before` (before the first message when `before` is unknown); `messages(agentId)` holds them from then on, and the change emits `messages`. An empty answer means the start is reached, and `hasOlder(agentId)` says whether there is more. Concurrent calls share one load, an agent's older answers never count as unread, a notice stays after the last committed message it followed (not after a reply still streaming, a queued input or a retry, whose ids change), and a new conversation (New chat, a rewind's fork) starts a new transcript. `AgentControl.entries({ agentId, conversation, minEntryId?, maxEntryId?, order?, limit? })` answers `{ conversation, entries, more }`: a page of the agent's fork-aware history (`Conversation.entries()`), at most 200 entries, slimmed like the views (large images become thumbnails; a page waits at most 2 s for its own thumbnails, then answers with a placeholder), and an empty page when `conversation` is no longer the agent's. Owner, control and view-only seats have it. A view-only seat's `image` answers the full image of an entry only while the entry is in a current view, or when that seat itself read it through `entries` and the entry is still in that agent's current conversation (checked again on each call, so a page read before a rewind or a new chat, or by another seat, grants nothing); guests see only their window, and so does an adapter on an older agent whose control service doesn't offer `entries` (`connection.history` is `true` only when it does; `older()` then answers `[]` and `hasOlder()` `false`).
|
|
183
183
|
|
|
184
|
-
Each cone's active conversation is in the session document `slicc.agents` (the root until the first rewind). The host's transcript follows it across forks. Rewinding is refused while the cone itself is running or has queued input, because a fork starts with an empty inbox, but never because its scoops are busy (see Cones and scoops). A background compaction still running on the old branch finishes there. A fork also starts with fresh `pi.usage`. Credential and model errors lead with a plain sentence ("Bedrock rejected the API key.", "This model isn't available with the current account.") and keep the provider's raw error as `detail`, which spectrum (≥ 1.11.0) shows underneath. `busy()` and `queue()` read durable's live and inbox documents. Steering is the default (#4): a send or a steer goes out with `whenBusy: 'steer'`, so while a run is going it joins after the current tool round, and a `queue` send is a follow-up. User messages carry `delivered` from the host's deliveries; entries the host didn't record (from before a reload) count as steered when they follow a tool result. Cones and scoops are below; the freezer and questions come later. Licks show as spectrum's lick cards (below). slicc-spectrum is an optional peer dependency (`^
|
|
184
|
+
Each cone's active conversation is in the session document `slicc.agents` (the root until the first rewind). The host's transcript follows it across forks. Rewinding is refused while the cone itself is running or has queued input, because a fork starts with an empty inbox, but never because its scoops are busy (see Cones and scoops). A background compaction still running on the old branch finishes there. A fork also starts with fresh `pi.usage`. Credential and model errors lead with a plain sentence ("Bedrock rejected the API key.", "This model isn't available with the current account.") and keep the provider's raw error as `detail`, which spectrum (≥ 1.11.0) shows underneath. `busy()` and `queue()` read durable's live and inbox documents. Steering is the default (#4): a send or a steer goes out with `whenBusy: 'steer'`, so while a run is going it joins after the current tool round, and a `queue` send is a follow-up. User messages carry `delivered` from the host's deliveries; entries the host didn't record (from before a reload) count as steered when they follow a tool result. Cones and scoops are below; the freezer and questions come later. Licks show as spectrum's lick cards (below). slicc-spectrum is an optional peer dependency (`^2.4.1`, the lowest whose monitor, tray, panel, guest seat, guest and capture approval (with `args` and `argsTruncated`, and a verdict without `decision`) and profile import types match the agent's; `npm run typecheck` fails on anything older), used for types only, so package managers don't install it next to the agent.
|
|
185
185
|
|
|
186
186
|
Each agent in `list()` has a real `contextFill` and `unread`:
|
|
187
187
|
- **`contextFill`** is the context the agent uses, as a share of its model's `contextWindow` from the settings' model list. The tokens are those of the newest assistant's usage after the active head, counted the way pi-ai's `calculateContextTokens` does (`totalTokens`, or input, output and both cache counts). Aborted and failed turns don't count. After a compaction, the kept turns' usage no longer counts. Until the next turn reports its usage, the fill is estimated the way pi does it, at four characters a token, over the summary and the kept entries (without the system prompt and tools). An unknown model also reads 0. The Monitor's "Fullest context" and its context alerts use the same functions (`src/context.ts`).
|
|
@@ -738,22 +738,33 @@ It prints the tab's stdout and stderr on their own streams and exits with its co
|
|
|
738
738
|
|
|
739
739
|
### Approvals
|
|
740
740
|
|
|
741
|
-
Every approval, of a guest's prompt, of a tool call in a run a guest started,
|
|
741
|
+
Every approval, of a guest's prompt, of a tool call in a run a guest started, of a sudo request, or of a media capture from a run a guest started, is an item in one session document, `slicc.approvals` ([`src/approvals/`](src/approvals/)). That document is the authority: not a lick, which the agent can confirm itself, and not a UI projection, so a settled item stays settled after a reload.
|
|
742
742
|
|
|
743
|
-
- **An item** is `{ id, kind, seat?, agentId, requester, detail, tier, state, decidedBy, device?, answer?, reason?, verdict?, judging?, verdictError?, always, createdAt, expiresAt, decidedAt? }`. `kind` is `guest-message` (`detail: { text, attachments }`), `guest-tool` (`{ tool, summary, arguments?, task? }`)
|
|
743
|
+
- **An item** is `{ id, kind, seat?, agentId, requester, detail, tier, state, decidedBy, device?, answer?, reason?, verdict?, judging?, verdictError?, always, createdAt, expiresAt, decidedAt? }`. `kind` is `guest-message` (`detail: { text, attachments }`), `guest-tool` (`{ tool, summary, arguments?, task? }`) `sudo` (`{ command, target?, cwd?, alwaysScope?, stdin?, rootOnly?, writable? }`) or `capture` (`{ what, mode, seconds?, system?, microphone?, device?, program }`, see Media capture). `judging` is `true` while the judge runs; `verdictError` says why there is no verdict. `requester` is `{ kind: 'guest' | 'agent' | 'user', name, seat?, agentId?, where?, device? }`.
|
|
744
744
|
- **`state`** is `pending`, `approved` (with `answer` `once` or `always`), `rejected` (someone said no), `unanswered` (nobody decided: it timed out or couldn't be routed) or `withdrawn` (the requester went away). `reason` is a field, never a state: a person's own words, or `timeout`, `unknown-tier`, `unroutable`, `unknown-answer`, `restart`, `revoked`, `aborted` or `disconnected`. `decidedBy` is `owner`, `follower`, `judge` or `host`.
|
|
745
|
-
- **`tier`** says who answers: `user` (a person, through `decide`), `agent` (the automatic judge), `cone` or `scoop:<name>`. A tier the agent doesn't know settles at once as `unanswered` with `unknown-tier`, and so does `cone` for a guest's tool call (`unroutable`), because a run can't approve its own gate. A person answers only `user` items, the judge only `agent` ones.
|
|
746
|
-
- **The rules:** the first decision wins, and a later one, or one past `expiresAt`, is refused ("Someone else already answered this.", "This request timed out.", "This request was withdrawn."). An answer other than `once`, `always` or `deny` is a deny (`unknown-answer`). `always` is `false` for anything a guest triggered unless the approval policy's `guests.always` offers it for that kind (by default it doesn't). A `sudo` item starts with `always: false` and gets `true` only from a verdict (see The automatic judge), and `decide(id, 'always')` on an item without it is refused and leaves it pending. For a guest's tool call, Always records an exact rule on the seat (see Guest seats).
|
|
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.
|
|
745
|
+
- **`tier`** says who answers: `user` (a person, through `decide`), `agent` (the automatic judge), `cone` or `scoop:<name>`. A tier the agent doesn't know settles at once as `unanswered` with `unknown-tier`, and so does `cone` for a guest's tool call or capture (`unroutable`), because a run can't approve its own gate. A person answers only `user` items, the judge only `agent` ones.
|
|
746
|
+
- **The rules:** the first decision wins, and a later one, or one past `expiresAt`, is refused ("Someone else already answered this.", "This request timed out.", "This request was withdrawn."). An answer other than `once`, `always` or `deny` is a deny (`unknown-answer`). `always` is `false` for anything a guest triggered unless the approval policy's `guests.always` offers it for that kind (by default it doesn't). A `sudo` or `capture` item starts with `always: false` and gets `true` only from a verdict (see The automatic judge), and `decide(id, 'always')` on an item without it is refused and leaves it pending. For a guest's tool call, Always records an exact rule on the seat (see Guest seats), and for a capture a narrow one (see Media capture).
|
|
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` and `capture` items are withdrawn (`restart`), because a reload ends the kernel's processes and the page's request. 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 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.
|
|
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 `capture` item is a `CaptureApproval`, with the guest items' `agentId`, `agentName`, `always` and verdict fields and the item's `detail` as it is (`what`, `mode`, `seconds?`, `system?`, `microphone?`, `device?`, `program`), which spectrum 2.4.1 on shows as its capture line. 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.
|
|
754
754
|
- **Answers:** `approved` resolves its answer, a judge's rejection resolves a `SudoDenial`, `{ answer: 'deny', message: 'sudo: denied by the approval judge: <reason>' }` (the prefix is `JUDGE_DENIED`), so the shell can say who refused, and anything else `deny`. A kernel that doesn't know the object denies it as it denies any answer but `once` and `always`. Every device of the owner answers with the same powers: a follower, with or without Control, sees the same item, Always included when the verdict offers it, and its `always` counts as the owner tab's would. `device` on the item names the device that answered, from `owner.port({ device })`.
|
|
755
755
|
- **Ends:** when the kernel aborts `signal` (`withdrawn`) the item is withdrawn, and on `expired` the page keeps its link until the record's own timeout settles it (`unanswered`), so it never reads as withdrawn. When the page's link closes the worker withdraws its open sudo items (`disconnected`). A restart or release of the owner first ends the old worker, then denies the requests still waiting, so the old worker never sees their links close, and the next worker withdraws their items (`restart`). The kernel already allows one pending request per user.
|
|
756
756
|
- **Scoops:** a scoop's request sends its cone a `sudo-request` lick without actions once a person has to answer it (at once on the `user` tier, after the judge hands it on with the `agent` policy, never when the judge decides), so the cone knows the scoop waits and can't approve it itself. A cone that asks gets none: it waits in its own command.
|
|
757
|
+
- **Media capture:** `AgentOwner.approveCapture(request, { signal, where? })` takes a `/dev/embedder` request as bios's hook receives it, `{ kind, options, stamp }`, and resolves `once`, `always`, `deny` or `{ answer: 'deny', message }`. It rejects with `code: 'EAGAIN'` when the agent can't answer (released, restarting, or a worker without it) and when `stamp.users` is neither `report` nor `enforce`, since the agent can't tell who started the program then, so bios falls back to its own prompt.
|
|
758
|
+
- **Who started it** comes only from the kernel's stamp: its `tags`, plus the taints the agent has seen alive for that process (`stamp.pid`) since it first saw it, the `recent` set the `agent` CLI uses ([`src/kernel/lineage.ts`](src/kernel/lineage.ts)). So a clean process that a guest's process sets off counts as the guest's while that cover holds: while a tagged process of the guest, or a `crontab` line it installed, lives, and for about 2 s after it ends (the agent's `ps` reads). Something the guest planted that runs later, such as a sprinkle CGI, a `~/.bashrc` line or a git hook, is attributed to whoever starts it then. As for the `agent` CLI, this is conservative: while a guest's leftover job or `crontab` line lives, everyone's captures are reviewed too. When the agent has no lineage provider or can't read the process's lineage, it denies.
|
|
759
|
+
- **Shell clients:** `stamp.pid` is the process that wrote the header line, so that process must stay until the reply is read. A header written by a short-lived child (`cat req >&3`) has no lineage by then and is denied; write it from the shell itself (`read -r line < req; printf '%s\n' "$line" >&3`).
|
|
760
|
+
- **Untainted runs are never asked:** a request with no guest taint, from any cone, scoop or terminal, resolves `once` at once, with no item, no dialog and no judge call, because every agent may capture.
|
|
761
|
+
- **A run a guest started** (its taint tags, read with `taggedTaints`) gets a `capture` item for that guest's seat, decided exactly as that seat's tool calls are: the seat's tools gate (`user`, `agent` or `scoop:<name>`), within `guests.allowedToolGates`, the judge first where that gate routes to it. A seat that ended once its item is filed withdraws the item (`revoked`) and denies. With several taints each seat is asked in turn, and the first that denies decides.
|
|
762
|
+
- **A seat whose tools gate is `off`** has no review for captures, so a capture any such seat taints rejects with `EAGAIN`: no item, no judge call and no rule, and bios shows its own Allow once / Deny dialog, as before this port.
|
|
763
|
+
- **Detail:** `capture.screen` and `capture.camera` are `screen` or `camera`, `video` for a `video/…` `type` (with `seconds` from `duration`, and `system` and `microphone` when asked) and `still` otherwise; `audio.record` is `microphone` and `audio`, `seconds` from `seconds`. `device` is `request.label`, the device's label bios resolves from the `deviceId`, cleaned, and left out without one, so an id is never shown. `program` is `stamp.argv0`, else `a program`. Any other kind is `{ answer: 'deny', message: 'capture: not a capture kind' }`.
|
|
764
|
+
- **Answers:** `approved` resolves its answer, and a judge's rejection resolves `{ answer: 'deny', message: 'capture: denied by the approval judge: <reason>' }`. Any other deny for a seat that only the `recent` set brought in, or for a seat that has ended or been revoked, resolves `{ answer: 'deny', message: "capture: a guest's job or crontab line is still running" }`. Anything else is `deny`.
|
|
765
|
+
- **Always** records a narrow rule on the seat, `alwaysCaptures: [{ approval, what, mode, by, at }]`, shown on `GuestSeat` and removed by `AgentControl.guestAlwaysForget(seat, approval)` or with the seat. A later capture of the same `what` and `mode` from that seat resolves `always` without an item while `guests.always.tools` is on; anything else is asked.
|
|
766
|
+
- **Ends:** when bios aborts `signal`, or the page's link closes, the item is withdrawn (`aborted`).
|
|
767
|
+
- **In spectrum** (2.4.1 on), a capture item that waits for a person is listed like a guest tool call, as a `CaptureApproval` (see In spectrum above), so it shows in the same approvals dialog.
|
|
757
768
|
- **With the host's own approvals:** bios has its own `approvals` port for sudo, and a page that spreads `{ ...bios, ...createAgentModel(connection) }` would lose it. Pass that port in instead, as `createAgentModel(connection, { approvals: biosPort })`. The returned port then lists both sets, oldest first, sends `decide` to whichever port listed the id, and passes on both ports' `approvals` and `ended` events. It has `decide` when either side can answer; asked for an item its owner can't answer, it rejects with "This request can't be answered in this tab." Without the option, it lists only the agent's items.
|
|
758
769
|
- **Secret requests** (a program's `ask` on `/dev/sealed`, such as `fnox set NAME --ask` or `sealed ask NAME`) are bios's approvals of kind `secret`, and only a person answers them. They come in through `approvals: biosPort` and go out unchanged: the adapter lists them with the rest, oldest first, sends their `decide` (Deny, which cancels the vault's request) to bios, and passes on bios's `ended`. The value is typed, and a reveal allowed, only in the vault's own frame inside the dialog, so neither the agent nor the page sees it. They are never items in `slicc.approvals`, so the judge never gives them a verdict or an answer, whatever `sudo.approver` says, and `AgentOwner.approve` refuses them with `EAGAIN`.
|
|
759
770
|
|
|
@@ -766,10 +777,12 @@ The judge ([`src/approvals/judge.ts`](src/approvals/judge.ts)) gives a request a
|
|
|
766
777
|
- **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
778
|
- **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
779
|
- **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.
|
|
780
|
+
- **Captures** are a guest kind: one call, no action, intent or veto calls. `CAPTURE_QUESTIONS` are the guest `level` and `aligned` with the capture facts (`request.capture`) added, plus a capture `always`: could a later capture of the same `what` and `mode` by this guest, of any length, audio or device, record more than the owner would give unasked. So `always` holds when a classifier puts P(that) at 0.2 or less, or the chat model answers `false`. Guest message and tool verdicts never carry it, and the judge itself still answers a capture only once or deny.
|
|
769
781
|
- **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.
|
|
770
782
|
- **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).
|
|
771
783
|
- **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.
|
|
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
|
|
784
|
+
- **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 `capture` item offers it on the same verdict, for a person, and only while `guests.always.tools` is on. Other guest items' Always stays under `guests.always`.
|
|
785
|
+
- **A capture** is judged on `request.capture`, the facts of what granting it records: `asks` says it in plain words ("a video of the screen, window or tab the person picks, for 30 seconds, with the microphone"), with `what`, `mode`, `seconds` (`null`: until the program stops), `system` and `microphone`. The program's name and the device are the requester's, so they are in `request.untrusted`. The owner's intent is read from the guest's conversation, as for a guest's tool call.
|
|
773
786
|
- **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.
|
|
774
787
|
- **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.
|
|
775
788
|
- **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.
|
|
@@ -825,7 +838,7 @@ All the limits on approvals and guests live in one owner-changeable policy, the
|
|
|
825
838
|
|
|
826
839
|
A guest seat (plan D13, PR 19) is a revocable seat on one cone: the guest sees that cone's live transcript and has a composer, and nothing else.
|
|
827
840
|
|
|
828
|
-
- **Minting.** The tray hub mints the seat and its one-time URL (v6's routes, D10); the page hands the agent adapter its routes: `createAgentModel(connection, { guests: { mint({ label, expiresAt, gates, agentId }) → { id, url }, revoke(id) } })`. Its `guests` port (spectrum's `GuestPort`) mints through the hub, then opens the seat in the worker with `AgentControl.guestOpen({ id, label, agentId, expiresAt, gates })`; if the worker refuses, the hub's seat is revoked again. `list()` is the transcript's `guests` state (`{ id, label, agentId, createdAt, expiresAt, gates, connected, pending, alwaysTools }`), and the URL is returned once and never kept. Its `alwaysTools` rules carry no `argumentsHash`. `unavailable()` says "Inviting guests needs the tray hub." without a hub, and "Only the owner's devices can invite guests." on a guest. Every owner device can invite, with or without Control. `gates()` (spectrum's `GuestPort.gates?()`) lists the gates the approval policy allows for messages and tools, in display order, for the invite pickers; `scoop:*`, for "any scoop", shows only when the policy offers the scoop tier.
|
|
841
|
+
- **Minting.** The tray hub mints the seat and its one-time URL (v6's routes, D10); the page hands the agent adapter its routes: `createAgentModel(connection, { guests: { mint({ label, expiresAt, gates, agentId }) → { id, url }, revoke(id) } })`. Its `guests` port (spectrum's `GuestPort`) mints through the hub, then opens the seat in the worker with `AgentControl.guestOpen({ id, label, agentId, expiresAt, gates })`; if the worker refuses, the hub's seat is revoked again. `list()` is the transcript's `guests` state (`{ id, label, agentId, createdAt, expiresAt, gates, connected, pending, alwaysTools, alwaysCaptures }`), and the URL is returned once and never kept. Its `alwaysTools` rules carry no `argumentsHash`. `unavailable()` says "Inviting guests needs the tray hub." without a hub, and "Only the owner's devices can invite guests." on a guest. Every owner device can invite, with or without Control. `gates()` (spectrum's `GuestPort.gates?()`) lists the gates the approval policy allows for messages and tools, in display order, for the invite pickers; `scoop:*`, for "any scoop", shows only when the policy offers the scoop tier.
|
|
829
842
|
- **The record.** Seats live in the session document `slicc.guests`, so they survive reloads and restarts: id, label (control characters stripped, at most 64 characters), cone, expiry (at most the policy's `guests.maxSeatDays`, 30 by default), the two gates (`user`, `agent`, `cone`, `scoop:<name>` or `off`, fixed when the seat is opened and checked then against the policy's `allowedMessageGates` and `allowedToolGates`; by default the tools gate can't be `off` or `cone`, from any caller: "A guest's tool calls need a review: by a person, the judge or a scoop.") and an epoch. Revoking (`guestRevoke(id)`) keeps a tombstone, bumps the epoch, withdraws the guest's messages still queued in the cone, and ends every guest link of the seat (`invalidatePrincipal`). An expired seat ends the same way at its expiry. Tombstones go 365 days after they end, the longest a seat can be opened for.
|
|
830
843
|
- **Joining.** The hub resolves the guest's token to the seat's id and label, and the owner page opens `owner.port({ guest: { id, label } })` and bridges it like a follower's. Before Chord sees the link, the worker checks that the seat exists, isn't revoked or expired, and has that label; otherwise it closes the port. The link's principal is `{ seat: 'guest', link, guest: { id, name, epoch } }`, and anything else the port asks for (`readOnly: false`, `pages`) is ignored. A guest link has at most four calls in flight (Chord's `maxCalls`): further ones are answered at once with `unavailable` ("Too many calls in progress on this connection (4)"), and the link stays open. A revoked guest leaves nothing behind on the host: Chord 1.3 drops each disposed object, where 1.2 kept one per guest principal (seat and epoch), with its link, until the worker restarted.
|
|
831
844
|
- **What a guest gets.** Every contract served from the agent's host refuses a guest principal (`forbidden`) unless its factory is opened with `openToGuests`, so a contract added later is closed to guests until someone opens it. The only open one is `slicc.agent.guest`: its `guest` variant has the shared cone's transcript (its user, assistant, tool and compaction entries; `pi.live`; `pi.agent`'s model and thinking level; and only the guest's own queued messages) and the seat, plus `propose({ text, requestId })`. Everyone else gets its empty `none` variant.
|
|
@@ -835,7 +848,7 @@ A guest seat (plan D13, PR 19) is a revocable seat on one cone: the guest sees t
|
|
|
835
848
|
- **The tier decides.** `off` passes, if the policy's `allowedToolGates` still allows it (it doesn't by default). A tier the policy no longer allows is refused with the policy's sentence. A tier the agent doesn't know, a guest input with no recorded submission, and a seat that has ended all deny. So does `scoop:<name>`, at once, because no scoop can answer an approval yet. Otherwise the hook files a `guest-tool` approval on that tier (`user`, or `agent` for the judge), with `detail: { tool, summary, arguments, task }`, and waits for it on the approvals document, honouring the abort signal. If the seat ends while the call is filed or reviewed, the item is withdrawn and the call blocked, even after an approval. Anything else but approve blocks too, and the model sees `Tool call blocked: <reason>`, such as "The owner declined this tool call in a run a guest started." with the owner's reason.
|
|
836
849
|
- **Once per call.** The approval's id is a memo of the tool task (`slicc.guest-tool:<seat>:<tier>`), so after a crash or reload the hook reruns before the tool runs and rejoins the same review, without asking again.
|
|
837
850
|
- **Abort.** Once a waiting call's task ends without an answer, its approval is withdrawn (`aborted`), so aborting the conversation withdraws its pending guest tool calls. That also covers the calls of a script abandoned by a restart.
|
|
838
|
-
- **Always** is offered only while `guests.always.tools` is true. An Always answer adds a rule to the seat's `alwaysTools`: `{ approval, tool, argumentsHash, arguments, by, at }`. `argumentsHash` is the hex SHA-256 of the call's canonical JSON (keys sorted), and `arguments` is that JSON scrubbed of secrets, for display only, so no secret from the call is kept on the seat or published in the `guests` list. The hash stays in the seat document: the `guests` list leaves it out, because an unsalted hash of a short secret can be guessed offline. Rules from before the hash are hashed and scrubbed when the session opens. Later calls from that seat with the same tool and arguments of the same hash pass without asking, while the policy still offers Always. The transcript's `guests` list shows each seat's rules. `AgentControl.guestAlwaysForget(seat, approval)`, for owner devices, removes one, and revoking the seat drops them all.
|
|
851
|
+
- **Always** is offered only while `guests.always.tools` is true. An Always answer adds a rule to the seat's `alwaysTools`: `{ approval, tool, argumentsHash, arguments, by, at }`. `argumentsHash` is the hex SHA-256 of the call's canonical JSON (keys sorted), and `arguments` is that JSON scrubbed of secrets, for display only, so no secret from the call is kept on the seat or published in the `guests` list. The hash stays in the seat document: the `guests` list leaves it out, because an unsalted hash of a short secret can be guessed offline. Rules from before the hash are hashed and scrubbed when the session opens. Later calls from that seat with the same tool and arguments of the same hash pass without asking, while the policy still offers Always. The transcript's `guests` list shows each seat's rules. `AgentControl.guestAlwaysForget(seat, approval)`, for owner devices, removes one (a capture's `alwaysCaptures` rule too), and revoking the seat drops them all.
|
|
839
852
|
- **Revocation and expiry clean up alike.** Revoking or expiring a seat withdraws its queued input and its pending approvals; a proposal still being placed is serialised with them per seat and rechecks the seat right before it's placed, so nothing lands after a revoke.
|
|
840
853
|
- **Every owner device manages guests.** The owner's pages and followers, with or without Control, open, list and revoke seats alike.
|
|
841
854
|
- **A guest managing guests** is refused by the approval policy (`guests.manageGuests`, `deny`). The guest contract has `guestOpen` and `guestRevoke`, and both are refused with `forbidden` ("The owner's guest policy doesn't let guests manage guests."). The approval policy itself is never a guest's to change: its write is on `AgentControl`, which a guest can't reach.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const UNATTRIBUTED = "unavailable";
|
|
2
|
+
const objectOf = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
3
|
+
const stampOf = (request) => objectOf(objectOf(request).stamp);
|
|
4
|
+
function attributed(request) {
|
|
5
|
+
const { users } = stampOf(request);
|
|
6
|
+
return users === "report" || users === "enforce";
|
|
7
|
+
}
|
|
8
|
+
export {
|
|
9
|
+
UNATTRIBUTED,
|
|
10
|
+
attributed,
|
|
11
|
+
stampOf
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=attributed.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/approvals/attributed.ts"],
|
|
4
|
+
"sourcesContent": ["export const UNATTRIBUTED = 'unavailable';\n\nconst objectOf = (value: unknown): Record<string, unknown> =>\n value && typeof value === 'object' && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n\nexport const stampOf = (request: unknown): Record<string, unknown> =>\n objectOf(objectOf(request).stamp);\n\nexport function attributed(request: unknown): boolean {\n const { users } = stampOf(request);\n return users === 'report' || users === 'enforce';\n}\n"],
|
|
5
|
+
"mappings": "AAAO,MAAM,eAAe;AAE5B,MAAM,WAAW,CAAC,UAChB,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACrD,QACD,CAAC;AAEA,MAAM,UAAU,CAAC,YACtB,SAAS,SAAS,OAAO,EAAE,KAAK;AAE3B,SAAS,WAAW,SAA2B;AACpD,QAAM,EAAE,MAAM,IAAI,QAAQ,OAAO;AACjC,SAAO,UAAU,YAAY,UAAU;AACzC;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/approvals/index.js
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
cleanReason,
|
|
11
11
|
gateOf,
|
|
12
12
|
guestKind,
|
|
13
|
+
heldKind,
|
|
13
14
|
knownTier,
|
|
14
15
|
MAX_DELAY,
|
|
15
16
|
prune,
|
|
@@ -34,7 +35,7 @@ function mark(item, how, at) {
|
|
|
34
35
|
delete item.judging;
|
|
35
36
|
if (how.reason) item.reason = how.reason;
|
|
36
37
|
}
|
|
37
|
-
const offered = (options, draft) => guestKind(draft.kind) ? options.guestAlways?.(draft.kind) === true : false;
|
|
38
|
+
const offered = (options, draft) => guestKind(draft.kind) && draft.kind !== "capture" ? options.guestAlways?.(draft.kind) === true : false;
|
|
38
39
|
const judgedKind = (kind, tier) => kind === "sudo" || tier === "agent" || tier === "user";
|
|
39
40
|
function detailOf(draft) {
|
|
40
41
|
if (draft.kind !== "sudo" || draft.always !== false) return draft.detail;
|
|
@@ -81,6 +82,7 @@ const judgedIn = (id, judged, now) => (doc) => {
|
|
|
81
82
|
if (routed === "ask") {
|
|
82
83
|
item.tier = "user";
|
|
83
84
|
if (item.kind === "sudo") item.always = alwaysOffered(item);
|
|
85
|
+
if (item.kind === "capture") item.always = alwaysOffered(item) && judged.offer === true;
|
|
84
86
|
return copy([item])[0];
|
|
85
87
|
}
|
|
86
88
|
const at = now();
|
|
@@ -110,9 +112,10 @@ function judgeRunner(run) {
|
|
|
110
112
|
};
|
|
111
113
|
if (signal?.aborted) return abort();
|
|
112
114
|
signal?.addEventListener("abort", abort, { once: true });
|
|
113
|
-
const
|
|
115
|
+
const found = await judgedBy(judge, run.present, item, using, now);
|
|
114
116
|
signal?.removeEventListener("abort", abort);
|
|
115
117
|
if (gone || run.closed()) return;
|
|
118
|
+
const judged = { ...found, offer: run.guestAlways?.(item.kind) === true };
|
|
116
119
|
const after = await serial(judgedIn(item.id, judged, now), BACKGROUND_CONTEXT).catch(
|
|
117
120
|
() => void 0
|
|
118
121
|
);
|
|
@@ -176,7 +179,7 @@ async function attachApprovals(options, context = BACKGROUND_CONTEXT) {
|
|
|
176
179
|
const startup = await write((doc) => {
|
|
177
180
|
for (const item of doc.items) {
|
|
178
181
|
if (item.state !== "pending") continue;
|
|
179
|
-
if (item.kind
|
|
182
|
+
if (heldKind(item.kind))
|
|
180
183
|
settle(item, { state: "withdrawn", by: "host", reason: REASONS.restart });
|
|
181
184
|
else if (item.expiresAt <= now())
|
|
182
185
|
settle(item, { state: "unanswered", by: "host", reason: REASONS.timeout });
|
|
@@ -244,6 +247,7 @@ async function attachApprovals(options, context = BACKGROUND_CONTEXT) {
|
|
|
244
247
|
const judging = judgeRunner({
|
|
245
248
|
serial,
|
|
246
249
|
present: options.present,
|
|
250
|
+
guestAlways: options.guestAlways,
|
|
247
251
|
now,
|
|
248
252
|
closed: () => closed
|
|
249
253
|
});
|
|
@@ -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 { 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,
|
|
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 heldKind,\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) && draft.kind !== 'capture'\n ? options.guestAlways?.(draft.kind) === true\n : 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; offer?: 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 if (item.kind === 'capture') item.always = alwaysOffered(item) && judged.offer === true;\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 guestAlways: ApprovalsAttach['guestAlways'];\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 found = await judgedBy(judge, run.present, item, using, now);\n signal?.removeEventListener('abort', abort);\n if (gone || run.closed()) return;\n const judged = { ...found, offer: run.guestAlways?.(item.kind) === true };\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 (heldKind(item.kind))\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 guestAlways: options.guestAlways,\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,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,KAAK,MAAM,SAAS,YACpC,QAAQ,cAAc,MAAM,IAAI,MAAM,OACtC;AAEN,MAAM,aAAa,CAAC,MAAoB,SACtC,SAAS,UAAU,SAAS,WAAW,SAAS;AAElD,SAAS,SAAS,OAA+C;AAC/D,MAAI,MAAM,SAAS,UAAU,MAAM,WAAW,MAAO,QAAO,MAAM;AAClE,SAAO,EAAE,GAAG,MAAM,QAAQ,UAAU,MAAM;AAC5C;AAEA,SAAS,MACP,OACA,IACA,KACA,SACU;AACV,QAAM,OAAO,OAAO,MAAM,MAAM,MAAM,MAAM,aAAa,QAAQ,eAAe,CAAC,CAAC;AAClF,QAAM,OAAO;AAAA,IACX,GAAG;AAAA,IACH,QAA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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;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/approvals/judge.js
CHANGED
|
@@ -108,6 +108,21 @@ const GUEST_GROUP = {
|
|
|
108
108
|
}
|
|
109
109
|
}
|
|
110
110
|
};
|
|
111
|
+
const CAPTURE_FACTS = "request.capture says what granting the request records: asks says it plainly, what is screen, camera or microphone, mode is still, video or audio, seconds is how long it runs (null: until the program stops), and system and microphone say which audio comes with it. The program's name and the device are inside request.untrusted, because the requester chose them.";
|
|
112
|
+
const CAPTURE_GROUP = {
|
|
113
|
+
about: `${INSTRUCTIONS} ${CAPTURE_FACTS}`,
|
|
114
|
+
questions: {
|
|
115
|
+
...GUEST_GROUP.questions,
|
|
116
|
+
always: {
|
|
117
|
+
type: "bool",
|
|
118
|
+
instructions: "Allowing it always lets this guest make every later capture of the same what and mode without asking, whatever its length, audio or device. Could such a later capture record something the owner would not let this guest have without being asked?",
|
|
119
|
+
criteria: {
|
|
120
|
+
true: "yes: a longer capture, another device or more audio of the same kind could record more than the owner would give this guest unasked",
|
|
121
|
+
false: "no: every later capture of the same kind is as fine as this one"
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
};
|
|
111
126
|
const asked = ({ about, questions }) => Object.fromEntries(
|
|
112
127
|
Object.entries(questions).map(([id, question]) => [
|
|
113
128
|
id,
|
|
@@ -115,11 +130,13 @@ const asked = ({ about, questions }) => Object.fromEntries(
|
|
|
115
130
|
])
|
|
116
131
|
);
|
|
117
132
|
const JUDGE_QUESTIONS = asked(GUEST_GROUP);
|
|
133
|
+
const CAPTURE_QUESTIONS = asked(CAPTURE_GROUP);
|
|
118
134
|
const SUDO_QUESTIONS = asked(SUDO_GROUP);
|
|
119
135
|
const INTENT_QUESTIONS = asked(INTENT_GROUP);
|
|
120
136
|
const FORBID_QUESTIONS = asked(FORBID_GROUP);
|
|
121
137
|
function questionsOf(item) {
|
|
122
|
-
|
|
138
|
+
if (item.kind === "sudo") return SUDO_QUESTIONS;
|
|
139
|
+
return item.kind === "capture" ? CAPTURE_QUESTIONS : JUDGE_QUESTIONS;
|
|
123
140
|
}
|
|
124
141
|
function fenced(text, nonce) {
|
|
125
142
|
const tag = `untrusted-${nonce}`;
|
|
@@ -139,11 +156,50 @@ function sudoText(detail) {
|
|
|
139
156
|
...paths
|
|
140
157
|
].join("\n");
|
|
141
158
|
}
|
|
159
|
+
const SUBJECT = {
|
|
160
|
+
screen: "the screen, window or tab the person picks",
|
|
161
|
+
camera: "the camera",
|
|
162
|
+
microphone: "the microphone"
|
|
163
|
+
};
|
|
164
|
+
function audioOf(detail) {
|
|
165
|
+
if (detail.mode !== "video") return "";
|
|
166
|
+
if (detail.system && detail.microphone) return ", with the system's audio and the microphone";
|
|
167
|
+
if (detail.system) return ", with the system's audio";
|
|
168
|
+
return detail.microphone ? ", with the microphone" : ", without audio";
|
|
169
|
+
}
|
|
170
|
+
function captureAsks(detail) {
|
|
171
|
+
const subject = SUBJECT[detail.what];
|
|
172
|
+
if (detail.mode === "still") return `a still image of ${subject}`;
|
|
173
|
+
const made = detail.mode === "video" ? `a video of ${subject}` : `a recording of ${subject}`;
|
|
174
|
+
const length = detail.seconds === void 0 ? ", until the program stops" : `, for ${detail.seconds} seconds`;
|
|
175
|
+
return `${made}${length}${audioOf(detail)}`;
|
|
176
|
+
}
|
|
177
|
+
function captureText(detail) {
|
|
178
|
+
return [
|
|
179
|
+
`program: ${JSON.stringify(detail.program)}`,
|
|
180
|
+
...detail.device === void 0 ? [] : [`device: ${JSON.stringify(detail.device)}`]
|
|
181
|
+
].join("\n");
|
|
182
|
+
}
|
|
142
183
|
function untrustedOf(item) {
|
|
143
184
|
if (item.kind === "guest-message") return item.detail.text;
|
|
144
185
|
if (item.kind === "guest-tool") return `${item.detail.tool}: ${item.detail.summary}`;
|
|
186
|
+
if (item.kind === "capture") return captureText(item.detail);
|
|
145
187
|
return sudoText(item.detail);
|
|
146
188
|
}
|
|
189
|
+
function captureContext(item) {
|
|
190
|
+
if (item.kind !== "capture") return {};
|
|
191
|
+
const { detail } = item;
|
|
192
|
+
return {
|
|
193
|
+
capture: {
|
|
194
|
+
asks: captureAsks(detail),
|
|
195
|
+
what: detail.what,
|
|
196
|
+
mode: detail.mode,
|
|
197
|
+
seconds: detail.seconds ?? null,
|
|
198
|
+
system: detail.system === true,
|
|
199
|
+
microphone: detail.microphone === true
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
}
|
|
147
203
|
function sudoContext(item) {
|
|
148
204
|
if (item.kind !== "sudo") return {};
|
|
149
205
|
const { stdin, rootOnly, writable } = item.detail;
|
|
@@ -167,7 +223,8 @@ function judgeState(item, intent, nonce) {
|
|
|
167
223
|
kind: item.kind,
|
|
168
224
|
requester: { kind: item.requester.kind, name: item.requester.name },
|
|
169
225
|
untrusted: fenced(untrustedOf(item), nonce),
|
|
170
|
-
...sudoContext(item)
|
|
226
|
+
...sudoContext(item),
|
|
227
|
+
...captureContext(item)
|
|
171
228
|
},
|
|
172
229
|
owner: ownerState(intent)
|
|
173
230
|
};
|
|
@@ -200,7 +257,8 @@ function verdictOf(result, model) {
|
|
|
200
257
|
return verdict ? { verdict } : { error: "the judge gave no usable answer" };
|
|
201
258
|
}
|
|
202
259
|
function guestVerdict(answers, model, via) {
|
|
203
|
-
const { level: chosen, aligned: fit } = answers;
|
|
260
|
+
const { level: chosen, aligned: fit, always: more } = answers;
|
|
261
|
+
const replay = more?.type === "bool" ? unit(more.probability) : void 0;
|
|
204
262
|
const level = chosen?.type === "choice" ? levelOf(chosen.probabilities) : void 0;
|
|
205
263
|
const routine = chosen?.type === "choice" ? unit(chosen.probabilities.routine) : void 0;
|
|
206
264
|
const aligned = fit?.type === "bool" ? unit(fit.probability) : void 0;
|
|
@@ -208,6 +266,7 @@ function guestVerdict(answers, model, via) {
|
|
|
208
266
|
return {
|
|
209
267
|
level,
|
|
210
268
|
...via === "classifier" ? { routine, aligned } : { aligned: aligned >= JUDGE_CUT },
|
|
269
|
+
...replay === void 0 ? {} : { always: clears(1 - replay, JUDGE_ALWAYS) },
|
|
211
270
|
reason: fallbackReason(level),
|
|
212
271
|
via,
|
|
213
272
|
model
|
|
@@ -346,7 +405,8 @@ ${[about, ...Object.entries(questions).map(([id, q]) => questionText(id, q))].jo
|
|
|
346
405
|
|
|
347
406
|
${ANSWER}`;
|
|
348
407
|
function judgePrompt(item) {
|
|
349
|
-
|
|
408
|
+
if (item.kind === "sudo") return promptOf(`${REVIEW} ${SUDO_FACTS}`, SUDO_GROUP);
|
|
409
|
+
return item.kind === "capture" ? promptOf(REVIEW, CAPTURE_GROUP) : promptOf(INSTRUCTIONS, GUEST_GROUP);
|
|
350
410
|
}
|
|
351
411
|
const FORBID_PROMPT = promptOf(REVIEW, FORBID_GROUP);
|
|
352
412
|
const INTENT_PROMPT = promptOf(
|
|
@@ -380,6 +440,7 @@ function chatAnswers(text, questions) {
|
|
|
380
440
|
}
|
|
381
441
|
const CHAT_QUESTIONS = {
|
|
382
442
|
guest: GUEST_GROUP.questions,
|
|
443
|
+
capture: CAPTURE_GROUP.questions,
|
|
383
444
|
sudo: SUDO_GROUP.questions,
|
|
384
445
|
intent: INTENT_GROUP.questions,
|
|
385
446
|
forbidden: FORBID_GROUP.questions
|
|
@@ -435,6 +496,7 @@ function deadline(context, ms) {
|
|
|
435
496
|
};
|
|
436
497
|
}
|
|
437
498
|
const sum = (...costs) => costs.every((cost) => cost == null) ? null : costs.reduce((a, b) => a + (b ?? 0), 0);
|
|
499
|
+
const guestAsk = (item) => item.kind === "capture" ? "capture" : "guest";
|
|
438
500
|
function approvalJudge(options) {
|
|
439
501
|
const nonce = options.nonce ?? (() => crypto.randomUUID().replaceAll("-", ""));
|
|
440
502
|
const intents = /* @__PURE__ */ new Map();
|
|
@@ -502,12 +564,13 @@ ${JSON.stringify(state)}`;
|
|
|
502
564
|
const model = classifier ? nameOf(prepared.ref) : nameOf(chat);
|
|
503
565
|
const asking = {
|
|
504
566
|
guest: [JUDGE_QUESTIONS, judgePrompt(item)],
|
|
567
|
+
capture: [CAPTURE_QUESTIONS, judgePrompt(item)],
|
|
505
568
|
sudo: [SUDO_QUESTIONS, judgePrompt(item)],
|
|
506
569
|
forbidden: [FORBID_QUESTIONS, FORBID_PROMPT]
|
|
507
570
|
};
|
|
508
571
|
const ask = (state, kind) => classifier ? classify(item, classifier, state, asking[kind][0], clock) : chatAsk(item, chat, asking[kind][1], state, CHAT_QUESTIONS[kind], clock);
|
|
509
572
|
if (item.kind !== "sudo") {
|
|
510
|
-
const got = await ask(judgeState(item, intent, nonce()),
|
|
573
|
+
const got = await ask(judgeState(item, intent, nonce()), guestAsk(item));
|
|
511
574
|
if ("error" in got) return got;
|
|
512
575
|
const verdict2 = guestVerdict(got.answers, model, via);
|
|
513
576
|
return verdict2 ? { verdict: verdict2, cost: got.cost } : { error: "the judge gave no usable answer", cost: got.cost };
|
|
@@ -583,6 +646,7 @@ function judgeSpender(conversation) {
|
|
|
583
646
|
export {
|
|
584
647
|
ACTIONS,
|
|
585
648
|
ASK_MIN_MS,
|
|
649
|
+
CAPTURE_QUESTIONS,
|
|
586
650
|
CHAT_QUESTIONS,
|
|
587
651
|
FORBID_PROMPT,
|
|
588
652
|
FORBID_QUESTIONS,
|
|
@@ -613,6 +677,8 @@ export {
|
|
|
613
677
|
actionState,
|
|
614
678
|
approvalJudge,
|
|
615
679
|
barOf,
|
|
680
|
+
captureAsks,
|
|
681
|
+
captureContext,
|
|
616
682
|
chatAnswers,
|
|
617
683
|
fallbackReason,
|
|
618
684
|
fenced,
|