@ai-ecoverse/slicc-agent 7.25.1 → 7.27.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 +9 -6
- package/dist/approvals/index.js +5 -4
- package/dist/approvals/index.js.map +2 -2
- package/dist/approvals/people.js +5 -0
- package/dist/approvals/people.js.map +7 -0
- package/dist/approvals/record.js +5 -2
- package/dist/approvals/record.js.map +2 -2
- package/dist/approvals/sudo-client.js +11 -4
- package/dist/approvals/sudo-client.js.map +2 -2
- package/dist/approvals/sudo.js +13 -5
- package/dist/approvals/sudo.js.map +2 -2
- package/dist/attachments.js +92 -43
- package/dist/attachments.js.map +2 -2
- package/dist/index.js.map +2 -2
- package/dist/main.js +27 -7
- package/dist/main.js.map +2 -2
- package/dist/page.js.map +2 -2
- package/dist/spectrum/agent-port.js +36 -7
- package/dist/spectrum/agent-port.js.map +2 -2
- package/dist/spectrum/outgoing.js +85 -24
- package/dist/spectrum/outgoing.js.map +2 -2
- package/dist/staging.js +42 -0
- package/dist/staging.js.map +7 -0
- package/dist/types/approvals/people.d.ts +2 -0
- package/dist/types/approvals/record.d.ts +5 -3
- package/dist/types/approvals/sudo-client.d.ts +1 -1
- package/dist/types/approvals/sudo.d.ts +9 -1
- package/dist/types/attachments.d.ts +13 -3
- package/dist/types/index.d.ts +1 -1
- package/dist/types/main.d.ts +1 -0
- package/dist/types/page.d.ts +1 -1
- package/dist/types/spectrum/agent-port.d.ts +2 -0
- package/dist/types/spectrum/outgoing.d.ts +12 -3
- package/dist/types/staging.d.ts +13 -0
- package/dist/types/uploads.d.ts +2 -0
- package/dist/uploads.js +3 -1
- package/dist/uploads.js.map +2 -2
- package/package.json +4 -4
package/README.md
CHANGED
|
@@ -85,7 +85,7 @@ const owner = await startAgent({
|
|
|
85
85
|
});
|
|
86
86
|
```
|
|
87
87
|
|
|
88
|
-
At boot, the worker sets `/.slicc`, where the session database lives in OPFS, to `0700`, so that only root can read it through the kernel.
|
|
88
|
+
At boot, the worker sets `/.slicc`, where the session database lives in OPFS, to `0700`, so that only root can read it through the kernel, and makes `/.slicc/attachments/<serverId>` for the attachments pages stage (see Attachments).
|
|
89
89
|
|
|
90
90
|
With users, each cone and each scoop is a kernel user, and works as that user:
|
|
91
91
|
- **Users and groups:**
|
|
@@ -196,14 +196,15 @@ Each tool call shows its input in the way that suits it:
|
|
|
196
196
|
|
|
197
197
|
#### Attachments
|
|
198
198
|
|
|
199
|
-
A send's `Outgoing.attachments` reach the model. In the page, `send()` reads each attachment's `url` (a `data:` or `blob:` URL)
|
|
199
|
+
A send's `Outgoing.attachments` reach the model. In the page, `send()` reads each attachment's `url` (a `data:` or `blob:` URL) before anything else, so a `blob:` URL spectrum revokes later has already been read, and passes them on `SendRequest.attachments` as `{ name, mimeType, kind, data?, text?, path?, upload? }`. What fits one link frame travels inline: `data` (base64, because chord carries JSON only) or `text`, up to 8 MiB each and 10 MiB together. Anything bigger, or past that budget, is streamed into the agent's own OPFS, into `/.slicc/attachments/<serverId>/<uuid>`, and travels as `upload: <uuid>`; the worker deletes each one as soon as it has read it, whether the send is accepted or refused, the page removes what is left once `send` answers, the worker sweeps files older than an hour (`AgentWorkerOptions.stagedMs`, checked on that interval and at every send with attachments), and it empties `/.slicc/attachments` at boot and makes the folder of its own `serverId` (the id a connection's link hello carries, `AgentConnection.serverId`), so a page finds the folder only when it shares OPFS with that very worker. A text past the budget goes as a file, or, when it has a `path` (an @-mention), by its path only. It skips attachments with an `error` and secrets. In the worker, `control.send` turns them into the user message:
|
|
200
200
|
- an image (`image/png`, `jpeg`, `gif` or `webp`) becomes a pi-ai `ImageContent` part after a short `<attachment kind="image" …>` text part that names it;
|
|
201
201
|
- a text file is inlined as `<attachment kind="text" name="…" type="…">` with its text, and with its `path` when it is an @-mention;
|
|
202
|
-
- any other file is written with the conversation's own environment, so the user's own client in users mode, into `uploads/` under the conversation's `cwd` (`/home` by default), and the text says `Saved at <path>.` A free name gets `-1`, `-2` and so on;
|
|
202
|
+
- any other file, and every `upload` (which the worker reads straight from OPFS, since `/.slicc` is root's alone), is written with the conversation's own environment, so the user's own client in users mode, into `uploads/` under the conversation's `cwd` (`/home` by default), and the text says `Saved at <path>.` A free name gets `-1`, `-2` and so on;
|
|
203
|
+
- an image over 5 MiB, or one that came as an `upload`, is saved the same way, and the text adds "The image was too large to show the model, so it was saved as a file instead.";
|
|
203
204
|
- for a model whose `input` lacks `image`, an image is saved the same way and the text adds "This model can't see images, so the image was saved as a file instead." (pi-ai alone would put `(image omitted: model does not support images)` in its place, and the image would be lost to the tools.)
|
|
204
205
|
- an attachment with only a `path` is mentioned by its path.
|
|
205
206
|
|
|
206
|
-
|
|
207
|
+
**Limits.** The spectrum adapter's `attachmentLimits()` tells the composer what it takes, so the composer disables Send for an attachment that is too large instead of posting a message that is then dropped: where the page reaches the worker's staging folder, `{ image, text, file }` are 100 MiB each and `total` 256 MiB; elsewhere (a follower on another device), 8 MiB each and 10 MiB together, what fits one 16 MiB link frame as base64. It knows which once `ready()` resolves. The page first shrinks an image over 5 MiB (providers refuse bigger ones) to 1600 px, as image reads do, and the model gets as images only those that fit 5 MiB each within the 10 MiB inline budget; the rest are saved as files. Anything that still doesn't fit isn't sent, and a notice says why, for example "big.pdf is larger than 8 MiB, so it can't be sent.". The worker holds an inline `data` or `text` to 8 MiB, inline attachments to 10 MiB together, an `upload` to 100 MiB, and a message's attachments, inline and uploaded, to 256 MiB together; an `upload` it can't find (a `uuid` from another worker, or none at all) is refused. It checks every attachment of a message before it saves any, so a refused message leaves nothing in `uploads/`. When the page refuses an attachment, `send()` shows the notice and rejects with the same sentence. A saved file's name loses `/`, `\`, `<`, `>`, `"` and control characters, and every name and path in the attachment text is escaped, so no name can end the `<attachment>` element. Text and inlined files go through the vault's scrubbing like any send; images can't be scrubbed as text. The replicated transcript and views don't carry the full images: the host swaps every image part over 48 KB, in entries and in the inbox, for a JPEG thumbnail of at most 256 px and 48 KB (made once per image in the worker with `OffscreenCanvas`) plus `full: { mimeType, size }`, so a conversation with many images still attaches in one 16 MiB frame. The model still gets the full image from storage. The transcript maps the parts back to spectrum's user message `attachments`, with the thumbnail as `url` and the id `ref:<entry>:<message>:<part>`. When such an attachment is sent again, by Retry or from the composer after a rewind, the adapter fetches the full image with `AgentControl.image({ entry, message, part })`. A remote `prompt()` takes the same `attachments`.
|
|
207
208
|
|
|
208
209
|
### Licks
|
|
209
210
|
|
|
@@ -740,7 +741,7 @@ It prints the tab's stdout and stderr on their own streams and exits with its co
|
|
|
740
741
|
|
|
741
742
|
Every approval, of a guest's prompt, of a tool call in a run a guest started, of a sudo request, or of a media capture from a run a guest started, is an item in one session document, `slicc.approvals` ([`src/approvals/`](src/approvals/)). That document is the authority: not a lick, which the agent can confirm itself, and not a UI projection, so a settled item stays settled after a reload.
|
|
742
743
|
|
|
743
|
-
- **An item** is `{ id, kind, seat?, agentId, requester, detail, tier, state, decidedBy, device?, answer?, reason?, verdict?, judging?, verdictError?, always, createdAt, expiresAt, decidedAt? }`. `kind` is `guest-message` (`detail: { text, attachments }`), `guest-tool` (`{ tool, summary, arguments?, task? }`) `sudo` (`{ command, target?, cwd?, alwaysScope?, stdin?, rootOnly?, writable? }`) or `capture` (`{ what, mode, seconds?, system?, microphone?, device?, program }`, see Media capture). `judging` is `true` while the judge runs; `verdictError` says why there is no verdict. `requester` is `{ kind: 'guest' | 'agent' | 'user', name, seat?, agentId?, where?, device? }`.
|
|
744
|
+
- **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? }`.
|
|
744
745
|
- **`state`** is `pending`, `approved` (with `answer` `once` or `always`), `rejected` (someone said no), `unanswered` (nobody decided: it timed out or couldn't be routed) or `withdrawn` (the requester went away). `reason` is a field, never a state: a person's own words, or `timeout`, `unknown-tier`, `unroutable`, `unknown-answer`, `restart`, `revoked`, `aborted` or `disconnected`. `decidedBy` is `owner`, `follower`, `judge` or `host`.
|
|
745
746
|
- **`tier`** says who answers: `user` (a person, through `decide`), `agent` (the automatic judge), `cone` or `scoop:<name>`. A tier the agent doesn't know settles at once as `unanswered` with `unknown-tier`, and so does `cone` for a guest's tool call or capture (`unroutable`), because a run can't approve its own gate. A person answers only `user` items, the judge only `agent` ones.
|
|
746
747
|
- **The rules:** the first decision wins, and a later one, or one past `expiresAt`, is refused ("Someone else already answered this.", "This request timed out.", "This request was withdrawn."). An answer other than `once`, `always` or `deny` is a deny (`unknown-answer`). `always` is `false` for anything a guest triggered unless the approval policy's `guests.always` offers it for that kind (by default it doesn't). A `sudo` or `capture` item starts with `always: false` and gets `true` only from a verdict (see The automatic judge), and `decide(id, 'always')` on an item without it is refused and leaves it pending. For a guest's tool call, Always records an exact rule on the seat (see Guest seats), and for a capture a narrow one (see Media capture).
|
|
@@ -752,6 +753,8 @@ Every approval, of a guest's prompt, of a tool call in a run a guest started, of
|
|
|
752
753
|
- **Requester** comes from the kernel's process tag: `{ kind: 'agent', agentId }` is the cone or scoop by its name, `{ kind: 'user', where }` is the kernel user with `where` (`terminal:…` reads "a terminal", `follower:<device>` the `where` the page passes, such as "on Pat's phone", or "a linked device", with the device id kept as `requester.device`), and anything else is the kernel user alone.
|
|
753
754
|
- **Detail:** the command as the kernel resolved it (`path` and the arguments, shell-quoted), `target`, `cwd`, `alwaysScope: 'cwd'` when `req.always === true`, since the kernel's Always writes a rule for that directory, and the kernel's facts for the judge: `stdin` (`tty`, `none`, `pipe` or `file`), `rootOnly` (for each path on the line, whether only root can change it) and `writable` (`req.always`, whether the kernel can record the line). Requests without them still work; `req.always: false` or `writable: false` means no Always.
|
|
754
755
|
- **Answers:** `approved` resolves its answer, a judge's rejection resolves a `SudoDenial`, `{ answer: 'deny', message: 'sudo: denied by the approval judge: <reason>' }` (the prefix is `JUDGE_DENIED`), so the shell can say who refused, and anything else `deny`. A kernel that doesn't know the object denies it as it denies any answer but `once` and `always`. Every device of the owner answers with the same powers: a follower, with or without Control, sees the same item, Always included when the verdict offers it, and its `always` counts as the owner tab's would. `device` on the item names the device that answered, from `owner.port({ device })`.
|
|
756
|
+
- **Timestamps:** a kernel that keeps sudo timestamps (`Defaults timestamp_timeout`) says so with `req.timestamp: true`. To such a request, an approval decided by a person (`decidedBy` `owner` or `follower`) resolves `SudoTimestamp`, `{ answer: 'once' | 'always', timestamp: true }`, which lets the kernel open or refresh the timestamp, so that shell isn't asked again until it runs out. The judge's and the host's approvals stay plain `once`, and a scoop can't approve sudo at all, so none of them open the window. Denials don't change. A request without `timestamp: true` always gets the plain string, because an older kernel denies any object that isn't a denial.
|
|
757
|
+
- **`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.
|
|
755
758
|
- **Ends:** when the kernel aborts `signal` (`withdrawn`) the item is withdrawn, and on `expired` the page keeps its link until the record's own timeout settles it (`unanswered`), so it never reads as withdrawn. When the page's link closes the worker withdraws its open sudo items (`disconnected`). A restart or release of the owner first ends the old worker, then denies the requests still waiting, so the old worker never sees their links close, and the next worker withdraws their items (`restart`). The kernel already allows one pending request per user.
|
|
756
759
|
- **Scoops:** a scoop's request sends its cone a `sudo-request` lick without actions once a person has to answer it (at once on the `user` tier, after the judge hands it on with the `agent` policy, never when the judge decides), so the cone knows the scoop waits and can't approve it itself. A cone that asks gets none: it waits in its own command.
|
|
757
760
|
- **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.
|
|
@@ -770,7 +773,7 @@ Every approval, of a guest's prompt, of a tool call in a run a guest started, of
|
|
|
770
773
|
|
|
771
774
|
#### The automatic judge
|
|
772
775
|
|
|
773
|
-
The judge ([`src/approvals/judge.ts`](src/approvals/judge.ts)) gives a request a verdict by the owner's intent, never the requester's. It judges only items in `slicc.approvals`, never a `secret` approval, which always goes to a person. `request()` starts it at once for every `sudo` item
|
|
776
|
+
The judge ([`src/approvals/judge.ts`](src/approvals/judge.ts)) gives a request a verdict by the owner's intent, never the requester's. It judges only items in `slicc.approvals`, never a `secret` approval, which always goes to a person. `request()` starts it at once for every `sudo` item but `sudo -v`, whatever its tier, and for every `agent` or `user` item, so a person is asked with the verdict shown. Who answers is the gate: a `sudo` item's tier is the owner's approval policy (`sudo.approver`), not the request's, `user` (a person) by default and for anything but `agent`; a guest item's tier is the seat's gate. On a `user` item the verdict is advice for the person and decides nothing; on an `agent` item the routing table below decides. The dialog never waits: Allow once and Deny work while `judging` is `true`.
|
|
774
777
|
|
|
775
778
|
- **Levels:** the verdict is `level` 1 Routine (normal work that doesn't change who may do what), 2 Permissions (it changes who may do what: sudoers, users and groups, ownership or modes, secret rules, the approvals policy, guest seats, credentials and tokens) or 3 Harm (it would damage the system or the work in a way that is hard to undo); `aligned`, whether it serves what the owner asked for; and for sudo `always`, whether a later run of exactly this line can do no more than this one. No command lists anywhere: every answer is the model's, and code only combines them. `request.sudo: { stdin, writable, rootOnly }` holds only what the requester can't choose (`rootOnly` is whether every path on the line and the directory can be changed only by root), while the command, the target user, the directory and each path's root-only fact (`path "/etc/x": root-only` or `changeable`, one JSON-quoted path per line) are inside the fenced `request.untrusted`, because the requester chose them.
|
|
776
779
|
- **Sudo: narrow questions, matched in code.** A classifier on `approvals.judgeModel` (in the agent's `settings.json`, `/etc/slicc/agent/settings.json` with kernel users, `adobe/clef` by default), on the harness's own `Models`, with one retry and a 15 s timeout (`JUDGE_TIMEOUT`), gets two calls in parallel. The action call (`SUDO_QUESTIONS`, state `{ request }` only) asks eleven bools about the command: `changes` (creates, changes, moves, copies or deletes anything), `others` (in another user's home), `system` (system files), `delete`, `permissions`, `code` (code or output the line doesn't spell out: scripts, package installs, `xargs`, `find -exec` or `-delete`, redirections, command substitution, `sort -o`, `tee`, `curl` or `wget`, `git` with its hooks, pager and aliases, interpreters, editors, pagers), `services`, `send` (off the machine), `secrets` (its output shows a secret, including dumps of the environment, process environments, shell history and config or credentials files), `plain` (a standard tool whose whole effect its options and paths show) and `always` ("Could a later run of exactly this line do something different from this one, because it reads piped or file input, runs a script or a file someone other than root can change, takes code on the line, or is interactive?"). The intent call (`INTENT_QUESTIONS`, state `{ owner }` only: `owner.policy`, the last 10 `owner.messages` and `owner.memory`) asks what the owner wants done now, the latest messages with earlier ones only as context ("A request the owner made earlier for a task that is finished or replaced doesn't count."), in the same words: `wants_read`, `wants_write`, `wants_delete`, `wants_permissions`, `wants_code`, `wants_send`, `wants_secrets`, `wants_services`. It depends only on the owner's words, so the judge keeps its answer per judge model and owner state (the last 16, `INTENTS_KEPT`) and asks again only when the owner said something new or the policy or memory changed; a failed intent call isn't kept. `matchOf` then decides in code, a probability counting at ≥ 0.5 (`JUDGE_CUT`): level 3 when it deletes anything, changes something in another user's home or among system files, or touches processes or services; else 2 when it changes permissions; else 1. Deleting counts as harm wherever it is, because on live `clef` the `system` answer stayed under 0.5 for 24 of 28 `rm` commands outside `/home` in a real cleanup session, most of them on directories at the top of `/`. `routine` is 1 minus the highest danger answer, over all of them (`delete`, `services`, `permissions`, `send`, `secrets`, `code`, `others` and `system`), and never more than P(plain). For a line that changes anything (P(changes) ≥ 0.2), `others` and `system` count from 0.05 (`JUDGE_PLACE`): they enter `routine` scaled by 0.2 / 0.05. So any danger answer of 0.2 or more, or a system or another user answer of 0.05 or more on a write, keeps `routine` at or under 0.8 and the line goes to a person, even when the owner asked for it; on live `clef` every dangerous line in the evals had a danger answer over its bar, none relied on `plain` alone. Every action the command may take (P ≥ 0.2, `JUDGE_LOW`) needs an intent: `changes` needs `write`, `delete` `delete`, `permissions` `permissions`, `code` `code`, `services` `services`, `send` `send`, `secrets` `secrets`, and a line that changes nothing needs `read`. `aligned` is the lowest of the needed intents, so it counts (over 0.8, `JUDGE_ALLOW`) only when the owner asked for everything the line does: showing a secret or sending data out never rides on a read. `always` is safe at P < 0.2 (`JUDGE_ALWAYS`). Exact boundaries never approve: a danger cut counts from its bar minus 1e-9 (`JUDGE_EPSILON`), and `routine`, `aligned` and 1 − P(always) must reach their bar plus 1e-9 (`clears`), so a danger of exactly 0.2, a `plain` or an intent of exactly 0.8 all ask. The verdict keeps every answer as `actions` and `intent`.
|
package/dist/approvals/index.js
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
heldKind,
|
|
14
14
|
knownTier,
|
|
15
15
|
MAX_DELAY,
|
|
16
|
+
personOnly,
|
|
16
17
|
prune,
|
|
17
18
|
REASONS,
|
|
18
19
|
routable,
|
|
@@ -36,13 +37,13 @@ function mark(item, how, at) {
|
|
|
36
37
|
if (how.reason) item.reason = how.reason;
|
|
37
38
|
}
|
|
38
39
|
const offered = (options, draft) => guestKind(draft.kind) && draft.kind !== "capture" ? options.guestAlways?.(draft.kind) === true : false;
|
|
39
|
-
const judgedKind = (
|
|
40
|
+
const judgedKind = (item, tier) => !personOnly(item) && (item.kind === "sudo" || tier === "agent" || tier === "user");
|
|
40
41
|
function detailOf(draft) {
|
|
41
42
|
if (draft.kind !== "sudo" || draft.always !== false) return draft.detail;
|
|
42
43
|
return { ...draft.detail, writable: false };
|
|
43
44
|
}
|
|
44
45
|
function fresh(draft, at, ttl, options) {
|
|
45
|
-
const tier = tierOf(draft
|
|
46
|
+
const tier = tierOf(draft, sudoApprover(options.sudoApprover?.()));
|
|
46
47
|
const item = {
|
|
47
48
|
...draft,
|
|
48
49
|
detail: detailOf(draft),
|
|
@@ -51,7 +52,7 @@ function fresh(draft, at, ttl, options) {
|
|
|
51
52
|
state: "pending",
|
|
52
53
|
decidedBy: null,
|
|
53
54
|
always: offered(options, draft),
|
|
54
|
-
...options.judge && judgedKind(draft
|
|
55
|
+
...options.judge && judgedKind(draft, tier) ? { judging: true } : {},
|
|
55
56
|
createdAt: at,
|
|
56
57
|
expiresAt: draft.expiresAt ?? at + ttl
|
|
57
58
|
};
|
|
@@ -265,7 +266,7 @@ async function attachApprovals(options, context = BACKGROUND_CONTEXT) {
|
|
|
265
266
|
doc.items.push(item);
|
|
266
267
|
return copy([item])[0];
|
|
267
268
|
}, using);
|
|
268
|
-
if (created && options.judge && made.state === "pending" && judgedKind(made
|
|
269
|
+
if (created && options.judge && made.state === "pending" && judgedKind(made, made.tier))
|
|
269
270
|
void judging(options.judge, made, made.tier === "agent" ? using : BACKGROUND_CONTEXT);
|
|
270
271
|
if (created) toScoop(made);
|
|
271
272
|
return made;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/approvals/index.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type Context,\n type ReplicatedState,\n replicatedState,\n type WatchHandle,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Harness } from '@earendil-works/pi-durable';\nimport type { Clock } from '../clock.ts';\nimport { type ApprovalJudge, ASK_MIN_MS, JUDGE_RESTARTED, type Judgement } from './judge.ts';\nimport {\n APPROVAL_MS,\n type Approval,\n type ApprovalDraft,\n type ApprovalKind,\n type ApprovalState,\n ApprovalsDoc,\n type ApprovalsState,\n alwaysOffered,\n cleanReason,\n type DecidedBy,\n gateOf,\n guestKind,\n heldKind,\n knownTier,\n MAX_DELAY,\n prune,\n REASONS,\n type Routed,\n routable,\n route,\n ruled,\n type Settle,\n scoopTier,\n sudoApprover,\n tierOf,\n} from './record.ts';\n\nexport * from './intent.ts';\nexport * from './judge.ts';\nexport * from './present.ts';\nexport * from './record.ts';\n\nexport type ApprovalDecided =\n | { done: true; state: ApprovalState; error: null }\n | { done: false; state: null; error: string };\n\nexport type Decider = DecidedBy | { by: DecidedBy; device?: string };\n\nconst deciderOf = (decider: Decider) => (typeof decider === 'string' ? { by: decider } : decider);\n\nexport interface Approvals {\n readonly state: ReplicatedState<Approval[]>;\n request(draft: ApprovalDraft & { id?: string }, context: Context): Promise<Approval>;\n decide(\n id: string,\n answer: unknown,\n reason: string | null,\n by: Decider,\n context: Context\n ): Promise<ApprovalDecided>;\n settled(id: string, context: Context): Promise<Approval>;\n assign(id: string, reviewer: string, context: Context): Promise<Approval | undefined>;\n withdraw(id: string, reason: string | null, context: Context): Promise<Approval | undefined>;\n withdrawSeat(seat: string, context: Context): Promise<number>;\n expire(id: string, context: Context): Promise<Approval | undefined>;\n close(): void;\n}\n\nexport interface ScoopRouter {\n route(item: Approval): Promise<void>;\n}\n\nexport interface ApprovalsAttach {\n harness: Pick<Harness, 'commit' | 'watchDoc'>;\n now?: () => number;\n setTimer?: Clock['setTimer'];\n ttlMs?: number;\n judge?: ApprovalJudge;\n scoops?: ScoopRouter;\n guestAlways?: (kind: ApprovalKind) => boolean;\n sudoApprover?: () => unknown;\n present?: (item: Approval, context: Context) => Promise<boolean>;\n}\n\nconst copy = (items: readonly Approval[]): Approval[] => JSON.parse(JSON.stringify(items));\n\nfunction mark(item: Approval, how: Settle, at: number) {\n item.state = how.state;\n item.decidedBy = how.by;\n item.decidedAt = at;\n delete item.judging;\n if (how.reason) item.reason = how.reason;\n}\n\nconst offered = (options: ApprovalsAttach, draft: ApprovalDraft): boolean =>\n guestKind(draft.kind) && draft.kind !== 'capture'\n ? options.guestAlways?.(draft.kind) === true\n : false;\n\nconst judgedKind = (kind: ApprovalKind, tier: string) =>\n kind === 'sudo' || tier === 'agent' || tier === 'user';\n\nfunction detailOf(draft: ApprovalDraft): ApprovalDraft['detail'] {\n if (draft.kind !== 'sudo' || draft.always !== false) return draft.detail;\n return { ...draft.detail, writable: false };\n}\n\nfunction fresh(\n draft: ApprovalDraft & { id?: string },\n at: number,\n ttl: number,\n options: ApprovalsAttach\n): Approval {\n const tier = tierOf(draft.kind, draft.tier, sudoApprover(options.sudoApprover?.()));\n const item = {\n ...draft,\n detail: detailOf(draft),\n tier,\n id: draft.id ?? `apr-${crypto.randomUUID()}`,\n state: 'pending',\n decidedBy: null,\n always: offered(options, draft),\n ...(options.judge && judgedKind(draft.kind, tier) ? { judging: true } : {}),\n createdAt: at,\n expiresAt: draft.expiresAt ?? at + ttl,\n } as Approval;\n if (!knownTier(item.tier))\n mark(item, { state: 'unanswered', by: 'host', reason: REASONS.unknownTier }, at);\n else if (!routable(draft.kind, item.tier))\n mark(item, { state: 'unanswered', by: 'host', reason: REASONS.unroutable }, at);\n return item;\n}\n\nconst withdrawIn =\n (match: (item: Approval) => boolean, reason: string | undefined, now: () => number) =>\n (doc: ApprovalsState) => {\n const hit = doc.items.filter((item) => item.state === 'pending' && match(item));\n for (const item of hit)\n mark(item, { state: 'withdrawn', by: 'host', ...(reason ? { reason } : {}) }, now());\n return hit.map((item) => copy([item])[0] as Approval);\n };\n\ntype Judged = { judgement: Judgement; present: boolean; offer?: boolean };\n\nconst routeOf = (item: Approval, { judgement, present }: Judged): Routed =>\n route(judgement.verdict, item.requester, gateOf(item.tier), present);\n\nconst judgedIn = (id: string, judged: Judged, now: () => number) => (doc: ApprovalsState) => {\n const { judgement } = judged;\n const item = doc.items.find((entry) => entry.id === id);\n if (!item) return undefined;\n const late = item.state === 'unanswered' && item.reason === REASONS.timeout && !item.verdict;\n if (item.state !== 'pending' && !(late && judgement.verdict)) return undefined;\n delete item.judging;\n if (judgement.verdict) item.verdict = judgement.verdict;\n else item.verdictError = judgement.error ?? 'the judge gave no verdict';\n if (late) return copy([item])[0] as Approval;\n const routed = routeOf(item, judged);\n if (routed === 'ask') {\n item.tier = 'user';\n if (item.kind === 'sudo') item.always = alwaysOffered(item);\n if (item.kind === 'capture') item.always = alwaysOffered(item) && judged.offer === true;\n return copy([item])[0] as Approval;\n }\n const at = now();\n const ruling = ruled(item, routed === 'approve' ? 'once' : 'deny', null, 'judge', at);\n if (ruling.answer) item.answer = ruling.answer;\n if (ruling.settle) mark(item, ruling.settle, at);\n return copy([item])[0] as Approval;\n};\n\nasync function judgedBy(\n judge: ApprovalJudge,\n present: ApprovalsAttach['present'],\n item: Approval,\n using: Context,\n now: () => number\n): Promise<Judged> {\n const judgement = await judge\n .judge(item, using)\n .catch((error: unknown): Judgement => ({ error: String(error) }));\n if (judgement.verdict?.level !== 3 || !present || item.tier !== 'agent')\n return { judgement, present: false };\n const there = await present(item, using).catch(() => false);\n return { judgement, present: there && item.expiresAt - now() >= ASK_MIN_MS };\n}\n\ntype Serial = <R>(change: (doc: ApprovalsState) => R, using: Context) => Promise<R>;\n\nfunction judgeRunner(run: {\n serial: Serial;\n present: ApprovalsAttach['present'];\n guestAlways: ApprovalsAttach['guestAlways'];\n now: () => number;\n closed: () => boolean;\n}) {\n const { serial, now } = run;\n return async (judge: ApprovalJudge, item: Approval, using: Context) => {\n const signal = using.abortSignal;\n let gone = false;\n const abort = () => {\n gone = true;\n void serial(\n withdrawIn((entry) => entry.id === item.id && entry.tier === 'agent', REASONS.aborted, now),\n BACKGROUND_CONTEXT\n ).catch(() => undefined);\n };\n if (signal?.aborted) return abort();\n signal?.addEventListener('abort', abort, { once: true });\n const found = await judgedBy(judge, run.present, item, using, now);\n signal?.removeEventListener('abort', abort);\n if (gone || run.closed()) return;\n const judged = { ...found, offer: run.guestAlways?.(item.kind) === true };\n const after = await serial(judgedIn(item.id, judged, now), BACKGROUND_CONTEXT).catch(\n () => undefined\n );\n if (!after) return;\n await judge.record?.(after, judged.judgement, BACKGROUND_CONTEXT).catch(() => undefined);\n };\n}\n\nfunction following(\n watch: WatchHandle<Readonly<ApprovalsState>>,\n changed: (using: Context, items: Approval[]) => void\n) {\n const items = () => watch.value.items;\n let shown = items();\n return (using: Context) => {\n const now = items();\n if (now === shown) return;\n shown = now;\n changed(using, copy(now));\n };\n}\n\nfunction settledIn(\n state: ReplicatedState<Approval[]>,\n id: string,\n using: Context\n): Promise<Approval> {\n return new Promise((resolve, reject) => {\n const signal = using.abortSignal;\n let done = false;\n let off: (() => void) | undefined;\n const finish = (end: () => void) => {\n done = true;\n off?.();\n signal?.removeEventListener('abort', abort);\n end();\n };\n const abort = () => finish(() => reject(signal?.reason));\n const check = (items: readonly Approval[] | undefined) => {\n const item = items?.find((entry) => entry.id === id);\n if (!item) finish(() => reject(new Error(`There is no approval ${id}.`)));\n else if (item.state !== 'pending') finish(() => resolve(item));\n };\n if (signal?.aborted) return abort();\n check(state.value);\n if (done) return;\n signal?.addEventListener('abort', abort, { once: true });\n off = state.subscribe((items) => check(items));\n });\n}\n\nconst systemTimer: Clock['setTimer'] = (callback, delayMs) => {\n const timer = setTimeout(callback, delayMs);\n return () => clearTimeout(timer);\n};\n\nexport async function attachApprovals(\n options: ApprovalsAttach,\n context: Context = BACKGROUND_CONTEXT\n): Promise<Approvals> {\n const { harness } = options;\n const now = options.now ?? Date.now;\n const ttl = options.ttlMs ?? APPROVAL_MS;\n const setTimer = options.setTimer ?? systemTimer;\n const timers = new Map<string, () => void>();\n let line: Promise<unknown> = Promise.resolve();\n let closed = false;\n const settle = (item: Approval, how: Settle) => mark(item, how, now());\n const write = <R>(\n change: (doc: ApprovalsState) => R,\n using: Context\n ): Promise<{ result: R; items: Approval[] }> =>\n harness.commit(async (tx) => {\n const doc = await tx.doc(ApprovalsDoc);\n const result = change(doc);\n doc.items = prune(doc.items);\n return { result, items: copy(doc.items) };\n }, using);\n const startup = await write((doc) => {\n for (const item of doc.items) {\n if (item.state !== 'pending') continue;\n if (heldKind(item.kind))\n settle(item, { state: 'withdrawn', by: 'host', reason: REASONS.restart });\n else if (item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n else if (options.judge && item.tier === 'agent') item.tier = 'user';\n if (item.state === 'pending' && item.judging) {\n delete item.judging;\n item.verdictError = JUDGE_RESTARTED;\n }\n }\n }, context);\n const state = replicatedState<Approval[]>(startup.items);\n const watch = await harness.watchDoc(ApprovalsDoc, context);\n if (!watch) throw new Error('approvals document is missing');\n const follow = following(watch, (using, items) => {\n state.replace(using, items);\n arm(items);\n });\n follow(context);\n watch.start(async (call, using) => {\n if (call.kind === 'value') follow(using);\n });\n const serial = <R>(change: (doc: ApprovalsState) => R, using: Context): Promise<R> => {\n const run = line.then(async () => {\n const { result } = await write(change, using);\n follow(using);\n return result;\n });\n line = run.catch(() => undefined);\n return run;\n };\n const expire = (id: string) => {\n timers.delete(id);\n const due = (state.value as Approval[]).find((entry) => entry.id === id);\n if (due?.state === 'pending' && due.expiresAt > now()) return arm(state.value as Approval[]);\n void serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n }, BACKGROUND_CONTEXT).catch(() => undefined);\n };\n function arm(items: readonly Approval[]) {\n const pending = new Set<string>();\n for (const item of items) {\n if (item.state !== 'pending') continue;\n pending.add(item.id);\n if (timers.has(item.id) || closed) continue;\n timers.set(\n item.id,\n setTimer(() => expire(item.id), Math.min(MAX_DELAY, Math.max(0, item.expiresAt - now())))\n );\n }\n for (const [id, timer] of timers)\n if (!pending.has(id)) {\n timer();\n timers.delete(id);\n }\n }\n arm(startup.items);\n const toScoop = (item: Approval) => {\n if (options.scoops && item.state === 'pending' && scoopTier(item.tier))\n void options.scoops.route(item).catch(() => undefined);\n };\n for (const item of startup.items) toScoop(item);\n const withdrawWhere = (match: (item: Approval) => boolean, reason: string | undefined) =>\n withdrawIn(match, reason, now);\n const judging = judgeRunner({\n serial,\n present: options.present,\n guestAlways: options.guestAlways,\n now,\n closed: () => closed,\n });\n return {\n state,\n async request(draft, using) {\n let created = true;\n const made = await serial((doc) => {\n const kept = draft.id && doc.items.find((entry) => entry.id === draft.id);\n if (kept) {\n created = false;\n return copy([kept])[0] as Approval;\n }\n const item = fresh(draft, now(), ttl, options);\n doc.items.push(item);\n return copy([item])[0] as Approval;\n }, using);\n if (created && options.judge && made.state === 'pending' && judgedKind(made.kind, made.tier))\n void judging(options.judge, made, made.tier === 'agent' ? using : BACKGROUND_CONTEXT);\n if (created) toScoop(made);\n return made;\n },\n decide(id, answer, reason, decider, using) {\n const { by, device } = deciderOf(decider);\n return serial((doc): ApprovalDecided => {\n const item = doc.items.find((entry) => entry.id === id);\n const ruling = item\n ? ruled(item, answer, reason, by, now())\n : { error: `There is no approval ${id}.` };\n if (item && ruling.settle) {\n if (ruling.answer) item.answer = ruling.answer;\n if (device && ruling.settle.by === by) item.device = device;\n settle(item, ruling.settle);\n }\n if ('error' in ruling && ruling.error)\n return { done: false, state: null, error: ruling.error };\n return { done: true, state: (item as Approval).state, error: null };\n }, using);\n },\n settled: (id, using) => settledIn(state, id, using),\n assign(id, reviewer, using) {\n return serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && scoopTier(item.tier)) item.reviewer ??= reviewer;\n return item ? (copy([item])[0] as Approval) : undefined;\n }, using);\n },\n async withdraw(id, reason, using) {\n const [hit] = await serial(\n withdrawWhere((item) => item.id === id, cleanReason(reason)),\n using\n );\n return hit;\n },\n async withdrawSeat(seat, using) {\n return (\n await serial(\n withdrawWhere((item) => item.seat === seat, REASONS.revoked),\n using\n )\n ).length;\n },\n async expire(id, using) {\n return serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n return item ? (copy([item])[0] as Approval) : undefined;\n }, using);\n },\n close() {\n closed = true;\n for (const timer of timers.values()) timer();\n timers.clear();\n void watch.stop();\n },\n };\n}\n"],
|
|
5
|
-
"mappings": "AAAA;AAAA,EAGE;AAAA,OAEK;AACP,SAAS,0BAA0B;AAGnC,SAA6B,YAAY,uBAAuC;AAChF;AAAA,EACE;AAAA,EAKA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAQd,MAAM,YAAY,CAAC,YAAsB,OAAO,YAAY,WAAW,EAAE,IAAI,QAAQ,IAAI;AAoCzF,MAAM,OAAO,CAAC,UAA2C,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAEzF,SAAS,KAAK,MAAgB,KAAa,IAAY;AACrD,OAAK,QAAQ,IAAI;AACjB,OAAK,YAAY,IAAI;AACrB,OAAK,YAAY;AACjB,SAAO,KAAK;AACZ,MAAI,IAAI,OAAQ,MAAK,SAAS,IAAI;AACpC;AAEA,MAAM,UAAU,CAAC,SAA0B,UACzC,UAAU,MAAM,IAAI,KAAK,MAAM,SAAS,YACpC,QAAQ,cAAc,MAAM,IAAI,MAAM,OACtC;AAEN,MAAM,aAAa,CAAC,
|
|
4
|
+
"sourcesContent": ["import {\n type Context,\n type ReplicatedState,\n replicatedState,\n type WatchHandle,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Harness } from '@earendil-works/pi-durable';\nimport type { Clock } from '../clock.ts';\nimport { type ApprovalJudge, ASK_MIN_MS, JUDGE_RESTARTED, type Judgement } from './judge.ts';\nimport {\n APPROVAL_MS,\n type Approval,\n type ApprovalDraft,\n type ApprovalKind,\n type ApprovalState,\n ApprovalsDoc,\n type ApprovalsState,\n alwaysOffered,\n cleanReason,\n type DecidedBy,\n gateOf,\n guestKind,\n heldKind,\n knownTier,\n MAX_DELAY,\n personOnly,\n prune,\n REASONS,\n type Routed,\n routable,\n route,\n ruled,\n type Settle,\n scoopTier,\n sudoApprover,\n tierOf,\n} from './record.ts';\n\nexport * from './intent.ts';\nexport * from './judge.ts';\nexport * from './present.ts';\nexport * from './record.ts';\n\nexport type ApprovalDecided =\n | { done: true; state: ApprovalState; error: null }\n | { done: false; state: null; error: string };\n\nexport type Decider = DecidedBy | { by: DecidedBy; device?: string };\n\nconst deciderOf = (decider: Decider) => (typeof decider === 'string' ? { by: decider } : decider);\n\nexport interface Approvals {\n readonly state: ReplicatedState<Approval[]>;\n request(draft: ApprovalDraft & { id?: string }, context: Context): Promise<Approval>;\n decide(\n id: string,\n answer: unknown,\n reason: string | null,\n by: Decider,\n context: Context\n ): Promise<ApprovalDecided>;\n settled(id: string, context: Context): Promise<Approval>;\n assign(id: string, reviewer: string, context: Context): Promise<Approval | undefined>;\n withdraw(id: string, reason: string | null, context: Context): Promise<Approval | undefined>;\n withdrawSeat(seat: string, context: Context): Promise<number>;\n expire(id: string, context: Context): Promise<Approval | undefined>;\n close(): void;\n}\n\nexport interface ScoopRouter {\n route(item: Approval): Promise<void>;\n}\n\nexport interface ApprovalsAttach {\n harness: Pick<Harness, 'commit' | 'watchDoc'>;\n now?: () => number;\n setTimer?: Clock['setTimer'];\n ttlMs?: number;\n judge?: ApprovalJudge;\n scoops?: ScoopRouter;\n guestAlways?: (kind: ApprovalKind) => boolean;\n sudoApprover?: () => unknown;\n present?: (item: Approval, context: Context) => Promise<boolean>;\n}\n\nconst copy = (items: readonly Approval[]): Approval[] => JSON.parse(JSON.stringify(items));\n\nfunction mark(item: Approval, how: Settle, at: number) {\n item.state = how.state;\n item.decidedBy = how.by;\n item.decidedAt = at;\n delete item.judging;\n if (how.reason) item.reason = how.reason;\n}\n\nconst offered = (options: ApprovalsAttach, draft: ApprovalDraft): boolean =>\n guestKind(draft.kind) && draft.kind !== 'capture'\n ? options.guestAlways?.(draft.kind) === true\n : false;\n\nconst judgedKind = (item: Pick<ApprovalDraft, 'kind' | 'detail'>, tier: string) =>\n !personOnly(item) && (item.kind === 'sudo' || tier === 'agent' || tier === 'user');\n\nfunction detailOf(draft: ApprovalDraft): ApprovalDraft['detail'] {\n if (draft.kind !== 'sudo' || draft.always !== false) return draft.detail;\n return { ...draft.detail, writable: false };\n}\n\nfunction fresh(\n draft: ApprovalDraft & { id?: string },\n at: number,\n ttl: number,\n options: ApprovalsAttach\n): Approval {\n const tier = tierOf(draft, sudoApprover(options.sudoApprover?.()));\n const item = {\n ...draft,\n detail: detailOf(draft),\n tier,\n id: draft.id ?? `apr-${crypto.randomUUID()}`,\n state: 'pending',\n decidedBy: null,\n always: offered(options, draft),\n ...(options.judge && judgedKind(draft, tier) ? { judging: true } : {}),\n createdAt: at,\n expiresAt: draft.expiresAt ?? at + ttl,\n } as Approval;\n if (!knownTier(item.tier))\n mark(item, { state: 'unanswered', by: 'host', reason: REASONS.unknownTier }, at);\n else if (!routable(draft.kind, item.tier))\n mark(item, { state: 'unanswered', by: 'host', reason: REASONS.unroutable }, at);\n return item;\n}\n\nconst withdrawIn =\n (match: (item: Approval) => boolean, reason: string | undefined, now: () => number) =>\n (doc: ApprovalsState) => {\n const hit = doc.items.filter((item) => item.state === 'pending' && match(item));\n for (const item of hit)\n mark(item, { state: 'withdrawn', by: 'host', ...(reason ? { reason } : {}) }, now());\n return hit.map((item) => copy([item])[0] as Approval);\n };\n\ntype Judged = { judgement: Judgement; present: boolean; offer?: boolean };\n\nconst routeOf = (item: Approval, { judgement, present }: Judged): Routed =>\n route(judgement.verdict, item.requester, gateOf(item.tier), present);\n\nconst judgedIn = (id: string, judged: Judged, now: () => number) => (doc: ApprovalsState) => {\n const { judgement } = judged;\n const item = doc.items.find((entry) => entry.id === id);\n if (!item) return undefined;\n const late = item.state === 'unanswered' && item.reason === REASONS.timeout && !item.verdict;\n if (item.state !== 'pending' && !(late && judgement.verdict)) return undefined;\n delete item.judging;\n if (judgement.verdict) item.verdict = judgement.verdict;\n else item.verdictError = judgement.error ?? 'the judge gave no verdict';\n if (late) return copy([item])[0] as Approval;\n const routed = routeOf(item, judged);\n if (routed === 'ask') {\n item.tier = 'user';\n if (item.kind === 'sudo') item.always = alwaysOffered(item);\n if (item.kind === 'capture') item.always = alwaysOffered(item) && judged.offer === true;\n return copy([item])[0] as Approval;\n }\n const at = now();\n const ruling = ruled(item, routed === 'approve' ? 'once' : 'deny', null, 'judge', at);\n if (ruling.answer) item.answer = ruling.answer;\n if (ruling.settle) mark(item, ruling.settle, at);\n return copy([item])[0] as Approval;\n};\n\nasync function judgedBy(\n judge: ApprovalJudge,\n present: ApprovalsAttach['present'],\n item: Approval,\n using: Context,\n now: () => number\n): Promise<Judged> {\n const judgement = await judge\n .judge(item, using)\n .catch((error: unknown): Judgement => ({ error: String(error) }));\n if (judgement.verdict?.level !== 3 || !present || item.tier !== 'agent')\n return { judgement, present: false };\n const there = await present(item, using).catch(() => false);\n return { judgement, present: there && item.expiresAt - now() >= ASK_MIN_MS };\n}\n\ntype Serial = <R>(change: (doc: ApprovalsState) => R, using: Context) => Promise<R>;\n\nfunction judgeRunner(run: {\n serial: Serial;\n present: ApprovalsAttach['present'];\n guestAlways: ApprovalsAttach['guestAlways'];\n now: () => number;\n closed: () => boolean;\n}) {\n const { serial, now } = run;\n return async (judge: ApprovalJudge, item: Approval, using: Context) => {\n const signal = using.abortSignal;\n let gone = false;\n const abort = () => {\n gone = true;\n void serial(\n withdrawIn((entry) => entry.id === item.id && entry.tier === 'agent', REASONS.aborted, now),\n BACKGROUND_CONTEXT\n ).catch(() => undefined);\n };\n if (signal?.aborted) return abort();\n signal?.addEventListener('abort', abort, { once: true });\n const found = await judgedBy(judge, run.present, item, using, now);\n signal?.removeEventListener('abort', abort);\n if (gone || run.closed()) return;\n const judged = { ...found, offer: run.guestAlways?.(item.kind) === true };\n const after = await serial(judgedIn(item.id, judged, now), BACKGROUND_CONTEXT).catch(\n () => undefined\n );\n if (!after) return;\n await judge.record?.(after, judged.judgement, BACKGROUND_CONTEXT).catch(() => undefined);\n };\n}\n\nfunction following(\n watch: WatchHandle<Readonly<ApprovalsState>>,\n changed: (using: Context, items: Approval[]) => void\n) {\n const items = () => watch.value.items;\n let shown = items();\n return (using: Context) => {\n const now = items();\n if (now === shown) return;\n shown = now;\n changed(using, copy(now));\n };\n}\n\nfunction settledIn(\n state: ReplicatedState<Approval[]>,\n id: string,\n using: Context\n): Promise<Approval> {\n return new Promise((resolve, reject) => {\n const signal = using.abortSignal;\n let done = false;\n let off: (() => void) | undefined;\n const finish = (end: () => void) => {\n done = true;\n off?.();\n signal?.removeEventListener('abort', abort);\n end();\n };\n const abort = () => finish(() => reject(signal?.reason));\n const check = (items: readonly Approval[] | undefined) => {\n const item = items?.find((entry) => entry.id === id);\n if (!item) finish(() => reject(new Error(`There is no approval ${id}.`)));\n else if (item.state !== 'pending') finish(() => resolve(item));\n };\n if (signal?.aborted) return abort();\n check(state.value);\n if (done) return;\n signal?.addEventListener('abort', abort, { once: true });\n off = state.subscribe((items) => check(items));\n });\n}\n\nconst systemTimer: Clock['setTimer'] = (callback, delayMs) => {\n const timer = setTimeout(callback, delayMs);\n return () => clearTimeout(timer);\n};\n\nexport async function attachApprovals(\n options: ApprovalsAttach,\n context: Context = BACKGROUND_CONTEXT\n): Promise<Approvals> {\n const { harness } = options;\n const now = options.now ?? Date.now;\n const ttl = options.ttlMs ?? APPROVAL_MS;\n const setTimer = options.setTimer ?? systemTimer;\n const timers = new Map<string, () => void>();\n let line: Promise<unknown> = Promise.resolve();\n let closed = false;\n const settle = (item: Approval, how: Settle) => mark(item, how, now());\n const write = <R>(\n change: (doc: ApprovalsState) => R,\n using: Context\n ): Promise<{ result: R; items: Approval[] }> =>\n harness.commit(async (tx) => {\n const doc = await tx.doc(ApprovalsDoc);\n const result = change(doc);\n doc.items = prune(doc.items);\n return { result, items: copy(doc.items) };\n }, using);\n const startup = await write((doc) => {\n for (const item of doc.items) {\n if (item.state !== 'pending') continue;\n if (heldKind(item.kind))\n settle(item, { state: 'withdrawn', by: 'host', reason: REASONS.restart });\n else if (item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n else if (options.judge && item.tier === 'agent') item.tier = 'user';\n if (item.state === 'pending' && item.judging) {\n delete item.judging;\n item.verdictError = JUDGE_RESTARTED;\n }\n }\n }, context);\n const state = replicatedState<Approval[]>(startup.items);\n const watch = await harness.watchDoc(ApprovalsDoc, context);\n if (!watch) throw new Error('approvals document is missing');\n const follow = following(watch, (using, items) => {\n state.replace(using, items);\n arm(items);\n });\n follow(context);\n watch.start(async (call, using) => {\n if (call.kind === 'value') follow(using);\n });\n const serial = <R>(change: (doc: ApprovalsState) => R, using: Context): Promise<R> => {\n const run = line.then(async () => {\n const { result } = await write(change, using);\n follow(using);\n return result;\n });\n line = run.catch(() => undefined);\n return run;\n };\n const expire = (id: string) => {\n timers.delete(id);\n const due = (state.value as Approval[]).find((entry) => entry.id === id);\n if (due?.state === 'pending' && due.expiresAt > now()) return arm(state.value as Approval[]);\n void serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n }, BACKGROUND_CONTEXT).catch(() => undefined);\n };\n function arm(items: readonly Approval[]) {\n const pending = new Set<string>();\n for (const item of items) {\n if (item.state !== 'pending') continue;\n pending.add(item.id);\n if (timers.has(item.id) || closed) continue;\n timers.set(\n item.id,\n setTimer(() => expire(item.id), Math.min(MAX_DELAY, Math.max(0, item.expiresAt - now())))\n );\n }\n for (const [id, timer] of timers)\n if (!pending.has(id)) {\n timer();\n timers.delete(id);\n }\n }\n arm(startup.items);\n const toScoop = (item: Approval) => {\n if (options.scoops && item.state === 'pending' && scoopTier(item.tier))\n void options.scoops.route(item).catch(() => undefined);\n };\n for (const item of startup.items) toScoop(item);\n const withdrawWhere = (match: (item: Approval) => boolean, reason: string | undefined) =>\n withdrawIn(match, reason, now);\n const judging = judgeRunner({\n serial,\n present: options.present,\n guestAlways: options.guestAlways,\n now,\n closed: () => closed,\n });\n return {\n state,\n async request(draft, using) {\n let created = true;\n const made = await serial((doc) => {\n const kept = draft.id && doc.items.find((entry) => entry.id === draft.id);\n if (kept) {\n created = false;\n return copy([kept])[0] as Approval;\n }\n const item = fresh(draft, now(), ttl, options);\n doc.items.push(item);\n return copy([item])[0] as Approval;\n }, using);\n if (created && options.judge && made.state === 'pending' && judgedKind(made, made.tier))\n void judging(options.judge, made, made.tier === 'agent' ? using : BACKGROUND_CONTEXT);\n if (created) toScoop(made);\n return made;\n },\n decide(id, answer, reason, decider, using) {\n const { by, device } = deciderOf(decider);\n return serial((doc): ApprovalDecided => {\n const item = doc.items.find((entry) => entry.id === id);\n const ruling = item\n ? ruled(item, answer, reason, by, now())\n : { error: `There is no approval ${id}.` };\n if (item && ruling.settle) {\n if (ruling.answer) item.answer = ruling.answer;\n if (device && ruling.settle.by === by) item.device = device;\n settle(item, ruling.settle);\n }\n if ('error' in ruling && ruling.error)\n return { done: false, state: null, error: ruling.error };\n return { done: true, state: (item as Approval).state, error: null };\n }, using);\n },\n settled: (id, using) => settledIn(state, id, using),\n assign(id, reviewer, using) {\n return serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && scoopTier(item.tier)) item.reviewer ??= reviewer;\n return item ? (copy([item])[0] as Approval) : undefined;\n }, using);\n },\n async withdraw(id, reason, using) {\n const [hit] = await serial(\n withdrawWhere((item) => item.id === id, cleanReason(reason)),\n using\n );\n return hit;\n },\n async withdrawSeat(seat, using) {\n return (\n await serial(\n withdrawWhere((item) => item.seat === seat, REASONS.revoked),\n using\n )\n ).length;\n },\n async expire(id, using) {\n return serial((doc) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.state === 'pending' && item.expiresAt <= now())\n settle(item, { state: 'unanswered', by: 'host', reason: REASONS.timeout });\n return item ? (copy([item])[0] as Approval) : undefined;\n }, using);\n },\n close() {\n closed = true;\n for (const timer of timers.values()) timer();\n timers.clear();\n void watch.stop();\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EAGE;AAAA,OAEK;AACP,SAAS,0BAA0B;AAGnC,SAA6B,YAAY,uBAAuC;AAChF;AAAA,EACE;AAAA,EAKA;AAAA,EAEA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;AAQd,MAAM,YAAY,CAAC,YAAsB,OAAO,YAAY,WAAW,EAAE,IAAI,QAAQ,IAAI;AAoCzF,MAAM,OAAO,CAAC,UAA2C,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAEzF,SAAS,KAAK,MAAgB,KAAa,IAAY;AACrD,OAAK,QAAQ,IAAI;AACjB,OAAK,YAAY,IAAI;AACrB,OAAK,YAAY;AACjB,SAAO,KAAK;AACZ,MAAI,IAAI,OAAQ,MAAK,SAAS,IAAI;AACpC;AAEA,MAAM,UAAU,CAAC,SAA0B,UACzC,UAAU,MAAM,IAAI,KAAK,MAAM,SAAS,YACpC,QAAQ,cAAc,MAAM,IAAI,MAAM,OACtC;AAEN,MAAM,aAAa,CAAC,MAA8C,SAChE,CAAC,WAAW,IAAI,MAAM,KAAK,SAAS,UAAU,SAAS,WAAW,SAAS;AAE7E,SAAS,SAAS,OAA+C;AAC/D,MAAI,MAAM,SAAS,UAAU,MAAM,WAAW,MAAO,QAAO,MAAM;AAClE,SAAO,EAAE,GAAG,MAAM,QAAQ,UAAU,MAAM;AAC5C;AAEA,SAAS,MACP,OACA,IACA,KACA,SACU;AACV,QAAM,OAAO,OAAO,OAAO,aAAa,QAAQ,eAAe,CAAC,C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,QAAQ,QAAQ,CAAC;AAC3E,eAAO,OAAQ,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,IAAiB;AAAA,MAChD,GAAG,KAAK;AAAA,IACV;AAAA,IACA,QAAQ;AACN,eAAS;AACT,iBAAW,SAAS,OAAO,OAAO,EAAG,OAAM;AAC3C,aAAO,MAAM;AACb,WAAK,MAAM,KAAK;AAAA,IAClB;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/approvals/people.ts"],
|
|
4
|
+
"sourcesContent": ["import type { DecidedBy } from './record.ts';\n\nexport const personal = (by: DecidedBy): boolean => by === 'owner' || by === 'follower';\n"],
|
|
5
|
+
"mappings": "AAEO,MAAM,WAAW,CAAC,OAA2B,OAAO,WAAW,OAAO;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/approvals/record.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { defineDoc } from "@earendil-works/pi-durable";
|
|
2
2
|
import { boundedDeltas } from "../checkpoints.js";
|
|
3
3
|
import { clears, fits, JUDGE_ALLOW, JUDGE_LOW, reaches } from "./aligned.js";
|
|
4
|
+
import { personal } from "./people.js";
|
|
4
5
|
const ApprovalsDoc = defineDoc({
|
|
5
6
|
kind: "slicc.approvals",
|
|
6
7
|
checkpointWhen: boundedDeltas,
|
|
@@ -39,7 +40,6 @@ function routable(kind, tier) {
|
|
|
39
40
|
function answerOf(value) {
|
|
40
41
|
return value === "once" || value === "always" || value === "deny" ? value : null;
|
|
41
42
|
}
|
|
42
|
-
const personal = (by) => by === "owner" || by === "follower";
|
|
43
43
|
function answerer(by, item) {
|
|
44
44
|
if (personal(by)) return item.tier === "user";
|
|
45
45
|
if (by === "judge") return item.tier === "agent";
|
|
@@ -47,7 +47,8 @@ function answerer(by, item) {
|
|
|
47
47
|
return true;
|
|
48
48
|
}
|
|
49
49
|
const sudoApprover = (value) => value === "agent" ? "agent" : "user";
|
|
50
|
-
const
|
|
50
|
+
const personOnly = (item) => item.kind === "sudo" && item.detail.validate === true;
|
|
51
|
+
const tierOf = (draft, sudo) => draft.kind !== "sudo" ? draft.tier : personOnly(draft) ? "user" : sudo;
|
|
51
52
|
const gateOf = (tier) => tier === "agent" ? "judge" : "person";
|
|
52
53
|
const vetoed = ({ forbidden }) => forbidden === true || typeof forbidden === "number" && reaches(forbidden, JUDGE_LOW);
|
|
53
54
|
function approvable(verdict) {
|
|
@@ -62,6 +63,7 @@ function route(verdict, requester, gate, present) {
|
|
|
62
63
|
}
|
|
63
64
|
function alwaysOffered(item) {
|
|
64
65
|
if (item.kind !== "sudo" && item.kind !== "capture" || item.tier !== "user") return false;
|
|
66
|
+
if (personOnly(item)) return false;
|
|
65
67
|
const { verdict } = item;
|
|
66
68
|
const writable = item.kind !== "sudo" || item.detail.writable !== false;
|
|
67
69
|
return verdict?.level === 1 && verdict.always === true && writable;
|
|
@@ -122,6 +124,7 @@ export {
|
|
|
122
124
|
guestKind,
|
|
123
125
|
heldKind,
|
|
124
126
|
knownTier,
|
|
127
|
+
personOnly,
|
|
125
128
|
personal,
|
|
126
129
|
prune,
|
|
127
130
|
routable,
|
|
@@ -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';\n\nexport { fits, JUDGE_ALLOW };\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 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};\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 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 noScoop: 'no-scoop',\n scoopStopped: 'scoop-stopped',\n scoopAsked: 'scoop-asked',\n scoopUndecided: 'scoop-undecided',\n} as const;\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): ApprovalAnswer | null {\n return value === 'once' || value === 'always' || value === 'deny' ? value : null;\n}\n\nexport
|
|
5
|
-
"mappings": "AAAA,SAAS,iBAAiB;AAC1B,SAAS,qBAAqB;AAC9B,SAAS,QAAQ,MAAM,aAAa,WAAW,eAAe;
|
|
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';\n\nexport { fits, JUDGE_ALLOW, personal };\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 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 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 noScoop: 'no-scoop',\n scoopStopped: 'scoop-stopped',\n scoopAsked: 'scoop-asked',\n scoopUndecided: 'scoop-undecided',\n} as const;\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): ApprovalAnswer | null {\n return value === 'once' || value === 'always' || value === 'deny' ? value : 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 = { 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)) 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 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;AAmHlB,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,UAAU;AAAA,EACrB,SAAS;AAAA,EACT,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,SAAS;AAAA,EACT,SAAS;AAAA,EACT,SAAS;AAAA,EACT,cAAc;AAAA,EACd,SAAS;AAAA,EACT,cAAc;AAAA,EACd,YAAY;AAAA,EACZ,gBAAgB;AAClB;AAEO,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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,QAAM,QAAQ,SAAS,MAAM;AAC7B,MAAI,UAAU,YAAY,UAAU,EAAE,EAAG,QAAO,EAAE,OAAO,gCAAgC;AACzF,MAAI,UAAU,YAAY,CAAC,SAAS,EAAE;AACpC,WAAO,EAAE,OAAO,2CAA2C;AAC7D,MAAI,UAAU,YAAY,CAAC,KAAK;AAC9B,WAAO,EAAE,OAAO,yCAAyC;AAC3D,MAAI,CAAC,MAAO,QAAO,EAAE,QAAQ,EAAE,OAAO,YAAY,IAAI,QAAQ,QAAQ,cAAc,EAAE;AACtF,QAAM,QAAQ,IAAI,YAAY,MAAM,CAAC;AACrC,MAAI,UAAU,OAAQ,QAAO,EAAE,QAAQ,EAAE,OAAO,YAAY,IAAI,GAAG,MAAM,EAAE;AAC3E,SAAO,EAAE,QAAQ,EAAE,OAAO,YAAY,IAAI,GAAG,MAAM,GAAG,QAAQ,MAAM;AACtE;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -4,6 +4,7 @@ import { AgentSudoService, SUDO_METHODS } from "../services.js";
|
|
|
4
4
|
import { bound } from "../serving.js";
|
|
5
5
|
import { PortLink } from "../wire.js";
|
|
6
6
|
import { attributed, UNATTRIBUTED } from "./attributed.js";
|
|
7
|
+
import { personal } from "./people.js";
|
|
7
8
|
const UNAVAILABLE = "The agent can't take this sudo request.";
|
|
8
9
|
const unavailable = (cause) => Object.assign(new Error(UNAVAILABLE), { code: "EAGAIN", ...cause ? { cause } : {} });
|
|
9
10
|
const missing = () => () => Promise.reject(unavailable());
|
|
@@ -12,8 +13,11 @@ function answerOf(item) {
|
|
|
12
13
|
return item.state === "approved" && item.answer ? item.answer : "deny";
|
|
13
14
|
}
|
|
14
15
|
const JUDGE_DENIED = "sudo: denied by the approval judge";
|
|
15
|
-
function replyOf(item) {
|
|
16
|
+
function replyOf(item, stamps = false) {
|
|
16
17
|
const answer = answerOf(item);
|
|
18
|
+
const by = item?.decidedBy;
|
|
19
|
+
if (stamps && answer !== null && answer !== "deny" && by && personal(by))
|
|
20
|
+
return { answer, timestamp: true };
|
|
17
21
|
if (answer !== "deny" || item?.state !== "rejected" || item.decidedBy !== "judge") return answer;
|
|
18
22
|
const reason = item.verdict?.reason;
|
|
19
23
|
const denial = {
|
|
@@ -56,7 +60,7 @@ async function open(endpoint, stop) {
|
|
|
56
60
|
}
|
|
57
61
|
}
|
|
58
62
|
function settled(approvals, id, signals, ended) {
|
|
59
|
-
const { signal, stop } = signals;
|
|
63
|
+
const { signal, stop, stamps } = signals;
|
|
60
64
|
return new Promise((resolve) => {
|
|
61
65
|
let off = () => void 0;
|
|
62
66
|
let done = false;
|
|
@@ -76,7 +80,10 @@ function settled(approvals, id, signals, ended) {
|
|
|
76
80
|
stop?.addEventListener("abort", halt, { once: true });
|
|
77
81
|
ended.catch(() => finish("deny"));
|
|
78
82
|
off = approvals.subscribe((items) => {
|
|
79
|
-
const answer = replyOf(
|
|
83
|
+
const answer = replyOf(
|
|
84
|
+
items?.find((item) => item.id === id),
|
|
85
|
+
stamps
|
|
86
|
+
);
|
|
80
87
|
if (answer) finish(answer);
|
|
81
88
|
});
|
|
82
89
|
if (done) off();
|
|
@@ -130,7 +137,7 @@ async function askSudo(endpoint, request, options = {}, stop) {
|
|
|
130
137
|
if (signal?.aborted || stop?.aborted) return "deny";
|
|
131
138
|
const asked = await link.sudo.request(request, options.where ?? null, BACKGROUND_CONTEXT);
|
|
132
139
|
if (asked.id === null) throw new Error(asked.error);
|
|
133
|
-
const signals = { signal, stop };
|
|
140
|
+
const signals = { signal, stop, stamps: request.timestamp === true };
|
|
134
141
|
const { answer, aborted } = await settled(link.approvals, asked.id, signals, link.ended);
|
|
135
142
|
if (aborted === "expired") await timedOut(link, asked.id, request.expiresAt);
|
|
136
143
|
else if (aborted)
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/approvals/sudo-client.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Readable } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT, withAbortSignal } from '@earendil-works/chord/context';\nimport { clientHost, holding } from '../client.ts';\nimport type { CaptureReply } from '../guests/capture.ts';\nimport { AgentSudoService, SUDO_METHODS } from '../services.ts';\nimport { bound, type Remote, type Root } from '../serving.ts';\nimport { type PortEndpoint, PortLink } from '../wire.ts';\nimport { attributed, UNATTRIBUTED } from './attributed.ts';\nimport type { Approval } from './record.ts';\nimport type { AgentSudo, SudoAnswer, SudoDenial, SudoReply, SudoRequest } from './sudo.ts';\n\nexport interface ApproveOptions {\n signal?: AbortSignal;\n where?: string;\n}\n\nexport const UNAVAILABLE = \"The agent can't take this sudo request.\";\n\nexport const unavailable = (cause?: unknown): Error =>\n Object.assign(new Error(UNAVAILABLE), { code: 'EAGAIN', ...(cause ? { cause } : {}) });\n\nconst missing = () => () => Promise.reject(unavailable());\n\nexport function answerOf(item: Approval | undefined): SudoAnswer | null {\n if (!item || item.state === 'pending') return null;\n return item.state === 'approved' && item.answer ? item.answer : 'deny';\n}\n\nexport const JUDGE_DENIED = 'sudo: denied by the approval judge';\n\nexport function replyOf(item: Approval | undefined): SudoReply | null {\n const answer = answerOf(item);\n if (answer !== 'deny' || item?.state !== 'rejected' || item.decidedBy !== 'judge') return answer;\n const reason = item.verdict?.reason;\n const denial: SudoDenial = {\n answer: 'deny',\n message: reason ? `${JUDGE_DENIED}: ${reason}` : JUDGE_DENIED,\n };\n return denial;\n}\n\nfunction halted(stop: AbortSignal | undefined): Promise<never> {\n return new Promise((_, reject) => {\n if (stop?.aborted) reject(unavailable());\n stop?.addEventListener('abort', () => reject(unavailable()), { once: true });\n });\n}\n\nasync function open(endpoint: PortEndpoint, stop: AbortSignal | undefined) {\n const link = new PortLink(endpoint);\n let host: ReturnType<typeof clientHost> | undefined;\n const close = async () => {\n link.close('closed');\n await host?.close().catch(() => undefined);\n };\n const ended = link.ended.then((reason) => {\n throw reason ?? new Error('the agent closed the link');\n });\n ended.catch(() => undefined);\n const stopped = halted(stop);\n stopped.catch(() => undefined);\n try {\n await Promise.race([link.hello, ended, stopped]);\n const client = clientHost(link, 'sudo');\n host = client;\n const [handle] = (await Promise.race([holding(client, link, [AgentSudoService]), stopped])) as [\n Remote,\n ];\n if (handle.variant !== 'sudo') throw unavailable();\n const root: Root = (run, options) => client.root(run, options);\n const sudo = bound<Omit<AgentSudo, 'approvals'>>(handle, root, SUDO_METHODS, missing);\n return { sudo, approvals: handle.approvals as Readable<Approval[]>, ended, close };\n } catch (error) {\n await close();\n throw (error as { code?: unknown })?.code === 'EAGAIN' ? error : unavailable(error);\n }\n}\n\nfunction settled(\n approvals: Readable<Approval[]>,\n id: string,\n signals: { signal: AbortSignal | undefined; stop: AbortSignal | undefined },\n ended: Promise<never>\n): Promise<{ answer: SudoReply; aborted: unknown }> {\n const { signal, stop } = signals;\n return new Promise((resolve) => {\n let off: () => void = () => undefined;\n let done = false;\n const finish = (answer: SudoReply, aborted: unknown = null) => {\n if (done) return;\n done = true;\n off();\n signal?.removeEventListener('abort', abort);\n stop?.removeEventListener('abort', halt);\n resolve({ answer, aborted });\n };\n const abort = () => finish('deny', signal?.reason ?? 'withdrawn');\n const halt = () => finish('deny');\n if (signal?.aborted) return abort();\n if (stop?.aborted) return halt();\n signal?.addEventListener('abort', abort, { once: true });\n stop?.addEventListener('abort', halt, { once: true });\n ended.catch(() => finish('deny'));\n off = approvals.subscribe((items) => {\n const answer = replyOf(items?.find((item) => item.id === id));\n if (answer) finish(answer);\n });\n if (done) off();\n });\n}\n\nexport const WITHDRAW_MS = 5000;\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nfunction timedOut(\n link: { approvals: Readable<Approval[]>; ended: Promise<never> },\n id: string,\n expiresAt: number\n): Promise<unknown> {\n let off: () => void = () => undefined;\n const left = new Promise<void>((resolve) => {\n off = link.approvals.subscribe((items) => {\n if (answerOf(items?.find((item) => item.id === id))) resolve();\n });\n });\n const wait = Math.max(0, expiresAt - Date.now()) + WITHDRAW_MS;\n return Promise.race([left, link.ended.catch(() => undefined), delay(wait)]).finally(() => off());\n}\n\nexport interface CaptureAsk {\n kind: string;\n options?: Record<string, unknown>;\n stamp?: Record<string, unknown>;\n label?: string;\n}\n\nconst isEagain = (error: unknown) => (error as { code?: unknown })?.code === 'EAGAIN';\n\nexport async function askCapture(\n endpoint: PortEndpoint,\n request: CaptureAsk,\n options: ApproveOptions = {},\n stop?: AbortSignal\n): Promise<CaptureReply> {\n if (!attributed(request)) throw unavailable();\n const { signal } = options;\n const link = await open(endpoint, stop);\n const ending = new AbortController();\n const end = () => ending.abort();\n signal?.addEventListener('abort', end, { once: true });\n stop?.addEventListener('abort', end, { once: true });\n const using = withAbortSignal(ending.signal, BACKGROUND_CONTEXT);\n try {\n if (signal?.aborted || stop?.aborted) return 'deny';\n const asked = link.sudo.capture(request, options.where ?? null, using);\n const gone = link.ended.catch(() => 'deny' as const);\n const halted = new Promise<'deny'>((resolve) =>\n ending.signal.addEventListener('abort', () => resolve('deny'), { once: true })\n );\n const answer = await Promise.race([asked, gone, halted]);\n if (answer === UNATTRIBUTED) throw unavailable();\n return answer;\n } catch (error) {\n if (isEagain(error)) throw error;\n return 'deny';\n } finally {\n signal?.removeEventListener('abort', end);\n stop?.removeEventListener('abort', end);\n await link.close();\n }\n}\n\nexport async function askSudo(\n endpoint: PortEndpoint,\n request: SudoRequest,\n options: ApproveOptions = {},\n stop?: AbortSignal\n): Promise<SudoReply> {\n const { signal } = options;\n const link = await open(endpoint, stop);\n try {\n if (signal?.aborted || stop?.aborted) return 'deny';\n const asked = await link.sudo.request(request, options.where ?? null, BACKGROUND_CONTEXT);\n if (asked.id === null) throw new Error(asked.error);\n const signals = { signal, stop };\n const { answer, aborted } = await settled(link.approvals, asked.id, signals, link.ended);\n if (aborted === 'expired') await timedOut(link, asked.id, request.expiresAt);\n else if (aborted)\n await Promise.race([\n link.sudo.withdraw(asked.id, String(aborted), BACKGROUND_CONTEXT),\n delay(WITHDRAW_MS),\n ]);\n return answer;\n } finally {\n await link.close();\n }\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,oBAAoB,uBAAuB;AACpD,SAAS,YAAY,eAAe;AAEpC,SAAS,kBAAkB,oBAAoB;AAC/C,SAAS,aAAqC;AAC9C,SAA4B,gBAAgB;AAC5C,SAAS,YAAY,oBAAoB;
|
|
4
|
+
"sourcesContent": ["import type { Readable } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT, withAbortSignal } from '@earendil-works/chord/context';\nimport { clientHost, holding } from '../client.ts';\nimport type { CaptureReply } from '../guests/capture.ts';\nimport { AgentSudoService, SUDO_METHODS } from '../services.ts';\nimport { bound, type Remote, type Root } from '../serving.ts';\nimport { type PortEndpoint, PortLink } from '../wire.ts';\nimport { attributed, UNATTRIBUTED } from './attributed.ts';\nimport { personal } from './people.ts';\nimport type { Approval } from './record.ts';\nimport type { AgentSudo, SudoAnswer, SudoDenial, SudoReply, SudoRequest } from './sudo.ts';\n\nexport interface ApproveOptions {\n signal?: AbortSignal;\n where?: string;\n}\n\nexport const UNAVAILABLE = \"The agent can't take this sudo request.\";\n\nexport const unavailable = (cause?: unknown): Error =>\n Object.assign(new Error(UNAVAILABLE), { code: 'EAGAIN', ...(cause ? { cause } : {}) });\n\nconst missing = () => () => Promise.reject(unavailable());\n\nexport function answerOf(item: Approval | undefined): SudoAnswer | null {\n if (!item || item.state === 'pending') return null;\n return item.state === 'approved' && item.answer ? item.answer : 'deny';\n}\n\nexport const JUDGE_DENIED = 'sudo: denied by the approval judge';\n\nexport function replyOf(item: Approval | undefined, stamps = false): SudoReply | null {\n const answer = answerOf(item);\n const by = item?.decidedBy;\n if (stamps && answer !== null && answer !== 'deny' && by && personal(by))\n return { answer, timestamp: true };\n if (answer !== 'deny' || item?.state !== 'rejected' || item.decidedBy !== 'judge') return answer;\n const reason = item.verdict?.reason;\n const denial: SudoDenial = {\n answer: 'deny',\n message: reason ? `${JUDGE_DENIED}: ${reason}` : JUDGE_DENIED,\n };\n return denial;\n}\n\nfunction halted(stop: AbortSignal | undefined): Promise<never> {\n return new Promise((_, reject) => {\n if (stop?.aborted) reject(unavailable());\n stop?.addEventListener('abort', () => reject(unavailable()), { once: true });\n });\n}\n\nasync function open(endpoint: PortEndpoint, stop: AbortSignal | undefined) {\n const link = new PortLink(endpoint);\n let host: ReturnType<typeof clientHost> | undefined;\n const close = async () => {\n link.close('closed');\n await host?.close().catch(() => undefined);\n };\n const ended = link.ended.then((reason) => {\n throw reason ?? new Error('the agent closed the link');\n });\n ended.catch(() => undefined);\n const stopped = halted(stop);\n stopped.catch(() => undefined);\n try {\n await Promise.race([link.hello, ended, stopped]);\n const client = clientHost(link, 'sudo');\n host = client;\n const [handle] = (await Promise.race([holding(client, link, [AgentSudoService]), stopped])) as [\n Remote,\n ];\n if (handle.variant !== 'sudo') throw unavailable();\n const root: Root = (run, options) => client.root(run, options);\n const sudo = bound<Omit<AgentSudo, 'approvals'>>(handle, root, SUDO_METHODS, missing);\n return { sudo, approvals: handle.approvals as Readable<Approval[]>, ended, close };\n } catch (error) {\n await close();\n throw (error as { code?: unknown })?.code === 'EAGAIN' ? error : unavailable(error);\n }\n}\n\nfunction settled(\n approvals: Readable<Approval[]>,\n id: string,\n signals: { signal: AbortSignal | undefined; stop: AbortSignal | undefined; stamps: boolean },\n ended: Promise<never>\n): Promise<{ answer: SudoReply; aborted: unknown }> {\n const { signal, stop, stamps } = signals;\n return new Promise((resolve) => {\n let off: () => void = () => undefined;\n let done = false;\n const finish = (answer: SudoReply, aborted: unknown = null) => {\n if (done) return;\n done = true;\n off();\n signal?.removeEventListener('abort', abort);\n stop?.removeEventListener('abort', halt);\n resolve({ answer, aborted });\n };\n const abort = () => finish('deny', signal?.reason ?? 'withdrawn');\n const halt = () => finish('deny');\n if (signal?.aborted) return abort();\n if (stop?.aborted) return halt();\n signal?.addEventListener('abort', abort, { once: true });\n stop?.addEventListener('abort', halt, { once: true });\n ended.catch(() => finish('deny'));\n off = approvals.subscribe((items) => {\n const answer = replyOf(\n items?.find((item) => item.id === id),\n stamps\n );\n if (answer) finish(answer);\n });\n if (done) off();\n });\n}\n\nexport const WITHDRAW_MS = 5000;\n\nconst delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));\n\nfunction timedOut(\n link: { approvals: Readable<Approval[]>; ended: Promise<never> },\n id: string,\n expiresAt: number\n): Promise<unknown> {\n let off: () => void = () => undefined;\n const left = new Promise<void>((resolve) => {\n off = link.approvals.subscribe((items) => {\n if (answerOf(items?.find((item) => item.id === id))) resolve();\n });\n });\n const wait = Math.max(0, expiresAt - Date.now()) + WITHDRAW_MS;\n return Promise.race([left, link.ended.catch(() => undefined), delay(wait)]).finally(() => off());\n}\n\nexport interface CaptureAsk {\n kind: string;\n options?: Record<string, unknown>;\n stamp?: Record<string, unknown>;\n label?: string;\n}\n\nconst isEagain = (error: unknown) => (error as { code?: unknown })?.code === 'EAGAIN';\n\nexport async function askCapture(\n endpoint: PortEndpoint,\n request: CaptureAsk,\n options: ApproveOptions = {},\n stop?: AbortSignal\n): Promise<CaptureReply> {\n if (!attributed(request)) throw unavailable();\n const { signal } = options;\n const link = await open(endpoint, stop);\n const ending = new AbortController();\n const end = () => ending.abort();\n signal?.addEventListener('abort', end, { once: true });\n stop?.addEventListener('abort', end, { once: true });\n const using = withAbortSignal(ending.signal, BACKGROUND_CONTEXT);\n try {\n if (signal?.aborted || stop?.aborted) return 'deny';\n const asked = link.sudo.capture(request, options.where ?? null, using);\n const gone = link.ended.catch(() => 'deny' as const);\n const halted = new Promise<'deny'>((resolve) =>\n ending.signal.addEventListener('abort', () => resolve('deny'), { once: true })\n );\n const answer = await Promise.race([asked, gone, halted]);\n if (answer === UNATTRIBUTED) throw unavailable();\n return answer;\n } catch (error) {\n if (isEagain(error)) throw error;\n return 'deny';\n } finally {\n signal?.removeEventListener('abort', end);\n stop?.removeEventListener('abort', end);\n await link.close();\n }\n}\n\nexport async function askSudo(\n endpoint: PortEndpoint,\n request: SudoRequest,\n options: ApproveOptions = {},\n stop?: AbortSignal\n): Promise<SudoReply> {\n const { signal } = options;\n const link = await open(endpoint, stop);\n try {\n if (signal?.aborted || stop?.aborted) return 'deny';\n const asked = await link.sudo.request(request, options.where ?? null, BACKGROUND_CONTEXT);\n if (asked.id === null) throw new Error(asked.error);\n const signals = { signal, stop, stamps: request.timestamp === true };\n const { answer, aborted } = await settled(link.approvals, asked.id, signals, link.ended);\n if (aborted === 'expired') await timedOut(link, asked.id, request.expiresAt);\n else if (aborted)\n await Promise.race([\n link.sudo.withdraw(asked.id, String(aborted), BACKGROUND_CONTEXT),\n delay(WITHDRAW_MS),\n ]);\n return answer;\n } finally {\n await link.close();\n }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,oBAAoB,uBAAuB;AACpD,SAAS,YAAY,eAAe;AAEpC,SAAS,kBAAkB,oBAAoB;AAC/C,SAAS,aAAqC;AAC9C,SAA4B,gBAAgB;AAC5C,SAAS,YAAY,oBAAoB;AACzC,SAAS,gBAAgB;AASlB,MAAM,cAAc;AAEpB,MAAM,cAAc,CAAC,UAC1B,OAAO,OAAO,IAAI,MAAM,WAAW,GAAG,EAAE,MAAM,UAAU,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC,EAAG,CAAC;AAEvF,MAAM,UAAU,MAAM,MAAM,QAAQ,OAAO,YAAY,CAAC;AAEjD,SAAS,SAAS,MAA+C;AACtE,MAAI,CAAC,QAAQ,KAAK,UAAU,UAAW,QAAO;AAC9C,SAAO,KAAK,UAAU,cAAc,KAAK,SAAS,KAAK,SAAS;AAClE;AAEO,MAAM,eAAe;AAErB,SAAS,QAAQ,MAA4B,SAAS,OAAyB;AACpF,QAAM,SAAS,SAAS,IAAI;AAC5B,QAAM,KAAK,MAAM;AACjB,MAAI,UAAU,WAAW,QAAQ,WAAW,UAAU,MAAM,SAAS,EAAE;AACrE,WAAO,EAAE,QAAQ,WAAW,KAAK;AACnC,MAAI,WAAW,UAAU,MAAM,UAAU,cAAc,KAAK,cA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AA,EACT,SAAS,OAAO;AACd,QAAI,SAAS,KAAK,EAAG,OAAM;AAC3B,WAAO;AAAA,EACT,UAAE;AACA,YAAQ,oBAAoB,SAAS,GAAG;AACxC,UAAM,oBAAoB,SAAS,GAAG;AACtC,UAAM,KAAK,MAAM;AAAA,EACnB;AACF;AAEA,eAAsB,QACpB,UACA,SACA,UAA0B,CAAC,GAC3B,MACoB;AACpB,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,OAAO,MAAM,KAAK,UAAU,IAAI;AACtC,MAAI;AACF,QAAI,QAAQ,WAAW,MAAM,QAAS,QAAO;AAC7C,UAAM,QAAQ,MAAM,KAAK,KAAK,QAAQ,SAAS,QAAQ,SAAS,MAAM,kBAAkB;AACxF,QAAI,MAAM,OAAO,KAAM,OAAM,IAAI,MAAM,MAAM,KAAK;AAClD,UAAM,UAAU,EAAE,QAAQ,MAAM,QAAQ,QAAQ,cAAc,KAAK;AACnE,UAAM,EAAE,QAAQ,QAAQ,IAAI,MAAM,QAAQ,KAAK,WAAW,MAAM,IAAI,SAAS,KAAK,KAAK;AACvF,QAAI,YAAY,UAAW,OAAM,SAAS,MAAM,MAAM,IAAI,QAAQ,SAAS;AAAA,aAClE;AACP,YAAM,QAAQ,KAAK;AAAA,QACjB,KAAK,KAAK,SAAS,MAAM,IAAI,OAAO,OAAO,GAAG,kBAAkB;AAAA,QAChE,MAAM,WAAW;AAAA,MACnB,CAAC;AACH,WAAO;AAAA,EACT,UAAE;AACA,UAAM,KAAK,MAAM;AAAA,EACnB;AACF;",
|
|
6
6
|
"names": ["halted"]
|
|
7
7
|
}
|
package/dist/approvals/sudo.js
CHANGED
|
@@ -11,7 +11,8 @@ function sudoRequest(value) {
|
|
|
11
11
|
const request = value;
|
|
12
12
|
if (typeof request !== "object" || request === null || request.kind !== "sudo") return null;
|
|
13
13
|
const { argv, user, expiresAt } = request;
|
|
14
|
-
if (!Array.isArray(argv) || !argv.
|
|
14
|
+
if (!Array.isArray(argv) || !argv.every(text)) return null;
|
|
15
|
+
if (!argv.length && request.validate !== true) return null;
|
|
15
16
|
if (!text(user) || typeof expiresAt !== "number" || !Number.isFinite(expiresAt)) return null;
|
|
16
17
|
return request;
|
|
17
18
|
}
|
|
@@ -74,7 +75,11 @@ function kernelFacts(request) {
|
|
|
74
75
|
...typeof request.always === "boolean" ? { writable: request.always } : {}
|
|
75
76
|
};
|
|
76
77
|
}
|
|
78
|
+
const validating = (request) => request.validate === true;
|
|
79
|
+
const timestampFor = (user) => `start a sudo timestamp for ${user} (no command)`;
|
|
77
80
|
function sudoDetail(request) {
|
|
81
|
+
if (validating(request))
|
|
82
|
+
return { command: timestampFor(request.user), validate: true, writable: false };
|
|
78
83
|
const command = [request.path || request.argv[0], ...request.argv.slice(1)].map((word) => shellWord(String(word))).join(" ");
|
|
79
84
|
return {
|
|
80
85
|
command,
|
|
@@ -87,15 +92,16 @@ function sudoDetail(request) {
|
|
|
87
92
|
function scoopLick(id, agentId, detail, agents) {
|
|
88
93
|
const scoop = agents?.scoops[agentId];
|
|
89
94
|
if (!scoop) return void 0;
|
|
90
|
-
const { command, target, cwd } = detail;
|
|
95
|
+
const { command, target, cwd, validate } = detail;
|
|
91
96
|
const as = target ? ` as ${target}` : "";
|
|
92
97
|
const at = cwd ? ` in ${cwd}` : "";
|
|
98
|
+
const asked = validate ? "to start a sudo timestamp" : `to run ${command}${as}${at}`;
|
|
93
99
|
return {
|
|
94
100
|
channel: "sudo-request",
|
|
95
101
|
source: id,
|
|
96
102
|
title: `${scoop.name} waits for sudo`,
|
|
97
103
|
text: `[scoop ${scoop.name} waits for a person to approve sudo]`,
|
|
98
|
-
body: `${scoop.name} asked
|
|
104
|
+
body: `${scoop.name} asked ${asked}. A person answers it in the approvals dialog; you can't approve it. It ends when someone answers or it times out.`,
|
|
99
105
|
target: `cone:${scoop.cone}`
|
|
100
106
|
};
|
|
101
107
|
}
|
|
@@ -127,7 +133,7 @@ function createSudo(options) {
|
|
|
127
133
|
agentId,
|
|
128
134
|
requester,
|
|
129
135
|
tier: "user",
|
|
130
|
-
always: request.always !== false,
|
|
136
|
+
always: request.always !== false && !validating(request),
|
|
131
137
|
expiresAt: request.expiresAt,
|
|
132
138
|
detail
|
|
133
139
|
},
|
|
@@ -184,6 +190,8 @@ export {
|
|
|
184
190
|
shellWord,
|
|
185
191
|
sudoDetail,
|
|
186
192
|
sudoRequest,
|
|
187
|
-
sudoRequester
|
|
193
|
+
sudoRequester,
|
|
194
|
+
timestampFor,
|
|
195
|
+
validating
|
|
188
196
|
};
|
|
189
197
|
//# sourceMappingURL=sudo.js.map
|