@ai-ecoverse/slicc-agent 7.34.3 → 7.35.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.
Files changed (57) hide show
  1. package/README.md +25 -11
  2. package/dist/agent.js +4 -0
  3. package/dist/agent.js.map +2 -2
  4. package/dist/approvals/index.js +4 -1
  5. package/dist/approvals/index.js.map +2 -2
  6. package/dist/approvals/judge.js +2 -1
  7. package/dist/approvals/judge.js.map +2 -2
  8. package/dist/approvals/owner-tools.js +165 -0
  9. package/dist/approvals/owner-tools.js.map +7 -0
  10. package/dist/approvals/policy.js +22 -3
  11. package/dist/approvals/policy.js.map +2 -2
  12. package/dist/approvals/record.js +1 -1
  13. package/dist/approvals/record.js.map +2 -2
  14. package/dist/control.js.map +2 -2
  15. package/dist/freezer/v6.js +3 -2
  16. package/dist/freezer/v6.js.map +2 -2
  17. package/dist/guests/guard.js +12 -8
  18. package/dist/guests/guard.js.map +2 -2
  19. package/dist/host.js +5 -1
  20. package/dist/host.js.map +2 -2
  21. package/dist/index.js.map +2 -2
  22. package/dist/kernel/agent-users.js +43 -3
  23. package/dist/kernel/agent-users.js.map +2 -2
  24. package/dist/local.js +159 -0
  25. package/dist/local.js.map +7 -0
  26. package/dist/main.js +25 -14
  27. package/dist/main.js.map +2 -2
  28. package/dist/providers.js +29 -1
  29. package/dist/providers.js.map +2 -2
  30. package/dist/scoops/index.js +30 -16
  31. package/dist/scoops/index.js.map +2 -2
  32. package/dist/secrets/credentials.js +4 -2
  33. package/dist/secrets/credentials.js.map +2 -2
  34. package/dist/services.js +4 -0
  35. package/dist/services.js.map +2 -2
  36. package/dist/settings.js +50 -13
  37. package/dist/settings.js.map +2 -2
  38. package/dist/spectrum/approvals-port.js +4 -1
  39. package/dist/spectrum/approvals-port.js.map +2 -2
  40. package/dist/types/agent.d.ts +2 -0
  41. package/dist/types/approvals/judge.d.ts +3 -3
  42. package/dist/types/approvals/owner-tools.d.ts +39 -0
  43. package/dist/types/approvals/policy.d.ts +6 -0
  44. package/dist/types/approvals/record.d.ts +7 -3
  45. package/dist/types/control.d.ts +1 -1
  46. package/dist/types/guests/guard.d.ts +3 -0
  47. package/dist/types/index.d.ts +2 -2
  48. package/dist/types/kernel/agent-users.d.ts +3 -1
  49. package/dist/types/local.d.ts +38 -0
  50. package/dist/types/main.d.ts +20 -0
  51. package/dist/types/providers.d.ts +3 -1
  52. package/dist/types/scoops/index.d.ts +10 -3
  53. package/dist/types/secrets/credentials.d.ts +1 -1
  54. package/dist/types/services.d.ts +6 -2
  55. package/dist/types/settings.d.ts +1 -0
  56. package/dist/types/spectrum/approvals-port.d.ts +1 -0
  57. package/package.json +2 -2
package/README.md CHANGED
@@ -32,7 +32,7 @@ await agent.prompt('What is in /home?');
32
32
  - `@ai-ecoverse/slicc-agent/page` has what the page needs (`startAgent`, `connectAgent`) without the agent's runtime: no pi-durable, pi-ai, providers or SQLite, which load only in the worker. `@ai-ecoverse/slicc-agent/spectrum` is just as light, and a test keeps both that way.
33
33
  - `startAgent({ worker })` takes the Web Lock `slicc-agent`, so one tab at a time owns the agent worker, and waits while another tab holds it. `connect()` returns an `AgentConnection` (`control`, `transcript`, `prompt()`, `webhook(name, { id?, headers?, body })`, which hands a webhook delivery, such as one from the tray hub, to the licks without a chord `Context`, and `approvalRunNotice(notice)`, see Run now), `restart()` replaces the worker (durable resumes from SQLite), and `release()` stops it and lets the next tab take over. `port()` returns a raw `MessagePort` into the worker instead, for another tab: hand it over (through a SharedWorker, say), and that tab calls `connectAgent(port)`. A caller that already holds the lock passes `held: true`. A connection's `closed` resolves when its port ends (with the error, if any), and from then on its states keep their last values.
34
34
  - **Followers over a link** (PR 18): `port({ readOnly: true })` and `connect({ readOnly: true })` give a view-only connection, and `port({ pages: false })` a full one that never takes `panel` requests (see Panels).
35
- - **What a view-only connection can do:** it sees the transcript, the agents, settings state and remote-control `watch`, and may call `wait` and `changesOpen`. It's still an owner device, so it has the owner-device methods (`OWNER_DEVICE_METHODS` in [`src/services.ts`](src/services.ts)) with the owner's powers: `decide`, `approvalRun`, `approvalRunStop`, `approvalRunNotice`, `guestOpen`, `guestRevoke`, `guestAlwaysForget` and `approvalPolicySet`. Control gates driving, not approvals.
35
+ - **What a view-only connection can do:** it sees the transcript, the agents, settings state and remote-control `watch`, and may call `wait` and `changesOpen`. It's still an owner device, so it has the owner-device methods (`OWNER_DEVICE_METHODS` in [`src/services.ts`](src/services.ts)) with the owner's powers: `decide`, `approvalRun`, `approvalRunStop`, `approvalRunNotice`, `guestOpen`, `guestRevoke`, `guestAlwaysForget`, `ownerAlways`, `ownerAlwaysForget` and `approvalPolicySet`. Control gates driving, not approvals.
36
36
  - **What it can't:** every other `AgentControl` method, settings action and remote-control `prompt` or `abort` is refused with `EACCES` ("this follower can watch, but not send, steer or abort"). Send and compact answer `accepted: false` with that code, and `addServer` and `removeServer` answer `not-owner`. The `view` seat's variants don't have those methods at all (`view` for control and settings, `watch` for remote control, `none` for Panels); the follower's client answers the missing ones with the refusals ([`src/readonly.ts`](src/readonly.ts)), so the worker never runs them. A `watch` stream is readable only over the link that opened it.
37
37
  - **Carrying the connection over a byte stream:** `linkEndpoint({ write, close })` is a `PortEndpoint` that `connectAgent` accepts. Feed it the stream's bytes with `receive(bytes)` and its end with `end(error?)`. On the owner's side, `bridgePort(port, { write, close })` does the same for the `MessagePort` from `port()`.
38
38
  - **The bytes:** the owner first posts a hello, its server id, then each Chord frame travels as its JSON text in UTF-8 (`PortLink` in [`src/wire.ts`](src/wire.ts)), and `{ close: true }` ends the port. The owner holds its own Chord frames until the client's Chord hello arrives, so it knows which Chord it talks to before it says anything. `PortLink.send` returns each frame's size, so Chord's flow control applies: once 256 KiB are unacknowledged, state waits at the owner, coalesced per member, instead of piling up in front of a slow WebRTC follower, while calls and results still pass. On a byte stream each message becomes a frame: a `u32` big-endian length, then a tag (0 data, 1 hello, 2 close), then the payload. A frame is at most 16 MiB, and a malformed one ends the link.
@@ -102,7 +102,7 @@ With users, each cone and each scoop is a kernel user, and works as that user:
102
102
  - So a cone reads its scoops' work, and a scoop reads only what its cone shares with `chmod g+r` (and `g+x` on the folders on the way).
103
103
  - The worker adds every user at boot, and on every change to `slicc.agents`. Stopping, dropping or removing a scoop removes its user and its home; scoops go before their cone.
104
104
  - **Clients:** a conversation's bash, file tools and codemode, and its background tasks, use its agent's bound client. Its cwd defaults to its home, and the kernel sets `HOME`, `USER` and `PATH`. The client carries the page's tag for its agentId, so a `sudo` prompt names the agent.
105
- - **The `agent` command:** each user has its own request spool, `/var/lib/slicc/agent/requests/<user>/` (`0700`). The spool's owner is the caller, so a `SLICC_AGENT` that names someone else is refused. `--file` and `--system-prompt-file` are read as the caller.
105
+ - **The `agent` command:** each user has its own request spool, `/var/lib/slicc/agent/requests/<user>/` (`0700`). The spool's owner is the caller, so a `SLICC_AGENT` that names someone else is refused. When the worker starts, one `stat` lists every user's spool, and one script puts back only the spools that are missing a folder or have another owner or mode; then every user's requests are served at once. So a profile with many cones, scoops or frozen conversations doesn't start slower for them: before, each spool cost its own `mkdir`, `chown` and `chmod`, one user after the other (about 170 ms each). `--file` and `--system-prompt-file` are read as the caller.
106
106
  - **Sharing in a sync run:** when the caller's cwd, or a `--read-only` path, is inside the caller's home, the run first shares it with the scoop: `chmod -R g+rX` on it and `g+x` on the folders above it. The v6 form's working folder gets `g+rwX`, plus `g+s` on its folders. The modes stay afterwards.
107
107
  - **Where things are:**
108
108
 
