@ai-ecoverse/slicc-agent 3.44.0 → 3.45.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 +5 -2
- package/dist/browser/guard.js +2 -8
- package/dist/browser/guard.js.map +2 -2
- package/dist/index.js +3 -1
- package/dist/index.js.map +2 -2
- package/dist/kernel/loopback.js +17 -0
- package/dist/kernel/loopback.js.map +7 -0
- package/dist/main.js +7 -2
- package/dist/main.js.map +2 -2
- package/dist/net.js +14 -1
- package/dist/net.js.map +2 -2
- package/dist/secrets/extension.js +1 -4
- package/dist/secrets/extension.js.map +2 -2
- package/dist/secrets/vault.js +4 -3
- package/dist/secrets/vault.js.map +2 -2
- package/dist/secrets/view.js +15 -0
- package/dist/secrets/view.js.map +7 -0
- package/dist/spectrum/agent-port.js +61 -4
- package/dist/spectrum/agent-port.js.map +2 -2
- package/dist/spectrum/messages.js +13 -0
- package/dist/spectrum/messages.js.map +2 -2
- package/dist/types/browser/guard.d.ts +2 -2
- package/dist/types/index.d.ts +1 -1
- package/dist/types/kernel/client.d.ts +4 -0
- package/dist/types/kernel/loopback.d.ts +4 -0
- package/dist/types/net.d.ts +6 -1
- package/dist/types/secrets/extension.d.ts +2 -2
- package/dist/types/secrets/view.d.ts +9 -0
- package/dist/types/spectrum/agent-port.d.ts +7 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -85,7 +85,7 @@ At boot, the worker sets `/.slicc`, where the session database lives in OPFS, to
|
|
|
85
85
|
### The worker seven starts
|
|
86
86
|
|
|
87
87
|
`@ai-ecoverse/slicc-agent/agent-worker` is a complete agent worker. It waits for the page kernel's port, then:
|
|
88
|
-
- attaches to the kernel and routes its cross-origin `fetch` through the kernel's transport when that transport isn't bound by CORS (slicc-node, slicc-swift or slicc-extension);
|
|
88
|
+
- attaches to the kernel and routes its cross-origin `fetch` through the kernel's transport when that transport isn't bound by CORS (slicc-node, slicc-swift or slicc-extension), and every `<port>.kernel.localhost` request to the kernel's loopback (`loopbackFetch`);
|
|
89
89
|
- opens the encrypted credential store, the AWS Bedrock provider and the session in OPFS SQLite;
|
|
90
90
|
- installs durable's coding tools and SLICC's system prompt, and serves the agent.
|
|
91
91
|
|
|
@@ -308,6 +308,8 @@ A codemode script waits up to 10 s for servers still connecting. For the model,
|
|
|
308
308
|
|
|
309
309
|
**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 run slicc-node, slicc-swift or the extension. 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.
|
|
310
310
|
|
|
311
|
+
**Kernel servers.** A server a kernel program serves with `ctx.net.listen` on the kernel's loopback works as `"url": "http://<port>.kernel.localhost/mcp"`, as for [mcpcat](https://github.com/ai-ecoverse/mcpcat)'s `mcpcat serve --proxy <name> --http <port>`, which bridges a stdio server to HTTP. The worker's fetch hands every `<port>.kernel.localhost` request to the kernel client's `loopbackFetch` on that port, whatever the transport, so it needs no CORS headers, no service worker and no open `/os/` tab, SSE streams have no idle limit, and the request carries no `Origin`. The URL's own port is ignored, as slicc-bios ignores it. The route shares the browser guard's rule (`ownKernelServer`): any other `*.kernel.localhost` name, the CDP facade's `9222.kernel.localhost` included, fails before anything is sent, so no URL in a config can drive SLICC's own pages. `test/integration/mcp-loopback.test.mjs` runs a JS kernel program as the server and calls its tool on the page and relay routes, with a JSON-RPC answer streamed as SSE, and checks that an entry on 9222 is refused.
|
|
312
|
+
|
|
311
313
|
**Limiting a server** until approvals (PR 25): `"enabled": false`; `"exposure": "hidden"` with a `toolExposure` allow list; `toolExposure` deny patterns; role and `--tools` lists for scoops; and tokens or scopes that allow only what the server should do.
|
|
312
314
|
|
|
313
315
|
### Memory
|
|
@@ -546,10 +548,11 @@ The agent never holds a secret's value. Values live in the vault (`vault.sliccy.
|
|
|
546
548
|
- **`slicc-secrets`**, a built-in extension modelled on [pi-fnox](https://github.com/Bucurenciu-Cristian/pi-fnox) (MIT, © 2026 Kicky), with its hooks mapped to pi-durable: `secret list --json` in the home env at start and whenever `version` changes (pi-fnox's `fnox export`; nothing goes into the worker's environment); an `afterTool` hook scrubbing every result's text, diagnostics and string `details` (pi-fnox's `tool_result`); a `secrets` system section with the names, placeholders, where each works and how to use them (`before_agent_start`); and `/secrets`, answered locally as a `slicc.secrets` entry (`/fnox-list`; reloading is automatic). When at least one secret is `shell = true`, every conversation command runs as `fnox exec --shell-grants -- <argv>` (pi-fnox's `spawnHook`). slicc-agent doesn't depend on `@kickythrust/pi-fnox`. Every conversation keeps the extension: new ones are pinned at creation, and conversations stored with an extension list that lacks it get it back at start.
|
|
547
549
|
- **Where text is scrubbed before anything keeps or cuts it:** command output, per stream, before the bash tool's tail window, the spill file and the live slot; `read`'s bytes (images aren't, and files over 8 MiB stream in 1 MiB chunks); MCP results before their middle cut and progress text; codemode output before its cut; user and remote sends after skill expansion; every lick (sprinkle sends and scoop results included) before triage and the outbox; and memory writes, before the pattern redaction. Remote-control summaries are built from stored entries only.
|
|
548
550
|
- **The hold.** A vault that doesn't answer within 2 s reads as `waiting`. Nothing unscrubbed is appended: tool results, sends and licks wait in memory, model requests wait before they start, and command output held past 32 MiB kills the command with "output held: waiting for the vault". The state is the transcript's `vault` field (`{ port, needed, version, locked, held }`), and remote `watch` streams get a `notice` "waiting for the vault" and one when it answers again.
|
|
551
|
+
- **In spectrum.** The agent port's `hold()` is `{ reason: 'locked', held }` while the vault needs a passkey, `{ reason: 'waiting', held }` while scrubbing is needed and the port isn't `ready`, and `null` otherwise, with a `hold` event on each change (and `null` when it clears); spectrum (≥ 1.62.0) shows it above the composer, and older spectrum ignores it. While a hold is up, the worker's active cone is busy (`working` when it isn't running), so the composer steers and queues; a send made during the hold waits in the tab, shown in that cone's queue, and goes to the worker once the hold clears; removing it before then means it's never sent. `/secrets` entries (`slicc.secrets`) show as a "Secrets listed" notice.
|
|
549
552
|
|
|
550
553
|
## The kernel
|
|
551
554
|
|
|
552
|
-
`@ai-ecoverse/slicc-kernel` is a peer dependency (`>=1.47.1 <2`, the first kernel with users and the H1 wasm commands; until 3.31.0 the floor was 1.26.3): the agent only calls `attachKernel`, the client end of the page kernel's port, so it must match the kernel the page runs. Seven chooses that version: slicc-bios pins the certified kernel next to the agent in `src/packages/agent/package.json`, and pnpm fills the peer from that pin. The devDependency is the lowest certified kernel the range allows (1.47.1), and the unit and integration tests run on it with the H1 wasm commands as devDependencies. A second CI job reruns the integration tests on the newest certified kernel (`NEWEST_CERTIFIED_KERNEL` in `.github/workflows/ci.yml`), with the wasm commands certified for it (`NEWEST_CERTIFIED_WASM`). Today the floor is 1.47.1 and the newest certified kernel 1.
|
|
555
|
+
`@ai-ecoverse/slicc-kernel` is a peer dependency (`>=1.47.1 <2`, the first kernel with users and the H1 wasm commands; until 3.31.0 the floor was 1.26.3): the agent only calls `attachKernel`, the client end of the page kernel's port, so it must match the kernel the page runs. Seven chooses that version: slicc-bios pins the certified kernel next to the agent in `src/packages/agent/package.json`, and pnpm fills the peer from that pin. The devDependency is the lowest certified kernel the range allows (1.47.1), and the unit and integration tests run on it with the H1 wasm commands as devDependencies. A second CI job reruns the integration tests on the newest certified kernel (`NEWEST_CERTIFIED_KERNEL` in `.github/workflows/ci.yml`), with the wasm commands certified for it (`NEWEST_CERTIFIED_WASM`). Today the floor is 1.47.1 and the newest certified kernel 1.65.2; the second job moves by hand to each newer certified kernel, so both ends of the range are tested. If the port protocol ever breaks within 1.x, a patch release narrows the upper bound. Renovate opens PRs for the kernel, `wasi-pnpm`, the `wasm-*` packages and `slicc-cdp` but never merges them, because they move only after the homescoop coordinator certifies them.
|
|
553
556
|
|
|
554
557
|
## Patched dependencies
|
|
555
558
|
|
package/dist/browser/guard.js
CHANGED
|
@@ -4,11 +4,11 @@ import {
|
|
|
4
4
|
ToolTask,
|
|
5
5
|
wrapTool
|
|
6
6
|
} from "@earendil-works/pi-durable";
|
|
7
|
+
import { FACADE_PORT, kernelHost, ownKernelServer } from "../kernel/loopback.js";
|
|
7
8
|
import { PROTECTED_RULES, protectedMatcher } from "./origins.js";
|
|
8
9
|
import { words } from "./shell.js";
|
|
9
10
|
const BROWSER_GUARD = "slicc-browser-guard";
|
|
10
11
|
const REFUSAL = "SLICC's own pages can't be opened or driven from the browser tools.";
|
|
11
|
-
const FACADE_PORT = 9222;
|
|
12
12
|
const BROWSER = /* @__PURE__ */ new Set(["playwright-cli", "curlwright"]);
|
|
13
13
|
const WEB = /* @__PURE__ */ new Set(["http:", "https:", "ws:", "wss:"]);
|
|
14
14
|
const INNER = new Set(PROTECTED_RULES.innerSchemes.map((scheme) => `${scheme}:`));
|
|
@@ -16,8 +16,6 @@ const SCHEMED = /^[a-z][a-z0-9+.-]*:/i;
|
|
|
16
16
|
const EMBEDDED = /[a-z][a-z0-9+.-]*:\/\/[^\s'"`<>(){}\\]+/gi;
|
|
17
17
|
const RELATIVE = /(?<![:\w/])\/\/[^\s'"`<>(){}\\/]+/g;
|
|
18
18
|
const PREFIX = /^(?:[A-Za-z_][A-Za-z0-9_]*|-{1,2}[A-Za-z0-9-]+)=/;
|
|
19
|
-
const KERNEL = "kernel.localhost";
|
|
20
|
-
const OWN_KERNEL = /^([1-9][0-9]{0,4})\.kernel\.localhost$/;
|
|
21
19
|
function parse(url) {
|
|
22
20
|
try {
|
|
23
21
|
return new URL(url);
|
|
@@ -25,17 +23,13 @@ function parse(url) {
|
|
|
25
23
|
return void 0;
|
|
26
24
|
}
|
|
27
25
|
}
|
|
28
|
-
function ownKernelServer(host) {
|
|
29
|
-
const port = OWN_KERNEL.exec(host)?.[1];
|
|
30
|
-
return port !== void 0 && Number(port) <= 65535 && Number(port) !== FACADE_PORT;
|
|
31
|
-
}
|
|
32
26
|
function foreignKernel(url) {
|
|
33
27
|
let parsed = parse(url);
|
|
34
28
|
for (let depth = 0; parsed && INNER.has(parsed.protocol) && depth < 8; depth++)
|
|
35
29
|
parsed = parse(parsed.href.slice(parsed.protocol.length));
|
|
36
30
|
if (!parsed || !WEB.has(parsed.protocol)) return false;
|
|
37
31
|
const host = parsed.hostname.replace(/\.+$/, "");
|
|
38
|
-
return (host
|
|
32
|
+
return kernelHost(host) && !ownKernelServer(host);
|
|
39
33
|
}
|
|
40
34
|
function forbidden(url, matcher) {
|
|
41
35
|
return matcher.url(url) || foreignKernel(url);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/browser/guard.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n defineExtension,\n type Extension,\n hook,\n type ToolRegistration,\n ToolTask,\n wrapTool,\n} from '@earendil-works/pi-durable';\nimport { PROTECTED_RULES, type ProtectedMatcher, protectedMatcher } from './origins.ts';\nimport { words } from './shell.ts';\n\nexport const BROWSER_GUARD = 'slicc-browser-guard';\nexport const REFUSAL = \"SLICC's own pages can't be opened or driven from the browser tools.\";\nexport
|
|
5
|
-
"mappings": "AAAA;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AACP,SAAS,iBAAwC,wBAAwB;AACzE,SAAS,aAAa;AAEf,MAAM,gBAAgB;AACtB,MAAM,UAAU;
|
|
4
|
+
"sourcesContent": ["import {\n defineExtension,\n type Extension,\n hook,\n type ToolRegistration,\n ToolTask,\n wrapTool,\n} from '@earendil-works/pi-durable';\nimport { FACADE_PORT, kernelHost, ownKernelServer } from '../kernel/loopback.ts';\nimport { PROTECTED_RULES, type ProtectedMatcher, protectedMatcher } from './origins.ts';\nimport { words } from './shell.ts';\n\nexport const BROWSER_GUARD = 'slicc-browser-guard';\nexport const REFUSAL = \"SLICC's own pages can't be opened or driven from the browser tools.\";\nexport { FACADE_PORT, ownKernelServer };\n\nconst BROWSER = new Set(['playwright-cli', 'curlwright']);\nconst WEB = new Set(['http:', 'https:', 'ws:', 'wss:']);\nconst INNER = new Set(PROTECTED_RULES.innerSchemes.map((scheme) => `${scheme}:`));\nconst SCHEMED = /^[a-z][a-z0-9+.-]*:/i;\nconst EMBEDDED = /[a-z][a-z0-9+.-]*:\\/\\/[^\\s'\"`<>(){}\\\\]+/gi;\nconst RELATIVE = /(?<![:\\w/])\\/\\/[^\\s'\"`<>(){}\\\\/]+/g;\nconst PREFIX = /^(?:[A-Za-z_][A-Za-z0-9_]*|-{1,2}[A-Za-z0-9-]+)=/;\n\nfunction parse(url: string): URL | undefined {\n try {\n return new URL(url);\n } catch {\n return undefined;\n }\n}\n\nexport function foreignKernel(url: string): boolean {\n let parsed = parse(url);\n for (let depth = 0; parsed && INNER.has(parsed.protocol) && depth < 8; depth++)\n parsed = parse(parsed.href.slice(parsed.protocol.length));\n if (!parsed || !WEB.has(parsed.protocol)) return false;\n const host = parsed.hostname.replace(/\\.+$/, '');\n return kernelHost(host) && !ownKernelServer(host);\n}\n\nexport function forbidden(url: string, matcher: ProtectedMatcher): boolean {\n return matcher.url(url) || foreignKernel(url);\n}\n\nexport function candidates(raw: string): string[] {\n const word = raw.replace(/[\\t\\n\\r]/g, '').replace(/^[\\0- ]+|[\\0- ]+$/g, '');\n const value = word.replace(PREFIX, '');\n const found = [\n word,\n value,\n ...(value.match(EMBEDDED) ?? []),\n ...(value.match(RELATIVE) ?? []).map((relative) => `https:${relative}`),\n ];\n if (!/^[/.~-]/.test(value) && !/^[a-z][a-z0-9+.-]*:\\/\\//i.test(value))\n found.push(`https://${value}`);\n if (value.startsWith('//')) found.push(`https:${value}`);\n return found.filter((each) => SCHEMED.test(each));\n}\n\nfunction browserCommand(word: string): boolean {\n return BROWSER.has(word.slice(word.lastIndexOf('/') + 1));\n}\n\nexport function refused(command: string, matcher: ProtectedMatcher): boolean {\n const all = words(command);\n if (!all.some(browserCommand)) return false;\n return all.some((word) => candidates(word).some((url) => forbidden(url, matcher)));\n}\n\nfunction commandOf(args: unknown): string {\n const command = (args as { command?: unknown } | undefined)?.command;\n return typeof command === 'string' ? command : '';\n}\n\nexport function browserGuard(\n origins: readonly string[],\n tools: readonly ToolRegistration[]\n): Extension {\n const bash = tools.find((tool) => tool.name === 'bash') as ToolRegistration;\n const matcher = protectedMatcher(origins);\n return defineExtension({\n name: BROWSER_GUARD,\n hooks: [\n hook(ToolTask, {\n beforeTool: (call) =>\n call.name === bash.name && refused(commandOf(call.arguments), matcher)\n ? { block: REFUSAL }\n : undefined,\n }),\n ],\n wraps: [\n wrapTool(bash, (inner) => ({\n ...inner,\n execute(args, api, context) {\n if (!refused(commandOf(args), matcher)) return inner.execute(args, api, context);\n return Promise.resolve({ content: [{ type: 'text', text: REFUSAL }], isError: true });\n },\n })),\n ],\n });\n}\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EACE;AAAA,EAEA;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa,YAAY,uBAAuB;AACzD,SAAS,iBAAwC,wBAAwB;AACzE,SAAS,aAAa;AAEf,MAAM,gBAAgB;AACtB,MAAM,UAAU;AAGvB,MAAM,UAAU,oBAAI,IAAI,CAAC,kBAAkB,YAAY,CAAC;AACxD,MAAM,MAAM,oBAAI,IAAI,CAAC,SAAS,UAAU,OAAO,MAAM,CAAC;AACtD,MAAM,QAAQ,IAAI,IAAI,gBAAgB,aAAa,IAAI,CAAC,WAAW,GAAG,MAAM,GAAG,CAAC;AAChF,MAAM,UAAU;AAChB,MAAM,WAAW;AACjB,MAAM,WAAW;AACjB,MAAM,SAAS;AAEf,SAAS,MAAM,KAA8B;AAC3C,MAAI;AACF,WAAO,IAAI,IAAI,GAAG;AAAA,EACpB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,cAAc,KAAsB;AAClD,MAAI,SAAS,MAAM,GAAG;AACtB,WAAS,QAAQ,GAAG,UAAU,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,QAAQ,UAAU,KAAK,OAAO,CAAC,CAAC;AACnF;AAEA,SAAS,UAAU,MAAuB;AACxC,QAAM,UAAW,MAA4C;AAC7D,SAAO,OAAO,YAAY,WAAW,UAAU;AACjD;AAEO,SAAS,aACd,SACA,OACW;AACX,QAAM,OAAO,MAAM,KAAK,CAAC,SAAS,KAAK,SAAS,MAAM;AACtD,QAAM,UAAU,iBAAiB,OAAO;AACxC,SAAO,gBAAgB;AAAA,IACrB,MAAM;AAAA,IACN,OAAO;AAAA,MACL,KAAK,UAAU;AAAA,QACb,YAAY,CAAC,SACX,KAAK,SAAS,KAAK,QAAQ,QAAQ,UAAU,KAAK,SAAS,GAAG,OAAO,IACjE,EAAE,OAAO,QAAQ,IACjB;AAAA,MACR,CAAC;AAAA,IACH;AAAA,IACA,OAAO;AAAA,MACL,SAAS,MAAM,CAAC,WAAW;AAAA,QACzB,GAAG;AAAA,QACH,QAAQ,MAAM,KAAK,SAAS;AAC1B,cAAI,CAAC,QAAQ,UAAU,IAAI,GAAG,OAAO,EAAG,QAAO,MAAM,QAAQ,MAAM,KAAK,OAAO;AAC/E,iBAAO,QAAQ,QAAQ,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,QAAQ,CAAC,GAAG,SAAS,KAAK,CAAC;AAAA,QACtF;AAAA,MACF,EAAE;AAAA,IACJ;AAAA,EACF,CAAC;AACH;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/index.ts"],
|
|
4
|
-
"sourcesContent": ["export {\n ADOBE,\n ADOBE_PROXY,\n type AdobeConfig,\n type AdobeModelInfo,\n adobeClassifiers,\n adobeConfig,\n adobeModel,\n adobeProvider,\n adobeUsage,\n type Budget,\n} from './adobe.ts';\nexport { type Agent, type AgentOptions, answerText, openAgent } from './agent.ts';\nexport { type AgentConnection, connectAgent } from './client.ts';\nexport { createAgentControl } from './control.ts';\nexport { CREDENTIALS_DATABASE, EncryptedCredentialStore } from './credentials.ts';\nexport { type AgentHost, type ConnectOptions, hostAgent } from './host.ts';\nexport type {\n KernelClient,\n KernelFs,\n KernelProcess,\n KernelStat,\n SpawnOptions,\n} from './kernel/client.ts';\nexport { HOME, type KernelEnvOptions, kernelEnvironment, SliccKernelEnv } from './kernel/env.ts';\nexport {\n adminOver,\n type KernelAdmin,\n type KernelUser,\n type KernelUsers,\n serveAdmin,\n type UserClient,\n type UserClients,\n type UserConnect,\n type UserSpec,\n userClients,\n} from './kernel/users.ts';\nexport { PortListener } from './listener.ts';\nexport {\n type AgentWorkerOptions,\n type AgentWorkerScope,\n type KernelAttach,\n runAgentWorker,\n} from './main.ts';\nexport { type Transport
|
|
5
|
-
"mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAwC,YAAY,iBAAiB;AACrE,SAA+B,oBAAoB;AACnD,SAAS,0BAA0B;AACnC,SAAS,sBAAsB,gCAAgC;AAC/D,SAA8C,iBAAiB;AAQ/D,SAAS,MAA6B,mBAAmB,sBAAsB;AAC/E;AAAA,EACE;AAAA,EAIA;AAAA,EAKA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B;AAAA,EAIE;AAAA,OACK;AACP,
|
|
4
|
+
"sourcesContent": ["export {\n ADOBE,\n ADOBE_PROXY,\n type AdobeConfig,\n type AdobeModelInfo,\n adobeClassifiers,\n adobeConfig,\n adobeModel,\n adobeProvider,\n adobeUsage,\n type Budget,\n} from './adobe.ts';\nexport { type Agent, type AgentOptions, answerText, openAgent } from './agent.ts';\nexport { type AgentConnection, connectAgent } from './client.ts';\nexport { createAgentControl } from './control.ts';\nexport { CREDENTIALS_DATABASE, EncryptedCredentialStore } from './credentials.ts';\nexport { type AgentHost, type ConnectOptions, hostAgent } from './host.ts';\nexport type {\n KernelClient,\n KernelFs,\n KernelProcess,\n KernelStat,\n SpawnOptions,\n} from './kernel/client.ts';\nexport { HOME, type KernelEnvOptions, kernelEnvironment, SliccKernelEnv } from './kernel/env.ts';\nexport {\n adminOver,\n type KernelAdmin,\n type KernelUser,\n type KernelUsers,\n serveAdmin,\n type UserClient,\n type UserClients,\n type UserConnect,\n type UserSpec,\n userClients,\n} from './kernel/users.ts';\nexport { PortListener } from './listener.ts';\nexport {\n type AgentWorkerOptions,\n type AgentWorkerScope,\n type KernelAttach,\n runAgentWorker,\n} from './main.ts';\nexport {\n type Loopback,\n type Transport,\n type TransportResponse,\n transportFetch,\n} from './net.ts';\nexport {\n AGENT_LOCK,\n type AgentOwner,\n type AgentWorker,\n type KernelSource,\n type OwnerOptions,\n startAgent,\n} from './owner.ts';\nexport { applyPatches, patchServerAccept } from './patches.ts';\nexport { SliccPrompt, sliccPrompt } from './prompt.ts';\nexport {\n type AgentPages,\n createPages,\n type PageBatch,\n type PageCaller,\n type PageRequest,\n type PageResult,\n type Pages,\n type PagesOpened,\n type PageTab,\n} from './remote/pages.ts';\nexport {\n type AccountState,\n AGENT_SESSION,\n AgentControl,\n AgentPagesService,\n AgentSessions,\n AgentSettings,\n type AgentSettingsChange,\n AgentTranscript,\n type BudgetState,\n type ModelChoice,\n type OperationError,\n type PromptResult,\n type SendMode,\n type SendRequest,\n type SendResponse,\n type SettingsState,\n type SignIn,\n} from './services.ts';\nexport {\n BEDROCK,\n createAgentSettings,\n createSliccModels,\n DEFAULT_MODEL,\n DEFAULT_REGIONS,\n sliccProviders,\n withDefaultRegions,\n} from './settings.ts';\nexport {\n AGENT_DIRECTORY,\n type OpfsSqliteOptions,\n openMemorySqliteStorage,\n openOpfsSqliteStorage,\n WasmSqliteDatabase,\n} from './sqlite.ts';\nexport { type SystemFacts, systemSection } from './system.ts';\nexport { PortChannel, type PortEndpoint, withUnrefTimers } from './wire.ts';\nexport {\n type KernelPorts,\n kernelPort,\n kernelPorts,\n serveConnections,\n type WorkerScope,\n} from './worker.ts';\n"],
|
|
5
|
+
"mappings": "AAAA;AAAA,EACE;AAAA,EACA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAwC,YAAY,iBAAiB;AACrE,SAA+B,oBAAoB;AACnD,SAAS,0BAA0B;AACnC,SAAS,sBAAsB,gCAAgC;AAC/D,SAA8C,iBAAiB;AAQ/D,SAAS,MAA6B,mBAAmB,sBAAsB;AAC/E;AAAA,EACE;AAAA,EAIA;AAAA,EAKA;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B;AAAA,EAIE;AAAA,OACK;AACP;AAAA,EAIE;AAAA,OACK;AACP;AAAA,EACE;AAAA,EAKA;AAAA,OACK;AACP,SAAS,cAAc,yBAAyB;AAChD,SAAS,aAAa,mBAAmB;AACzC;AAAA,EAEE;AAAA,OAQK;AACP;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,OAUK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAA2B,qBAAqB;AAChD,SAAS,aAAgC,uBAAuB;AAChE;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
const FACADE_PORT = 9222;
|
|
2
|
+
const KERNEL = "kernel.localhost";
|
|
3
|
+
const OWN_KERNEL = /^([1-9][0-9]{0,4})\.kernel\.localhost$/;
|
|
4
|
+
function ownKernelServer(host) {
|
|
5
|
+
const port = OWN_KERNEL.exec(host)?.[1];
|
|
6
|
+
return port !== void 0 && Number(port) <= 65535 && Number(port) !== FACADE_PORT;
|
|
7
|
+
}
|
|
8
|
+
function kernelHost(host) {
|
|
9
|
+
return host === KERNEL || host.endsWith(`.${KERNEL}`);
|
|
10
|
+
}
|
|
11
|
+
export {
|
|
12
|
+
FACADE_PORT,
|
|
13
|
+
KERNEL,
|
|
14
|
+
kernelHost,
|
|
15
|
+
ownKernelServer
|
|
16
|
+
};
|
|
17
|
+
//# sourceMappingURL=loopback.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/kernel/loopback.ts"],
|
|
4
|
+
"sourcesContent": ["export const FACADE_PORT = 9222;\nexport const KERNEL = 'kernel.localhost';\nconst OWN_KERNEL = /^([1-9][0-9]{0,4})\\.kernel\\.localhost$/;\n\nexport function ownKernelServer(host: string): boolean {\n const port = OWN_KERNEL.exec(host)?.[1];\n return port !== undefined && Number(port) <= 65535 && Number(port) !== FACADE_PORT;\n}\n\nexport function kernelHost(host: string): boolean {\n return host === KERNEL || host.endsWith(`.${KERNEL}`);\n}\n"],
|
|
5
|
+
"mappings": "AAAO,MAAM,cAAc;AACpB,MAAM,SAAS;AACtB,MAAM,aAAa;AAEZ,SAAS,gBAAgB,MAAuB;AACrD,QAAM,OAAO,WAAW,KAAK,IAAI,IAAI,CAAC;AACtC,SAAO,SAAS,UAAa,OAAO,IAAI,KAAK,SAAS,OAAO,IAAI,MAAM;AACzE;AAEO,SAAS,WAAW,MAAuB;AAChD,SAAO,SAAS,UAAU,KAAK,SAAS,IAAI,MAAM,EAAE;AACtD;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/dist/main.js
CHANGED
|
@@ -100,13 +100,18 @@ async function secretsFor(home, vault) {
|
|
|
100
100
|
await names.refresh(BACKGROUND_CONTEXT);
|
|
101
101
|
return names;
|
|
102
102
|
}
|
|
103
|
+
function routeFetch(scope, client) {
|
|
104
|
+
const native = scope.fetch.bind(scope);
|
|
105
|
+
const loopback = client.loopbackFetch?.bind(client);
|
|
106
|
+
scope.fetch = transportFetch(client.transport, scope.location.origin, native, loopback);
|
|
107
|
+
return native;
|
|
108
|
+
}
|
|
103
109
|
async function start(scope, ports, options, vault) {
|
|
104
110
|
const { client, users } = await attached(ports, options);
|
|
105
111
|
const home = new SliccKernelEnv(client, { cwd: HOME });
|
|
106
112
|
await privateStore(home);
|
|
107
113
|
const names = await secretsFor(home, vault);
|
|
108
|
-
const native =
|
|
109
|
-
scope.fetch = transportFetch(client.transport, scope.location.origin, native);
|
|
114
|
+
const native = routeFetch(scope, client);
|
|
110
115
|
const facts = {
|
|
111
116
|
version: await agentVersion((url) => native(url)),
|
|
112
117
|
commands: await commandsOnPath(client),
|
package/dist/main.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/main.ts"],
|
|
4
|
-
"sourcesContent": ["import { attachKernel } from '@ai-ecoverse/slicc-kernel';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { CredentialStore, Provider } from '@earendil-works/pi-ai';\nimport {\n createRegistry,\n type ModelRef,\n type Storage,\n type ToolRegistration,\n} from '@earendil-works/pi-durable';\nimport { CodingTools } from '@earendil-works/pi-durable/tools';\nimport { type Agent, type AgentOptions, openAgent } from './agent.ts';\nimport { browserGuard } from './browser/guard.ts';\nimport { attachChanges, CHANGES_MS } from './changes/index.ts';\nimport {\n codemodeExtension,\n codemodeTool,\n disabledBySettings,\n locateWasm,\n sandboxFactory,\n} from './codemode/index.ts';\nimport { EncryptedCredentialStore } from './credentials.ts';\nimport { attachFreezer } from './freezer/index.ts';\nimport { settingsText, titler } from './freezer/title.ts';\nimport { lateGelatiere } from './gelatiere/index.ts';\nimport { type AgentHost, hostAgent } from './host.ts';\nimport { imageReads } from './images/index.ts';\nimport { createActivity } from './kernel/activity.ts';\nimport type { KernelClient } from './kernel/client.ts';\nimport { HOME, kernelEnvironment, SliccKernelEnv } from './kernel/env.ts';\nimport { processGroups } from './kernel/groups.ts';\nimport { adminOver, type UserClient, type UserClients, userClients } from './kernel/users.ts';\nimport { setupLicks } from './licks/index.ts';\nimport { lickTriage } from './licks/triage.ts';\nimport { setupMcp } from './mcp/index.ts';\nimport { setupMemory } from './memory/index.ts';\nimport { modelsCommand } from './models/index.ts';\nimport { type Transport, transportFetch } from './net.ts';\nimport { sliccPrompt } from './prompt.ts';\nimport { createPages } from './remote/pages.ts';\nimport { identity } from './scoops/identity.ts';\nimport { type Assets, packageAssets, type ScoopsRuntime, setupScoops } from './scoops/index.ts';\nimport { repin, secretsExtension, shellGrants } from './secrets/extension.ts';\nimport { secretNames } from './secrets/names.ts';\nimport { scrubWith } from './secrets/scrub.ts';\nimport { listenVault, Vault } from './secrets/vault.ts';\nimport {\n createAgentSettings,\n createSliccModels,\n DEFAULT_MODEL,\n sliccProviders,\n} from './settings.ts';\nimport { RELOAD_MS, setupSkills } from './skills/index.ts';\nimport { setupSprinkles } from './sprinkles/index.ts';\nimport { openOpfsSqliteStorage } from './sqlite.ts';\nimport {\n agentVersion,\n browserConnected,\n commandsOnPath,\n kernelBoot,\n transportName,\n} from './system.ts';\nimport { type KernelPorts, kernelPorts, serveConnections, type WorkerScope } from './worker.ts';\n\nexport interface AgentWorkerScope extends WorkerScope {\n fetch: typeof fetch;\n location: { origin: string };\n}\n\nexport type KernelAttach = (port: MessagePort) => Promise<KernelClient & { transport: Transport }>;\n\nexport interface AgentWorkerOptions {\n model?: ModelRef;\n providers?: Provider[];\n attach?: KernelAttach;\n credentials?: () => Promise<CredentialStore>;\n storage?: () => Promise<Storage>;\n assets?: Assets;\n codemodeWasm?: () => Promise<WebAssembly.Module | undefined>;\n codemodeWorker?: string | URL;\n catalog?: string;\n users?: boolean;\n mcpRedirect?: string;\n}\n\nexport function usersOf(\n admin: MessagePort | undefined,\n wanted: boolean | undefined,\n attach: KernelAttach\n): UserClients | undefined {\n if (!admin) return undefined;\n if (wanted === false) {\n admin.close();\n return undefined;\n }\n return userClients(adminOver(admin), attach as (port: MessagePort) => Promise<UserClient>);\n}\n\nexport const STORE_DIR = '/.slicc';\n\nasync function attached(ports: Promise<KernelPorts>, options: AgentWorkerOptions) {\n const attach: KernelAttach = options.attach ?? attachKernel;\n const { kernel, admin } = await ports;\n const client = await attach(kernel);\n return { client, users: usersOf(admin, options.users, attach) };\n}\n\nfunction privateStore(env: SliccKernelEnv): Promise<unknown> {\n return env.exec(`mkdir -p ${STORE_DIR} && chmod 700 ${STORE_DIR}`, undefined, BACKGROUND_CONTEXT);\n}\n\nasync function codemodeTools(\n client: KernelClient,\n options: AgentWorkerOptions,\n native: typeof fetch,\n extra: Parameters<typeof codemodeTool>[0]['extra']\n) {\n const settings = await client.fs\n .readFile(`${HOME}/.pi/agent/settings.json`)\n .catch(() => undefined);\n if (disabledBySettings(settings === undefined ? undefined : new TextDecoder().decode(settings)))\n return [];\n const sandbox = sandboxFactory(\n options.codemodeWasm ?? (() => locateWasm(native, new URL(import.meta.url))),\n options.codemodeWorker\n );\n return [\n codemodeTool({ declared: CodingTools.tools as readonly ToolRegistration[], sandbox, extra }),\n ];\n}\n\nexport const MCP_CALLBACK = '/oauth/mcp-callback';\n\nasync function openRepinned(\n options: AgentWorkerOptions,\n base: Omit<AgentOptions, 'storage' | 'beforeResume'>\n): Promise<Agent> {\n const storage = await (options.storage ?? (() => openOpfsSqliteStorage()))();\n return openAgent({\n ...base,\n storage,\n beforeResume: (harness, using) => repin(harness, storage, using),\n });\n}\n\nasync function secretsFor(home: SliccKernelEnv, vault: Vault) {\n scrubWith(vault);\n const names = secretNames(home, vault);\n await names.refresh(BACKGROUND_CONTEXT);\n return names;\n}\n\nasync function start(\n scope: AgentWorkerScope,\n ports: Promise<KernelPorts>,\n options: AgentWorkerOptions,\n vault: Vault\n): Promise<AgentHost> {\n const { client, users } = await attached(ports, options);\n const home = new SliccKernelEnv(client, { cwd: HOME });\n await privateStore(home);\n const names = await secretsFor(home, vault);\n const native = scope.fetch.bind(scope);\n scope.fetch = transportFetch(client.transport, scope.location.origin, native);\n const facts = {\n version: await agentVersion((url) => native(url)),\n commands: await commandsOnPath(client),\n transport: transportName(client.transport),\n browser: await browserConnected(client),\n };\n const credentials = await (options.credentials ?? (() => EncryptedCredentialStore.open()))();\n const providers = options.providers ?? sliccProviders();\n const models = createSliccModels(credentials, providers);\n const registry = createRegistry();\n registry.install(CodingTools);\n registry.install(sliccPrompt(facts));\n registry.install(\n imageReads(\n (CodingTools.tools as readonly ToolRegistration[]).find(\n (tool) => tool.name === 'read'\n ) as ToolRegistration\n )\n );\n const memory = setupMemory(registry);\n const coding = CodingTools.tools as readonly ToolRegistration[];\n registry.install(browserGuard([scope.location.origin], coding));\n const mcp = setupMcp(registry);\n const codemode = await codemodeTools(client, options, native, mcp.codemode);\n registry.install(codemodeExtension(codemode));\n const licks = setupLicks(registry);\n licks.licks.triage(lickTriage(models));\n const scoops = setupScoops(registry, licks.licks, [...coding, ...codemode, ...memory.tools]);\n const skills = setupSkills(registry, licks.licks);\n registry.install(secretsExtension({ names, vault }));\n const activity = createActivity();\n const groups = processGroups(client);\n const model = options.model ?? DEFAULT_MODEL;\n let opened: Agent | undefined;\n const environment = kernelEnvironment(client, {\n activity,\n groups,\n identify: identity(() => opened?.agents, model),\n scrub: vault,\n spawn: shellGrants(names),\n });\n const agent = await openRepinned(options, { models, model, registry, env: environment });\n opened = agent;\n const sources = licks.attach(agent, { env: home, home: HOME, activity });\n await sources.start(BACKGROUND_CONTEXT);\n await sources.boot(\n { version: facts.version, boot: await kernelBoot(client) },\n BACKGROUND_CONTEXT\n );\n const skillsRuntime = await skills.attach(\n { env: home, home: HOME, assets: options.assets ?? packageAssets(), reloadMs: RELOAD_MS },\n BACKGROUND_CONTEXT\n );\n const mcpRuntime = await mcp.attach(\n {\n env: home,\n home: HOME,\n credentials,\n licks: licks.licks,\n fetch: scope.fetch,\n version: facts.version,\n reloadMs: RELOAD_MS,\n codemode: codemode.length > 0,\n cors: client.transport.traits?.crossOrigin === 'cors',\n redirect: options.mcpRedirect ?? new URL(MCP_CALLBACK, scope.location.origin).href,\n },\n BACKGROUND_CONTEXT\n );\n const gelatiere = lateGelatiere();\n const sprinkles = await setupSprinkles().attach(\n {\n intercept: gelatiere.intercept,\n harness: agent.harness,\n agents: agent.agents,\n licks: licks.licks,\n env: home,\n assets: options.assets ?? packageAssets(),\n reloadMs: RELOAD_MS,\n },\n BACKGROUND_CONTEXT\n );\n let roles: ScoopsRuntime | undefined;\n const memoryRuntime = await memory.attach(\n {\n harness: agent.harness,\n agents: agent.agents,\n env: home,\n home: HOME,\n reloadMs: RELOAD_MS,\n roles: async (using) => roles?.roles(using),\n },\n BACKGROUND_CONTEXT\n );\n const freezer = attachFreezer({\n harness: agent.harness,\n agents: agent.agents,\n env: home,\n extract: memory.extract,\n title: titler(models, settingsText(home, HOME)),\n });\n licks.licks.guard(freezer.frozenTarget);\n const settings = await createAgentSettings(models, credentials, providers, { mcp: mcpRuntime });\n const pages = createPages({ claim: sprinkles.claim });\n const runtime = await scoops.attach(\n {\n harness: agent.harness,\n agents: agent.agents,\n groups,\n env: home,\n home: HOME,\n alive: alive(client),\n reads: skillsRuntime.dirs,\n memory: memoryRuntime.command,\n gelatiere: gelatiere.command,\n freezer: freezer.command,\n models: modelsCommand({ agents: agent.agents, settings, catalog: models }),\n panel: pages.command,\n mcp: mcp.direct,\n ...(options.assets ? { assets: options.assets } : {}),\n },\n BACKGROUND_CONTEXT\n );\n roles = runtime;\n gelatiere.attach({\n agents: agent.agents,\n licks: licks.licks,\n env: home,\n home: HOME,\n scoops: scoops.scoops,\n roles: runtime.roles,\n assets: options.assets ?? packageAssets(),\n fetch: scope.fetch,\n skills: skillsRuntime.skills,\n ...(options.catalog ? { catalog: options.catalog } : {}),\n });\n await memoryRuntime.reload(BACKGROUND_CONTEXT).catch(() => undefined);\n const changes = attachChanges({ agents: agent.agents, env: home, reloadMs: CHANGES_MS });\n return hostAgent(agent, {\n settings,\n licks: { licks: licks.licks, sources },\n scoops: { scoops: scoops.scoops, runtime },\n skills: skillsRuntime,\n sprinkles,\n memory: memoryRuntime,\n freezer,\n changes,\n pages,\n mcp: mcpRuntime,\n ...(users ? { users } : {}),\n secrets: { vault: vault.state, list: () => names.state.value, close: names.close },\n monitor: {\n kernel: client,\n groups,\n ...(users ? { users: () => users.users.list() } : {}),\n secrets: () => mcpRuntime.secrets(),\n },\n });\n}\n\nexport function alive(client: KernelClient) {\n return async (pid: number): Promise<boolean> => {\n if (!client.ps) return true;\n return (await client.ps()).some((process) => process.pid === pid);\n };\n}\n\nexport function runAgentWorker(\n scope: AgentWorkerScope,\n options: AgentWorkerOptions = {}\n): Promise<AgentHost> {\n const vault = new Vault();\n listenVault(scope, vault);\n const host = start(scope, kernelPorts(scope), options, vault);\n host.catch(() => undefined);\n serveConnections(scope, host);\n return host;\n}\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AAEnC;AAAA,EACE;AAAA,OAIK;AACP,SAAS,mBAAmB;AAC5B,SAAwC,iBAAiB;AACzD,SAAS,oBAAoB;AAC7B,SAAS,eAAe,kBAAkB;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gCAAgC;AACzC,SAAS,qBAAqB;AAC9B,SAAS,cAAc,cAAc;AACrC,SAAS,qBAAqB;AAC9B,SAAyB,iBAAiB;AAC1C,SAAS,kBAAkB;AAC3B,SAAS,sBAAsB;AAE/B,SAAS,MAAM,mBAAmB,sBAAsB;AACxD,SAAS,qBAAqB;AAC9B,SAAS,WAA8C,mBAAmB;AAC1E,SAAS,kBAAkB;AAC3B,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,SAAS,mBAAmB;AAC5B,SAAS,qBAAqB;AAC9B,SAAyB,sBAAsB;AAC/C,SAAS,mBAAmB;AAC5B,SAAS,mBAAmB;AAC5B,SAAS,gBAAgB;AACzB,SAAsB,eAAmC,mBAAmB;AAC5E,SAAS,OAAO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AS,MAAM,CAAC;AAAA,EAC7F;AACF;AAEO,MAAM,eAAe;AAE5B,eAAe,aACb,SACA,MACgB;AAChB,QAAM,UAAU,OAAO,QAAQ,YAAY,MAAM,sBAAsB,IAAI;AAC3E,SAAO,UAAU;AAAA,IACf,GAAG;AAAA,IACH;AAAA,IACA,cAAc,CAAC,SAAS,UAAU,MAAM,SAAS,SAAS,KAAK;AAAA,EACjE,CAAC;AACH;AAEA,eAAe,WAAW,MAAsB,OAAc;AAC5D,YAAU,KAAK;AACf,QAAM,QAAQ,YAAY,MAAM,KAAK;AACrC,QAAM,MAAM,QAAQ,kBAAkB;AACtC,SAAO;AACT;AAEA,eAAe,MACb,OACA,OACA,SACA,OACoB;AACpB,QAAM,EAAE,QAAQ,MAAM,IAAI,MAAM,SAAS,OAAO,OAAO;AACvD,QAAM,OAAO,IAAI,eAAe,QAAQ,EAAE,KAAK,KAAK,CAAC;AACrD,QAAM,aAAa,IAAI;AACvB,QAAM,QAAQ,MAAM,WAAW,MAAM,KAAK;AAC1C,QAAM,SAAS,
|
|
4
|
+
"sourcesContent": ["import { attachKernel } from '@ai-ecoverse/slicc-kernel';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { CredentialStore, Provider } from '@earendil-works/pi-ai';\nimport {\n createRegistry,\n type ModelRef,\n type Storage,\n type ToolRegistration,\n} from '@earendil-works/pi-durable';\nimport { CodingTools } from '@earendil-works/pi-durable/tools';\nimport { type Agent, type AgentOptions, openAgent } from './agent.ts';\nimport { browserGuard } from './browser/guard.ts';\nimport { attachChanges, CHANGES_MS } from './changes/index.ts';\nimport {\n codemodeExtension,\n codemodeTool,\n disabledBySettings,\n locateWasm,\n sandboxFactory,\n} from './codemode/index.ts';\nimport { EncryptedCredentialStore } from './credentials.ts';\nimport { attachFreezer } from './freezer/index.ts';\nimport { settingsText, titler } from './freezer/title.ts';\nimport { lateGelatiere } from './gelatiere/index.ts';\nimport { type AgentHost, hostAgent } from './host.ts';\nimport { imageReads } from './images/index.ts';\nimport { createActivity } from './kernel/activity.ts';\nimport type { KernelClient } from './kernel/client.ts';\nimport { HOME, kernelEnvironment, SliccKernelEnv } from './kernel/env.ts';\nimport { processGroups } from './kernel/groups.ts';\nimport { adminOver, type UserClient, type UserClients, userClients } from './kernel/users.ts';\nimport { setupLicks } from './licks/index.ts';\nimport { lickTriage } from './licks/triage.ts';\nimport { setupMcp } from './mcp/index.ts';\nimport { setupMemory } from './memory/index.ts';\nimport { modelsCommand } from './models/index.ts';\nimport { type Transport, transportFetch } from './net.ts';\nimport { sliccPrompt } from './prompt.ts';\nimport { createPages } from './remote/pages.ts';\nimport { identity } from './scoops/identity.ts';\nimport { type Assets, packageAssets, type ScoopsRuntime, setupScoops } from './scoops/index.ts';\nimport { repin, secretsExtension, shellGrants } from './secrets/extension.ts';\nimport { secretNames } from './secrets/names.ts';\nimport { scrubWith } from './secrets/scrub.ts';\nimport { listenVault, Vault } from './secrets/vault.ts';\nimport {\n createAgentSettings,\n createSliccModels,\n DEFAULT_MODEL,\n sliccProviders,\n} from './settings.ts';\nimport { RELOAD_MS, setupSkills } from './skills/index.ts';\nimport { setupSprinkles } from './sprinkles/index.ts';\nimport { openOpfsSqliteStorage } from './sqlite.ts';\nimport {\n agentVersion,\n browserConnected,\n commandsOnPath,\n kernelBoot,\n transportName,\n} from './system.ts';\nimport { type KernelPorts, kernelPorts, serveConnections, type WorkerScope } from './worker.ts';\n\nexport interface AgentWorkerScope extends WorkerScope {\n fetch: typeof fetch;\n location: { origin: string };\n}\n\nexport type KernelAttach = (port: MessagePort) => Promise<KernelClient & { transport: Transport }>;\n\nexport interface AgentWorkerOptions {\n model?: ModelRef;\n providers?: Provider[];\n attach?: KernelAttach;\n credentials?: () => Promise<CredentialStore>;\n storage?: () => Promise<Storage>;\n assets?: Assets;\n codemodeWasm?: () => Promise<WebAssembly.Module | undefined>;\n codemodeWorker?: string | URL;\n catalog?: string;\n users?: boolean;\n mcpRedirect?: string;\n}\n\nexport function usersOf(\n admin: MessagePort | undefined,\n wanted: boolean | undefined,\n attach: KernelAttach\n): UserClients | undefined {\n if (!admin) return undefined;\n if (wanted === false) {\n admin.close();\n return undefined;\n }\n return userClients(adminOver(admin), attach as (port: MessagePort) => Promise<UserClient>);\n}\n\nexport const STORE_DIR = '/.slicc';\n\nasync function attached(ports: Promise<KernelPorts>, options: AgentWorkerOptions) {\n const attach: KernelAttach = options.attach ?? attachKernel;\n const { kernel, admin } = await ports;\n const client = await attach(kernel);\n return { client, users: usersOf(admin, options.users, attach) };\n}\n\nfunction privateStore(env: SliccKernelEnv): Promise<unknown> {\n return env.exec(`mkdir -p ${STORE_DIR} && chmod 700 ${STORE_DIR}`, undefined, BACKGROUND_CONTEXT);\n}\n\nasync function codemodeTools(\n client: KernelClient,\n options: AgentWorkerOptions,\n native: typeof fetch,\n extra: Parameters<typeof codemodeTool>[0]['extra']\n) {\n const settings = await client.fs\n .readFile(`${HOME}/.pi/agent/settings.json`)\n .catch(() => undefined);\n if (disabledBySettings(settings === undefined ? undefined : new TextDecoder().decode(settings)))\n return [];\n const sandbox = sandboxFactory(\n options.codemodeWasm ?? (() => locateWasm(native, new URL(import.meta.url))),\n options.codemodeWorker\n );\n return [\n codemodeTool({ declared: CodingTools.tools as readonly ToolRegistration[], sandbox, extra }),\n ];\n}\n\nexport const MCP_CALLBACK = '/oauth/mcp-callback';\n\nasync function openRepinned(\n options: AgentWorkerOptions,\n base: Omit<AgentOptions, 'storage' | 'beforeResume'>\n): Promise<Agent> {\n const storage = await (options.storage ?? (() => openOpfsSqliteStorage()))();\n return openAgent({\n ...base,\n storage,\n beforeResume: (harness, using) => repin(harness, storage, using),\n });\n}\n\nasync function secretsFor(home: SliccKernelEnv, vault: Vault) {\n scrubWith(vault);\n const names = secretNames(home, vault);\n await names.refresh(BACKGROUND_CONTEXT);\n return names;\n}\n\nfunction routeFetch(scope: AgentWorkerScope, client: KernelClient & { transport: Transport }) {\n const native = scope.fetch.bind(scope);\n const loopback = client.loopbackFetch?.bind(client);\n scope.fetch = transportFetch(client.transport, scope.location.origin, native, loopback);\n return native;\n}\n\nasync function start(\n scope: AgentWorkerScope,\n ports: Promise<KernelPorts>,\n options: AgentWorkerOptions,\n vault: Vault\n): Promise<AgentHost> {\n const { client, users } = await attached(ports, options);\n const home = new SliccKernelEnv(client, { cwd: HOME });\n await privateStore(home);\n const names = await secretsFor(home, vault);\n const native = routeFetch(scope, client);\n const facts = {\n version: await agentVersion((url) => native(url)),\n commands: await commandsOnPath(client),\n transport: transportName(client.transport),\n browser: await browserConnected(client),\n };\n const credentials = await (options.credentials ?? (() => EncryptedCredentialStore.open()))();\n const providers = options.providers ?? sliccProviders();\n const models = createSliccModels(credentials, providers);\n const registry = createRegistry();\n registry.install(CodingTools);\n registry.install(sliccPrompt(facts));\n registry.install(\n imageReads(\n (CodingTools.tools as readonly ToolRegistration[]).find(\n (tool) => tool.name === 'read'\n ) as ToolRegistration\n )\n );\n const memory = setupMemory(registry);\n const coding = CodingTools.tools as readonly ToolRegistration[];\n registry.install(browserGuard([scope.location.origin], coding));\n const mcp = setupMcp(registry);\n const codemode = await codemodeTools(client, options, native, mcp.codemode);\n registry.install(codemodeExtension(codemode));\n const licks = setupLicks(registry);\n licks.licks.triage(lickTriage(models));\n const scoops = setupScoops(registry, licks.licks, [...coding, ...codemode, ...memory.tools]);\n const skills = setupSkills(registry, licks.licks);\n registry.install(secretsExtension({ names, vault }));\n const activity = createActivity();\n const groups = processGroups(client);\n const model = options.model ?? DEFAULT_MODEL;\n let opened: Agent | undefined;\n const environment = kernelEnvironment(client, {\n activity,\n groups,\n identify: identity(() => opened?.agents, model),\n scrub: vault,\n spawn: shellGrants(names),\n });\n const agent = await openRepinned(options, { models, model, registry, env: environment });\n opened = agent;\n const sources = licks.attach(agent, { env: home, home: HOME, activity });\n await sources.start(BACKGROUND_CONTEXT);\n await sources.boot(\n { version: facts.version, boot: await kernelBoot(client) },\n BACKGROUND_CONTEXT\n );\n const skillsRuntime = await skills.attach(\n { env: home, home: HOME, assets: options.assets ?? packageAssets(), reloadMs: RELOAD_MS },\n BACKGROUND_CONTEXT\n );\n const mcpRuntime = await mcp.attach(\n {\n env: home,\n home: HOME,\n credentials,\n licks: licks.licks,\n fetch: scope.fetch,\n version: facts.version,\n reloadMs: RELOAD_MS,\n codemode: codemode.length > 0,\n cors: client.transport.traits?.crossOrigin === 'cors',\n redirect: options.mcpRedirect ?? new URL(MCP_CALLBACK, scope.location.origin).href,\n },\n BACKGROUND_CONTEXT\n );\n const gelatiere = lateGelatiere();\n const sprinkles = await setupSprinkles().attach(\n {\n intercept: gelatiere.intercept,\n harness: agent.harness,\n agents: agent.agents,\n licks: licks.licks,\n env: home,\n assets: options.assets ?? packageAssets(),\n reloadMs: RELOAD_MS,\n },\n BACKGROUND_CONTEXT\n );\n let roles: ScoopsRuntime | undefined;\n const memoryRuntime = await memory.attach(\n {\n harness: agent.harness,\n agents: agent.agents,\n env: home,\n home: HOME,\n reloadMs: RELOAD_MS,\n roles: async (using) => roles?.roles(using),\n },\n BACKGROUND_CONTEXT\n );\n const freezer = attachFreezer({\n harness: agent.harness,\n agents: agent.agents,\n env: home,\n extract: memory.extract,\n title: titler(models, settingsText(home, HOME)),\n });\n licks.licks.guard(freezer.frozenTarget);\n const settings = await createAgentSettings(models, credentials, providers, { mcp: mcpRuntime });\n const pages = createPages({ claim: sprinkles.claim });\n const runtime = await scoops.attach(\n {\n harness: agent.harness,\n agents: agent.agents,\n groups,\n env: home,\n home: HOME,\n alive: alive(client),\n reads: skillsRuntime.dirs,\n memory: memoryRuntime.command,\n gelatiere: gelatiere.command,\n freezer: freezer.command,\n models: modelsCommand({ agents: agent.agents, settings, catalog: models }),\n panel: pages.command,\n mcp: mcp.direct,\n ...(options.assets ? { assets: options.assets } : {}),\n },\n BACKGROUND_CONTEXT\n );\n roles = runtime;\n gelatiere.attach({\n agents: agent.agents,\n licks: licks.licks,\n env: home,\n home: HOME,\n scoops: scoops.scoops,\n roles: runtime.roles,\n assets: options.assets ?? packageAssets(),\n fetch: scope.fetch,\n skills: skillsRuntime.skills,\n ...(options.catalog ? { catalog: options.catalog } : {}),\n });\n await memoryRuntime.reload(BACKGROUND_CONTEXT).catch(() => undefined);\n const changes = attachChanges({ agents: agent.agents, env: home, reloadMs: CHANGES_MS });\n return hostAgent(agent, {\n settings,\n licks: { licks: licks.licks, sources },\n scoops: { scoops: scoops.scoops, runtime },\n skills: skillsRuntime,\n sprinkles,\n memory: memoryRuntime,\n freezer,\n changes,\n pages,\n mcp: mcpRuntime,\n ...(users ? { users } : {}),\n secrets: { vault: vault.state, list: () => names.state.value, close: names.close },\n monitor: {\n kernel: client,\n groups,\n ...(users ? { users: () => users.users.list() } : {}),\n secrets: () => mcpRuntime.secrets(),\n },\n });\n}\n\nexport function alive(client: KernelClient) {\n return async (pid: number): Promise<boolean> => {\n if (!client.ps) return true;\n return (await client.ps()).some((process) => process.pid === pid);\n };\n}\n\nexport function runAgentWorker(\n scope: AgentWorkerScope,\n options: AgentWorkerOptions = {}\n): Promise<AgentHost> {\n const vault = new Vault();\n listenVault(scope, vault);\n const host = start(scope, kernelPorts(scope), options, vault);\n host.catch(() => undefined);\n serveConnections(scope, host);\n return host;\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,0BAA0B;AAEnC;AAAA,EACE;AAAA,OAIK;AACP,SAAS,mBAAmB;AAC5B,SAAwC,iBAAiB;AACzD,SAAS,oBAAoB;AAC7B,SAAS,eAAe,kBAAkB;AAC1C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,gCAAgC;AACzC,SAAS,qBAAqB;AAC9B,SAAS,cAAc,cAAc;AACrC,SAAS,qBAAqB;AAC9B,SAAyB,iBAAiB;AAC1C,SAAS,kBAAkB;AAC3B,SAAS,sBAAsB;AAE/B,SAAS,MAAM,mBAAmB,sBAAsB;AACxD,SAAS,qBAAqB;AAC9B,SAAS,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1,4 +1,14 @@
|
|
|
1
|
+
import { FACADE_PORT, kernelHost, ownKernelServer } from "./kernel/loopback.js";
|
|
1
2
|
const empty = /* @__PURE__ */ new Set([101, 103, 204, 205, 304]);
|
|
3
|
+
function kernelPort(url) {
|
|
4
|
+
const host = new URL(url).hostname.replace(/\.+$/, "");
|
|
5
|
+
if (!kernelHost(host)) return void 0;
|
|
6
|
+
if (!ownKernelServer(host))
|
|
7
|
+
throw new TypeError(
|
|
8
|
+
`${host} isn't a kernel server SLICC may reach: use <port>.kernel.localhost with a port from 1 to 65535 other than ${FACADE_PORT}, the CDP facade`
|
|
9
|
+
);
|
|
10
|
+
return Number(host.split(".")[0]);
|
|
11
|
+
}
|
|
2
12
|
function stream(body) {
|
|
3
13
|
const iterator = body[Symbol.asyncIterator]();
|
|
4
14
|
return new ReadableStream({
|
|
@@ -12,9 +22,11 @@ function stream(body) {
|
|
|
12
22
|
}
|
|
13
23
|
});
|
|
14
24
|
}
|
|
15
|
-
function transportFetch(transport, origin, native = globalThis.fetch.bind(globalThis)) {
|
|
25
|
+
function transportFetch(transport, origin, native = globalThis.fetch.bind(globalThis), loopback) {
|
|
16
26
|
return async (input, init) => {
|
|
17
27
|
const request = new Request(input, init);
|
|
28
|
+
const port = kernelPort(request.url);
|
|
29
|
+
if (loopback && port) return loopback(request, { port, signal: request.signal });
|
|
18
30
|
if (new URL(request.url).origin === origin || transport.traits?.crossOrigin === "cors") {
|
|
19
31
|
return native(request);
|
|
20
32
|
}
|
|
@@ -34,6 +46,7 @@ function transportFetch(transport, origin, native = globalThis.fetch.bind(global
|
|
|
34
46
|
};
|
|
35
47
|
}
|
|
36
48
|
export {
|
|
49
|
+
kernelPort,
|
|
37
50
|
transportFetch
|
|
38
51
|
};
|
|
39
52
|
//# sourceMappingURL=net.js.map
|
package/dist/net.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/net.ts"],
|
|
4
|
-
"sourcesContent": ["
|
|
5
|
-
"mappings": "
|
|
4
|
+
"sourcesContent": ["import { FACADE_PORT, kernelHost, ownKernelServer } from './kernel/loopback.ts';\n\nexport interface TransportResponse {\n status: number;\n statusText?: string;\n headers: HeadersInit;\n body: AsyncIterable<Uint8Array>;\n}\n\nexport interface Transport {\n traits?: { crossOrigin?: 'cors' | 'any'; manualRedirects?: boolean };\n fetch(request: {\n url: string;\n method: string;\n headers: [string, string][];\n body?: Uint8Array;\n signal?: AbortSignal;\n }): Promise<TransportResponse>;\n}\n\nexport type Loopback = (\n request: Request,\n options: { port: number; signal?: AbortSignal }\n) => Promise<Response>;\n\nconst empty = new Set([101, 103, 204, 205, 304]);\n\nexport function kernelPort(url: string): number | undefined {\n const host = new URL(url).hostname.replace(/\\.+$/, '');\n if (!kernelHost(host)) return undefined;\n if (!ownKernelServer(host))\n throw new TypeError(\n `${host} isn't a kernel server SLICC may reach: use <port>.kernel.localhost with a port from 1 to 65535 other than ${FACADE_PORT}, the CDP facade`\n );\n return Number(host.split('.')[0]);\n}\n\nfunction stream(body: AsyncIterable<Uint8Array>): ReadableStream<Uint8Array> {\n const iterator = body[Symbol.asyncIterator]();\n return new ReadableStream({\n async pull(controller) {\n const next = await iterator.next();\n if (next.done) controller.close();\n else controller.enqueue(next.value);\n },\n async cancel() {\n await iterator.return?.();\n },\n });\n}\n\nexport function transportFetch(\n transport: Transport,\n origin: string,\n native: typeof fetch = globalThis.fetch.bind(globalThis),\n loopback?: Loopback\n): typeof fetch {\n return async (input, init) => {\n const request = new Request(input, init);\n const port = kernelPort(request.url);\n if (loopback && port) return loopback(request, { port, signal: request.signal });\n if (new URL(request.url).origin === origin || transport.traits?.crossOrigin === 'cors') {\n return native(request);\n }\n const body = ['GET', 'HEAD'].includes(request.method)\n ? undefined\n : new Uint8Array(await request.arrayBuffer());\n const response = await transport.fetch({\n url: request.url,\n method: request.method,\n headers: [...request.headers],\n ...(body ? { body } : {}),\n signal: request.signal,\n });\n return new Response(empty.has(response.status) ? null : stream(response.body), {\n status: response.status,\n statusText: response.statusText ?? '',\n headers: response.headers,\n });\n };\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,aAAa,YAAY,uBAAuB;AAyBzD,MAAM,QAAQ,oBAAI,IAAI,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG,CAAC;AAExC,SAAS,WAAW,KAAiC;AAC1D,QAAM,OAAO,IAAI,IAAI,GAAG,EAAE,SAAS,QAAQ,QAAQ,EAAE;AACrD,MAAI,CAAC,WAAW,IAAI,EAAG,QAAO;AAC9B,MAAI,CAAC,gBAAgB,IAAI;AACvB,UAAM,IAAI;AAAA,MACR,GAAG,IAAI,8GAA8G,WAAW;AAAA,IAClI;AACF,SAAO,OAAO,KAAK,MAAM,GAAG,EAAE,CAAC,CAAC;AAClC;AAEA,SAAS,OAAO,MAA6D;AAC3E,QAAM,WAAW,KAAK,OAAO,aAAa,EAAE;AAC5C,SAAO,IAAI,eAAe;AAAA,IACxB,MAAM,KAAK,YAAY;AACrB,YAAM,OAAO,MAAM,SAAS,KAAK;AACjC,UAAI,KAAK,KAAM,YAAW,MAAM;AAAA,UAC3B,YAAW,QAAQ,KAAK,KAAK;AAAA,IACpC;AAAA,IACA,MAAM,SAAS;AACb,YAAM,SAAS,SAAS;AAAA,IAC1B;AAAA,EACF,CAAC;AACH;AAEO,SAAS,eACd,WACA,QACA,SAAuB,WAAW,MAAM,KAAK,UAAU,GACvD,UACc;AACd,SAAO,OAAO,OAAO,SAAS;AAC5B,UAAM,UAAU,IAAI,QAAQ,OAAO,IAAI;AACvC,UAAM,OAAO,WAAW,QAAQ,GAAG;AACnC,QAAI,YAAY,KAAM,QAAO,SAAS,SAAS,EAAE,MAAM,QAAQ,QAAQ,OAAO,CAAC;AAC/E,QAAI,IAAI,IAAI,QAAQ,GAAG,EAAE,WAAW,UAAU,UAAU,QAAQ,gBAAgB,QAAQ;AACtF,aAAO,OAAO,OAAO;AAAA,IACvB;AACA,UAAM,OAAO,CAAC,OAAO,MAAM,EAAE,SAAS,QAAQ,MAAM,IAChD,SACA,IAAI,WAAW,MAAM,QAAQ,YAAY,CAAC;AAC9C,UAAM,WAAW,MAAM,UAAU,MAAM;AAAA,MACrC,KAAK,QAAQ;AAAA,MACb,QAAQ,QAAQ;AAAA,MAChB,SAAS,CAAC,GAAG,QAAQ,OAAO;AAAA,MAC5B,GAAI,OAAO,EAAE,KAAK,IAAI,CAAC;AAAA,MACvB,QAAQ,QAAQ;AAAA,IAClB,CAAC;AACD,WAAO,IAAI,SAAS,MAAM,IAAI,SAAS,MAAM,IAAI,OAAO,OAAO,SAAS,IAAI,GAAG;AAAA,MAC7E,QAAQ,SAAS;AAAA,MACjB,YAAY,SAAS,cAAc;AAAA,MACnC,SAAS,SAAS;AAAA,IACpB,CAAC;AAAA,EACH;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -5,8 +5,8 @@ import {
|
|
|
5
5
|
section,
|
|
6
6
|
ToolTask
|
|
7
7
|
} from "@earendil-works/pi-durable";
|
|
8
|
+
import { listedLine, SECRETS_KIND } from "./view.js";
|
|
8
9
|
const SECRETS = "slicc-secrets";
|
|
9
|
-
const SECRETS_KIND = "slicc.secrets";
|
|
10
10
|
const SECRETS_COMMAND = "/secrets";
|
|
11
11
|
const SHELL_GRANTS = ["fnox", "exec", "--shell-grants", "--"];
|
|
12
12
|
const MODEL_LINE = "Credentials are env vars (`$NAME`) holding placeholders; `secret list` shows them and where each works. The vault fills in the real value only in the listed header, for the listed domain, method and path, over HTTPS (curl, git, fetch). Adding a rule means editing `/etc/fnox/config.toml` with sudo, which the user approves. `fnox exec` gives real values only for secrets the user enabled for exec, and the secrets listed as 'in every bash' already hold real values in your commands. Everything is logged, and stored values are replaced by their placeholder in everything you see; edit around placeholders, since files show them too. Never ask the user to paste a credential into the chat.";
|
|
@@ -82,9 +82,6 @@ function renderSecrets(names) {
|
|
|
82
82
|
const lines = names.map((name) => `- ${name.name} = ${name.placeholder}${where(name)}`);
|
|
83
83
|
return [MODEL_LINE, "", ...lines].join("\n");
|
|
84
84
|
}
|
|
85
|
-
function listedLine(names) {
|
|
86
|
-
return `The user listed secrets: ${names.length ? names.map((name) => name.name).join(", ") : "none"}.`;
|
|
87
|
-
}
|
|
88
85
|
function secretsEntry(names) {
|
|
89
86
|
return {
|
|
90
87
|
kind: SECRETS_KIND,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/secrets/extension.ts"],
|
|
4
|
-
"sourcesContent": ["import type { Context, JsonValue } from '@earendil-works/chord';\nimport {\n type AgentChange,\n type Cursor,\n defineExtension,\n type Extension,\n GenerationTask,\n type Harness,\n hook,\n type Storage,\n section,\n type ToolExecutionResult,\n ToolTask,\n} from '@earendil-works/pi-durable';\nimport type { Names, SecretName } from './names.ts';\nimport type { Scrub } from './scrub.ts';\nimport type { Vault } from './vault.ts';\n\nexport
|
|
5
|
-
"mappings": "AACA;AAAA,EAGE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,OACK;
|
|
4
|
+
"sourcesContent": ["import type { Context, JsonValue } from '@earendil-works/chord';\nimport {\n type AgentChange,\n type Cursor,\n defineExtension,\n type Extension,\n GenerationTask,\n type Harness,\n hook,\n type Storage,\n section,\n type ToolExecutionResult,\n ToolTask,\n} from '@earendil-works/pi-durable';\nimport type { Names, SecretName } from './names.ts';\nimport type { Scrub } from './scrub.ts';\nimport type { Vault } from './vault.ts';\nimport { listedLine, SECRETS_KIND } from './view.ts';\n\nexport { listedLine, SECRETS_KIND };\n\nexport const SECRETS = 'slicc-secrets';\nexport const SECRETS_COMMAND = '/secrets';\nexport const SHELL_GRANTS = ['fnox', 'exec', '--shell-grants', '--'] as const;\n\nexport const MODEL_LINE =\n \"Credentials are env vars (`$NAME`) holding placeholders; `secret list` shows them and where each works. The vault fills in the real value only in the listed header, for the listed domain, method and path, over HTTPS (curl, git, fetch). Adding a rule means editing `/etc/fnox/config.toml` with sudo, which the user approves. `fnox exec` gives real values only for secrets the user enabled for exec, and the secrets listed as 'in every bash' already hold real values in your commands. Everything is logged, and stored values are replaced by their placeholder in everything you see; edit around placeholders, since files show them too. Never ask the user to paste a credential into the chat.\";\n\ntype Leaf = { get(): string; set(text: string): void };\n\nfunction leaves(value: JsonValue, out: Leaf[], set: (next: JsonValue) => void): void {\n if (typeof value === 'string') {\n out.push({ get: () => value, set });\n return;\n }\n if (Array.isArray(value)) {\n value.forEach((item, at) => {\n leaves(item, out, (next) => {\n value[at] = next;\n });\n });\n return;\n }\n if (value && typeof value === 'object')\n for (const [key, item] of Object.entries(value))\n leaves(item as JsonValue, out, (next) => {\n (value as Record<string, JsonValue>)[key] = next;\n });\n}\n\nexport async function scrubResult(\n result: ToolExecutionResult,\n scrub: Pick<Scrub, 'texts'>\n): Promise<ToolExecutionResult | undefined> {\n const content = [...(result.content ?? [])];\n const diagnostics = [...(result.diagnostics ?? [])];\n const details =\n result.details === undefined ? undefined : (structuredClone(result.details) as JsonValue);\n const found: Leaf[] = [];\n content.forEach((item, at) => {\n if (item.type === 'text')\n found.push({ get: () => item.text, set: (text) => void (content[at] = { ...item, text }) });\n });\n diagnostics.forEach((item, at) => {\n found.push({\n get: () => item.message,\n set: (message) => void (diagnostics[at] = { ...item, message }),\n });\n });\n let replaced = details;\n if (details !== undefined)\n leaves(details, found, (next) => {\n replaced = next;\n });\n const before = found.map((leaf) => leaf.get());\n const after = await scrub.texts(before);\n if (after.every((text, at) => text === before[at])) return undefined;\n found.forEach((leaf, at) => {\n leaf.set(after[at] as string);\n });\n const kept = result.content as ToolExecutionResult['content'] & unknown[];\n if (kept) kept.splice(0, kept.length, ...content);\n return {\n ...result,\n ...(kept ? { content: kept } : {}),\n ...(result.diagnostics ? { diagnostics } : {}),\n ...(replaced === undefined ? {} : { details: replaced }),\n };\n}\n\nfunction where(name: SecretName): string {\n const rules = name.rules.map((rule) =>\n [\n rule.domain,\n rule.header ? `header ${rule.header}` : '',\n rule.methods?.length ? rule.methods.join(' ') : '',\n rule.paths?.length ? rule.paths.join(' ') : '',\n ]\n .filter(Boolean)\n .join(', ')\n );\n const shell = name.exec === 'shell' ? ['in every bash'] : [];\n const parts = [...rules, ...shell];\n return parts.length ? `: ${parts.join('; ')}` : '';\n}\n\nexport function renderSecrets(names: readonly SecretName[]): string | undefined {\n if (!names.length) return undefined;\n const lines = names.map((name) => `- ${name.name} = ${name.placeholder}${where(name)}`);\n return [MODEL_LINE, '', ...lines].join('\\n');\n}\n\nexport function secretsEntry(names: readonly SecretName[]) {\n return {\n kind: SECRETS_KIND,\n data: { names: structuredClone(names) as unknown as JsonValue },\n model: [{ role: 'user' as const, content: listedLine(names), timestamp: Date.now() }],\n };\n}\n\nexport function shellGrants(names: Pick<Names, 'state'>) {\n return (argv: readonly string[]): readonly string[] =>\n names.state.value.some((name) => name.exec === 'shell') ? [...SHELL_GRANTS, ...argv] : argv;\n}\n\nexport function pinned<T extends AgentChange>(change: T): T {\n const list = change.extensions;\n if (!Array.isArray(list) || list.some((extension) => extension.name === SECRETS)) return change;\n return { ...change, extensions: [...list, { name: SECRETS }] };\n}\n\nexport async function repin(\n harness: Pick<Harness, 'conversation'>,\n storage: Pick<Storage, 'scanConversations'>,\n context: Context\n): Promise<number> {\n let fixed = 0;\n let cursor: Cursor | undefined;\n do {\n const page = await storage.scanConversations({}, 100, cursor, context);\n for (const record of page.items) {\n const conversation = await harness.conversation(record.id, context);\n if (!conversation) continue;\n const agent = await conversation.agent(context);\n if (agent.extensions.some((extension) => extension.name === SECRETS)) continue;\n await conversation.configure(pinned({ extensions: agent.extensions }), context);\n fixed++;\n }\n cursor = page.next;\n } while (cursor);\n return fixed;\n}\n\nexport function secretsExtension(deps: {\n names: Pick<Names, 'state'>;\n vault: Pick<Vault, 'ready' | 'texts'>;\n}): Extension {\n return defineExtension({\n name: SECRETS,\n sections: [section('secrets', () => renderSecrets(deps.names.state.value))],\n hooks: [\n hook(ToolTask, { afterTool: (_call, result) => scrubResult(result, deps.vault) }),\n hook(GenerationTask, {\n beforeRequest: async () => {\n await deps.vault.ready();\n return undefined;\n },\n }),\n ],\n });\n}\n"],
|
|
5
|
+
"mappings": "AACA;AAAA,EAGE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,OACK;AAIP,SAAS,YAAY,oBAAoB;AAIlC,MAAM,UAAU;AAChB,MAAM,kBAAkB;AACxB,MAAM,eAAe,CAAC,QAAQ,QAAQ,kBAAkB,IAAI;AAE5D,MAAM,aACX;AAIF,SAAS,OAAO,OAAkB,KAAa,KAAsC;AACnF,MAAI,OAAO,UAAU,UAAU;AAC7B,QAAI,KAAK,EAAE,KAAK,MAAM,OAAO,IAAI,CAAC;AAClC;AAAA,EACF;AACA,MAAI,MAAM,QAAQ,KAAK,GAAG;AACxB,UAAM,QAAQ,CAAC,MAAM,OAAO;AAC1B,aAAO,MAAM,KAAK,CAAC,SAAS;AAC1B,cAAM,EAAE,IAAI;AAAA,MACd,CAAC;AAAA,IACH,CAAC;AACD;AAAA,EACF;AACA,MAAI,SAAS,OAAO,UAAU;AAC5B,eAAW,CAAC,KAAK,IAAI,KAAK,OAAO,QAAQ,KAAK;AAC5C,aAAO,MAAmB,KAAK,CAAC,SAAS;AACvC,QAAC,MAAoC,GAAG,IAAI;AAAA,MAC9C,CAAC;AACP;AAEA,eAAsB,YACpB,QACA,OAC0C;AAC1C,QAAM,UAAU,CAAC,GAAI,OAAO,WAAW,CAAC,CAAE;AAC1C,QAAM,cAAc,CAAC,GAAI,OAAO,eAAe,CAAC,CAAE;AAClD,QAAM,UACJ,OAAO,YAAY,SAAY,SAAa,gBAAgB,OAAO,OAAO;AAC5E,QAAM,QAAgB,CAAC;AACvB,UAAQ,QAAQ,CAAC,MAAM,OAAO;AAC5B,QAAI,KAAK,SAAS;AAChB,YAAM,KAAK,EAAE,KAAK,MAAM,KAAK,MAAM,KAAK,CAAC,SAAS,MAA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AW,UAAU,KAAK,OAAO;AAC/B,YAAM,eAAe,MAAM,QAAQ,aAAa,OAAO,IAAI,OAAO;AAClE,UAAI,CAAC,aAAc;AACnB,YAAM,QAAQ,MAAM,aAAa,MAAM,OAAO;AAC9C,UAAI,MAAM,WAAW,KAAK,CAAC,cAAc,UAAU,SAAS,OAAO,EAAG;AACtE,YAAM,aAAa,UAAU,OAAO,EAAE,YAAY,MAAM,WAAW,CAAC,GAAG,OAAO;AAC9E;AAAA,IACF;AACA,aAAS,KAAK;AAAA,EAChB,SAAS;AACT,SAAO;AACT;AAEO,SAAS,iBAAiB,MAGnB;AACZ,SAAO,gBAAgB;AAAA,IACrB,MAAM;AAAA,IACN,UAAU,CAAC,QAAQ,WAAW,MAAM,cAAc,KAAK,MAAM,MAAM,KAAK,CAAC,CAAC;AAAA,IAC1E,OAAO;AAAA,MACL,KAAK,UAAU,EAAE,WAAW,CAAC,OAAO,WAAW,YAAY,QAAQ,KAAK,KAAK,EAAE,CAAC;AAAA,MAChF,KAAK,gBAAgB;AAAA,QACnB,eAAe,YAAY;AACzB,gBAAM,KAAK,MAAM,MAAM;AACvB,iBAAO;AAAA,QACT;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/secrets/vault.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { replicatedState } from "@earendil-works/chord";
|
|
2
2
|
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
3
|
+
import { vaultHold } from "./view.js";
|
|
3
4
|
const WAITING_MS = 2e3;
|
|
4
5
|
const WAITING = "waiting for the vault";
|
|
5
6
|
const LOCKS = ["no", "scrubbing", "passkey"];
|
|
@@ -139,9 +140,9 @@ class Vault {
|
|
|
139
140
|
}
|
|
140
141
|
}
|
|
141
142
|
function holdText(state) {
|
|
142
|
-
|
|
143
|
-
if (
|
|
144
|
-
return
|
|
143
|
+
const hold = vaultHold(state);
|
|
144
|
+
if (!hold) return void 0;
|
|
145
|
+
return hold.reason === "locked" ? "unlock the vault to continue" : WAITING;
|
|
145
146
|
}
|
|
146
147
|
function listenVault(scope, vault) {
|
|
147
148
|
scope.addEventListener("message", ({ data }) => {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/secrets/vault.ts"],
|
|
4
|
-
"sourcesContent": ["import { type MutableReplicatedState, replicatedState } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Scrub, Scrubbable, ScrubStream } from './scrub.ts';\n\nexport type ScrubPair = { needed: boolean; version: number };\nexport type Locked = 'no' | 'scrubbing' | 'passkey';\n\nexport interface VaultState {\n port: 'none' | 'ready' | 'waiting';\n needed: boolean;\n version: number;\n locked: Locked;\n held: number;\n}\n\nexport const WAITING_MS = 2000;\nexport const WAITING = 'waiting for the vault';\n\ntype Message = Record<string, unknown> & { id: number; op: string };\n\ninterface Pending {\n message: Message;\n at: number;\n resolve(value: unknown): void;\n reject(error: Error): void;\n}\n\ntype Answer = {\n id?: unknown;\n ok?: unknown;\n error?: { message?: string };\n scrub?: unknown;\n locked?: unknown;\n};\n\nconst LOCKS: readonly unknown[] = ['no', 'scrubbing', 'passkey'];\n\nconst EMPTY = new Uint8Array();\n\nfunction pairOf(value: unknown): ScrubPair | undefined {\n const pair = value as Partial<ScrubPair> | null;\n if (pair === null) return { needed: false, version: 0 };\n if (typeof pair?.needed !== 'boolean' || typeof pair.version !== 'number') return undefined;\n return { needed: pair.needed, version: pair.version };\n}\n\nexport class Vault implements Scrub {\n readonly state: MutableReplicatedState<VaultState>;\n readonly #pending = new Map<number, Pending>();\n readonly #streams = new Set<number>();\n readonly #waiters = new Set<() => void>();\n readonly #now: () => number;\n #port: MessagePort | undefined;\n #pair: ScrubPair = { needed: false, version: 0 };\n #locked: Locked = 'no';\n #seen = 0;\n #serial = 0;\n #streamSerial = 0;\n\n constructor(now: () => number = Date.now) {\n this.#now = now;\n this.state = replicatedState<VaultState>(this.#snapshot());\n }\n\n get needed(): boolean {\n return this.#pair.needed || this.#seen > this.#pair.version;\n }\n\n connect(port: MessagePort | undefined, scrub: unknown): void {\n const pair = scrub === undefined ? undefined : pairOf(scrub);\n if (pair) this.#pair = pair;\n if (port && port !== this.#port) {\n if (this.#port) this.#port.onmessage = null;\n this.#port = port;\n port.onmessage = (event) => this.#answer(event.data as Answer);\n port.start?.();\n const resend = [...this.#pending.values()];\n const opening = new Set(\n resend\n .filter((item) => item.message.op === 'redactStream')\n .map((item) => item.message.stream)\n );\n for (const stream of this.#streams)\n if (!opening.has(stream)) void this.#call('redactStream', { stream });\n for (const item of resend) port.postMessage(item.message);\n }\n this.#refresh();\n }\n\n ready(): Promise<void> {\n if (!this.#holding()) return Promise.resolve();\n return new Promise((resolve) => this.#waiters.add(resolve));\n }\n\n async texts<T extends Scrubbable>(texts: readonly T[]): Promise<T[]> {\n if (!this.needed) return [...texts];\n const answer = (await this.#call('redact', { texts: [...texts] })) as {\n texts: T[];\n version?: number;\n };\n return answer.texts;\n }\n\n stream(): ScrubStream {\n let stream: number | undefined;\n return {\n push: (chunk) => {\n if (stream === undefined && !this.needed) return Promise.resolve(chunk);\n if (stream === undefined) {\n stream = ++this.#streamSerial;\n this.#streams.add(stream);\n void this.#call('redactStream', { stream });\n }\n return this.#call('push', { stream, chunk }) as Promise<Uint8Array>;\n },\n end: async () => {\n if (stream === undefined) return EMPTY;\n const tail = (await this.#call('end', { stream })) as Uint8Array;\n this.#streams.delete(stream);\n return tail;\n },\n drop: () => {\n if (stream === undefined) return;\n const dropped = stream;\n this.#streams.delete(dropped);\n for (const [id, item] of this.#pending)\n if (item.message.stream === dropped && item.message.op !== 'redactStream') {\n this.#pending.delete(id);\n item.resolve(EMPTY);\n }\n void this.#call('drop', { stream: dropped });\n },\n };\n }\n\n #call(op: string, fields: Record<string, unknown>): Promise<unknown> {\n const message: Message = { id: ++this.#serial, op, ...fields };\n const result = new Promise((resolve, reject) => {\n this.#pending.set(message.id, { message, at: this.#now(), resolve, reject });\n });\n this.#port?.postMessage(message);\n setTimeout(() => this.#refresh(), WAITING_MS);\n this.#refresh();\n return result;\n }\n\n #answer(data: Answer): void {\n if (!data || typeof data !== 'object') return;\n const pair = 'scrub' in data ? pairOf(data.scrub) : undefined;\n if (pair) this.#pair = pair;\n if (LOCKS.includes(data.locked)) this.#locked = data.locked as Locked;\n const item = typeof data.id === 'number' ? this.#pending.get(data.id) : undefined;\n if (item) {\n this.#pending.delete(data.id as number);\n const version = (data.ok as { version?: unknown } | undefined)?.version;\n if (typeof version === 'number') this.#seen = Math.max(this.#seen, version);\n if (data.error) item.reject(new Error(data.error.message ?? 'the vault refused'));\n else item.resolve(data.ok);\n }\n this.#refresh();\n }\n\n #waiting(): boolean {\n const now = this.#now();\n return [...this.#pending.values()].some((item) => now - item.at >= WAITING_MS);\n }\n\n #holding(): boolean {\n return this.needed && (!this.#port || this.#waiting() || this.#locked === 'passkey');\n }\n\n #snapshot(): VaultState {\n return {\n port: !this.#port ? 'none' : this.#waiting() ? 'waiting' : 'ready',\n needed: this.needed,\n version: this.#pair.version,\n locked: this.#locked,\n held: this.#pending.size,\n };\n }\n\n #refresh(): void {\n const next = this.#snapshot();\n const before = this.state.value;\n if (Object.entries(next).some(([key, value]) => before[key as keyof VaultState] !== value))\n this.state.replace(BACKGROUND_CONTEXT, next);\n if (this.#holding()) return;\n for (const resolve of this.#waiters) resolve();\n this.#waiters.clear();\n }\n}\n\nexport function holdText(state: VaultState): string | undefined {\n if (!
|
|
5
|
-
"mappings": "AAAA,SAAsC,uBAAuB;AAC7D,SAAS,0BAA0B;
|
|
4
|
+
"sourcesContent": ["import { type MutableReplicatedState, replicatedState } from '@earendil-works/chord';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { Scrub, Scrubbable, ScrubStream } from './scrub.ts';\nimport { vaultHold } from './view.ts';\n\nexport type ScrubPair = { needed: boolean; version: number };\nexport type Locked = 'no' | 'scrubbing' | 'passkey';\n\nexport interface VaultState {\n port: 'none' | 'ready' | 'waiting';\n needed: boolean;\n version: number;\n locked: Locked;\n held: number;\n}\n\nexport const WAITING_MS = 2000;\nexport const WAITING = 'waiting for the vault';\n\ntype Message = Record<string, unknown> & { id: number; op: string };\n\ninterface Pending {\n message: Message;\n at: number;\n resolve(value: unknown): void;\n reject(error: Error): void;\n}\n\ntype Answer = {\n id?: unknown;\n ok?: unknown;\n error?: { message?: string };\n scrub?: unknown;\n locked?: unknown;\n};\n\nconst LOCKS: readonly unknown[] = ['no', 'scrubbing', 'passkey'];\n\nconst EMPTY = new Uint8Array();\n\nfunction pairOf(value: unknown): ScrubPair | undefined {\n const pair = value as Partial<ScrubPair> | null;\n if (pair === null) return { needed: false, version: 0 };\n if (typeof pair?.needed !== 'boolean' || typeof pair.version !== 'number') return undefined;\n return { needed: pair.needed, version: pair.version };\n}\n\nexport class Vault implements Scrub {\n readonly state: MutableReplicatedState<VaultState>;\n readonly #pending = new Map<number, Pending>();\n readonly #streams = new Set<number>();\n readonly #waiters = new Set<() => void>();\n readonly #now: () => number;\n #port: MessagePort | undefined;\n #pair: ScrubPair = { needed: false, version: 0 };\n #locked: Locked = 'no';\n #seen = 0;\n #serial = 0;\n #streamSerial = 0;\n\n constructor(now: () => number = Date.now) {\n this.#now = now;\n this.state = replicatedState<VaultState>(this.#snapshot());\n }\n\n get needed(): boolean {\n return this.#pair.needed || this.#seen > this.#pair.version;\n }\n\n connect(port: MessagePort | undefined, scrub: unknown): void {\n const pair = scrub === undefined ? undefined : pairOf(scrub);\n if (pair) this.#pair = pair;\n if (port && port !== this.#port) {\n if (this.#port) this.#port.onmessage = null;\n this.#port = port;\n port.onmessage = (event) => this.#answer(event.data as Answer);\n port.start?.();\n const resend = [...this.#pending.values()];\n const opening = new Set(\n resend\n .filter((item) => item.message.op === 'redactStream')\n .map((item) => item.message.stream)\n );\n for (const stream of this.#streams)\n if (!opening.has(stream)) void this.#call('redactStream', { stream });\n for (const item of resend) port.postMessage(item.message);\n }\n this.#refresh();\n }\n\n ready(): Promise<void> {\n if (!this.#holding()) return Promise.resolve();\n return new Promise((resolve) => this.#waiters.add(resolve));\n }\n\n async texts<T extends Scrubbable>(texts: readonly T[]): Promise<T[]> {\n if (!this.needed) return [...texts];\n const answer = (await this.#call('redact', { texts: [...texts] })) as {\n texts: T[];\n version?: number;\n };\n return answer.texts;\n }\n\n stream(): ScrubStream {\n let stream: number | undefined;\n return {\n push: (chunk) => {\n if (stream === undefined && !this.needed) return Promise.resolve(chunk);\n if (stream === undefined) {\n stream = ++this.#streamSerial;\n this.#streams.add(stream);\n void this.#call('redactStream', { stream });\n }\n return this.#call('push', { stream, chunk }) as Promise<Uint8Array>;\n },\n end: async () => {\n if (stream === undefined) return EMPTY;\n const tail = (await this.#call('end', { stream })) as Uint8Array;\n this.#streams.delete(stream);\n return tail;\n },\n drop: () => {\n if (stream === undefined) return;\n const dropped = stream;\n this.#streams.delete(dropped);\n for (const [id, item] of this.#pending)\n if (item.message.stream === dropped && item.message.op !== 'redactStream') {\n this.#pending.delete(id);\n item.resolve(EMPTY);\n }\n void this.#call('drop', { stream: dropped });\n },\n };\n }\n\n #call(op: string, fields: Record<string, unknown>): Promise<unknown> {\n const message: Message = { id: ++this.#serial, op, ...fields };\n const result = new Promise((resolve, reject) => {\n this.#pending.set(message.id, { message, at: this.#now(), resolve, reject });\n });\n this.#port?.postMessage(message);\n setTimeout(() => this.#refresh(), WAITING_MS);\n this.#refresh();\n return result;\n }\n\n #answer(data: Answer): void {\n if (!data || typeof data !== 'object') return;\n const pair = 'scrub' in data ? pairOf(data.scrub) : undefined;\n if (pair) this.#pair = pair;\n if (LOCKS.includes(data.locked)) this.#locked = data.locked as Locked;\n const item = typeof data.id === 'number' ? this.#pending.get(data.id) : undefined;\n if (item) {\n this.#pending.delete(data.id as number);\n const version = (data.ok as { version?: unknown } | undefined)?.version;\n if (typeof version === 'number') this.#seen = Math.max(this.#seen, version);\n if (data.error) item.reject(new Error(data.error.message ?? 'the vault refused'));\n else item.resolve(data.ok);\n }\n this.#refresh();\n }\n\n #waiting(): boolean {\n const now = this.#now();\n return [...this.#pending.values()].some((item) => now - item.at >= WAITING_MS);\n }\n\n #holding(): boolean {\n return this.needed && (!this.#port || this.#waiting() || this.#locked === 'passkey');\n }\n\n #snapshot(): VaultState {\n return {\n port: !this.#port ? 'none' : this.#waiting() ? 'waiting' : 'ready',\n needed: this.needed,\n version: this.#pair.version,\n locked: this.#locked,\n held: this.#pending.size,\n };\n }\n\n #refresh(): void {\n const next = this.#snapshot();\n const before = this.state.value;\n if (Object.entries(next).some(([key, value]) => before[key as keyof VaultState] !== value))\n this.state.replace(BACKGROUND_CONTEXT, next);\n if (this.#holding()) return;\n for (const resolve of this.#waiters) resolve();\n this.#waiters.clear();\n }\n}\n\nexport function holdText(state: VaultState): string | undefined {\n const hold = vaultHold(state);\n if (!hold) return undefined;\n return hold.reason === 'locked' ? 'unlock the vault to continue' : WAITING;\n}\n\nexport function listenVault(\n scope: { addEventListener(type: 'message', listener: (event: MessageEvent) => void): void },\n vault: Vault\n): void {\n scope.addEventListener('message', ({ data }) => {\n const message = data as { vault?: MessagePort; scrub?: unknown } | null;\n if (!message || typeof message !== 'object' || !('vault' in message || 'scrub' in message))\n return;\n vault.connect(message.vault, message.scrub);\n });\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAsC,uBAAuB;AAC7D,SAAS,0BAA0B;AAEnC,SAAS,iBAAiB;AAanB,MAAM,aAAa;AACnB,MAAM,UAAU;AAmBvB,MAAM,QAA4B,CAAC,MAAM,aAAa,SAAS;AAE/D,MAAM,QAAQ,IAAI,WAAW;AAE7B,SAAS,OAAO,OAAuC;AACrD,QAAM,OAAO;AACb,MAAI,SAAS,KAAM,QAAO,EAAE,QAAQ,OAAO,SAAS,EAAE;AACtD,MAAI,OAAO,MAAM,WAAW,aAAa,OAAO,KAAK,YAAY,SAAU,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AS,KAAK,SAAS,KAAK,KAAK,YAAY;AAAA,EAC5E;AAAA,EAEA,YAAwB;AACtB,WAAO;AAAA,MACL,MAAM,CAAC,KAAK,QAAQ,SAAS,KAAK,SAAS,IAAI,YAAY;AAAA,MAC3D,QAAQ,KAAK;AAAA,MACb,SAAS,KAAK,MAAM;AAAA,MACpB,QAAQ,KAAK;AAAA,MACb,MAAM,KAAK,SAAS;AAAA,IACtB;AAAA,EACF;AAAA,EAEA,WAAiB;AACf,UAAM,OAAO,KAAK,UAAU;AAC5B,UAAM,SAAS,KAAK,MAAM;AAC1B,QAAI,OAAO,QAAQ,IAAI,EAAE,KAAK,CAAC,CAAC,KAAK,KAAK,MAAM,OAAO,GAAuB,MAAM,KAAK;AACvF,WAAK,MAAM,QAAQ,oBAAoB,IAAI;AAC7C,QAAI,KAAK,SAAS,EAAG;AACrB,eAAW,WAAW,KAAK,SAAU,SAAQ;AAC7C,SAAK,SAAS,MAAM;AAAA,EACtB;AACF;AAEO,SAAS,SAAS,OAAuC;AAC9D,QAAM,OAAO,UAAU,KAAK;AAC5B,MAAI,CAAC,KAAM,QAAO;AAClB,SAAO,KAAK,WAAW,WAAW,iCAAiC;AACrE;AAEO,SAAS,YACd,OACA,OACM;AACN,QAAM,iBAAiB,WAAW,CAAC,EAAE,KAAK,MAAM;AAC9C,UAAM,UAAU;AAChB,QAAI,CAAC,WAAW,OAAO,YAAY,YAAY,EAAE,WAAW,WAAW,WAAW;AAChF;AACF,UAAM,QAAQ,QAAQ,OAAO,QAAQ,KAAK;AAAA,EAC5C,CAAC;AACH;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
const SECRETS_KIND = "slicc.secrets";
|
|
2
|
+
function vaultHold(state) {
|
|
3
|
+
if (!state?.needed) return null;
|
|
4
|
+
if (state.locked === "passkey") return { reason: "locked", held: state.held };
|
|
5
|
+
return state.port === "ready" ? null : { reason: "waiting", held: state.held };
|
|
6
|
+
}
|
|
7
|
+
function listedLine(names) {
|
|
8
|
+
return `The user listed secrets: ${names.length ? names.map((name) => name.name).join(", ") : "none"}.`;
|
|
9
|
+
}
|
|
10
|
+
export {
|
|
11
|
+
SECRETS_KIND,
|
|
12
|
+
listedLine,
|
|
13
|
+
vaultHold
|
|
14
|
+
};
|
|
15
|
+
//# sourceMappingURL=view.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../src/secrets/view.ts"],
|
|
4
|
+
"sourcesContent": ["import type { SecretName } from './names.ts';\nimport type { VaultState } from './vault.ts';\n\nexport const SECRETS_KIND = 'slicc.secrets';\n\nexport interface VaultHold {\n reason: 'waiting' | 'locked';\n held: number;\n}\n\nexport function vaultHold(state: VaultState | undefined): VaultHold | null {\n if (!state?.needed) return null;\n if (state.locked === 'passkey') return { reason: 'locked', held: state.held };\n return state.port === 'ready' ? null : { reason: 'waiting', held: state.held };\n}\n\nexport function listedLine(names: readonly SecretName[]): string {\n return `The user listed secrets: ${names.length ? names.map((name) => name.name).join(', ') : 'none'}.`;\n}\n"],
|
|
5
|
+
"mappings": "AAGO,MAAM,eAAe;AAOrB,SAAS,UAAU,OAAiD;AACzE,MAAI,CAAC,OAAO,OAAQ,QAAO;AAC3B,MAAI,MAAM,WAAW,UAAW,QAAO,EAAE,QAAQ,UAAU,MAAM,MAAM,KAAK;AAC5E,SAAO,MAAM,SAAS,UAAU,OAAO,EAAE,QAAQ,WAAW,MAAM,MAAM,KAAK;AAC/E;AAEO,SAAS,WAAW,OAAsC;AAC/D,SAAO,4BAA4B,MAAM,SAAS,MAAM,IAAI,CAAC,SAAS,KAAK,IAAI,EAAE,KAAK,IAAI,IAAI,MAAM;AACtG;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
2
2
|
import { entryLick } from "../licks/state.js";
|
|
3
|
+
import { vaultHold } from "../secrets/view.js";
|
|
3
4
|
import { Emitter } from "./emitter.js";
|
|
4
5
|
import { isBusy, queued, toMessages } from "./messages.js";
|
|
5
6
|
const CONE = "cone";
|
|
@@ -23,15 +24,29 @@ function status(view, messages) {
|
|
|
23
24
|
function slashCommand({ kind, ...command }) {
|
|
24
25
|
return kind === "action" ? command : { ...command, kind };
|
|
25
26
|
}
|
|
27
|
+
function sameHold(a, b) {
|
|
28
|
+
return a === b || a !== null && b !== null && a.reason === b.reason && a.held === b.held;
|
|
29
|
+
}
|
|
26
30
|
class AgentAdapter extends Emitter {
|
|
27
31
|
#connection;
|
|
28
32
|
#ready;
|
|
29
33
|
#messages = /* @__PURE__ */ new Map();
|
|
30
34
|
#active = null;
|
|
31
35
|
#creating = /* @__PURE__ */ new Map();
|
|
36
|
+
#hold = null;
|
|
37
|
+
#outbox = /* @__PURE__ */ new Map();
|
|
32
38
|
constructor(connection) {
|
|
33
39
|
super();
|
|
34
40
|
this.#connection = connection;
|
|
41
|
+
this.#hold = this.hold();
|
|
42
|
+
connection.vault?.subscribe(() => {
|
|
43
|
+
const next = this.hold();
|
|
44
|
+
if (sameHold(next, this.#hold)) return;
|
|
45
|
+
this.#hold = next;
|
|
46
|
+
if (!next) for (const pending of this.#outbox.values()) pending.release();
|
|
47
|
+
this.emit("hold", next);
|
|
48
|
+
this.emit("agents", this.list());
|
|
49
|
+
});
|
|
35
50
|
connection.frozen?.subscribe(() => {
|
|
36
51
|
this.emit("frozen", this.frozen());
|
|
37
52
|
this.emit("agents", this.list());
|
|
@@ -83,6 +98,9 @@ class AgentAdapter extends Emitter {
|
|
|
83
98
|
ready() {
|
|
84
99
|
return this.#ready;
|
|
85
100
|
}
|
|
101
|
+
hold() {
|
|
102
|
+
return vaultHold(this.#connection.vault?.value);
|
|
103
|
+
}
|
|
86
104
|
list() {
|
|
87
105
|
const rows = this.#connection.frozen?.value ?? [];
|
|
88
106
|
return this.#summary().map((summary) => {
|
|
@@ -94,7 +112,7 @@ class AgentAdapter extends Emitter {
|
|
|
94
112
|
name: summary.role ? `${summary.name} \xB7 ${summary.role}` : summary.name,
|
|
95
113
|
kind: summary.kind,
|
|
96
114
|
parentId: summary.parentId,
|
|
97
|
-
status: status(view, this.#messages.get(summary.id) ?? []),
|
|
115
|
+
status: this.#status(summary.id, status(view, this.#messages.get(summary.id) ?? [])),
|
|
98
116
|
model: doc?.model ? `${doc.model.provider}/${doc.model.modelId}` : "",
|
|
99
117
|
contextFill: 0,
|
|
100
118
|
unread: 0,
|
|
@@ -129,6 +147,9 @@ class AgentAdapter extends Emitter {
|
|
|
129
147
|
const outgoing = typeof input === "string" ? { text: input } : input;
|
|
130
148
|
const target = this.#creating.has(agentId) ? await this.#creating.get(agentId) : agentId;
|
|
131
149
|
if (target === null) throw new Error("The scoop could not be created.");
|
|
150
|
+
const pending = target && this.#held(target) ? this.#pending(target, outgoing) : void 0;
|
|
151
|
+
if (pending) await pending.released;
|
|
152
|
+
if (pending?.dropped) return this.#settle(pending);
|
|
132
153
|
const sent = await this.#connection.control.send(
|
|
133
154
|
{
|
|
134
155
|
text: outgoing.text,
|
|
@@ -137,8 +158,30 @@ class AgentAdapter extends Emitter {
|
|
|
137
158
|
agentId: target || null
|
|
138
159
|
},
|
|
139
160
|
BACKGROUND_CONTEXT
|
|
140
|
-
);
|
|
161
|
+
).finally(() => pending && this.#settle(pending));
|
|
141
162
|
if (!sent.accepted) throw new Error(sent.error.message);
|
|
163
|
+
if (pending?.dropped)
|
|
164
|
+
void this.#connection.control.unqueue(pending.agentId, sent.submissionId, BACKGROUND_CONTEXT);
|
|
165
|
+
}
|
|
166
|
+
#pending(agentId, outgoing) {
|
|
167
|
+
const id = `p${crypto.randomUUID()}`;
|
|
168
|
+
const message = {
|
|
169
|
+
id,
|
|
170
|
+
role: "user",
|
|
171
|
+
text: outgoing.text,
|
|
172
|
+
createdAt: Date.now(),
|
|
173
|
+
queued: true,
|
|
174
|
+
mode: outgoing.mode === "queue" ? "queue" : "steer"
|
|
175
|
+
};
|
|
176
|
+
const { promise: released, resolve: release } = Promise.withResolvers();
|
|
177
|
+
const pending = { agentId, message, dropped: false, release, released };
|
|
178
|
+
this.#outbox.set(id, pending);
|
|
179
|
+
this.emit("messages", agentId);
|
|
180
|
+
return pending;
|
|
181
|
+
}
|
|
182
|
+
#settle(pending) {
|
|
183
|
+
this.#outbox.delete(pending.message.id);
|
|
184
|
+
this.emit("messages", pending.agentId);
|
|
142
185
|
}
|
|
143
186
|
async rewind(agentId, messageId) {
|
|
144
187
|
const rewound = await this.#connection.control.rewindAgent(
|
|
@@ -152,12 +195,26 @@ class AgentAdapter extends Emitter {
|
|
|
152
195
|
void this.#connection.control.stopAgent(agentId, BACKGROUND_CONTEXT);
|
|
153
196
|
}
|
|
154
197
|
busy(agentId = this.active()) {
|
|
155
|
-
return isBusy(this.#view(agentId));
|
|
198
|
+
return isBusy(this.#view(agentId)) || this.#held(agentId);
|
|
199
|
+
}
|
|
200
|
+
#status(agentId, shown) {
|
|
201
|
+
return shown === "idle" && this.#held(agentId) ? "working" : shown;
|
|
202
|
+
}
|
|
203
|
+
#held(agentId) {
|
|
204
|
+
return this.#hold !== null && agentId === (this.#connection.agents?.value?.active ?? CONE);
|
|
156
205
|
}
|
|
157
206
|
queue(agentId = this.active()) {
|
|
158
|
-
|
|
207
|
+
const pending = [...this.#outbox.values()].filter((item) => item.agentId === agentId && !item.dropped).map((item) => item.message);
|
|
208
|
+
return [...queued(this.#view(agentId)), ...pending];
|
|
159
209
|
}
|
|
160
210
|
unqueue(agentId, messageId) {
|
|
211
|
+
const pending = this.#outbox.get(messageId);
|
|
212
|
+
if (pending) {
|
|
213
|
+
pending.dropped = true;
|
|
214
|
+
pending.release();
|
|
215
|
+
this.emit("messages", pending.agentId);
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
161
218
|
void this.#connection.control.unqueue(agentId, messageId.replace(/^q/, ""), BACKGROUND_CONTEXT);
|
|
162
219
|
}
|
|
163
220
|
suggestion() {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/spectrum/agent-port.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n Agent,\n AgentEvents,\n AgentPort,\n AgentStatus,\n FrozenCone,\n Message,\n Outgoing,\n SlashCommand,\n Thinking,\n UserMessage,\n} from '@ai-ecoverse/slicc-spectrum/ui';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { ConversationView } from '@earendil-works/pi-durable';\nimport type { AgentConnection } from '../client.ts';\nimport { entryLick } from '../licks/state.ts';\nimport type { AgentSettingsChange, AgentSummary, Command } from '../services.ts';\nimport { Emitter } from './emitter.ts';\nimport { isBusy, queued, toMessages } from './messages.ts';\n\nexport const CONE = 'cone';\n\nconst thinking: Record<string, Thinking> = {\n off: 'off',\n minimal: 'low',\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'high',\n max: 'high',\n};\n\ninterface AgentDoc {\n model?: { provider: string; modelId: string };\n thinkingLevel?: string;\n}\n\nfunction status(view: ConversationView | undefined, messages: readonly Message[]): AgentStatus {\n if (isBusy(view)) {\n const live = view?.docs['pi.live'] as { tools?: { status: string }[] } | undefined;\n return live?.tools?.some((slot) => slot.status === 'running') ? 'working' : 'thinking';\n }\n const last = messages.at(-1);\n return last?.role === 'assistant' && last.status === 'error' ? 'error' : 'idle';\n}\n\nexport function slashCommand({ kind, ...command }: Command): SlashCommand {\n return kind === 'action' ? command : { ...command, kind };\n}\n\nexport class AgentAdapter extends Emitter<AgentEvents> implements AgentPort {\n readonly #connection: AgentConnection;\n readonly #ready: Promise<void>;\n readonly #messages = new Map<string, Message[]>();\n #active: string | null = null;\n #creating = new Map<string, Promise<string | null>>();\n\n constructor(connection: AgentConnection) {\n super();\n this.#connection = connection;\n connection.frozen?.subscribe(() => {\n this.emit('frozen', this.frozen());\n this.emit('agents', this.list());\n });\n this.#ready = new Promise((resolve) => {\n connection.transcript.subscribe(() => {\n this.#refresh();\n resolve();\n });\n connection.deliveries.subscribe(() => this.#refresh());\n connection.views?.subscribe(() => this.#refresh());\n connection.agents?.subscribe(() => this.#refresh());\n });\n }\n\n #summary(): readonly AgentSummary[] {\n const agents = this.#connection.agents?.value?.agents;\n return agents?.length\n ? agents\n : [{ id: CONE, name: 'sliccy', kind: 'cone', parentId: null, role: null }];\n }\n\n #view(agentId: string = this.active()): ConversationView | undefined {\n const views = this.#connection.views?.value;\n const view = views?.[agentId];\n if (view) return view;\n const cone = this.#connection.agents?.value?.active ?? CONE;\n return agentId === cone ? this.#connection.transcript.value : undefined;\n }\n\n #refresh(): void {\n this.#active ??= this.#connection.agents?.value?.active ?? null;\n this.emit('agents', this.list());\n for (const summary of this.#summary()) this.#update(summary.id);\n for (const id of [...this.#messages.keys()])\n if (!this.#summary().some((summary) => summary.id === id)) this.#messages.delete(id);\n }\n\n #update(agentId: string): void {\n const view = this.#view(agentId);\n if (!view) return;\n const before = this.#messages.get(agentId) ?? [];\n const after = toMessages(view, this.#connection.deliveries.value);\n this.#messages.set(agentId, after);\n if (before.length !== after.length) {\n this.emit('messages', agentId);\n return;\n }\n const changed = after.filter(\n (message, index) => JSON.stringify(message) !== JSON.stringify(before[index])\n );\n if (changed.length === 1) this.emit('message', { agentId, message: changed[0] as Message });\n else if (changed.length > 1) this.emit('messages', agentId);\n }\n\n ready(): Promise<void> {\n return this.#ready;\n }\n\n list(): readonly Agent[] {\n const rows = this.#connection.frozen?.value ?? [];\n return this.#summary().map((summary) => {\n const view = this.#view(summary.id);\n const doc = view?.docs['pi.agent'] as AgentDoc | undefined;\n const title =\n summary.kind === 'cone' ? rows.find((row) => row.id === summary.id)?.title : undefined;\n return {\n id: summary.id,\n name: summary.role ? `${summary.name} \u00B7 ${summary.role}` : summary.name,\n kind: summary.kind,\n parentId: summary.parentId,\n status: status(view, this.#messages.get(summary.id) ?? []),\n model: doc?.model ? `${doc.model.provider}/${doc.model.modelId}` : '',\n contextFill: 0,\n unread: 0,\n thinking: thinking[doc?.thinkingLevel ?? 'off'] ?? 'off',\n ...(title ? { title } : {}),\n };\n });\n }\n\n active(): string {\n const known = this.#summary();\n if (this.#active && this.#creating.has(this.#active)) return this.#active;\n if (this.#active && known.some((summary) => summary.id === this.#active)) return this.#active;\n return this.#connection.agents?.value?.active ?? CONE;\n }\n\n select(id: string): void {\n if (this.#creating.has(id)) {\n this.#active = id;\n this.emit('active', id);\n return;\n }\n const found = this.#summary().find((summary) => summary.id === id);\n if (!found) return;\n this.#active = id;\n if (found.kind === 'cone') void this.#connection.control.selectCone(id, BACKGROUND_CONTEXT);\n this.emit('active', id);\n this.emit('messages', id);\n }\n\n messages(agentId: string = this.active()): readonly Message[] {\n return this.#messages.get(agentId) ?? [];\n }\n\n async send(agentId: string, input: string | Outgoing): Promise<void> {\n const outgoing = typeof input === 'string' ? { text: input } : input;\n const target = this.#creating.has(agentId) ? await this.#creating.get(agentId) : agentId;\n if (target === null) throw new Error('The scoop could not be created.');\n const sent = await this.#connection.control.send(\n {\n text: outgoing.text,\n whenBusy: outgoing.mode === 'queue' ? 'followUp' : 'steer',\n requestId: crypto.randomUUID(),\n agentId: target || null,\n },\n BACKGROUND_CONTEXT\n );\n if (!sent.accepted) throw new Error(sent.error.message);\n }\n\n async rewind(agentId: string, messageId: string): Promise<Outgoing | null> {\n const rewound = await this.#connection.control.rewindAgent(\n agentId,\n messageId,\n BACKGROUND_CONTEXT\n );\n return rewound.done ? { text: rewound.text } : null;\n }\n\n stop(agentId: string = this.active()): void {\n void this.#connection.control.stopAgent(agentId, BACKGROUND_CONTEXT);\n }\n\n busy(agentId: string = this.active()): boolean {\n return isBusy(this.#view(agentId));\n }\n\n queue(agentId: string = this.active()): readonly UserMessage[] {\n return queued(this.#view(agentId));\n }\n\n unqueue(agentId: string, messageId: string): void {\n void this.#connection.control.unqueue(agentId, messageId.replace(/^q/, ''), BACKGROUND_CONTEXT);\n }\n\n suggestion(): string | null {\n return null;\n }\n\n answer(): void {}\n\n resolveLick(agentId: string, messageId: string, state: 'confirmed' | 'dismissed'): void {\n const message = this.messages(agentId).find((candidate) => candidate.id === messageId);\n const entry = this.#view(agentId)?.entries.find(\n (candidate) => `e${candidate.id}` === messageId\n );\n const lick = message?.role === 'lick' && entry ? entryLick(entry) : undefined;\n if (lick)\n void this.#connection.control.resolveAgentLick(agentId, lick.id, state, BACKGROUND_CONTEXT);\n }\n\n compact(agentId: string = this.active()): void {\n void this.#connection.control.compactAgent(agentId, null, BACKGROUND_CONTEXT);\n }\n\n clear(agentId: string = this.active()): void {\n void this.#connection.control.newChat(agentId, BACKGROUND_CONTEXT);\n }\n\n freeze(agentId: string = this.active()): void {\n void this.#connection.control.freeze(agentId, BACKGROUND_CONTEXT);\n }\n\n #configure(agentId: string, change: Partial<AgentSettingsChange>): void {\n void this.#connection.control.configure(\n {\n model: change.model ?? null,\n thinkingLevel: change.thinkingLevel ?? null,\n agentId,\n },\n BACKGROUND_CONTEXT\n );\n }\n\n setModel(agentId: string, model: string): void {\n const at = model.indexOf('/');\n if (at <= 0) return;\n this.#configure(agentId, {\n model: { provider: model.slice(0, at), modelId: model.slice(at + 1) },\n });\n }\n\n setThinking(agentId: string, level: Thinking): void {\n this.#configure(agentId, { thinkingLevel: level });\n }\n\n async older(): Promise<readonly Message[]> {\n return [];\n }\n\n commands(): readonly SlashCommand[] {\n return (this.#connection.commands?.value ?? []).map(slashCommand);\n }\n\n createScoop(parentId: string, name: string): Agent {\n const provisional = `scoop:creating-${crypto.randomUUID()}`;\n const created = this.#connection.control.createScoop(parentId, name, BACKGROUND_CONTEXT).then(\n (result) => result.id,\n () => null\n );\n this.#creating.set(provisional, created);\n void created.then((id) => {\n if (this.#active !== provisional) return;\n this.#active = id ?? parentId;\n this.emit('active', this.#active);\n this.emit('messages', this.#active);\n });\n return {\n id: provisional,\n name,\n kind: 'scoop',\n parentId,\n status: 'idle',\n model: '',\n contextFill: 0,\n unread: 0,\n };\n }\n\n async drop(agentId: string): Promise<void> {\n const parent = this.#summary().find((summary) => summary.id === agentId)?.parentId ?? CONE;\n const dropped = await this.#connection.control.drop(agentId, BACKGROUND_CONTEXT);\n if (dropped.error !== null) throw new Error(dropped.error);\n if (this.#active === agentId) this.select(parent);\n }\n\n async createCone(name: string): Promise<Agent> {\n const created = await this.#connection.control.createCone(name, BACKGROUND_CONTEXT);\n if (created.error !== null) throw new Error(created.error);\n return {\n id: created.id,\n name: name.trim(),\n kind: 'cone',\n parentId: null,\n status: 'idle',\n model: '',\n contextFill: 0,\n unread: 0,\n };\n }\n\n frozen(): readonly FrozenCone[] {\n return (this.#connection.frozen?.value ?? []).map(\n ({ id, name, title, model, messages, frozenAt, kind, live, thawedAs }) => ({\n id,\n name,\n title,\n model,\n messages,\n frozenAt,\n kind,\n live,\n ...(thawedAs ? { thawedAs } : {}),\n })\n );\n }\n\n thaw(id: string): Agent | null {\n const record = this.frozen().find((item) => item.id === id);\n if (!record) return null;\n if (record.live) {\n const running = this.list().find((agent) => agent.id === id) ?? null;\n if (running) this.select(id);\n return running;\n }\n const provisional = `thawing-${crypto.randomUUID()}`;\n const thawed = this.#connection.control.thaw(id, BACKGROUND_CONTEXT).then(\n (result) => result.id,\n () => null\n );\n this.#creating.set(provisional, thawed);\n void thawed.then((cone) => {\n if (this.#active !== provisional) return;\n this.#active = cone ?? CONE;\n this.emit('active', this.#active);\n this.emit('messages', this.#active);\n });\n return {\n id: provisional,\n name: record.name,\n kind: 'cone',\n parentId: null,\n status: 'idle',\n model: record.model,\n contextFill: 0,\n unread: 0,\n };\n }\n\n discard(id: string): void {\n void this.#connection.control.discard(id, BACKGROUND_CONTEXT);\n }\n}\n"],
|
|
5
|
-
"mappings": "AAYA,SAAS,0BAA0B;AAGnC,SAAS,iBAAiB;
|
|
4
|
+
"sourcesContent": ["import type {\n Agent,\n AgentEvents,\n AgentPort,\n AgentStatus,\n FrozenCone,\n Message,\n Outgoing,\n SlashCommand,\n Thinking,\n UserMessage,\n} from '@ai-ecoverse/slicc-spectrum/ui';\nimport { BACKGROUND_CONTEXT } from '@earendil-works/chord/context';\nimport type { ConversationView } from '@earendil-works/pi-durable';\nimport type { AgentConnection } from '../client.ts';\nimport { entryLick } from '../licks/state.ts';\nimport { type VaultHold, vaultHold } from '../secrets/view.ts';\nimport type { AgentSettingsChange, AgentSummary, Command } from '../services.ts';\nimport { Emitter } from './emitter.ts';\nimport { isBusy, queued, toMessages } from './messages.ts';\n\nexport const CONE = 'cone';\n\nconst thinking: Record<string, Thinking> = {\n off: 'off',\n minimal: 'low',\n low: 'low',\n medium: 'medium',\n high: 'high',\n xhigh: 'high',\n max: 'high',\n};\n\ninterface AgentDoc {\n model?: { provider: string; modelId: string };\n thinkingLevel?: string;\n}\n\nfunction status(view: ConversationView | undefined, messages: readonly Message[]): AgentStatus {\n if (isBusy(view)) {\n const live = view?.docs['pi.live'] as { tools?: { status: string }[] } | undefined;\n return live?.tools?.some((slot) => slot.status === 'running') ? 'working' : 'thinking';\n }\n const last = messages.at(-1);\n return last?.role === 'assistant' && last.status === 'error' ? 'error' : 'idle';\n}\n\nexport function slashCommand({ kind, ...command }: Command): SlashCommand {\n return kind === 'action' ? command : { ...command, kind };\n}\n\nexport type AgentHold = VaultHold;\n\nexport type AgentAdapterEvents = AgentEvents & { hold: AgentHold | null };\n\nfunction sameHold(a: AgentHold | null, b: AgentHold | null): boolean {\n return a === b || (a !== null && b !== null && a.reason === b.reason && a.held === b.held);\n}\n\ninterface Pending {\n agentId: string;\n message: UserMessage;\n dropped: boolean;\n release(): void;\n released: Promise<void>;\n}\n\nexport class AgentAdapter extends Emitter<AgentAdapterEvents> implements AgentPort {\n readonly #connection: AgentConnection;\n readonly #ready: Promise<void>;\n readonly #messages = new Map<string, Message[]>();\n #active: string | null = null;\n #creating = new Map<string, Promise<string | null>>();\n #hold: AgentHold | null = null;\n readonly #outbox = new Map<string, Pending>();\n\n constructor(connection: AgentConnection) {\n super();\n this.#connection = connection;\n this.#hold = this.hold();\n connection.vault?.subscribe(() => {\n const next = this.hold();\n if (sameHold(next, this.#hold)) return;\n this.#hold = next;\n if (!next) for (const pending of this.#outbox.values()) pending.release();\n this.emit('hold', next);\n this.emit('agents', this.list());\n });\n connection.frozen?.subscribe(() => {\n this.emit('frozen', this.frozen());\n this.emit('agents', this.list());\n });\n this.#ready = new Promise((resolve) => {\n connection.transcript.subscribe(() => {\n this.#refresh();\n resolve();\n });\n connection.deliveries.subscribe(() => this.#refresh());\n connection.views?.subscribe(() => this.#refresh());\n connection.agents?.subscribe(() => this.#refresh());\n });\n }\n\n #summary(): readonly AgentSummary[] {\n const agents = this.#connection.agents?.value?.agents;\n return agents?.length\n ? agents\n : [{ id: CONE, name: 'sliccy', kind: 'cone', parentId: null, role: null }];\n }\n\n #view(agentId: string = this.active()): ConversationView | undefined {\n const views = this.#connection.views?.value;\n const view = views?.[agentId];\n if (view) return view;\n const cone = this.#connection.agents?.value?.active ?? CONE;\n return agentId === cone ? this.#connection.transcript.value : undefined;\n }\n\n #refresh(): void {\n this.#active ??= this.#connection.agents?.value?.active ?? null;\n this.emit('agents', this.list());\n for (const summary of this.#summary()) this.#update(summary.id);\n for (const id of [...this.#messages.keys()])\n if (!this.#summary().some((summary) => summary.id === id)) this.#messages.delete(id);\n }\n\n #update(agentId: string): void {\n const view = this.#view(agentId);\n if (!view) return;\n const before = this.#messages.get(agentId) ?? [];\n const after = toMessages(view, this.#connection.deliveries.value);\n this.#messages.set(agentId, after);\n if (before.length !== after.length) {\n this.emit('messages', agentId);\n return;\n }\n const changed = after.filter(\n (message, index) => JSON.stringify(message) !== JSON.stringify(before[index])\n );\n if (changed.length === 1) this.emit('message', { agentId, message: changed[0] as Message });\n else if (changed.length > 1) this.emit('messages', agentId);\n }\n\n ready(): Promise<void> {\n return this.#ready;\n }\n\n hold(): AgentHold | null {\n return vaultHold(this.#connection.vault?.value);\n }\n\n list(): readonly Agent[] {\n const rows = this.#connection.frozen?.value ?? [];\n return this.#summary().map((summary) => {\n const view = this.#view(summary.id);\n const doc = view?.docs['pi.agent'] as AgentDoc | undefined;\n const title =\n summary.kind === 'cone' ? rows.find((row) => row.id === summary.id)?.title : undefined;\n return {\n id: summary.id,\n name: summary.role ? `${summary.name} \u00B7 ${summary.role}` : summary.name,\n kind: summary.kind,\n parentId: summary.parentId,\n status: this.#status(summary.id, status(view, this.#messages.get(summary.id) ?? [])),\n model: doc?.model ? `${doc.model.provider}/${doc.model.modelId}` : '',\n contextFill: 0,\n unread: 0,\n thinking: thinking[doc?.thinkingLevel ?? 'off'] ?? 'off',\n ...(title ? { title } : {}),\n };\n });\n }\n\n active(): string {\n const known = this.#summary();\n if (this.#active && this.#creating.has(this.#active)) return this.#active;\n if (this.#active && known.some((summary) => summary.id === this.#active)) return this.#active;\n return this.#connection.agents?.value?.active ?? CONE;\n }\n\n select(id: string): void {\n if (this.#creating.has(id)) {\n this.#active = id;\n this.emit('active', id);\n return;\n }\n const found = this.#summary().find((summary) => summary.id === id);\n if (!found) return;\n this.#active = id;\n if (found.kind === 'cone') void this.#connection.control.selectCone(id, BACKGROUND_CONTEXT);\n this.emit('active', id);\n this.emit('messages', id);\n }\n\n messages(agentId: string = this.active()): readonly Message[] {\n return this.#messages.get(agentId) ?? [];\n }\n\n async send(agentId: string, input: string | Outgoing): Promise<void> {\n const outgoing = typeof input === 'string' ? { text: input } : input;\n const target = this.#creating.has(agentId) ? await this.#creating.get(agentId) : agentId;\n if (target === null) throw new Error('The scoop could not be created.');\n const pending = target && this.#held(target) ? this.#pending(target, outgoing) : undefined;\n if (pending) await pending.released;\n if (pending?.dropped) return this.#settle(pending);\n const sent = await this.#connection.control\n .send(\n {\n text: outgoing.text,\n whenBusy: outgoing.mode === 'queue' ? 'followUp' : 'steer',\n requestId: crypto.randomUUID(),\n agentId: target || null,\n },\n BACKGROUND_CONTEXT\n )\n .finally(() => pending && this.#settle(pending));\n if (!sent.accepted) throw new Error(sent.error.message);\n if (pending?.dropped)\n void this.#connection.control.unqueue(pending.agentId, sent.submissionId, BACKGROUND_CONTEXT);\n }\n\n #pending(agentId: string, outgoing: Outgoing): Pending {\n const id = `p${crypto.randomUUID()}`;\n const message: UserMessage = {\n id,\n role: 'user',\n text: outgoing.text,\n createdAt: Date.now(),\n queued: true,\n mode: outgoing.mode === 'queue' ? 'queue' : 'steer',\n };\n const { promise: released, resolve: release } = Promise.withResolvers<void>();\n const pending = { agentId, message, dropped: false, release, released };\n this.#outbox.set(id, pending);\n this.emit('messages', agentId);\n return pending;\n }\n\n #settle(pending: Pending): void {\n this.#outbox.delete(pending.message.id);\n this.emit('messages', pending.agentId);\n }\n\n async rewind(agentId: string, messageId: string): Promise<Outgoing | null> {\n const rewound = await this.#connection.control.rewindAgent(\n agentId,\n messageId,\n BACKGROUND_CONTEXT\n );\n return rewound.done ? { text: rewound.text } : null;\n }\n\n stop(agentId: string = this.active()): void {\n void this.#connection.control.stopAgent(agentId, BACKGROUND_CONTEXT);\n }\n\n busy(agentId: string = this.active()): boolean {\n return isBusy(this.#view(agentId)) || this.#held(agentId);\n }\n\n #status(agentId: string, shown: AgentStatus): AgentStatus {\n return shown === 'idle' && this.#held(agentId) ? 'working' : shown;\n }\n\n #held(agentId: string): boolean {\n return this.#hold !== null && agentId === (this.#connection.agents?.value?.active ?? CONE);\n }\n\n queue(agentId: string = this.active()): readonly UserMessage[] {\n const pending = [...this.#outbox.values()]\n .filter((item) => item.agentId === agentId && !item.dropped)\n .map((item) => item.message);\n return [...queued(this.#view(agentId)), ...pending];\n }\n\n unqueue(agentId: string, messageId: string): void {\n const pending = this.#outbox.get(messageId);\n if (pending) {\n pending.dropped = true;\n pending.release();\n this.emit('messages', pending.agentId);\n return;\n }\n void this.#connection.control.unqueue(agentId, messageId.replace(/^q/, ''), BACKGROUND_CONTEXT);\n }\n\n suggestion(): string | null {\n return null;\n }\n\n answer(): void {}\n\n resolveLick(agentId: string, messageId: string, state: 'confirmed' | 'dismissed'): void {\n const message = this.messages(agentId).find((candidate) => candidate.id === messageId);\n const entry = this.#view(agentId)?.entries.find(\n (candidate) => `e${candidate.id}` === messageId\n );\n const lick = message?.role === 'lick' && entry ? entryLick(entry) : undefined;\n if (lick)\n void this.#connection.control.resolveAgentLick(agentId, lick.id, state, BACKGROUND_CONTEXT);\n }\n\n compact(agentId: string = this.active()): void {\n void this.#connection.control.compactAgent(agentId, null, BACKGROUND_CONTEXT);\n }\n\n clear(agentId: string = this.active()): void {\n void this.#connection.control.newChat(agentId, BACKGROUND_CONTEXT);\n }\n\n freeze(agentId: string = this.active()): void {\n void this.#connection.control.freeze(agentId, BACKGROUND_CONTEXT);\n }\n\n #configure(agentId: string, change: Partial<AgentSettingsChange>): void {\n void this.#connection.control.configure(\n {\n model: change.model ?? null,\n thinkingLevel: change.thinkingLevel ?? null,\n agentId,\n },\n BACKGROUND_CONTEXT\n );\n }\n\n setModel(agentId: string, model: string): void {\n const at = model.indexOf('/');\n if (at <= 0) return;\n this.#configure(agentId, {\n model: { provider: model.slice(0, at), modelId: model.slice(at + 1) },\n });\n }\n\n setThinking(agentId: string, level: Thinking): void {\n this.#configure(agentId, { thinkingLevel: level });\n }\n\n async older(): Promise<readonly Message[]> {\n return [];\n }\n\n commands(): readonly SlashCommand[] {\n return (this.#connection.commands?.value ?? []).map(slashCommand);\n }\n\n createScoop(parentId: string, name: string): Agent {\n const provisional = `scoop:creating-${crypto.randomUUID()}`;\n const created = this.#connection.control.createScoop(parentId, name, BACKGROUND_CONTEXT).then(\n (result) => result.id,\n () => null\n );\n this.#creating.set(provisional, created);\n void created.then((id) => {\n if (this.#active !== provisional) return;\n this.#active = id ?? parentId;\n this.emit('active', this.#active);\n this.emit('messages', this.#active);\n });\n return {\n id: provisional,\n name,\n kind: 'scoop',\n parentId,\n status: 'idle',\n model: '',\n contextFill: 0,\n unread: 0,\n };\n }\n\n async drop(agentId: string): Promise<void> {\n const parent = this.#summary().find((summary) => summary.id === agentId)?.parentId ?? CONE;\n const dropped = await this.#connection.control.drop(agentId, BACKGROUND_CONTEXT);\n if (dropped.error !== null) throw new Error(dropped.error);\n if (this.#active === agentId) this.select(parent);\n }\n\n async createCone(name: string): Promise<Agent> {\n const created = await this.#connection.control.createCone(name, BACKGROUND_CONTEXT);\n if (created.error !== null) throw new Error(created.error);\n return {\n id: created.id,\n name: name.trim(),\n kind: 'cone',\n parentId: null,\n status: 'idle',\n model: '',\n contextFill: 0,\n unread: 0,\n };\n }\n\n frozen(): readonly FrozenCone[] {\n return (this.#connection.frozen?.value ?? []).map(\n ({ id, name, title, model, messages, frozenAt, kind, live, thawedAs }) => ({\n id,\n name,\n title,\n model,\n messages,\n frozenAt,\n kind,\n live,\n ...(thawedAs ? { thawedAs } : {}),\n })\n );\n }\n\n thaw(id: string): Agent | null {\n const record = this.frozen().find((item) => item.id === id);\n if (!record) return null;\n if (record.live) {\n const running = this.list().find((agent) => agent.id === id) ?? null;\n if (running) this.select(id);\n return running;\n }\n const provisional = `thawing-${crypto.randomUUID()}`;\n const thawed = this.#connection.control.thaw(id, BACKGROUND_CONTEXT).then(\n (result) => result.id,\n () => null\n );\n this.#creating.set(provisional, thawed);\n void thawed.then((cone) => {\n if (this.#active !== provisional) return;\n this.#active = cone ?? CONE;\n this.emit('active', this.#active);\n this.emit('messages', this.#active);\n });\n return {\n id: provisional,\n name: record.name,\n kind: 'cone',\n parentId: null,\n status: 'idle',\n model: record.model,\n contextFill: 0,\n unread: 0,\n };\n }\n\n discard(id: string): void {\n void this.#connection.control.discard(id, BACKGROUND_CONTEXT);\n }\n}\n"],
|
|
5
|
+
"mappings": "AAYA,SAAS,0BAA0B;AAGnC,SAAS,iBAAiB;AAC1B,SAAyB,iBAAiB;AAE1C,SAAS,eAAe;AACxB,SAAS,QAAQ,QAAQ,kBAAkB;AAEpC,MAAM,OAAO;AAEpB,MAAM,WAAqC;AAAA,EACzC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,OAAO;AAAA,EACP,KAAK;A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d,aAAa;AAAA,MACb,QAAQ;AAAA,IACV;AAAA,EACF;AAAA,EAEA,QAAQ,IAAkB;AACxB,SAAK,KAAK,YAAY,QAAQ,QAAQ,IAAI,kBAAkB;AAAA,EAC9D;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -2,6 +2,7 @@ import { parseLick } from "../licks/lick.js";
|
|
|
2
2
|
import { entryLick, LICK_TOOLS, lickDecisions } from "../licks/state.js";
|
|
3
3
|
import { mcpLabel } from "../mcp/label.js";
|
|
4
4
|
import { FROM_KIND } from "../scoops/from.js";
|
|
5
|
+
import { listedLine, SECRETS_KIND } from "../secrets/view.js";
|
|
5
6
|
import { SPRINKLE_KIND } from "../sprinkles/kind.js";
|
|
6
7
|
function textOf(content) {
|
|
7
8
|
if (typeof content === "string") return content;
|
|
@@ -264,11 +265,23 @@ function thawed(id, entry) {
|
|
|
264
265
|
createdAt: entry.model?.[0]?.timestamp ?? 0
|
|
265
266
|
};
|
|
266
267
|
}
|
|
268
|
+
function secrets(id, entry) {
|
|
269
|
+
const data = entry.data ?? {};
|
|
270
|
+
return {
|
|
271
|
+
id,
|
|
272
|
+
role: "system",
|
|
273
|
+
kind: "notice",
|
|
274
|
+
title: "Secrets listed",
|
|
275
|
+
text: listedLine(data.names ?? []),
|
|
276
|
+
createdAt: entry.model?.[0]?.timestamp ?? 0
|
|
277
|
+
};
|
|
278
|
+
}
|
|
267
279
|
function entryMessage(entry, out, calls, delivered, notes) {
|
|
268
280
|
const id = `e${entry.id}`;
|
|
269
281
|
const model = entry.model?.[0];
|
|
270
282
|
if (entry.kind === "slicc.rewound") out.push(rewound(id, entry));
|
|
271
283
|
if (entry.kind === "slicc.thawed") out.push(thawed(id, entry));
|
|
284
|
+
else if (entry.kind === SECRETS_KIND) out.push(secrets(id, entry));
|
|
272
285
|
else if (entry.kind === SPRINKLE_KIND) out.push(sprinkleMessage(id, entry));
|
|
273
286
|
else if (entry.kind === "pi.user" && model)
|
|
274
287
|
out.push(
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/spectrum/messages.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n AssistantMessage,\n AssistantStatus,\n ErrorAction,\n LickMessage,\n Message,\n MessagePart,\n SystemMessage,\n ToolCall,\n ToolStatus,\n Usage,\n UserMessage,\n} from '@ai-ecoverse/slicc-spectrum/ui';\nimport type { ConversationView, EntryRecord } from '@earendil-works/pi-durable';\nimport { parseLick } from '../licks/lick.ts';\nimport { entryLick, LICK_TOOLS, type LickDecision, lickDecisions } from '../licks/state.ts';\nimport { mcpLabel } from '../mcp/label.ts';\nimport { FROM_KIND, type From } from '../scoops/from.ts';\nimport type { Delivered } from '../services.ts';\nimport { SPRINKLE_KIND } from '../sprinkles/kind.ts';\n\ntype Json = Record<string, unknown>;\n\ninterface Block {\n type: string;\n text?: string;\n thinking?: string;\n id?: string;\n name?: string;\n arguments?: Json;\n}\n\ninterface ModelMessage {\n role: string;\n content?: string | Block[];\n timestamp?: number;\n stopReason?: string;\n errorMessage?: string;\n provider?: string;\n model?: string;\n usage?: {\n input?: number;\n output?: number;\n cacheRead?: number;\n cacheWrite?: number;\n cost?: { total?: number };\n };\n toolCallId?: string;\n isError?: boolean;\n details?: { patch?: unknown };\n}\n\ninterface Slot {\n callId: string;\n status: string;\n output?: string;\n}\n\ninterface Live {\n run?: unknown;\n generation?: { message?: ModelMessage; retry?: { at: number; error: string } };\n tools?: Slot[];\n compactions?: { taskId: number; reason: string }[];\n}\n\nexport function textOf(content: ModelMessage['content']): string {\n if (typeof content === 'string') return content;\n return (content ?? []).map((block) => (block.type === 'text' ? (block.text ?? '') : '')).join('');\n}\n\nconst paths = (args: Json | undefined): string[] =>\n typeof args?.path === 'string' ? [args.path] : [];\n\nfunction title(args: Json | undefined): string {\n const subject = args?.command ?? args?.path;\n return typeof subject === 'string' ? subject : '';\n}\n\ninterface Replacement {\n oldText?: string;\n newText?: string;\n}\n\nconst GAP = '\u2026';\n\nfunction seconds(value: unknown): string | undefined {\n return typeof value === 'number' ? `timeout ${value}s` : undefined;\n}\n\nfunction lines(args: Json): string | undefined {\n const { offset, limit } = args as { offset?: number; limit?: number };\n if (typeof offset === 'number' && typeof limit === 'number')\n return `lines ${offset}\u2013${offset + limit - 1}`;\n if (typeof offset === 'number') return `from line ${offset}`;\n return typeof limit === 'number' ? `first ${limit} lines` : undefined;\n}\n\nfunction edits(args: Json): ToolCall['diff'] {\n const list = Array.isArray(args.edits) ? (args.edits as Replacement[]) : [];\n if (list.length === 0) return undefined;\n return {\n before: list.map((edit) => edit.oldText ?? '').join(`\\n${GAP}\\n`),\n after: list.map((edit) => edit.newText ?? '').join(`\\n${GAP}\\n`),\n };\n}\n\nexport function fromPatch(patch: string): ToolCall['diff'] {\n const before: string[] = [];\n const after: string[] = [];\n let hunks = 0;\n for (const line of patch.split('\\n')) {\n if (line.startsWith('@@')) {\n if (hunks++ > 0) {\n before.push(GAP);\n after.push(GAP);\n }\n continue;\n }\n if (hunks === 0 || line === '' || line.startsWith('\\\\')) continue;\n const text = line.slice(1);\n if (line.startsWith('-')) before.push(text);\n else if (line.startsWith('+')) after.push(text);\n else {\n before.push(text);\n after.push(text);\n }\n }\n return hunks ? { before: before.join('\\n'), after: after.join('\\n') } : undefined;\n}\n\nfunction shape(name: string, args: Json): Pick<ToolCall, 'input' | 'meta' | 'diff'> {\n const path = typeof args.path === 'string' ? args.path : '';\n const meta = name === 'bash' ? seconds(args.timeout) : name === 'read' ? lines(args) : undefined;\n const base = meta ? { meta } : {};\n if (name === 'bash' && typeof args.command === 'string') return { input: args.command, ...base };\n if (name === 'read' || name === 'write') return { input: path, ...base };\n if (name === 'edit') {\n const diff = edits(args);\n return { input: path, ...(diff ? { diff } : {}) };\n }\n return { input: JSON.stringify(args, null, 2) };\n}\n\nfunction toolCall(block: Block): ToolCall {\n const args = block.arguments ?? {};\n return {\n id: block.id ?? '',\n name: block.name ?? 'tool',\n title: mcpLabel(block.name ?? '') ?? title(block.arguments),\n ...shape(block.name ?? 'tool', args),\n output: '',\n status: 'running',\n paths: paths(block.arguments),\n };\n}\n\nfunction part(block: Block): MessagePart | undefined {\n if (block.type === 'text') return { type: 'text', text: block.text ?? '' };\n if (block.type === 'thinking') return { type: 'thinking', text: block.thinking ?? '' };\n if (block.type === 'toolCall') return { type: 'tool', tool: toolCall(block) };\n return undefined;\n}\n\nfunction usage(message: ModelMessage): Usage | undefined {\n const used = message.usage;\n if (!used) return undefined;\n return {\n input: used.input ?? 0,\n output: used.output ?? 0,\n cost: used.cost?.total ?? 0,\n cacheRead: used.cacheRead ?? 0,\n cacheWrite: used.cacheWrite ?? 0,\n };\n}\n\nconst statuses: Record<string, AssistantStatus> = { error: 'error', aborted: 'stopped' };\n\nconst credentials =\n /security token|unrecognizedclient|not authori[sz]ed|unauthori[sz]ed|forbidden|\\b40[13]\\b|api key|credential|bearer/i;\nconst models = /model/i;\nconst unavailable =\n /access|invalid|not found|identifier|unsupported|not supported|isn['\u2019]t supported|not available|isn['\u2019]t available/i;\n\nconst providerNames: Record<string, string> = { 'amazon-bedrock': 'Bedrock' };\nconst filtered =\n /Provider (?:stopped with|finish_reason): (?:content_filter(?:ed)?|guardrail_intervened|sensitive)|content[_ ]filter(?:ed|ing)?\\b|guardrail[_ ]intervened/i;\nconst refused =\n /refused to complete the request|Provider (?:stopped with|finish_reason): refusal|\\bstop_?reason\\W+refusal\\b/i;\nconst missing = /no api key|missing|not configured|no credentials/i;\n\nexport function errorPart(error: string, provider?: string): MessagePart {\n const action = errorAction(error);\n if (action === 'drop-turn') {\n return {\n type: 'error',\n message: filtered.test(error)\n ? \"The model's content filter stopped this reply.\"\n : 'The model refused to answer this turn.',\n detail: error,\n action,\n };\n }\n if (action === 'settings' && provider === 'adobe') {\n return {\n type: 'error',\n message: 'Your Adobe session has expired.',\n detail: error,\n action: 'login',\n };\n }\n const name = providerNames[provider ?? ''] ?? 'The provider';\n const lead =\n action === 'settings'\n ? missing.test(error)\n ? `${name} needs an API key.`\n : `${name} rejected the API key.`\n : action === 'change-model'\n ? \"This model isn't available with the current account.\"\n : null;\n return lead\n ? { type: 'error', message: lead, detail: error, action }\n : { type: 'error', message: error, action };\n}\n\nexport function errorAction(message: string): ErrorAction {\n if (filtered.test(message) || refused.test(message)) return 'drop-turn';\n if (credentials.test(message)) return 'settings';\n if (models.test(message) && unavailable.test(message)) return 'change-model';\n return 'retry';\n}\n\nfunction sprinkleMessage(id: string, entry: EntryRecord): AssistantMessage {\n const data = (entry.data ?? {}) as { sprinkle?: unknown; at?: unknown };\n return {\n id,\n role: 'assistant',\n parts: [{ type: 'sprinkle', sprinkle: String(data.sprinkle ?? '') }],\n status: 'done',\n createdAt: typeof data.at === 'number' ? data.at : 0,\n };\n}\n\nexport function assistant(\n id: string,\n message: ModelMessage,\n status?: AssistantStatus\n): AssistantMessage {\n const blocks = Array.isArray(message.content) ? message.content : [];\n const parts = blocks.map(part).filter((item): item is MessagePart => item !== undefined);\n if (message.errorMessage) parts.push(errorPart(message.errorMessage, message.provider));\n const used = usage(message);\n return {\n id,\n role: 'assistant',\n parts,\n status: status ?? statuses[message.stopReason ?? ''] ?? 'done',\n createdAt: message.timestamp ?? 0,\n ...(message.provider && message.model ? { model: `${message.provider}/${message.model}` } : {}),\n ...(used ? { usage: used } : {}),\n };\n}\n\nfunction user(\n id: string,\n message: ModelMessage,\n delivered: Delivered | undefined,\n from: From | undefined\n): UserMessage {\n return {\n id,\n role: 'user',\n text: textOf(message.content),\n createdAt: message.timestamp ?? 0,\n ...(delivered ? { delivered } : {}),\n ...(from ? { from: from.from } : {}),\n ...(from?.agent ? { origin: 'agent' as const } : {}),\n };\n}\n\nexport function origins(entries: readonly EntryRecord[]): Map<number, From> {\n const out = new Map<number, From>();\n for (const entry of entries)\n if (entry.kind === FROM_KIND) {\n const note = entry.data as From;\n out.set(note.entry, note);\n }\n return out;\n}\n\nfunction lickMessage(\n id: string,\n entry: EntryRecord,\n decisions: ReadonlyMap<string, LickDecision>\n): LickMessage | undefined {\n const lick = entryLick(entry);\n if (!lick) return undefined;\n const state = lick.actions?.length ? (decisions.get(lick.id) ?? 'pending') : undefined;\n return {\n id,\n role: 'lick',\n channel: lick.channel,\n title: lick.title,\n text: lick.text,\n createdAt: lick.at,\n ...(lick.body ? { body: lick.body } : {}),\n ...(lick.count > 1 ? { count: lick.count } : {}),\n ...(state ? { state } : {}),\n ...(lick.severity ? { severity: lick.severity } : {}),\n };\n}\n\nfunction withoutLickTools(message: AssistantMessage): AssistantMessage {\n const parts = message.parts.filter((item) => item.type !== 'tool' || !LICK_TOOLS[item.tool.name]);\n return parts.length === message.parts.length ? message : { ...message, parts };\n}\n\nfunction system(id: string, entry: EntryRecord, text: string): SystemMessage {\n const reason = (entry.data as Json | undefined)?.reason as SystemMessage['trigger'] | undefined;\n return {\n id,\n role: 'system',\n kind: 'compaction',\n text,\n createdAt: 0,\n state: 'summarized',\n ...(reason ? { trigger: reason } : {}),\n };\n}\n\nfunction tools(messages: Message[]): Map<string, ToolCall> {\n const found = new Map<string, ToolCall>();\n for (const message of messages) {\n if (message.role !== 'assistant') continue;\n for (const item of message.parts) if (item.type === 'tool') found.set(item.tool.id, item.tool);\n }\n return found;\n}\n\nfunction settle(calls: Map<string, ToolCall>, result: ModelMessage): void {\n const call = calls.get(result.toolCallId ?? '');\n if (!call) return;\n call.output = textOf(result.content);\n call.status = result.isError ? 'error' : 'done';\n const image = Array.isArray(result.content)\n ? (result.content as { type: string; data?: string; mimeType?: string }[]).find(\n (part) => part.type === 'image' && part.data && part.mimeType\n )\n : undefined;\n if (image) call.image = `data:${image.mimeType};base64,${image.data}`;\n const patch = result.details?.patch;\n const diff = typeof patch === 'string' ? fromPatch(patch) : undefined;\n if (diff) call.diff = diff;\n else if (result.isError) delete call.diff;\n}\n\nfunction rewound(id: string, entry: EntryRecord): SystemMessage {\n const data = (entry.data ?? {}) as { stopped?: string[]; restored?: string[]; files?: boolean };\n const notes = [\n 'Its prompt is back in the composer.',\n ...(data.stopped?.length\n ? [`Stopped ${data.stopped.map((name) => `scoop ${name}`).join(', ')}.`]\n : []),\n ...(data.restored?.length\n ? [`Restored ${data.restored.map((name) => `scoop ${name}`).join(', ')}.`]\n : []),\n ...(data.files ? ['Changed files stay; use Changes or git to revert them.'] : []),\n ];\n return {\n id,\n role: 'system',\n kind: 'notice',\n title: 'Rewound 1 turn',\n text: notes.join(' '),\n createdAt: 0,\n };\n}\n\nfunction thawed(id: string, entry: EntryRecord): SystemMessage {\n const data = (entry.data ?? {}) as { name?: string; kind?: string };\n const what = data.kind === 'agent' ? 'agent run' : 'scoop';\n return {\n id,\n role: 'system',\n kind: 'notice',\n title: `Thawed from ${what} ${data.name ?? ''}`.trim(),\n text: textOf(entry.model?.[0]?.content ?? ''),\n createdAt: entry.model?.[0]?.timestamp ?? 0,\n };\n}\n\nfunction entryMessage(\n entry: EntryRecord,\n out: Message[],\n calls: Map<string, ToolCall>,\n delivered: Delivered | undefined,\n notes: { decisions: ReadonlyMap<string, LickDecision>; origins: ReadonlyMap<number, From> }\n): void {\n const id = `e${entry.id}`;\n const model = entry.model?.[0] as ModelMessage | undefined;\n if (entry.kind === 'slicc.rewound') out.push(rewound(id, entry));\n if (entry.kind === 'slicc.thawed') out.push(thawed(id, entry));\n else if (entry.kind === SPRINKLE_KIND) out.push(sprinkleMessage(id, entry));\n else if (entry.kind === 'pi.user' && model)\n out.push(\n lickMessage(id, entry, notes.decisions) ??\n user(id, model, delivered, notes.origins.get(entry.id))\n );\n else if (entry.kind === 'pi.assistant' && model) {\n const message = assistant(id, model);\n out.push(withoutLickTools(message));\n for (const [key, value] of tools([message])) calls.set(key, value);\n } else if (entry.kind === 'pi.tool-result' && model) settle(calls, model);\n else if (entry.kind === 'pi.compaction') out.push(system(id, entry, textOf(model?.content)));\n}\n\nconst slotStatus: Record<string, ToolStatus> = {\n pending: 'running',\n running: 'running',\n done: 'done',\n};\n\nfunction live(view: ConversationView, out: Message[], calls: Map<string, ToolCall>): void {\n const state = view.docs['pi.live'] as Live | undefined;\n for (const slot of state?.tools ?? []) {\n const call = calls.get(slot.callId);\n if (call && call.status === 'running') {\n call.status = slotStatus[slot.status] ?? 'running';\n call.output = slot.output ?? call.output;\n }\n }\n const partial = state?.generation?.message;\n if (partial) out.push(assistant('live', partial, 'streaming'));\n for (const compaction of state?.compactions ?? []) {\n out.push({\n id: `compaction-${compaction.taskId}`,\n role: 'system',\n kind: 'compaction',\n text: '',\n createdAt: 0,\n state: 'summarizing',\n trigger: compaction.reason as SystemMessage['trigger'],\n });\n }\n const retry = state?.generation?.retry;\n if (retry)\n out.push({\n id: 'retry',\n role: 'system',\n kind: 'notice',\n text: retry.error,\n createdAt: retry.at,\n });\n}\n\nexport function toMessages(\n view: ConversationView | undefined,\n deliveries: Readonly<Record<string, Delivered>> = {}\n): Message[] {\n const out: Message[] = [];\n if (!view) return out;\n const calls = new Map<string, ToolCall>();\n const notes = { decisions: lickDecisions(view.entries), origins: origins(view.entries) };\n let previous: EntryRecord | undefined;\n for (const entry of view.entries) {\n const steered = previous?.kind === 'pi.tool-result' ? 'steer' : undefined;\n entryMessage(entry, out, calls, deliveries[String(entry.id)] ?? steered, notes);\n previous = entry;\n }\n live(view, out, calls);\n return out;\n}\n\nexport function isBusy(view: ConversationView | undefined): boolean {\n return Boolean((view?.docs['pi.live'] as Live | undefined)?.run);\n}\n\nexport function queued(view: ConversationView | undefined): UserMessage[] {\n const items = ((view?.docs['pi.inbox'] as { items?: Json[] } | undefined)?.items ?? []) as {\n id: number;\n mode: string;\n content?: ModelMessage['content'];\n }[];\n return items\n .filter((item) => item.mode !== 'write' && !parseLick(textOf(item.content)))\n .map((item) => ({\n id: `q${item.id}`,\n role: 'user',\n text: textOf(item.content),\n createdAt: 0,\n queued: true,\n mode: item.mode === 'steer' ? 'steer' : 'queue',\n }));\n}\n"],
|
|
5
|
-
"mappings": "AAcA,SAAS,iBAAiB;AAC1B,SAAS,WAAW,YAA+B,q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AK,OAAO;AAAA,IACzB,WAAW;AAAA,IACX,QAAQ;AAAA,IACR,MAAM,KAAK,SAAS,UAAU,UAAU;AAAA,EAC1C,EAAE;AACN;",
|
|
4
|
+
"sourcesContent": ["import type {\n AssistantMessage,\n AssistantStatus,\n ErrorAction,\n LickMessage,\n Message,\n MessagePart,\n SystemMessage,\n ToolCall,\n ToolStatus,\n Usage,\n UserMessage,\n} from '@ai-ecoverse/slicc-spectrum/ui';\nimport type { ConversationView, EntryRecord } from '@earendil-works/pi-durable';\nimport { parseLick } from '../licks/lick.ts';\nimport { entryLick, LICK_TOOLS, type LickDecision, lickDecisions } from '../licks/state.ts';\nimport { mcpLabel } from '../mcp/label.ts';\nimport { FROM_KIND, type From } from '../scoops/from.ts';\nimport type { SecretName } from '../secrets/names.ts';\nimport { listedLine, SECRETS_KIND } from '../secrets/view.ts';\nimport type { Delivered } from '../services.ts';\nimport { SPRINKLE_KIND } from '../sprinkles/kind.ts';\n\ntype Json = Record<string, unknown>;\n\ninterface Block {\n type: string;\n text?: string;\n thinking?: string;\n id?: string;\n name?: string;\n arguments?: Json;\n}\n\ninterface ModelMessage {\n role: string;\n content?: string | Block[];\n timestamp?: number;\n stopReason?: string;\n errorMessage?: string;\n provider?: string;\n model?: string;\n usage?: {\n input?: number;\n output?: number;\n cacheRead?: number;\n cacheWrite?: number;\n cost?: { total?: number };\n };\n toolCallId?: string;\n isError?: boolean;\n details?: { patch?: unknown };\n}\n\ninterface Slot {\n callId: string;\n status: string;\n output?: string;\n}\n\ninterface Live {\n run?: unknown;\n generation?: { message?: ModelMessage; retry?: { at: number; error: string } };\n tools?: Slot[];\n compactions?: { taskId: number; reason: string }[];\n}\n\nexport function textOf(content: ModelMessage['content']): string {\n if (typeof content === 'string') return content;\n return (content ?? []).map((block) => (block.type === 'text' ? (block.text ?? '') : '')).join('');\n}\n\nconst paths = (args: Json | undefined): string[] =>\n typeof args?.path === 'string' ? [args.path] : [];\n\nfunction title(args: Json | undefined): string {\n const subject = args?.command ?? args?.path;\n return typeof subject === 'string' ? subject : '';\n}\n\ninterface Replacement {\n oldText?: string;\n newText?: string;\n}\n\nconst GAP = '\u2026';\n\nfunction seconds(value: unknown): string | undefined {\n return typeof value === 'number' ? `timeout ${value}s` : undefined;\n}\n\nfunction lines(args: Json): string | undefined {\n const { offset, limit } = args as { offset?: number; limit?: number };\n if (typeof offset === 'number' && typeof limit === 'number')\n return `lines ${offset}\u2013${offset + limit - 1}`;\n if (typeof offset === 'number') return `from line ${offset}`;\n return typeof limit === 'number' ? `first ${limit} lines` : undefined;\n}\n\nfunction edits(args: Json): ToolCall['diff'] {\n const list = Array.isArray(args.edits) ? (args.edits as Replacement[]) : [];\n if (list.length === 0) return undefined;\n return {\n before: list.map((edit) => edit.oldText ?? '').join(`\\n${GAP}\\n`),\n after: list.map((edit) => edit.newText ?? '').join(`\\n${GAP}\\n`),\n };\n}\n\nexport function fromPatch(patch: string): ToolCall['diff'] {\n const before: string[] = [];\n const after: string[] = [];\n let hunks = 0;\n for (const line of patch.split('\\n')) {\n if (line.startsWith('@@')) {\n if (hunks++ > 0) {\n before.push(GAP);\n after.push(GAP);\n }\n continue;\n }\n if (hunks === 0 || line === '' || line.startsWith('\\\\')) continue;\n const text = line.slice(1);\n if (line.startsWith('-')) before.push(text);\n else if (line.startsWith('+')) after.push(text);\n else {\n before.push(text);\n after.push(text);\n }\n }\n return hunks ? { before: before.join('\\n'), after: after.join('\\n') } : undefined;\n}\n\nfunction shape(name: string, args: Json): Pick<ToolCall, 'input' | 'meta' | 'diff'> {\n const path = typeof args.path === 'string' ? args.path : '';\n const meta = name === 'bash' ? seconds(args.timeout) : name === 'read' ? lines(args) : undefined;\n const base = meta ? { meta } : {};\n if (name === 'bash' && typeof args.command === 'string') return { input: args.command, ...base };\n if (name === 'read' || name === 'write') return { input: path, ...base };\n if (name === 'edit') {\n const diff = edits(args);\n return { input: path, ...(diff ? { diff } : {}) };\n }\n return { input: JSON.stringify(args, null, 2) };\n}\n\nfunction toolCall(block: Block): ToolCall {\n const args = block.arguments ?? {};\n return {\n id: block.id ?? '',\n name: block.name ?? 'tool',\n title: mcpLabel(block.name ?? '') ?? title(block.arguments),\n ...shape(block.name ?? 'tool', args),\n output: '',\n status: 'running',\n paths: paths(block.arguments),\n };\n}\n\nfunction part(block: Block): MessagePart | undefined {\n if (block.type === 'text') return { type: 'text', text: block.text ?? '' };\n if (block.type === 'thinking') return { type: 'thinking', text: block.thinking ?? '' };\n if (block.type === 'toolCall') return { type: 'tool', tool: toolCall(block) };\n return undefined;\n}\n\nfunction usage(message: ModelMessage): Usage | undefined {\n const used = message.usage;\n if (!used) return undefined;\n return {\n input: used.input ?? 0,\n output: used.output ?? 0,\n cost: used.cost?.total ?? 0,\n cacheRead: used.cacheRead ?? 0,\n cacheWrite: used.cacheWrite ?? 0,\n };\n}\n\nconst statuses: Record<string, AssistantStatus> = { error: 'error', aborted: 'stopped' };\n\nconst credentials =\n /security token|unrecognizedclient|not authori[sz]ed|unauthori[sz]ed|forbidden|\\b40[13]\\b|api key|credential|bearer/i;\nconst models = /model/i;\nconst unavailable =\n /access|invalid|not found|identifier|unsupported|not supported|isn['\u2019]t supported|not available|isn['\u2019]t available/i;\n\nconst providerNames: Record<string, string> = { 'amazon-bedrock': 'Bedrock' };\nconst filtered =\n /Provider (?:stopped with|finish_reason): (?:content_filter(?:ed)?|guardrail_intervened|sensitive)|content[_ ]filter(?:ed|ing)?\\b|guardrail[_ ]intervened/i;\nconst refused =\n /refused to complete the request|Provider (?:stopped with|finish_reason): refusal|\\bstop_?reason\\W+refusal\\b/i;\nconst missing = /no api key|missing|not configured|no credentials/i;\n\nexport function errorPart(error: string, provider?: string): MessagePart {\n const action = errorAction(error);\n if (action === 'drop-turn') {\n return {\n type: 'error',\n message: filtered.test(error)\n ? \"The model's content filter stopped this reply.\"\n : 'The model refused to answer this turn.',\n detail: error,\n action,\n };\n }\n if (action === 'settings' && provider === 'adobe') {\n return {\n type: 'error',\n message: 'Your Adobe session has expired.',\n detail: error,\n action: 'login',\n };\n }\n const name = providerNames[provider ?? ''] ?? 'The provider';\n const lead =\n action === 'settings'\n ? missing.test(error)\n ? `${name} needs an API key.`\n : `${name} rejected the API key.`\n : action === 'change-model'\n ? \"This model isn't available with the current account.\"\n : null;\n return lead\n ? { type: 'error', message: lead, detail: error, action }\n : { type: 'error', message: error, action };\n}\n\nexport function errorAction(message: string): ErrorAction {\n if (filtered.test(message) || refused.test(message)) return 'drop-turn';\n if (credentials.test(message)) return 'settings';\n if (models.test(message) && unavailable.test(message)) return 'change-model';\n return 'retry';\n}\n\nfunction sprinkleMessage(id: string, entry: EntryRecord): AssistantMessage {\n const data = (entry.data ?? {}) as { sprinkle?: unknown; at?: unknown };\n return {\n id,\n role: 'assistant',\n parts: [{ type: 'sprinkle', sprinkle: String(data.sprinkle ?? '') }],\n status: 'done',\n createdAt: typeof data.at === 'number' ? data.at : 0,\n };\n}\n\nexport function assistant(\n id: string,\n message: ModelMessage,\n status?: AssistantStatus\n): AssistantMessage {\n const blocks = Array.isArray(message.content) ? message.content : [];\n const parts = blocks.map(part).filter((item): item is MessagePart => item !== undefined);\n if (message.errorMessage) parts.push(errorPart(message.errorMessage, message.provider));\n const used = usage(message);\n return {\n id,\n role: 'assistant',\n parts,\n status: status ?? statuses[message.stopReason ?? ''] ?? 'done',\n createdAt: message.timestamp ?? 0,\n ...(message.provider && message.model ? { model: `${message.provider}/${message.model}` } : {}),\n ...(used ? { usage: used } : {}),\n };\n}\n\nfunction user(\n id: string,\n message: ModelMessage,\n delivered: Delivered | undefined,\n from: From | undefined\n): UserMessage {\n return {\n id,\n role: 'user',\n text: textOf(message.content),\n createdAt: message.timestamp ?? 0,\n ...(delivered ? { delivered } : {}),\n ...(from ? { from: from.from } : {}),\n ...(from?.agent ? { origin: 'agent' as const } : {}),\n };\n}\n\nexport function origins(entries: readonly EntryRecord[]): Map<number, From> {\n const out = new Map<number, From>();\n for (const entry of entries)\n if (entry.kind === FROM_KIND) {\n const note = entry.data as From;\n out.set(note.entry, note);\n }\n return out;\n}\n\nfunction lickMessage(\n id: string,\n entry: EntryRecord,\n decisions: ReadonlyMap<string, LickDecision>\n): LickMessage | undefined {\n const lick = entryLick(entry);\n if (!lick) return undefined;\n const state = lick.actions?.length ? (decisions.get(lick.id) ?? 'pending') : undefined;\n return {\n id,\n role: 'lick',\n channel: lick.channel,\n title: lick.title,\n text: lick.text,\n createdAt: lick.at,\n ...(lick.body ? { body: lick.body } : {}),\n ...(lick.count > 1 ? { count: lick.count } : {}),\n ...(state ? { state } : {}),\n ...(lick.severity ? { severity: lick.severity } : {}),\n };\n}\n\nfunction withoutLickTools(message: AssistantMessage): AssistantMessage {\n const parts = message.parts.filter((item) => item.type !== 'tool' || !LICK_TOOLS[item.tool.name]);\n return parts.length === message.parts.length ? message : { ...message, parts };\n}\n\nfunction system(id: string, entry: EntryRecord, text: string): SystemMessage {\n const reason = (entry.data as Json | undefined)?.reason as SystemMessage['trigger'] | undefined;\n return {\n id,\n role: 'system',\n kind: 'compaction',\n text,\n createdAt: 0,\n state: 'summarized',\n ...(reason ? { trigger: reason } : {}),\n };\n}\n\nfunction tools(messages: Message[]): Map<string, ToolCall> {\n const found = new Map<string, ToolCall>();\n for (const message of messages) {\n if (message.role !== 'assistant') continue;\n for (const item of message.parts) if (item.type === 'tool') found.set(item.tool.id, item.tool);\n }\n return found;\n}\n\nfunction settle(calls: Map<string, ToolCall>, result: ModelMessage): void {\n const call = calls.get(result.toolCallId ?? '');\n if (!call) return;\n call.output = textOf(result.content);\n call.status = result.isError ? 'error' : 'done';\n const image = Array.isArray(result.content)\n ? (result.content as { type: string; data?: string; mimeType?: string }[]).find(\n (part) => part.type === 'image' && part.data && part.mimeType\n )\n : undefined;\n if (image) call.image = `data:${image.mimeType};base64,${image.data}`;\n const patch = result.details?.patch;\n const diff = typeof patch === 'string' ? fromPatch(patch) : undefined;\n if (diff) call.diff = diff;\n else if (result.isError) delete call.diff;\n}\n\nfunction rewound(id: string, entry: EntryRecord): SystemMessage {\n const data = (entry.data ?? {}) as { stopped?: string[]; restored?: string[]; files?: boolean };\n const notes = [\n 'Its prompt is back in the composer.',\n ...(data.stopped?.length\n ? [`Stopped ${data.stopped.map((name) => `scoop ${name}`).join(', ')}.`]\n : []),\n ...(data.restored?.length\n ? [`Restored ${data.restored.map((name) => `scoop ${name}`).join(', ')}.`]\n : []),\n ...(data.files ? ['Changed files stay; use Changes or git to revert them.'] : []),\n ];\n return {\n id,\n role: 'system',\n kind: 'notice',\n title: 'Rewound 1 turn',\n text: notes.join(' '),\n createdAt: 0,\n };\n}\n\nfunction thawed(id: string, entry: EntryRecord): SystemMessage {\n const data = (entry.data ?? {}) as { name?: string; kind?: string };\n const what = data.kind === 'agent' ? 'agent run' : 'scoop';\n return {\n id,\n role: 'system',\n kind: 'notice',\n title: `Thawed from ${what} ${data.name ?? ''}`.trim(),\n text: textOf(entry.model?.[0]?.content ?? ''),\n createdAt: entry.model?.[0]?.timestamp ?? 0,\n };\n}\n\nfunction secrets(id: string, entry: EntryRecord): SystemMessage {\n const data = (entry.data ?? {}) as { names?: SecretName[] };\n return {\n id,\n role: 'system',\n kind: 'notice',\n title: 'Secrets listed',\n text: listedLine(data.names ?? []),\n createdAt: entry.model?.[0]?.timestamp ?? 0,\n };\n}\n\nfunction entryMessage(\n entry: EntryRecord,\n out: Message[],\n calls: Map<string, ToolCall>,\n delivered: Delivered | undefined,\n notes: { decisions: ReadonlyMap<string, LickDecision>; origins: ReadonlyMap<number, From> }\n): void {\n const id = `e${entry.id}`;\n const model = entry.model?.[0] as ModelMessage | undefined;\n if (entry.kind === 'slicc.rewound') out.push(rewound(id, entry));\n if (entry.kind === 'slicc.thawed') out.push(thawed(id, entry));\n else if (entry.kind === SECRETS_KIND) out.push(secrets(id, entry));\n else if (entry.kind === SPRINKLE_KIND) out.push(sprinkleMessage(id, entry));\n else if (entry.kind === 'pi.user' && model)\n out.push(\n lickMessage(id, entry, notes.decisions) ??\n user(id, model, delivered, notes.origins.get(entry.id))\n );\n else if (entry.kind === 'pi.assistant' && model) {\n const message = assistant(id, model);\n out.push(withoutLickTools(message));\n for (const [key, value] of tools([message])) calls.set(key, value);\n } else if (entry.kind === 'pi.tool-result' && model) settle(calls, model);\n else if (entry.kind === 'pi.compaction') out.push(system(id, entry, textOf(model?.content)));\n}\n\nconst slotStatus: Record<string, ToolStatus> = {\n pending: 'running',\n running: 'running',\n done: 'done',\n};\n\nfunction live(view: ConversationView, out: Message[], calls: Map<string, ToolCall>): void {\n const state = view.docs['pi.live'] as Live | undefined;\n for (const slot of state?.tools ?? []) {\n const call = calls.get(slot.callId);\n if (call && call.status === 'running') {\n call.status = slotStatus[slot.status] ?? 'running';\n call.output = slot.output ?? call.output;\n }\n }\n const partial = state?.generation?.message;\n if (partial) out.push(assistant('live', partial, 'streaming'));\n for (const compaction of state?.compactions ?? []) {\n out.push({\n id: `compaction-${compaction.taskId}`,\n role: 'system',\n kind: 'compaction',\n text: '',\n createdAt: 0,\n state: 'summarizing',\n trigger: compaction.reason as SystemMessage['trigger'],\n });\n }\n const retry = state?.generation?.retry;\n if (retry)\n out.push({\n id: 'retry',\n role: 'system',\n kind: 'notice',\n text: retry.error,\n createdAt: retry.at,\n });\n}\n\nexport function toMessages(\n view: ConversationView | undefined,\n deliveries: Readonly<Record<string, Delivered>> = {}\n): Message[] {\n const out: Message[] = [];\n if (!view) return out;\n const calls = new Map<string, ToolCall>();\n const notes = { decisions: lickDecisions(view.entries), origins: origins(view.entries) };\n let previous: EntryRecord | undefined;\n for (const entry of view.entries) {\n const steered = previous?.kind === 'pi.tool-result' ? 'steer' : undefined;\n entryMessage(entry, out, calls, deliveries[String(entry.id)] ?? steered, notes);\n previous = entry;\n }\n live(view, out, calls);\n return out;\n}\n\nexport function isBusy(view: ConversationView | undefined): boolean {\n return Boolean((view?.docs['pi.live'] as Live | undefined)?.run);\n}\n\nexport function queued(view: ConversationView | undefined): UserMessage[] {\n const items = ((view?.docs['pi.inbox'] as { items?: Json[] } | undefined)?.items ?? []) as {\n id: number;\n mode: string;\n content?: ModelMessage['content'];\n }[];\n return items\n .filter((item) => item.mode !== 'write' && !parseLick(textOf(item.content)))\n .map((item) => ({\n id: `q${item.id}`,\n role: 'user',\n text: textOf(item.content),\n createdAt: 0,\n queued: true,\n mode: item.mode === 'steer' ? 'steer' : 'queue',\n }));\n}\n"],
|
|
5
|
+
"mappings": "AAcA,SAAS,iBAAiB;AAC1B,SAAS,WAAW,YAA+B,qBAAqB;AACxE,SAAS,gBAAgB;AACzB,SAAS,iBAA4B;AAErC,SAAS,YAAY,oBAAoB;AAEzC,SAAS,qBAAqB;AA8CvB,SAAS,OAAO,SAA0C;AAC/D,MAAI,OAAO,YAAY,SAAU,QAAO;AACxC,UAAQ,WAAW,CAAC,GAAG,IAAI,CAAC,UAAW,MAAM,SAAS,SAAU,MAAM,QAAQ,KAAM,EAAG,EAAE,KAAK,EAAE;AAClG;AAEA,MAAM,QAAQ,CAAC,SACb,OAAO,MAAM,SAAS,WAAW,CAAC,KAAK,IAAI,IAAI,CAAC;AAElD,SAAS,MAAM,MAAgC;AAC7C,QAAM,UAAU,MAAM,WAAW,MAAM;AACvC,SAAO,OAAO,YAAY,WAAW,UAAU;AACjD;AAOA,MAAM,MAAM;AAEZ,SAAS,QAAQ,OAAoC;AACnD,SAAO,OAAO,UAAU,WAAW,WAAW,KAAK,MAAM;AAC3D;AAEA,SAAS,MAAM,MAAgC;AAC7C,QAAM,EAAE,QAAQ,MAAM,IAAI;AAC1B,MAAI,OAAO,WAAW,YAAY,OAAO,UAAU;AACjD,WAAO,SAAS,MAAM,SAAI,SAAS,QAAQ,CAAC;AAC9C,MAAI,OAAO,WAAW,SAAU,QAAO,aAAa,MAAM;AAC1D,SAAO,OAAO,UAAU,WAAW,SAAS,KAAK,WAAW;AAC9D;AAEA,SAAS,MAAM,MAA8B;AAC3C,QAAM,OAAO,MAAM,QAAQ,KAAK,KAAK,IAAK,KAAK,QAA0B,CAAC;AAC1E,MA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,cAAc,KAAK,OAAO,GAAG,SAAS,QAAQ,KAAK,OAAO,EAAE;AACvF,MAAI;AACJ,aAAW,SAAS,KAAK,SAAS;AAChC,UAAM,UAAU,UAAU,SAAS,mBAAmB,UAAU;AAChE,iBAAa,OAAO,KAAK,OAAO,WAAW,OAAO,MAAM,EAAE,CAAC,KAAK,SAAS,KAAK;AAC9E,eAAW;AAAA,EACb;AACA,OAAK,MAAM,KAAK,KAAK;AACrB,SAAO;AACT;AAEO,SAAS,OAAO,MAA6C;AAClE,SAAO,QAAS,MAAM,KAAK,SAAS,GAAwB,GAAG;AACjE;AAEO,SAAS,OAAO,MAAmD;AACxE,QAAM,QAAU,MAAM,KAAK,UAAU,GAAsC,SAAS,CAAC;AAKrF,SAAO,MACJ,OAAO,CAAC,SAAS,KAAK,SAAS,WAAW,CAAC,UAAU,OAAO,KAAK,OAAO,CAAC,CAAC,EAC1E,IAAI,CAAC,UAAU;AAAA,IACd,IAAI,IAAI,KAAK,EAAE;AAAA,IACf,MAAM;AAAA,IACN,MAAM,OAAO,KAAK,OAAO;AAAA,IACzB,WAAW;AAAA,IACX,QAAQ;AAAA,IACR,MAAM,KAAK,SAAS,UAAU,UAAU;AAAA,EAC1C,EAAE;AACN;",
|
|
6
6
|
"names": ["part"]
|
|
7
7
|
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { type Extension, type ToolRegistration } from '@earendil-works/pi-durable';
|
|
2
|
+
import { FACADE_PORT, ownKernelServer } from '../kernel/loopback.ts';
|
|
2
3
|
import { type ProtectedMatcher } from './origins.ts';
|
|
3
4
|
export declare const BROWSER_GUARD = "slicc-browser-guard";
|
|
4
5
|
export declare const REFUSAL = "SLICC's own pages can't be opened or driven from the browser tools.";
|
|
5
|
-
export
|
|
6
|
-
export declare function ownKernelServer(host: string): boolean;
|
|
6
|
+
export { FACADE_PORT, ownKernelServer };
|
|
7
7
|
export declare function foreignKernel(url: string): boolean;
|
|
8
8
|
export declare function forbidden(url: string, matcher: ProtectedMatcher): boolean;
|
|
9
9
|
export declare function candidates(raw: string): string[];
|
package/dist/types/index.d.ts
CHANGED
|
@@ -9,7 +9,7 @@ export { HOME, type KernelEnvOptions, kernelEnvironment, SliccKernelEnv } from '
|
|
|
9
9
|
export { adminOver, type KernelAdmin, type KernelUser, type KernelUsers, serveAdmin, type UserClient, type UserClients, type UserConnect, type UserSpec, userClients, } from './kernel/users.ts';
|
|
10
10
|
export { PortListener } from './listener.ts';
|
|
11
11
|
export { type AgentWorkerOptions, type AgentWorkerScope, type KernelAttach, runAgentWorker, } from './main.ts';
|
|
12
|
-
export { type Transport, type TransportResponse, transportFetch } from './net.ts';
|
|
12
|
+
export { type Loopback, type Transport, type TransportResponse, transportFetch, } from './net.ts';
|
|
13
13
|
export { AGENT_LOCK, type AgentOwner, type AgentWorker, type KernelSource, type OwnerOptions, startAgent, } from './owner.ts';
|
|
14
14
|
export { applyPatches, patchServerAccept } from './patches.ts';
|
|
15
15
|
export { SliccPrompt, sliccPrompt } from './prompt.ts';
|
package/dist/types/net.d.ts
CHANGED
|
@@ -17,4 +17,9 @@ export interface Transport {
|
|
|
17
17
|
signal?: AbortSignal;
|
|
18
18
|
}): Promise<TransportResponse>;
|
|
19
19
|
}
|
|
20
|
-
export
|
|
20
|
+
export type Loopback = (request: Request, options: {
|
|
21
|
+
port: number;
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
}) => Promise<Response>;
|
|
24
|
+
export declare function kernelPort(url: string): number | undefined;
|
|
25
|
+
export declare function transportFetch(transport: Transport, origin: string, native?: typeof fetch, loopback?: Loopback): typeof fetch;
|
|
@@ -3,14 +3,14 @@ import { type AgentChange, type Extension, type Harness, type Storage, type Tool
|
|
|
3
3
|
import type { Names, SecretName } from './names.ts';
|
|
4
4
|
import type { Scrub } from './scrub.ts';
|
|
5
5
|
import type { Vault } from './vault.ts';
|
|
6
|
+
import { listedLine, SECRETS_KIND } from './view.ts';
|
|
7
|
+
export { listedLine, SECRETS_KIND };
|
|
6
8
|
export declare const SECRETS = "slicc-secrets";
|
|
7
|
-
export declare const SECRETS_KIND = "slicc.secrets";
|
|
8
9
|
export declare const SECRETS_COMMAND = "/secrets";
|
|
9
10
|
export declare const SHELL_GRANTS: readonly ['fnox', 'exec', '--shell-grants', '--'];
|
|
10
11
|
export declare const MODEL_LINE = "Credentials are env vars (`$NAME`) holding placeholders; `secret list` shows them and where each works. The vault fills in the real value only in the listed header, for the listed domain, method and path, over HTTPS (curl, git, fetch). Adding a rule means editing `/etc/fnox/config.toml` with sudo, which the user approves. `fnox exec` gives real values only for secrets the user enabled for exec, and the secrets listed as 'in every bash' already hold real values in your commands. Everything is logged, and stored values are replaced by their placeholder in everything you see; edit around placeholders, since files show them too. Never ask the user to paste a credential into the chat.";
|
|
11
12
|
export declare function scrubResult(result: ToolExecutionResult, scrub: Pick<Scrub, 'texts'>): Promise<ToolExecutionResult | undefined>;
|
|
12
13
|
export declare function renderSecrets(names: readonly SecretName[]): string | undefined;
|
|
13
|
-
export declare function listedLine(names: readonly SecretName[]): string;
|
|
14
14
|
export declare function secretsEntry(names: readonly SecretName[]): {
|
|
15
15
|
kind: string;
|
|
16
16
|
data: {
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SecretName } from './names.ts';
|
|
2
|
+
import type { VaultState } from './vault.ts';
|
|
3
|
+
export declare const SECRETS_KIND = "slicc.secrets";
|
|
4
|
+
export interface VaultHold {
|
|
5
|
+
reason: 'waiting' | 'locked';
|
|
6
|
+
held: number;
|
|
7
|
+
}
|
|
8
|
+
export declare function vaultHold(state: VaultState | undefined): VaultHold | null;
|
|
9
|
+
export declare function listedLine(names: readonly SecretName[]): string;
|
|
@@ -1,13 +1,19 @@
|
|
|
1
1
|
import type { Agent, AgentEvents, AgentPort, FrozenCone, Message, Outgoing, SlashCommand, Thinking, UserMessage } from '@ai-ecoverse/slicc-spectrum/ui';
|
|
2
2
|
import type { AgentConnection } from '../client.ts';
|
|
3
|
+
import { type VaultHold } from '../secrets/view.ts';
|
|
3
4
|
import type { Command } from '../services.ts';
|
|
4
5
|
import { Emitter } from './emitter.ts';
|
|
5
6
|
export declare const CONE = "cone";
|
|
6
7
|
export declare function slashCommand({ kind, ...command }: Command): SlashCommand;
|
|
7
|
-
export
|
|
8
|
+
export type AgentHold = VaultHold;
|
|
9
|
+
export type AgentAdapterEvents = AgentEvents & {
|
|
10
|
+
hold: AgentHold | null;
|
|
11
|
+
};
|
|
12
|
+
export declare class AgentAdapter extends Emitter<AgentAdapterEvents> implements AgentPort {
|
|
8
13
|
#private;
|
|
9
14
|
constructor(connection: AgentConnection);
|
|
10
15
|
ready(): Promise<void>;
|
|
16
|
+
hold(): AgentHold | null;
|
|
11
17
|
list(): readonly Agent[];
|
|
12
18
|
active(): string;
|
|
13
19
|
select(id: string): void;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-ecoverse/slicc-agent",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.45.1",
|
|
4
4
|
"description": "SLICC's agent core on pi durable: an agent worker, session storage, remoting and pi extensions",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -63,7 +63,7 @@
|
|
|
63
63
|
"devDependencies": {
|
|
64
64
|
"@ai-ecoverse/slicc-kernel": "1.47.1",
|
|
65
65
|
"@ai-ecoverse/slicc-shared-web": "1.13.1",
|
|
66
|
-
"@ai-ecoverse/slicc-spectrum": "1.
|
|
66
|
+
"@ai-ecoverse/slicc-spectrum": "1.62.0",
|
|
67
67
|
"@ai-ecoverse/wasm-bash": "5.3.0-17",
|
|
68
68
|
"@ai-ecoverse/wasm-coreutils": "9.12.0-5",
|
|
69
69
|
"@ai-ecoverse/wasm-git": "2.55.0-15",
|