@ai-ecoverse/slicc-agent 7.12.2 → 7.13.1
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 +14 -13
- package/dist/agent.js +2 -2
- package/dist/agent.js.map +2 -2
- package/dist/approvals/index.js +13 -9
- package/dist/approvals/index.js.map +2 -2
- package/dist/changes/index.js +1 -1
- package/dist/changes/index.js.map +2 -2
- package/dist/codemode/index.js +4 -4
- package/dist/codemode/index.js.map +2 -2
- package/dist/control.js +12 -9
- package/dist/control.js.map +2 -2
- package/dist/guests/index.js +18 -11
- package/dist/guests/index.js.map +2 -2
- package/dist/guests/review.js +2 -2
- package/dist/guests/review.js.map +2 -2
- package/dist/guests/scoop.js +6 -6
- package/dist/guests/scoop.js.map +2 -2
- package/dist/host.js +16 -11
- package/dist/host.js.map +2 -2
- package/dist/inventory.js +21 -12
- package/dist/inventory.js.map +2 -2
- package/dist/kernel/env.js +7 -7
- package/dist/kernel/env.js.map +2 -2
- package/dist/kernel/watch.js +5 -5
- package/dist/kernel/watch.js.map +2 -2
- package/dist/licks/extension.js +4 -6
- package/dist/licks/extension.js.map +2 -2
- package/dist/licks/fswatch.js +4 -4
- package/dist/licks/fswatch.js.map +2 -2
- package/dist/licks/sources.js +2 -2
- package/dist/licks/sources.js.map +2 -2
- package/dist/main.js +19 -6
- package/dist/main.js.map +2 -2
- package/dist/mcp/catalog.js +35 -19
- package/dist/mcp/catalog.js.map +2 -2
- package/dist/mcp/runtime.js +2 -1
- package/dist/mcp/runtime.js.map +2 -2
- package/dist/mcp/tools.js +6 -2
- package/dist/mcp/tools.js.map +3 -3
- package/dist/memory/extract.js +18 -9
- package/dist/memory/extract.js.map +2 -2
- package/dist/memory/prompt.js +8 -12
- package/dist/memory/prompt.js.map +2 -2
- package/dist/memory/runtime.js +1 -1
- package/dist/memory/runtime.js.map +2 -2
- package/dist/monitor/index.js +10 -4
- package/dist/monitor/index.js.map +2 -2
- package/dist/remote/busy.js +15 -10
- package/dist/remote/busy.js.map +2 -2
- package/dist/remote/events.js +141 -67
- package/dist/remote/events.js.map +2 -2
- package/dist/remote/host.js +244 -103
- package/dist/remote/host.js.map +2 -2
- package/dist/reports.js +11 -11
- package/dist/reports.js.map +3 -3
- package/dist/roles/frontmatter.js +96 -73
- package/dist/roles/frontmatter.js.map +3 -3
- package/dist/scoops/cli.js +3 -3
- package/dist/scoops/cli.js.map +2 -2
- package/dist/scoops/extension.js +10 -4
- package/dist/scoops/extension.js.map +2 -2
- package/dist/scoops/requests.js +1 -1
- package/dist/scoops/requests.js.map +2 -2
- package/dist/scoops/retry.js +5 -11
- package/dist/scoops/retry.js.map +2 -2
- package/dist/scoops/service.js +7 -4
- package/dist/scoops/service.js.map +2 -2
- package/dist/serving.js +4 -4
- package/dist/serving.js.map +2 -2
- package/dist/skills/index.js +2 -2
- package/dist/skills/index.js.map +2 -2
- package/dist/spectrum/monitor-port.js +5 -16
- package/dist/spectrum/monitor-port.js.map +2 -2
- package/dist/sprinkles/index.js +2 -2
- package/dist/sprinkles/index.js.map +2 -2
- package/dist/sqlite.js +8 -0
- package/dist/sqlite.js.map +2 -2
- package/dist/titles/extension.js +97 -34
- package/dist/titles/extension.js.map +2 -2
- package/dist/types/approvals/index.d.ts +1 -1
- package/dist/types/codemode/index.d.ts +1 -1
- package/dist/types/guests/index.d.ts +1 -1
- package/dist/types/host.d.ts +6 -0
- package/dist/types/inventory.d.ts +1 -1
- package/dist/types/kernel/env.d.ts +2 -2
- package/dist/types/kernel/watch.d.ts +3 -3
- package/dist/types/main.d.ts +9 -2
- package/dist/types/mcp/catalog.d.ts +2 -1
- package/dist/types/mcp/runtime.d.ts +1 -0
- package/dist/types/mcp/tools.d.ts +2 -2
- package/dist/types/monitor/index.d.ts +1 -1
- package/dist/types/remote/busy.d.ts +10 -3
- package/dist/types/remote/events.d.ts +13 -2
- package/dist/types/remote/host.d.ts +3 -5
- package/dist/types/reports.d.ts +3 -3
- package/dist/types/scoops/cli.d.ts +1 -1
- package/dist/types/scoops/extension.d.ts +1 -1
- package/dist/types/scoops/retry.d.ts +1 -3
- package/dist/types/sqlite.d.ts +2 -0
- package/dist/views.js +12 -10
- package/dist/views.js.map +2 -2
- package/dist/workflow/index.js +12 -18
- package/dist/workflow/index.js.map +2 -2
- package/dist/workflow/step.js +5 -4
- package/dist/workflow/step.js.map +2 -2
- package/package.json +10 -9
package/README.md
CHANGED
|
@@ -27,7 +27,7 @@ await agent.prompt('What is in /home?');
|
|
|
27
27
|
```
|
|
28
28
|
|
|
29
29
|
- `openAgent({ models, model, storage?, registry?, settings?, clock? })` opens a durable Harness (in memory unless `storage` is given) and its root conversation, and resumes work a previous worker left unfinished. `clock` (`{ now, setTimer }`) is the Harness clock: task times, sleeps and the timers of its tasks, such as a guest review's expiry, run on it; `attachApprovals` takes the same `now` and `setTimer`. Tests pass a fake one and move it forward.
|
|
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)
|
|
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
33
|
- `startAgent({ worker })` takes the Web Lock `slicc-agent`, so one tab at a time owns the agent worker, and waits while another tab holds it. `connect()` returns an `AgentConnection` (`control`, `transcript`, `prompt()`, and `webhook(name, { id?, headers?, body })`, which hands a webhook delivery, such as one from the tray hub, to the licks without a chord `Context`), `restart()` replaces the worker (durable resumes from SQLite), and `release()` stops it and lets the next tab take over. `port()` returns a raw `MessagePort` into the worker instead, for another tab: hand it over (through a SharedWorker, say), and that tab calls `connectAgent(port)`. A caller that already holds the lock passes `held: true`. A connection's `closed` resolves when its port ends (with the error, if any), and from then on its states keep their last values.
|
|
@@ -257,7 +257,7 @@ Each scoop is owned by a background durable task, its **anchor**, so Stop in its
|
|
|
257
257
|
|
|
258
258
|
**The `agent` command.** One bash script is installed under seven names, `agent`, `subagent`, `memory`, `gelatiere`, `freezer`, `models` and `panel`, in `/usr/local/bin`, mode `0755`, which is on every user's `PATH`, so the user, a cone or a scoop runs it in any bash. A file at one of those paths that isn't slicc-agent's (it lacks the `slicc-agent/1` request marker), such as a root global package's `memory`, is left alone, with one warning per boot in the worker's console. Root's `$PNPM_HOME/bin` (`/usr/local/share/pnpm/bin`) is on root's `PATH` only: other users find root's installed packages in `/usr/bin`, but not loose scripts. Copies that earlier versions put in the kernel's `$PNPM_HOME/bin` are removed, so they can't shadow the new ones for root. It writes a request (NUL-separated fields: `slicc-agent/1`, the name it was called by, `$SLICC_AGENT`, or `tab:$SLICC_TAB` from a terminal that has only that, the working directory, its pid, argc, the arguments and stdin) to `/var/lib/slicc/agent/requests/in/` and polls `out/` for the answer and exit code (with an optional `<id>.err`, the answer's stdout is `<id>.out` and its stderr `<id>.err`); the worker writes `<id>.ack` when it picks a request up, and the script gives up after 20 s without one ("the SLICC agent isn't running", exit 1). The kernel environment exports `SLICC_AGENT`, `PI_PROVIDER`, `PI_MODEL` and `PI_REASONING_LEVEL` into every agent command, so the worker knows the caller, and `PLAYWRIGHT_CLI_SESSION` with the same agent id, so each agent's `playwright-cli` keeps its own current tab (slicc-cdp #129). The user's terminals get none of these. `SLICC_AGENT` is checked against the process tree: the worker reads `ps`, walks up from the request's pid to the nearest bash an agent's kernel environment started, and refuses a request whose `SLICC_AGENT` names another agent, or names one when no agent's bash is above it; with kernel users, a user whose processes belong to another agent is refused too. The pid in the request is the script's own `$$`, so it is checked first: its `ps` row has to be the command it was called as (`/…/agent`, `subagent`, …) followed by exactly the request's arguments, and with kernel users it has to run as the spool's user (by `/etc/passwd`). A request whose pid isn't in the table or fails these checks, or a `ps` read that fails or stalls, is refused. A caller with no agent above it and no `SLICC_AGENT` is the user. `/var/lib/slicc/agent/scoops/<handle>/metadata.json` mirrors each scoop's state for scripts.
|
|
259
259
|
- `agent [options] --prompt <text>` (or `--file <path>`, or `-` for stdin, or v6's `agent <cwd> <allowed-commands> <prompt>`) is **synchronous**: an ephemeral scoop runs, and the command prints its final answer and exits 0, or prints the reason on stderr and exits 1. Afterwards the scoop is stopped, its folder removed, its conversation marked dropped and its transcript archived as Markdown in `/tmp/agent-sessions/<handle>.md` (`/home/sessions/` with `--persist-session`, nowhere with `--no-persist-session`). The script traps TERM, INT and HUP and cancels the scoop, and the worker checks the script's pid in the kernel's process table every second for a SIGKILL. If the caller's run is still going when the bash call dies (a bash timeout), the scoop continues and its answer arrives as a `bash` lick; `--background-after <seconds>` does the same on purpose. Sync calls nest up to three deep. Allowed commands in v6's form are told to the scoop, not enforced.
|
|
260
|
-
- `agent retry <task id>`
|
|
260
|
+
- `agent retry <task id>` answers that a task which stopped after repeated restarts has ended, and that the work has to be submitted again. Only the user may ask; an agent is refused.
|
|
261
261
|
- `agent --async …` (= `subagent spawn …`) starts a persistent scoop and prints its handle; only cones start them. `list [--agents]`, `status`, `rename`, `send [--follow-up]`, `wait [--timeout <s>] [--notify]` (30 s by default; `--notify` returns at once and brings the answers together in one `scoop-wait` lick) and `stop` manage them. From a scoop, `agent send parent "<note>"` posts a progress note to its cone as a lick, coalesced per scoop.
|
|
262
262
|
- Options: `--name`, `--agent <role>`, `--model <provider/model>`, `--thinking <level>` or `--effort low|medium|high|max`, `--tools <a,b>` (or `auto`/`full`), `--read-only <paths>`, `--system-prompt[-file]`. `--schema-b64`, `--tools output`, `--session`, `--resume`, `--image`, `--no-escalate`, `--minimal` and `--usage` answer "not supported in SLICC yet".
|
|
263
263
|
|
|
@@ -266,7 +266,7 @@ Each scoop is owned by a background durable task, its **anchor**, so Stop in its
|
|
|
266
266
|
- `models use <provider/model> [--thinking <level>]` switches the caller's model the way the Settings picker does (`Conversation.configure`): a cone's or a scoop's own, or, in a terminal, the active cone's. An unknown id exits 1 naming the three closest ids; a model whose account isn't connected exits 1 and says to connect it in Settings.
|
|
267
267
|
- `models --help` prints the usage; an unknown verb exits 2 with it.
|
|
268
268
|
|
|
269
|
-
**Roles** are pi agent files: Markdown with
|
|
269
|
+
**Roles** are pi agent files: Markdown with YAML frontmatter (`name`, `description`, `tools`, `model`, `thinking`, `memory`, `inheritProjectContext`, `inheritGlobalContext`, …) and the role's prompt as the body, added to the scoop's instructions. The built-ins are `scout`, `worker`, `reviewer`, `oracle`, `delegate` and `gelatiere` (below). The first source with a name wins: `~/.pi/agent/agents/`, then the built-ins, then packages (see Package resources) that name a folder in `pi-subagents.agents` or `pi.subagents.agents`. A package role that loses its name is skipped with a warning in `agent list`. A project's `.pi/agents/` will count only in trusted folders, and folders can't be trusted yet. `~/.pi/agent/settings.json` can override roles (`subagents.agentOverrides`) and set the limits `subagents.maxLiveScoops` (16 live scoops per cone) and `subagents.maxPerTurn` (64 scoops started per cone turn), which the worker counts for both kinds.
|
|
270
270
|
|
|
271
271
|
**Isolation, for now.** The file tools of a scoop write only under its folder and `/tmp`, plus the cwd of a v6-form call, and read those, their cone's working folder (`/home` by default) and `--read-only` paths; paths are normalized, `..` included, before the check. bash isn't confined, and the scoop is told so: the guard is a guardrail, not a boundary. A scoop's commands share one process group (see Bash and files on slicc-kernel), and stopping the scoop signals it, together with any group recorded for the scoop on an older kernel.
|
|
272
272
|
|
|
@@ -288,7 +288,8 @@ Skills and prompt templates work as in pi's coding-agent. pi's loaders read with
|
|
|
288
288
|
On a name collision the first skill found wins: an agent's own skills shadow the global ones, a global skill shadows a built-in, and a built-in shadows a package's. A missing root is skipped.
|
|
289
289
|
- **The global folder.** On every start the worker, as root, creates `/usr/share/skills` if it's missing and sets it to 0755, so it's root's and readable by everyone; once kernel users give each cone its own user and the kernel checks file modes, only root (the worker, sudo or the human) writes there, and every cone and scoop reads it. Each skill's `source` is `user`, `global`, `package` or `builtin`, and the transcript service's `commands` carry it. A skill folder in `/usr/share/skills` whose real path lies in a package under root's global pnpm (`/usr/local/share/pnpm/`), as bios links a certified catalog package's `pi.skills`, reads `package` with that package's `name` and `version` from its nearest `package.json`; every other skill there, such as those imported from SLICC 6 or written by root, stays `global`. Only these links count: root's global pnpm isn't scanned, and loading and precedence don't change.
|
|
290
290
|
- **Inside a root.** Folders with `SKILL.md` are found at any depth, and a `SKILL.md` ends its branch. A `.md` file with a description directly in a root counts too. Folders starting with `.` and `node_modules` are skipped. Symbolic links are followed, but each folder is read once by its real path, so a link back up a tree can't loop. Scoops may `read` the folders of the loaded skills, even outside their own folders.
|
|
291
|
-
- **
|
|
291
|
+
- **YAML.** Skills, roles and prompt templates use YAML 1.2 core scalars and folding through `yaml`. Custom tags and aliases are refused; nested fields remain unsupported except the role memory mapping. Duplicate keys keep their last value. On a YAML syntax error, the reader retries once with plain top-level text quoted and its continuation lines folded, so descriptions such as `Use when: foo` still load. A ` #` in an unquoted value starts a YAML comment, and `0x`/`0o` numbers parse as numbers; these differ from the old reader.
|
|
292
|
+
- **Problems.** A problem (a missing description, a bad name, a collision, a YAML error with its line number) becomes one lick with `severity="warn"` per distinct problem. A skill without a description is skipped; any other problem only warns.
|
|
292
293
|
- **Untrusted folders.** A project's `.pi/skills` and `.agents/skills` are read only in trusted folders, which come with PR 21.
|
|
293
294
|
|
|
294
295
|
The worker watches the roots and reloads on change. A `skills` prompt section, given to cones and scoops, lists every skill's name, description and location in pi's `<available_skills>` block, and the model reads a `SKILL.md` with the `read` tool when a task matches.
|
|
@@ -403,9 +404,9 @@ MCP servers reachable over Streamable HTTP become native agent tools. The client
|
|
|
403
404
|
- `codemode` (the default): callable from codemode scripts as `tools.mcp__docs__search(args)`, which resolves to the whole `CallToolResult`, but not declared to the model. The `mcp_servers` section lists these servers with their description or the first line of the server's instructions. It also says that MCP results are data from the server, not instructions.
|
|
404
405
|
- `direct`: declared to the model like a built-in tool, and callable from codemode too.
|
|
405
406
|
- `hidden`: unreachable.
|
|
406
|
-
- `deferred`
|
|
407
|
+
- `deferred`: hidden from the model until `tool_search` loads it. `tool_search` is installed unless `~/.pi/agent/settings.json` lists `-tool_search` in `defaultTools`. With `tool_search` off and codemode on, `deferred` falls back to `codemode`; with both off it becomes `direct`, so a tool is never left unreachable. A codemode script can call a deferred tool before the model has loaded it. With codemode turned off, `codemode` tools become `direct`.
|
|
407
408
|
|
|
408
|
-
A codemode script waits up to 10 s for servers still connecting. For the model, text results over 20 KB keep their start and end around a `…N chars truncated…` marker, and the full text goes to `/tmp/slicc-mcp-<call>.txt`. Images pass through, and binary resources are saved to `/tmp`. Servers with resources add pi's `list_mcp_resources`, `list_mcp_resource_templates` and `read_mcp_resource
|
|
409
|
+
A codemode script waits up to 10 s for servers still connecting. For the model, text results over 20 KB keep their start and end around a `…N chars truncated…` marker, and the full text goes to `/tmp/slicc-mcp-<call>.txt`. Images pass through, and binary resources are saved to `/tmp`. Servers with resources add pi's `list_mcp_resources`, `list_mcp_resource_templates` and `read_mcp_resource` at the widest exposure among those servers. `direct` registers them for the model, `deferred` registers them as deferred so `tool_search` can load them, and `codemode` leaves them to codemode scripts. With `tool_search` and codemode both off they are `direct`. They skip servers whose exposure is `hidden`. MCP prompts, sampling and elicitation aren't supported, so a server can't call the model or ask the user anything.
|
|
409
410
|
|
|
410
411
|
**Network.** Requests go through the worker's transport fetch, as Bedrock's do. On the page's own fetch, a server must send CORS headers allowing `Authorization`, `Content-Type`, `Mcp-Session-Id`, `Mcp-Protocol-Version` and `Last-Event-ID`, and exposing `Mcp-Session-Id`. A server that doesn't gets a lick saying to link the `slicc` CLI or connect the extension (only when no exit was linked at attach). There, a browser hides where a redirect goes, so a server that redirects a request holding a credential is refused: put its final URL in `mcp.json`. Stop or a steer that aborts the turn cancels a running call (`notifications/cancelled`). Lists and reads are retried once after 408, 429 or 5xx, and tool calls never are. An interrupted call isn't rerun after a worker restart. Server log messages go to `~/.pi/agent/mcp.log`, which rolls over to `mcp.log.1` at 5 MB.
|
|
411
412
|
|
|
@@ -620,11 +621,11 @@ pi has no git integration and no changes list; pi coding-agent leaves that to th
|
|
|
620
621
|
### The live monitor
|
|
621
622
|
|
|
622
623
|
Spectrum's Monitor panel (`MonitorPort`, opened from the Budget chip) shows the agent's task graph, its usage and the kernel's process table. Most of it comes from pi durable as is:
|
|
623
|
-
- **Tasks:** `harness.watchTaskGraph()` gives every live task with its kind, owner, conversation, state and abort mark, a sleeping task's `until` and a blocked task's reason. The adapter shows a sleeping task with how long it still sleeps (`sleeps 30s`) and a blocked one (`blocked:
|
|
624
|
+
- **Tasks:** `harness.watchTaskGraph()` gives every live task with its kind, owner, conversation, state and abort mark, a sleeping task's `until` and a blocked task's reason. The adapter shows a sleeping task with how long it still sleeps (`sleeps 30s`) and a blocked one (`blocked: no definition`, `blocked: definition too old`, `blocked: migration failed`) as a warning. A task cut off by repeated restarts ends instead of parking, and `agent retry` cannot resume it. Generation retry backoffs still sleep, so a retrying agent's generation task sleeps until its next attempt.
|
|
624
625
|
- **Usage:** `harness.usage()` gives the session's tokens and cost. The cost is pi-ai's, recorded with each response.
|
|
625
|
-
- **Failures, retries and usage changes:** one `
|
|
626
|
+
- **Failures, retries and usage changes:** one `observeCommits` listener catches them.
|
|
626
627
|
- **Model latency:** the agent passes pi durable a telemetry context (`HarnessOptions.telemetry`, `src/timings.ts`) that keeps only pi-ai's `pi.ai.request` spans: provider, model, stop reason, duration and the time of the `pi.ai.first_chunk` event, the last 50 of them (`agent.timings`). pi's spans are content-free, and nothing else of them is kept. The feed's `latency` has the median duration and median time to the first chunk of the last 20 requests, how many failed, their durations as a series, and the median per model. The adapter shows it as the `Model latency` vital (`1.2 s`, `first chunk 400 ms · 1 failed`, the per-model medians as its hint). Requests outside the Harness, such as titles and the judge, aren't counted.
|
|
627
|
-
- **Reported failures:** pi durable's `onReport` gets what fails without failing the calling operation: a throwing section, hook or listener, a faulted
|
|
628
|
+
- **Reported failures:** pi durable's `onReport` gets what fails without failing the calling operation: a throwing section, hook or listener, a faulted task, a task cut off by repeated restarts, a failed migration, a host callback that threw, and the Session's own failure (`storage_failed`). The agent keeps the last 50 (`agent.reports`) whether or not the panel is open, and the feed adds them to `problems` as `kind: 'report'` with `report: { type, source }` (the extension or host callback, when known) and, when the report names a task, its `taskId`. The adapter names a row by its type and source (`sliccy · extension error (slicc-memory)`), shows it as a warning, and as an error with an alert for `storage_failed`, `task_faulted`, `task_interrupted` and `migration_failed`. A faulted task appears once, whether the report or the commit listener sees it first.
|
|
628
629
|
- **Agent state:** each agent's `pi.live`, `pi.inbox` and `pi.agent` come from the views the host already mounts. `inspect()` runs only on a resync.
|
|
629
630
|
|
|
630
631
|
The process table is the worker's root client's `ps()`. Each process is named after the agent whose process group it's in.
|
|
@@ -785,10 +786,10 @@ All the limits on approvals and guests live in one owner-changeable policy, the
|
|
|
785
786
|
- **The answer** carries `busy: true | false`, the state after any replay. Without the option it has no `busy`, and neither does an older agent's, so the page's OPENED leaves it out and the node can tell.
|
|
786
787
|
- **Then** a `{ t: 'busy', busy, why? }` line follows each flip, in order with the other events. It has no id and is never replayed. `why` (`cone`, `scoop:<name>`, `pending-lick`) comes only with `true`.
|
|
787
788
|
- **Busy** means, for the cone the stream belongs to (a scoop's own cone when `agent()` names a scoop): the cone has a run or a queued input (`pi.live`, `pi.inbox`); a live scoop of that cone has a run, a queued input or a feed (`ScoopWorkDoc.feeds`); or a lick is still to reach the cone or one of those scoops: a scoop `wait` still to deliver (`ScoopWorkDoc.waits`), or a lick pending in the licks outbox, a lick held there until its conversation's model is known (#475) included. A cron or file-watch lick counts once it is queued, not before. If the model never comes, `busy` stays true.
|
|
788
|
-
- **Computed** in the worker from the Session's commits (`
|
|
789
|
+
- **Computed** in the worker from the Session's commits (`observeCommits`, one consistent state per commit: the cone's and its scoops' `pi.live` and `pi.inbox`, `slicc.agents`, `slicc.scoops.work` and the licks outbox `slicc.licks`), never polled, and a line goes out only on a flip.
|
|
789
790
|
- **Ordering:** a `run` `start` never comes before its `busy: true` (one is sent first when needed), and a `busy: false` goes out only after the stream has delivered every event of the commits before it, so the last `busy: false` follows the last `run` `end`. A `busy: true` sent ahead of a run whose work had already ended by then is followed by its `false` the same way.
|
|
790
791
|
- **`abort()`** resolves `{ aborted }`, `false` when nothing was running.
|
|
791
|
-
- **Events** are `user`, `text`, `thinking` (only with `thinking`), `tool`, `tool-result`, `run`, `notice`, `error` and `busy` (only on a `watch` with `busy`). They are mapped in the worker from
|
|
792
|
+
- **Events** are `user`, `text`, `thinking` (only with `thinking`), `tool`, `tool-result`, `run`, `notice`, `error` and `busy` (only on a `watch` with `busy`). They are mapped in the worker from the conversation view (`pi.live` and new entries: run start and end, partial text, tool results, retries, compactions) and polled by the page over the `slicc.agent.remote` service.
|
|
792
793
|
- **Ids:** entry ids for committed entries, `a<timestamp>.<block>` for an assistant message's blocks (stable from the first delta to the committed entry; `~n` when timestamps collide), and unique ids for transient notices.
|
|
793
794
|
- **What leaves the worker:** tool summaries of at most 200 characters (the tool's name and main argument), result summaries (a line count, or an error's first line), secrets redacted; never tool output.
|
|
794
795
|
- **Bounds:** a stream nobody polls for two minutes is dropped, and one more than 10 000 events behind ends with `{ t: 'end', reason: 'error' }`.
|
|
@@ -859,14 +860,14 @@ Fixes to pi stay in this repository. [`patches/patches.json`](patches/patches.js
|
|
|
859
860
|
- `environment`: something the host must provide.
|
|
860
861
|
- pi-codemode runs QuickJS in a `node:worker_threads` Worker. slicc-bios must serve a `node:worker_threads` stub that wraps a module Web Worker; inside the worker, the stub gives `parentPort` and `workerData` from the first message. `test/integration/shims/node-worker-threads.js` is that stub, and the integration bundles alias to it.
|
|
861
862
|
- pi-mcp's index re-exports its stdio transport, which imports `node:child_process`, `node:process` and the CommonJS `cross-spawn` at the top. SLICC never constructs it, so slicc-bios's `node:*` stubs and CommonJS wrapping only have to let them load; `cross-spawn`, `which` and `isexe` also read the free globals `process` and `global` when they load. The MCP runtime is imported lazily, so if it fails to load, the agent still starts, and a configured `mcp.json` gets a lick saying MCP servers can't start. The integration bundles alias all three to `test/integration/shims/node-only.js`.
|
|
862
|
-
- `environment`, pruned from seven's install: slicc-bios's `/opt/agent` (its `src/packages/agent`) removes `@google/genai` with a pnpm override in `pnpm-workspace.yaml` (#22). Its `esbuild` override is moot since chord 1.2.0, which
|
|
863
|
+
- `environment`, pruned from seven's install: slicc-bios's `/opt/agent` (its `src/packages/agent`) removes `@google/genai` with a pnpm override in `pnpm-workspace.yaml` (#22). Its `esbuild` override is moot since chord 1.2.0, which does not depend on esbuild.
|
|
863
864
|
- A real Bedrock turn loads 28 of 95 installed packages and never those two trees. Adobe's APIs reach only `@anthropic-ai/sdk`, `openai` and `partial-json`, so those stay.
|
|
864
865
|
- The prune takes the install from 99 to 58 packages and `node_modules` from 143 to 92 MB.
|
|
865
866
|
- The markers keep pi-ai's two Google APIs (Gemini and Vertex) lazy. Seven offers only the Bedrock and Adobe providers: if a Google provider is ever added, the bios override has to go first, and a failing marker is the reminder.
|
|
866
867
|
|
|
867
868
|
`npm run lint:patches` (part of `npm run lint`) fails when an installed version differs from `patchedVersion`, a marker is gone, a monkeypatch isn't named in `src/patches.ts`, a patch file and its entry don't match, or `renovate.json` doesn't route the package to the `patched dependencies` group with automerge off. That group covers every `@earendil-works/*` package and `@aws-sdk/middleware-websocket`, so a pi bump is always a reviewed PR: rerun each entry's `verify`, then move `patchedVersion` forward or drop the entry.
|
|
868
869
|
|
|
869
|
-
**One Chord.** `@earendil-works/chord` is pinned to the version pi-durable pins (1.
|
|
870
|
+
**One Chord.** `@earendil-works/chord` is pinned to the version pi-durable pins (1.5.0), so the link, the serving code and pi-durable's state layer share one copy. `npm run lint:chord` (part of `npm run lint`) fails if the lockfile has a second Chord that the agent would load, or none. The `slicc-agent-5` devDependency brings its own Chords 1.2 and 1.3 for the version tests only, which the check skips because it's dev-only.
|
|
870
871
|
|
|
871
872
|
**pi-ai in lockstep with the vault.** The vault fills a model key only under the endpoints of its built-in table, which it generates from its own pi-ai pin and publishes as `"piAi"` in its package.json (slicc-vault 1.12.2 and later). `npm run lint:vault-pi` (part of `npm run lint`) fails when the installed `@ai-ecoverse/slicc-vault`'s `piAi` has another minor than our `@earendil-works/pi-ai`, or when it has none (an older vault). Renovate's `patched dependencies` group carries the `pi-ai-lockstep` label, as the vault's pi-ai updates do, so the two are found and bumped together.
|
|
872
873
|
|
package/dist/agent.js
CHANGED
|
@@ -44,7 +44,7 @@ async function openAgent(options) {
|
|
|
44
44
|
registry.install(scooped.extension);
|
|
45
45
|
const reports = createReports();
|
|
46
46
|
const timings = createTimings({
|
|
47
|
-
onError: (error) => reports.record(
|
|
47
|
+
onError: (error) => reports.record({ kind: "listener_error", error })
|
|
48
48
|
});
|
|
49
49
|
const harness = await Harness.open(
|
|
50
50
|
options.storage ?? new MemoryStorage(),
|
|
@@ -53,7 +53,7 @@ async function openAgent(options) {
|
|
|
53
53
|
registry,
|
|
54
54
|
identity: IDENTITY,
|
|
55
55
|
...options.settings ? { settings: options.settings } : {},
|
|
56
|
-
onReport: (
|
|
56
|
+
onReport: (report) => reports.record(report),
|
|
57
57
|
telemetry: timings.telemetry,
|
|
58
58
|
...options.clock ? clocked(options.clock) : {},
|
|
59
59
|
...options.env ? { env: options.env } : {},
|
package/dist/agent.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/agent.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Context } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Models } from '@earendil-works/pi-ai/models';\nimport {\n AssistantEntry,\n type Conversation,\n createRegistry,\n type EntryId,\n Harness,\n type HarnessOptions,\n MemoryStorage,\n type ModelRef,\n type Registry,\n type Storage,\n} from '@earendil-works/pi-durable';\nimport { type Agents, openAgents } from './agents.ts';\nimport type { Clock } from './clock.ts';\nimport type { Cones } from './cone.ts';\nimport { type GuestToolGate, guestToolGate } from './guests/guard.ts';\nimport { type GuestReviews, guestReviews } from './guests/review.ts';\nimport { type ScoopReviews, scoopReviews } from './guests/scoop.ts';\nimport { createReports, type Reports } from './reports.ts';\nimport { createTimings, type Timings } from './timings.ts';\n\nexport interface AgentOptions {\n models: Models;\n model: ModelRef;\n storage?: Storage;\n registry?: Registry;\n settings?: HarnessOptions['settings'];\n env?: HarnessOptions['env'];\n conversationCreated?: HarnessOptions['conversationCreated'];\n context?: Context;\n beforeResume?: (harness: Harness, context: Context) => Promise<unknown>;\n clock?: Clock;\n}\n\nexport interface Agent extends Cones {\n readonly harness: Harness;\n readonly models: Models;\n readonly root: Conversation;\n readonly agents: Agents;\n readonly reviews: GuestReviews;\n readonly gate: GuestToolGate;\n readonly scoopReviews: ScoopReviews;\n readonly reports: Reports;\n readonly timings: Timings;\n onCone(listener: (conversation: Conversation) => void | Promise<void>): () => void;\n prompt(text: string): Promise<string>;\n close(): Promise<void>;\n}\n\ninterface Block {\n type: string;\n text?: string;\n}\n\nexport function answerText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return (content as Block[])\n .filter((block) => block.type === 'text')\n .map((block) => block.text ?? '')\n .join('');\n}\n\nasync function prompt(root: Conversation, text: string, context: Context): Promise<string> {\n const submission = await root.submit({ type: 'input', content: text }, context);\n const settled = await submission.wait(context);\n const { answer, reason } = settled as { answer?: EntryId; reason?: string };\n if (answer === undefined) throw new Error(`unanswered: ${reason}`);\n const entry = await root.commit((tx) => tx.entry(AssistantEntry, answer), context);\n return answerText(entry?.model?.[0]?.content);\n}\n\nexport const SLICC_ATTRIBUTION = { name: 'SLICC', url: 'https://www.sliccy.com' };\nconst IDENTITY = { attribution: SLICC_ATTRIBUTION };\nfunction clocked(clock: Clock): Pick<HarnessOptions, 'now' | 'setTimer'> {\n return {\n now: () => clock.now(),\n setTimer: (callback, delayMs) => clock.setTimer(callback, delayMs),\n };\n}\n\nexport async function openAgent(options: AgentOptions): Promise<Agent> {\n const context = options.context ?? BACKGROUND_CONTEXT;\n const registry = options.registry ?? createRegistry();\n let opened: Harness | undefined;\n const gate = guestToolGate(() => opened);\n registry.install(gate.extension);\n const reviews = guestReviews();\n registry.install(reviews.extension);\n const scooped = scoopReviews();\n registry.install(scooped.extension);\n const reports = createReports();\n const timings = createTimings({\n onError: (error) => reports.record(
|
|
5
|
-
"mappings": "AACA,SAAS,0BAA0B;AAEnC;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,OAIK;AACP,SAAsB,kBAAkB;AAGxC,SAA6B,qBAAqB;AAClD,SAA4B,oBAAoB;AAChD,SAA4B,oBAAoB;AAChD,SAAS,qBAAmC;AAC5C,SAAS,qBAAmC;AAmCrC,SAAS,WAAW,SAA0B;AACnD,MAAI,OAAO,YAAY,SAAU,QAAO;A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context } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Models } from '@earendil-works/pi-ai/models';\nimport {\n AssistantEntry,\n type Conversation,\n createRegistry,\n type EntryId,\n Harness,\n type HarnessOptions,\n MemoryStorage,\n type ModelRef,\n type Registry,\n type Storage,\n} from '@earendil-works/pi-durable';\nimport { type Agents, openAgents } from './agents.ts';\nimport type { Clock } from './clock.ts';\nimport type { Cones } from './cone.ts';\nimport { type GuestToolGate, guestToolGate } from './guests/guard.ts';\nimport { type GuestReviews, guestReviews } from './guests/review.ts';\nimport { type ScoopReviews, scoopReviews } from './guests/scoop.ts';\nimport { createReports, type Reports } from './reports.ts';\nimport { createTimings, type Timings } from './timings.ts';\n\nexport interface AgentOptions {\n models: Models;\n model: ModelRef;\n storage?: Storage;\n registry?: Registry;\n settings?: HarnessOptions['settings'];\n env?: HarnessOptions['env'];\n conversationCreated?: HarnessOptions['conversationCreated'];\n context?: Context;\n beforeResume?: (harness: Harness, context: Context) => Promise<unknown>;\n clock?: Clock;\n}\n\nexport interface Agent extends Cones {\n readonly harness: Harness;\n readonly models: Models;\n readonly root: Conversation;\n readonly agents: Agents;\n readonly reviews: GuestReviews;\n readonly gate: GuestToolGate;\n readonly scoopReviews: ScoopReviews;\n readonly reports: Reports;\n readonly timings: Timings;\n onCone(listener: (conversation: Conversation) => void | Promise<void>): () => void;\n prompt(text: string): Promise<string>;\n close(): Promise<void>;\n}\n\ninterface Block {\n type: string;\n text?: string;\n}\n\nexport function answerText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (!Array.isArray(content)) return '';\n return (content as Block[])\n .filter((block) => block.type === 'text')\n .map((block) => block.text ?? '')\n .join('');\n}\n\nasync function prompt(root: Conversation, text: string, context: Context): Promise<string> {\n const submission = await root.submit({ type: 'input', content: text }, context);\n const settled = await submission.wait(context);\n const { answer, reason } = settled as { answer?: EntryId; reason?: string };\n if (answer === undefined) throw new Error(`unanswered: ${reason}`);\n const entry = await root.commit((tx) => tx.entry(AssistantEntry, answer), context);\n return answerText(entry?.model?.[0]?.content);\n}\n\nexport const SLICC_ATTRIBUTION = { name: 'SLICC', url: 'https://www.sliccy.com' };\nconst IDENTITY = { attribution: SLICC_ATTRIBUTION };\nfunction clocked(clock: Clock): Pick<HarnessOptions, 'now' | 'setTimer'> {\n return {\n now: () => clock.now(),\n setTimer: (callback, delayMs) => clock.setTimer(callback, delayMs),\n };\n}\n\nexport async function openAgent(options: AgentOptions): Promise<Agent> {\n const context = options.context ?? BACKGROUND_CONTEXT;\n const registry = options.registry ?? createRegistry();\n let opened: Harness | undefined;\n const gate = guestToolGate(() => opened);\n registry.install(gate.extension);\n const reviews = guestReviews();\n registry.install(reviews.extension);\n const scooped = scoopReviews();\n registry.install(scooped.extension);\n const reports = createReports();\n const timings = createTimings({\n onError: (error) => reports.record({ kind: 'listener_error', error }),\n });\n const harness = await Harness.open(\n options.storage ?? new MemoryStorage(),\n {\n models: options.models,\n registry,\n identity: IDENTITY,\n ...(options.settings ? { settings: options.settings } : {}),\n onReport: (report) => reports.record(report),\n telemetry: timings.telemetry,\n ...(options.clock ? clocked(options.clock) : {}),\n ...(options.env ? { env: options.env } : {}),\n ...(options.conversationCreated ? { conversationCreated: options.conversationCreated } : {}),\n },\n context\n );\n opened = harness;\n const root = await harness.root(context, { agent: { model: options.model } });\n const agents = await openAgents(harness, root, context);\n await options.beforeResume?.(harness, context);\n harness.resume();\n return {\n harness,\n models: options.models,\n root,\n agents,\n reviews,\n gate,\n scoopReviews: scooped,\n reports,\n timings,\n cone: () => agents.cone(),\n switchCone: (conversation, switching) => agents.switchCone(conversation, switching),\n onCone: (listener) => agents.onCone(listener),\n prompt: (text) => prompt(agents.cone(), text, context),\n close: () => harness.close(context),\n };\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,0BAA0B;AAEnC;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,OAIK;AACP,SAAsB,kBAAkB;AAGxC,SA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OAAO,KAAK,GAAG,MAAM,OAAO;AAAA,IACrD,OAAO,MAAM,QAAQ,MAAM,OAAO;AAAA,EACpC;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/approvals/index.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
replicatedState
|
|
3
|
+
} from "@earendil-works/chord";
|
|
2
4
|
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
3
5
|
import {
|
|
4
6
|
APPROVAL_MS,
|
|
@@ -72,8 +74,8 @@ const judgedIn = (id, judgement, now) => (doc) => {
|
|
|
72
74
|
}
|
|
73
75
|
return copy([item])[0];
|
|
74
76
|
};
|
|
75
|
-
function following(
|
|
76
|
-
const items = () =>
|
|
77
|
+
function following(watch, changed) {
|
|
78
|
+
const items = () => watch.value.items;
|
|
77
79
|
let shown = items();
|
|
78
80
|
return (using) => {
|
|
79
81
|
const now = items();
|
|
@@ -136,15 +138,16 @@ async function attachApprovals(options, context = BACKGROUND_CONTEXT) {
|
|
|
136
138
|
}
|
|
137
139
|
}, context);
|
|
138
140
|
const state = replicatedState(startup.items);
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
);
|
|
143
|
-
const follow = following(committed, (using, items) => {
|
|
141
|
+
const watch = await harness.watchDoc(ApprovalsDoc, context);
|
|
142
|
+
if (!watch) throw new Error("approvals document is missing");
|
|
143
|
+
const follow = following(watch, (using, items) => {
|
|
144
144
|
state.replace(using, items);
|
|
145
145
|
arm(items);
|
|
146
146
|
});
|
|
147
|
-
|
|
147
|
+
follow(context);
|
|
148
|
+
watch.start(async (call, using) => {
|
|
149
|
+
if (call.kind === "value") follow(using);
|
|
150
|
+
});
|
|
148
151
|
const serial = (change, using) => {
|
|
149
152
|
const run = line.then(async () => {
|
|
150
153
|
const { result } = await write(change, using);
|
|
@@ -275,6 +278,7 @@ async function attachApprovals(options, context = BACKGROUND_CONTEXT) {
|
|
|
275
278
|
closed = true;
|
|
276
279
|
for (const timer of timers.values()) timer();
|
|
277
280
|
timers.clear();
|
|
281
|
+
void watch.stop();
|
|
278
282
|
}
|
|
279
283
|
};
|
|
280
284
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/approvals/index.ts"],
|
|
4
|
-
"sourcesContent": ["import { type Context, type ReplicatedState, replicatedState } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { DocumentState, Harness } from '@earendil-works/pi-durable';\nimport type { Clock } from '../clock.ts';\nimport type { ApprovalJudge, 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 cleanReason,\n type DecidedBy,\n guestKind,\n knownTier,\n MAX_DELAY,\n prune,\n REASONS,\n routable,\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 './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' | 'documentState'>;\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}\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 if (how.reason) item.reason = how.reason;\n}\n\nconst offered = (options: ApprovalsAttach, draft: ApprovalDraft): boolean =>\n guestKind(draft.kind) ? options.guestAlways?.(draft.kind) === true : draft.always === true;\n\nfunction fresh(\n draft: ApprovalDraft & { id?: string },\n at: number,\n ttl: number,\n options: ApprovalsAttach\n): Approval {\n const item = {\n ...draft,\n tier: tierOf(draft.kind, draft.tier, sudoApprover(options.sudoApprover?.())),\n id: draft.id ?? `apr-${crypto.randomUUID()}`,\n state: 'pending',\n decidedBy: null,\n always: offered(options, draft),\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\nconst judgedIn = (id: string, judgement: Judgement, now: () => number) => (doc: ApprovalsState) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.tier !== 'agent') 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 if (judgement.verdict) item.verdict = judgement.verdict;\n if (late) return copy([item])[0] as Approval;\n if (judgement.outcome === 'ask') item.tier = 'user';\n else {\n const at = now();\n const ruling = ruled(\n item,\n judgement.outcome === 'approve' ? 'once' : 'deny',\n null,\n 'judge',\n at\n );\n if (ruling.answer) item.answer = ruling.answer;\n if (ruling.settle) mark(item, ruling.settle, at);\n }\n return copy([item])[0] as Approval;\n};\n\nfunction following(\n committed: DocumentState<ApprovalsState>,\n changed: (using: Context, items: Approval[]) => void\n) {\n const items = () => (committed.value as ApprovalsState).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 (item.kind === 'sudo')\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 }\n }, context);\n const state = replicatedState<Approval[]>(startup.items);\n const committed = (await harness.documentState(\n ApprovalsDoc,\n context\n )) as DocumentState<ApprovalsState>;\n const follow = following(committed, (using, items) => {\n state.replace(using, items);\n arm(items);\n });\n committed.subscribe((_value, using) => follow(using));\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 = 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 withdrawWhere((entry) => entry.id === item.id && entry.tier === 'agent', REASONS.aborted),\n BACKGROUND_CONTEXT\n ).catch(() => undefined);\n };\n if (signal?.aborted) return abort();\n signal?.addEventListener('abort', abort, { once: true });\n const judgement = await judge\n .judge(item, using)\n .catch((error: unknown): Judgement => ({ outcome: 'ask', error: String(error) }));\n signal?.removeEventListener('abort', abort);\n if (gone || closed) return;\n const after = await serial(judgedIn(item.id, judgement, now), BACKGROUND_CONTEXT).catch(\n () => undefined\n );\n if (after) await judge.record?.(after, judgement, BACKGROUND_CONTEXT).catch(() => undefined);\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' && made.tier === 'agent')\n void judging(options.judge, made, using);\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 },\n };\n}\n"],
|
|
5
|
-
"mappings": "AAAA,
|
|
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, 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 cleanReason,\n type DecidedBy,\n guestKind,\n knownTier,\n MAX_DELAY,\n prune,\n REASONS,\n routable,\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 './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}\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 if (how.reason) item.reason = how.reason;\n}\n\nconst offered = (options: ApprovalsAttach, draft: ApprovalDraft): boolean =>\n guestKind(draft.kind) ? options.guestAlways?.(draft.kind) === true : draft.always === true;\n\nfunction fresh(\n draft: ApprovalDraft & { id?: string },\n at: number,\n ttl: number,\n options: ApprovalsAttach\n): Approval {\n const item = {\n ...draft,\n tier: tierOf(draft.kind, draft.tier, sudoApprover(options.sudoApprover?.())),\n id: draft.id ?? `apr-${crypto.randomUUID()}`,\n state: 'pending',\n decidedBy: null,\n always: offered(options, draft),\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\nconst judgedIn = (id: string, judgement: Judgement, now: () => number) => (doc: ApprovalsState) => {\n const item = doc.items.find((entry) => entry.id === id);\n if (item?.tier !== 'agent') 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 if (judgement.verdict) item.verdict = judgement.verdict;\n if (late) return copy([item])[0] as Approval;\n if (judgement.outcome === 'ask') item.tier = 'user';\n else {\n const at = now();\n const ruling = ruled(\n item,\n judgement.outcome === 'approve' ? 'once' : 'deny',\n null,\n 'judge',\n at\n );\n if (ruling.answer) item.answer = ruling.answer;\n if (ruling.settle) mark(item, ruling.settle, at);\n }\n return copy([item])[0] as Approval;\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 (item.kind === 'sudo')\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 }\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 = 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 withdrawWhere((entry) => entry.id === item.id && entry.tier === 'agent', REASONS.aborted),\n BACKGROUND_CONTEXT\n ).catch(() => undefined);\n };\n if (signal?.aborted) return abort();\n signal?.addEventListener('abort', abort, { once: true });\n const judgement = await judge\n .judge(item, using)\n .catch((error: unknown): Judgement => ({ outcome: 'ask', error: String(error) }));\n signal?.removeEventListener('abort', abort);\n if (gone || closed) return;\n const after = await serial(judgedIn(item.id, judgement, now), BACKGROUND_CONTEXT).catch(\n () => undefined\n );\n if (after) await judge.record?.(after, judgement, BACKGROUND_CONTEXT).catch(() => undefined);\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' && made.tier === 'agent')\n void judging(options.judge, made, using);\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;AAInC;AAAA,EACE;AAAA,EAKA;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,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;AAAA,QAClB,cAAc,CAAC,SAAS,KAAK,OAAO,IAAI,YAAY,MAAM,CAAC;AAAA,QAC3D;AAAA,MACF;AACA,aAAO;AAAA,IACT;AAAA,IACA,MAAM,aAAa,MAAM,OAAO;AAC9B,cACE,MAAM;AAAA,QACJ,cAAc,CAAC,SAAS,KAAK,SAAS,MAAM,QAAQ,OAAO;AAAA,QAC3D;AAAA,MACF,GACA;AAAA,IACJ;AAAA,IACA,MAAM,OAAO,IAAI,OAAO;AACtB,aAAO,OAAO,CAAC,QAAQ;AACrB,cAAM,OAAO,IAAI,MAAM,KAAK,CAAC,UAAU,MAAM,OAAO,EAAE;AACtD,YAAI,MAAM,UAAU,aAAa,KAAK,aAAa,IAAI;AACrD,iBAAO,MAAM,EAAE,OAAO,cAAc,IAAI,QAAQ,QAAQ,QAAQ,QAAQ,CAAC;AAC3E,eAAO,OAAQ,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC,IAAiB;AAAA,MAChD,GAAG,KAAK;AAAA,IACV;AAAA,IACA,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
|
}
|
package/dist/changes/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/changes/index.ts"],
|
|
4
|
-
"sourcesContent": ["import { type Context, type MutableReplicatedState, replicatedState } from '@earendil-works/chord';\nimport type { ExecutionEnv, FileWatcher } from '@earendil-works/pi-durable/env';\nimport type { Agents } from '../agents.ts';\nimport { HOME } from '../kernel/env.ts';\nimport {\n BATCH_BYTES,\n type ChangesView,\n type FileChange,\n failure,\n joined,\n MAX_FILES,\n MAX_TEXT,\n NO_GIT,\n NO_REPO,\n type Pending,\n parseBatch,\n parseCheck,\n parseStatus,\n quote,\n relative,\n run,\n SCAN_DEPTH,\n SCAN_ENTRIES,\n STATUS,\n type Stored,\n scanned,\n shown,\n textOf,\n within,\n} from './git.ts';\n\nexport interface ChangesRuntime {\n readonly view: MutableReplicatedState<ChangesView>;\n open(context: Context): Promise<void>;\n accept(path: string, context: Context): Promise<void>;\n revert(path: string, context: Context): Promise<void>;\n refresh(context: Context): Promise<void>;\n close(context: Context): Promise<void>;\n}\n\nexport const CHANGES_MS = 500;\n\nexport interface ChangesOptions {\n env: ExecutionEnv;\n agents: Agents;\n reloadMs: number;\n}\n\nconst WATCHED = [HOME, '/mnt', '/scoops'];\nconst EXCLUDED = ['/tmp', '/var/lib/slicc'];\n\ntype Env = ChangesOptions['env'];\n\nasync function walk(env: Env, dir: string, depth: number, out: Set<string>, context: Context) {\n const listed = await env.listDir(dir, context);\n if (!listed.ok) return;\n if (listed.value.some((entry) => entry.name === '.git')) {\n out.add(dir);\n return;\n }\n if (depth >= SCAN_DEPTH) return;\n const dirs = listed.value\n .filter((entry) => entry.kind === 'directory' && scanned(entry.name))\n .slice(0, SCAN_ENTRIES);\n for (const entry of dirs) await walk(env, entry.path, depth + 1, out, context);\n}\n\nasync function cwds(agents: Agents, context: Context): Promise<string[]> {\n const state = agents.state();\n const ids = [\n state.active,\n ...Object.keys(state.cones).filter((id) => id !== state.active),\n ...Object.entries(state.scoops)\n .filter(([, scoop]) => !scoop.gone && !scoop.dropped && !scoop.frozen)\n .map(([id]) => id),\n ];\n const out: string[] = [];\n for (const id of ids) {\n const conversation = await agents.conversation(id, context);\n if (conversation) out.push((await conversation.agent(context)).cwd ?? HOME);\n }\n return out;\n}\n\nasync function discover(options: ChangesOptions, context: Context): Promise<string[]> {\n const { env } = options;\n const found: string[] = [];\n for (const cwd of await cwds(options.agents, context)) {\n const top = await run(env, ['git', 'rev-parse', '--show-toplevel'], cwd, context);\n if (top.code === 0 && top.out.trim()) found.push(top.out.trim());\n }\n const walked = new Set<string>();\n await walk(env, HOME, 0, walked, context);\n const mounts = await env.listDir('/mnt', context);\n if (mounts.ok)\n for (const mount of mounts.value)\n if (mount.kind === 'directory') await walk(env, mount.path, 0, walked, context);\n const ordered = [...found, ...[...walked].sort()];\n return [...new Set(ordered)].filter(\n (root) => !EXCLUDED.some((excluded) => within(root, excluded))\n );\n}\n\nconst piped = (words: readonly string[], command: string) =>\n `printf '%s\\\\n' ${words.map(quote).join(' ')} | ${command}`;\n\nasync function shownOne(env: Env, repo: string, path: string, context: Context) {\n const ran = await run(env, ['git', 'show', `:${path}`], repo, context);\n return ran.code === 0 ? shown(ran.out) : null;\n}\n\nfunction chunked(items: readonly Stored[]): Stored[][] {\n const out: Stored[][] = [];\n let bytes = Infinity;\n for (const item of items) {\n if (bytes + item.size > BATCH_BYTES) {\n out.push([]);\n bytes = 0;\n }\n out.at(-1)?.push(item);\n bytes += item.size;\n }\n return out;\n}\n\nasync function befores(\n env: Env,\n repo: string,\n pending: readonly Pending[],\n context: Context\n): Promise<Map<string, string | null>> {\n const paths = pending.filter((item) => item.status !== 'added').map((item) => item.path);\n const out = new Map<string, string | null>();\n if (!paths.length) return out;\n const listing = paths.some((path) => path.includes('\\n'))\n ? null\n : await run(\n env,\n piped(\n paths.map((path) => `:${path}`),\n 'git cat-file --batch-check'\n ),\n repo,\n context\n );\n const checked = listing?.code === 0 ? parseCheck(listing.out, paths) : null;\n if (!checked) {\n for (const path of paths) out.set(path, await shownOne(env, repo, path, context));\n return out;\n }\n for (const path of paths) out.set(path, null);\n const small = checked.filter((item) => item.size <= MAX_TEXT);\n for (const chunk of chunked(small)) {\n const batch = await run(\n env,\n piped(\n chunk.map((item) => item.oid),\n 'git cat-file --batch'\n ),\n repo,\n context\n );\n const parsed =\n batch.code === 0 && !batch.out.includes('\\uFFFD')\n ? parseBatch(new TextEncoder().encode(batch.out), chunk.length)\n : null;\n for (const [i, item] of chunk.entries()) {\n const bytes = parsed?.[i];\n out.set(\n item.path,\n parsed ? (bytes ? textOf(bytes) : null) : await shownOne(env, repo, item.path, context)\n );\n }\n }\n return out;\n}\n\nasync function sideOf(\n env: Env,\n repo: string,\n pending: Pending,\n before: string | null,\n context: Context\n) {\n const path = joined(repo, pending.path);\n const read = pending.status === 'deleted' ? null : await env.readBinaryFile(path, context);\n const after = read?.ok ? textOf(read.value) : null;\n const opaque =\n (pending.status !== 'added' && before === null) ||\n (pending.status !== 'deleted' && after === null);\n return { path, before: opaque ? null : before, after: opaque ? null : after };\n}\n\nasync function statusOf(env: Env, repo: string, context: Context): Promise<FileChange[] | null> {\n const ran = await run(env, STATUS, repo, context);\n if (ran.code !== 0) return null;\n const pending = parseStatus(ran.out).slice(0, MAX_FILES);\n const before = await befores(env, repo, pending, context);\n const out: FileChange[] = [];\n for (const item of pending) {\n const side = await sideOf(env, repo, item, before.get(item.path) ?? null, context);\n out.push({ ...side, repo, status: item.status, kind: item.kind });\n }\n return out.sort((a, b) => a.path.localeCompare(b.path));\n}\n\nconst STATE = ['index', 'HEAD', 'refs'];\n\ntype Target = Pick<FileChange, 'path' | 'repo' | 'kind'>;\n\nfunction noise(path: string, repos: readonly string[]): boolean {\n return repos.some((repo) => {\n const git = joined(repo, '.git');\n return (\n within(path, git) &&\n path !== git &&\n !STATE.includes(relative(path, git).split('/')[0] as string)\n );\n });\n}\n\nfunction rediscovers(paths: readonly string[], repos: readonly string[]): boolean {\n return paths.some((path) => {\n const parts = path.split('/');\n const git = parts.indexOf('.git');\n if (git > 0) return !repos.includes(parts.slice(0, git).join('/') || '/');\n if (parts.some((part) => part && !scanned(part))) return false;\n return !repos.some((repo) => within(path, repo));\n });\n}\n\nexport function attachChanges(options: ChangesOptions): ChangesRuntime {\n const { env } = options;\n const view = replicatedState<ChangesView>({ unavailable: null, changes: [] });\n let repos: string[] | null = null;\n let opened: Promise<void> | null = null;\n let watcher: FileWatcher | undefined;\n let stop = () => undefined as void;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let lock: Promise<unknown> = Promise.resolve();\n const serial = <T>(work: () => Promise<T>): Promise<T> => {\n const next = lock.then(work, work);\n lock = next.catch(() => undefined);\n return next;\n };\n const hasGit = async (context: Context) =>\n (await run(env, 'command -v git', HOME, context)).code === 0;\n const missing = (context: Context) => {\n repos = null;\n view.replace(context, { unavailable: NO_GIT, changes: [] });\n };\n const scan = async (context: Context) => {\n if (!repos?.length && !(await hasGit(context))) return missing(context);\n repos ??= await discover(options, context);\n const changes: FileChange[] = [];\n const live: string[] = [];\n let checked = false;\n for (const repo of repos) {\n const found = await statusOf(env, repo, context);\n if (!found) {\n if (!checked && !(await hasGit(context))) return missing(context);\n checked = true;\n const still = await env.exists(joined(repo, '.git'), context);\n if (!still.ok || !still.value) continue;\n }\n live.push(repo);\n changes.push(...(found ?? view.value.changes.filter((change) => change.repo === repo)));\n }\n repos = live;\n view.replace(context, { unavailable: live.length ? null : NO_REPO, changes });\n };\n const pendingOf = async (path: string, context: Context): Promise<Target | null> => {\n const listed = () => view.value.changes.find((item) => item.path === path);\n if (!listed()) await scan(context);\n const repo = listed()?.repo;\n if (!repo) return null;\n const rel = relative(path, repo);\n const ran = await run(env, [...STATUS, '--', `:(literal)${rel}`], repo, context);\n if (ran.code !== 0) throw failure(ran, `git status ${rel}`);\n const fresh = parseStatus(ran.out).find((item) => item.path === rel);\n if (fresh) return { path, repo, kind: fresh.kind };\n await scan(context);\n return null;\n };\n const refresh = (context: Context) => serial(() => scan(context));\n let running = false;\n let again = false;\n const kick = async (context: Context) => {\n if (running) {\n again = true;\n return;\n }\n running = true;\n do {\n again = false;\n await refresh(context).catch(() => undefined);\n } while (again);\n running = false;\n };\n const later = (context: Context) => {\n clearTimeout(timer);\n timer = setTimeout(() => void kick(context), options.reloadMs);\n };\n const change = (path: string, context: Context, act: (found: Target) => Promise<void>) =>\n serial(async () => {\n const found = await pendingOf(path, context);\n if (!found) throw new Error(`${path} has no pending change`);\n await act(found);\n await scan(context);\n });\n const start = async (context: Context) => {\n await refresh(context);\n const watched = await env.watch(\n WATCHED.map((path) => ({ path, recursive: true, exclude: { names: ['node_modules'] } })),\n (change) => {\n const known = repos ?? [];\n const paths = 'paths' in change ? change.paths.filter((path) => !noise(path, known)) : null;\n if (paths?.length === 0) return;\n if (!paths || rediscovers(paths, known)) repos = null;\n later(context);\n },\n context\n );\n watcher = watched.ok ? watched.value : undefined;\n stop = options.agents.onChange(() => {\n repos = null;\n later(context);\n });\n };\n return {\n view,\n open(context) {\n opened ??= start(context);\n return opened;\n },\n accept: (path, context) =>\n change(path, context, async (found) => {\n const rel = relative(found.path, found.repo);\n const ran = await run(env, ['git', 'add', '-A', '--', rel], found.repo, context);\n if (ran.code !== 0) throw failure(ran, `git add ${rel}`);\n }),\n revert: (path, context) =>\n change(path, context, async (found) => {\n const rel = relative(found.path, found.repo);\n if (found.kind === 'conflict')\n throw new Error(`${found.path} has a merge conflict; resolve it with git first.`);\n if (found.kind === 'untracked') {\n const removed = await env.remove(found.path, { force: true }, context);\n if (!removed.ok) throw removed.error;\n } else {\n const ran = await run(env, ['git', 'restore', '--', rel], found.repo, context);\n if (ran.code !== 0) throw failure(ran, `git restore ${rel}`);\n }\n }),\n refresh,\n async close(context) {\n clearTimeout(timer);\n stop();\n await watcher?.close(context);\n },\n };\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAoD,uBAAuB;AAG3E,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAWA,MAAM,aAAa;AAQ1B,MAAM,UAAU,CAAC,MAAM,QAAQ,SAAS;AACxC,MAAM,WAAW,CAAC,QAAQ,gBAAgB;AAI1C,eAAe,KAAK,KAAU,KAAa,OAAe,KAAkB,SAAkB;AAC5F,QAAM,SAAS,MAAM,IAAI,QAAQ,KAAK,O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ACT;AAAA,IACA,QAAQ,CAAC,MAAM,YACb,OAAO,MAAM,SAAS,OAAO,UAAU;AACrC,YAAM,MAAM,SAAS,MAAM,MAAM,MAAM,IAAI;AAC3C,YAAM,MAAM,MAAM,IAAI,KAAK,CAAC,OAAO,OAAO,MAAM,MAAM,GAAG,GAAG,MAAM,MAAM,OAAO;AAC/E,UAAI,IAAI,SAAS,EAAG,OAAM,QAAQ,KAAK,WAAW,GAAG,EAAE;AAAA,IACzD,CAAC;AAAA,IACH,QAAQ,CAAC,MAAM,YACb,OAAO,MAAM,SAAS,OAAO,UAAU;AACrC,YAAM,MAAM,SAAS,MAAM,MAAM,MAAM,IAAI;AAC3C,UAAI,MAAM,SAAS;AACjB,cAAM,IAAI,MAAM,GAAG,MAAM,IAAI,mDAAmD;AAClF,UAAI,MAAM,SAAS,aAAa;AAC9B,cAAM,UAAU,MAAM,IAAI,OAAO,MAAM,MAAM,EAAE,OAAO,KAAK,GAAG,OAAO;AACrE,YAAI,CAAC,QAAQ,GAAI,OAAM,QAAQ;AAAA,MACjC,OAAO;AACL,cAAM,MAAM,MAAM,IAAI,KAAK,CAAC,OAAO,WAAW,MAAM,GAAG,GAAG,MAAM,MAAM,OAAO;AAC7E,YAAI,IAAI,SAAS,EAAG,OAAM,QAAQ,KAAK,eAAe,GAAG,EAAE;AAAA,MAC7D;AAAA,IACF,CAAC;AAAA,IACH;AAAA,IACA,MAAM,MAAM,SAAS;AACnB,mBAAa,KAAK;AAClB,WAAK;AACL,YAAM,SAAS,
|
|
4
|
+
"sourcesContent": ["import { type Context, type MutableReplicatedState, replicatedState } from '@earendil-works/chord';\nimport type { ExecutionEnv, FileWatcher } from '@earendil-works/pi-durable/env';\nimport type { Agents } from '../agents.ts';\nimport { HOME } from '../kernel/env.ts';\nimport {\n BATCH_BYTES,\n type ChangesView,\n type FileChange,\n failure,\n joined,\n MAX_FILES,\n MAX_TEXT,\n NO_GIT,\n NO_REPO,\n type Pending,\n parseBatch,\n parseCheck,\n parseStatus,\n quote,\n relative,\n run,\n SCAN_DEPTH,\n SCAN_ENTRIES,\n STATUS,\n type Stored,\n scanned,\n shown,\n textOf,\n within,\n} from './git.ts';\n\nexport interface ChangesRuntime {\n readonly view: MutableReplicatedState<ChangesView>;\n open(context: Context): Promise<void>;\n accept(path: string, context: Context): Promise<void>;\n revert(path: string, context: Context): Promise<void>;\n refresh(context: Context): Promise<void>;\n close(context: Context): Promise<void>;\n}\n\nexport const CHANGES_MS = 500;\n\nexport interface ChangesOptions {\n env: ExecutionEnv;\n agents: Agents;\n reloadMs: number;\n}\n\nconst WATCHED = [HOME, '/mnt', '/scoops'];\nconst EXCLUDED = ['/tmp', '/var/lib/slicc'];\n\ntype Env = ChangesOptions['env'];\n\nasync function walk(env: Env, dir: string, depth: number, out: Set<string>, context: Context) {\n const listed = await env.listDir(dir, context);\n if (!listed.ok) return;\n if (listed.value.some((entry) => entry.name === '.git')) {\n out.add(dir);\n return;\n }\n if (depth >= SCAN_DEPTH) return;\n const dirs = listed.value\n .filter((entry) => entry.kind === 'directory' && scanned(entry.name))\n .slice(0, SCAN_ENTRIES);\n for (const entry of dirs) await walk(env, entry.path, depth + 1, out, context);\n}\n\nasync function cwds(agents: Agents, context: Context): Promise<string[]> {\n const state = agents.state();\n const ids = [\n state.active,\n ...Object.keys(state.cones).filter((id) => id !== state.active),\n ...Object.entries(state.scoops)\n .filter(([, scoop]) => !scoop.gone && !scoop.dropped && !scoop.frozen)\n .map(([id]) => id),\n ];\n const out: string[] = [];\n for (const id of ids) {\n const conversation = await agents.conversation(id, context);\n if (conversation) out.push((await conversation.agent(context)).cwd ?? HOME);\n }\n return out;\n}\n\nasync function discover(options: ChangesOptions, context: Context): Promise<string[]> {\n const { env } = options;\n const found: string[] = [];\n for (const cwd of await cwds(options.agents, context)) {\n const top = await run(env, ['git', 'rev-parse', '--show-toplevel'], cwd, context);\n if (top.code === 0 && top.out.trim()) found.push(top.out.trim());\n }\n const walked = new Set<string>();\n await walk(env, HOME, 0, walked, context);\n const mounts = await env.listDir('/mnt', context);\n if (mounts.ok)\n for (const mount of mounts.value)\n if (mount.kind === 'directory') await walk(env, mount.path, 0, walked, context);\n const ordered = [...found, ...[...walked].sort()];\n return [...new Set(ordered)].filter(\n (root) => !EXCLUDED.some((excluded) => within(root, excluded))\n );\n}\n\nconst piped = (words: readonly string[], command: string) =>\n `printf '%s\\\\n' ${words.map(quote).join(' ')} | ${command}`;\n\nasync function shownOne(env: Env, repo: string, path: string, context: Context) {\n const ran = await run(env, ['git', 'show', `:${path}`], repo, context);\n return ran.code === 0 ? shown(ran.out) : null;\n}\n\nfunction chunked(items: readonly Stored[]): Stored[][] {\n const out: Stored[][] = [];\n let bytes = Infinity;\n for (const item of items) {\n if (bytes + item.size > BATCH_BYTES) {\n out.push([]);\n bytes = 0;\n }\n out.at(-1)?.push(item);\n bytes += item.size;\n }\n return out;\n}\n\nasync function befores(\n env: Env,\n repo: string,\n pending: readonly Pending[],\n context: Context\n): Promise<Map<string, string | null>> {\n const paths = pending.filter((item) => item.status !== 'added').map((item) => item.path);\n const out = new Map<string, string | null>();\n if (!paths.length) return out;\n const listing = paths.some((path) => path.includes('\\n'))\n ? null\n : await run(\n env,\n piped(\n paths.map((path) => `:${path}`),\n 'git cat-file --batch-check'\n ),\n repo,\n context\n );\n const checked = listing?.code === 0 ? parseCheck(listing.out, paths) : null;\n if (!checked) {\n for (const path of paths) out.set(path, await shownOne(env, repo, path, context));\n return out;\n }\n for (const path of paths) out.set(path, null);\n const small = checked.filter((item) => item.size <= MAX_TEXT);\n for (const chunk of chunked(small)) {\n const batch = await run(\n env,\n piped(\n chunk.map((item) => item.oid),\n 'git cat-file --batch'\n ),\n repo,\n context\n );\n const parsed =\n batch.code === 0 && !batch.out.includes('\\uFFFD')\n ? parseBatch(new TextEncoder().encode(batch.out), chunk.length)\n : null;\n for (const [i, item] of chunk.entries()) {\n const bytes = parsed?.[i];\n out.set(\n item.path,\n parsed ? (bytes ? textOf(bytes) : null) : await shownOne(env, repo, item.path, context)\n );\n }\n }\n return out;\n}\n\nasync function sideOf(\n env: Env,\n repo: string,\n pending: Pending,\n before: string | null,\n context: Context\n) {\n const path = joined(repo, pending.path);\n const read = pending.status === 'deleted' ? null : await env.readBinaryFile(path, context);\n const after = read?.ok ? textOf(read.value) : null;\n const opaque =\n (pending.status !== 'added' && before === null) ||\n (pending.status !== 'deleted' && after === null);\n return { path, before: opaque ? null : before, after: opaque ? null : after };\n}\n\nasync function statusOf(env: Env, repo: string, context: Context): Promise<FileChange[] | null> {\n const ran = await run(env, STATUS, repo, context);\n if (ran.code !== 0) return null;\n const pending = parseStatus(ran.out).slice(0, MAX_FILES);\n const before = await befores(env, repo, pending, context);\n const out: FileChange[] = [];\n for (const item of pending) {\n const side = await sideOf(env, repo, item, before.get(item.path) ?? null, context);\n out.push({ ...side, repo, status: item.status, kind: item.kind });\n }\n return out.sort((a, b) => a.path.localeCompare(b.path));\n}\n\nconst STATE = ['index', 'HEAD', 'refs'];\n\ntype Target = Pick<FileChange, 'path' | 'repo' | 'kind'>;\n\nfunction noise(path: string, repos: readonly string[]): boolean {\n return repos.some((repo) => {\n const git = joined(repo, '.git');\n return (\n within(path, git) &&\n path !== git &&\n !STATE.includes(relative(path, git).split('/')[0] as string)\n );\n });\n}\n\nfunction rediscovers(paths: readonly string[], repos: readonly string[]): boolean {\n return paths.some((path) => {\n const parts = path.split('/');\n const git = parts.indexOf('.git');\n if (git > 0) return !repos.includes(parts.slice(0, git).join('/') || '/');\n if (parts.some((part) => part && !scanned(part))) return false;\n return !repos.some((repo) => within(path, repo));\n });\n}\n\nexport function attachChanges(options: ChangesOptions): ChangesRuntime {\n const { env } = options;\n const view = replicatedState<ChangesView>({ unavailable: null, changes: [] });\n let repos: string[] | null = null;\n let opened: Promise<void> | null = null;\n let watcher: FileWatcher | undefined;\n let stop = () => undefined as void;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let lock: Promise<unknown> = Promise.resolve();\n const serial = <T>(work: () => Promise<T>): Promise<T> => {\n const next = lock.then(work, work);\n lock = next.catch(() => undefined);\n return next;\n };\n const hasGit = async (context: Context) =>\n (await run(env, 'command -v git', HOME, context)).code === 0;\n const missing = (context: Context) => {\n repos = null;\n view.replace(context, { unavailable: NO_GIT, changes: [] });\n };\n const scan = async (context: Context) => {\n if (!repos?.length && !(await hasGit(context))) return missing(context);\n repos ??= await discover(options, context);\n const changes: FileChange[] = [];\n const live: string[] = [];\n let checked = false;\n for (const repo of repos) {\n const found = await statusOf(env, repo, context);\n if (!found) {\n if (!checked && !(await hasGit(context))) return missing(context);\n checked = true;\n const still = await env.exists(joined(repo, '.git'), context);\n if (!still.ok || !still.value) continue;\n }\n live.push(repo);\n changes.push(...(found ?? view.value.changes.filter((change) => change.repo === repo)));\n }\n repos = live;\n view.replace(context, { unavailable: live.length ? null : NO_REPO, changes });\n };\n const pendingOf = async (path: string, context: Context): Promise<Target | null> => {\n const listed = () => view.value.changes.find((item) => item.path === path);\n if (!listed()) await scan(context);\n const repo = listed()?.repo;\n if (!repo) return null;\n const rel = relative(path, repo);\n const ran = await run(env, [...STATUS, '--', `:(literal)${rel}`], repo, context);\n if (ran.code !== 0) throw failure(ran, `git status ${rel}`);\n const fresh = parseStatus(ran.out).find((item) => item.path === rel);\n if (fresh) return { path, repo, kind: fresh.kind };\n await scan(context);\n return null;\n };\n const refresh = (context: Context) => serial(() => scan(context));\n let running = false;\n let again = false;\n const kick = async (context: Context) => {\n if (running) {\n again = true;\n return;\n }\n running = true;\n do {\n again = false;\n await refresh(context).catch(() => undefined);\n } while (again);\n running = false;\n };\n const later = (context: Context) => {\n clearTimeout(timer);\n timer = setTimeout(() => void kick(context), options.reloadMs);\n };\n const change = (path: string, context: Context, act: (found: Target) => Promise<void>) =>\n serial(async () => {\n const found = await pendingOf(path, context);\n if (!found) throw new Error(`${path} has no pending change`);\n await act(found);\n await scan(context);\n });\n const start = async (context: Context) => {\n await refresh(context);\n const watched = await env.watch(\n WATCHED.map((path) => ({ path, recursive: true, exclude: { names: ['node_modules'] } })),\n (change) => {\n const known = repos ?? [];\n const paths = 'paths' in change ? change.paths.filter((path) => !noise(path, known)) : null;\n if (paths?.length === 0) return;\n if (!paths || rediscovers(paths, known)) repos = null;\n later(context);\n },\n context\n );\n watcher = watched.ok ? watched.value : undefined;\n stop = options.agents.onChange(() => {\n repos = null;\n later(context);\n });\n };\n return {\n view,\n open(context) {\n opened ??= start(context);\n return opened;\n },\n accept: (path, context) =>\n change(path, context, async (found) => {\n const rel = relative(found.path, found.repo);\n const ran = await run(env, ['git', 'add', '-A', '--', rel], found.repo, context);\n if (ran.code !== 0) throw failure(ran, `git add ${rel}`);\n }),\n revert: (path, context) =>\n change(path, context, async (found) => {\n const rel = relative(found.path, found.repo);\n if (found.kind === 'conflict')\n throw new Error(`${found.path} has a merge conflict; resolve it with git first.`);\n if (found.kind === 'untracked') {\n const removed = await env.remove(found.path, { force: true }, context);\n if (!removed.ok) throw removed.error;\n } else {\n const ran = await run(env, ['git', 'restore', '--', rel], found.repo, context);\n if (ran.code !== 0) throw failure(ran, `git restore ${rel}`);\n }\n }),\n refresh,\n async close(context) {\n clearTimeout(timer);\n stop();\n await watcher?.stop(context);\n },\n };\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAoD,uBAAuB;AAG3E,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAWA,MAAM,aAAa;AAQ1B,MAAM,UAAU,CAAC,MAAM,QAAQ,SAAS;AACxC,MAAM,WAAW,CAAC,QAAQ,gBAAgB;AAI1C,eAAe,KAAK,KAAU,KAAa,OAAe,KAAkB,SAAkB;AAC5F,QAAM,SAAS,MAAM,I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AACxB,aAAO;AAAA,IACT;AAAA,IACA,QAAQ,CAAC,MAAM,YACb,OAAO,MAAM,SAAS,OAAO,UAAU;AACrC,YAAM,MAAM,SAAS,MAAM,MAAM,MAAM,IAAI;AAC3C,YAAM,MAAM,MAAM,IAAI,KAAK,CAAC,OAAO,OAAO,MAAM,MAAM,GAAG,GAAG,MAAM,MAAM,OAAO;AAC/E,UAAI,IAAI,SAAS,EAAG,OAAM,QAAQ,KAAK,WAAW,GAAG,EAAE;AAAA,IACzD,CAAC;AAAA,IACH,QAAQ,CAAC,MAAM,YACb,OAAO,MAAM,SAAS,OAAO,UAAU;AACrC,YAAM,MAAM,SAAS,MAAM,MAAM,MAAM,IAAI;AAC3C,UAAI,MAAM,SAAS;AACjB,cAAM,IAAI,MAAM,GAAG,MAAM,IAAI,mDAAmD;AAClF,UAAI,MAAM,SAAS,aAAa;AAC9B,cAAM,UAAU,MAAM,IAAI,OAAO,MAAM,MAAM,EAAE,OAAO,KAAK,GAAG,OAAO;AACrE,YAAI,CAAC,QAAQ,GAAI,OAAM,QAAQ;AAAA,MACjC,OAAO;AACL,cAAM,MAAM,MAAM,IAAI,KAAK,CAAC,OAAO,WAAW,MAAM,GAAG,GAAG,MAAM,MAAM,OAAO;AAC7E,YAAI,IAAI,SAAS,EAAG,OAAM,QAAQ,KAAK,eAAe,GAAG,EAAE;AAAA,MAC7D;AAAA,IACF,CAAC;AAAA,IACH;AAAA,IACA,MAAM,MAAM,SAAS;AACnB,mBAAa,KAAK;AAClB,WAAK;AACL,YAAM,SAAS,KAAK,OAAO;AAAA,IAC7B;AAAA,EACF;AACF;",
|
|
6
6
|
"names": ["change"]
|
|
7
7
|
}
|
package/dist/codemode/index.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { withAbortSignal } from "@earendil-works/chord/context";
|
|
2
|
-
import { Type } from "@earendil-works/pi-ai";
|
|
3
2
|
import {
|
|
4
3
|
CodemodeSandbox,
|
|
5
4
|
loadQuickJSWasm,
|
|
@@ -11,6 +10,7 @@ import {
|
|
|
11
10
|
defineExtension,
|
|
12
11
|
defineTool
|
|
13
12
|
} from "@earendil-works/pi-durable";
|
|
13
|
+
import { obj, str } from "@earendil-works/pi-schema";
|
|
14
14
|
import { boundedDeltas } from "../checkpoints.js";
|
|
15
15
|
import { scrubItems } from "../secrets/scrub.js";
|
|
16
16
|
const CODEMODE = "codemode";
|
|
@@ -171,7 +171,7 @@ function codemodeTool(options) {
|
|
|
171
171
|
return defineTool({
|
|
172
172
|
name: CODEMODE,
|
|
173
173
|
description: codemodeDescription(options.declared, options.extra !== void 0),
|
|
174
|
-
parameters:
|
|
174
|
+
parameters: obj({ code: str({ description: "Raw JavaScript source." }) }),
|
|
175
175
|
replay: "unsafe",
|
|
176
176
|
callers: ["model"],
|
|
177
177
|
async execute({ code }, api, context) {
|
|
@@ -234,11 +234,11 @@ Output:
|
|
|
234
234
|
function codemodeExtension(tools) {
|
|
235
235
|
return defineExtension({ name: "slicc-codemode", tools });
|
|
236
236
|
}
|
|
237
|
-
function disabledBySettings(text) {
|
|
237
|
+
function disabledBySettings(text, tool = CODEMODE) {
|
|
238
238
|
if (!text) return false;
|
|
239
239
|
try {
|
|
240
240
|
const settings = JSON.parse(text);
|
|
241
|
-
return Array.isArray(settings.defaultTools) && settings.defaultTools.includes(`-${
|
|
241
|
+
return Array.isArray(settings.defaultTools) && settings.defaultTools.includes(`-${tool}`);
|
|
242
242
|
} catch {
|
|
243
243
|
return false;
|
|
244
244
|
}
|