@@ -146,7 +146,11 @@ const owner = await startAgent({
146
146
 
147
147
  `runAgentWorker(self, options)` is the same with its parts replaceable (model, providers, kernel attach, the account store, storage).
148
148
 
149
- **Providers.** `sliccProviders()` registers Bedrock, Adobe and every pi-ai provider that takes a plain API key: Anthropic, OpenAI, Mistral, Groq, DeepSeek, Together, Hugging Face, Xiaomi and its three token plans, Cerebras, OpenRouter, Fireworks, Baseten, Moonshot AI and its China platform, xAI, Meta, Vercel AI Gateway, MiniMax and MiniMax CN, Z.AI and Z.AI Coding CN, NVIDIA, Kimi For Coding, Ant Ling, OpenCode Zen and Go, and the three Qwen token plans (`KEY_PROVIDERS` in `src/providers.ts`, each with its id, pi-ai factory, pi-ai env name, a description, a key URL and whether it answers browsers). Three more take a key and non-secret fields (`auth: 'fields'`), each checked in `connect` and mapped to pi-ai's env: Azure (`endpoint`, required: a resource name becomes `AZURE_OPENAI_RESOURCE_NAME`, an `https:` URL without a port or user name `AZURE_OPENAI_BASE_URL`; `deployments`, optional `model=deployment` pairs, `AZURE_OPENAI_DEPLOYMENT_NAME_MAP`), Cloudflare Workers AI (`account`, 32 hex characters, `CLOUDFLARE_ACCOUNT_ID`) and Cloudflare AI Gateway (`account` and `gateway`, `CLOUDFLARE_GATEWAY_ID`). Bedrock's `region` is on the same mechanism. A bad value rejects `connect` with a sentence, a required field left out keeps its stored value or rejects with “{label} can’t be empty.”, and a stored value that no longer passes is left out of the env. A fields provider whose required fields are missing or no longer pass shows as not connected, gives pi-ai no credential and offers no models, even with its key already in the vault (spectrum puts the key before `connect` checks the fields). Bedrock's region is any AWS region name (`eusc-de-east-1` and `us-gov-west-1` included), and stored values are trimmed. OpenCode Zen and OpenCode Go need seven's vault 1.12.2 or later, whose built-in table has their `/inference` endpoints; their descriptions say so. Azure's `endpoint` field says `customBase: true`: when its value is a full URL, spectrum registers it with the vault (the page's `endpoints`) before `connect`, since the agent never registers model endpoints for pi-ai providers; a resource name needs nothing, as `*.openai.azure.com` is built into the vault. The worker routes requests to an Azure account's base URL as Azure's. Google and Google Vertex wait for slicc-bios to stop removing `@google/genai`; the sign-ins come later. A provider's preferred model is pi-coding-agent 1.4.0's `defaultModelPerProvider` (Bedrock keeps `us.anthropic.claude-sonnet-5-5`), and the first model when that one is missing. Providers that don't answer a browser from `https://seven.sliccy.ai` with the headers pi-ai and the AWS SDK send say `needs: 'cors-free-transport'`; the direct ones are Bedrock, Adobe, Anthropic, OpenAI, Azure, Mistral, Groq, DeepSeek, Together, Hugging Face, Baseten, both Moonshot AI platforms, xAI, Meta and the four Xiaomi providers. Z.AI Coding CN stays cors-free: the nightly check found it answering browsers on one day and not two days later. Chrome accepts `Authorization` under a bare `Access-Control-Allow-Headers: *` (as xAI, Meta and Adobe's proxy answer), checked in Chrome 156. The worker's transport fetch drops the Stainless SDKs' `x-stainless-*` telemetry headers from every request it sends, which is what Baseten's and Moonshot AI's preflights refuse.
149
+ **Providers.** `sliccProviders()` registers Bedrock, Adobe and every pi-ai provider that takes a plain API key: Anthropic, OpenAI, Mistral, Groq, DeepSeek, Together, Hugging Face, Xiaomi and its three token plans, Cerebras, OpenRouter, Fireworks, Baseten, Moonshot AI and its China platform, xAI, Meta, Vercel AI Gateway, MiniMax and MiniMax CN, Z.AI and Z.AI Coding CN, NVIDIA, Kimi For Coding, Ant Ling, OpenCode Zen and Go, and the three Qwen token plans (`KEY_PROVIDERS` in `src/providers.ts`, each with its id, pi-ai factory, pi-ai env name, a description, a key URL and whether it answers browsers). Three more take a key and non-secret fields (`auth: 'fields'`), each checked in `connect` and mapped to pi-ai's env: Azure (`endpoint`, required: a resource name becomes `AZURE_OPENAI_RESOURCE_NAME`, an `https:` URL without a port or user name `AZURE_OPENAI_BASE_URL`; `deployments`, optional `model=deployment` pairs, `AZURE_OPENAI_DEPLOYMENT_NAME_MAP`), Cloudflare Workers AI (`account`, 32 hex characters, `CLOUDFLARE_ACCOUNT_ID`) and Cloudflare AI Gateway (`account` and `gateway`, `CLOUDFLARE_GATEWAY_ID`). Bedrock's `region` is on the same mechanism. A bad value rejects `connect` with a sentence, a required field left out keeps its stored value or rejects with “{label} can’t be empty.”, and a stored value that no longer passes is left out of the env. A fields provider whose required fields are missing or no longer pass shows as not connected, gives pi-ai no credential and offers no models, even with its key already in the vault (spectrum puts the key before `connect` checks the fields). Bedrock's region is any AWS region name (`eusc-de-east-1` and `us-gov-west-1` included), and stored values are trimmed. OpenCode Zen and OpenCode Go need seven's vault 1.12.2 or later, whose built-in table has their `/inference` endpoints; their descriptions say so. Azure's `endpoint` field says `customBase: true`: when its value is a full URL, spectrum registers it with the vault (the page's `endpoints`) before `connect`, since the agent never registers model endpoints for pi-ai providers; a resource name needs nothing, as `*.openai.azure.com` is built into the vault. The worker routes requests to an Azure account's base URL as Azure's.
150
+
151
+ **Local or self-hosted.** `local` (`src/local.ts`) is any OpenAI-compatible server: Ollama, LM Studio, llama.cpp, vLLM, SGLang, slicc-ortllama or a proxy. It is built from pi-ai's `createProvider`, `openAICompletionsApi()`, `fetchModels` and `typesafeSystemOneApi()`, with pi-coding-agent's llama.cpp provider (not exported) as the reference. Its `endpoint` field is required: `https:` anywhere, `http:` only on loopback (`localhost`, `*.localhost`, `127.0.0.0/8`, `[::1]`), private networks (`10/8`, `172.16/12`, `192.168/16`, `fc00::/7`, `.local`), the tailnet (`100.64.0.0/10`, `*.ts.net`) and the agent's own kernel servers (`<port>.kernel.localhost`, never `9222`), never with a user name or password. A trailing `/v1` is optional; the base URL is the address with `/v1` (`LOCAL_BASE_URL`). The optional `context` field (`LOCAL_CONTEXT_WINDOW`) is the context window for a server that doesn't report one. Models come from `GET {base}/models`: `architecture.input_modalities` with `image` gives image input; the context window is `context_length` (ortllama), `meta.n_ctx` (llama.cpp) or `max_context_length` (LM Studio), else the `context` field, else 32768; cost is 0; compat is `supportsStore`, `supportsDeveloperRole`, `supportsReasoningEffort` and `supportsStrictMode` off and `maxTokensField: 'max_tokens'`. A model whose `architecture.output_modalities` has `decisions` is only a classifier, on `typesafe-system-one` at `{base}/systemone`, so `approvals.judgeModel: "local/<id>"` works. The key is optional and kept in the vault (`LOCAL_API_KEY`): the `endpoint` field is a `customBase`, so spectrum registers an `https:` endpoint with the vault, as for Azure; `connect` refuses a key with an `http:` endpoint, since the vault sends keys over https only. Without a key the account is connected by its fields alone (`No key`), pi-ai gets a keyless credential (`apiKey: 'local'`), and its requests bypass the vault's `model` op. `connect` probes `GET {base}/models` over the worker's transport first; a failure names the fixes (`OLLAMA_ORIGINS=https://seven.sliccy.ai`, LM Studio's Enable CORS, vLLM's `--allowed-origins`, `ORTLLAMA_ORIGINS`, or linking slicc). There is no static `needs: 'cors-free-transport'`: the kernel loopback, llama.cpp (which sends `*`) and a linked slicc work without it. An account with a chat model under 16k tokens says `context under 16k tokens` after its identity. Disconnecting it forgets its fields. Its models are listed again at connect, at start and every 5 minutes, as Adobe's are.
152
+
153
+ Google and Google Vertex wait for slicc-bios to stop removing `@google/genai`; the sign-ins come later. A provider's preferred model is pi-coding-agent 1.4.0's `defaultModelPerProvider` (Bedrock keeps `us.anthropic.claude-sonnet-5-5`), and the first model when that one is missing. Providers that don't answer a browser from `https://seven.sliccy.ai` with the headers pi-ai and the AWS SDK send say `needs: 'cors-free-transport'`; the direct ones are Bedrock, Adobe, Anthropic, OpenAI, Azure, Mistral, Groq, DeepSeek, Together, Hugging Face, Baseten, both Moonshot AI platforms, xAI, Meta and the four Xiaomi providers. Z.AI Coding CN stays cors-free: the nightly check found it answering browsers on one day and not two days later. Chrome accepts `Authorization` under a bare `Access-Control-Allow-Headers: *` (as xAI, Meta and Adobe's proxy answer), checked in Chrome 156. The worker's transport fetch drops the Stainless SDKs' `x-stainless-*` telemetry headers from every request it sends, which is what Baseten's and Moonshot AI's preflights refuse.
150
154
 
151
155
  **Reachability, by hand.** `npm run reach` (`scripts/reach.mjs`, through `verdict.mjs`) checks every listing from `https://seven.sliccy.ai`. It captures the request pi-ai builds for each of the provider's APIs (with a dummy key and dummy fields, and the fetch faked; Bedrock's from the AWS SDK's own request, caught at its Node HTTP handler, which carries the same headers as in a browser: `amz-sdk-invocation-id`, `amz-sdk-request`, `authorization`, `content-type`, `x-amz-user-agent`). Then it sends that request's preflight and, when the preflight passes, the request itself with dummy credentials, whose answer must carry `Access-Control-Allow-Origin` too. Besides each chat API it probes what the provider's models need beyond a turn: the requests its model discovery sends under its base URL (Adobe's `/v1/config`), one classifier call per classifier API (Adobe's `/v1/ai/run`, OpenAI's `/v1/decisions`, OpenRouter's and Cloudflare's), and Adobe's `/v1/usage`. It prints `reach: <id> direct|cors-free|unknown|unprobed` per provider (`unknown` when the network gave no answer; `unprobed` when it captured no request at all, which counts as a disagreement, so a provider can't silently drop out of the check) and one `reach: PASS` line. A provider that stays `unknown` three runs in a row counts as a disagreement too, when `REACH_HISTORY` names a file that keeps the streaks between runs, and the line says how many runs in a row; `REACH_REPORT` names a file for the JSON report. A direct provider that passes only because Chrome lets `Authorization` through under a bare `Access-Control-Allow-Headers: *` reads `direct (wildcard auth)` (today Adobe, xAI and Meta); the PASS line and the report list them, without failing, so we know at once which break if Chrome ever enforces the Fetch spec. No workflow runs it: it calls the real providers' endpoints, so it is a check to run before changing a listing, and no CI job or integration test reaches a real provider (`test/integration/reach.test.mjs` fakes the network). A run without the PASS line fails.
152
156
 
@@ -168,7 +172,7 @@ The first provider is AWS Bedrock with a Bedrock API key as the bearer token; th
168
172
 
169
173
  **Subscription sign-ins.** xAI, Kimi For Coding and ChatGPT (`openai-codex`, shown as ChatGPT) sign in with pi-ai's own device-code flows (`DEVICE_SIGN_INS` in `src/sign-ins.ts`); xAI and Kimi keep API-key entry too, so their accounts are `auth: 'oauth'` with `secret: 'api-key'` (spectrum's “Use an API key instead”) and a `keyUrl`. Spectrum's Sign in calls `connect(id, undefined, undefined, { method: 'sign-in' })` in the click, and a pasted key `put`s first and calls `connect(id, undefined, fields, { method: 'key' })` (spectrum's `ConnectOptions`); without the fourth argument an `oauth` account signs in. The adapter asks the owner for a baseline and opens a held popup (`slicc-sign-in`, see **Held sign-in windows**) before anything else, then asks the worker's `signIn(id)`, which adds the account, runs the provider's `auth.oauth.login` and answers `{ url, code }` once the provider gives its device code (an `https:` page only). While it waits the account is `signing-in` with `signIn: { url, code? }`, kept in the page and never in the replicated settings state; the prompt appears and the popup goes to `url` only once the popup is held, and spectrum shows `code` with Copy and a link to `url` when the browser blocked the popup. The adapter's `connect` call then waits in the worker for the token (a sign-in no `connect` claims within a minute is dropped) and hands the vault `grant { provider, name, response, settings? }`, `name` being the account's `vaultName` and `response` the token response built from pi-ai's credential, as bytes zeroed after the call; the token is never stored, logged, licked or put in the state, and pi-ai's own error texts, which can quote a token response, never leave the worker. A refusal reads “The sign-in was refused.”, a timeout, network failure or malformed answer “The sign-in didn't finish. Try again.”, the vault's `EEXIST` “This name holds another provider's key.”, and Cancel aborts at once with an `AbortError`. Signing in again is a rotation that keeps the placeholder, and over a pasted key the vault keeps that key restorable. The vault refreshes the token through `egress`; after `invalid_grant` its record is `expired` and the account offers Sign in again. ChatGPT's API reads the account id from the access token's JWT, which a placeholder isn't: the grant carries `settings: { CHATGPT_ACCOUNT_ID }` (every sign-in), the credential's env gets it from the record, and the worker hands pi-ai a carrier key `slicc.<claims>.<placeholder>` that the worker's fetch turns back into `Bearer <placeholder>` before the vault fills it, so pi-ai sends `chatgpt-account-id` itself; its turns use SSE, not WebSockets. Kimi's auth host answers browsers but its API needs the CORS-free transport; xAI's API answers browsers but its device endpoints don't, so an xAI sign-in needs the CORS-free transport while its key doesn't; ChatGPT's auth host answers browsers and its API doesn't. The flows load lazily from pi-ai: xAI's and Kimi's modules import nothing from Node, and openai-codex's imports `node:http` for its browser callback, which the device flow never runs, so slicc-bios's `node:*` stubs let it load.
