@ai-ecoverse/slicc-agent 7.33.2 → 7.34.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 +3 -2
- package/dist/approvals/run-licks.js +40 -22
- package/dist/approvals/run-licks.js.map +2 -2
- package/dist/approvals/run-notice.js +170 -0
- package/dist/approvals/run-notice.js.map +7 -0
- package/dist/client.js +3 -0
- package/dist/client.js.map +2 -2
- package/dist/control.js.map +2 -2
- package/dist/guests/client.js +1 -0
- package/dist/guests/client.js.map +2 -2
- package/dist/host.js +8 -2
- package/dist/host.js.map +2 -2
- package/dist/index.js +6 -0
- package/dist/index.js.map +2 -2
- package/dist/services.js +3 -1
- package/dist/services.js.map +2 -2
- package/dist/types/approvals/run-licks.d.ts +15 -3
- package/dist/types/approvals/run-notice.d.ts +63 -0
- package/dist/types/client.d.ts +2 -0
- package/dist/types/control.d.ts +1 -1
- package/dist/types/index.d.ts +1 -0
- package/dist/types/services.d.ts +3 -1
- package/package.json +7 -7
package/README.md
CHANGED
|
@@ -30,9 +30,9 @@ await agent.prompt('What is in /home?');
|
|
|
30
30
|
- `openOpfsSqliteStorage({ directory?, file? })` keeps the session in wasm SQLite ([`@sqlite.org/sqlite-wasm`](https://www.npmjs.com/package/@sqlite.org/sqlite-wasm)) in an `opfs-sahpool` pool, by default `/.slicc/agent/` in OPFS. It needs a dedicated worker. Only one worker holds a pool at a time: the opener takes a Web Lock per directory and waits until every file of the pool can be opened before sqlite-wasm installs it, because a failed install deletes the pool's directory. `openMemorySqliteStorage()` keeps the same database in memory. **Document bases.** Every session and conversation document the agent defines stores a complete base after 64 deltas (`boundedDeltas` in `src/checkpoints.ts`, the policy pi durable's codemode journal uses), so reading one replays at most 64 changes: with deltas only, a document changed 5,000 times took about 26 ms to read after a reopen, against under 1 ms. Task documents, which end with their task, keep deltas only. **Profile marker:** every open, under the pool's lock and before pi durable opens (and migrates) the database, writes `<directory>-profile.json` next to the pool, `/.slicc/agent-profile.json` by default: `{ "durableSchema": 2, "agent": "<version>" }`, with pi durable's `CURRENT_SQLITE_SCHEMA_VERSION` and the agent's version (the `agent` option, or the version in the agent's `package.json`). A `durableSchema` already in the file is never lowered. bios reads it from OPFS before it starts an agent, and refuses one whose pi durable schema is lower (slicc-agent 6.x is 1): the schema version lives in a `durable_schema` table, not in the SQLite header, so the database itself can't be checked without opening it. On pi durable 1.4, opening a database written by an earlier agent migrates it to durable's SQLite schema 2, once and in place; an agent on pi durable 1.3 or earlier (slicc-agent 6.19.13 and earlier) can't open it afterwards, so the agent can't be rolled back past this version. Requests through the Harness are attributed to SLICC (`identity: { attribution: { name: 'SLICC', url: 'https://www.sliccy.com' } }`), which pi-ai sends as OpenRouter's `HTTP-Referer` and `X-OpenRouter-Title`, NVIDIA's `X-BILLING-INVOKE-ORIGIN` and OpenCode's `x-opencode-client`; OpenRouter's preflight allows them from `https://seven.sliccy.ai`, and NVIDIA and OpenCode answer no browser preflight at all, so they go through a CORS-free transport either way. pi durable's crash-loop guard is on with its default: a task cut off 5 times in a row without committing a new state (a crash, a reload or `restart()`, which end the worker without closing the session) ends instead of being parked. A built-in generation, tool or compaction reports `task_interrupted`; any other task reports `task_faulted` with reason `restart_limit`. The monitor alerts that as an error and offers no command to resume it. `agent retry <task id>` says to submit the work again. Only the user may ask; an agent's `agent retry` is refused.
|
|
31
31
|
- `hostAgent(agent)` serves the agent from one Chord host named `agent` (`serveAgent` in [`src/host.ts`](src/host.ts)). Its remote contracts, in [`src/services.ts`](src/services.ts), are `slicc.agent.control` (send with `whenBusy` `steer`, `followUp` or `reject`, wait, withdraw, abort, compact) and `slicc.agent.transcript` (the conversation's durable view as replicated state, plus `deliveries`: how each user entry was delivered, `run`, `steer` or `follow-up`, derived by the host from where each send it accepted was placed: after a tool result it steered, queued first it's a follow-up or a late steer per its `whenBusy`, placed at once it started a run), `slicc.agent.settings`, `slicc.agent.remote` (remote control), `slicc.agent.pages` (Panels) and `slicc.agent.guest` (Guest seats). `serveConnections(self, host)` hands it every `MessagePort` the page sends, and each port becomes one Chord link whose principal is a seat: `owner` (a page of the owner, with its own Panels), `control` (a follower with Control), `view` (a follower without) or `guest` (a guest seat, with its id, label and epoch), plus the link's number, so every link gets its own objects. The principal is typed (`AgentPrincipal` in [`src/serving.ts`](src/serving.ts)); the host's own code acts as `{ seat: 'host' }`, which no link gets. Each factory picks a variant per seat. Every contract places its objects on the host `agent` (`hostNamed`), so no caller names a host. The contracts take their methods' arguments as one JSON array, and the client in [`src/serving.ts`](src/serving.ts) turns them back into the `AgentControl`, `AgentSettings`, `AgentRemote` and `AgentPages` interfaces and their replicated states, so callers don't see Chord.
|
|
32
32
|
- `@ai-ecoverse/slicc-agent/page` has what the page needs (`startAgent`, `connectAgent`) without the agent's runtime: no pi-durable, pi-ai, providers or SQLite, which load only in the worker. `@ai-ecoverse/slicc-agent/spectrum` is just as light, and a test keeps both that way.
|
|
33
|
-
- `startAgent({ worker })` takes the Web Lock `slicc-agent`, so one tab at a time owns the agent worker, and waits while another tab holds it. `connect()` returns an `AgentConnection` (`control`, `transcript`, `prompt()`,
|
|
33
|
+
- `startAgent({ worker })` takes the Web Lock `slicc-agent`, so one tab at a time owns the agent worker, and waits while another tab holds it. `connect()` returns an `AgentConnection` (`control`, `transcript`, `prompt()`, `webhook(name, { id?, headers?, body })`, which hands a webhook delivery, such as one from the tray hub, to the licks without a chord `Context`, and `approvalRunNotice(notice)`, see Run now), `restart()` replaces the worker (durable resumes from SQLite), and `release()` stops it and lets the next tab take over. `port()` returns a raw `MessagePort` into the worker instead, for another tab: hand it over (through a SharedWorker, say), and that tab calls `connectAgent(port)`. A caller that already holds the lock passes `held: true`. A connection's `closed` resolves when its port ends (with the error, if any), and from then on its states keep their last values.
|
|
34
34
|
- **Followers over a link** (PR 18): `port({ readOnly: true })` and `connect({ readOnly: true })` give a view-only connection, and `port({ pages: false })` a full one that never takes `panel` requests (see Panels).
|
|
35
|
-
- **What a view-only connection can do:** it sees the transcript, the agents, settings state and remote-control `watch`, and may call `wait` and `changesOpen`. It's still an owner device, so it has the owner-device methods (`OWNER_DEVICE_METHODS` in [`src/services.ts`](src/services.ts)) with the owner's powers: `decide`, `approvalRun`, `approvalRunStop`, `guestOpen`, `guestRevoke`, `guestAlwaysForget` and `approvalPolicySet`. Control gates driving, not approvals.
|
|
35
|
+
- **What a view-only connection can do:** it sees the transcript, the agents, settings state and remote-control `watch`, and may call `wait` and `changesOpen`. It's still an owner device, so it has the owner-device methods (`OWNER_DEVICE_METHODS` in [`src/services.ts`](src/services.ts)) with the owner's powers: `decide`, `approvalRun`, `approvalRunStop`, `approvalRunNotice`, `guestOpen`, `guestRevoke`, `guestAlwaysForget` and `approvalPolicySet`. Control gates driving, not approvals.
|
|
36
36
|
- **What it can't:** every other `AgentControl` method, settings action and remote-control `prompt` or `abort` is refused with `EACCES` ("this follower can watch, but not send, steer or abort"). Send and compact answer `accepted: false` with that code, and `addServer` and `removeServer` answer `not-owner`. The `view` seat's variants don't have those methods at all (`view` for control and settings, `watch` for remote control, `none` for Panels); the follower's client answers the missing ones with the refusals ([`src/readonly.ts`](src/readonly.ts)), so the worker never runs them. A `watch` stream is readable only over the link that opened it.
|
|
37
37
|
- **Carrying the connection over a byte stream:** `linkEndpoint({ write, close })` is a `PortEndpoint` that `connectAgent` accepts. Feed it the stream's bytes with `receive(bytes)` and its end with `end(error?)`. On the owner's side, `bridgePort(port, { write, close })` does the same for the `MessagePort` from `port()`.
|
|
38
38
|
- **The bytes:** the owner first posts a hello, its server id, then each Chord frame travels as its JSON text in UTF-8 (`PortLink` in [`src/wire.ts`](src/wire.ts)), and `{ close: true }` ends the port. The owner holds its own Chord frames until the client's Chord hello arrives, so it knows which Chord it talks to before it says anything. `PortLink.send` returns each frame's size, so Chord's flow control applies: once 256 KiB are unacknowledged, state waits at the owner, coalesced per member, instead of piling up in front of a slow WebRTC follower, while calls and results still pass. On a byte stream each message becomes a frame: a `u32` big-endian length, then a tag (0 data, 1 hello, 2 close), then the payload. A frame is at most 16 MiB, and a malformed one ends the link.
|
|
@@ -781,6 +781,7 @@ Every approval, of a guest's prompt, of a tool call in a run a guest started, of
|
|
|
781
781
|
- **At most once:** a task resumed after a worker restart while it was calling the kernel never calls again: it adopts the process from `ps` that carries the tag and runs as the target's uid, trying five times with backoff (250 ms doubling), and only then ends `failed` with "interrupted before it started". A resumed `running` one subscribes again and checks `ps`: gone without an exit is `done` with no status, and a kernel that booted since (`btime`, the page reloaded) is `failed` with "the page reloaded while it ran", unless a process with the tag is still alive, which it then keeps waiting for. A boot id that couldn't be read (`null`) is unknown, never a reload.
|
|
782
782
|
- **Stop:** `AgentControl.approvalRunStop(id)` sends `SIGTERM` to every live process with the run's tag, and `SIGKILL` 5 s later to those still there; a running run ends `stopped`. It also works on a `done` run that still has survivors. With no tagged process left it answers "Its processes are already gone." for a running run and "This request isn't running." otherwise, and without a process list "The kernel's process list isn't available, so it can't be stopped.". One stopped before the kernel was called never runs. The agent's own Stop (`Conversation.abort`) doesn't touch it, since it's the owner's run, not the agent's turn; aborting the task stops it.
|
|
783
783
|
- **Licks** go to `requester.agentId` (a scoop that's gone falls back to its cone, a frozen cone gets the frozen notice) on the channel `sudo-run`, from the item's id, never coalesced and once per `eventId` (`<id>:start`, `<id>:end`), with the taints of the request's tags, and both steer, so each wakes an idle agent. The start lick says the owner ran the timed-out request, when it asked and when it ran, the pid and the output path; the end lick has the exit status or signal, how long it took, any survivors and the full paths, never the output itself: the requester can write those files while the command runs, so the agent reads them with its own shell if it needs them, as normal tool output. It has `severity="warn"` unless it exited 0 with no survivors. When the requester is a scoop that has ended, both licks go to its cone and say so. Title, text and body go through the secrets redaction, then both go through `scrubbedLick`. The licks prompt section says a sudo-run lick reports a command the owner ran late, not a new request.
|
|
784
|
+
- **Run by bios:** a timed-out sudo that the owner runs from bios's own Approvals panel is bios's run, not the agent's, so bios reports it with `AgentControl.approvalRunNotice(notice)` (`connectAgent().approvalRunNotice(notice)` without a `Context`), once when it starts and once when it ends, and the agent tells the requester with the same `sudo-run` licks. Ids never collide: the agent's items are `apr-<uuid>`, bios's are `bios:<kernel id>`. It's an owner-device method (`OWNER_DEVICE_METHODS`), so every owner device, view-only ones included, may call it, and a guest seat can't. A process can't send it either: `agent send --lick=sudo-run` stays refused as the agent's own channel. The notice is facts, never text: `{ id, phase, agentId, command, requestedAt, at, tags, pid?, endedAt?, status?, signal?, survivors?, stopped?, capped?, stdout?, stderr? }`, `id` matching `bios:` (at most 128 characters), `phase` `start` or `end`, `agentId` the cone or scoop that asked, `command` the typed command (at most 1024 characters, control characters shown as spaces), the times in ms, `status` 0 to 255, `signal` a name such as `SIGTERM`, `survivors` at most 64 pids, `stopped` for one the owner stopped, `capped` the output cap in bytes it passed, `stdout` and `stderr` absolute paths (at most 1024 characters), and `tags`, required, at most 16 kernel tags, whose taints the licks carry as for `replay.tag`: bios must pass the kernel's tags for the run exactly (`[]` when it has none), so leaving them out can't drop a taint. Any other key, a wrong type, an oversized field, or a control character or line or paragraph separator (U+2028, U+2029) in `agentId`, a path or a tag is refused. The agent takes `agentId`, `command` and `tags` from the owner device on trust, as it does for `decide`: it can't check a run that bios held. The agent renders both licks itself with the templates above (`<id>:start`, `<id>:end`, source `id`, never coalesced, never the output), to the same target: the requester, its cone when the scoop has ended. It answers `{ delivered, reason? }` and never throws for a missing target: `delivered` is `false` with the sentence when the notice is malformed (such as "A run notice id is bios:<kernel id>." or "A run notice has no channel field."), when that `eventId` was already delivered ("This notice was already delivered.", so a retry never tells the agent twice), for a `start` after that id's `end` was delivered ("This run already ended.", so the agent is never told it runs after it exited), when the agent is gone ("The agent that asked is gone, so nobody was told.") or its cone is frozen ("<cone> is frozen, so nobody was told."). A run that never started sends no notice, as nothing ran.
|
|
784
785
|
- **In spectrum,** the adapter's `history()` lists every item, newest first, as an `ApprovalRecord` `{ approval, state, reason?, decidedBy?, device?, decidedAt?, answer?, run?, runnable? }` (`run` without `pgid` and `stopBy`, with `survivors` when there are some, `runnable` from `approvalRunnable`), with a `history` event when it changes; `run(id)` and `stopRun(id)` reject with the agent's sentence. Every owner device's adapter has all three, a guest connection's has none. With `approvals: biosPort`, the adapter merges bios's `history()` in and sends `run` and `stopRun` to whichever side listed the id. A `sudo-run` lick card carries `approval`, the item's id.
|
|
785
786
|
- **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.
|
|
786
787
|
- **Who started it** comes only from the kernel's stamp: its `tags`, plus the taints the agent has seen alive for that process (`stamp.pid`) since it first saw it, the `recent` set the `agent` CLI uses ([`src/kernel/lineage.ts`](src/kernel/lineage.ts)). So a clean process that a guest's process sets off counts as the guest's while that cover holds: while a tagged process of the guest, or a `crontab` line it installed, lives, and for about 2 s after it ends (the agent's `ps` reads). Something the guest planted that runs later, such as a sprinkle CGI, a `~/.bashrc` line or a git hook, is attributed to whoever starts it then. As for the `agent` CLI, this is conservative: while a guest's leftover job or `crontab` line lives, everyone's captures are reviewed too. When the agent has no lineage provider or can't read the process's lineage, it denies.
|
|
@@ -68,14 +68,27 @@ function handedOn(state, agentId) {
|
|
|
68
68
|
if (!scoop || live(scoop) || scoop.frozen) return [];
|
|
69
69
|
return [`The scoop that asked, ${scoop.name}, has ended, so this goes to its cone.`];
|
|
70
70
|
}
|
|
71
|
-
|
|
71
|
+
function itemFacts(item) {
|
|
72
|
+
const run = item.run;
|
|
72
73
|
const replay = item.replay;
|
|
73
|
-
|
|
74
|
-
|
|
74
|
+
return {
|
|
75
|
+
id: item.id,
|
|
76
|
+
agentId: item.requester.agentId,
|
|
77
|
+
typed: typed(item),
|
|
78
|
+
where: where(item),
|
|
79
|
+
requestedAt: item.createdAt,
|
|
80
|
+
run,
|
|
81
|
+
tags: [...replay?.tag ? [replay.tag] : [], ...replay?.tags ?? []],
|
|
82
|
+
started: ` Output: ${run.stdout} (.err)`,
|
|
83
|
+
ended: ` Read it with your shell if you need it: ${run.stdout} and ${run.stderr} (kept for ${KEEP_HOURS} h).`
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
async function lickBase(host, facts) {
|
|
87
|
+
const taints = await taggedTaints(host.harness, facts.tags, BACKGROUND_CONTEXT);
|
|
75
88
|
return {
|
|
76
89
|
channel: "sudo-run",
|
|
77
|
-
source:
|
|
78
|
-
target: agentTarget(host.agents.state(),
|
|
90
|
+
source: facts.id,
|
|
91
|
+
target: agentTarget(host.agents.state(), facts.agentId),
|
|
79
92
|
coalesce: false,
|
|
80
93
|
...taints.length ? { taints } : {}
|
|
81
94
|
};
|
|
@@ -88,39 +101,43 @@ function clean(event) {
|
|
|
88
101
|
body: redacted(event.body)
|
|
89
102
|
};
|
|
90
103
|
}
|
|
91
|
-
|
|
92
|
-
|
|
104
|
+
const factsOf = (from) => "kind" in from ? itemFacts(from) : from;
|
|
105
|
+
async function startLick(host, from) {
|
|
106
|
+
const facts = factsOf(from);
|
|
107
|
+
const { run } = facts;
|
|
93
108
|
const now = host.now?.() ?? Date.now();
|
|
109
|
+
const pid = run.pid !== void 0 ? ` (pid ${run.pid})` : "";
|
|
94
110
|
return clean({
|
|
95
|
-
...await lickBase(host,
|
|
96
|
-
eventId: `${
|
|
97
|
-
title: `sudo runs now: ${typed
|
|
111
|
+
...await lickBase(host, facts),
|
|
112
|
+
eventId: `${facts.id}:start`,
|
|
113
|
+
title: `sudo runs now: ${facts.typed}`,
|
|
98
114
|
text: "[the owner ran your timed-out sudo request]",
|
|
99
115
|
body: [
|
|
100
|
-
`Your sudo request from ${clock(
|
|
101
|
-
`The owner ran it at ${clock(run.at, now)} with Run now. It runs in the background
|
|
102
|
-
`Its result follows as another sudo-run lick
|
|
103
|
-
...handedOn(host.agents.state(),
|
|
116
|
+
`Your sudo request from ${clock(facts.requestedAt, now)} (${facts.where}) timed out.`,
|
|
117
|
+
`The owner ran it at ${clock(run.at, now)} with Run now. It runs in the background${pid}, with no terminal and no input.`,
|
|
118
|
+
`Its result follows as another sudo-run lick.${facts.started}`,
|
|
119
|
+
...handedOn(host.agents.state(), facts.agentId)
|
|
104
120
|
].join("\n")
|
|
105
121
|
});
|
|
106
122
|
}
|
|
107
|
-
async function endLick(host,
|
|
108
|
-
const
|
|
123
|
+
async function endLick(host, from) {
|
|
124
|
+
const facts = factsOf(from);
|
|
125
|
+
const { run } = facts;
|
|
109
126
|
const ran = outcome(run);
|
|
110
127
|
const took = run.endedAt !== void 0 ? ` after ${duration(run.endedAt - run.at)}` : "";
|
|
111
128
|
const left = run.survivors?.length ? [
|
|
112
129
|
`Still running: pid ${run.survivors.join(", ")}. They left its process group; the owner can end them with Stop in Approvals.`
|
|
113
130
|
] : [];
|
|
114
131
|
return clean({
|
|
115
|
-
...await lickBase(host,
|
|
116
|
-
eventId: `${
|
|
117
|
-
title: `sudo run ended: ${typed
|
|
132
|
+
...await lickBase(host, facts),
|
|
133
|
+
eventId: `${facts.id}:end`,
|
|
134
|
+
title: `sudo run ended: ${facts.typed}`,
|
|
118
135
|
text: `[your late sudo run ended: ${ran.text}]`,
|
|
119
136
|
body: [
|
|
120
|
-
`${where
|
|
137
|
+
`${facts.where} ${ran.sentence}${took}.`,
|
|
121
138
|
...left,
|
|
122
|
-
`Its output isn't shown here
|
|
123
|
-
...handedOn(host.agents.state(),
|
|
139
|
+
`Its output isn't shown here.${facts.ended}`,
|
|
140
|
+
...handedOn(host.agents.state(), facts.agentId)
|
|
124
141
|
].join("\n"),
|
|
125
142
|
...ran.ok && !left.length ? {} : { severity: "warn" }
|
|
126
143
|
});
|
|
@@ -131,6 +148,7 @@ export {
|
|
|
131
148
|
clock,
|
|
132
149
|
duration,
|
|
133
150
|
endLick,
|
|
151
|
+
itemFacts,
|
|
134
152
|
sized,
|
|
135
153
|
startLick
|
|
136
154
|
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/approvals/run-licks.ts"],
|
|
4
|
-
"sourcesContent": ["import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Harness } from '@earendil-works/pi-durable';\nimport { type AgentsState, live } from '../agents.ts';\nimport { taggedTaints } from '../guests/tags.ts';\nimport type { LickEvent } from '../licks/licks.ts';\nimport { redactSecrets } from '../memory/format.ts';\nimport type { SudoApproval, SudoRun } from './record.ts';\nimport { agentTarget } from './runnable.ts';\nimport { shellWord } from './sudo.ts';\n\nexport const KEEP_HOURS = 24;\nexport const MIB = 1024 * 1024;\n\nexport type LickHost = {\n harness: Pick<Harness, 'commit' | 'snapshot'>;\n agents: { state(): Readonly<AgentsState> };\n now?: () => number;\n};\n\nconst redacted = (text: string) => redactSecrets(text).text;\n\nexport const sized = (bytes: number): string =>\n bytes % MIB === 0 ? `${bytes / MIB} MiB` : `${Math.round(bytes / 1024)} KiB`;\n\nfunction typed(item: SudoApproval): string {\n return (item.replay?.argv ?? [])\n .map((word) => shellWord(String(word)))\n .join(' ')\n .trim();\n}\n\nfunction where(item: SudoApproval): string {\n const { command, target, cwd } = item.detail;\n return `${command} as ${target ?? 'root'}${cwd ? ` in ${cwd}` : ''}`;\n}\n\nconst pad = (value: number) => String(value).padStart(2, '0');\n\nexport function clock(at: number, now: number): string {\n const when = new Date(at);\n const time = `${pad(when.getHours())}:${pad(when.getMinutes())}`;\n if (when.toDateString() === new Date(now).toDateString()) return time;\n return `${when.getFullYear()}-${pad(when.getMonth() + 1)}-${pad(when.getDate())} ${time}`;\n}\n\nexport function duration(ms: number): string {\n const seconds = Math.max(0, Math.round(ms / 1000));\n if (seconds < 60) return `${seconds} s`;\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes} min ${seconds % 60} s`;\n return `${Math.floor(minutes / 60)} h ${minutes % 60} min`;\n}\n\nfunction outcome(run: SudoRun): { text: string; sentence: string; ok: boolean } {\n if (run.state === 'failed')\n return { text: run.error ?? 'failed', sentence: `didn't finish: ${run.error}`, ok: false };\n const signal = run.signal ? ` (${run.signal})` : '';\n if (run.capped)\n return {\n text: `stopped: its output passed ${sized(run.capped)}`,\n sentence: `was stopped because its output passed ${sized(run.capped)}${signal}`,\n ok: false,\n };\n if (run.state === 'stopped')\n return {\n text: 'stopped by the owner',\n sentence: `was stopped by the owner${signal}`,\n ok: false,\n };\n if (run.status === undefined)\n return {\n text: 'status unknown',\n sentence: 'ended while the agent was away, so its exit status is unknown',\n ok: false,\n };\n if (run.signal)\n return {\n text: `killed by ${run.signal}`,\n sentence: `was killed by ${run.signal} (status ${run.status})`,\n ok: false,\n };\n return {\n text: `exit ${run.status}`,\n sentence: `exited with status ${run.status}`,\n ok: run.status === 0,\n };\n}\n\nfunction handedOn(state: Readonly<AgentsState>, agentId: string): string[] {\n const scoop = agentId.startsWith('scoop:') ? state.scoops[agentId] : undefined;\n if (!scoop || live(scoop) || scoop.frozen) return [];\n return [`The scoop that asked, ${scoop.name}, has ended, so this goes to its cone.`];\n}\n\
|
|
5
|
-
"mappings": "AAAA,SAAS,0BAA0B;AAEnC,SAA2B,YAAY;AACvC,SAAS,oBAAoB;AAE7B,SAAS,qBAAqB;AAE9B,SAAS,mBAAmB;AAC5B,SAAS,iBAAiB;AAEnB,MAAM,aAAa;AACnB,MAAM,MAAM,OAAO;AAQ1B,MAAM,WAAW,CAAC,SAAiB,cAAc,IAAI,EAAE;AAEhD,MAAM,QAAQ,CAAC,UACpB,QAAQ,QAAQ,IAAI,GAAG,QAAQ,GAAG,SAAS,GAAG,KAAK,MAAM,QAAQ,IAAI,CAAC;AAExE,SAAS,MAAM,MAA4B;AACzC,UAAQ,KAAK,QAAQ,QAAQ,CAAC,GAC3B,IAAI,CAAC,SAAS,UAAU,OAAO,IAAI,CAAC,CAAC,EACrC,KAAK,GAAG,EACR,KAAK;AACV;AAEA,SAAS,MAAM,MAA4B;AACzC,QAAM,EAAE,S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IAAI,UAAU;AAChB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,UAAU,2BAA2B,MAAM;AAAA,MAC3C,IAAI;AAAA,IACN;AACF,MAAI,IAAI,WAAW;AACjB,WAAO;AAAA,MACL,MAAM;AAAA,MACN,UAAU;AAAA,MACV,IAAI;AAAA,IACN;AACF,MAAI,IAAI;AACN,WAAO;AAAA,MACL,MAAM,aAAa,IAAI,MAAM;AAAA,MAC7B,UAAU,iBAAiB,IAAI,MAAM,YAAY,IAAI,MAAM;AAAA,MAC3D,IAAI;AAAA,IACN;AACF,SAAO;AAAA,IACL,MAAM,QAAQ,IAAI,MAAM;AAAA,IACxB,UAAU,sBAAsB,IAAI,MAAM;AAAA,IAC1C,IAAI,IAAI,WAAW;AAAA,EACrB;AACF;AAEA,SAAS,SAAS,OAA8B,SAA2B;AACzE,QAAM,QAAQ,QAAQ,WAAW,QAAQ,IAAI,MAAM,OAAO,OAAO,IAAI;AACrE,MAAI,CAAC,SAAS,KAAK,KAAK,KAAK,MAAM,OAAQ,QAAO,CAAC;AACnD,SAAO,CAAC,yBAAyB,MAAM,IAAI,wCAAwC;AACrF;
|
|
4
|
+
"sourcesContent": ["import { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Harness } from '@earendil-works/pi-durable';\nimport { type AgentsState, live } from '../agents.ts';\nimport { taggedTaints } from '../guests/tags.ts';\nimport type { LickEvent } from '../licks/licks.ts';\nimport { redactSecrets } from '../memory/format.ts';\nimport type { SudoApproval, SudoRun } from './record.ts';\nimport { agentTarget } from './runnable.ts';\nimport { shellWord } from './sudo.ts';\n\nexport const KEEP_HOURS = 24;\nexport const MIB = 1024 * 1024;\n\nexport type LickHost = {\n harness: Pick<Harness, 'commit' | 'snapshot'>;\n agents: { state(): Readonly<AgentsState> };\n now?: () => number;\n};\n\nconst redacted = (text: string) => redactSecrets(text).text;\n\nexport const sized = (bytes: number): string =>\n bytes % MIB === 0 ? `${bytes / MIB} MiB` : `${Math.round(bytes / 1024)} KiB`;\n\nfunction typed(item: SudoApproval): string {\n return (item.replay?.argv ?? [])\n .map((word) => shellWord(String(word)))\n .join(' ')\n .trim();\n}\n\nfunction where(item: SudoApproval): string {\n const { command, target, cwd } = item.detail;\n return `${command} as ${target ?? 'root'}${cwd ? ` in ${cwd}` : ''}`;\n}\n\nconst pad = (value: number) => String(value).padStart(2, '0');\n\nexport function clock(at: number, now: number): string {\n const when = new Date(at);\n const time = `${pad(when.getHours())}:${pad(when.getMinutes())}`;\n if (when.toDateString() === new Date(now).toDateString()) return time;\n return `${when.getFullYear()}-${pad(when.getMonth() + 1)}-${pad(when.getDate())} ${time}`;\n}\n\nexport function duration(ms: number): string {\n const seconds = Math.max(0, Math.round(ms / 1000));\n if (seconds < 60) return `${seconds} s`;\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes} min ${seconds % 60} s`;\n return `${Math.floor(minutes / 60)} h ${minutes % 60} min`;\n}\n\nfunction outcome(run: SudoRun): { text: string; sentence: string; ok: boolean } {\n if (run.state === 'failed')\n return { text: run.error ?? 'failed', sentence: `didn't finish: ${run.error}`, ok: false };\n const signal = run.signal ? ` (${run.signal})` : '';\n if (run.capped)\n return {\n text: `stopped: its output passed ${sized(run.capped)}`,\n sentence: `was stopped because its output passed ${sized(run.capped)}${signal}`,\n ok: false,\n };\n if (run.state === 'stopped')\n return {\n text: 'stopped by the owner',\n sentence: `was stopped by the owner${signal}`,\n ok: false,\n };\n if (run.status === undefined)\n return {\n text: 'status unknown',\n sentence: 'ended while the agent was away, so its exit status is unknown',\n ok: false,\n };\n if (run.signal)\n return {\n text: `killed by ${run.signal}`,\n sentence: `was killed by ${run.signal} (status ${run.status})`,\n ok: false,\n };\n return {\n text: `exit ${run.status}`,\n sentence: `exited with status ${run.status}`,\n ok: run.status === 0,\n };\n}\n\nfunction handedOn(state: Readonly<AgentsState>, agentId: string): string[] {\n const scoop = agentId.startsWith('scoop:') ? state.scoops[agentId] : undefined;\n if (!scoop || live(scoop) || scoop.frozen) return [];\n return [`The scoop that asked, ${scoop.name}, has ended, so this goes to its cone.`];\n}\n\nexport type RunFacts = {\n id: string;\n agentId: string;\n typed: string;\n where: string;\n requestedAt: number;\n run: SudoRun;\n tags: readonly string[];\n started: string;\n ended: string;\n};\n\nexport function itemFacts(item: SudoApproval): RunFacts {\n const run = item.run as SudoRun;\n const replay = item.replay;\n return {\n id: item.id,\n agentId: item.requester.agentId as string,\n typed: typed(item),\n where: where(item),\n requestedAt: item.createdAt,\n run,\n tags: [...(replay?.tag ? [replay.tag] : []), ...(replay?.tags ?? [])],\n started: ` Output: ${run.stdout} (.err)`,\n ended: ` Read it with your shell if you need it: ${run.stdout} and ${run.stderr} (kept for ${KEEP_HOURS} h).`,\n };\n}\n\nasync function lickBase(host: LickHost, facts: RunFacts) {\n const taints = await taggedTaints(host.harness, facts.tags, BACKGROUND_CONTEXT);\n return {\n channel: 'sudo-run' as const,\n source: facts.id,\n target: agentTarget(host.agents.state(), facts.agentId),\n coalesce: false,\n ...(taints.length ? { taints } : {}),\n };\n}\n\nfunction clean(event: LickEvent): LickEvent {\n return {\n ...event,\n title: redacted(event.title),\n text: redacted(event.text),\n body: redacted(event.body as string),\n };\n}\n\nconst factsOf = (from: SudoApproval | RunFacts): RunFacts =>\n 'kind' in from ? itemFacts(from) : from;\n\nexport async function startLick(host: LickHost, from: SudoApproval | RunFacts): Promise<LickEvent> {\n const facts = factsOf(from);\n const { run } = facts;\n const now = host.now?.() ?? Date.now();\n const pid = run.pid !== undefined ? ` (pid ${run.pid})` : '';\n return clean({\n ...(await lickBase(host, facts)),\n eventId: `${facts.id}:start`,\n title: `sudo runs now: ${facts.typed}`,\n text: '[the owner ran your timed-out sudo request]',\n body: [\n `Your sudo request from ${clock(facts.requestedAt, now)} (${facts.where}) timed out.`,\n `The owner ran it at ${clock(run.at, now)} with Run now. It runs in the background${pid}, with no terminal and no input.`,\n `Its result follows as another sudo-run lick.${facts.started}`,\n ...handedOn(host.agents.state(), facts.agentId),\n ].join('\\n'),\n });\n}\n\nexport async function endLick(host: LickHost, from: SudoApproval | RunFacts): Promise<LickEvent> {\n const facts = factsOf(from);\n const { run } = facts;\n const ran = outcome(run);\n const took = run.endedAt !== undefined ? ` after ${duration(run.endedAt - run.at)}` : '';\n const left = run.survivors?.length\n ? [\n `Still running: pid ${run.survivors.join(', ')}. They left its process group; the owner can end them with Stop in Approvals.`,\n ]\n : [];\n return clean({\n ...(await lickBase(host, facts)),\n eventId: `${facts.id}:end`,\n title: `sudo run ended: ${facts.typed}`,\n text: `[your late sudo run ended: ${ran.text}]`,\n body: [\n `${facts.where} ${ran.sentence}${took}.`,\n ...left,\n `Its output isn't shown here.${facts.ended}`,\n ...handedOn(host.agents.state(), facts.agentId),\n ].join('\\n'),\n ...(ran.ok && !left.length ? {} : { severity: 'warn' as const }),\n });\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,0BAA0B;AAEnC,SAA2B,YAAY;AACvC,SAAS,oBAAoB;AAE7B,SAAS,qBAAqB;AAE9B,SAAS,mBAAmB;AAC5B,SAAS,iBAAiB;AAEnB,MAAM,aAAa;AACnB,MAAM,MAAM,OAAO;AAQ1B,MAAM,WAAW,CAAC,SAAiB,cAAc,IAAI,EAAE;AAEhD,MAAM,QAAQ,CAAC,UACpB,QAAQ,QAAQ,IAAI,GAAG,QAAQ,GAAG,SAAS,GAAG,KAAK,MAAM,QAAQ,IAAI,CAAC;AAExE,SAAS,MAAM,MAA4B;AACzC,UAAQ,KAAK,QAAQ,QAAQ,CAAC,GAC3B,IAAI,CAAC,SAAS,UAAU,OAAO,IAAI,CAAC,CAAC,EACrC,KAAK,GAAG,EACR,KAAK;AACV;AAEA,SAAS,MAAM,MAA4B;AACzC,QAAM,EAAE,SAAS,QAAQ,IAAI,IAAI,KAAK;AACtC,SAAO,GAAG,OAAO,OAAO,UAAU,MAAM,GAAG,MAAM,OAAO,GAAG,KAAK,EAAE;AACpE;AAEA,MAAM,MAAM,CAAC,UAAkB,OAAO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xB;AAAA,IACE,sBAAsB,IAAI,UAAU,KAAK,IAAI,CAAC;AAAA,EAChD,IACA,CAAC;AACL,SAAO,MAAM;AAAA,IACX,GAAI,MAAM,SAAS,MAAM,KAAK;AAAA,IAC9B,SAAS,GAAG,MAAM,EAAE;AAAA,IACpB,OAAO,mBAAmB,MAAM,KAAK;AAAA,IACrC,MAAM,8BAA8B,IAAI,IAAI;AAAA,IAC5C,MAAM;AAAA,MACJ,GAAG,MAAM,KAAK,IAAI,IAAI,QAAQ,GAAG,IAAI;AAAA,MACrC,GAAG;AAAA,MACH,+BAA+B,MAAM,KAAK;AAAA,MAC1C,GAAG,SAAS,KAAK,OAAO,MAAM,GAAG,MAAM,OAAO;AAAA,IAChD,EAAE,KAAK,IAAI;AAAA,IACX,GAAI,IAAI,MAAM,CAAC,KAAK,SAAS,CAAC,IAAI,EAAE,UAAU,OAAgB;AAAA,EAChE,CAAC;AACH;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
2
|
+
import { LicksOutbox } from "../licks/licks.js";
|
|
3
|
+
import { endLick, startLick } from "./run-licks.js";
|
|
4
|
+
import { frozenOf, goneOf } from "./runnable.js";
|
|
5
|
+
const NOTICE_LIMITS = {
|
|
6
|
+
id: 128,
|
|
7
|
+
agentId: 256,
|
|
8
|
+
command: 1024,
|
|
9
|
+
path: 1024,
|
|
10
|
+
tag: 256,
|
|
11
|
+
tags: 16,
|
|
12
|
+
survivors: 64
|
|
13
|
+
};
|
|
14
|
+
const NOTICE_REASONS = {
|
|
15
|
+
shape: "A run notice is an object.",
|
|
16
|
+
id: "A run notice id is bios:<kernel id>.",
|
|
17
|
+
phase: "A run notice phase is start or end.",
|
|
18
|
+
agentId: "A run notice needs the agentId of the cone or scoop that asked.",
|
|
19
|
+
command: `A run notice needs its command, at most ${NOTICE_LIMITS.command} characters.`,
|
|
20
|
+
time: "A run notice needs requestedAt and at as times.",
|
|
21
|
+
endedAt: "endedAt is a time, no earlier than at.",
|
|
22
|
+
pid: "pid is a process id.",
|
|
23
|
+
status: "status is an exit status from 0 to 255.",
|
|
24
|
+
signal: "signal is a signal name such as SIGTERM.",
|
|
25
|
+
survivors: `survivors is a list of at most ${NOTICE_LIMITS.survivors} process ids.`,
|
|
26
|
+
stopped: "stopped is true or false.",
|
|
27
|
+
capped: "capped is a size in bytes.",
|
|
28
|
+
path: `stdout and stderr are absolute paths, at most ${NOTICE_LIMITS.path} characters.`,
|
|
29
|
+
tagsMissing: "A run notice needs tags, the kernel's tags for the run exactly (an empty list when it has none).",
|
|
30
|
+
tags: `tags is a list of at most ${NOTICE_LIMITS.tags} tags of at most ${NOTICE_LIMITS.tag} characters.`,
|
|
31
|
+
licks: "This agent has no licks.",
|
|
32
|
+
gone: "The agent that asked is gone, so nobody was told.",
|
|
33
|
+
seen: "This notice was already delivered.",
|
|
34
|
+
ended: "This run already ended.",
|
|
35
|
+
failed: "The notice couldn't be delivered."
|
|
36
|
+
};
|
|
37
|
+
const unknownKey = (key) => `A run notice has no ${key.slice(0, 64)} field.`;
|
|
38
|
+
const frozenNoticed = (name) => `${name} is frozen, so nobody was told.`;
|
|
39
|
+
const KEYS = /* @__PURE__ */ new Set([
|
|
40
|
+
"id",
|
|
41
|
+
"phase",
|
|
42
|
+
"agentId",
|
|
43
|
+
"command",
|
|
44
|
+
"requestedAt",
|
|
45
|
+
"at",
|
|
46
|
+
"pid",
|
|
47
|
+
"endedAt",
|
|
48
|
+
"status",
|
|
49
|
+
"signal",
|
|
50
|
+
"survivors",
|
|
51
|
+
"stopped",
|
|
52
|
+
"capped",
|
|
53
|
+
"stdout",
|
|
54
|
+
"stderr",
|
|
55
|
+
"tags"
|
|
56
|
+
]);
|
|
57
|
+
const ID = /^bios:[\w.:-]+$/;
|
|
58
|
+
const AGENT = /^[^\s\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+$/u;
|
|
59
|
+
const PATH = /^\/[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]*$/u;
|
|
60
|
+
const TAG = /^[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+$/u;
|
|
61
|
+
const SIGNAL = /^SIG[A-Z0-9+-]{1,12}$/;
|
|
62
|
+
const shown = (text2) => text2.replace(/[\p{Cc}\p{Cf}]/gu, " ").replace(/\s+/g, " ").trim();
|
|
63
|
+
const time = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
64
|
+
const whole = (value, least) => typeof value === "number" && Number.isSafeInteger(value) && value >= least;
|
|
65
|
+
const text = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max;
|
|
66
|
+
const list = (value, max, each) => Array.isArray(value) && value.length <= max && value.every(each);
|
|
67
|
+
const path = (value) => text(value, NOTICE_LIMITS.path) && PATH.test(value);
|
|
68
|
+
const CHECKS = [
|
|
69
|
+
["pid", (value) => whole(value, 1)],
|
|
70
|
+
["endedAt", (value, notice) => time(value) && value >= notice.at],
|
|
71
|
+
["status", (value) => whole(value, 0) && value <= 255],
|
|
72
|
+
["signal", (value) => typeof value === "string" && SIGNAL.test(value)],
|
|
73
|
+
["survivors", (value) => list(value, NOTICE_LIMITS.survivors, (one) => whole(one, 1))],
|
|
74
|
+
["stopped", (value) => typeof value === "boolean"],
|
|
75
|
+
["capped", (value) => whole(value, 1)],
|
|
76
|
+
["stdout", path],
|
|
77
|
+
["stderr", path],
|
|
78
|
+
[
|
|
79
|
+
"tags",
|
|
80
|
+
(value) => list(value, NOTICE_LIMITS.tags, (one) => text(one, NOTICE_LIMITS.tag) && TAG.test(one))
|
|
81
|
+
]
|
|
82
|
+
];
|
|
83
|
+
const REASON_OF = {
|
|
84
|
+
...NOTICE_REASONS,
|
|
85
|
+
stdout: NOTICE_REASONS.path,
|
|
86
|
+
stderr: NOTICE_REASONS.path
|
|
87
|
+
};
|
|
88
|
+
function optional(notice) {
|
|
89
|
+
const bad = CHECKS.find(
|
|
90
|
+
([key, check]) => notice[key] !== void 0 && !check(notice[key], notice)
|
|
91
|
+
);
|
|
92
|
+
return bad ? REASON_OF[bad[0]] : void 0;
|
|
93
|
+
}
|
|
94
|
+
function checkNotice(raw) {
|
|
95
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return NOTICE_REASONS.shape;
|
|
96
|
+
const notice = raw;
|
|
97
|
+
const extra = Object.keys(notice).find((key) => !KEYS.has(key));
|
|
98
|
+
if (extra !== void 0) return unknownKey(extra);
|
|
99
|
+
const { id, phase, agentId, command } = notice;
|
|
100
|
+
if (!(text(id, NOTICE_LIMITS.id) && ID.test(id))) return NOTICE_REASONS.id;
|
|
101
|
+
if (phase !== "start" && phase !== "end") return NOTICE_REASONS.phase;
|
|
102
|
+
if (!(text(agentId, NOTICE_LIMITS.agentId) && AGENT.test(agentId))) return NOTICE_REASONS.agentId;
|
|
103
|
+
if (!(text(command, NOTICE_LIMITS.command) && shown(command))) return NOTICE_REASONS.command;
|
|
104
|
+
if (!time(notice.requestedAt) || !time(notice.at)) return NOTICE_REASONS.time;
|
|
105
|
+
if (!Array.isArray(notice.tags)) return NOTICE_REASONS.tagsMissing;
|
|
106
|
+
return optional(notice) ?? notice;
|
|
107
|
+
}
|
|
108
|
+
function factsOf(notice, agentId) {
|
|
109
|
+
const paths = [notice.stdout, notice.stderr].filter((path2) => !!path2);
|
|
110
|
+
const run = {
|
|
111
|
+
state: notice.stopped ? "stopped" : "done",
|
|
112
|
+
by: "owner",
|
|
113
|
+
at: notice.at,
|
|
114
|
+
...notice.pid !== void 0 ? { pid: notice.pid } : {},
|
|
115
|
+
...notice.endedAt !== void 0 ? { endedAt: notice.endedAt } : {},
|
|
116
|
+
...notice.status !== void 0 ? { status: notice.status } : {},
|
|
117
|
+
...notice.signal ? { signal: notice.signal } : {},
|
|
118
|
+
...notice.survivors?.length ? { survivors: notice.survivors } : {},
|
|
119
|
+
...notice.capped ? { capped: notice.capped } : {}
|
|
120
|
+
};
|
|
121
|
+
const command = shown(notice.command);
|
|
122
|
+
return {
|
|
123
|
+
id: notice.id,
|
|
124
|
+
agentId,
|
|
125
|
+
typed: command,
|
|
126
|
+
where: command,
|
|
127
|
+
requestedAt: notice.requestedAt,
|
|
128
|
+
run,
|
|
129
|
+
tags: notice.tags,
|
|
130
|
+
started: paths.length ? ` Output: ${paths.join(" and ")}` : "",
|
|
131
|
+
ended: paths.length ? ` Read it with your shell if you need it: ${paths.join(" and ")}.` : ""
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
async function seen(host, id, eventId, context) {
|
|
135
|
+
const events = (await host.harness.snapshot(LicksOutbox, context))?.events ?? {};
|
|
136
|
+
return (events[`sudo-run|${id}`] ?? []).includes(eventId);
|
|
137
|
+
}
|
|
138
|
+
async function deliverNotice(host, raw) {
|
|
139
|
+
const notice = checkNotice(raw);
|
|
140
|
+
if (typeof notice === "string") return { delivered: false, reason: notice };
|
|
141
|
+
const licks = host.licks;
|
|
142
|
+
if (!licks) return { delivered: false, reason: NOTICE_REASONS.licks };
|
|
143
|
+
const agentId = notice.agentId.startsWith("cone:") ? notice.agentId.slice("cone:".length) : notice.agentId;
|
|
144
|
+
const state = () => host.agents.state();
|
|
145
|
+
const frozen = frozenOf(state)(agentId);
|
|
146
|
+
if (frozen) return { delivered: false, reason: frozenNoticed(frozen) };
|
|
147
|
+
if (goneOf(state)(agentId)) return { delivered: false, reason: NOTICE_REASONS.gone };
|
|
148
|
+
const eventId = `${notice.id}:${notice.phase}`;
|
|
149
|
+
try {
|
|
150
|
+
if (notice.phase === "start" && await seen(host, notice.id, `${notice.id}:end`, BACKGROUND_CONTEXT))
|
|
151
|
+
return { delivered: false, reason: NOTICE_REASONS.ended };
|
|
152
|
+
if (await seen(host, notice.id, eventId, BACKGROUND_CONTEXT))
|
|
153
|
+
return { delivered: false, reason: NOTICE_REASONS.seen };
|
|
154
|
+
const facts = factsOf(notice, agentId);
|
|
155
|
+
const event = await (notice.phase === "start" ? startLick : endLick)(host, facts);
|
|
156
|
+
await licks.deliver(event, BACKGROUND_CONTEXT);
|
|
157
|
+
} catch {
|
|
158
|
+
return { delivered: false, reason: NOTICE_REASONS.failed };
|
|
159
|
+
}
|
|
160
|
+
return { delivered: true };
|
|
161
|
+
}
|
|
162
|
+
export {
|
|
163
|
+
NOTICE_LIMITS,
|
|
164
|
+
NOTICE_REASONS,
|
|
165
|
+
checkNotice,
|
|
166
|
+
deliverNotice,
|
|
167
|
+
frozenNoticed,
|
|
168
|
+
unknownKey
|
|
169
|
+
};
|
|
170
|
+
//# sourceMappingURL=run-notice.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/approvals/run-notice.ts"],
|
|
4
|
+
"sourcesContent": ["import type { Context } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport { type Licks, LicksOutbox } from '../licks/licks.ts';\nimport type { SudoRun } from './record.ts';\nimport { endLick, type LickHost, type RunFacts, startLick } from './run-licks.ts';\nimport { frozenOf, goneOf } from './runnable.ts';\n\nexport type RunNotice = {\n id: string;\n phase: 'start' | 'end';\n agentId: string;\n command: string;\n requestedAt: number;\n at: number;\n pid?: number;\n endedAt?: number;\n status?: number;\n signal?: string;\n survivors?: number[];\n stopped?: boolean;\n capped?: number;\n stdout?: string;\n stderr?: string;\n tags: string[];\n};\n\nexport type NoticeAnswer = { delivered: boolean; reason?: string };\n\nexport type NoticeHost = LickHost & { licks?: Pick<Licks, 'deliver'> };\n\nexport const NOTICE_LIMITS = {\n id: 128,\n agentId: 256,\n command: 1024,\n path: 1024,\n tag: 256,\n tags: 16,\n survivors: 64,\n} as const;\n\nexport const NOTICE_REASONS = {\n shape: 'A run notice is an object.',\n id: 'A run notice id is bios:<kernel id>.',\n phase: 'A run notice phase is start or end.',\n agentId: 'A run notice needs the agentId of the cone or scoop that asked.',\n command: `A run notice needs its command, at most ${NOTICE_LIMITS.command} characters.`,\n time: 'A run notice needs requestedAt and at as times.',\n endedAt: 'endedAt is a time, no earlier than at.',\n pid: 'pid is a process id.',\n status: 'status is an exit status from 0 to 255.',\n signal: 'signal is a signal name such as SIGTERM.',\n survivors: `survivors is a list of at most ${NOTICE_LIMITS.survivors} process ids.`,\n stopped: 'stopped is true or false.',\n capped: 'capped is a size in bytes.',\n path: `stdout and stderr are absolute paths, at most ${NOTICE_LIMITS.path} characters.`,\n tagsMissing:\n \"A run notice needs tags, the kernel's tags for the run exactly (an empty list when it has none).\",\n tags: `tags is a list of at most ${NOTICE_LIMITS.tags} tags of at most ${NOTICE_LIMITS.tag} characters.`,\n licks: 'This agent has no licks.',\n gone: 'The agent that asked is gone, so nobody was told.',\n seen: 'This notice was already delivered.',\n ended: 'This run already ended.',\n failed: \"The notice couldn't be delivered.\",\n} as const;\n\nexport const unknownKey = (key: string): string => `A run notice has no ${key.slice(0, 64)} field.`;\n\nexport const frozenNoticed = (name: string): string => `${name} is frozen, so nobody was told.`;\n\nconst KEYS = new Set([\n 'id',\n 'phase',\n 'agentId',\n 'command',\n 'requestedAt',\n 'at',\n 'pid',\n 'endedAt',\n 'status',\n 'signal',\n 'survivors',\n 'stopped',\n 'capped',\n 'stdout',\n 'stderr',\n 'tags',\n]);\n\nconst ID = /^bios:[\\w.:-]+$/;\nconst AGENT = /^[^\\s\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]+$/u;\nconst PATH = /^\\/[^\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]*$/u;\nconst TAG = /^[^\\p{Cc}\\p{Cf}\\p{Zl}\\p{Zp}]+$/u;\nconst SIGNAL = /^SIG[A-Z0-9+-]{1,12}$/;\n\nconst shown = (text: string) =>\n text\n .replace(/[\\p{Cc}\\p{Cf}]/gu, ' ')\n .replace(/\\s+/g, ' ')\n .trim();\n\nconst time = (value: unknown): value is number =>\n typeof value === 'number' && Number.isFinite(value) && value >= 0;\n\nconst whole = (value: unknown, least: number): value is number =>\n typeof value === 'number' && Number.isSafeInteger(value) && value >= least;\n\nconst text = (value: unknown, max: number): value is string =>\n typeof value === 'string' && value.length > 0 && value.length <= max;\n\nconst list = (value: unknown, max: number, each: (one: unknown) => boolean) =>\n Array.isArray(value) && value.length <= max && value.every(each);\n\nconst path = (value: unknown) => text(value, NOTICE_LIMITS.path) && PATH.test(value as string);\n\nconst CHECKS: [keyof RunNotice, (value: unknown, notice: Record<string, unknown>) => boolean][] = [\n ['pid', (value) => whole(value, 1)],\n ['endedAt', (value, notice) => time(value) && value >= (notice.at as number)],\n ['status', (value) => whole(value, 0) && value <= 255],\n ['signal', (value) => typeof value === 'string' && SIGNAL.test(value)],\n ['survivors', (value) => list(value, NOTICE_LIMITS.survivors, (one) => whole(one, 1))],\n ['stopped', (value) => typeof value === 'boolean'],\n ['capped', (value) => whole(value, 1)],\n ['stdout', path],\n ['stderr', path],\n [\n 'tags',\n (value) =>\n list(value, NOTICE_LIMITS.tags, (one) => text(one, NOTICE_LIMITS.tag) && TAG.test(one)),\n ],\n];\n\nconst REASON_OF: Partial<Record<keyof RunNotice, string>> = {\n ...NOTICE_REASONS,\n stdout: NOTICE_REASONS.path,\n stderr: NOTICE_REASONS.path,\n};\n\nfunction optional(notice: Record<string, unknown>): string | undefined {\n const bad = CHECKS.find(\n ([key, check]) => notice[key] !== undefined && !check(notice[key], notice)\n );\n return bad ? REASON_OF[bad[0]] : undefined;\n}\n\nexport function checkNotice(raw: unknown): RunNotice | string {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return NOTICE_REASONS.shape;\n const notice = raw as Record<string, unknown>;\n const extra = Object.keys(notice).find((key) => !KEYS.has(key));\n if (extra !== undefined) return unknownKey(extra);\n const { id, phase, agentId, command } = notice;\n if (!(text(id, NOTICE_LIMITS.id) && ID.test(id))) return NOTICE_REASONS.id;\n if (phase !== 'start' && phase !== 'end') return NOTICE_REASONS.phase;\n if (!(text(agentId, NOTICE_LIMITS.agentId) && AGENT.test(agentId))) return NOTICE_REASONS.agentId;\n if (!(text(command, NOTICE_LIMITS.command) && shown(command))) return NOTICE_REASONS.command;\n if (!time(notice.requestedAt) || !time(notice.at)) return NOTICE_REASONS.time;\n if (!Array.isArray(notice.tags)) return NOTICE_REASONS.tagsMissing;\n return optional(notice) ?? (notice as RunNotice);\n}\n\nfunction factsOf(notice: RunNotice, agentId: string): RunFacts {\n const paths = [notice.stdout, notice.stderr].filter((path): path is string => !!path);\n const run: SudoRun = {\n state: notice.stopped ? 'stopped' : 'done',\n by: 'owner',\n at: notice.at,\n ...(notice.pid !== undefined ? { pid: notice.pid } : {}),\n ...(notice.endedAt !== undefined ? { endedAt: notice.endedAt } : {}),\n ...(notice.status !== undefined ? { status: notice.status } : {}),\n ...(notice.signal ? { signal: notice.signal } : {}),\n ...(notice.survivors?.length ? { survivors: notice.survivors } : {}),\n ...(notice.capped ? { capped: notice.capped } : {}),\n };\n const command = shown(notice.command);\n return {\n id: notice.id,\n agentId,\n typed: command,\n where: command,\n requestedAt: notice.requestedAt,\n run,\n tags: notice.tags,\n started: paths.length ? ` Output: ${paths.join(' and ')}` : '',\n ended: paths.length ? ` Read it with your shell if you need it: ${paths.join(' and ')}.` : '',\n };\n}\n\nasync function seen(host: NoticeHost, id: string, eventId: string, context: Context) {\n const events = (await host.harness.snapshot(LicksOutbox, context))?.events ?? {};\n return (events[`sudo-run|${id}`] ?? []).includes(eventId);\n}\n\nexport async function deliverNotice(host: NoticeHost, raw: unknown): Promise<NoticeAnswer> {\n const notice = checkNotice(raw);\n if (typeof notice === 'string') return { delivered: false, reason: notice };\n const licks = host.licks;\n if (!licks) return { delivered: false, reason: NOTICE_REASONS.licks };\n const agentId = notice.agentId.startsWith('cone:')\n ? notice.agentId.slice('cone:'.length)\n : notice.agentId;\n const state = () => host.agents.state();\n const frozen = frozenOf(state)(agentId);\n if (frozen) return { delivered: false, reason: frozenNoticed(frozen) };\n if (goneOf(state)(agentId)) return { delivered: false, reason: NOTICE_REASONS.gone };\n const eventId = `${notice.id}:${notice.phase}`;\n try {\n if (\n notice.phase === 'start' &&\n (await seen(host, notice.id, `${notice.id}:end`, BACKGROUND_CONTEXT))\n )\n return { delivered: false, reason: NOTICE_REASONS.ended };\n if (await seen(host, notice.id, eventId, BACKGROUND_CONTEXT))\n return { delivered: false, reason: NOTICE_REASONS.seen };\n const facts = factsOf(notice, agentId);\n const event = await (notice.phase === 'start' ? startLick : endLick)(host, facts);\n await licks.deliver(event, BACKGROUND_CONTEXT);\n } catch {\n return { delivered: false, reason: NOTICE_REASONS.failed };\n }\n return { delivered: true };\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,0BAA0B;AACnC,SAAqB,mBAAmB;AAExC,SAAS,SAAuC,iBAAiB;AACjE,SAAS,UAAU,cAAc;AAyB1B,MAAM,gBAAgB;AAAA,EAC3B,IAAI;AAAA,EACJ,SAAS;AAAA,EACT,SAAS;AAAA,EACT,MAAM;AAAA,EACN,KAAK;AAAA,EACL,MAAM;AAAA,EACN,WAAW;AACb;AAEO,MAAM,iBAAiB;AAAA,EAC5B,OAAO;AAAA,EACP,IAAI;AAAA,EACJ,OAAO;AAAA,EACP,SAAS;AAAA,EACT,SAAS,2CAA2C,cAAc,OAAO;AAAA,EACzE,MAAM;AAAA,EACN,SAAS;AAAA,EACT,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,WAAW,kCAAkC,cAAc,SAAS;AAAA,EACpE,SAAS;AAAA,EACT,QAAQ;AAAA,EACR,MAAM,iDAAiD,cAAc,IAAI;AAAA,EACzE,aACE;AAAA,EACF,MAAM,6BAA6B,cAAc,IAAI,oBAAoB,cAAc,GAAG;AAAA,EAC1F,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AAAA,EACP,QAAQ;AACV;AAEO,MAAM,aAAa,CAAC,QAAwB,uBAAuB,IAAI,MAAM,GAAG,EAAE,CAAC;AAEnF,MAAM,gBAAgB,CAAC,SAAyB,GAAG,IAAI;AAE9D,MAAM,OAAO,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Ae,OAAO;AAAA,EAC3D;AACA,SAAO,EAAE,WAAW,KAAK;AAC3B;",
|
|
6
|
+
"names": ["text", "path"]
|
|
7
|
+
}
|
package/dist/client.js
CHANGED
|
@@ -200,6 +200,9 @@ async function connectAgent(endpoint, options = {}) {
|
|
|
200
200
|
context
|
|
201
201
|
);
|
|
202
202
|
},
|
|
203
|
+
approvalRunNotice(notice) {
|
|
204
|
+
return control.approvalRunNotice(notice, context);
|
|
205
|
+
},
|
|
203
206
|
async prompt(text, whenBusy = "followUp") {
|
|
204
207
|
const sent = await control.send({ text, whenBusy, requestId: null }, context);
|
|
205
208
|
if (!sent.accepted) throw new Error(`${sent.error.code}: ${sent.error.message}`);
|
package/dist/client.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/client.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type Context,\n createHost,\n type Host,\n isChordError,\n type Readable,\n type ReplicatedState,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { ConversationView } from '@earendil-works/pi-durable';\nimport type { ApprovalPolicy } from './approvals/policy.ts';\nimport type { Approval } from './approvals/record.ts';\nimport type { Runnable } from './approvals/runnable.ts';\nimport type { ChangesView } from './changes/git.ts';\nimport type { FrozenCone } from './freezer/index.ts';\nimport type { ImportProgress } from './freezer/v6.ts';\nimport type { GuestSeat } from './guests/seats.ts';\nimport type { MemoryEntry, MemoryScope } from './memory/format.ts';\nimport { controlAnswer, pageAnswer, remoteAnswer, settingsAnswer } from './readonly.ts';\nimport type { AgentRemote } from './remote/host.ts';\nimport type { AgentPages } from './remote/pages.ts';\nimport type { VaultState } from './secrets/vault.ts';\nimport {\n AgentControl,\n AgentInventoryService,\n AgentPagesService,\n AgentRemoteService,\n AgentSettings,\n type AgentsSummary,\n AgentTranscript,\n CONTROL_METHODS,\n type Command,\n type Delivered,\n type GuestProposal,\n type GuestShown,\n type InventoryState,\n type MonitorFeed,\n OWNER_SETTINGS_METHODS,\n PAGE_METHODS,\n type PrivateRevision,\n REMOTE_METHODS,\n type SendMode,\n type SettingsState,\n TRANSCRIPT_STATES,\n} from './services.ts';\nimport {\n type AgentPrincipal,\n bound,\n offers,\n type Remote,\n type Root,\n replicated,\n SELF,\n} from './serving.ts';\nimport type { Sprinkle } from './sprinkles/kind.ts';\nimport { otherVersion, type PortEndpoint, PortLink } from './wire.ts';\n\nexport interface AgentConnection {\n readonly serverId: string;\n readonly control: AgentControl;\n readonly transcript: ReplicatedState<ConversationView>;\n readonly deliveries: ReplicatedState<Record<string, Delivered>>;\n readonly agents?: ReplicatedState<AgentsSummary>;\n readonly views?: ReplicatedState<Record<string, ConversationView>>;\n readonly commands?: ReplicatedState<Command[]>;\n readonly privateRevision?: ReplicatedState<PrivateRevision>;\n readonly sprinkles?: ReplicatedState<Sprinkle[]>;\n readonly memories?: ReplicatedState<MemoryEntry[]>;\n readonly memoryScopes?: ReplicatedState<MemoryScope[]>;\n readonly frozen?: ReplicatedState<FrozenCone[]>;\n readonly importing?: ReplicatedState<ImportProgress>;\n readonly changes?: ReplicatedState<ChangesView>;\n readonly monitor?: ReplicatedState<MonitorFeed>;\n readonly vault?: ReplicatedState<VaultState>;\n readonly labels?: ReplicatedState<Record<string, string>>;\n readonly guests?: ReplicatedState<GuestSeat[]>;\n readonly viewOnly?: boolean;\n readonly guest?: GuestShown;\n readonly proposals?: ReplicatedState<GuestProposal[]>;\n readonly owner?: boolean;\n readonly approvals?: ReplicatedState<Approval[]>;\n readonly approvalPolicy?: ReplicatedState<ApprovalPolicy>;\n readonly approvalRunnable?: ReplicatedState<Record<string, Runnable>>;\n readonly settings: AgentSettings;\n readonly remote?: AgentRemote;\n readonly history?: boolean;\n readonly pages?: AgentPages;\n readonly inventory?: ReplicatedState<InventoryState>;\n readonly closed: Promise<Error | undefined>;\n readonly readOnly?: boolean;\n prompt(text: string, whenBusy?: SendMode): Promise<string>;\n webhook(\n name: string,\n delivery: { id?: string | null; headers?: Record<string, string>; body: string }\n ): Promise<{ delivered: boolean }>;\n close(): Promise<void>;\n}\n\nexport interface Lasting<T> {\n readonly state: ReplicatedState<T>;\n freeze(): void;\n}\n\nexport function lasting<T>(state: ReplicatedState<T>): Lasting<T> {\n let last: T | undefined;\n let frozen = false;\n const read = () => {\n if (frozen) return last;\n try {\n last = state.value;\n } catch {}\n return last;\n };\n return {\n state: {\n get value() {\n return read();\n },\n subscribe: (listener) => (frozen ? () => undefined : state.subscribe(listener)),\n },\n freeze() {\n read();\n frozen = true;\n },\n };\n}\n\nexport function lastingSettings(\n settings: AgentSettings,\n hold: <T>(state: ReplicatedState<T>) => ReplicatedState<T>\n): AgentSettings {\n return {\n state: hold(settings.state),\n connect: (providerId, secret, fields, context) =>\n settings.connect(providerId, secret, fields, context),\n disconnect: (providerId, context) => settings.disconnect(providerId, context),\n remove: (providerId, context) => settings.remove(providerId, context),\n serverUrl: (providerId, context) => settings.serverUrl(providerId, context),\n signIn: (providerId, context) => settings.signIn(providerId, context),\n dismissMoved: (context) => settings.dismissMoved(context),\n addServer: (name, entry, context) => settings.addServer(name, entry, context),\n removeServer: (id, context) => settings.removeServer(id, context),\n refusals: (context) => settings.refusals(context),\n };\n}\n\nconst VERSIONS = new Set(['upgrade_required', 'contract_mismatch']);\n\nexport const final = (error: unknown): unknown =>\n isChordError(error) && VERSIONS.has(error.code) ? otherVersion(error) : error;\n\nexport const ended = (link: PortLink): Promise<never> =>\n link.ended.then((reason) => {\n throw reason ?? new Error('the agent closed the link');\n });\n\ntype Contract = Parameters<Host<AgentPrincipal>['get']>[0];\n\nexport function clientHost(link: PortLink, name: string): Host<AgentPrincipal> {\n const host = createHost<AgentPrincipal>({\n name: `${name}:${crypto.randomUUID()}`,\n kind: 'client',\n self: SELF,\n });\n host.connect(link, { principal: SELF, onProtocolMismatch: () => link.mismatched() });\n return host;\n}\n\nexport async function holding(\n host: Host<AgentPrincipal>,\n link: PortLink,\n contracts: readonly Contract[]\n): Promise<Remote[]> {\n const stop = new AbortController();\n const getting = contracts.map(\n (contract) =>\n host.get(contract, {}, { signal: stop.signal }) as Promise<unknown> as Promise<Remote>\n );\n try {\n return await Promise.race([Promise.all(getting), ended(link)]);\n } catch (error) {\n stop.abort();\n for (const got of getting)\n void got.then(\n (ref) => ref.release(),\n () => undefined\n );\n link.close('handshake failed');\n void host.close().catch(() => undefined);\n throw error;\n }\n}\n\nexport async function optional(\n host: Host<AgentPrincipal>,\n link: PortLink,\n contract: Contract\n): Promise<Remote | undefined> {\n const got = host.get(contract, {}) as Promise<unknown> as Promise<Remote>;\n return Promise.race([got, ended(link)]).catch(() => {\n void got.then(\n (ref) => ref.release(),\n () => undefined\n );\n return undefined;\n });\n}\n\nexport async function connectAgent(\n endpoint: PortEndpoint,\n options: { context?: Context } = {}\n): Promise<AgentConnection> {\n const context = options.context ?? BACKGROUND_CONTEXT;\n const link = new PortLink(endpoint);\n const serverId = await link.hello;\n const host = clientHost(link, 'follower');\n const inventory = optional(host, link, AgentInventoryService);\n const handles = await holding(host, link, [\n AgentControl,\n AgentTranscript,\n AgentSettings,\n AgentRemoteService,\n AgentPagesService,\n ]).catch((error: unknown) => {\n void inventory.then((handle) => handle?.release());\n throw final(error);\n });\n const [controlHandle, transcriptHandle, settingsHandle, remoteHandle, pagesHandle] = handles as [\n Remote,\n Remote,\n Remote,\n Remote,\n Remote,\n ];\n const inventoryHandle = await inventory;\n const release = () => {\n for (const handle of handles) handle.release();\n inventoryHandle?.release();\n };\n const root: Root = (run, rootOptions) => host.root(run, rootOptions);\n const control = bound<AgentControl>(controlHandle, root, CONTROL_METHODS, controlAnswer);\n const members = Object.fromEntries(\n TRANSCRIPT_STATES.map((name) => [name, transcriptHandle[name] as Readable<unknown>])\n ) as Record<(typeof TRANSCRIPT_STATES)[number], Readable<unknown>>;\n const settingsState = settingsHandle.state as Readable<SettingsState>;\n const settings: AgentSettings = {\n ...bound<Omit<AgentSettings, 'state'>>(\n settingsHandle,\n root,\n OWNER_SETTINGS_METHODS,\n settingsAnswer\n ),\n state: replicated(settingsState),\n };\n const remote = bound<AgentRemote>(remoteHandle, root, REMOTE_METHODS, remoteAnswer);\n const pages = bound<AgentPages>(pagesHandle, root, PAGE_METHODS, pageAnswer);\n const state = <K extends keyof typeof members>(name: K) =>\n replicated(members[name] as Readable<never>);\n const held: Lasting<unknown>[] = [];\n const hold = <T>(state: ReplicatedState<T>): ReplicatedState<T> => {\n const kept = lasting(state);\n held.push(kept as Lasting<unknown>);\n return kept.state;\n };\n let open = true;\n const finish = () => {\n if (!open) return;\n open = false;\n for (const kept of held) kept.freeze();\n release();\n };\n const closed = link.ended.then((reason) => {\n finish();\n return reason;\n });\n return {\n serverId,\n readOnly: controlHandle.variant === 'view',\n control,\n transcript: hold<ConversationView>(state('state')),\n deliveries: hold<Record<string, Delivered>>(state('deliveries')),\n agents: hold<AgentsSummary>(state('agents')),\n views: hold<Record<string, ConversationView>>(state('views')),\n commands: hold<Command[]>(state('commands')),\n privateRevision: hold<PrivateRevision>(state('privateRevision')),\n sprinkles: hold<Sprinkle[]>(state('sprinkles')),\n memories: hold<MemoryEntry[]>(state('memories')),\n memoryScopes: hold<MemoryScope[]>(state('memoryScopes')),\n frozen: hold<FrozenCone[]>(state('frozen')),\n importing: hold<ImportProgress>(state('importing')),\n changes: hold<ChangesView>(state('changes')),\n monitor: hold<MonitorFeed>(state('monitor')),\n vault: hold<VaultState>(state('vault')),\n labels: hold<Record<string, string>>(state('labels')),\n guests: hold<GuestSeat[]>(state('guests')),\n viewOnly: controlHandle.variant === 'view',\n owner: pagesHandle.variant === 'pages',\n approvals: hold<Approval[]>(state('approvals')),\n approvalPolicy: hold<ApprovalPolicy>(state('approvalPolicy')),\n approvalRunnable: hold<Record<string, Runnable>>(state('approvalRunnable')),\n settings: lastingSettings(settings, hold),\n remote,\n history: offers(controlHandle, 'entries'),\n pages,\n ...(inventoryHandle?.variant === 'owner'\n ? { inventory: hold(replicated(inventoryHandle.inventory as Readable<InventoryState>)) }\n : {}),\n closed,\n webhook(name, delivery) {\n return control.webhook(\n name,\n { id: delivery.id ?? null, headers: delivery.headers ?? {}, body: delivery.body },\n context\n );\n },\n async prompt(text, whenBusy = 'followUp') {\n const sent = await control.send({ text, whenBusy, requestId: null }, context);\n if (!sent.accepted) throw new Error(`${sent.error.code}: ${sent.error.message}`);\n const settled = await control.wait(sent.submissionId, context);\n if (settled.status !== 'done') throw new Error(`unanswered: ${settled.reason}`);\n return settled.text;\n },\n async close() {\n finish();\n link.close('closed');\n await closed;\n await host.close();\n },\n };\n}\n"],
|
|
5
|
-
"mappings": "AAAA;AAAA,EAEE;AAAA,EAEA;AAAA,OAGK;AACP,SAAS,0BAA0B;
|
|
4
|
+
"sourcesContent": ["import {\n type Context,\n createHost,\n type Host,\n isChordError,\n type Readable,\n type ReplicatedState,\n} from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { ConversationView } from '@earendil-works/pi-durable';\nimport type { ApprovalPolicy } from './approvals/policy.ts';\nimport type { Approval } from './approvals/record.ts';\nimport type { NoticeAnswer, RunNotice } from './approvals/run-notice.ts';\nimport type { Runnable } from './approvals/runnable.ts';\nimport type { ChangesView } from './changes/git.ts';\nimport type { FrozenCone } from './freezer/index.ts';\nimport type { ImportProgress } from './freezer/v6.ts';\nimport type { GuestSeat } from './guests/seats.ts';\nimport type { MemoryEntry, MemoryScope } from './memory/format.ts';\nimport { controlAnswer, pageAnswer, remoteAnswer, settingsAnswer } from './readonly.ts';\nimport type { AgentRemote } from './remote/host.ts';\nimport type { AgentPages } from './remote/pages.ts';\nimport type { VaultState } from './secrets/vault.ts';\nimport {\n AgentControl,\n AgentInventoryService,\n AgentPagesService,\n AgentRemoteService,\n AgentSettings,\n type AgentsSummary,\n AgentTranscript,\n CONTROL_METHODS,\n type Command,\n type Delivered,\n type GuestProposal,\n type GuestShown,\n type InventoryState,\n type MonitorFeed,\n OWNER_SETTINGS_METHODS,\n PAGE_METHODS,\n type PrivateRevision,\n REMOTE_METHODS,\n type SendMode,\n type SettingsState,\n TRANSCRIPT_STATES,\n} from './services.ts';\nimport {\n type AgentPrincipal,\n bound,\n offers,\n type Remote,\n type Root,\n replicated,\n SELF,\n} from './serving.ts';\nimport type { Sprinkle } from './sprinkles/kind.ts';\nimport { otherVersion, type PortEndpoint, PortLink } from './wire.ts';\n\nexport interface AgentConnection {\n readonly serverId: string;\n readonly control: AgentControl;\n readonly transcript: ReplicatedState<ConversationView>;\n readonly deliveries: ReplicatedState<Record<string, Delivered>>;\n readonly agents?: ReplicatedState<AgentsSummary>;\n readonly views?: ReplicatedState<Record<string, ConversationView>>;\n readonly commands?: ReplicatedState<Command[]>;\n readonly privateRevision?: ReplicatedState<PrivateRevision>;\n readonly sprinkles?: ReplicatedState<Sprinkle[]>;\n readonly memories?: ReplicatedState<MemoryEntry[]>;\n readonly memoryScopes?: ReplicatedState<MemoryScope[]>;\n readonly frozen?: ReplicatedState<FrozenCone[]>;\n readonly importing?: ReplicatedState<ImportProgress>;\n readonly changes?: ReplicatedState<ChangesView>;\n readonly monitor?: ReplicatedState<MonitorFeed>;\n readonly vault?: ReplicatedState<VaultState>;\n readonly labels?: ReplicatedState<Record<string, string>>;\n readonly guests?: ReplicatedState<GuestSeat[]>;\n readonly viewOnly?: boolean;\n readonly guest?: GuestShown;\n readonly proposals?: ReplicatedState<GuestProposal[]>;\n readonly owner?: boolean;\n readonly approvals?: ReplicatedState<Approval[]>;\n readonly approvalPolicy?: ReplicatedState<ApprovalPolicy>;\n readonly approvalRunnable?: ReplicatedState<Record<string, Runnable>>;\n readonly settings: AgentSettings;\n readonly remote?: AgentRemote;\n readonly history?: boolean;\n readonly pages?: AgentPages;\n readonly inventory?: ReplicatedState<InventoryState>;\n readonly closed: Promise<Error | undefined>;\n readonly readOnly?: boolean;\n prompt(text: string, whenBusy?: SendMode): Promise<string>;\n webhook(\n name: string,\n delivery: { id?: string | null; headers?: Record<string, string>; body: string }\n ): Promise<{ delivered: boolean }>;\n approvalRunNotice(notice: RunNotice): Promise<NoticeAnswer>;\n close(): Promise<void>;\n}\n\nexport interface Lasting<T> {\n readonly state: ReplicatedState<T>;\n freeze(): void;\n}\n\nexport function lasting<T>(state: ReplicatedState<T>): Lasting<T> {\n let last: T | undefined;\n let frozen = false;\n const read = () => {\n if (frozen) return last;\n try {\n last = state.value;\n } catch {}\n return last;\n };\n return {\n state: {\n get value() {\n return read();\n },\n subscribe: (listener) => (frozen ? () => undefined : state.subscribe(listener)),\n },\n freeze() {\n read();\n frozen = true;\n },\n };\n}\n\nexport function lastingSettings(\n settings: AgentSettings,\n hold: <T>(state: ReplicatedState<T>) => ReplicatedState<T>\n): AgentSettings {\n return {\n state: hold(settings.state),\n connect: (providerId, secret, fields, context) =>\n settings.connect(providerId, secret, fields, context),\n disconnect: (providerId, context) => settings.disconnect(providerId, context),\n remove: (providerId, context) => settings.remove(providerId, context),\n serverUrl: (providerId, context) => settings.serverUrl(providerId, context),\n signIn: (providerId, context) => settings.signIn(providerId, context),\n dismissMoved: (context) => settings.dismissMoved(context),\n addServer: (name, entry, context) => settings.addServer(name, entry, context),\n removeServer: (id, context) => settings.removeServer(id, context),\n refusals: (context) => settings.refusals(context),\n };\n}\n\nconst VERSIONS = new Set(['upgrade_required', 'contract_mismatch']);\n\nexport const final = (error: unknown): unknown =>\n isChordError(error) && VERSIONS.has(error.code) ? otherVersion(error) : error;\n\nexport const ended = (link: PortLink): Promise<never> =>\n link.ended.then((reason) => {\n throw reason ?? new Error('the agent closed the link');\n });\n\ntype Contract = Parameters<Host<AgentPrincipal>['get']>[0];\n\nexport function clientHost(link: PortLink, name: string): Host<AgentPrincipal> {\n const host = createHost<AgentPrincipal>({\n name: `${name}:${crypto.randomUUID()}`,\n kind: 'client',\n self: SELF,\n });\n host.connect(link, { principal: SELF, onProtocolMismatch: () => link.mismatched() });\n return host;\n}\n\nexport async function holding(\n host: Host<AgentPrincipal>,\n link: PortLink,\n contracts: readonly Contract[]\n): Promise<Remote[]> {\n const stop = new AbortController();\n const getting = contracts.map(\n (contract) =>\n host.get(contract, {}, { signal: stop.signal }) as Promise<unknown> as Promise<Remote>\n );\n try {\n return await Promise.race([Promise.all(getting), ended(link)]);\n } catch (error) {\n stop.abort();\n for (const got of getting)\n void got.then(\n (ref) => ref.release(),\n () => undefined\n );\n link.close('handshake failed');\n void host.close().catch(() => undefined);\n throw error;\n }\n}\n\nexport async function optional(\n host: Host<AgentPrincipal>,\n link: PortLink,\n contract: Contract\n): Promise<Remote | undefined> {\n const got = host.get(contract, {}) as Promise<unknown> as Promise<Remote>;\n return Promise.race([got, ended(link)]).catch(() => {\n void got.then(\n (ref) => ref.release(),\n () => undefined\n );\n return undefined;\n });\n}\n\nexport async function connectAgent(\n endpoint: PortEndpoint,\n options: { context?: Context } = {}\n): Promise<AgentConnection> {\n const context = options.context ?? BACKGROUND_CONTEXT;\n const link = new PortLink(endpoint);\n const serverId = await link.hello;\n const host = clientHost(link, 'follower');\n const inventory = optional(host, link, AgentInventoryService);\n const handles = await holding(host, link, [\n AgentControl,\n AgentTranscript,\n AgentSettings,\n AgentRemoteService,\n AgentPagesService,\n ]).catch((error: unknown) => {\n void inventory.then((handle) => handle?.release());\n throw final(error);\n });\n const [controlHandle, transcriptHandle, settingsHandle, remoteHandle, pagesHandle] = handles as [\n Remote,\n Remote,\n Remote,\n Remote,\n Remote,\n ];\n const inventoryHandle = await inventory;\n const release = () => {\n for (const handle of handles) handle.release();\n inventoryHandle?.release();\n };\n const root: Root = (run, rootOptions) => host.root(run, rootOptions);\n const control = bound<AgentControl>(controlHandle, root, CONTROL_METHODS, controlAnswer);\n const members = Object.fromEntries(\n TRANSCRIPT_STATES.map((name) => [name, transcriptHandle[name] as Readable<unknown>])\n ) as Record<(typeof TRANSCRIPT_STATES)[number], Readable<unknown>>;\n const settingsState = settingsHandle.state as Readable<SettingsState>;\n const settings: AgentSettings = {\n ...bound<Omit<AgentSettings, 'state'>>(\n settingsHandle,\n root,\n OWNER_SETTINGS_METHODS,\n settingsAnswer\n ),\n state: replicated(settingsState),\n };\n const remote = bound<AgentRemote>(remoteHandle, root, REMOTE_METHODS, remoteAnswer);\n const pages = bound<AgentPages>(pagesHandle, root, PAGE_METHODS, pageAnswer);\n const state = <K extends keyof typeof members>(name: K) =>\n replicated(members[name] as Readable<never>);\n const held: Lasting<unknown>[] = [];\n const hold = <T>(state: ReplicatedState<T>): ReplicatedState<T> => {\n const kept = lasting(state);\n held.push(kept as Lasting<unknown>);\n return kept.state;\n };\n let open = true;\n const finish = () => {\n if (!open) return;\n open = false;\n for (const kept of held) kept.freeze();\n release();\n };\n const closed = link.ended.then((reason) => {\n finish();\n return reason;\n });\n return {\n serverId,\n readOnly: controlHandle.variant === 'view',\n control,\n transcript: hold<ConversationView>(state('state')),\n deliveries: hold<Record<string, Delivered>>(state('deliveries')),\n agents: hold<AgentsSummary>(state('agents')),\n views: hold<Record<string, ConversationView>>(state('views')),\n commands: hold<Command[]>(state('commands')),\n privateRevision: hold<PrivateRevision>(state('privateRevision')),\n sprinkles: hold<Sprinkle[]>(state('sprinkles')),\n memories: hold<MemoryEntry[]>(state('memories')),\n memoryScopes: hold<MemoryScope[]>(state('memoryScopes')),\n frozen: hold<FrozenCone[]>(state('frozen')),\n importing: hold<ImportProgress>(state('importing')),\n changes: hold<ChangesView>(state('changes')),\n monitor: hold<MonitorFeed>(state('monitor')),\n vault: hold<VaultState>(state('vault')),\n labels: hold<Record<string, string>>(state('labels')),\n guests: hold<GuestSeat[]>(state('guests')),\n viewOnly: controlHandle.variant === 'view',\n owner: pagesHandle.variant === 'pages',\n approvals: hold<Approval[]>(state('approvals')),\n approvalPolicy: hold<ApprovalPolicy>(state('approvalPolicy')),\n approvalRunnable: hold<Record<string, Runnable>>(state('approvalRunnable')),\n settings: lastingSettings(settings, hold),\n remote,\n history: offers(controlHandle, 'entries'),\n pages,\n ...(inventoryHandle?.variant === 'owner'\n ? { inventory: hold(replicated(inventoryHandle.inventory as Readable<InventoryState>)) }\n : {}),\n closed,\n webhook(name, delivery) {\n return control.webhook(\n name,\n { id: delivery.id ?? null, headers: delivery.headers ?? {}, body: delivery.body },\n context\n );\n },\n approvalRunNotice(notice) {\n return control.approvalRunNotice(notice, context);\n },\n async prompt(text, whenBusy = 'followUp') {\n const sent = await control.send({ text, whenBusy, requestId: null }, context);\n if (!sent.accepted) throw new Error(`${sent.error.code}: ${sent.error.message}`);\n const settled = await control.wait(sent.submissionId, context);\n if (settled.status !== 'done') throw new Error(`unanswered: ${settled.reason}`);\n return settled.text;\n },\n async close() {\n finish();\n link.close('closed');\n await closed;\n await host.close();\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EAEE;AAAA,EAEA;AAAA,OAGK;AACP,SAAS,0BAA0B;AAWnC,SAAS,eAAe,YAAY,cAAc,sBAAsB;AAIxE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EAOA;AAAA,EACA;AAAA,EAEA;AAAA,EAGA;AAAA,OACK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,cAAiC,gBAAgB;AAiDnD,SAAS,QAAW,OAAuC;AAChE,MAAI;AACJ,MAAI,SAAS;AACb,QAAM,OAAO,MAAM;AACjB,QAAI,OAAQ,QAAO;AACnB,QAAI;AACF,aAAO,MAAM;AAAA,IACf,QAAQ;AAAA,IAAC;AACT,WAAO;AAAA,EACT;AACA,SAAO;AAAA,IACL,OAAO;AAAA,MACL,IAAI,QAAQ;AACV,eAAO,KAAK;AAAA,MACd;AAAA,MACA,WAAW,CAAC,aAAc,SAAS,MAAM,SAAY,MAAM,UAAU,QAAQ;AAAA,IAC/E;AAAA,IACA,SAAS;AACP,WAAK;AACL,eAAS;AAAA,IACX;AAAA,EACF;AACF;AAEO,SAAS,gBACd,UACA,MACe;AACf,SAAO;AAAA,IACL,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