@ai-ecoverse/slicc-agent 5.7.0 → 5.8.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 +10 -6
- package/dist/agent.js +4 -2
- package/dist/agent.js.map +2 -2
- package/dist/approvals/record.js.map +1 -1
- package/dist/control.js +2 -1
- package/dist/control.js.map +2 -2
- package/dist/guests/guard.js +168 -23
- package/dist/guests/guard.js.map +3 -3
- package/dist/guests/index.js +13 -4
- package/dist/guests/index.js.map +2 -2
- package/dist/guests/seats.js.map +2 -2
- package/dist/host.js +13 -8
- package/dist/host.js.map +2 -2
- package/dist/services.js +2 -0
- package/dist/services.js.map +2 -2
- package/dist/types/agent.d.ts +2 -0
- package/dist/types/approvals/record.d.ts +2 -0
- package/dist/types/control.d.ts +1 -1
- package/dist/types/guests/guard.d.ts +29 -2
- package/dist/types/guests/index.d.ts +3 -0
- package/dist/types/guests/seats.d.ts +9 -0
- package/dist/types/services.d.ts +4 -1
- 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()`, 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` 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`, `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. 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. 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.
|
|
@@ -604,10 +604,10 @@ It prints the tab's stdout and stderr on their own streams and exits with its co
|
|
|
604
604
|
|
|
605
605
|
Every approval, of a guest's prompt, of a tool call in a run a guest started, or of a sudo request, 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.
|
|
606
606
|
|
|
607
|
-
- **An item** is `{ id, kind, seat?, agentId, requester, detail, tier, state, decidedBy, device?, answer?, reason?, verdict?, always, createdAt, expiresAt, decidedAt? }`. `kind` is `guest-message` (`detail: { text, attachments }`), `guest-tool` (`{ tool, summary }`) or `sudo` (`{ command, target?, cwd?, alwaysScope? }`). `requester` is `{ kind: 'guest' | 'agent' | 'user', name, seat?, agentId?, where?, device? }`.
|
|
607
|
+
- **An item** is `{ id, kind, seat?, agentId, requester, detail, tier, state, decidedBy, device?, answer?, reason?, verdict?, always, createdAt, expiresAt, decidedAt? }`. `kind` is `guest-message` (`detail: { text, attachments }`), `guest-tool` (`{ tool, summary, arguments?, task? }`) or `sudo` (`{ command, target?, cwd?, alwaysScope? }`). `requester` is `{ kind: 'guest' | 'agent' | 'user', name, seat?, agentId?, where?, device? }`.
|
|
608
608
|
- **`state`** is `pending`, `approved` (with `answer` `once` or `always`), `rejected` (someone said no), `unanswered` (nobody decided: it timed out or couldn't be routed) or `withdrawn` (the requester went away). `reason` is a field, never a state: a person's own words, or `timeout`, `unknown-tier`, `unroutable`, `unknown-answer`, `restart`, `revoked`, `aborted` or `disconnected`. `decidedBy` is `owner`, `follower`, `judge` or `host`.
|
|
609
609
|
- **`tier`** says who answers: `user` (a person, through `decide`), `agent` (the automatic judge), `cone` or `scoop:<name>`. A tier the agent doesn't know settles at once as `unanswered` with `unknown-tier`, and so does `cone` for a guest's tool call (`unroutable`), because a run can't approve its own gate. A person answers only `user` items, the judge only `agent` ones.
|
|
610
|
-
- **The rules:** the first decision wins, and a later one, or one past `expiresAt`, is refused ("Someone else already answered this.", "This request timed out.", "This request was withdrawn."). An answer other than `once`, `always` or `deny` is a deny (`unknown-answer`). `always` is `false` for anything a guest triggered unless the approval policy's `guests.always` offers it for that kind (by default it doesn't), and `decide(id, 'always')` on an item without it is refused and leaves it pending.
|
|
610
|
+
- **The rules:** the first decision wins, and a later one, or one past `expiresAt`, is refused ("Someone else already answered this.", "This request timed out.", "This request was withdrawn."). An answer other than `once`, `always` or `deny` is a deny (`unknown-answer`). `always` is `false` for anything a guest triggered unless the approval policy's `guests.always` offers it for that kind (by default it doesn't), 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).
|
|
611
611
|
- **Lifetime:** an item waits 5 minutes unless its requester sets `expiresAt`, then settles `unanswered`. Pending guest items survive a reload of the worker; pending `sudo` items are withdrawn (`restart`), because a reload ends the kernel's processes. The document keeps every pending item and the last 100 settled ones.
|
|
612
612
|
- **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.
|
|
613
613
|
- **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`.
|
|
@@ -648,7 +648,7 @@ All the limits on approvals and guests live in one owner-changeable policy, the
|
|
|
648
648
|
- **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.
|
|
649
649
|
- **Where it applies:** gates and expiry are checked when a seat opens, so a seat keeps its gates when the policy changes later.
|
|
650
650
|
- **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.
|
|
651
|
-
- **Not policy:** the
|
|
651
|
+
- **Not policy:** the technical bounds (label 64, proposal 32,000 characters).
|
|
652
652
|
|
|
653
653
|
### Remote control
|
|
654
654
|
|
|
@@ -666,13 +666,17 @@ All the limits on approvals and guests live in one owner-changeable policy, the
|
|
|
666
666
|
|
|
667
667
|
A guest seat (plan D13, PR 19) is a revocable seat on one cone: the guest sees that cone's live transcript and has a composer, and nothing else.
|
|
668
668
|
|
|
669
|
-
- **Minting.** The tray hub mints the seat and its one-time URL (v6's routes, D10); the page hands the agent adapter its routes: `createAgentModel(connection, { guests: { mint({ label, expiresAt, gates, agentId }) → { id, url }, revoke(id) } })`. Its `guests` port (spectrum's `GuestPort`) mints through the hub, then opens the seat in the worker with `AgentControl.guestOpen({ id, label, agentId, expiresAt, gates })`; if the worker refuses, the hub's seat is revoked again. `list()` is the transcript's `guests` state (`{ id, label, agentId, createdAt, expiresAt, gates, connected, pending }`), and the URL is returned once and never kept. `unavailable()` says "Inviting guests needs the tray hub." without a hub, and "Only the owner's devices can invite guests." on a guest. Every owner device can invite, with or without Control. `gates()` lists the gates the approval policy allows for messages and tools, in display order, with `scoop:*` for "any scoop", for the invite dialog.
|
|
669
|
+
- **Minting.** The tray hub mints the seat and its one-time URL (v6's routes, D10); the page hands the agent adapter its routes: `createAgentModel(connection, { guests: { mint({ label, expiresAt, gates, agentId }) → { id, url }, revoke(id) } })`. Its `guests` port (spectrum's `GuestPort`) mints through the hub, then opens the seat in the worker with `AgentControl.guestOpen({ id, label, agentId, expiresAt, gates })`; if the worker refuses, the hub's seat is revoked again. `list()` is the transcript's `guests` state (`{ id, label, agentId, createdAt, expiresAt, gates, connected, pending, alwaysTools }`), and the URL is returned once and never kept. `unavailable()` says "Inviting guests needs the tray hub." without a hub, and "Only the owner's devices can invite guests." on a guest. Every owner device can invite, with or without Control. `gates()` lists the gates the approval policy allows for messages and tools, in display order, with `scoop:*` for "any scoop", for the invite dialog.
|
|
670
670
|
- **The record.** Seats live in the session document `slicc.guests`, so they survive reloads and restarts: id, label (control characters stripped, at most 64 characters), cone, expiry (at most the policy's `guests.maxSeatDays`, 30 by default), the two gates (`user`, `agent`, `cone`, `scoop:<name>` or `off`, fixed when the seat is opened and checked then against the policy's `allowedMessageGates` and `allowedToolGates`; by default the tools gate can't be `off` or `cone`, from any caller: "A guest's tool calls need a review: by a person, the judge or a scoop.") and an epoch. Revoking (`guestRevoke(id)`) keeps a tombstone, bumps the epoch, withdraws the guest's messages still queued in the cone, and ends every guest link of the seat (`invalidatePrincipal`). An expired seat ends the same way at its expiry. Tombstones go 365 days after they end, the longest a seat can be opened for.
|
|
671
671
|
- **Joining.** The hub resolves the guest's token to the seat's id and label, and the owner page opens `owner.port({ guest: { id, label } })` and bridges it like a follower's. Before Chord sees the link, the worker checks that the seat exists, isn't revoked or expired, and has that label; otherwise it closes the port. The link's principal is `{ seat: 'guest', link, guest: { id, name, epoch } }`, and anything else the port asks for (`readOnly: false`, `pages`) is ignored.
|
|
672
672
|
- **What a guest gets.** Every contract served from the agent's host refuses a guest principal (`forbidden`) unless its factory is opened with `openToGuests`, so a contract added later is closed to guests until someone opens it. The only open one is `slicc.agent.guest`: its `guest` variant has the shared cone's transcript (its user, assistant, tool and compaction entries; `pi.live`; `pi.agent`'s model and thinking level; and only the guest's own queued messages) and the seat, plus `propose({ text, requestId })`. Everyone else gets its empty `none` variant.
|
|
673
673
|
- **The guest's page** calls `connectGuest(endpoint)` from `@ai-ecoverse/slicc-agent/page`, which resolves an `AgentConnection` for that one cone with `guest` (the seat as the guest sees it); `connectAgent` on a guest port is forbidden. `createAgentModel(guest).agent` shows the transcript and sends through `propose`; every other control method, settings action, `prompt` and `webhook` rejects with `EACCES` ("a guest can only watch and send messages"). A port that isn't a valid seat rejects with `EACCES` "This guest link isn't valid any more."
|
|
674
674
|
- **Messages.** With the messages gate `off`, a guest's message is submitted to the cone as a follow-up placed as a `slicc.guest-input` entry (`{ seat, name, approval: null }`), and the model reads it after the line "[A guest message from "<label>", shared through a guest seat, NOT from the cone's owner. …]". The spectrum adapter shows it as a user message with `origin: 'guest'` and `from` the label, without that line, queued or placed. Under any other gate it waits as a pending `guest-message` approval (tier = the gate, requester from the seat), which times out like other approvals. The guest contract's `proposals` state lists the seat's own, and the guest's adapter shows a pending one as its queued message and an ended one as a notice: "Nobody approved this in time.", "It was declined." or "It was withdrawn." Once approved it is delivered exactly once (request id `guest:<seat>:<approval>`, and the seat record keeps the ids it delivered) as the same entry with `approval` set; a seat revoked or expired by then gets nothing. #253 makes the delivery durable across a crash between approval and submit, and adds the review UX.
|
|
675
|
-
- **Tool calls in guest runs
|
|
675
|
+
- **Tool calls in guest runs wait for a review.** `slicc-guest-guard` ([`src/guests/guard.ts`](src/guests/guard.ts)) is a `beforeTool` hook that `openAgent` installs in every registry, so every conversation has it: old ones stored with an extension list, forks and thawed cones included. It gates each tool call in a run whose `pi.live` inputs include a guest's delivered message, found in the seat's `submissions` with the tools tier fixed when it was submitted. A run an owner steered into still counts. Nested calls from codemode and MCP bridges go through the same hook, so a `codemode` call is reviewed itself and so is each tool call its script makes. Owner-only runs pass untouched.
|
|
676
|
+
- **The tier decides.** `off` passes, if the policy's `allowedToolGates` still allows it (it doesn't by default). A tier the policy no longer allows is refused with the policy's sentence. A tier the agent doesn't know, a guest input with no recorded submission, and a seat that has ended all deny. So does `scoop:<name>`, at once, because no scoop can answer an approval yet. Otherwise the hook files a `guest-tool` approval on that tier (`user`, or `agent` for the judge), with `detail: { tool, summary, arguments, task }`, and waits for it on the approvals document, honouring the abort signal. If the seat ends while the call is filed or reviewed, the item is withdrawn and the call blocked, even after an approval. Anything else but approve blocks too, and the model sees `Tool call blocked: <reason>`, such as "The owner declined this tool call in a run a guest started." with the owner's reason.
|
|
677
|
+
- **Once per call.** The approval's id is a memo of the tool task (`slicc.guest-tool:<seat>:<tier>`), so after a crash or reload the hook reruns before the tool runs and rejoins the same review, without asking again.
|
|
678
|
+
- **Abort.** Once a waiting call's task ends without an answer, its approval is withdrawn (`aborted`), so aborting the conversation withdraws its pending guest tool calls. That also covers the calls of a script abandoned by a restart.
|
|
679
|
+
- **Always** is offered only while `guests.always.tools` is true. An Always answer adds a rule to the seat's `alwaysTools`: `{ approval, tool, arguments, by, at }`, where `arguments` is the call's canonical JSON (keys sorted). Later calls from that seat with the same tool and exactly the same arguments pass without asking, while the policy still offers Always. The transcript's `guests` list shows each seat's rules. `AgentControl.guestAlwaysForget(seat, approval)`, for owner devices, removes one, and revoking the seat drops them all.
|
|
676
680
|
- **Revocation and expiry clean up alike.** Revoking or expiring a seat withdraws its queued input and its pending approvals; a proposal still being placed is serialised with them per seat and rechecks the seat right before it's placed, so nothing lands after a revoke.
|
|
677
681
|
- **Every owner device manages guests.** The owner's pages and followers, with or without Control, open, list and revoke seats alike.
|
|
678
682
|
- **A guest managing guests** is refused by the approval policy (`guests.manageGuests`, `deny`). The guest contract has `guestOpen` and `guestRevoke`, and both are refused with `forbidden` ("The owner's guest policy doesn't let guests manage guests."). The approval policy itself is never a guest's to change: its write is on `AgentControl`, which a guest can't reach.
|
package/dist/agent.js
CHANGED
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
MemoryStorage
|
|
7
7
|
} from "@earendil-works/pi-durable";
|
|
8
8
|
import { openAgents } from "./agents.js";
|
|
9
|
-
import {
|
|
9
|
+
import { guestToolGate } from "./guests/guard.js";
|
|
10
10
|
import { guestReviews } from "./guests/review.js";
|
|
11
11
|
function answerText(content) {
|
|
12
12
|
if (typeof content === "string") return content;
|
|
@@ -25,7 +25,8 @@ async function openAgent(options) {
|
|
|
25
25
|
const context = options.context ?? BACKGROUND_CONTEXT;
|
|
26
26
|
const registry = options.registry ?? createRegistry();
|
|
27
27
|
let opened;
|
|
28
|
-
|
|
28
|
+
const gate = guestToolGate(() => opened);
|
|
29
|
+
registry.install(gate.extension);
|
|
29
30
|
const reviews = guestReviews();
|
|
30
31
|
registry.install(reviews.extension);
|
|
31
32
|
const harness = await Harness.open(
|
|
@@ -49,6 +50,7 @@ async function openAgent(options) {
|
|
|
49
50
|
root,
|
|
50
51
|
agents,
|
|
51
52
|
reviews,
|
|
53
|
+
gate,
|
|
52
54
|
cone: () => agents.cone(),
|
|
53
55
|
switchCone: (conversation, switching) => agents.switchCone(conversation, switching),
|
|
54
56
|
onCone: (listener) => agents.onCone(listener),
|
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 { Cones } from './cone.ts';\nimport {
|
|
5
|
-
"mappings": "AACA,SAAS,0BAA0B;AAEnC;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,OAIK;AACP,SAAsB,kBAAkB;AAExC,
|
|
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 { Cones } from './cone.ts';\nimport { type GuestToolGate, guestToolGate } from './guests/guard.ts';\nimport { type GuestReviews, guestReviews } from './guests/review.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}\n\nexport interface Agent extends Cones {\n readonly harness: Harness;\n readonly root: Conversation;\n readonly agents: Agents;\n readonly reviews: GuestReviews;\n readonly gate: GuestToolGate;\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 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 harness = await Harness.open(\n options.storage ?? new MemoryStorage(),\n {\n models: options.models,\n registry,\n ...(options.settings ? { settings: options.settings } : {}),\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 root,\n agents,\n reviews,\n gate,\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: ()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,SAAS,IAAI,CAAC;AAAA,MACzD,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;AAAA,IACA;AAAA,IACA;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
|
}
|
|
@@ -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';\n\nexport type ApprovalKind = 'guest-message' | 'guest-tool' | 'sudo';\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 DecidedBy = 'owner' | 'follower' | 'judge' | 'host';\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 ApprovalVerdict = {\n decision: 'allow' | 'deny' | 'unsure';\n reason: string;\n risk?: number;\n aligned?: number;\n model?: string;\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 };\n\nexport type SudoDetail = {\n command: string;\n target?: string;\n cwd?: string;\n alwaysScope?: 'cwd';\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 reason?: string;\n verdict?: ApprovalVerdict;\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 };\n\nexport type Approval = GuestMessageApproval | GuestToolApproval | SudoApproval;\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\nexport type ApprovalsState = { items: Approval[] };\n\nexport const ApprovalsDoc = defineDoc<ApprovalsState>({\n kind: 'slicc.approvals',\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 REASONS = {\n timeout: 'timeout',\n unknownTier: 'unknown-tier',\n unroutable: 'unroutable',\n unknownAnswer: 'unknown-answer',\n restart: 'restart',\n revoked: 'revoked',\n aborted: 'aborted',\n disconnected: 'disconnected',\n} as const;\n\nexport const guestKind = (kind: ApprovalKind): boolean => kind !== 'sudo';\n\nexport function knownTier(tier: unknown): tier is ApprovalTier {\n if (tier === 'user' || tier === 'agent' || tier === 'cone') return true;\n return typeof tier === 'string' && /^scoop:\\S+$/.test(tier);\n}\n\nexport function routable(kind: ApprovalKind, tier: ApprovalTier): boolean {\n return !(kind === 'guest-tool' && tier === 'cone');\n}\n\nexport function answerOf(value: unknown): ApprovalAnswer | null {\n return value === 'once' || value === 'always' || value === 'deny' ? value : null;\n}\n\nexport const personal = (by: DecidedBy): boolean => by === 'owner' || by === 'follower';\n\nexport function answerer(by: DecidedBy, tier: string): boolean {\n if (personal(by)) return tier === 'user';\n if (by === 'judge') return tier === 'agent';\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 tierOf = (kind: ApprovalKind, tier: string, sudo: SudoApprover): string =>\n kind === 'sudo' ? sudo : tier;\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 = { error?: string; settle?: Settle; answer?: 'once' | 'always' };\n\nconst why = (reason: string | undefined) => (reason ? { 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.tier)) return { error: \"This request isn't yours to answer.\" };\n const known = answerOf(answer);\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 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"],
|
|
4
|
+
"sourcesContent": ["import { defineDoc } from '@earendil-works/pi-durable';\n\nexport type ApprovalKind = 'guest-message' | 'guest-tool' | 'sudo';\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 DecidedBy = 'owner' | 'follower' | 'judge' | 'host';\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 ApprovalVerdict = {\n decision: 'allow' | 'deny' | 'unsure';\n reason: string;\n risk?: number;\n aligned?: number;\n model?: string;\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 SudoDetail = {\n command: string;\n target?: string;\n cwd?: string;\n alwaysScope?: 'cwd';\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 reason?: string;\n verdict?: ApprovalVerdict;\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 };\n\nexport type Approval = GuestMessageApproval | GuestToolApproval | SudoApproval;\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\nexport type ApprovalsState = { items: Approval[] };\n\nexport const ApprovalsDoc = defineDoc<ApprovalsState>({\n kind: 'slicc.approvals',\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 REASONS = {\n timeout: 'timeout',\n unknownTier: 'unknown-tier',\n unroutable: 'unroutable',\n unknownAnswer: 'unknown-answer',\n restart: 'restart',\n revoked: 'revoked',\n aborted: 'aborted',\n disconnected: 'disconnected',\n} as const;\n\nexport const guestKind = (kind: ApprovalKind): boolean => kind !== 'sudo';\n\nexport function knownTier(tier: unknown): tier is ApprovalTier {\n if (tier === 'user' || tier === 'agent' || tier === 'cone') return true;\n return typeof tier === 'string' && /^scoop:\\S+$/.test(tier);\n}\n\nexport function routable(kind: ApprovalKind, tier: ApprovalTier): boolean {\n return !(kind === 'guest-tool' && tier === 'cone');\n}\n\nexport function answerOf(value: unknown): ApprovalAnswer | null {\n return value === 'once' || value === 'always' || value === 'deny' ? value : null;\n}\n\nexport const personal = (by: DecidedBy): boolean => by === 'owner' || by === 'follower';\n\nexport function answerer(by: DecidedBy, tier: string): boolean {\n if (personal(by)) return tier === 'user';\n if (by === 'judge') return tier === 'agent';\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 tierOf = (kind: ApprovalKind, tier: string, sudo: SudoApprover): string =>\n kind === 'sudo' ? sudo : tier;\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 = { error?: string; settle?: Settle; answer?: 'once' | 'always' };\n\nconst why = (reason: string | undefined) => (reason ? { 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.tier)) return { error: \"This request isn't yours to answer.\" };\n const known = answerOf(answer);\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 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}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OAAO,YAAY,IAAI,GAAG,MAAM,GAAG,QAAQ,MAAM;AACtE;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/control.js
CHANGED
|
@@ -49,7 +49,8 @@ function freezerControl(freezer) {
|
|
|
49
49
|
function guestControl(guests) {
|
|
50
50
|
return {
|
|
51
51
|
guestOpen: async (draft, context) => guests ? guests.open(draft, context) : { seat: null, error: NO_GUESTS },
|
|
52
|
-
guestRevoke: async (id, context) => guests ? guests.revoke(id, context) : { revoked: false }
|
|
52
|
+
guestRevoke: async (id, context) => guests ? guests.revoke(id, context) : { revoked: false },
|
|
53
|
+
guestAlwaysForget: async (seat, approval, context) => guests ? guests.forgetAlways(seat, approval, context) : { removed: false }
|
|
53
54
|
};
|
|
54
55
|
}
|
|
55
56
|
const NO_GUESTS = "This agent has no guest seats.";
|
package/dist/control.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/control.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Context } from '@earendil-works/chord';\nimport {\n AssistantEntry,\n type Conversation,\n ConversationBusy,\n type ConversationView,\n type EntryId,\n type EntryRecord,\n type Harness,\n type SubmissionId,\n type UserInput,\n} from '@earendil-works/pi-durable';\nimport { answerText } from './agent.ts';\nimport type { Agents, ScoopRecord } from './agents.ts';\nimport { type ShownAttachment, splitUser, userParts } from './attachments.ts';\nimport type { ChangesRuntime } from './changes/index.ts';\nimport type { Cones } from './cone.ts';\nimport type { Deliveries } from './deliveries.ts';\nimport type { FreezerRuntime } from './freezer/index.ts';\nimport type { Guests } from './guests/index.ts';\nimport type { LickSources, Licks } from './licks/index.ts';\nimport { LICK_STATE_KIND } from './licks/state.ts';\nimport type { MemoryRuntime } from './memory/index.ts';\nimport type { Monitor } from './monitor/index.ts';\nimport type { Scoops, ScoopsRuntime } from './scoops/index.ts';\nimport { SECRETS_COMMAND, secretsEntry } from './secrets/extension.ts';\nimport type { SecretName } from './secrets/names.ts';\nimport { scrubItems, scrubText } from './secrets/scrub.ts';\nimport { copyAgent, storedAgent } from './selection.ts';\nimport type {\n AgentControl,\n Created,\n ImageRef,\n LickResolved,\n OperationError,\n Rewound,\n SendRequest,\n SendResponse,\n StoredImage,\n} from './services.ts';\nimport type { SkillsRuntime } from './skills/index.ts';\nimport type { SprinklesRuntime } from './sprinkles/index.ts';\nimport type { LabelsRuntime } from './titles/labels.ts';\nimport { saverFor, type Uploads } from './uploads.ts';\n\nexport interface HostLicks {\n licks: Licks;\n sources: LickSources;\n}\n\nexport interface HostScoops {\n scoops: Scoops;\n runtime: ScoopsRuntime;\n}\n\ntype WithAgents = { agents?: Agents };\n\nexport function readable(out: string): string {\n const text = out.replace(/^(?:sub)?agent: /, '').trim();\n const sentence = text.charAt(0).toUpperCase() + text.slice(1);\n return /[.!?]$/.test(sentence) ? sentence : `${sentence}.`;\n}\n\nfunction created(run: () => Promise<string>): Promise<Created> {\n return run().then(\n (id) => ({ id, error: null }),\n (error: Error) => ({ id: null, error: error.message })\n );\n}\n\nfunction monitorControl(\n monitor: Pick<Monitor, 'open' | 'close'> | undefined\n): Pick<AgentControl, 'monitorOpen' | 'monitorClose'> {\n return {\n monitorOpen: async (lease, resync, context) =>\n monitor ? monitor.open(lease, resync, context) : { lease: '', ttlMs: 0 },\n monitorClose: async (lease, context) => monitor?.close(lease, context),\n };\n}\n\nconst noApprovals: AgentControl['decide'] = async () => ({\n done: false,\n state: null,\n error: 'This agent has no approvals.',\n});\n\nfunction freezerControl(\n freezer: Pick<FreezerRuntime, 'freeze' | 'newChat' | 'thaw' | 'discard'> | undefined\n): Pick<AgentControl, 'freeze' | 'newChat' | 'thaw' | 'discard'> {\n const needed = () => {\n if (!freezer) throw new Error('This agent has no freezer.');\n return freezer;\n };\n return {\n freeze: (agentId, context) => created(async () => needed().freeze(agentId, context)),\n newChat: (agentId, context) =>\n created(async () => (await needed().newChat(agentId, context)) ?? ''),\n thaw: (id, context) => created(async () => needed().thaw(id, context)),\n discard: (id, context) =>\n created(async () => {\n await needed().discard(id, context);\n return id;\n }),\n };\n}\n\nfunction guestControl(\n guests: Pick<Guests, 'open' | 'revoke'> | undefined\n): Pick<AgentControl, 'guestOpen' | 'guestRevoke'> {\n return {\n guestOpen: async (draft, context) =>\n guests ? guests.open(draft, context) : { seat: null, error: NO_GUESTS },\n guestRevoke: async (id, context) => (guests ? guests.revoke(id, context) : { revoked: false }),\n };\n}\n\nconst NO_GUESTS = 'This agent has no guest seats.';\n\nfunction changesControl(\n changes: Pick<ChangesRuntime, 'open' | 'accept' | 'revert'> | undefined\n): Pick<AgentControl, 'changesOpen' | 'changeAccept' | 'changeRevert'> {\n const needed = () => {\n if (!changes) throw new Error('This agent tracks no changes.');\n return changes;\n };\n const done = (path: string, run: (runtime: NonNullable<typeof changes>) => Promise<void>) =>\n created(async () => {\n await run(needed());\n return path;\n });\n return {\n changesOpen: async (context) => changes?.open(context),\n changeAccept: (path, context) => done(path, (runtime) => runtime.accept(path, context)),\n changeRevert: (path, context) => done(path, (runtime) => runtime.revert(path, context)),\n };\n}\n\nfunction memoryControl(\n memory: Pick<MemoryRuntime, 'save' | 'remove'> | undefined\n): Pick<AgentControl, 'memorySave' | 'memoryRemove'> {\n return {\n async memorySave(draft, context) {\n if (!memory) throw new Error('This agent has no memory.');\n const { id, ...rest } = draft;\n return memory.save({ ...rest, ...(id ? { id } : {}) }, context);\n },\n async memoryRemove(id, context) {\n return { removed: memory ? await memory.remove(id, context) : false };\n },\n };\n}\n\nfunction sprinkleControl(\n sprinkles: Pick<SprinklesRuntime, 'send' | 'call'> | undefined\n): Pick<AgentControl, 'sprinkleSend' | 'sprinkleCall'> {\n return {\n sprinkleSend: async (id, payload, context) =>\n sprinkles ? sprinkles.send(id, payload, context) : { delivered: false },\n async sprinkleCall(id, method, args, context) {\n if (!sprinkles) throw new Error('This agent has no sprinkles.');\n return sprinkles.call(id, method, args, context);\n },\n };\n}\n\nexport function submissionId(value: string): SubmissionId | undefined {\n const id = Number(value);\n return /^[1-9][0-9]*$/.test(value) && Number.isSafeInteger(id) ? (id as SubmissionId) : undefined;\n}\n\nfunction operationError(error: unknown): OperationError {\n if (error instanceof ConversationBusy) return { code: 'busy', message: error.message };\n return { code: 'failed', message: error instanceof Error ? error.message : String(error) };\n}\n\nasync function accepted(operation: () => Promise<{ id: number } | number>): Promise<SendResponse> {\n try {\n const result = await operation();\n const id = typeof result === 'number' ? result : result.id;\n return { accepted: true, submissionId: String(id), error: null };\n } catch (error) {\n return { accepted: false, submissionId: null, error: operationError(error) };\n }\n}\n\nfunction cones(target: Conversation | Cones): Cones {\n if ('cone' in target) return target;\n return {\n cone: () => target,\n switchCone: async () => {\n throw new Error('this conversation has no cone to rewind');\n },\n };\n}\n\ninterface Turn {\n text: string;\n attachments: ShownAttachment[];\n at: EntryId | null;\n files: boolean;\n}\n\ntype Block = { type?: string; name?: string };\n\nconst WRITERS = ['write', 'edit', 'bash', 'codemode'];\n\nfunction writesIn(entries: readonly EntryRecord[]): boolean {\n return entries.some((entry) =>\n (entry.model ?? []).some(\n (message) =>\n Array.isArray(message.content) &&\n (message.content as Block[]).some(\n (block) => block.type === 'toolCall' && WRITERS.includes(String(block.name))\n )\n )\n );\n}\n\nfunction lastTurn(view: ConversationView, messageId: string | null): Turn | null {\n const { entries } = view;\n const target = entries.findIndex((entry) => `e${entry.id}` === messageId);\n if (target < 0) return null;\n const turn = entries.slice(0, target).findLastIndex((entry) => entry.kind === 'pi.user');\n if (turn < 0) return null;\n const user = entries[turn] as EntryRecord;\n return {\n ...splitUser(user.model?.[0]?.content),\n at: entries[turn - 1]?.id ?? null,\n files: writesIn(entries.slice(turn)),\n };\n}\n\nfunction busy(view: ConversationView): boolean {\n const live = view.docs['pi.live'] as { run?: unknown } | undefined;\n const inbox = view.docs['pi.inbox'] as { items?: unknown[] } | undefined;\n return Boolean(live?.run) || Boolean(inbox?.items?.length);\n}\n\ntype RewindDeps = {\n harness: Harness;\n agents?: Agents;\n cone: Cones;\n scoops?: HostScoops;\n};\n\nasync function turnIn(\n harness: Harness,\n conversation: Conversation,\n messageId: string | null,\n context: Context\n): Promise<{ turn: Turn; view: ConversationView } | Rewound> {\n const attached = await conversation.viewState(context);\n const view = attached.value;\n attached.dispose();\n const pending = (await harness.inspect(context)).submissions.some(\n (submission) => submission.conversationId === conversation.id\n );\n if (pending || busy(view)) return { done: false, text: null, reason: 'busy' };\n const turn = lastTurn(view, messageId);\n return turn ? { turn, view } : { done: false, text: null, reason: 'no-turn' };\n}\n\nasync function forkAt(\n harness: Harness,\n conversation: Conversation,\n found: { turn: Turn },\n context: Context\n): Promise<Conversation> {\n const ownership = { kind: 'ownerless' } as const;\n if (found.turn.at !== null) return conversation.fork(found.turn.at, { ownership }, context);\n const init = copyAgent(await storedAgent(harness, conversation.id, context));\n return harness.createConversation({ ownership, init }, context);\n}\n\nasync function rewindAgent(\n deps: RewindDeps,\n agentId: string | null,\n messageId: string | null,\n context: Context\n): Promise<Rewound> {\n const { harness, agents, cone, scoops } = deps;\n const scoop = agentId && agents ? agents.state().scoops[agentId] : undefined;\n if (agentId && agents && !scoop && agentId !== agents.activeCone())\n await agents.selectCone(agentId, context);\n const conversation =\n scoop && agents\n ? ((await agents.conversation(agentId as string, context)) as Conversation)\n : cone.cone();\n const found = await turnIn(harness, conversation, messageId, context);\n if ('reason' in found) return found;\n const fork = await forkAt(harness, conversation, found, context);\n const changed =\n scoops && agents && !scoop\n ? await scoops.scoops.rewound(agents.activeCone(), fork, context)\n : { stopped: [], restored: [] };\n const files = found.turn.files;\n await fork.submit(\n { type: 'write', entry: { kind: 'slicc.rewound', data: { turns: 1, ...changed, files } } },\n context\n );\n if (scoop && agents)\n await agents.update((_tx, state) => {\n const record = state.scoops[agentId as string] as ScoopRecord;\n record.conversation = fork.id;\n delete record.title;\n delete record.titled;\n }, context);\n else await cone.switchCone(fork, context);\n const { attachments } = found.turn;\n return {\n done: true,\n text: found.turn.text,\n reason: null,\n ...(attachments.length ? { attachments } : {}),\n };\n}\n\ntype Picture = { type?: string; data?: string; mimeType?: string };\n\nasync function storedImage(\n harness: Harness,\n ref: ImageRef,\n context: Context\n): Promise<StoredImage> {\n const entry = await harness.commit((tx) => tx.entry(ref.entry as EntryId), context);\n const content = entry?.model?.[ref.message]?.content;\n const part = Array.isArray(content) ? (content[ref.part] as Picture | undefined) : undefined;\n return part?.type === 'image' && part.data && part.mimeType\n ? { data: part.data, mimeType: part.mimeType }\n : { data: null, mimeType: null };\n}\n\nasync function contentOf(\n text: string,\n request: SendRequest,\n conversation: Conversation,\n uploads: Uploads | undefined,\n context: Context\n): Promise<UserInput> {\n if (!request.attachments?.length) return scrubText(text);\n const saver = await saverFor(conversation, uploads, context);\n return scrubItems(await userParts(text, request.attachments, saver));\n}\n\nexport function createAgentControl(\n harness: Harness,\n target: Conversation | Cones,\n deliveries?: Deliveries,\n licks?: HostLicks,\n scoops?: HostScoops,\n skills?: Pick<SkillsRuntime, 'expand' | 'commandsFor'>,\n sprinkles?: Pick<SprinklesRuntime, 'send' | 'call'>,\n memory?: Pick<MemoryRuntime, 'save' | 'remove'>,\n freezer?: Pick<FreezerRuntime, 'freeze' | 'newChat' | 'thaw' | 'discard'>,\n changes?: Pick<ChangesRuntime, 'open' | 'accept' | 'revert'>,\n monitor?: Pick<Monitor, 'open' | 'close'>,\n secrets?: () => readonly SecretName[],\n uploads?: Uploads,\n labels?: Pick<LabelsRuntime, 'label'>,\n guests?: Pick<Guests, 'open' | 'revoke'>\n): Omit<AgentControl, 'approvalPolicySet'> {\n const cone = cones(target);\n const current = () => cone.cone();\n const agents = (target as WithAgents).agents;\n const conversationFor = async (agentId: string | null | undefined, context: Context) => {\n if (!agentId || !agents) return current();\n const found = await agents.conversation(agentId, context);\n if (!found) throw new Error(`There is no agent ${agentId}.`);\n return found;\n };\n const withdraw = async (conversation: Conversation, id: string, context: Context) => {\n const parsed = submissionId(id);\n if (parsed === undefined) return { outcome: 'not_found' as const };\n const result = await harness.abortSubmission(parsed, context, conversation.id);\n if (result === 'aborted') return { outcome: 'withdrawn' as const };\n return {\n outcome: result === 'not_found' ? ('not_found' as const) : ('already_placed' as const),\n };\n };\n let lock: Promise<unknown> = Promise.resolve();\n const serial = <T>(operation: () => Promise<T>): Promise<T> => {\n const run = lock.then(operation, operation);\n lock = run.catch(() => undefined);\n return run;\n };\n const rewindIn = (agentId: string | null, messageId: string | null, context: Context) =>\n serial(() => rewindAgent({ harness, agents, cone, scoops }, agentId, messageId, context));\n const decide = (\n agentId: string | null,\n lickId: string,\n state: 'confirmed' | 'dismissed',\n context: Context\n ): Promise<LickResolved> =>\n serial(async () => {\n if (!licks) return { done: false, text: null, error: 'this agent has no licks' };\n const action = state === 'confirmed' ? 'confirm' : 'dismiss';\n try {\n const conversation = await conversationFor(agentId, context);\n const text = await licks.licks.decide(conversation, lickId, action, undefined, context);\n await conversation.submit(\n {\n type: 'write',\n entry: {\n kind: LICK_STATE_KIND,\n data: { lick: lickId, state, by: 'user' },\n model: [\n {\n role: 'user',\n content: `The user ${state} lick ${lickId}: ${text}`,\n timestamp: Date.now(),\n },\n ],\n },\n },\n context\n );\n return { done: true, text, error: null };\n } catch (error) {\n return { done: false, text: null, error: (error as Error).message };\n }\n });\n return {\n send(request, context) {\n return serial(async () => {\n if (secrets && request.text.trim() === SECRETS_COMMAND)\n return accepted(async () =>\n (await conversationFor(request.agentId, context)).submit(\n { type: 'write', entry: secretsEntry(secrets()) },\n context\n )\n );\n const response = await accepted(async () => {\n const conversation = await conversationFor(request.agentId, context);\n const expanded = skills\n ? await skills.expand(request.text, context, conversation.id)\n : request.text;\n return conversation.submit(\n {\n type: 'input',\n content: await contentOf(expanded, request, conversation, uploads, context),\n whenBusy: request.whenBusy,\n ...(request.requestId ? { requestId: request.requestId } : {}),\n },\n context\n );\n });\n const id = response.submissionId === null ? undefined : submissionId(response.submissionId);\n if (id !== undefined) deliveries?.expect(id, request.whenBusy);\n return response;\n });\n },\n rewind: (messageId, context) => rewindIn(null, messageId, context),\n rewindAgent: (agentId, messageId, context) => rewindIn(agentId, messageId, context),\n\n async wait(id, context) {\n const parsed = submissionId(id);\n const submission =\n parsed === undefined ? undefined : await harness.submission(parsed, context);\n if (!submission) throw new Error(`unknown submission ${id}`);\n const settled = await submission.wait(context);\n const { answer, reason } = settled as { answer?: EntryId; reason?: string };\n if (answer === undefined) return { status: 'unanswered', text: null, reason: String(reason) };\n const entry = await harness.commit((tx) => tx.entry(AssistantEntry, answer), context);\n return { status: 'done', text: answerText(entry?.model?.[0]?.content), reason: null };\n },\n withdraw: (id, context) => withdraw(current(), id, context),\n ...sprinkleControl(sprinkles),\n ...memoryControl(memory),\n ...freezerControl(freezer),\n ...changesControl(changes),\n ...guestControl(guests),\n ...monitorControl(monitor),\n image: (ref, context) => storedImage(harness, ref, context),\n async unqueue(agentId, id, context) {\n return withdraw(await conversationFor(agentId, context), id, context);\n },\n abort: (context) => current().abort(context),\n compact: (instructions, context) =>\n accepted(() => current().compact(instructions ?? undefined, context)),\n compactAgent: (agentId, instructions, context) =>\n accepted(async () =>\n (await conversationFor(agentId, context)).compact(instructions ?? undefined, context)\n ),\n reset: (handoff, context) => current().reset(handoff ?? undefined, context),\n resolveLick: (lickId, state, context) => decide(null, lickId, state, context),\n resolveAgentLick: (agentId, lickId, state, context) => decide(agentId, lickId, state, context),\n async webhook(name, delivery, context) {\n const delivered = licks\n ? await licks.sources.webhook(\n name,\n {\n ...(delivery.id ? { id: delivery.id } : {}),\n headers: delivery.headers,\n body: delivery.body,\n },\n context\n )\n : false;\n return { delivered };\n },\n async stopAgent(agentId, context) {\n await (await conversationFor(agentId, context)).abort(context);\n },\n async selectCone(agentId, context) {\n await agents?.selectCone(agentId, context);\n },\n createCone(name, context) {\n return created(async () => {\n if (!agents) throw new Error('This agent has a single cone.');\n return agents.createCone(name, context);\n });\n },\n createScoop(parentId, name, context) {\n return created(async () => {\n if (!scoops) throw new Error('This agent has no scoops.');\n const roles = await scoops.runtime.roles(context);\n const answer = await scoops.scoops.spawn(\n { cone: parentId, name, prompts: [], fromAgent: false, limits: roles.limits },\n context\n );\n if (answer.code !== 0) throw new Error(readable(answer.out));\n return `scoop:${answer.out.trim()}`;\n });\n },\n drop(agentId, context) {\n return created(async () => {\n if (!scoops) throw new Error('This agent has no scoops.');\n const answer = await scoops.scoops.stop(agentId, false, context);\n if (answer.code !== 0) throw new Error(readable(answer.out));\n return agentId;\n });\n },\n configure: async (change, context) =>\n (await conversationFor(change.agentId, context)).configure(\n {\n ...(change.model ? { model: change.model } : {}),\n ...(change.thinkingLevel ? { thinkingLevel: change.thinkingLevel } : {}),\n },\n context\n ),\n agentCommands: async (agentId) => skills?.commandsFor(agentId) ?? [],\n toolLabel: async (agentId, callIds, context) =>\n labels ? labels.label(agentId, callIds, context) : null,\n decide: noApprovals,\n };\n}\n"],
|
|
5
|
-
"mappings": "AACA;AAAA,EACE;AAAA,EAEA;AAAA,OAOK;AACP,SAAS,kBAAkB;AAE3B,SAA+B,WAAW,iBAAiB;AAO3D,SAAS,uBAAuB;AAIhC,SAAS,iBAAiB,oBAAoB;AAE9C,SAAS,YAAY,iBAAiB;AACtC,SAAS,WAAW,mBAAmB;AAevC,SAAS,gBAA8B;AAchC,SAAS,SAAS,KAAqB;AAC5C,QAAM,OAAO,IAAI,QAAQ,oBAAoB,EAAE,EAAE,KAAK;AACtD,QAAM,WAAW,KAAK,OAAO,CAAC,EAAE,YAAY,IAAI,KAAK,MAAM,CAAC;AAC5D,SAAO,SAAS,KAAK,QAAQ,IAAI,WAAW,GAAG,QAAQ;AACzD;AAEA,SAAS,QAAQ,KAA8C;AAC7D,SAAO,IAAI,EAAE;AAAA,IACX,CAAC,QAAQ,EAAE,IAAI,OAAO,KAAK;AAAA,IAC3B,CAAC,WAAkB,EAAE,IAAI,MAAM,OAAO,MAAM,QAAQ;AAAA,EACtD;AACF;AAEA,SAAS,eACP,SACoD;AACpD,SAAO;AAAA,IACL,aAAa,OAAO,OAAO,QAAQ,YACjC,UAAU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AQ,aACvB,MAAM,gBAAgB,OAAO,SAAS,OAAO,GAAG;AAAA,MAC/C;AAAA,QACE,GAAI,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;AAAA,QAC9C,GAAI,OAAO,gBAAgB,EAAE,eAAe,OAAO,cAAc,IAAI,CAAC;AAAA,MACxE;AAAA,MACA;AAAA,IACF;AAAA,IACF,eAAe,OAAO,YAAY,QAAQ,YAAY,OAAO,KAAK,CAAC;AAAA,IACnE,WAAW,OAAO,SAAS,SAAS,YAClC,SAAS,OAAO,MAAM,SAAS,SAAS,OAAO,IAAI;AAAA,IACrD,QAAQ;AAAA,EACV;AACF;",
|
|
4
|
+
"sourcesContent": ["import type { Context } from '@earendil-works/chord';\nimport {\n AssistantEntry,\n type Conversation,\n ConversationBusy,\n type ConversationView,\n type EntryId,\n type EntryRecord,\n type Harness,\n type SubmissionId,\n type UserInput,\n} from '@earendil-works/pi-durable';\nimport { answerText } from './agent.ts';\nimport type { Agents, ScoopRecord } from './agents.ts';\nimport { type ShownAttachment, splitUser, userParts } from './attachments.ts';\nimport type { ChangesRuntime } from './changes/index.ts';\nimport type { Cones } from './cone.ts';\nimport type { Deliveries } from './deliveries.ts';\nimport type { FreezerRuntime } from './freezer/index.ts';\nimport type { Guests } from './guests/index.ts';\nimport type { LickSources, Licks } from './licks/index.ts';\nimport { LICK_STATE_KIND } from './licks/state.ts';\nimport type { MemoryRuntime } from './memory/index.ts';\nimport type { Monitor } from './monitor/index.ts';\nimport type { Scoops, ScoopsRuntime } from './scoops/index.ts';\nimport { SECRETS_COMMAND, secretsEntry } from './secrets/extension.ts';\nimport type { SecretName } from './secrets/names.ts';\nimport { scrubItems, scrubText } from './secrets/scrub.ts';\nimport { copyAgent, storedAgent } from './selection.ts';\nimport type {\n AgentControl,\n Created,\n ImageRef,\n LickResolved,\n OperationError,\n Rewound,\n SendRequest,\n SendResponse,\n StoredImage,\n} from './services.ts';\nimport type { SkillsRuntime } from './skills/index.ts';\nimport type { SprinklesRuntime } from './sprinkles/index.ts';\nimport type { LabelsRuntime } from './titles/labels.ts';\nimport { saverFor, type Uploads } from './uploads.ts';\n\nexport interface HostLicks {\n licks: Licks;\n sources: LickSources;\n}\n\nexport interface HostScoops {\n scoops: Scoops;\n runtime: ScoopsRuntime;\n}\n\ntype WithAgents = { agents?: Agents };\n\nexport function readable(out: string): string {\n const text = out.replace(/^(?:sub)?agent: /, '').trim();\n const sentence = text.charAt(0).toUpperCase() + text.slice(1);\n return /[.!?]$/.test(sentence) ? sentence : `${sentence}.`;\n}\n\nfunction created(run: () => Promise<string>): Promise<Created> {\n return run().then(\n (id) => ({ id, error: null }),\n (error: Error) => ({ id: null, error: error.message })\n );\n}\n\nfunction monitorControl(\n monitor: Pick<Monitor, 'open' | 'close'> | undefined\n): Pick<AgentControl, 'monitorOpen' | 'monitorClose'> {\n return {\n monitorOpen: async (lease, resync, context) =>\n monitor ? monitor.open(lease, resync, context) : { lease: '', ttlMs: 0 },\n monitorClose: async (lease, context) => monitor?.close(lease, context),\n };\n}\n\nconst noApprovals: AgentControl['decide'] = async () => ({\n done: false,\n state: null,\n error: 'This agent has no approvals.',\n});\n\nfunction freezerControl(\n freezer: Pick<FreezerRuntime, 'freeze' | 'newChat' | 'thaw' | 'discard'> | undefined\n): Pick<AgentControl, 'freeze' | 'newChat' | 'thaw' | 'discard'> {\n const needed = () => {\n if (!freezer) throw new Error('This agent has no freezer.');\n return freezer;\n };\n return {\n freeze: (agentId, context) => created(async () => needed().freeze(agentId, context)),\n newChat: (agentId, context) =>\n created(async () => (await needed().newChat(agentId, context)) ?? ''),\n thaw: (id, context) => created(async () => needed().thaw(id, context)),\n discard: (id, context) =>\n created(async () => {\n await needed().discard(id, context);\n return id;\n }),\n };\n}\n\nfunction guestControl(\n guests: Pick<Guests, 'open' | 'revoke' | 'forgetAlways'> | undefined\n): Pick<AgentControl, 'guestOpen' | 'guestRevoke' | 'guestAlwaysForget'> {\n return {\n guestOpen: async (draft, context) =>\n guests ? guests.open(draft, context) : { seat: null, error: NO_GUESTS },\n guestRevoke: async (id, context) => (guests ? guests.revoke(id, context) : { revoked: false }),\n guestAlwaysForget: async (seat, approval, context) =>\n guests ? guests.forgetAlways(seat, approval, context) : { removed: false },\n };\n}\n\nconst NO_GUESTS = 'This agent has no guest seats.';\n\nfunction changesControl(\n changes: Pick<ChangesRuntime, 'open' | 'accept' | 'revert'> | undefined\n): Pick<AgentControl, 'changesOpen' | 'changeAccept' | 'changeRevert'> {\n const needed = () => {\n if (!changes) throw new Error('This agent tracks no changes.');\n return changes;\n };\n const done = (path: string, run: (runtime: NonNullable<typeof changes>) => Promise<void>) =>\n created(async () => {\n await run(needed());\n return path;\n });\n return {\n changesOpen: async (context) => changes?.open(context),\n changeAccept: (path, context) => done(path, (runtime) => runtime.accept(path, context)),\n changeRevert: (path, context) => done(path, (runtime) => runtime.revert(path, context)),\n };\n}\n\nfunction memoryControl(\n memory: Pick<MemoryRuntime, 'save' | 'remove'> | undefined\n): Pick<AgentControl, 'memorySave' | 'memoryRemove'> {\n return {\n async memorySave(draft, context) {\n if (!memory) throw new Error('This agent has no memory.');\n const { id, ...rest } = draft;\n return memory.save({ ...rest, ...(id ? { id } : {}) }, context);\n },\n async memoryRemove(id, context) {\n return { removed: memory ? await memory.remove(id, context) : false };\n },\n };\n}\n\nfunction sprinkleControl(\n sprinkles: Pick<SprinklesRuntime, 'send' | 'call'> | undefined\n): Pick<AgentControl, 'sprinkleSend' | 'sprinkleCall'> {\n return {\n sprinkleSend: async (id, payload, context) =>\n sprinkles ? sprinkles.send(id, payload, context) : { delivered: false },\n async sprinkleCall(id, method, args, context) {\n if (!sprinkles) throw new Error('This agent has no sprinkles.');\n return sprinkles.call(id, method, args, context);\n },\n };\n}\n\nexport function submissionId(value: string): SubmissionId | undefined {\n const id = Number(value);\n return /^[1-9][0-9]*$/.test(value) && Number.isSafeInteger(id) ? (id as SubmissionId) : undefined;\n}\n\nfunction operationError(error: unknown): OperationError {\n if (error instanceof ConversationBusy) return { code: 'busy', message: error.message };\n return { code: 'failed', message: error instanceof Error ? error.message : String(error) };\n}\n\nasync function accepted(operation: () => Promise<{ id: number } | number>): Promise<SendResponse> {\n try {\n const result = await operation();\n const id = typeof result === 'number' ? result : result.id;\n return { accepted: true, submissionId: String(id), error: null };\n } catch (error) {\n return { accepted: false, submissionId: null, error: operationError(error) };\n }\n}\n\nfunction cones(target: Conversation | Cones): Cones {\n if ('cone' in target) return target;\n return {\n cone: () => target,\n switchCone: async () => {\n throw new Error('this conversation has no cone to rewind');\n },\n };\n}\n\ninterface Turn {\n text: string;\n attachments: ShownAttachment[];\n at: EntryId | null;\n files: boolean;\n}\n\ntype Block = { type?: string; name?: string };\n\nconst WRITERS = ['write', 'edit', 'bash', 'codemode'];\n\nfunction writesIn(entries: readonly EntryRecord[]): boolean {\n return entries.some((entry) =>\n (entry.model ?? []).some(\n (message) =>\n Array.isArray(message.content) &&\n (message.content as Block[]).some(\n (block) => block.type === 'toolCall' && WRITERS.includes(String(block.name))\n )\n )\n );\n}\n\nfunction lastTurn(view: ConversationView, messageId: string | null): Turn | null {\n const { entries } = view;\n const target = entries.findIndex((entry) => `e${entry.id}` === messageId);\n if (target < 0) return null;\n const turn = entries.slice(0, target).findLastIndex((entry) => entry.kind === 'pi.user');\n if (turn < 0) return null;\n const user = entries[turn] as EntryRecord;\n return {\n ...splitUser(user.model?.[0]?.content),\n at: entries[turn - 1]?.id ?? null,\n files: writesIn(entries.slice(turn)),\n };\n}\n\nfunction busy(view: ConversationView): boolean {\n const live = view.docs['pi.live'] as { run?: unknown } | undefined;\n const inbox = view.docs['pi.inbox'] as { items?: unknown[] } | undefined;\n return Boolean(live?.run) || Boolean(inbox?.items?.length);\n}\n\ntype RewindDeps = {\n harness: Harness;\n agents?: Agents;\n cone: Cones;\n scoops?: HostScoops;\n};\n\nasync function turnIn(\n harness: Harness,\n conversation: Conversation,\n messageId: string | null,\n context: Context\n): Promise<{ turn: Turn; view: ConversationView } | Rewound> {\n const attached = await conversation.viewState(context);\n const view = attached.value;\n attached.dispose();\n const pending = (await harness.inspect(context)).submissions.some(\n (submission) => submission.conversationId === conversation.id\n );\n if (pending || busy(view)) return { done: false, text: null, reason: 'busy' };\n const turn = lastTurn(view, messageId);\n return turn ? { turn, view } : { done: false, text: null, reason: 'no-turn' };\n}\n\nasync function forkAt(\n harness: Harness,\n conversation: Conversation,\n found: { turn: Turn },\n context: Context\n): Promise<Conversation> {\n const ownership = { kind: 'ownerless' } as const;\n if (found.turn.at !== null) return conversation.fork(found.turn.at, { ownership }, context);\n const init = copyAgent(await storedAgent(harness, conversation.id, context));\n return harness.createConversation({ ownership, init }, context);\n}\n\nasync function rewindAgent(\n deps: RewindDeps,\n agentId: string | null,\n messageId: string | null,\n context: Context\n): Promise<Rewound> {\n const { harness, agents, cone, scoops } = deps;\n const scoop = agentId && agents ? agents.state().scoops[agentId] : undefined;\n if (agentId && agents && !scoop && agentId !== agents.activeCone())\n await agents.selectCone(agentId, context);\n const conversation =\n scoop && agents\n ? ((await agents.conversation(agentId as string, context)) as Conversation)\n : cone.cone();\n const found = await turnIn(harness, conversation, messageId, context);\n if ('reason' in found) return found;\n const fork = await forkAt(harness, conversation, found, context);\n const changed =\n scoops && agents && !scoop\n ? await scoops.scoops.rewound(agents.activeCone(), fork, context)\n : { stopped: [], restored: [] };\n const files = found.turn.files;\n await fork.submit(\n { type: 'write', entry: { kind: 'slicc.rewound', data: { turns: 1, ...changed, files } } },\n context\n );\n if (scoop && agents)\n await agents.update((_tx, state) => {\n const record = state.scoops[agentId as string] as ScoopRecord;\n record.conversation = fork.id;\n delete record.title;\n delete record.titled;\n }, context);\n else await cone.switchCone(fork, context);\n const { attachments } = found.turn;\n return {\n done: true,\n text: found.turn.text,\n reason: null,\n ...(attachments.length ? { attachments } : {}),\n };\n}\n\ntype Picture = { type?: string; data?: string; mimeType?: string };\n\nasync function storedImage(\n harness: Harness,\n ref: ImageRef,\n context: Context\n): Promise<StoredImage> {\n const entry = await harness.commit((tx) => tx.entry(ref.entry as EntryId), context);\n const content = entry?.model?.[ref.message]?.content;\n const part = Array.isArray(content) ? (content[ref.part] as Picture | undefined) : undefined;\n return part?.type === 'image' && part.data && part.mimeType\n ? { data: part.data, mimeType: part.mimeType }\n : { data: null, mimeType: null };\n}\n\nasync function contentOf(\n text: string,\n request: SendRequest,\n conversation: Conversation,\n uploads: Uploads | undefined,\n context: Context\n): Promise<UserInput> {\n if (!request.attachments?.length) return scrubText(text);\n const saver = await saverFor(conversation, uploads, context);\n return scrubItems(await userParts(text, request.attachments, saver));\n}\n\nexport function createAgentControl(\n harness: Harness,\n target: Conversation | Cones,\n deliveries?: Deliveries,\n licks?: HostLicks,\n scoops?: HostScoops,\n skills?: Pick<SkillsRuntime, 'expand' | 'commandsFor'>,\n sprinkles?: Pick<SprinklesRuntime, 'send' | 'call'>,\n memory?: Pick<MemoryRuntime, 'save' | 'remove'>,\n freezer?: Pick<FreezerRuntime, 'freeze' | 'newChat' | 'thaw' | 'discard'>,\n changes?: Pick<ChangesRuntime, 'open' | 'accept' | 'revert'>,\n monitor?: Pick<Monitor, 'open' | 'close'>,\n secrets?: () => readonly SecretName[],\n uploads?: Uploads,\n labels?: Pick<LabelsRuntime, 'label'>,\n guests?: Pick<Guests, 'open' | 'revoke' | 'forgetAlways'>\n): Omit<AgentControl, 'approvalPolicySet'> {\n const cone = cones(target);\n const current = () => cone.cone();\n const agents = (target as WithAgents).agents;\n const conversationFor = async (agentId: string | null | undefined, context: Context) => {\n if (!agentId || !agents) return current();\n const found = await agents.conversation(agentId, context);\n if (!found) throw new Error(`There is no agent ${agentId}.`);\n return found;\n };\n const withdraw = async (conversation: Conversation, id: string, context: Context) => {\n const parsed = submissionId(id);\n if (parsed === undefined) return { outcome: 'not_found' as const };\n const result = await harness.abortSubmission(parsed, context, conversation.id);\n if (result === 'aborted') return { outcome: 'withdrawn' as const };\n return {\n outcome: result === 'not_found' ? ('not_found' as const) : ('already_placed' as const),\n };\n };\n let lock: Promise<unknown> = Promise.resolve();\n const serial = <T>(operation: () => Promise<T>): Promise<T> => {\n const run = lock.then(operation, operation);\n lock = run.catch(() => undefined);\n return run;\n };\n const rewindIn = (agentId: string | null, messageId: string | null, context: Context) =>\n serial(() => rewindAgent({ harness, agents, cone, scoops }, agentId, messageId, context));\n const decide = (\n agentId: string | null,\n lickId: string,\n state: 'confirmed' | 'dismissed',\n context: Context\n ): Promise<LickResolved> =>\n serial(async () => {\n if (!licks) return { done: false, text: null, error: 'this agent has no licks' };\n const action = state === 'confirmed' ? 'confirm' : 'dismiss';\n try {\n const conversation = await conversationFor(agentId, context);\n const text = await licks.licks.decide(conversation, lickId, action, undefined, context);\n await conversation.submit(\n {\n type: 'write',\n entry: {\n kind: LICK_STATE_KIND,\n data: { lick: lickId, state, by: 'user' },\n model: [\n {\n role: 'user',\n content: `The user ${state} lick ${lickId}: ${text}`,\n timestamp: Date.now(),\n },\n ],\n },\n },\n context\n );\n return { done: true, text, error: null };\n } catch (error) {\n return { done: false, text: null, error: (error as Error).message };\n }\n });\n return {\n send(request, context) {\n return serial(async () => {\n if (secrets && request.text.trim() === SECRETS_COMMAND)\n return accepted(async () =>\n (await conversationFor(request.agentId, context)).submit(\n { type: 'write', entry: secretsEntry(secrets()) },\n context\n )\n );\n const response = await accepted(async () => {\n const conversation = await conversationFor(request.agentId, context);\n const expanded = skills\n ? await skills.expand(request.text, context, conversation.id)\n : request.text;\n return conversation.submit(\n {\n type: 'input',\n content: await contentOf(expanded, request, conversation, uploads, context),\n whenBusy: request.whenBusy,\n ...(request.requestId ? { requestId: request.requestId } : {}),\n },\n context\n );\n });\n const id = response.submissionId === null ? undefined : submissionId(response.submissionId);\n if (id !== undefined) deliveries?.expect(id, request.whenBusy);\n return response;\n });\n },\n rewind: (messageId, context) => rewindIn(null, messageId, context),\n rewindAgent: (agentId, messageId, context) => rewindIn(agentId, messageId, context),\n\n async wait(id, context) {\n const parsed = submissionId(id);\n const submission =\n parsed === undefined ? undefined : await harness.submission(parsed, context);\n if (!submission) throw new Error(`unknown submission ${id}`);\n const settled = await submission.wait(context);\n const { answer, reason } = settled as { answer?: EntryId; reason?: string };\n if (answer === undefined) return { status: 'unanswered', text: null, reason: String(reason) };\n const entry = await harness.commit((tx) => tx.entry(AssistantEntry, answer), context);\n return { status: 'done', text: answerText(entry?.model?.[0]?.content), reason: null };\n },\n withdraw: (id, context) => withdraw(current(), id, context),\n ...sprinkleControl(sprinkles),\n ...memoryControl(memory),\n ...freezerControl(freezer),\n ...changesControl(changes),\n ...guestControl(guests),\n ...monitorControl(monitor),\n image: (ref, context) => storedImage(harness, ref, context),\n async unqueue(agentId, id, context) {\n return withdraw(await conversationFor(agentId, context), id, context);\n },\n abort: (context) => current().abort(context),\n compact: (instructions, context) =>\n accepted(() => current().compact(instructions ?? undefined, context)),\n compactAgent: (agentId, instructions, context) =>\n accepted(async () =>\n (await conversationFor(agentId, context)).compact(instructions ?? undefined, context)\n ),\n reset: (handoff, context) => current().reset(handoff ?? undefined, context),\n resolveLick: (lickId, state, context) => decide(null, lickId, state, context),\n resolveAgentLick: (agentId, lickId, state, context) => decide(agentId, lickId, state, context),\n async webhook(name, delivery, context) {\n const delivered = licks\n ? await licks.sources.webhook(\n name,\n {\n ...(delivery.id ? { id: delivery.id } : {}),\n headers: delivery.headers,\n body: delivery.body,\n },\n context\n )\n : false;\n return { delivered };\n },\n async stopAgent(agentId, context) {\n await (await conversationFor(agentId, context)).abort(context);\n },\n async selectCone(agentId, context) {\n await agents?.selectCone(agentId, context);\n },\n createCone(name, context) {\n return created(async () => {\n if (!agents) throw new Error('This agent has a single cone.');\n return agents.createCone(name, context);\n });\n },\n createScoop(parentId, name, context) {\n return created(async () => {\n if (!scoops) throw new Error('This agent has no scoops.');\n const roles = await scoops.runtime.roles(context);\n const answer = await scoops.scoops.spawn(\n { cone: parentId, name, prompts: [], fromAgent: false, limits: roles.limits },\n context\n );\n if (answer.code !== 0) throw new Error(readable(answer.out));\n return `scoop:${answer.out.trim()}`;\n });\n },\n drop(agentId, context) {\n return created(async () => {\n if (!scoops) throw new Error('This agent has no scoops.');\n const answer = await scoops.scoops.stop(agentId, false, context);\n if (answer.code !== 0) throw new Error(readable(answer.out));\n return agentId;\n });\n },\n configure: async (change, context) =>\n (await conversationFor(change.agentId, context)).configure(\n {\n ...(change.model ? { model: change.model } : {}),\n ...(change.thinkingLevel ? { thinkingLevel: change.thinkingLevel } : {}),\n },\n context\n ),\n agentCommands: async (agentId) => skills?.commandsFor(agentId) ?? [],\n toolLabel: async (agentId, callIds, context) =>\n labels ? labels.label(agentId, callIds, context) : null,\n decide: noApprovals,\n };\n}\n"],
|
|
5
|
+
"mappings": "AACA;AAAA,EACE;AAAA,EAEA;AAAA,OAOK;AACP,SAAS,kBAAkB;AAE3B,SAA+B,WAAW,iBAAiB;AAO3D,SAAS,uBAAuB;AAIhC,SAAS,iBAAiB,oBAAoB;AAE9C,SAAS,YAAY,iBAAiB;AACtC,SAAS,WAAW,mBAAmB;AAevC,SAAS,gBAA8B;AAchC,SAAS,SAAS,KAAqB;AAC5C,QAAM,OAAO,IAAI,QAAQ,oBAAoB,EAAE,EAAE,KAAK;AACtD,QAAM,WAAW,KAAK,OAAO,CAAC,EAAE,YAAY,IAAI,KAAK,MAAM,CAAC;AAC5D,SAAO,SAAS,KAAK,QAAQ,IAAI,WAAW,GAAG,QAAQ;AACzD;AAEA,SAAS,QAAQ,KAA8C;AAC7D,SAAO,IAAI,EAAE;AAAA,IACX,CAAC,QAAQ,EAAE,IAAI,OAAO,KAAK;AAAA,IAC3B,CAAC,WAAkB,EAAE,IAAI,MAAM,OAAO,MAAM,QAAQ;AAAA,EACtD;AACF;AAEA,SAAS,eACP,SACoD;AACpD,SAAO;AAAA,IACL,aAAa,OAAO,OAAO,QAAQ,YACjC,UAAU,QAAQ,KAAK,OAAO,QAAQ,OAAO,IAAI,EAAE,OAAO,IAAI,OAAO,EAAE;AAAA,IACzE,cAAc,OAAO,OAAO,YAAY,SAAS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aACvB,MAAM,gBAAgB,OAAO,SAAS,OAAO,GAAG;AAAA,MAC/C;AAAA,QACE,GAAI,OAAO,QAAQ,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;AAAA,QAC9C,GAAI,OAAO,gBAAgB,EAAE,eAAe,OAAO,cAAc,IAAI,CAAC;AAAA,MACxE;AAAA,MACA;AAAA,IACF;AAAA,IACF,eAAe,OAAO,YAAY,QAAQ,YAAY,OAAO,KAAK,CAAC;AAAA,IACnE,WAAW,OAAO,SAAS,SAAS,YAClC,SAAS,OAAO,MAAM,SAAS,SAAS,OAAO,IAAI;AAAA,IACrD,QAAQ;AAAA,EACV;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/guests/guard.js
CHANGED
|
@@ -1,38 +1,183 @@
|
|
|
1
|
+
import { awaitWithContext, BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
1
2
|
import {
|
|
2
3
|
defineExtension,
|
|
3
4
|
hook,
|
|
4
5
|
LiveDoc,
|
|
5
6
|
ToolTask
|
|
6
7
|
} from "@earendil-works/pi-durable";
|
|
8
|
+
import { REASONS } from "../approvals/record.js";
|
|
9
|
+
import { gateKind, gateRefusal } from "./policy.js";
|
|
10
|
+
import { GuestsDoc, isGate, liveSeat } from "./seats.js";
|
|
7
11
|
const GUEST_GUARD = "slicc-guest-guard";
|
|
8
12
|
const GUEST_REQUEST = "guest:";
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
13
|
+
const GUEST_TOOL_MEMO = "slicc.guest-tool";
|
|
14
|
+
const SUMMARY_LENGTH = 2e3;
|
|
15
|
+
const GATE_REASONS = {
|
|
16
|
+
unknown: "A guest started this run, and its seat names no review for tool calls that this agent knows.",
|
|
17
|
+
ended: "A guest started this run, and that guest's seat has ended.",
|
|
18
|
+
rejected: "The owner declined this tool call in a run a guest started.",
|
|
19
|
+
judged: "The automatic check declined this tool call in a run a guest started",
|
|
20
|
+
unanswered: "Nobody approved this tool call in a run a guest started in time.",
|
|
21
|
+
unroutable: "The cone can't review a tool call it is itself waiting on.",
|
|
22
|
+
scoop: "No scoop can review a guest's tool call yet, so this one is denied.",
|
|
23
|
+
withdrawn: "The review of this tool call was withdrawn."
|
|
24
|
+
};
|
|
25
|
+
function canonical(value) {
|
|
26
|
+
if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
|
|
27
|
+
if (value && typeof value === "object")
|
|
28
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
|
|
29
|
+
return JSON.stringify(value ?? null);
|
|
30
|
+
}
|
|
31
|
+
function summaryOf(args) {
|
|
32
|
+
const values = Object.values(args);
|
|
33
|
+
const text = values.length === 1 && typeof values[0] === "string" ? values[0] : canonical(args);
|
|
34
|
+
return text.length > SUMMARY_LENGTH ? `${text.slice(0, SUMMARY_LENGTH - 1)}\u2026` : text;
|
|
35
|
+
}
|
|
36
|
+
function reasonOf(item) {
|
|
37
|
+
if (item.state === "rejected" && item.decidedBy === "judge")
|
|
38
|
+
return item.verdict ? `${GATE_REASONS.judged}: ${item.verdict.reason}` : `${GATE_REASONS.judged}.`;
|
|
39
|
+
if (item.state === "rejected")
|
|
40
|
+
return item.reason && item.reason !== REASONS.unknownAnswer ? `${GATE_REASONS.rejected} ${item.reason}` : GATE_REASONS.rejected;
|
|
41
|
+
if (item.state === "withdrawn") return GATE_REASONS.withdrawn;
|
|
42
|
+
if (item.reason === REASONS.unknownTier) return GATE_REASONS.unknown;
|
|
43
|
+
if (item.reason === REASONS.unroutable) return GATE_REASONS.unroutable;
|
|
44
|
+
return GATE_REASONS.unanswered;
|
|
45
|
+
}
|
|
46
|
+
async function taintsOf(inputs, seats, harness, context) {
|
|
47
|
+
const found = /* @__PURE__ */ new Map();
|
|
48
|
+
for (const id of inputs) {
|
|
49
|
+
const seat = Object.values(seats).find(
|
|
50
|
+
(record2) => record2.submissions?.some((entry) => entry.id === String(id))
|
|
51
|
+
);
|
|
52
|
+
const tier = seat?.submissions?.find((entry) => entry.id === String(id))?.tools;
|
|
53
|
+
if (seat) {
|
|
54
|
+
found.set(`${seat.id}
|
|
55
|
+
${tier}`, { seat, tier: String(tier) });
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const submission = await harness.submission(id, context);
|
|
59
|
+
const record = submission ? await submission.status(context) : void 0;
|
|
60
|
+
if (record?.requestId?.startsWith(GUEST_REQUEST)) return [{ seat: null, tier: "" }];
|
|
61
|
+
}
|
|
62
|
+
return [...found.values()];
|
|
63
|
+
}
|
|
64
|
+
function settledEarly(seat, tier, policy, at, tool, args) {
|
|
65
|
+
if (!policy.allowedToolGates.includes(gateKind(tier)))
|
|
66
|
+
return gateRefusal("a guest's tool calls", policy.allowedToolGates);
|
|
67
|
+
if (!liveSeat(seat, at)) return GATE_REASONS.ended;
|
|
68
|
+
if (tier === "off") return "";
|
|
69
|
+
if (gateKind(tier) === "scoop") return GATE_REASONS.scoop;
|
|
70
|
+
const kept = seat.alwaysTools?.some((rule) => rule.tool === tool && rule.arguments === args);
|
|
71
|
+
return policy.always.tools && kept ? "" : null;
|
|
72
|
+
}
|
|
73
|
+
const ended = (status) => status === "terminal" || status === "completing";
|
|
74
|
+
function guestToolGate(harness) {
|
|
75
|
+
let resolveHost = () => {
|
|
76
|
+
};
|
|
77
|
+
const bound = new Promise((resolve) => {
|
|
78
|
+
resolveHost = resolve;
|
|
30
79
|
});
|
|
80
|
+
const watched = /* @__PURE__ */ new Set();
|
|
81
|
+
const watch = (host, id, task) => {
|
|
82
|
+
const held = harness();
|
|
83
|
+
if (!held || watched.has(id)) return;
|
|
84
|
+
watched.add(id);
|
|
85
|
+
void held.waitForTask(task, BACKGROUND_CONTEXT).then(
|
|
86
|
+
(record) => ended(record.state.status) ? host.approvals.withdraw(id, REASONS.aborted, BACKGROUND_CONTEXT) : void 0
|
|
87
|
+
).catch(() => void 0).finally(() => watched.delete(id));
|
|
88
|
+
};
|
|
89
|
+
const remember = (seat, rule) => harness().commit(async (tx) => {
|
|
90
|
+
const record = (await tx.doc(GuestsDoc)).seats[seat];
|
|
91
|
+
if (!record || record.revoked !== null) return;
|
|
92
|
+
const kept = (record.alwaysTools ?? []).filter(
|
|
93
|
+
(entry) => entry.tool !== rule.tool || entry.arguments !== rule.arguments
|
|
94
|
+
);
|
|
95
|
+
record.alwaysTools = [...kept, rule];
|
|
96
|
+
}, BACKGROUND_CONTEXT);
|
|
97
|
+
const review = async (taint, call, api, context) => {
|
|
98
|
+
const { seat } = taint;
|
|
99
|
+
if (seat === null || !isGate(taint.tier)) return GATE_REASONS.unknown;
|
|
100
|
+
const host = await awaitWithContext(bound, context);
|
|
101
|
+
const policy = host.policy();
|
|
102
|
+
const now = host.now ?? Date.now;
|
|
103
|
+
const args = canonical(call.arguments);
|
|
104
|
+
const always = policy.always.tools;
|
|
105
|
+
const early = settledEarly(seat, taint.tier, policy, now(), call.name, args);
|
|
106
|
+
if (early !== null) return early || void 0;
|
|
107
|
+
const id = await api.memo(
|
|
108
|
+
`${GUEST_TOOL_MEMO}:${seat.id}:${taint.tier}`,
|
|
109
|
+
`apr-${crypto.randomUUID()}`,
|
|
110
|
+
context
|
|
111
|
+
);
|
|
112
|
+
const task = Number(api.taskId);
|
|
113
|
+
const asked = await host.approvals.request(
|
|
114
|
+
{
|
|
115
|
+
id,
|
|
116
|
+
kind: "guest-tool",
|
|
117
|
+
seat: seat.id,
|
|
118
|
+
agentId: seat.agentId,
|
|
119
|
+
requester: { kind: "guest", name: seat.label, seat: seat.id },
|
|
120
|
+
tier: taint.tier,
|
|
121
|
+
detail: { tool: call.name, summary: summaryOf(call.arguments), arguments: args, task }
|
|
122
|
+
},
|
|
123
|
+
BACKGROUND_CONTEXT
|
|
124
|
+
);
|
|
125
|
+
watch(host, id, task);
|
|
126
|
+
const live = async () => liveSeat((await api.snapshot(GuestsDoc, context))?.seats[seat.id], now());
|
|
127
|
+
if (!await live()) {
|
|
128
|
+
await host.approvals.withdraw(id, REASONS.revoked, BACKGROUND_CONTEXT);
|
|
129
|
+
return GATE_REASONS.ended;
|
|
130
|
+
}
|
|
131
|
+
const item = asked.state === "pending" ? await host.approvals.settled(id, context) : asked;
|
|
132
|
+
if (item.state !== "approved") return reasonOf(item);
|
|
133
|
+
if (!await live()) return GATE_REASONS.ended;
|
|
134
|
+
if (item.answer === "always" && always)
|
|
135
|
+
await remember(seat.id, {
|
|
136
|
+
approval: item.id,
|
|
137
|
+
tool: call.name,
|
|
138
|
+
arguments: args,
|
|
139
|
+
by: item.decidedBy,
|
|
140
|
+
at: item.decidedAt ?? now()
|
|
141
|
+
});
|
|
142
|
+
return void 0;
|
|
143
|
+
};
|
|
144
|
+
return {
|
|
145
|
+
extension: defineExtension({
|
|
146
|
+
name: GUEST_GUARD,
|
|
147
|
+
hooks: [
|
|
148
|
+
hook(ToolTask, {
|
|
149
|
+
async beforeTool(call, api, context) {
|
|
150
|
+
const live = await api.snapshot(LiveDoc, api.conversationId, context);
|
|
151
|
+
const inputs = live?.run?.inputs ?? [];
|
|
152
|
+
if (!inputs.length) return void 0;
|
|
153
|
+
const seats = (await api.snapshot(GuestsDoc, context))?.seats ?? {};
|
|
154
|
+
const held = harness();
|
|
155
|
+
for (const taint of await taintsOf(inputs, seats, held, context)) {
|
|
156
|
+
const block = await review(taint, call, api, context);
|
|
157
|
+
if (block) return { block };
|
|
158
|
+
}
|
|
159
|
+
return void 0;
|
|
160
|
+
}
|
|
161
|
+
})
|
|
162
|
+
]
|
|
163
|
+
}),
|
|
164
|
+
bind(host) {
|
|
165
|
+
resolveHost(host);
|
|
166
|
+
for (const item of host.approvals.state.value ?? [])
|
|
167
|
+
if (item.kind === "guest-tool" && item.state === "pending" && item.detail.task)
|
|
168
|
+
watch(host, item.id, item.detail.task);
|
|
169
|
+
}
|
|
170
|
+
};
|
|
31
171
|
}
|
|
32
172
|
export {
|
|
173
|
+
GATE_REASONS,
|
|
33
174
|
GUEST_GUARD,
|
|
34
175
|
GUEST_REQUEST,
|
|
35
|
-
|
|
36
|
-
|
|
176
|
+
GUEST_TOOL_MEMO,
|
|
177
|
+
SUMMARY_LENGTH,
|
|
178
|
+
canonical,
|
|
179
|
+
guestToolGate,
|
|
180
|
+
reasonOf,
|
|
181
|
+
summaryOf
|
|
37
182
|
};
|
|
38
183
|
//# sourceMappingURL=guard.js.map
|