170
174
 
171
- **Adding providers.** The settings state's `providers` lists every provider seven can add (`ProviderOption`: `id`, `name`, `description`, `auth`, `keyUrl`, `needs`, `fields` and `vaultName`, sorted by name), and the spectrum adapter serves it as `providers()` with a `providers` event when it changes. `accounts` then lists only the added ones: Bedrock and Adobe start as added, `connect` adds a provider, and one with a vault record or stored fields counts as added too. The added list is `providers` in `/.slicc/accounts.json`. `vaultName` is the record name spectrum `put`s the key under: pi-ai's env name, or `<ID>_API_KEY` for providers that share one (Moonshot AI, OpenCode and the Qwen token plans), since a `put` under another provider's name would rebind that record; Bedrock's is `AWS_BEARER_TOKEN_BEDROCK` and Adobe's `ADOBE_IMS_TOKEN`. The agent finds a provider's record by its `provider`, never by name. Each provider has at most one secret, its key; `fields` are the non-secret inputs (`name`, `label`, `required`, `placeholder`, `help`, `customBase`, `vaultSetting`, `options` and `value`). `vaultSetting` names the vault record setting a field fills (slicc-vault's tenant-bound wildcards, V3), so the vault can bind a provider's wildcard endpoints to the user's own tenant: Cloudflare's `account` is `CLOUDFLARE_ACCOUNT_ID` and `gateway` `CLOUDFLARE_GATEWAY_ID`, and Azure's `endpoint` is `AZURE_OPENAI_RESOURCE_NAME` (spectrum applies it only to a bare resource name; an `https:` value stays a `customBase`). On an added account each field's `value` is its stored value, trimmed, so Settings can show it and knows a custom base URL to unregister after a reload; a field with a default carries that instead (Bedrock's `us-west-2`). Bedrock's `region` has `options`, the 21 regions where AWS supports Bedrock API keys (the bearer token seven uses; AWS's “Supported Regions … for Amazon Bedrock API keys”), labelled with AWS's names (`Europe (Frankfurt), eu-central-1`); a stored region outside the list comes first, under its own name, so a select never shows a region the account doesn't use. `disconnect(id)` keeps the row and its fields, so connecting again needs only the key, and `remove(id)` drops the row and its fields; for both, spectrum removes the vault record first. On an MCP row, `remove` disconnects it. `connect` with a secret is refused for every model account ("API keys are kept in seven's vault: update seven"); the only secret it still takes is an MCP sign-in's callback answer.
175
+ **Adding providers.** The settings state's `providers` lists every provider seven can add (`ProviderOption`: `id`, `name`, `description`, `auth`, `keyUrl`, `needs`, `fields` and `vaultName`, sorted by name), and the spectrum adapter serves it as `providers()` with a `providers` event when it changes. `accounts` then lists only the added ones: Bedrock and Adobe start as added, `connect` adds a provider, and one with a vault record or stored fields counts as added too. The added list is `providers` in `/.slicc/accounts.json`. `vaultName` is the record name spectrum `put`s the key under: pi-ai's env name, or `<ID>_API_KEY` for providers that share one (Moonshot AI, OpenCode and the Qwen token plans), since a `put` under another provider's name would rebind that record; Bedrock's is `AWS_BEARER_TOKEN_BEDROCK` and Adobe's `ADOBE_IMS_TOKEN`. The agent finds a provider's record by its `provider`, never by name. Each provider has at most one secret, its key; `fields` are the non-secret inputs (`name`, `label`, `required`, `placeholder`, `help`, `customBase`, `vaultSetting`, `options` and `value`). `vaultSetting` names the vault record setting a field fills (slicc-vault's tenant-bound wildcards, V3), so the vault can bind a provider's wildcard endpoints to the user's own tenant: Cloudflare's `account` is `CLOUDFLARE_ACCOUNT_ID` and `gateway` `CLOUDFLARE_GATEWAY_ID`, and Azure's `endpoint` is `AZURE_OPENAI_RESOURCE_NAME` (spectrum applies it only to a bare resource name; an `https:` value stays a `customBase`). On an added account each field's `value` is its stored value, trimmed, so Settings can show it and knows a custom base URL to unregister after a reload; a field with a default carries that instead (Bedrock's `us-west-2`). Bedrock's `region` has `options`, the 21 regions where AWS supports Bedrock API keys (the bearer token seven uses; AWS's “Supported Regions … for Amazon Bedrock API keys”), labelled with AWS's names (`Europe (Frankfurt), eu-central-1`); a stored region outside the list comes first, under its own name, so a select never shows a region the account doesn't use. `disconnect(id)` keeps the row and its fields (but `local`'s, which are its connection), so connecting again needs only the key, and `remove(id)` drops the row and its fields; for both, spectrum removes the vault record first. On an MCP row, `remove` disconnects it. `connect` with a secret is refused for every model account ("API keys are kept in seven's vault: update seven"); the only secret it still takes is an MCP sign-in's callback answer.
172
176
 
173
177
  ### In slicc-spectrum
174
178
 
@@ -266,7 +270,7 @@ A **cone** is a top-level agent the user talks to; a **scoop** is a helper agent
266
270
 
267
271
  Each scoop is owned by a background durable task, its **anchor**, so Stop in its cone doesn't end it; `agent stop` and Drop do. They keep its transcript in durable storage and its reports in `/scoops/<handle>/reports/`, which report licks point at, and remove its working folder `/scoops/<handle>/workspace`. Each request handed to a scoop gets a **reporter** task that waits for the run, writes the answer to `/scoops/<handle>/reports/<task id>.md` and reports it to whoever asked. Requests from a cone's or a scoop's bash report into that agent's `pi.inbox` as a lick, through the licks outbox, so they steer and coalesce like any lick; requests from a terminal report nowhere, and a user typing in a scoop's chat gets the answer there. In a scoop's chat, a request someone else sent shows who sent it (`UserMessage.from`): the asking cone's or scoop's name, with `origin: 'agent'` so spectrum (≥ 1.26.0) shows it as that agent's request with an "Agent" badge, or `terminal` without an origin. Once the request is placed, the reporter appends a `slicc.from` entry (`{ from, entry }`) without model messages, and the adapter sets `from` on that entry's message. A request withdrawn before it was placed leaves no entry. The report lick's text is `[scoop <name> (<role>) <status>]`, and its body has the report's path and line count and a 1,000-character preview. A scoop's prompt has a `scoop` section with its name, its cone, its folders and its limits. The `agent` command is taught by the built-in `agent` skill (below), whose description says that roles exist and that `agent list --agents` lists them.
268
272
 
269
- **The `agent` command.** One bash script is installed under seven names, `agent`, `subagent`, `memory`, `gelatiere`, `freezer`, `models` and `panel`, in `/usr/local/bin`, mode `0755`, which is on every user's `PATH`, so the user, a cone or a scoop runs it in any bash. A file at one of those paths that isn't slicc-agent's (it lacks the `slicc-agent/1` request marker), such as a root global package's `memory`, is left alone, with one warning per boot in the worker's console. Root's `$PNPM_HOME/bin` (`/usr/local/share/pnpm/bin`) is on root's `PATH` only: other users find root's installed packages in `/usr/bin`, but not loose scripts. Copies that earlier versions put in the kernel's `$PNPM_HOME/bin` are removed, so they can't shadow the new ones for root. It writes a request (NUL-separated fields: `slicc-agent/1`, the name it was called by, `$SLICC_AGENT`, or `tab:$SLICC_TAB` from a terminal that has only that, the working directory, its pid, argc, the arguments and stdin) to `/var/lib/slicc/agent/requests/in/` and polls `out/` for the answer and exit code (with an optional `<id>.err`, the answer's stdout is `<id>.out` and its stderr `<id>.err`); the worker writes `<id>.ack` when it picks a request up, and the script gives up after 20 s without one ("the SLICC agent isn't running", exit 1). The kernel environment exports `SLICC_AGENT`, `PI_PROVIDER`, `PI_MODEL` and `PI_REASONING_LEVEL` into every agent command, so the worker knows the caller, and `PLAYWRIGHT_CLI_SESSION` with the same agent id, so each agent's `playwright-cli` keeps its own current tab (slicc-cdp #129). The user's terminals get none of these. `SLICC_AGENT` is checked against the process tree: the worker reads `ps`, walks up from the request's pid to the nearest bash an agent's kernel environment started, and refuses a request whose `SLICC_AGENT` names another agent, or names one when no agent's bash is above it. With kernel users the caller is the kernel user its process runs as (its uid in `ps`), not the agent whose bash started the tree: `sudo -u cone-2 agent …` in cone `cone`'s bash acts as `cone-2`, with `cone`'s guest taints added (also for `rename`, whose new name enters the scoop's prompt, so the renamed scoop is gated like one the caller fed; `stop` starts no work, so it has nothing to carry them to). Root is the exception: a root request keeps the agent whose bash started it, so `sudo -u root agent list` in `cone-2`'s bash lists `cone-2`'s scoops, while `sudo -u root agent send cone-4 …` may message any cone as root. Neither `$USER` nor `SLICC_AGENT` can change that: the script refuses a `$USER` whose spool it can't write, and the worker one whose uid doesn't match. The pid in the request is the script's own `$$`, so it is checked first: its `ps` row has to be the command it was called as (`/…/agent`, `subagent`, …) followed by exactly the request's arguments, and with kernel users it has to run as the spool's user (by `/etc/passwd`). A request whose pid isn't in the table or fails these checks, or a `ps` read that fails or stalls, is refused. A caller with no agent above it and no `SLICC_AGENT` is the user. `/var/lib/slicc/agent/scoops/<handle>/metadata.json` mirrors each scoop's state for scripts.
273
+ **The `agent` command.** One bash script is installed under seven names, `agent`, `subagent`, `memory`, `gelatiere`, `freezer`, `models` and `panel`, in `/usr/local/bin`, mode `0755`, which is on every user's `PATH`, so the user, a cone or a scoop runs it in any bash. A file at one of those paths that isn't slicc-agent's (it lacks the `slicc-agent/1` request marker), such as a root global package's `memory`, is left alone, with one warning per boot in the worker's console. At boot the script is written only where it differs, and one `chmod 755` sets the mode of all of slicc-agent's copies. Root's `$PNPM_HOME/bin` (`/usr/local/share/pnpm/bin`) is on root's `PATH` only: other users find root's installed packages in `/usr/bin`, but not loose scripts. Copies that earlier versions put in the kernel's `$PNPM_HOME/bin` are removed, so they can't shadow the new ones for root. It writes a request (NUL-separated fields: `slicc-agent/1`, the name it was called by, `$SLICC_AGENT`, or `tab:$SLICC_TAB` from a terminal that has only that, the working directory, its pid, argc, the arguments and stdin) to `/var/lib/slicc/agent/requests/in/` and polls `out/` for the answer and exit code (with an optional `<id>.err`, the answer's stdout is `<id>.out` and its stderr `<id>.err`); the worker writes `<id>.ack` when it picks a request up, and the script gives up after 20 s without one ("the SLICC agent isn't running", exit 1). The kernel environment exports `SLICC_AGENT`, `PI_PROVIDER`, `PI_MODEL` and `PI_REASONING_LEVEL` into every agent command, so the worker knows the caller, and `PLAYWRIGHT_CLI_SESSION` with the same agent id, so each agent's `playwright-cli` keeps its own current tab (slicc-cdp #129). The user's terminals get none of these. `SLICC_AGENT` is checked against the process tree: the worker reads `ps`, walks up from the request's pid to the nearest bash an agent's kernel environment started, and refuses a request whose `SLICC_AGENT` names another agent, or names one when no agent's bash is above it. With kernel users the caller is the kernel user its process runs as (its uid in `ps`), not the agent whose bash started the tree: `sudo -u cone-2 agent …` in cone `cone`'s bash acts as `cone-2`, with `cone`'s guest taints added (also for `rename`, whose new name enters the scoop's prompt, so the renamed scoop is gated like one the caller fed; `stop` starts no work, so it has nothing to carry them to). Root is the exception: a root request keeps the agent whose bash started it, so `sudo -u root agent list` in `cone-2`'s bash lists `cone-2`'s scoops, while `sudo -u root agent send cone-4 …` may message any cone as root. Neither `$USER` nor `SLICC_AGENT` can change that: the script refuses a `$USER` whose spool it can't write, and the worker one whose uid doesn't match. The pid in the request is the script's own `$$`, so it is checked first: its `ps` row has to be the command it was called as (`/…/agent`, `subagent`, …) followed by exactly the request's arguments, and with kernel users it has to run as the spool's user (by `/etc/passwd`). A request whose pid isn't in the table or fails these checks, or a `ps` read that fails or stalls, is refused. A caller with no agent above it and no `SLICC_AGENT` is the user. `/var/lib/slicc/agent/scoops/<handle>/metadata.json` mirrors each scoop's state for scripts.
270
274
  - `agent [options] --prompt <text>` (or `--file <path>`, or `-` for stdin, or v6's `agent <cwd> <allowed-commands> <prompt>`) is **synchronous**: an ephemeral scoop runs, and the command prints its final answer and exits 0, or prints the reason on stderr and exits 1. Afterwards the scoop is stopped, its folder removed, its conversation marked dropped and its transcript archived as Markdown in `/tmp/agent-sessions/<handle>.md` (`/home/sessions/` with `--persist-session`, nowhere with `--no-persist-session`). The script traps TERM, INT and HUP and cancels the scoop, and the worker checks the script's pid in the kernel's process table every second for a SIGKILL. If the caller's run is still going when the bash call dies (a bash timeout), the scoop continues and its answer arrives as a `bash` lick; `--background-after <seconds>` does the same on purpose. Sync calls nest up to three deep. Allowed commands in v6's form are told to the scoop, not enforced.
271
275
  - `agent retry <task id>` answers that a task which stopped after repeated restarts has ended, and that the work has to be submitted again. Only the user may ask; an agent is refused.
272
276
  - `agent --async …` (= `subagent spawn …`) starts a persistent scoop and prints its handle; only cones start them. `list [--agents | --cones]`, `status`, `rename`, `send [--follow-up]`, `wait [--timeout <s>] [--notify]` (30 s by default; `--notify` returns at once and brings the answers together in one `scoop-wait` lick) and `stop` manage them. From a scoop, `agent send parent "<note>"` posts a progress note to its cone as a lick, coalesced per scoop. A scoop verb on a name that is a cone says how to message that cone instead.
@@ -559,7 +563,7 @@ SLICC 6 exports a profile as a `slicc-profile` v1 zip (#6). `test/integration/fi
559
563
  - **Caps:** an archive of at most 2 GiB and 60,000 entries, any file at most 256 MiB, a transcript at most 64 MiB, at most 4 GiB in all, and no more than 200:1 expansion.
560
564
  - **Names:** `manifest.json` comes first. A name that is absolute, has an empty, `.` or `..` part, a `\`, a NUL or a drive letter is refused, as are symlinks, names that appear twice, names that `files[]` doesn't list, and names with no place in the profile's layout. Every file must match its size and sha256.
561
565
  - **Schemas:** the manifest, each transcript (a copy of slicc's `validateTranscriptDocumentV1`) and `licks.json` are checked. Memory and git config must be UTF-8.
562
- - **The answer:** one sentence on what the profile holds, such as cones, scoops, frozen sessions, file size, skills, crons, webhooks, credential-like files, the providers to re-enter in Settings, and the mounts that don't move.
566
+ - **The answer:** one sentence on what the profile holds, such as cones, scoops, frozen sessions, file size, skills, crons, webhooks, credential-like files, the providers to re-enter in Settings, and the mounts that don't move. Six's `bedrock` and `bedrock-camp` accounts are seven's `amazon-bedrock`, and `local-llm` is `local` (the export carries no base URL, so it is entered again).
563
567
  - **Conversations:** each six cone and each frozen session becomes a frozen cone with its own `cone-<n>` user. Its conversation is one `slicc.v6` entry per six message, turned into a pi-ai message. Its `FrozenRecord` carries `v6: { origin, key }`, and its row in the Freezer list has `v6: true`. The cone's scoops become stopped scoops of that frozen cone, and no scoop users are made.
564
568
  - **A thaw forks:** thawing a v6 cone forks its conversation, with the active cone's model, and adds a `slicc.thawed` note saying that six's `/workspace` is now `~/workspace`. If that cone is live already, as it is for an "(updated)" conversation whose earlier import was thawed, the cone's current conversation goes to the Freezer, and the cone carries on with the updated one in the same home. Its note then names `~/workspace.v6-<date>`.
565
569
  - **Files:**
@@ -754,17 +758,25 @@ It prints the tab's stdout and stderr on their own streams and exits with its co
754
758
 
755
759
  ### Approvals
756
760
 
757
- 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.
761
+ Every approval, of a guest's prompt, of a tool call in a run a guest started, of the owner's own tool call when the policy asks for it (see The owner's tool calls), 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.
758
762
 
759
- - **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?, validate? }`, with `replay` and `run` on the item, see Run now) 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? }`.
763
+ - **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? }`), `owner-tool` (the same detail, see The owner's tool calls), `sudo` (`{ command, target?, cwd?, alwaysScope?, stdin?, rootOnly?, writable?, validate? }`, with `replay` and `run` on the item, see Run now) 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? }`.
760
764
  - **`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`, `disconnected` or `stopped` (see Deny and stop). `decidedBy` is `owner`, `follower`, `judge` or `host`.
761
765
  - **`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.
762
766
  - **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`, `deny` or `stop` 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).
763
767
  - **Deny and stop:** `decide(id, 'stop')` denies a `sudo` item and stops the turn of the agent that asked for it, in one step inside the worker. Only a person (`owner` or `follower`) may send it, and only for a pending `sudo` item whose `requester` is an agent with an `agentId` (a cone or a scoop); anything else is refused with an error ("Only a person can stop a turn.", "This request has no turn to stop.") and the item stays pending, and so is one to approvals attached without a way to stop a turn. One write settles the item `rejected` with `reason: 'stopped'` and `decidedBy` the person, withdraws that agent's other pending `sudo` and `capture` items (`withdrawn`, `stopped`), and holds that agent's next `sudo` or `capture` asks; then the worker aborts that agent's conversation (`Conversation.abort()`, as `stopAgent` does), which kills the running command's process tree, and `decide` waits (bounded) for that abort before it returns. A tombstone then keeps holding that agent's `sudo` and `capture` asks until its next turn begins, so a shell loop that survives the abort still can't reach a person: each late ask is filed `withdrawn` (`stopped`) at once. The tombstone clears when that agent's conversation becomes busy again. A scoop's request stops the scoop's turn, never its cone's: a cone waiting on it in `agent --prompt` gets "the scoop's request ended without an answer: aborted" and carries on, and `agent wait` returns once the scoop is idle. A person's own reason that is the word `stopped` isn't kept, so a plain deny never reads as a stop. A worker from before this answers `stop` as `unknown-answer`, a plain deny.
764
- - **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.
768
+ - **Lifetime:** an item waits 5 minutes unless its requester sets `expiresAt`, then settles `unanswered`. Pending guest and `owner-tool` 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.
765
769
  - **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.
766
770
  - **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`.
767
771
  - **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. A `sudo` approval from a cone or a scoop (`requester.kind` `agent` with an `agentId`) carries `stoppable: true`, and spectrum then offers Deny and stop, sent as `decide(id, 'stop')`; a terminal's, a sprinkle's or a linked device's never does. `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.
772
+ - **The owner's tool calls** ([`src/approvals/owner-tools.ts`](src/approvals/owner-tools.ts)) are filed only when the approval policy's `owner.tools` is `user` or `agent` (see Approval policy). With the default, `off`, nothing changes: the gate's `beforeTool` hook reads the policy and returns, no item is filed and no judge is asked, and the system prompt alone asks the model to check in chat before paying, sending or deleting.
773
+ - **Which calls:** every tool call, nested ones from codemode included, in a conversation of one of the owner's cones or scoops, workflow steps included. A run a guest started stays on the guest gate (see Guest seats) and is never filed as `owner-tool`; other conversations, such as title or memory runs, aren't gated.
774
+ - **The item** is `kind: 'owner-tool'`, `detail: { tool, summary, arguments?, task? }` scrubbed and capped as for `guest-tool`, `requester: { kind: 'agent', name, agentId }` (the cone's or scoop's name), `agentId` the same, `tier` the policy's `owner.tools` and `always: true`. A reload rejoins the same item, and aborting the call withdraws it (`aborted`).
775
+ - **`user`:** a person answers on any owner device: the page dialog, a follower, or a host program over the link. An unanswered call is denied after 5 minutes. The judge still gives a verdict as advice when it can.
776
+ - **`agent`:** the judge's single guest-style call over the owner's intent (the item's cone), then the routing table: level 1 and aligned is allowed by the judge, level 3 goes to a person while an owner device is attached with at least 30 s left and is denied otherwise, anything else goes to a person (`tier` becomes `user`).
777
+ - **What the model gets:** an approved call runs; any other end blocks it with "The owner declined this tool call." (and the person's reason), "The automatic check declined this tool call: <reason>", "Nobody approved this tool call in time." or "The review of this tool call was withdrawn.".
778
+ - **Always** records an exact rule, `{ approval, tool, argumentsHash, arguments, by, at }`, with the guest seat's matcher (the hex SHA-256 of the call's canonical JSON, `arguments` scrubbed for display), in the session document `slicc.owner-always`. A later call with the same tool and arguments then runs unasked, from any of the owner's agents, while `owner.tools` isn't `off`. `AgentControl.ownerAlways()` lists the rules without their hashes and `ownerAlwaysForget(approval)` removes one; both are owner-device methods, never a guest's.
779
+ - **In spectrum** an `owner-tool` item shows as a `guest-tool` approval (`tool`, `summary`, `args`, `argsTruncated`, `agentName`, `always`, the verdict), with `requester.name` `you`, so the current `<slicc-approvals>` reads "sliccy wants to run bash for you".
768
780
  - **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`:
769
781
  - **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.
770
782
  - **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.
@@ -817,6 +829,7 @@ The judge ([`src/approvals/judge.ts`](src/approvals/judge.ts)) gives a request a
817
829
  - **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.
818
830
  - **Abort:** the judge of an `agent` item runs with the request context's signal. When the request is aborted, the item is withdrawn (`aborted`) and a late verdict is dropped. After a reload, a pending `agent` item goes to a person.
819
831
  - **Evals:** [`evals/judge.json`](evals/judge.json) holds guest prompts, tool calls and sudo requests with their expected routing and, for some sudo cases, whether Always should be offered. A case brings `present`, whether an owner device is attached, and a sudo case its own owner messages and the kernel's facts. `SLICC_ADOBE_IMS_TOKEN=… npm run eval:judge -- --model adobe/clef --model adobe/clef-flash` runs them against Adobe's classifiers; `CLOUDFLARE_API_KEY=… CLOUDFLARE_ACCOUNT_ID=… npm run eval:judge -- --model cloudflare-workers-ai/@cf/cloudflare/clef` runs the same cases on Workers AI. Sudo cases run through `approvalJudge`, so they ask the action and intent calls as the agent does. Run either before changing the thresholds, questions or default policy. `--record` saves the probabilities it saw (`level` and `aligned` for a guest case, `actions` and `intent` for a sudo case), and CI replays those through the approvals surface. A non-blocking nightly (and `workflow_dispatch`) job runs the Cloudflare reference model.
832
+ - **A local judge (kev.js):** `npm run eval:judge -- --model local/ai-ecoverse/kev.js/kev-0.8b` runs the same cases on a System One classifier that [slicc-ortllama](https://github.com/ai-ecoverse/slicc-ortllama) serves (`ortllama serve`, at `SLICC_LOCAL_BASE`, `http://127.0.0.1:11435/v1` by default), through pi-ai's `typesafeSystemOneApi()`, with no key and at no cost. Kev-0.8B (`kev-0.8b@9a45d25`, `q8f32`, ortllama 1.29.6 on an Apple M4 Max CPU) isn't good enough to be `approvals.judgeModel` yet: it reached the expected routing in 30 of 42 cases, against 41 or 42 for Clef in the last five nightly runs. Its one strength is that it made no false approval, but only because it approved nothing: 0 of the 6 cases that should be approved. Clef, by contrast, approved `listing the sudoers rules` in 3 of those 5 runs. Kev also asked instead of denying 4 of the 6 cases that should be denied, and it denied a scoop's redacting read of the MCP config, which should go to a person. Its answers sit near 0.5 whatever the request, so no cut would fix this. For sudo, `permissions` is 0.63 to 0.80 and `code` 0.59 to 0.77 on every line, even plain reads, so `routine` is 0 throughout. For guests, the fake owner override gets a higher `aligned` (0.32) than any of the five cases it should approve (0.18 to 0.29). The veto barely moves with the nonce (at most 0.014 over 12 nonces, where Clef ranged from 0.15 to 0.67 on the out-of-scope read), but it reads 0.49 to 0.63 on every case, so it would veto any approval. Median latency per case, over three runs, was 250 to 330 ms for a guest case and 0.6 to 1.1 s for a sudo case, against about 280 ms and 460 ms for Clef on Workers AI. `kev-0.8b-vision` runs the same decoder and answers text requests the same way (also 30 of 42). Kev-4B (`kev-4b@139fdd9`, 4.7 GB) does better but isn't there either: 34 of 42, no false approval, 1 of the 6 approvals, and medians of 1.1 s for a guest case and 2.2 s for a sudo case. Its veto separates the cases (0.41 to 0.43 for the read the exclusion doesn't cover, 0.57 to 0.79 for the excluded ones, at most 0.034 apart over 12 nonces) but still sits over the 0.2 bar.
820
833
 
821
834
  ### Approval policy
822
835
 
@@ -830,8 +843,9 @@ All the limits on approvals and guests live in one owner-changeable policy, the
830
843
  - `guests.always: { messages: false, tools: false }`.
831
844
  - `sudo.approver: 'user'` (`'agent'` lets the judge decide sudo).
832
845
  - `sudo.runLate.maxAgeMinutes: 1440`, how long after its timeout a sudo request may still be run with Run now (0 to 10080 minutes; `0` turns Run now off). Set it as `approvalPolicySet({ sudo: { runLate: { maxAgeMinutes } } })`.
846
+ - `owner.tools: 'off'`, typed `'off' | 'user' | 'agent'`: who reviews the owner's own tool calls, nobody, a person or the judge (see The owner's tool calls in Approvals). Set it as `approvalPolicySet({ owner: { tools: 'user' } })`.
833
847
  - **Reading it:** `AgentTranscript.approvalPolicy` replicates it to every owner device.
834
- - **Changing it:** `AgentControl.approvalPolicySet({ guests?, sudo? })` changes the given entries. It's for owner devices only (the owner's pages, and followers with or without Control), never guests. It validates the change and answers `{ policy, error }`. Only the entries an owner device set are stored, as overrides read over the defaults, so a later default still reaches every entry nobody set.
848
+ - **Changing it:** `AgentControl.approvalPolicySet({ guests?, sudo?, owner? })` changes the given entries. It's for owner devices only (the owner's pages, and followers with or without Control), never guests. It validates the change and answers `{ policy, error }`. Only the entries an owner device set are stored, as overrides read over the defaults, so a later default still reaches every entry nobody set.
835
849
  - **Where it applies:** gates and expiry are checked when a seat opens, so a seat keeps its gates when the policy changes later.
836
850
  - **What it doesn't open:** the guest contract stays closed to everything but its own seat (`closedToGuests`). That's the default-deny base a later policy entry may open.
837
851
  - **Not policy:** the technical bounds (label 64, proposal 32,000 characters).
@@ -892,7 +906,7 @@ The agent worker never holds a secret's value. Values live in the vault (`vault.
892
906
  - **The wire** is slicc-vault's agent request/reply shape. The few wire types the agent needs (`AgentRecord`, `OutgoingRequest`, and the rest in `src/secrets/vault-types.ts`) are kept here so published `.d.ts` never name `@ai-ecoverse/slicc-vault`; that package is a devDependency for `npm run lint:vault-pi` and for `types/vault-conformance.ts`, which `npm run typecheck` uses to keep those copies equal to the vault's. Requests are `{ v: 1, id, op, ... }` and answers `{ v: 1, id, op, ... }` or `{ v: 1, id, error: { code, message } }`, in request order: `redact { texts }` (strings and `Uint8Array`s, answered in the same order and types, with `version`), the stream ops `redactStream`, `push { chunk }`, `end` and `drop` with the worker's string `stream` id, and `model`, `mcp`, `records`, `grant`, `refresh` and `endpoints`. The vault's first message, `welcome`, carries `status.scrub` and `status.locked`; version bumps come only from bios's `{ scrub }` posts and the `version` in answers.
893
907
  - **Credentials by placeholder.** `records()` lists the `model` and `mcp` records (names, placeholders, states, never values). It is read at start, whenever `version` changes, and after `connect`, `disconnect` and `remove`. The read-only `CredentialStore` behind pi-ai returns a model record's placeholder as the API key (found by `kind: 'model'` and `provider`), with the account's non-secret fields as its env (Bedrock's `region` as `AWS_REGION`); writing to it throws.
894
908
  - **The transport.** The worker's `fetch` is `vaultFetch`: a request to a configured provider's base URL (Bedrock's standard `bedrock-runtime.*.amazonaws.com` and `-fips` endpoints included, so the AWS SDK's bearer requests are covered), or one carrying a model placeholder in its URL or headers, goes out as `model { provider?, request }`; MCP requests go out as `mcp { server, request }`, discovery and client registration included. The vault returns the request scrubbed over every value and with the credential filled in its headers or URL, and the existing transport sends it (`loopbackFetch` for a server on `http://<port>.kernel.localhost`); the response comes back directly. `EAGAIN` prepares the request once more; a refusal becomes a response (403 for `EACCES`, with the vault's sentence); a 401 calls `refresh { provider | server }` once and sends again. A request the vault filled, and the code exchange of an MCP sign-in, don't follow redirects: they go out with `redirect: 'manual'`. A same-origin redirect goes back through the same op with the fetch spec's method and body rules, at most 5 times, so the vault's checks apply to the new URL. Any other redirect becomes a 403 that names only the origin, an opaque one included (`opaqueRedirect` from the transport), and it's an error if the transport reports that it followed one. The mode reaches the transport as `redirect` on its request, and a route that doesn't show it honours that (`traits.redirectPolicy`, or `traits.manualRedirects` without `traits.redirectHops`) gets no such request: it's a 403 before anything is sent. Nor does the worker's own fetch, so with no transport, or to the same origin, the same rule applies. Anything else passes through, and without a vault every request does. Transport errors name only the method and origin, never a prepared URL or header.
895
- - **Endpoints.** `endpoints { mcp: [{ server, url, names?, tokenUrl? }] }` is sent when the port opens and whenever `mcp.json` changes: every server URL with the `${NAME}`s its headers use. Registrations only add. The agent registers no model URL at all: from slicc-vault 1.13.0 every model provider's endpoints are built into the vault (pi-ai's catalog, Bedrock's regions and Adobe's proxy as `adobe`), and a custom base URL a user types (Azure's `customBase`) is registered by the page; the agent port's `{ provider, url }` would be a no-op anyway.
909
+ - **Endpoints.** `endpoints { mcp: [{ server, url, names?, tokenUrl? }] }` is sent when the port opens and whenever `mcp.json` changes: every server URL with the `${NAME}`s its headers use. Registrations only add. The agent registers no model URL at all: from slicc-vault 1.13.0 every model provider's endpoints are built into the vault (pi-ai's catalog, Bedrock's regions and Adobe's proxy as `adobe`), and a custom base URL a user types (Azure's and `local`'s `customBase`) is registered by the page; the agent port's `{ provider, url }` would be a no-op anyway.
896
910
  - **`slicc-secrets`**, a built-in extension modelled on [pi-fnox](https://github.com/Bucurenciu-Cristian/pi-fnox) (MIT, © 2026 Kicky), with its hooks mapped to pi-durable. fnox ([`@ai-ecoverse/wasi-fnox`](https://www.npmjs.com/package/@ai-ecoverse/wasi-fnox) 1.39, built by homescoop and used unpatched here) is seven's only secrets CLI; the agent adapts to its own commands and needs `fnox` on `PATH` in the home env.
897
911
  - **The listing**, read in the home env at start and whenever `version` changes (pi-fnox's `fnox export`; nothing goes into the worker's environment), joins three commands by name, none of which prints a value:
898
912
  - `fnox env --json --describe` gives the fnox config's keys (`kind: "secret"`), which are the `$NAME`s bash sees. It runs only with `--describe`: without it fnox prints values, so every command goes through one guard that refuses `fnox env` without `--describe`. `--for exec|shell` isn't passed, since fnox 1.39 ignores it when describing (both print the same keys).
package/dist/agent.js CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  MemoryStorage
7
7
  } from "@earendil-works/pi-durable";
8
8
  import { openAgents } from "./agents.js";
9
+ import { ownerToolGate } from "./approvals/owner-tools.js";
9
10
  import { sudoRuns } from "./approvals/run.js";
10
11
  import { guestToolGate } from "./guests/guard.js";
11
12
  import { guestReviews } from "./guests/review.js";
@@ -39,6 +40,8 @@ async function openAgent(options) {
39
40
  let opened;
40
41
  const gate = guestToolGate(() => opened);
41
42
  registry.install(gate.extension);
43
+ const ownerGate = ownerToolGate(() => opened);
44
+ registry.install(ownerGate.extension);
42
45
  const reviews = guestReviews();
43
46
  registry.install(reviews.extension);
44
47
  const scooped = scoopReviews();
@@ -76,6 +79,7 @@ async function openAgent(options) {
76
79
  agents,
77
80
  reviews,
78
81
  gate,
82
+ ownerGate,
79
83
  scoopReviews: scooped,
80
84
  sudoRuns: runs,
81
85
  reports,
package/dist/agent.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/agent.ts"],
4
- "sourcesContent": ["import type { Context } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Models } from '@earendil-works/pi-ai/models';\nimport {\n AssistantEntry,\n type Conversation,\n createRegistry,\n type EntryId,\n Harness,\n type HarnessOptions,\n MemoryStorage,\n type ModelRef,\n type Registry,\n type Storage,\n} from '@earendil-works/pi-durable';\nimport { type Agents, openAgents } from './agents.ts';\nimport { type SudoRuns, sudoRuns } from './approvals/run.ts';\nimport type { Clock } from './clock.ts';\nimport type { Cones } from './cone.ts';\nimport { type GuestToolGate, guestToolGate } from './guests/guard.ts';\nimport { type GuestReviews, guestReviews } from './guests/review.ts';\nimport { type ScoopReviews, scoopReviews } from './guests/scoop.ts';\nimport { createReports, type Reports } from './reports.ts';\nimport { createTimings, type Timings } from './timings.ts';\n\nexport interface AgentOptions {\n models: Models;\n model: ModelRef;\n storage?: Storage;\n registry?: Registry;\n settings?: HarnessOptions['settings'];\n env?: HarnessOptions['env'];\n conversationCreated?: HarnessOptions['conversationCreated'];\n context?: Context;\n beforeResume?: (harness: Harness, context: Context) => Promise<unknown>;\n clock?: Clock;\n}\n\nexport interface Agent extends Cones {\n readonly harness: Harness;\n readonly models: Models;\n readonly root: Conversation;\n readonly agents: Agents;\n readonly reviews: GuestReviews;\n readonly gate: GuestToolGate;\n readonly scoopReviews: ScoopReviews;\n readonly sudoRuns: SudoRuns;\n readonly reports: Reports;\n readonly timings: Timings;\n onCone(listener: (conversation: Conversation) => void | Promise<void>): () => void;\n prompt(text: string): Promise<string>;\n close(): Promise<void>;\n}\n\ninterface Block {\n type: string;\n text?: string;\n}\n\nexport function answerText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return (content as Block[])\n .filter((block) => block.type === 'text')\n .map((block) => block.text ?? '')\n .join('');\n}\n\nasync function prompt(root: Conversation, text: string, context: Context): Promise<string> {\n const submission = await root.submit({ type: 'input', content: text }, context);\n const settled = await submission.wait(context);\n const { answer, reason } = settled as { answer?: EntryId; reason?: string };\n if (answer === undefined) throw new Error(`unanswered: ${reason}`);\n const entry = await root.commit((tx) => tx.entry(AssistantEntry, answer), context);\n return answerText(entry?.model?.[0]?.content);\n}\n\nexport const SLICC_ATTRIBUTION = { name: 'SLICC', url: 'https://www.sliccy.com' };\nconst IDENTITY = { attribution: SLICC_ATTRIBUTION };\nfunction clocked(clock: Clock): Pick<HarnessOptions, 'now' | 'setTimer'> {\n return {\n now: () => clock.now(),\n setTimer: (callback, delayMs) => clock.setTimer(callback, delayMs),\n };\n}\n\nexport async function openAgent(options: AgentOptions): Promise<Agent> {\n const context = options.context ?? BACKGROUND_CONTEXT;\n const registry = options.registry ?? createRegistry();\n let opened: Harness | undefined;\n const gate = guestToolGate(() => opened);\n registry.install(gate.extension);\n const reviews = guestReviews();\n registry.install(reviews.extension);\n const scooped = scoopReviews();\n registry.install(scooped.extension);\n const runs = sudoRuns();\n registry.install(runs.extension);\n const reports = createReports();\n const timings = createTimings({\n onError: (error) => reports.record({ kind: 'listener_error', error }),\n });\n const harness = await Harness.open(\n options.storage ?? new MemoryStorage(),\n {\n models: options.models,\n registry,\n identity: IDENTITY,\n ...(options.settings ? { settings: options.settings } : {}),\n onReport: (report) => reports.record(report),\n telemetry: timings.telemetry,\n ...(options.clock ? clocked(options.clock) : {}),\n ...(options.env ? { env: options.env } : {}),\n ...(options.conversationCreated ? { conversationCreated: options.conversationCreated } : {}),\n },\n context\n );\n opened = harness;\n const root = await harness.root(context, { agent: { model: options.model } });\n const agents = await openAgents(harness, root, context);\n await options.beforeResume?.(harness, context);\n harness.resume();\n return {\n harness,\n models: options.models,\n root,\n agents,\n reviews,\n gate,\n scoopReviews: scooped,\n sudoRuns: runs,\n reports,\n timings,\n cone: () => agents.cone(),\n switchCone: (conversation, switching) => agents.switchCone(conversation, switching),\n onCone: (listener) => agents.onCone(listener),\n prompt: (text) => prompt(agents.cone(), text, context),\n close: () => harness.close(context),\n };\n}\n"],
5
- "mappings": "AACA,SAAS,0BAA0B;AAEnC;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,OAIK;AACP,SAAsB,kBAAkB;AACxC,SAAwB,gBAAgB;AAGxC,SAA6B,qBAAqB;AAClD,SAA4B,oBAAoB;AAChD,SAA4B,oBAAoB;AAChD,SAAS,qBAAmC;AAC5C,SAAS,qBAAmC;AAoCrC,SAAS,WAAW,SAA0B;AACnD,MAAI,OAAO,YAAY,SAAU,QAAO;AACxC,MAAI,CAAC,MAAM,QAAQ,OAAO,EAAG,QAAO;AACpC,SAAQ,QACL,OAAO,CAAC,UAAU,MAAM,SAAS,MAAM,EACvC,IAAI,CAAC,UAAU,MAAM,QAAQ,EAAE,EAC/B,KAAK,EAAE;AACZ;AAEA,eAAe,OAAO,MAAoB,MAAc,SAAmC;AACzF,QAAM,aAAa,MAAM,KAAK,OAAO,EAAE,MAAM,SAAS,SAAS,KAAK,GAAG,OAAO;AAC9E,QAAM,UAAU,MAAM,WAAW,KAAK,OAAO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AAA,MAC3C,WAAW,QAAQ;AAAA,MACnB,GAAI,QAAQ,QAAQ,QAAQ,QAAQ,KAAK,IAAI,CAAC;AAAA,MAC9C,GAAI,QAAQ,MAAM,EAAE,KAAK,QAAQ,IAAI,IAAI,CAAC;AAAA,MAC1C,GAAI,QAAQ,sBAAsB,EAAE,qBAAqB,QAAQ,oBAAoB,IAAI,CAAC;AAAA,IAC5F;AAAA,IACA;AAAA,EACF;AACA,WAAS;AACT,QAAM,OAAO,MAAM,QAAQ,KAAK,SAAS,EAAE,OAAO,EAAE,OAAO,QAAQ,MAAM,EAAE,CAAC;AAC5E,QAAM,SAAS,MAAM,WAAW,SAAS,MAAM,OAAO;AACtD,QAAM,QAAQ,eAAe,SAAS,OAAO;AAC7C,UAAQ,OAAO;AACf,SAAO;AAAA,IACL;AAAA,IACA,QAAQ,QAAQ;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc;AAAA,IACd,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA,MAAM,MAAM,OAAO,KAAK;AAAA,IACxB,YAAY,CAAC,cAAc,cAAc,OAAO,WAAW,cAAc,SAAS;AAAA,IAClF,QAAQ,CAAC,aAAa,OAAO,OAAO,QAAQ;AAAA,IAC5C,QAAQ,CAAC,SAAS,OAAO,OAAO,KAAK,GAAG,MAAM,OAAO;AAAA,IACrD,OAAO,MAAM,QAAQ,MAAM,OAAO;AAAA,EACpC;AACF;",
4
+ "sourcesContent": ["import type { Context } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Models } from '@earendil-works/pi-ai/models';\nimport {\n AssistantEntry,\n type Conversation,\n createRegistry,\n type EntryId,\n Harness,\n type HarnessOptions,\n MemoryStorage,\n type ModelRef,\n type Registry,\n type Storage,\n} from '@earendil-works/pi-durable';\nimport { type Agents, openAgents } from './agents.ts';\nimport { type OwnerToolGate, ownerToolGate } from './approvals/owner-tools.ts';\nimport { type SudoRuns, sudoRuns } from './approvals/run.ts';\nimport type { Clock } from './clock.ts';\nimport type { Cones } from './cone.ts';\nimport { type GuestToolGate, guestToolGate } from './guests/guard.ts';\nimport { type GuestReviews, guestReviews } from './guests/review.ts';\nimport { type ScoopReviews, scoopReviews } from './guests/scoop.ts';\nimport { createReports, type Reports } from './reports.ts';\nimport { createTimings, type Timings } from './timings.ts';\n\nexport interface AgentOptions {\n models: Models;\n model: ModelRef;\n storage?: Storage;\n registry?: Registry;\n settings?: HarnessOptions['settings'];\n env?: HarnessOptions['env'];\n conversationCreated?: HarnessOptions['conversationCreated'];\n context?: Context;\n beforeResume?: (harness: Harness, context: Context) => Promise<unknown>;\n clock?: Clock;\n}\n\nexport interface Agent extends Cones {\n readonly harness: Harness;\n readonly models: Models;\n readonly root: Conversation;\n readonly agents: Agents;\n readonly reviews: GuestReviews;\n readonly gate: GuestToolGate;\n readonly ownerGate: OwnerToolGate;\n readonly scoopReviews: ScoopReviews;\n readonly sudoRuns: SudoRuns;\n readonly reports: Reports;\n readonly timings: Timings;\n onCone(listener: (conversation: Conversation) => void | Promise<void>): () => void;\n prompt(text: string): Promise<string>;\n close(): Promise<void>;\n}\n\ninterface Block {\n type: string;\n text?: string;\n}\n\nexport function answerText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return (content as Block[])\n .filter((block) => block.type === 'text')\n .map((block) => block.text ?? '')\n .join('');\n}\n\nasync function prompt(root: Conversation, text: string, context: Context): Promise<string> {\n const submission = await root.submit({ type: 'input', content: text }, context);\n const settled = await submission.wait(context);\n const { answer, reason } = settled as { answer?: EntryId; reason?: string };\n if (answer === undefined) throw new Error(`unanswered: ${reason}`);\n const entry = await root.commit((tx) => tx.entry(AssistantEntry, answer), context);\n return answerText(entry?.model?.[0]?.content);\n}\n\nexport const SLICC_ATTRIBUTION = { name: 'SLICC', url: 'https://www.sliccy.com' };\nconst IDENTITY = { attribution: SLICC_ATTRIBUTION };\nfunction clocked(clock: Clock): Pick<HarnessOptions, 'now' | 'setTimer'> {\n return {\n now: () => clock.now(),\n setTimer: (callback, delayMs) => clock.setTimer(callback, delayMs),\n };\n}\n\nexport async function openAgent(options: AgentOptions): Promise<Agent> {\n const context = options.context ?? BACKGROUND_CONTEXT;\n const registry = options.registry ?? createRegistry();\n let opened: Harness | undefined;\n const gate = guestToolGate(() => opened);\n registry.install(gate.extension);\n const ownerGate = ownerToolGate(() => opened);\n registry.install(ownerGate.extension);\n const reviews = guestReviews();\n registry.install(reviews.extension);\n const scooped = scoopReviews();\n registry.install(scooped.extension);\n const runs = sudoRuns();\n registry.install(runs.extension);\n const reports = createReports();\n const timings = createTimings({\n onError: (error) => reports.record({ kind: 'listener_error', error }),\n });\n const harness = await Harness.open(\n options.storage ?? new MemoryStorage(),\n {\n models: options.models,\n registry,\n identity: IDENTITY,\n ...(options.settings ? { settings: options.settings } : {}),\n onReport: (report) => reports.record(report),\n telemetry: timings.telemetry,\n ...(options.clock ? clocked(options.clock) : {}),\n ...(options.env ? { env: options.env } : {}),\n ...(options.conversationCreated ? { conversationCreated: options.conversationCreated } : {}),\n },\n context\n );\n opened = harness;\n const root = await harness.root(context, { agent: { model: options.model } });\n const agents = await openAgents(harness, root, context);\n await options.beforeResume?.(harness, context);\n harness.resume();\n return {\n harness,\n models: options.models,\n root,\n agents,\n reviews,\n gate,\n ownerGate,\n scoopReviews: scooped,\n sudoRuns: runs,\n reports,\n timings,\n cone: () => agents.cone(),\n switchCone: (conversation, switching) => agents.switchCone(conversation, switching),\n onCone: (listener) => agents.onCone(listener),\n prompt: (text) => prompt(agents.cone(), text, context),\n close: () => harness.close(context),\n };\n}\n"],
5
+ "mappings": "AACA,SAAS,0BAA0B;AAEnC;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,OAIK;AACP,SAAsB,kBAAkB;AACxC,SAA6B,qBAAqB;AAClD,SAAwB,gBAAgB;AAGxC,SAA6B,qBAAqB;AAClD,SAA4B,oBAAoB;AACh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,OAAO,WAAW,cAAc,SAAS;AAAA,IAClF,QAAQ,CAAC,aAAa,OAAO,OAAO,QAAQ;AAAA,IAC5C,QAAQ,CAAC,SAAS,OAAO,OAAO,KAAK,GAAG,MAAM,OAAO;AAAA,IACrD,OAAO,MAAM,QAAQ,MAAM,OAAO;AAAA,EACpC;AACF;",
6
6
  "names": []
7
7
  }
@@ -57,7 +57,10 @@ function mark(item, how, at) {
57
57
  delete item.judging;
58
58
  if (how.reason) item.reason = how.reason;
59
59
  }
60
- const offered = (options, draft) => guestKind(draft.kind) && draft.kind !== "capture" ? options.guestAlways?.(draft.kind) === true : false;
60
+ const offered = (options, draft) => {
61
+ if (draft.kind === "owner-tool") return true;
62
+ return guestKind(draft.kind) && draft.kind !== "capture" ? options.guestAlways?.(draft.kind) === true : false;
63
+ };
61
64
  const judgedKind = (item, tier) => !personOnly(item) && (item.kind === "sudo" || tier === "agent" || tier === "user");
62
65
  function detailOf(draft) {
63
66
  if (draft.kind !== "sudo" || draft.always !== false) return draft.detail;
@@ -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 { Conversation, ConversationView, 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 { type ApprovalPolicies, alwaysFor } from './policy.ts';\nimport { type Attendance, ownerPresent } from './present.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 personOnly,\n prune,\n REASONS,\n type Routed,\n type Ruling,\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 resume(agentId: string): void;\n close(): void;\n}\n\nexport interface ScoopRouter {\n route(item: Approval): Promise<void>;\n}\n\nexport const STOP_WAIT_MS = 30_000;\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 stop?: (agentId: string, context: Context) => Promise<void>;\n turnOf?: (agentId: string, context: Context) => Promise<Conversation | undefined>;\n stopWaitMs?: number;\n}\n\nexport function stopOf(agents: {\n conversation(\n agentId: string,\n context: Context\n ): Promise<(Conversation & { abort(context: Context): Promise<void> }) | undefined>;\n}): Pick<ApprovalsAttach, 'stop' | 'turnOf'> {\n return {\n stop: async (agentId, using) => (await agents.conversation(agentId, using))?.abort(using),\n turnOf: (agentId, using) => agents.conversation(agentId, using),\n };\n}\n\nexport function stoppingAttach(\n agent: {\n agents: Parameters<typeof stopOf>[0] & { state(): unknown };\n harness: ApprovalsAttach['harness'];\n scoopReviews: ApprovalsAttach['scoops'];\n },\n policy: ApprovalPolicies,\n owners: Attendance,\n options: { judge?: ApprovalJudge; approvalMs?: number } = {}\n): ApprovalsAttach {\n return {\n harness: agent.harness,\n guestAlways: alwaysFor(policy),\n sudoApprover: () => policy.current().sudo.approver,\n present: ownerPresent({ attended: owners.attended, agents: agent.agents as never }),\n scoops: agent.scoopReviews,\n ...stopOf(agent.agents),\n ...(options.judge ? { judge: options.judge } : {}),\n ...(options.approvalMs ? { ttlMs: options.approvalMs } : {}),\n };\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 = (item: Pick<ApprovalDraft, 'kind' | 'detail'>, tier: string) =>\n !personOnly(item) && (item.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, 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, 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\nexport const NO_STOP = \"This agent can't stop a turn.\";\n\ntype Halts = ReturnType<typeof haltsOf>;\n\ntype Halt = { agentId: string; done: Promise<void>; release: () => void };\n\nconst runningOf = (view: ConversationView | undefined) =>\n Boolean((view?.docs?.['pi.live'] as { run?: unknown } | undefined)?.run);\n\nfunction bounded(done: Promise<void>, ms: number): Promise<void> {\n let clear = () => {};\n const timer = new Promise<void>((resolve) => {\n const id = setTimeout(resolve, ms);\n clear = () => clearTimeout(id);\n });\n return Promise.race([done, timer]).finally(clear);\n}\n\nfunction armResume(\n resume: (agentId: string) => void,\n turnOf: ApprovalsAttach['turnOf'],\n agentId: string\n) {\n if (!turnOf) return;\n void turnOf(agentId, BACKGROUND_CONTEXT)\n .then(async (conversation) => {\n if (!conversation) return;\n const watched = await conversation.watch(BACKGROUND_CONTEXT);\n let idle = !runningOf(watched.value);\n watched.start(async (call) => {\n if (call.kind !== 'value') return;\n const running = runningOf(call.value);\n if (idle && running) {\n resume(agentId);\n await watched.stop();\n }\n idle = !running;\n });\n })\n .catch(() => undefined);\n}\n\nfunction haltsOf(\n stop: ApprovalsAttach['stop'],\n turnOf: ApprovalsAttach['turnOf'],\n stopWaitMs: number\n) {\n const stopping = new Map<object, Halt>();\n const stopped = new Set<string>();\n const of = (agentId: string) =>\n [...stopping.values()].filter((entry) => entry.agentId === agentId);\n const drop = (token: object) => {\n stopping.get(token)?.release();\n stopping.delete(token);\n };\n const resume = (agentId: string) => {\n stopped.delete(agentId);\n };\n return {\n halted: (agentId: string) => of(agentId).length > 0 || stopped.has(agentId),\n async idle(agentId: string) {\n while (of(agentId).length) await Promise.all(of(agentId).map((entry) => entry.done));\n },\n able: (ruling: Ruling): Ruling => (ruling.stop && !stop ? { error: NO_STOP } : ruling),\n begin(token: object, agentId: string) {\n let release = () => {};\n const done = new Promise<void>((resolve) => {\n release = resolve;\n });\n drop(token);\n stopping.set(token, { agentId, done, release });\n stopped.add(agentId);\n },\n drop,\n resume,\n async end(token: object) {\n const entry = stopping.get(token);\n if (!entry) return;\n const done = Promise.resolve()\n .then(() => stop?.(entry.agentId, BACKGROUND_CONTEXT))\n .catch(() => undefined);\n await bounded(done, stopWaitMs);\n drop(token);\n armResume(resume, turnOf, entry.agentId);\n },\n };\n}\n\ntype Deciding = {\n token: object;\n by: DecidedBy;\n device: string | undefined;\n ruling: (item: Approval) => Ruling;\n halts: Halts;\n now: () => number;\n};\n\nconst decidedIn =\n (id: string, { token, by, device, ruling: rule, halts, now }: Deciding) =>\n (doc: ApprovalsState): ApprovalDecided => {\n halts.drop(token);\n const item = doc.items.find((entry) => entry.id === id);\n const ruling: Ruling = item ? rule(item) : { 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 mark(item, ruling.settle, now());\n }\n if (ruling.error) return { done: false, state: null, error: ruling.error };\n if (ruling.stop) {\n halts.begin(token, ruling.stop);\n stoppedIn(ruling.stop, id, now)(doc);\n }\n return { done: true, state: (item as Approval).state, error: null };\n };\n\nconst stoppedIn = (agentId: string, id: string, now: () => number) =>\n withdrawIn(\n (item) => item.id !== id && item.agentId === agentId && heldKind(item.kind),\n REASONS.stopped,\n now\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 const halts = haltsOf(options.stop, options.turnOf, options.stopWaitMs ?? STOP_WAIT_MS);\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 held = heldKind(draft.kind) && halts.halted(draft.agentId);\n if (held) await halts.idle(draft.agentId);\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 if (item.state === 'pending' && heldKind(item.kind) && (held || halts.halted(item.agentId)))\n settle(item, { state: 'withdrawn', by: 'host', reason: REASONS.stopped });\n doc.items.push(item);\n return copy([item])[0] as Approval;\n }, using);\n if (created && options.judge && made.state === 'pending' && judgedKind(made, made.tier))\n void judging(options.judge, made, made.tier === 'agent' ? using : BACKGROUND_CONTEXT);\n if (created) toScoop(made);\n return made;\n },\n async decide(id, answer, reason, decider, using) {\n const { by, device } = deciderOf(decider);\n const token = {};\n const ruling = (item: Approval) => halts.able(ruled(item, answer, reason, by, now()));\n const deciding = { token, by, device, ruling, halts, now };\n const decided = await serial(decidedIn(id, deciding), using).catch((error: unknown) => {\n halts.drop(token);\n throw error;\n });\n await halts.end(token);\n return decided;\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 resume(agentId) {\n halts.resume(agentId);\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,SAAgC,iBAAiB;AACjD,SAA0B,oBAAoB;AAC9C;AAAA,EACE;AAAA,EAKA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;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;AAyBlF,MAAM,eAAe;AAiBrB,SAAS,OAAO,QAKsB;AAC3C,SAAO;AAAA,IACL,MAAM,OAAO,SAAS,WAAW,MAAM,OAAO,aAAa,SAAS,KAAK,IAAI,MAAM,KAAK;AAAA,IACxF,QAAQ,CAAC,SAAS,UAAU,OAAO,aAAa,SAAS,KAAK;AAAA,EAChE;AACF;AAEO,SAAS,eACd,OAKA,QACA,QACA,UAA0D,CAAC,GAC1C;AACjB,SAAO;AAAA,IACL,SAAS,M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Q,OAAO;AAChC,YAAM,CAAC,GAAG,IAAI,MAAM;AAAA,QAClB,cAAc,CAAC,SAAS,KAAK,OAAO,IAAI,YAAY,MAAM,CAAC;AAAA,QAC3D;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,IACA,MAAM,aAAa,MAAM,OAAO;AAC9B,cACE,MAAM;AAAA,QACJ,cAAc,CAAC,SAAS,KAAK,SAAS,MAAM,QAAQ,OAAO;AAAA,QAC3D;AAAA,MACF,GACA;AAAA,IACJ;AAAA,IACA,MAAM,OAAO,IAAI,OAAO;AACtB,aAAO,OAAO,CAAC,QAAQ;AACrB,cAAM,OAAO,IAAI,MAAM,KAAK,CAAC,UAAU,MAAM,OAAO,EAAE;AACtD,YAAI,MAAM,UAAU,aAAa,KAAK,aAAa,IAAI;AACrD,iBAAO,MAAM,EAAE,OAAO,cAAc,IAAI,QAAQ,QAAQ,QAAQ,QAAQ,CAAC;AAC3E,eAAO,OAAQ,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,IAAiB;AAAA,MAChD,GAAG,KAAK;AAAA,IACV;AAAA,IACA,OAAO,SAAS;AACd,YAAM,OAAO,OAAO;AAAA,IACtB;AAAA,IACA,QAAQ;AACN,eAAS;AACT,iBAAW,SAAS,OAAO,OAAO,EAAG,OAAM;AAC3C,aAAO,MAAM;AACb,WAAK,MAAM,KAAK;AAAA,IAClB;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import {\n type Context,\n type ReplicatedState,\n replicatedState,\n type WatchHandle,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Conversation, ConversationView, 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 { type ApprovalPolicies, alwaysFor } from './policy.ts';\nimport { type Attendance, ownerPresent } from './present.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 personOnly,\n prune,\n REASONS,\n type Routed,\n type Ruling,\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 resume(agentId: string): void;\n close(): void;\n}\n\nexport interface ScoopRouter {\n route(item: Approval): Promise<void>;\n}\n\nexport const STOP_WAIT_MS = 30_000;\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 stop?: (agentId: string, context: Context) => Promise<void>;\n turnOf?: (agentId: string, context: Context) => Promise<Conversation | undefined>;\n stopWaitMs?: number;\n}\n\nexport function stopOf(agents: {\n conversation(\n agentId: string,\n context: Context\n ): Promise<(Conversation & { abort(context: Context): Promise<void> }) | undefined>;\n}): Pick<ApprovalsAttach, 'stop' | 'turnOf'> {\n return {\n stop: async (agentId, using) => (await agents.conversation(agentId, using))?.abort(using),\n turnOf: (agentId, using) => agents.conversation(agentId, using),\n };\n}\n\nexport function stoppingAttach(\n agent: {\n agents: Parameters<typeof stopOf>[0] & { state(): unknown };\n harness: ApprovalsAttach['harness'];\n scoopReviews: ApprovalsAttach['scoops'];\n },\n policy: ApprovalPolicies,\n owners: Attendance,\n options: { judge?: ApprovalJudge; approvalMs?: number } = {}\n): ApprovalsAttach {\n return {\n harness: agent.harness,\n guestAlways: alwaysFor(policy),\n sudoApprover: () => policy.current().sudo.approver,\n present: ownerPresent({ attended: owners.attended, agents: agent.agents as never }),\n scoops: agent.scoopReviews,\n ...stopOf(agent.agents),\n ...(options.judge ? { judge: options.judge } : {}),\n ...(options.approvalMs ? { ttlMs: options.approvalMs } : {}),\n };\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 if (draft.kind === 'owner-tool') return true;\n return guestKind(draft.kind) && draft.kind !== 'capture'\n ? options.guestAlways?.(draft.kind) === true\n : false;\n};\n\nconst judgedKind = (item: Pick<ApprovalDraft, 'kind' | 'detail'>, tier: string) =>\n !personOnly(item) && (item.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, 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, 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\nexport const NO_STOP = \"This agent can't stop a turn.\";\n\ntype Halts = ReturnType<typeof haltsOf>;\n\ntype Halt = { agentId: string; done: Promise<void>; release: () => void };\n\nconst runningOf = (view: ConversationView | undefined) =>\n Boolean((view?.docs?.['pi.live'] as { run?: unknown } | undefined)?.run);\n\nfunction bounded(done: Promise<void>, ms: number): Promise<void> {\n let clear = () => {};\n const timer = new Promise<void>((resolve) => {\n const id = setTimeout(resolve, ms);\n clear = () => clearTimeout(id);\n });\n return Promise.race([done, timer]).finally(clear);\n}\n\nfunction armResume(\n resume: (agentId: string) => void,\n turnOf: ApprovalsAttach['turnOf'],\n agentId: string\n) {\n if (!turnOf) return;\n void turnOf(agentId, BACKGROUND_CONTEXT)\n .then(async (conversation) => {\n if (!conversation) return;\n const watched = await conversation.watch(BACKGROUND_CONTEXT);\n let idle = !runningOf(watched.value);\n watched.start(async (call) => {\n if (call.kind !== 'value') return;\n const running = runningOf(call.value);\n if (idle && running) {\n resume(agentId);\n await watched.stop();\n }\n idle = !running;\n });\n })\n .catch(() => undefined);\n}\n\nfunction haltsOf(\n stop: ApprovalsAttach['stop'],\n turnOf: ApprovalsAttach['turnOf'],\n stopWaitMs: number\n) {\n const stopping = new Map<object, Halt>();\n const stopped = new Set<string>();\n const of = (agentId: string) =>\n [...stopping.values()].filter((entry) => entry.agentId === agentId);\n const drop = (token: object) => {\n stopping.get(token)?.release();\n stopping.delete(token);\n };\n const resume = (agentId: string) => {\n stopped.delete(agentId);\n };\n return {\n halted: (agentId: string) => of(agentId).length > 0 || stopped.has(agentId),\n async idle(agentId: string) {\n while (of(agentId).length) await Promise.all(of(agentId).map((entry) => entry.done));\n },\n able: (ruling: Ruling): Ruling => (ruling.stop && !stop ? { error: NO_STOP } : ruling),\n begin(token: object, agentId: string) {\n let release = () => {};\n const done = new Promise<void>((resolve) => {\n release = resolve;\n });\n drop(token);\n stopping.set(token, { agentId, done, release });\n stopped.add(agentId);\n },\n drop,\n resume,\n async end(token: object) {\n const entry = stopping.get(token);\n if (!entry) return;\n const done = Promise.resolve()\n .then(() => stop?.(entry.agentId, BACKGROUND_CONTEXT))\n .catch(() => undefined);\n await bounded(done, stopWaitMs);\n drop(token);\n armResume(resume, turnOf, entry.agentId);\n },\n };\n}\n\ntype Deciding = {\n token: object;\n by: DecidedBy;\n device: string | undefined;\n ruling: (item: Approval) => Ruling;\n halts: Halts;\n now: () => number;\n};\n\nconst decidedIn =\n (id: string, { token, by, device, ruling: rule, halts, now }: Deciding) =>\n (doc: ApprovalsState): ApprovalDecided => {\n halts.drop(token);\n const item = doc.items.find((entry) => entry.id === id);\n const ruling: Ruling = item ? rule(item) : { 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 mark(item, ruling.settle, now());\n }\n if (ruling.error) return { done: false, state: null, error: ruling.error };\n if (ruling.stop) {\n halts.begin(token, ruling.stop);\n stoppedIn(ruling.stop, id, now)(doc);\n }\n return { done: true, state: (item as Approval).state, error: null };\n };\n\nconst stoppedIn = (agentId: string, id: string, now: () => number) =>\n withdrawIn(\n (item) => item.id !== id && item.agentId === agentId && heldKind(item.kind),\n REASONS.stopped,\n now\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 const halts = haltsOf(options.stop, options.turnOf, options.stopWaitMs ?? STOP_WAIT_MS);\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 held = heldKind(draft.kind) && halts.halted(draft.agentId);\n if (held) await halts.idle(draft.agentId);\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 if (item.state === 'pending' && heldKind(item.kind) && (held || halts.halted(item.agentId)))\n settle(item, { state: 'withdrawn', by: 'host', reason: REASONS.stopped });\n doc.items.push(item);\n return copy([item])[0] as Approval;\n }, using);\n if (created && options.judge && made.state === 'pending' && judgedKind(made, made.tier))\n void judging(options.judge, made, made.tier === 'agent' ? using : BACKGROUND_CONTEXT);\n if (created) toScoop(made);\n return made;\n },\n async decide(id, answer, reason, decider, using) {\n const { by, device } = deciderOf(decider);\n const token = {};\n const ruling = (item: Approval) => halts.able(ruled(item, answer, reason, by, now()));\n const deciding = { token, by, device, ruling, halts, now };\n const decided = await serial(decidedIn(id, deciding), using).catch((error: unknown) => {\n halts.drop(token);\n throw error;\n });\n await halts.end(token);\n return decided;\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 resume(agentId) {\n halts.resume(agentId);\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,SAAgC,iBAAiB;AACjD,SAA0B,oBAAoB;AAC9C;AAAA,EACE;AAAA,EAKA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAGA;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;AAyBlF,MAAM,eAAe;AAiBrB,SAAS,OAAO,QAKsB;AAC3C,SAAO;AAAA,IACL,MAAM,OAAO,SAAS,WAAW,MAAM,OAAO,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AM,OAAO,IAAI,MAAM,KAAK,CAAC,UAAU,MAAM,OAAO,EAAE;AACtD,YAAI,MAAM,UAAU,aAAa,UAAU,KAAK,IAAI,EAAG,MAAK,aAAa;AACzE,eAAO,OAAQ,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,IAAiB;AAAA,MAChD,GAAG,KAAK;AAAA,IACV;AAAA,IACA,MAAM,SAAS,IAAI,QAAQ,OAAO;AAChC,YAAM,CAAC,GAAG,IAAI,MAAM;AAAA,QAClB,cAAc,CAAC,SAAS,KAAK,OAAO,IAAI,YAAY,MAAM,CAAC;AAAA,QAC3D;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,IACA,MAAM,aAAa,MAAM,OAAO;AAC9B,cACE,MAAM;AAAA,QACJ,cAAc,CAAC,SAAS,KAAK,SAAS,MAAM,QAAQ,OAAO;AAAA,QAC3D;AAAA,MACF,GACA;AAAA,IACJ;AAAA,IACA,MAAM,OAAO,IAAI,OAAO;AACtB,aAAO,OAAO,CAAC,QAAQ;AACrB,cAAM,OAAO,IAAI,MAAM,KAAK,CAAC,UAAU,MAAM,OAAO,EAAE;AACtD,YAAI,MAAM,UAAU,aAAa,KAAK,aAAa,IAAI;AACrD,iBAAO,MAAM,EAAE,OAAO,cAAc,IAAI,QAAQ,QAAQ,QAAQ,QAAQ,CAAC;AAC3E,eAAO,OAAQ,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,IAAiB;AAAA,MAChD,GAAG,KAAK;AAAA,IACV;AAAA,IACA,OAAO,SAAS;AACd,YAAM,OAAO,OAAO;AAAA,IACtB;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
  }
@@ -182,7 +182,8 @@ function captureText(detail) {
182
182
  }
183
183
  function untrustedOf(item) {
184
184
  if (item.kind === "guest-message") return item.detail.text;
185
- if (item.kind === "guest-tool") return `${item.detail.tool}: ${item.detail.summary}`;
185
+ if (item.kind === "guest-tool" || item.kind === "owner-tool")
186
+ return `${item.detail.tool}: ${item.detail.summary}`;
186
187
  if (item.kind === "capture") return captureText(item.detail);
187
188
  return sudoText(item.detail);
188
189
  }