@ai-ecoverse/slicc-agent 7.30.3 → 7.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -7
- package/dist/agent.js +4 -0
- package/dist/agent.js.map +2 -2
- package/dist/approvals/policy.js +27 -5
- package/dist/approvals/policy.js.map +2 -2
- package/dist/approvals/published.js +18 -0
- package/dist/approvals/published.js.map +7 -0
- package/dist/approvals/record.js +4 -1
- package/dist/approvals/record.js.map +2 -2
- package/dist/approvals/run-licks.js +137 -0
- package/dist/approvals/run-licks.js.map +7 -0
- package/dist/approvals/run-procs.js +127 -0
- package/dist/approvals/run-procs.js.map +7 -0
- package/dist/approvals/run.js +468 -0
- package/dist/approvals/run.js.map +7 -0
- package/dist/approvals/runnable.js +125 -0
- package/dist/approvals/runnable.js.map +7 -0
- package/dist/approvals/sudo.js +29 -1
- package/dist/approvals/sudo.js.map +2 -2
- package/dist/client.js +1 -0
- package/dist/client.js.map +2 -2
- package/dist/control.js +7 -1
- package/dist/control.js.map +2 -2
- package/dist/freezer/index.js +4 -1
- package/dist/freezer/index.js.map +2 -2
- package/dist/guests/attribution.js +4 -0
- package/dist/guests/attribution.js.map +2 -2
- package/dist/guests/guard.js +28 -3
- package/dist/guests/guard.js.map +2 -2
- package/dist/guests/view.js +20 -4
- package/dist/guests/view.js.map +2 -2
- package/dist/host.js +69 -16
- package/dist/host.js.map +2 -2
- package/dist/images/markers.js +2 -7
- package/dist/images/markers.js.map +2 -2
- package/dist/index.js +14 -0
- package/dist/index.js.map +2 -2
- package/dist/intent/index.js +75 -0
- package/dist/intent/index.js.map +7 -0
- package/dist/intent/said.js +26 -0
- package/dist/intent/said.js.map +7 -0
- package/dist/kernel/with-exec.js +13 -0
- package/dist/kernel/with-exec.js.map +7 -0
- package/dist/licks/extension.js +1 -0
- package/dist/licks/extension.js.map +2 -2
- package/dist/licks/lick.js +1 -0
- package/dist/licks/lick.js.map +2 -2
- package/dist/main.js +15 -6
- package/dist/main.js.map +2 -2
- package/dist/services.js +7 -2
- package/dist/services.js.map +2 -2
- package/dist/settings.js +1 -0
- package/dist/settings.js.map +2 -2
- package/dist/spectrum/agent-port.js +13 -2
- package/dist/spectrum/agent-port.js.map +2 -2
- package/dist/spectrum/approvals-port.js +69 -0
- package/dist/spectrum/approvals-port.js.map +2 -2
- package/dist/spectrum/messages.js +35 -16
- package/dist/spectrum/messages.js.map +2 -2
- package/dist/spectrum/monitor-port.js +2 -1
- package/dist/spectrum/monitor-port.js.map +2 -2
- package/dist/spectrum/tool-title.js +11 -8
- package/dist/spectrum/tool-title.js.map +2 -2
- package/dist/titles/cluster.js +15 -4
- package/dist/titles/cluster.js.map +2 -2
- package/dist/titles/generate.js +6 -2
- package/dist/titles/generate.js.map +2 -2
- package/dist/titles/labels.js +2 -7
- package/dist/titles/labels.js.map +2 -2
- package/dist/titles/shown.js +6 -0
- package/dist/titles/shown.js.map +2 -2
- package/dist/types/agent.d.ts +2 -0
- package/dist/types/approvals/policy.d.ts +10 -1
- package/dist/types/approvals/published.d.ts +3 -0
- package/dist/types/approvals/record.d.ts +44 -1
- package/dist/types/approvals/run-licks.d.ts +18 -0
- package/dist/types/approvals/run-procs.d.ts +40 -0
- package/dist/types/approvals/run.d.ts +60 -0
- package/dist/types/approvals/runnable.d.ts +55 -0
- package/dist/types/approvals/sudo.d.ts +3 -1
- package/dist/types/client.d.ts +2 -0
- package/dist/types/guests/attribution.d.ts +5 -0
- package/dist/types/guests/guard.d.ts +1 -1
- package/dist/types/host.d.ts +10 -0
- package/dist/types/index.d.ts +4 -1
- package/dist/types/intent/index.d.ts +7 -0
- package/dist/types/intent/said.d.ts +4 -0
- package/dist/types/kernel/client.d.ts +35 -0
- package/dist/types/kernel/with-exec.d.ts +2 -0
- package/dist/types/licks/lick.d.ts +1 -1
- package/dist/types/licks/triage.d.ts +1 -1
- package/dist/types/main.d.ts +2 -1
- package/dist/types/services.d.ts +8 -2
- package/dist/types/settings.d.ts +1 -0
- package/dist/types/spectrum/approvals-port.d.ts +10 -2
- package/dist/types/spectrum/messages.d.ts +3 -2
- package/dist/types/spectrum/tool-title.d.ts +1 -1
- package/dist/types/titles/cluster.d.ts +1 -0
- package/dist/types/titles/generate.d.ts +3 -2
- package/dist/types/titles/labels.d.ts +1 -1
- package/dist/types/titles/shown.d.ts +1 -0
- package/package.json +3 -3
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()`, and `webhook(name, { id?, headers?, body })`, which hands a webhook delivery, such as one from the tray hub, to the licks without a chord `Context`), `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`, `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`, `guestOpen`, `guestRevoke`, `guestAlwaysForget` 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.
|
|
@@ -164,7 +164,7 @@ The first provider is AWS Bedrock with a Bedrock API key as the bearer token; th
|
|
|
164
164
|
|
|
165
165
|
### In slicc-spectrum
|
|
166
166
|
|
|
167
|
-
`@ai-ecoverse/slicc-spectrum` is an optional peer dependency, `^2.
|
|
167
|
+
`@ai-ecoverse/slicc-spectrum` is an optional peer dependency, `^2.14.0`. 2.14.0 is the first release with the Approvals panel types (`ApprovalRecord`, `ApprovalRun`, the port's `history`, `run` and `stopRun`, and a lick's `approval` on the `sudo-run` channel), which the approvals adapter and the lick cards send. 2.4.1 is the first release with a capture approval (`CaptureApproval`). 1.112.0 makes an approval verdict's `decision` optional, which the agent no longer sends. 1.102.0 types a guest tool approval's `args` and `argsTruncated`, and 1.103.0 shows a device sign-in's `signIn` code and link in Settings. 1.107.0 heads the budget with its provider: the tray's `budget.provider` and the Monitor vital's `provider` and `window` (older releases ignore them). 1.94.0 is the first release with the provider picker (`providers()`, `remove`, `vaultName`, `customBase`, a field's `options` and `value`); 1.94.1 shows a field with `options` as an `sp-picker` on its `value`; 1.95.0 shows a `blocked` provider in the picker as unpickable with “Needs the SLICC extension or CLI”; 1.96.0 registers an MCP token's server URL (`Account.url`) with the vault itself, after a “Connect to {url}?” confirm, and offers Reconnect when the URL moves; and 1.98.0 saves a field's value as its `vaultSetting` on the vault record (`VaultPort.settings`, V3). `test/integration/settings-ui.test.mjs` checks each in a real `<slicc-settings>`: Bedrock's region picker on the stored region, a blocked provider that can't be picked until a CORS-free route appears, the moved note once `mcp.json` points a connected server elsewhere, and that adding Cloudflare Workers AI or Azure (by resource name) puts the key with its tenant fields as the record's vault `settings` (`CLOUDFLARE_ACCOUNT_ID`, `AZURE_OPENAI_RESOURCE_NAME`).
|
|
168
168
|
|
|
169
169
|
`@ai-ecoverse/slicc-agent/spectrum` turns an `AgentConnection` into slicc-spectrum's `AgentPort`, so `<slicc-app>` shows the real agent:
|
|
170
170
|
|
|
@@ -181,7 +181,7 @@ The adapter keeps the replicated transcript and maps it on every update. User, a
|
|
|
181
181
|
|
|
182
182
|
**Older messages.** An agent's view is durable's window, its newest 50 to 100 entries, approval verdicts and other entries the chat doesn't show included, so by itself it holds only the last few turns. The adapter keeps each agent's whole transcript in a pi-durable `ConversationTranscript` instead: every view merges into it, so messages the window drops stay, and a window that jumps ahead (a reconnect, a burst) leaves a gap the adapter fills at once, from its newest side, up to 40 pages (4,000 entries) per gap. A bigger jump keeps only the newest entries, contiguous, and the rest comes back through `older()`, so a gap never downloads a whole conversation. `older(agentId, before)` loads earlier pages of 100 entries through `AgentControl.entries` until at least one message older than the message `before` appears, or the conversation starts, and resolves the messages before `before` (before the first message when `before` is unknown); `messages(agentId)` holds them from then on, and the change emits `messages`. An empty answer means the start is reached, and `hasOlder(agentId)` says whether there is more. Concurrent calls share one load, an agent's older answers never count as unread, a notice stays after the last committed message it followed (not after a reply still streaming, a queued input or a retry, whose ids change), and a new conversation (New chat, a rewind's fork) starts a new transcript. `AgentControl.entries({ agentId, conversation, minEntryId?, maxEntryId?, order?, limit? })` answers `{ conversation, entries, more }`: a page of the agent's fork-aware history (`Conversation.entries()`), at most 200 entries, slimmed like the views (large images become thumbnails; a page waits at most 2 s for its own thumbnails, then answers with a placeholder), and an empty page when `conversation` is no longer the agent's. Owner, control and view-only seats have it. A view-only seat's `image` answers the full image of an entry only while the entry is in a current view, or when that seat itself read it through `entries` and the entry is still in that agent's current conversation (checked again on each call, so a page read before a rewind or a new chat, or by another seat, grants nothing); guests see only their window, and so does an adapter on an older agent whose control service doesn't offer `entries` (`connection.history` is `true` only when it does; `older()` then answers `[]` and `hasOlder()` `false`).
|
|
183
183
|
|
|
184
|
-
Each cone's active conversation is in the session document `slicc.agents` (the root until the first rewind). The host's transcript follows it across forks. Rewinding is refused while the cone itself is running or has queued input, because a fork starts with an empty inbox, but never because its scoops are busy (see Cones and scoops). A background compaction still running on the old branch finishes there. A fork also starts with fresh `pi.usage`. Credential and model errors lead with a plain sentence ("Bedrock rejected the API key.", "This model isn't available with the current account.") and keep the provider's raw error as `detail`, which spectrum (≥ 1.11.0) shows underneath. `busy()` and `queue()` read durable's live and inbox documents. Steering is the default (#4): a send or a steer goes out with `whenBusy: 'steer'`, so while a run is going it joins after the current tool round, and a `queue` send is a follow-up. User messages carry `delivered` from the host's deliveries; entries the host didn't record (from before a reload) count as steered when they follow a tool result. Cones and scoops are below; the freezer and questions come later. Licks show as spectrum's lick cards (below). slicc-spectrum is an optional peer dependency (`^2.
|
|
184
|
+
Each cone's active conversation is in the session document `slicc.agents` (the root until the first rewind). The host's transcript follows it across forks. Rewinding is refused while the cone itself is running or has queued input, because a fork starts with an empty inbox, but never because its scoops are busy (see Cones and scoops). A background compaction still running on the old branch finishes there. A fork also starts with fresh `pi.usage`. Credential and model errors lead with a plain sentence ("Bedrock rejected the API key.", "This model isn't available with the current account.") and keep the provider's raw error as `detail`, which spectrum (≥ 1.11.0) shows underneath. `busy()` and `queue()` read durable's live and inbox documents. Steering is the default (#4): a send or a steer goes out with `whenBusy: 'steer'`, so while a run is going it joins after the current tool round, and a `queue` send is a follow-up. User messages carry `delivered` from the host's deliveries; entries the host didn't record (from before a reload) count as steered when they follow a tool result. Cones and scoops are below; the freezer and questions come later. Licks show as spectrum's lick cards (below). slicc-spectrum is an optional peer dependency (`^2.14.0`, the lowest whose monitor, tray, panel, guest seat, guest and capture approval (with `args` and `argsTruncated`, and a verdict without `decision`), approvals history and profile import types match the agent's; `npm run typecheck` fails on anything older), used for types only, so package managers don't install it next to the agent.
|
|
185
185
|
|
|
186
186
|
Each agent in `list()` has a real `contextFill` and `unread`:
|
|
187
187
|
- **`contextFill`** is the context the agent uses, as a share of its model's `contextWindow` from the settings' model list. The tokens are those of the newest assistant's usage after the active head, counted the way pi-ai's `calculateContextTokens` does (`totalTokens`, or input, output and both cache counts). Aborted and failed turns don't count. After a compaction, the kept turns' usage no longer counts. Until the next turn reports its usage, the fill is estimated the way pi does it, at four characters a token, over the summary and the kept entries (without the system prompt and tools). An unknown model also reads 0. The Monitor's "Fullest context" and its context alerts use the same functions (`src/context.ts`).
|
|
@@ -497,9 +497,11 @@ pi durable keeps every conversation and entry in the session database, and has n
|
|
|
497
497
|
- The title moves with the cone. Freeze and New conversation copy it into the frozen row, then the final call replaces it there. Thaw brings that title back (and sets `titled` to the last early turn), also from a stopped scoop; if the thawed cone keeps chatting, the every-five-turns refresh can replace it later. A new conversation, or a scoop's reset, starts untitled.
|
|
498
498
|
- The Agents panel shows it as each cone's and scoop's summary (spectrum's `title`).
|
|
499
499
|
- The call goes through the same `Models` (and so `scope.fetch` and the vault) as every chat request.
|
|
500
|
-
- **Tool labels.** Spectrum groups tool runs into clusters and asks `AgentPort.toolLabel(agentId, callIds)` for a finished cluster of two or more runs. It asks `AgentPort.stepLabel(agentId, callId)` for a run that is going, the one run of a finished cluster, and every run of a cluster the user opens. The agent answers with
|
|
501
|
-
- **
|
|
502
|
-
- **
|
|
500
|
+
- **Tool labels.** Spectrum groups tool runs into clusters and asks `AgentPort.toolLabel(agentId, callIds)` for a finished cluster of two or more runs. It asks `AgentPort.stepLabel(agentId, callId)` for a run that is going, the one run of a finished cluster, and every run of a cluster the user opens. The agent answers with a label of three to eight words that starts with a present participle, such as "Checking the failing build logs", or `null`, and spectrum keeps its own title or summary either way. Every source of a label reads the same way: the model's own intent, the titles below and both label prompts.
|
|
501
|
+
- **Intents.** A wrapper (`slicc-intents`, like `slicc-images`) gives `bash` and `codemode` an optional `intent` argument, the first property of their schemas, so it streams before a long command or heredoc: "What this call does, as 2–6 words starting with a present participle, in the user's language, such as "Backing up the dataset's access list". At most 80 characters; a longer one is cut. No credentials, secrets or command output." The wrapper takes it out of the arguments before the tool runs, so the command runs unchanged. A nested `tools.bash()` in a codemode script gets the script's intent unless it sets its own. A trusted `bash` call runs with `SLICC_INTENT=<the cleaned intent>` in its environment, which every process it starts inherits (`playwright-cli` will read it). The schema sets no length limit, since pi's argument check would refuse the whole call, heredoc and all, for a long label: the intent is cleaned like a label instead (`cleanLabel`: whitespace, control and format characters such as bidi overrides and zero-width spaces, quotes and a final stop, cut to eight words and 80 characters), and secret-shaped text in it is redacted. The title cuts it again to 60 characters, like every title. `"toolIntents": false` in `~/.pi/agent/settings.json` leaves the field out of both schemas; it is read when the agent starts. The wrapper still strips an `intent` a call carries anyway, and such a call is titled, labelled and run as if it had none. The settings service says `toolIntents: true` only when intents are on, and the page titles a call by its intent only then.
|
|
502
|
+
- **An intent is a claim, not a fact.** A call in a run the guest guard gates (one a guest started, or one that inherited guest or lick taint, as for images from command output) never shows its intent and never gets `SLICC_INTENT`; the guard's memo (`gatedRun`) decides that for the spawn. The page can't see a run's taints, so the guard writes entries it can see, with no model message, so the model never sees them. Before each model request of a tainted run it writes a `slicc.tainted` entry (one in a row), and the adapter shows no intent for the tool calls of the next assistant message, the streaming one included. Taint can also arrive after that request, such as a guest-tainted `agent send` or `agent rename` to a scoop that is already streaming, so the guard also writes a `slicc.gated-call` entry (`{ callId }`) for each model-issued call it gates, before it reviews it; that call then shows its parsed title, also after a reload. The adapter fails closed: the first assistant message of a window that doesn't start at the transcript's start shows no intent, since its marker may be outside the window, and a paged transcript with a gap not yet filled shows none at all. A guest's view and the frozen markdown leave intents out of the tool calls they hold. The guard's reviewer, the judge and the approval cards get the arguments without `intent` (`summary`, `arguments`, `args` and the Always hash), and so does a step's input in the chat: they show what runs, never what the model says it does.
|
|
503
|
+
- **Step labels** come from the run's own name and arguments only, not its output, through the same model and scrubber, with their own prompt. While intents are on, a call that has an intent gets `null` without a label call, trusted or not: spectrum then shows its title, which is the intent for a trusted call and the parsed title for any other. The labellers never see an intent: it is left out of the arguments they get, for steps and clusters. A pull for a call the conversation doesn't have yet waits for it only while that call is going on, which spectrum sees while its arguments still stream: it is in the run's streaming message or tool slots in `pi.live`. Then it checks every 250 ms, for up to 30 seconds, until the call is written or leaves `pi.live`, so the label shows while the run still goes. Any other id, or one that isn't 1 to 256 characters without spaces, gets `null` at once. All pulls for one call share one wait, and each agent waits for at most 8 calls at a time and 60 a minute; over that, `null`. A watch-only seat never makes a label call or reads the conversation: it only waits for a label to show up, for at most 32 calls at a time per connection. A labelled call costs one label call, however many tabs ask, and its label is kept under `step:<call id>` in the same doc. Like clusters, only calls made after the agent started are labelled. Each agent makes at most 30 step labels a minute (`STEP_LABELS_PER_MINUTE`), apart from the cluster budget; a pull over it gets `null` and the run keeps its title.
|
|
504
|
+
- **Titles without a label.** A trusted `bash` or `codemode` call with an intent is titled by it, and the title follows the intent as it streams. Otherwise titles are present participles too. A bash call's title names the programs its command runs, such as `Running cd, rm, mkdir and more` (up to three, before any heredoc), or `Running a command`; `read`, `write` and `edit` are `Reading foo.ts`, `Writing bar.ts` and `Editing baz.md`, `codemode` is `Running code`, and an MCP tool is `Calling <server> · <tool>`.
|
|
503
505
|
- The label comes from the cluster's tool inputs and outputs (each output cut at 600 characters), through the title model and the title scrubber. A vault that is locked or not ready gives `null`, so no unscrubbed text goes out.
|
|
504
506
|
- A cluster pulled while it still runs (as spectrum used to do) costs about two calls. The first call happens when it forms, with any run still going shown as running. The second happens when it settles: every run has a result and the turn has moved on (assistant text, the end of the turn, or a new user message). A pull for a longer list while a run is still going doesn't call. It waits, up to ten minutes, for the cluster to settle and is then relabelled, unless an even longer pull takes over; then it gets the prefix's label. A cluster that settled and grows later gets one relabel. A pull for a list that a longer cached or pending one extends gets the prefix's label.
|
|
505
507
|
- Each id list costs at most one call, however many tabs ask, including calls still in flight. Labels live in the session's `slicc.labels` doc (the newest 1000) and reach every tab through the transcript service's `labels`. A reload, freeze or thaw reads them without calling again, and a watch-only tab only waits for one.
|
|
@@ -744,7 +746,7 @@ It prints the tab's stdout and stderr on their own streams and exits with its co
|
|
|
744
746
|
|
|
745
747
|
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.
|
|
746
748
|
|
|
747
|
-
- **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? }`) 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? }`.
|
|
749
|
+
- **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? }`.
|
|
748
750
|
- **`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`.
|
|
749
751
|
- **`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.
|
|
750
752
|
- **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).
|
|
@@ -761,6 +763,15 @@ Every approval, of a guest's prompt, of a tool call in a run a guest started, of
|
|
|
761
763
|
- **`sudo -v`:** a request with `validate: true` has no command (argv may be empty). It is always on the `user` tier, whatever `sudo.approver` says, the judge never sees it, and it never offers Always (`writable: false`). Its `detail` is only `{ command: 'start a sudo timestamp for <user> (no command)', validate: true, writable: false }`, and a scoop's lick says it asked to start a sudo timestamp. Any other request with an empty argv is refused.
|
|
762
764
|
- **Ends:** when the kernel aborts `signal` (`withdrawn`) the item is withdrawn, and on `expired` the page keeps its link until the record's own timeout settles it (`unanswered`), so it never reads as withdrawn. When the page's link closes the worker withdraws its open sudo items (`disconnected`). A restart or release of the owner first ends the old worker, then denies the requests still waiting, so the old worker never sees their links close, and the next worker withdraws their items (`restart`). The kernel already allows one pending request per user.
|
|
763
765
|
- **Scoops:** a scoop's request sends its cone a `sudo-request` lick without actions once a person has to answer it (at once on the `user` tier, after the judge hands it on with the `agent` policy, never when the judge decides), so the cone knows the scoop waits and can't approve it itself. A cone that asks gets none: it waits in its own command.
|
|
766
|
+
- **Run now** (a timed-out sudo, run later by the owner, [`src/approvals/run.ts`](src/approvals/run.ts)). A `sudo` item keeps `replay`, the facts the kernel's hook gave (`{ id, user, uid?, target?, argv, path?, cwd?, stdin?, rootOnly?, userWritable?, tag?, tags?, validate? }`, `userWritable` being `[{ path, sha256 }]`), which stays in the worker: the replicated `AgentTranscript.approvals` sends each item without `replay`, and a view seat's copy also leaves out the run's `stdout` and `stderr`. When nobody answered in time, an owner device may run it later with `AgentControl.approvalRun(id)`, and the item gets `run: { state, by, device?, at, pid?, pgid?, status?, signal?, endedAt?, error?, stdout?, stderr?, stopBy?, survivors?, capped?, removed? }`, `state` being `starting`, `running`, `done`, `failed` or `stopped`. The item itself stays `unanswered` with `timeout`, so the history stays true, and `prune()` never drops one whose run is `starting` or `running`, still has `survivors`, or still has its output files.
|
|
767
|
+
- **Who:** the same seats as `decide`, with `by` `owner` or `follower` and the link's `device`. A guest never gets it, and no tool or command reaches it, so an agent can't run its own request.
|
|
768
|
+
- **When:** `runnable(item, now, gates)` answers `true` or `{ reason }`, for the panel and the control method alike, and `AgentTranscript.approvalRunnable` replicates it per timed-out `sudo` item (`{ [id]: true | { reason } }`), refreshed when an item, the policy or the agents change and when one ages out. A request runs only when it timed out (`unanswered`, `timeout`) and never ran, came from a cone or a scoop with an `agentId` (anything else gets "Run it again in the terminal."), isn't `sudo -v`, had `stdin` `none` or `tty` ("Its input is gone, so it must be asked again."), has a `replay` with `rootOnly` (items from before this, or from a kernel that doesn't send `rootOnly`, get "This request is from before Run now, so it must be asked again."; the agent never fills in `{}`, which would empty the kernel's check), timed out at most `sudo.runLate.maxAgeMinutes` ago (see Approval policy), its cone isn't frozen ("Thaw <cone> first."), the agent that asked still exists (a deleted cone, or a scoop whose record or cone is gone, gets "The agent that asked is gone, so it must be asked again."), and the worker's kernel client has `sudoRun` and speaks protocol 1.16 or later ("Needs slicc-kernel protocol 1.16 or later.").
|
|
769
|
+
- **The claim:** one write checks `runnable`, sets `run = { state: 'starting', by, device, at }` and creates the run's durable task, so the first click wins and a second gets "This request is already running.".
|
|
770
|
+
- **The run** is a background durable task `slicc.sudo-run` on the root conversation (`sudo run now` in the monitor). It makes `~/.slicc/sudo-runs/` in the caller's home as the caller, subscribes to `trace('sudo-run:<id>')`, and calls the kernel's `sudoRun(replay, { stdout: ~/.slicc/sudo-runs/<id>.out, stderr: <id>.err, tag: 'sudo-run:<id>' })`, which checks everything again (policy, paths, the user-writable files' hashes) and runs it without a terminal or input. The agent never spawns it itself. A refusal ends the run `failed` with the kernel's sentence as it is (such as `sudo: <file> changed since it was requested`, `sudo: <cwd> changed since it was requested`, `sudo: <path> changed while it was opened` for an output file swapped for a symlink, or `sudo: that isn't a sudo request this kernel can run`) and no lick, since nothing ran; `ENOSYS` reads "Needs slicc-kernel protocol 1.16 or later.". Otherwise the run is `running` with its `pid`, and the task waits for its exit (the trace's `exit`, the call's `ended`, or the process gone from `ps`), then ends `done` with `status` and `signal`. Every process the run starts inherits the tag, so its tree is the set of live `ps` rows with `sudo-run:<id>`, a background job that job control (`set -m`) moved into a group of its own included. When the leader exits while others of its tree still run, the run is `done` with `survivors` (their pids), the end lick says "Still running: pid …", and the task keeps following `ps` until they are gone, then clears `survivors`. While it waits, a watchdog checks the size of both output files every 5 s; past 32 MiB together it stops the tree, and the run ends `stopped` with `capped` (the cap in bytes). The output files are removed as the requester 24 h after the run ended (on a timer, and again whenever the worker starts), and then the run drops `stdout` and `stderr` and gets `removed: true`. `AgentWorkerOptions.runTimes` (`{ pollMs?, killMs?, adoptMs?, outputCap?, keepMs? }`, the test page's `?run-times=<json>`) shortens these for tests; the test page's `?btime=<n>|none` stands in for the kernel's boot id.
|
|
771
|
+
- **At most once:** a task resumed after a worker restart while it was calling the kernel never calls again: it adopts the process from `ps` that carries the tag and runs as the target's uid, trying five times with backoff (250 ms doubling), and only then ends `failed` with "interrupted before it started". A resumed `running` one subscribes again and checks `ps`: gone without an exit is `done` with no status, and a kernel that booted since (`btime`, the page reloaded) is `failed` with "the page reloaded while it ran", unless a process with the tag is still alive, which it then keeps waiting for. A boot id that couldn't be read (`null`) is unknown, never a reload.
|
|
772
|
+
- **Stop:** `AgentControl.approvalRunStop(id)` sends `SIGTERM` to every live process with the run's tag, and `SIGKILL` 5 s later to those still there; a running run ends `stopped`. It also works on a `done` run that still has survivors. With no tagged process left it answers "Its processes are already gone." for a running run and "This request isn't running." otherwise, and without a process list "The kernel's process list isn't available, so it can't be stopped.". One stopped before the kernel was called never runs. The agent's own Stop (`Conversation.abort`) doesn't touch it, since it's the owner's run, not the agent's turn; aborting the task stops it.
|
|
773
|
+
- **Licks** go to `requester.agentId` (a scoop that's gone falls back to its cone, a frozen cone gets the frozen notice) on the channel `sudo-run`, from the item's id, never coalesced and once per `eventId` (`<id>:start`, `<id>:end`), with the taints of the request's tags, and both steer, so each wakes an idle agent. The start lick says the owner ran the timed-out request, when it asked and when it ran, the pid and the output path; the end lick has the exit status or signal, how long it took, any survivors and the full paths, never the output itself: the requester can write those files while the command runs, so the agent reads them with its own shell if it needs them, as normal tool output. It has `severity="warn"` unless it exited 0 with no survivors. When the requester is a scoop that has ended, both licks go to its cone and say so. Title, text and body go through the secrets redaction, then both go through `scrubbedLick`. The licks prompt section says a sudo-run lick reports a command the owner ran late, not a new request.
|
|
774
|
+
- **In spectrum,** the adapter's `history()` lists every item, newest first, as an `ApprovalRecord` `{ approval, state, reason?, decidedBy?, device?, decidedAt?, answer?, run?, runnable? }` (`run` without `pgid` and `stopBy`, with `survivors` when there are some, `runnable` from `approvalRunnable`), with a `history` event when it changes; `run(id)` and `stopRun(id)` reject with the agent's sentence. Every owner device's adapter has all three, a guest connection's has none. With `approvals: biosPort`, the adapter merges bios's `history()` in and sends `run` and `stopRun` to whichever side listed the id. A `sudo-run` lick card carries `approval`, the item's id.
|
|
764
775
|
- **Media capture:** `AgentOwner.approveCapture(request, { signal, where? })` takes a `/dev/embedder` request as bios's hook receives it, `{ kind, options, stamp }`, and resolves `once`, `always`, `deny` or `{ answer: 'deny', message }`. It rejects with `code: 'EAGAIN'` when the agent can't answer (released, restarting, or a worker without it) and when `stamp.users` is neither `report` nor `enforce`, since the agent can't tell who started the program then, so bios falls back to its own prompt.
|
|
765
776
|
- **Who started it** comes only from the kernel's stamp: its `tags`, plus the taints the agent has seen alive for that process (`stamp.pid`) since it first saw it, the `recent` set the `agent` CLI uses ([`src/kernel/lineage.ts`](src/kernel/lineage.ts)). So a clean process that a guest's process sets off counts as the guest's while that cover holds: while a tagged process of the guest, or a `crontab` line it installed, lives, and for about 2 s after it ends (the agent's `ps` reads). Something the guest planted that runs later, such as a sprinkle CGI, a `~/.bashrc` line or a git hook, is attributed to whoever starts it then. As for the `agent` CLI, this is conservative: while a guest's leftover job or `crontab` line lives, everyone's captures are reviewed too. When the agent has no lineage provider or can't read the process's lineage, it denies.
|
|
766
777
|
- **Shell clients:** `stamp.pid` is the process that wrote the header line, so that process must stay until the reply is read. A header written by a short-lived child (`cat req >&3`) has no lineage by then and is denied; write it from the shell itself (`read -r line < req; printf '%s\n' "$line" >&3`).
|
|
@@ -807,6 +818,7 @@ All the limits on approvals and guests live in one owner-changeable policy, the
|
|
|
807
818
|
- `guests.maxSeatDays: 30` (1 to 365).
|
|
808
819
|
- `guests.always: { messages: false, tools: false }`.
|
|
809
820
|
- `sudo.approver: 'user'` (`'agent'` lets the judge decide sudo).
|
|
821
|
+
- `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 } } })`.
|
|
810
822
|
- **Reading it:** `AgentTranscript.approvalPolicy` replicates it to every owner device.
|
|
811
823
|
- **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.
|
|
812
824
|
- **Where it applies:** gates and expiry are checked when a seat opens, so a seat keeps its gates when the policy changes later.
|
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 { sudoRuns } from "./approvals/run.js";
|
|
9
10
|
import { guestToolGate } from "./guests/guard.js";
|
|
10
11
|
import { guestReviews } from "./guests/review.js";
|
|
11
12
|
import { scoopReviews } from "./guests/scoop.js";
|
|
@@ -42,6 +43,8 @@ async function openAgent(options) {
|
|
|
42
43
|
registry.install(reviews.extension);
|
|
43
44
|
const scooped = scoopReviews();
|
|
44
45
|
registry.install(scooped.extension);
|
|
46
|
+
const runs = sudoRuns();
|
|
47
|
+
registry.install(runs.extension);
|
|
45
48
|
const reports = createReports();
|
|
46
49
|
const timings = createTimings({
|
|
47
50
|
onError: (error) => reports.record({ kind: "listener_error", error })
|
|
@@ -74,6 +77,7 @@ async function openAgent(options) {
|
|
|
74
77
|
reviews,
|
|
75
78
|
gate,
|
|
76
79
|
scoopReviews: scooped,
|
|
80
|
+
sudoRuns: runs,
|
|
77
81
|
reports,
|
|
78
82
|
timings,
|
|
79
83
|
cone: () => agents.cone(),
|
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 { 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 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 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 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;AAGxC,SAA6B,qBAAqB;AAClD,SAA4B,oBAAoB;AAChD,SAA4B,oBAAoB;AAChD,SAAS,qBAAmC;AAC5C,SAAS,qBAAmC;
|
|
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;AAC7C,QAAM,EAAE,QAAQ,OAAO,IAAI;AAC3B,MAAI,WAAW,OAAW,OAAM,IAAI,MAAM,eAAe,MAAM,EAA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C9C,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;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/approvals/policy.js
CHANGED
|
@@ -10,8 +10,9 @@ import {
|
|
|
10
10
|
} from "../guests/policy.js";
|
|
11
11
|
const DEFAULT_APPROVAL_POLICY = {
|
|
12
12
|
guests: DEFAULT_GUEST_POLICY,
|
|
13
|
-
sudo: { approver: "user" }
|
|
13
|
+
sudo: { approver: "user", runLate: { maxAgeMinutes: 1440 } }
|
|
14
14
|
};
|
|
15
|
+
const MAX_RUN_LATE_MINUTES = 10080;
|
|
15
16
|
const ApprovalPolicyDoc = defineDoc({
|
|
16
17
|
kind: "slicc.approval-policy",
|
|
17
18
|
checkpointWhen: boundedDeltas,
|
|
@@ -20,10 +21,25 @@ const ApprovalPolicyDoc = defineDoc({
|
|
|
20
21
|
initial: () => ({ overrides: {} })
|
|
21
22
|
});
|
|
22
23
|
const copy = (value) => JSON.parse(JSON.stringify(value));
|
|
24
|
+
const isObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
25
|
+
function changedRunLate(next, change) {
|
|
26
|
+
if (!isObject(change)) return "sudo.runLate is an object of policy entries.";
|
|
27
|
+
for (const [name, value] of Object.entries(change)) {
|
|
28
|
+
if (name !== "maxAgeMinutes") return `There is no sudo.runLate policy entry ${name}.`;
|
|
29
|
+
if (!Number.isInteger(value) || value < 0 || value > MAX_RUN_LATE_MINUTES)
|
|
30
|
+
return `sudo.runLate.maxAgeMinutes is a whole number of minutes from 0 to ${MAX_RUN_LATE_MINUTES}.`;
|
|
31
|
+
next.sudo.runLate.maxAgeMinutes = value;
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
23
35
|
function changedSudo(next, change) {
|
|
24
|
-
if (!change
|
|
25
|
-
return "The sudo policy is an object of policy entries.";
|
|
36
|
+
if (!isObject(change)) return "The sudo policy is an object of policy entries.";
|
|
26
37
|
for (const [name, value] of Object.entries(change)) {
|
|
38
|
+
if (name === "runLate") {
|
|
39
|
+
const error = changedRunLate(next, value);
|
|
40
|
+
if (error) return error;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
27
43
|
if (name !== "approver") return `There is no sudo policy entry ${name}.`;
|
|
28
44
|
if (value !== "user" && value !== "agent")
|
|
29
45
|
return "A sudo request is approved by user or agent.";
|
|
@@ -43,13 +59,18 @@ function changedPolicy(base, change) {
|
|
|
43
59
|
}
|
|
44
60
|
function resolvedPolicy(overrides) {
|
|
45
61
|
const guests = overrides.guests ?? {};
|
|
62
|
+
const sudo = overrides.sudo ?? {};
|
|
46
63
|
return copy({
|
|
47
64
|
guests: {
|
|
48
65
|
...DEFAULT_GUEST_POLICY,
|
|
49
66
|
...guests,
|
|
50
67
|
always: { ...DEFAULT_GUEST_POLICY.always, ...guests.always }
|
|
51
68
|
},
|
|
52
|
-
sudo: {
|
|
69
|
+
sudo: {
|
|
70
|
+
...DEFAULT_APPROVAL_POLICY.sudo,
|
|
71
|
+
...sudo,
|
|
72
|
+
runLate: { ...DEFAULT_APPROVAL_POLICY.sudo.runLate, ...sudo.runLate }
|
|
73
|
+
}
|
|
53
74
|
});
|
|
54
75
|
}
|
|
55
76
|
function overridden(overrides, change, policy) {
|
|
@@ -59,7 +80,7 @@ function overridden(overrides, change, policy) {
|
|
|
59
80
|
const into = next[key] ?? {};
|
|
60
81
|
const resolved = policy[key];
|
|
61
82
|
for (const name of Object.keys(entries))
|
|
62
|
-
into[name] = name === "always" ? { ...into
|
|
83
|
+
into[name] = name === "always" || name === "runLate" ? { ...into[name], ...entries[name] } : resolved[name];
|
|
63
84
|
next[key] = into;
|
|
64
85
|
}
|
|
65
86
|
return next;
|
|
@@ -103,6 +124,7 @@ async function attachApprovalPolicy(harness, context = BACKGROUND_CONTEXT) {
|
|
|
103
124
|
export {
|
|
104
125
|
ApprovalPolicyDoc,
|
|
105
126
|
DEFAULT_APPROVAL_POLICY,
|
|
127
|
+
MAX_RUN_LATE_MINUTES,
|
|
106
128
|
alwaysFor,
|
|
107
129
|
attachApprovalPolicy,
|
|
108
130
|
changedPolicy,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/approvals/policy.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type Context,\n type JsonValue,\n type ReplicatedState,\n replicatedState,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport { defineDoc, type Harness, type JsonObject } from '@earendil-works/pi-durable';\nimport { boundedDeltas } from '../checkpoints.ts';\nimport {\n changedGuests,\n DEFAULT_GUEST_POLICY,\n type GuestPolicy,\n type GuestPolicyChange,\n} from '../guests/policy.ts';\nimport type { ApprovalKind } from './record.ts';\n\nexport type SudoPolicy = { approver: 'user' | 'agent' };\n\nexport type ApprovalPolicy = { guests: GuestPolicy; sudo: SudoPolicy };\n\nexport type ApprovalPolicyChange = { guests?: GuestPolicyChange; sudo?:
|
|
5
|
-
"mappings": "AAAA;AAAA,EAIE;AAAA,OACK;AACP,SAAS,0BAA0B;AACnC,SAAS,iBAAgD;AACzD,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OAGK;
|
|
4
|
+
"sourcesContent": ["import {\n type Context,\n type JsonValue,\n type ReplicatedState,\n replicatedState,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport { defineDoc, type Harness, type JsonObject } from '@earendil-works/pi-durable';\nimport { boundedDeltas } from '../checkpoints.ts';\nimport {\n changedGuests,\n DEFAULT_GUEST_POLICY,\n type GuestPolicy,\n type GuestPolicyChange,\n} from '../guests/policy.ts';\nimport type { ApprovalKind } from './record.ts';\n\nexport type RunLatePolicy = { maxAgeMinutes: number };\n\nexport type SudoPolicy = { approver: 'user' | 'agent'; runLate: RunLatePolicy };\n\nexport type ApprovalPolicy = { guests: GuestPolicy; sudo: SudoPolicy };\n\nexport type SudoPolicyChange = {\n approver?: SudoPolicy['approver'];\n runLate?: Partial<RunLatePolicy>;\n};\n\nexport type ApprovalPolicyChange = { guests?: GuestPolicyChange; sudo?: SudoPolicyChange };\n\nexport type ApprovalPolicySet =\n | { policy: ApprovalPolicy; error: null }\n | { policy: null; error: string };\n\nexport const DEFAULT_APPROVAL_POLICY: ApprovalPolicy = {\n guests: DEFAULT_GUEST_POLICY,\n sudo: { approver: 'user', runLate: { maxAgeMinutes: 1440 } },\n};\n\nexport const MAX_RUN_LATE_MINUTES = 10_080;\n\ntype Overrides = Partial<Record<keyof ApprovalPolicy, JsonObject>>;\n\nexport const ApprovalPolicyDoc = defineDoc<{ overrides: Overrides }>({\n kind: 'slicc.approval-policy',\n checkpointWhen: boundedDeltas,\n version: 1,\n scope: 'session',\n initial: () => ({ overrides: {} }),\n});\n\nconst copy = <T>(value: T): T => JSON.parse(JSON.stringify(value));\n\nconst isObject = (value: unknown): value is Record<string, unknown> =>\n Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n\nfunction changedRunLate(next: ApprovalPolicy, change: unknown): string | null {\n if (!isObject(change)) return 'sudo.runLate is an object of policy entries.';\n for (const [name, value] of Object.entries(change)) {\n if (name !== 'maxAgeMinutes') return `There is no sudo.runLate policy entry ${name}.`;\n if (\n !Number.isInteger(value) ||\n (value as number) < 0 ||\n (value as number) > MAX_RUN_LATE_MINUTES\n )\n return `sudo.runLate.maxAgeMinutes is a whole number of minutes from 0 to ${MAX_RUN_LATE_MINUTES}.`;\n next.sudo.runLate.maxAgeMinutes = value as number;\n }\n return null;\n}\n\nfunction changedSudo(next: ApprovalPolicy, change: unknown): string | null {\n if (!isObject(change)) return 'The sudo policy is an object of policy entries.';\n for (const [name, value] of Object.entries(change)) {\n if (name === 'runLate') {\n const error = changedRunLate(next, value);\n if (error) return error;\n continue;\n }\n if (name !== 'approver') return `There is no sudo policy entry ${name}.`;\n if (value !== 'user' && value !== 'agent')\n return 'A sudo request is approved by user or agent.';\n next.sudo.approver = value;\n }\n return null;\n}\n\nexport function changedPolicy(base: ApprovalPolicy, change: unknown): ApprovalPolicySet {\n if (!change || typeof change !== 'object' || Array.isArray(change))\n return { policy: null, error: 'An approval policy change is an object of sections.' };\n const next = copy(base);\n for (const [name, value] of Object.entries(change)) {\n const error =\n name === 'guests'\n ? changedGuests(next.guests, value)\n : name === 'sudo'\n ? changedSudo(next, value)\n : `There is no approval policy section ${name}.`;\n if (error) return { policy: null, error };\n }\n return { policy: next, error: null };\n}\n\nexport function resolvedPolicy(overrides: Overrides): ApprovalPolicy {\n const guests = (overrides.guests ?? {}) as Partial<GuestPolicy>;\n const sudo = (overrides.sudo ?? {}) as Partial<SudoPolicy>;\n return copy({\n guests: {\n ...DEFAULT_GUEST_POLICY,\n ...guests,\n always: { ...DEFAULT_GUEST_POLICY.always, ...guests.always },\n },\n sudo: {\n ...DEFAULT_APPROVAL_POLICY.sudo,\n ...sudo,\n runLate: { ...DEFAULT_APPROVAL_POLICY.sudo.runLate, ...sudo.runLate },\n },\n });\n}\n\nexport function overridden(\n overrides: Overrides,\n change: Record<string, Record<string, unknown>>,\n policy: ApprovalPolicy\n): Overrides {\n const next = copy(overrides);\n for (const [section, entries] of Object.entries(change)) {\n const key = section as keyof ApprovalPolicy;\n const into = next[key] ?? {};\n const resolved = policy[key] as unknown as JsonObject;\n for (const name of Object.keys(entries))\n into[name] = (\n name === 'always' || name === 'runLate'\n ? { ...(into[name] as object), ...(entries[name] as object) }\n : resolved[name]\n ) as JsonValue;\n next[key] = into;\n }\n return next;\n}\n\nexport interface ApprovalPolicies {\n readonly state: ReplicatedState<ApprovalPolicy>;\n current(): ApprovalPolicy;\n set(change: unknown, context: Context): Promise<ApprovalPolicySet>;\n}\n\nexport const alwaysFor =\n (policy: Pick<ApprovalPolicies, 'current'>) =>\n (kind: ApprovalKind): boolean => {\n const { always } = policy.current().guests;\n return kind === 'guest-message' ? always.messages : always.tools;\n };\n\nexport async function attachApprovalPolicy(\n harness: Pick<Harness, 'commit'>,\n context: Context = BACKGROUND_CONTEXT\n): Promise<ApprovalPolicies> {\n let overrides = await harness.commit(\n async (tx) => copy((await tx.doc(ApprovalPolicyDoc)).overrides ?? {}),\n context\n );\n const state = replicatedState<ApprovalPolicy>(resolvedPolicy(overrides));\n let line: Promise<unknown> = Promise.resolve();\n return {\n state,\n current: () => copy(state.value as ApprovalPolicy),\n set(change, using) {\n const run = line.then(async () => {\n const made = changedPolicy(state.value as ApprovalPolicy, change);\n if (!made.policy) return made;\n const next = overridden(\n overrides,\n change as Record<string, Record<string, unknown>>,\n made.policy\n );\n await harness.commit(async (tx) => {\n (await tx.doc(ApprovalPolicyDoc)).overrides = copy(next);\n }, using);\n overrides = next;\n const policy = resolvedPolicy(next);\n state.replace(using, copy(policy));\n return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ACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { replicatedState } from "@earendil-works/chord";
|
|
2
|
+
function stripped(item, view) {
|
|
3
|
+
if (item.kind !== "sudo") return item;
|
|
4
|
+
const { replay: _replay, ...rest } = item;
|
|
5
|
+
if (!view || !rest.run) return rest;
|
|
6
|
+
const { stdout: _stdout, stderr: _stderr, ...run } = rest.run;
|
|
7
|
+
return { ...rest, run };
|
|
8
|
+
}
|
|
9
|
+
function publishedApprovals(state, view) {
|
|
10
|
+
const shown = (items) => (items ?? []).map((item) => stripped(item, view));
|
|
11
|
+
const out = replicatedState(shown(state.value));
|
|
12
|
+
state.subscribe((items, context) => out.replace(context, shown(items)));
|
|
13
|
+
return out;
|
|
14
|
+
}
|
|
15
|
+
export {
|
|
16
|
+
publishedApprovals
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=published.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/approvals/published.ts"],
|
|
4
|
+
"sourcesContent": ["import { type ReplicatedState, replicatedState } from '@earendil-works/chord';\nimport type { Approval } from './record.ts';\n\nfunction stripped(item: Approval, view: boolean): Approval {\n if (item.kind !== 'sudo') return item;\n const { replay: _replay, ...rest } = item;\n if (!view || !rest.run) return rest;\n const { stdout: _stdout, stderr: _stderr, ...run } = rest.run;\n return { ...rest, run };\n}\n\nexport function publishedApprovals(\n state: ReplicatedState<Approval[]>,\n view: boolean\n): ReplicatedState<Approval[]> {\n const shown = (items: readonly Approval[] | undefined) =>\n (items ?? []).map((item) => stripped(item, view));\n const out = replicatedState<Approval[]>(shown(state.value));\n state.subscribe((items, context) => out.replace(context, shown(items)));\n return out;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAA+B,uBAAuB;AAGtD,SAAS,SAAS,MAAgB,MAAyB;AACzD,MAAI,KAAK,SAAS,OAAQ,QAAO;AACjC,QAAM,EAAE,QAAQ,SAAS,GAAG,KAAK,IAAI;AACrC,MAAI,CAAC,QAAQ,CAAC,KAAK,IAAK,QAAO;AAC/B,QAAM,EAAE,QAAQ,SAAS,QAAQ,SAAS,GAAG,IAAI,IAAI,KAAK;AAC1D,SAAO,EAAE,GAAG,MAAM,IAAI;AACxB;AAEO,SAAS,mBACd,OACA,MAC6B;AAC7B,QAAM,QAAQ,CAAC,WACZ,SAAS,CAAC,GAAG,IAAI,CAAC,SAAS,SAAS,MAAM,IAAI,CAAC;AAClD,QAAM,MAAM,gBAA4B,MAAM,MAAM,KAAK,CAAC;AAC1D,QAAM,UAAU,CAAC,OAAO,YAAY,IAAI,QAAQ,SAAS,MAAM,KAAK,CAAC,CAAC;AACtE,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/approvals/record.js
CHANGED
|
@@ -67,8 +67,10 @@ function cleanReason(reason) {
|
|
|
67
67
|
return text || void 0;
|
|
68
68
|
}
|
|
69
69
|
const decided = (item) => item.decidedAt ?? item.createdAt;
|
|
70
|
+
const runLive = (item) => item.kind === "sudo" && (item.run?.state === "starting" || item.run?.state === "running");
|
|
71
|
+
const runHeld = (item) => item.kind === "sudo" && !!item.run && (runLive(item) || !!item.run.survivors?.length || !!item.run.stdout && !item.run.removed);
|
|
70
72
|
function prune(items, kept = APPROVALS_KEPT) {
|
|
71
|
-
const settled = items.filter((item) => item.state !== "pending");
|
|
73
|
+
const settled = items.filter((item) => item.state !== "pending" && !runHeld(item));
|
|
72
74
|
settled.sort((a, b) => decided(a) - decided(b));
|
|
73
75
|
const drop = new Set(settled.slice(0, Math.max(0, settled.length - kept)));
|
|
74
76
|
return items.filter((item) => !drop.has(item));
|
|
@@ -127,6 +129,7 @@ export {
|
|
|
127
129
|
routable,
|
|
128
130
|
route,
|
|
129
131
|
ruled,
|
|
132
|
+
runLive,
|
|
130
133
|
scoopTier,
|
|
131
134
|
stoppable,
|
|
132
135
|
sudoApprover,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/approvals/record.ts"],
|
|
4
|
-
"sourcesContent": ["import { defineDoc } from '@earendil-works/pi-durable';\nimport { boundedDeltas } from '../checkpoints.ts';\nimport { clears, fits, JUDGE_ALLOW, JUDGE_LOW, reaches } from './aligned.ts';\nimport { personal } from './people.ts';\nimport { REASONS } from './reasons.ts';\nimport { stoppable } from './stoppable.ts';\n\nexport { fits, JUDGE_ALLOW, personal, REASONS, stoppable };\n\nexport type ApprovalKind = 'guest-message' | 'guest-tool' | 'sudo' | 'capture';\n\nexport type ApprovalState = 'pending' | 'approved' | 'rejected' | 'unanswered' | 'withdrawn';\n\nexport type ApprovalTier = 'user' | 'agent' | 'cone' | `scoop:${string}`;\n\nexport type ApprovalAnswer = 'once' | 'always' | 'deny';\n\nexport type ApprovalDecision = ApprovalAnswer | 'stop';\n\nexport type DecidedBy = 'owner' | 'follower' | 'judge' | 'host' | `scoop:${string}`;\n\nexport type ApprovalRequester = {\n kind: 'guest' | 'agent' | 'user';\n name: string;\n seat?: string;\n agentId?: string;\n where?: string;\n device?: string;\n};\n\nexport type ApprovalLevel = 1 | 2 | 3;\n\nexport type ApprovalVerdict = {\n level?: ApprovalLevel;\n routine?: number;\n aligned?: number | boolean;\n always?: boolean;\n reason: string;\n via?: 'classifier' | 'chat';\n risk?: number;\n model?: string;\n actions?: Record<string, number>;\n intent?: Record<string, number>;\n forbidden?: number | boolean;\n};\n\nexport type ApprovalAttachment = { name: string; mimeType: string; size: number };\n\nexport type GuestMessageDetail = { text: string; attachments: ApprovalAttachment[] };\n\nexport type GuestToolDetail = { tool: string; summary: string; arguments?: string; task?: number };\n\nexport type SudoStdin = 'tty' | 'none' | 'pipe' | 'file';\n\nexport type SudoDetail = {\n command: string;\n target?: string;\n cwd?: string;\n alwaysScope?: 'cwd';\n stdin?: SudoStdin;\n rootOnly?: Record<string, boolean>;\n writable?: boolean;\n validate?: true;\n};\n\nexport type CaptureWhat = 'screen' | 'camera' | 'microphone';\n\nexport type CaptureMode = 'still' | 'video' | 'audio';\n\nexport type CaptureDetail = {\n what: CaptureWhat;\n mode: CaptureMode;\n seconds?: number;\n system?: boolean;\n microphone?: boolean;\n device?: string;\n program: string;\n};\n\ntype Base = {\n id: string;\n seat?: string;\n agentId: string;\n requester: ApprovalRequester;\n tier: string;\n state: ApprovalState;\n decidedBy: DecidedBy | null;\n device?: string;\n answer?: 'once' | 'always';\n reviewer?: string;\n reason?: string;\n verdict?: ApprovalVerdict;\n judging?: boolean;\n verdictError?: string;\n always: boolean;\n createdAt: number;\n expiresAt: number;\n decidedAt?: number;\n};\n\nexport type GuestMessageApproval = Base & { kind: 'guest-message'; detail: GuestMessageDetail };\nexport type GuestToolApproval = Base & { kind: 'guest-tool'; detail: GuestToolDetail };\nexport type SudoApproval = Base & { kind: 'sudo'; detail: SudoDetail };\nexport type CaptureApproval = Base & { kind: 'capture'; detail: CaptureDetail };\n\nexport type Approval = GuestMessageApproval | GuestToolApproval | SudoApproval | CaptureApproval;\n\ntype DraftOf<T extends Approval> = Pick<T, 'kind' | 'detail' | 'agentId' | 'requester'> & {\n seat?: string;\n tier: string;\n always?: boolean;\n expiresAt?: number;\n};\n\nexport type ApprovalDraft =\n | DraftOf<GuestMessageApproval>\n | DraftOf<GuestToolApproval>\n | DraftOf<SudoApproval>\n | DraftOf<CaptureApproval>;\n\nexport type ApprovalsState = { items: Approval[] };\n\nexport const ApprovalsDoc = defineDoc<ApprovalsState>({\n kind: 'slicc.approvals',\n checkpointWhen: boundedDeltas,\n version: 1,\n scope: 'session',\n initial: () => ({ items: [] }),\n});\n\nexport const APPROVAL_MS = 300_000;\nexport const APPROVALS_KEPT = 100;\nexport const MAX_DELAY = 2_147_483_647;\nexport const REASON_LENGTH = 500;\n\nexport const guestKind = (kind: ApprovalKind): boolean => kind !== 'sudo';\n\nexport const scoopTier = (tier: unknown): tier is `scoop:${string}` =>\n typeof tier === 'string' && /^scoop:\\S+$/.test(tier);\n\nexport function knownTier(tier: unknown): tier is ApprovalTier {\n if (tier === 'user' || tier === 'agent' || tier === 'cone') return true;\n return scoopTier(tier);\n}\n\nexport const heldKind = (kind: ApprovalKind): boolean => kind === 'sudo' || kind === 'capture';\n\nexport function routable(kind: ApprovalKind, tier: ApprovalTier): boolean {\n return !((kind === 'guest-tool' || kind === 'capture') && tier === 'cone');\n}\n\nexport function answerOf(value: unknown): ApprovalDecision | null {\n return value === 'once' || value === 'always' || value === 'deny' || value === 'stop'\n ? value\n : null;\n}\n\nexport function answerer(by: DecidedBy, item: Pick<Approval, 'tier' | 'reviewer'>): boolean {\n if (personal(by)) return item.tier === 'user';\n if (by === 'judge') return item.tier === 'agent';\n if (scoopTier(by)) return scoopTier(item.tier) && item.reviewer === by;\n return true;\n}\n\nexport type SudoApprover = 'user' | 'agent';\n\nexport const sudoApprover = (value: unknown): SudoApprover =>\n value === 'agent' ? 'agent' : 'user';\n\nexport const personOnly = (item: Pick<ApprovalDraft, 'kind' | 'detail'>): boolean =>\n item.kind === 'sudo' && (item.detail as SudoDetail).validate === true;\n\nexport const tierOf = (\n draft: Pick<ApprovalDraft, 'kind' | 'detail' | 'tier'>,\n sudo: SudoApprover\n) => (draft.kind !== 'sudo' ? draft.tier : personOnly(draft) ? 'user' : sudo);\n\nexport type Gate = 'person' | 'judge';\n\nexport type Routed = 'approve' | 'deny' | 'ask';\n\nexport const gateOf = (tier: string): Gate => (tier === 'agent' ? 'judge' : 'person');\n\nexport const vetoed = ({ forbidden }: ApprovalVerdict): boolean =>\n forbidden === true || (typeof forbidden === 'number' && reaches(forbidden, JUDGE_LOW));\n\nexport function approvable(verdict: ApprovalVerdict): boolean {\n const sure =\n verdict.routine === undefined ? verdict.via === 'chat' : clears(verdict.routine, JUDGE_ALLOW);\n return verdict.level === 1 && sure && fits(verdict.aligned);\n}\n\nexport function route(\n verdict: ApprovalVerdict | undefined,\n requester: Pick<ApprovalRequester, 'kind'>,\n gate: Gate,\n present: boolean\n): Routed {\n if (gate !== 'judge' || !verdict?.level) return 'ask';\n if (approvable(verdict) && !vetoed(verdict)) return 'approve';\n if (verdict.level === 3 && requester.kind !== 'user' && !present) return 'deny';\n return 'ask';\n}\n\nexport function alwaysOffered(item: Approval): boolean {\n if ((item.kind !== 'sudo' && item.kind !== 'capture') || item.tier !== 'user') return false;\n if (personOnly(item)) return false;\n const { verdict } = item;\n const writable = item.kind !== 'sudo' || item.detail.writable !== false;\n return verdict?.level === 1 && verdict.always === true && writable;\n}\n\nexport function gone(state: ApprovalState): string {\n if (state === 'unanswered') return 'This request timed out.';\n if (state === 'withdrawn') return 'This request was withdrawn.';\n return 'Someone else already answered this.';\n}\n\nexport function cleanReason(reason: unknown): string | undefined {\n if (typeof reason !== 'string') return undefined;\n const text = reason.trim().slice(0, REASON_LENGTH);\n return text || undefined;\n}\n\nconst decided = (item: Approval) => item.decidedAt ?? item.createdAt;\n\nexport function prune(items: Approval[], kept = APPROVALS_KEPT): Approval[] {\n const settled = items.filter((item) => item.state !== 'pending');\n settled.sort((a, b) => decided(a) - decided(b));\n const drop = new Set(settled.slice(0, Math.max(0, settled.length - kept)));\n return items.filter((item) => !drop.has(item));\n}\n\nexport type Settle = { state: Exclude<ApprovalState, 'pending'>; by: DecidedBy; reason?: string };\n\nexport type Ruling = {\n error?: string;\n settle?: Settle;\n answer?: 'once' | 'always';\n stop?: string;\n};\n\nfunction stopped(item: Approval, by: DecidedBy): Ruling {\n if (!personal(by)) return { error: 'Only a person can stop a turn.' };\n if (!stoppable(item)) return { error: 'This request has no turn to stop.' };\n return {\n settle: { state: 'rejected', by, reason: REASONS.stopped },\n stop: item.requester.agentId as string,\n };\n}\n\nconst why = (reason: string | undefined) =>\n reason && reason !== REASONS.stopped ? { reason } : {};\n\nexport function ruled(\n item: Approval,\n answer: unknown,\n reason: unknown,\n by: DecidedBy,\n at: number\n): Ruling {\n if (item.state !== 'pending') return { error: gone(item.state) };\n if (item.expiresAt <= at)\n return {\n error: gone('unanswered'),\n settle: { state: 'unanswered', by: 'host', reason: REASONS.timeout },\n };\n if (!answerer(by, item)) return { error: \"This request isn't yours to answer.\" };\n const known = answerOf(answer);\n if (known === 'always' && scoopTier(by)) return { error: 'A scoop answers once or deny.' };\n if (known === 'always' && !personal(by))\n return { error: 'Always can only be answered by a person.' };\n if (known === 'always' && !item.always)\n return { error: \"Always isn't offered for this request.\" };\n if (!known) return { settle: { state: 'rejected', by, reason: REASONS.unknownAnswer } };\n if (known === 'stop') return stopped(item, by);\n const given = why(cleanReason(reason));\n if (known === 'deny') return { settle: { state: 'rejected', by, ...given } };\n return { settle: { state: 'approved', by, ...given }, answer: known };\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B,SAAS,QAAQ,MAAM,aAAa,WAAW,eAAe;AAC9D,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,iBAAiB;
|
|
4
|
+
"sourcesContent": ["import { defineDoc } from '@earendil-works/pi-durable';\nimport { boundedDeltas } from '../checkpoints.ts';\nimport { clears, fits, JUDGE_ALLOW, JUDGE_LOW, reaches } from './aligned.ts';\nimport { personal } from './people.ts';\nimport { REASONS } from './reasons.ts';\nimport { stoppable } from './stoppable.ts';\n\nexport { fits, JUDGE_ALLOW, personal, REASONS, stoppable };\n\nexport type ApprovalKind = 'guest-message' | 'guest-tool' | 'sudo' | 'capture';\n\nexport type ApprovalState = 'pending' | 'approved' | 'rejected' | 'unanswered' | 'withdrawn';\n\nexport type ApprovalTier = 'user' | 'agent' | 'cone' | `scoop:${string}`;\n\nexport type ApprovalAnswer = 'once' | 'always' | 'deny';\n\nexport type ApprovalDecision = ApprovalAnswer | 'stop';\n\nexport type DecidedBy = 'owner' | 'follower' | 'judge' | 'host' | `scoop:${string}`;\n\nexport type ApprovalRequester = {\n kind: 'guest' | 'agent' | 'user';\n name: string;\n seat?: string;\n agentId?: string;\n where?: string;\n device?: string;\n};\n\nexport type ApprovalLevel = 1 | 2 | 3;\n\nexport type ApprovalVerdict = {\n level?: ApprovalLevel;\n routine?: number;\n aligned?: number | boolean;\n always?: boolean;\n reason: string;\n via?: 'classifier' | 'chat';\n risk?: number;\n model?: string;\n actions?: Record<string, number>;\n intent?: Record<string, number>;\n forbidden?: number | boolean;\n};\n\nexport type ApprovalAttachment = { name: string; mimeType: string; size: number };\n\nexport type GuestMessageDetail = { text: string; attachments: ApprovalAttachment[] };\n\nexport type GuestToolDetail = { tool: string; summary: string; arguments?: string; task?: number };\n\nexport type SudoStdin = 'tty' | 'none' | 'pipe' | 'file';\n\nexport type SudoDetail = {\n command: string;\n target?: string;\n cwd?: string;\n alwaysScope?: 'cwd';\n stdin?: SudoStdin;\n rootOnly?: Record<string, boolean>;\n writable?: boolean;\n validate?: true;\n};\n\nexport type SudoFile = { path: string; sha256: string };\n\nexport type SudoReplay = {\n id: string;\n user: string;\n uid?: number;\n target?: string;\n argv: string[];\n path?: string;\n cwd?: string;\n stdin?: SudoStdin;\n rootOnly?: Record<string, boolean>;\n userWritable?: SudoFile[];\n tag?: string;\n tags?: string[];\n validate?: boolean;\n};\n\nexport type SudoRunState = 'starting' | 'running' | 'done' | 'failed' | 'stopped';\n\nexport type SudoRun = {\n state: SudoRunState;\n by: DecidedBy;\n device?: string;\n at: number;\n pid?: number;\n pgid?: number;\n status?: number;\n signal?: string;\n endedAt?: number;\n error?: string;\n stdout?: string;\n stderr?: string;\n stopBy?: DecidedBy;\n survivors?: number[];\n capped?: number;\n removed?: true;\n};\n\nexport type CaptureWhat = 'screen' | 'camera' | 'microphone';\n\nexport type CaptureMode = 'still' | 'video' | 'audio';\n\nexport type CaptureDetail = {\n what: CaptureWhat;\n mode: CaptureMode;\n seconds?: number;\n system?: boolean;\n microphone?: boolean;\n device?: string;\n program: string;\n};\n\ntype Base = {\n id: string;\n seat?: string;\n agentId: string;\n requester: ApprovalRequester;\n tier: string;\n state: ApprovalState;\n decidedBy: DecidedBy | null;\n device?: string;\n answer?: 'once' | 'always';\n reviewer?: string;\n reason?: string;\n verdict?: ApprovalVerdict;\n judging?: boolean;\n verdictError?: string;\n always: boolean;\n createdAt: number;\n expiresAt: number;\n decidedAt?: number;\n};\n\nexport type GuestMessageApproval = Base & { kind: 'guest-message'; detail: GuestMessageDetail };\nexport type GuestToolApproval = Base & { kind: 'guest-tool'; detail: GuestToolDetail };\nexport type SudoApproval = Base & {\n kind: 'sudo';\n detail: SudoDetail;\n replay?: SudoReplay;\n run?: SudoRun;\n};\nexport type CaptureApproval = Base & { kind: 'capture'; detail: CaptureDetail };\n\nexport type Approval = GuestMessageApproval | GuestToolApproval | SudoApproval | CaptureApproval;\n\ntype DraftOf<T extends Approval> = Pick<T, 'kind' | 'detail' | 'agentId' | 'requester'> & {\n seat?: string;\n tier: string;\n always?: boolean;\n expiresAt?: number;\n};\n\nexport type ApprovalDraft =\n | DraftOf<GuestMessageApproval>\n | DraftOf<GuestToolApproval>\n | (DraftOf<SudoApproval> & { replay?: SudoReplay })\n | DraftOf<CaptureApproval>;\n\nexport type ApprovalsState = { items: Approval[] };\n\nexport const ApprovalsDoc = defineDoc<ApprovalsState>({\n kind: 'slicc.approvals',\n checkpointWhen: boundedDeltas,\n version: 1,\n scope: 'session',\n initial: () => ({ items: [] }),\n});\n\nexport const APPROVAL_MS = 300_000;\nexport const APPROVALS_KEPT = 100;\nexport const MAX_DELAY = 2_147_483_647;\nexport const REASON_LENGTH = 500;\n\nexport const guestKind = (kind: ApprovalKind): boolean => kind !== 'sudo';\n\nexport const scoopTier = (tier: unknown): tier is `scoop:${string}` =>\n typeof tier === 'string' && /^scoop:\\S+$/.test(tier);\n\nexport function knownTier(tier: unknown): tier is ApprovalTier {\n if (tier === 'user' || tier === 'agent' || tier === 'cone') return true;\n return scoopTier(tier);\n}\n\nexport const heldKind = (kind: ApprovalKind): boolean => kind === 'sudo' || kind === 'capture';\n\nexport function routable(kind: ApprovalKind, tier: ApprovalTier): boolean {\n return !((kind === 'guest-tool' || kind === 'capture') && tier === 'cone');\n}\n\nexport function answerOf(value: unknown): ApprovalDecision | null {\n return value === 'once' || value === 'always' || value === 'deny' || value === 'stop'\n ? value\n : null;\n}\n\nexport function answerer(by: DecidedBy, item: Pick<Approval, 'tier' | 'reviewer'>): boolean {\n if (personal(by)) return item.tier === 'user';\n if (by === 'judge') return item.tier === 'agent';\n if (scoopTier(by)) return scoopTier(item.tier) && item.reviewer === by;\n return true;\n}\n\nexport type SudoApprover = 'user' | 'agent';\n\nexport const sudoApprover = (value: unknown): SudoApprover =>\n value === 'agent' ? 'agent' : 'user';\n\nexport const personOnly = (item: Pick<ApprovalDraft, 'kind' | 'detail'>): boolean =>\n item.kind === 'sudo' && (item.detail as SudoDetail).validate === true;\n\nexport const tierOf = (\n draft: Pick<ApprovalDraft, 'kind' | 'detail' | 'tier'>,\n sudo: SudoApprover\n) => (draft.kind !== 'sudo' ? draft.tier : personOnly(draft) ? 'user' : sudo);\n\nexport type Gate = 'person' | 'judge';\n\nexport type Routed = 'approve' | 'deny' | 'ask';\n\nexport const gateOf = (tier: string): Gate => (tier === 'agent' ? 'judge' : 'person');\n\nexport const vetoed = ({ forbidden }: ApprovalVerdict): boolean =>\n forbidden === true || (typeof forbidden === 'number' && reaches(forbidden, JUDGE_LOW));\n\nexport function approvable(verdict: ApprovalVerdict): boolean {\n const sure =\n verdict.routine === undefined ? verdict.via === 'chat' : clears(verdict.routine, JUDGE_ALLOW);\n return verdict.level === 1 && sure && fits(verdict.aligned);\n}\n\nexport function route(\n verdict: ApprovalVerdict | undefined,\n requester: Pick<ApprovalRequester, 'kind'>,\n gate: Gate,\n present: boolean\n): Routed {\n if (gate !== 'judge' || !verdict?.level) return 'ask';\n if (approvable(verdict) && !vetoed(verdict)) return 'approve';\n if (verdict.level === 3 && requester.kind !== 'user' && !present) return 'deny';\n return 'ask';\n}\n\nexport function alwaysOffered(item: Approval): boolean {\n if ((item.kind !== 'sudo' && item.kind !== 'capture') || item.tier !== 'user') return false;\n if (personOnly(item)) return false;\n const { verdict } = item;\n const writable = item.kind !== 'sudo' || item.detail.writable !== false;\n return verdict?.level === 1 && verdict.always === true && writable;\n}\n\nexport function gone(state: ApprovalState): string {\n if (state === 'unanswered') return 'This request timed out.';\n if (state === 'withdrawn') return 'This request was withdrawn.';\n return 'Someone else already answered this.';\n}\n\nexport function cleanReason(reason: unknown): string | undefined {\n if (typeof reason !== 'string') return undefined;\n const text = reason.trim().slice(0, REASON_LENGTH);\n return text || undefined;\n}\n\nconst decided = (item: Approval) => item.decidedAt ?? item.createdAt;\n\nexport const runLive = (item: Approval): boolean =>\n item.kind === 'sudo' && (item.run?.state === 'starting' || item.run?.state === 'running');\n\nconst runHeld = (item: Approval): boolean =>\n item.kind === 'sudo' &&\n !!item.run &&\n (runLive(item) || !!item.run.survivors?.length || (!!item.run.stdout && !item.run.removed));\n\nexport function prune(items: Approval[], kept = APPROVALS_KEPT): Approval[] {\n const settled = items.filter((item) => item.state !== 'pending' && !runHeld(item));\n settled.sort((a, b) => decided(a) - decided(b));\n const drop = new Set(settled.slice(0, Math.max(0, settled.length - kept)));\n return items.filter((item) => !drop.has(item));\n}\n\nexport type Settle = { state: Exclude<ApprovalState, 'pending'>; by: DecidedBy; reason?: string };\n\nexport type Ruling = {\n error?: string;\n settle?: Settle;\n answer?: 'once' | 'always';\n stop?: string;\n};\n\nfunction stopped(item: Approval, by: DecidedBy): Ruling {\n if (!personal(by)) return { error: 'Only a person can stop a turn.' };\n if (!stoppable(item)) return { error: 'This request has no turn to stop.' };\n return {\n settle: { state: 'rejected', by, reason: REASONS.stopped },\n stop: item.requester.agentId as string,\n };\n}\n\nconst why = (reason: string | undefined) =>\n reason && reason !== REASONS.stopped ? { reason } : {};\n\nexport function ruled(\n item: Approval,\n answer: unknown,\n reason: unknown,\n by: DecidedBy,\n at: number\n): Ruling {\n if (item.state !== 'pending') return { error: gone(item.state) };\n if (item.expiresAt <= at)\n return {\n error: gone('unanswered'),\n settle: { state: 'unanswered', by: 'host', reason: REASONS.timeout },\n };\n if (!answerer(by, item)) return { error: \"This request isn't yours to answer.\" };\n const known = answerOf(answer);\n if (known === 'always' && scoopTier(by)) return { error: 'A scoop answers once or deny.' };\n if (known === 'always' && !personal(by))\n return { error: 'Always can only be answered by a person.' };\n if (known === 'always' && !item.always)\n return { error: \"Always isn't offered for this request.\" };\n if (!known) return { settle: { state: 'rejected', by, reason: REASONS.unknownAnswer } };\n if (known === 'stop') return stopped(item, by);\n const given = why(cleanReason(reason));\n if (known === 'deny') return { settle: { state: 'rejected', by, ...given } };\n return { settle: { state: 'approved', by, ...given }, answer: known };\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B,SAAS,QAAQ,MAAM,aAAa,WAAW,eAAe;AAC9D,SAAS,gBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS,iBAAiB;AAiKnB,MAAM,eAAe,UAA0B;AAAA,EACpD,MAAM;AAAA,EACN,gBAAgB;AAAA,EAChB,SAAS;AAAA,EACT,OAAO;AAAA,EACP,SAAS,OAAO,EAAE,OAAO,CAAC,EAAE;AAC9B,CAAC;AAEM,MAAM,cAAc;AACpB,MAAM,iBAAiB;AACvB,MAAM,YAAY;AAClB,MAAM,gBAAgB;AAEtB,MAAM,YAAY,CAAC,SAAgC,SAAS;AAE5D,MAAM,YAAY,CAAC,SACxB,OAAO,SAAS,YAAY,cAAc,KAAK,IAAI;AAE9C,SAAS,UAAU,MAAqC;AAC7D,MAAI,SAAS,UAAU,SAAS,WAAW,SAAS,OAAQ,QAAO;AACnE,SAAO,UAAU,IAAI;AACvB;AAEO,MAAM,WAAW,CAAC,SAAgC,SAAS,UAAU,SAAS;AAE9E,SAAS,SAAS,MAAoB,MAA6B;AACxE,SAAO,GAAG,SAAS,gBAAgB,SAAS,cAAc,SAAS;AACrE;AAEO,SAAS,SAAS,OAAyC;AAChE,SAAO,UAAU,UAAU,UAAU,YAAY,UAAU,UAA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