@ai-ecoverse/slicc-agent 7.34.1 → 7.34.3
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 -4
- package/dist/secrets/extension.js +8 -5
- package/dist/secrets/extension.js.map +2 -2
- package/dist/spectrum/held.js +14 -7
- package/dist/spectrum/held.js.map +2 -2
- package/dist/spectrum/mcp-login.js +8 -3
- package/dist/spectrum/mcp-login.js.map +2 -2
- package/dist/spectrum/settings-port.js +17 -10
- package/dist/spectrum/settings-port.js.map +2 -2
- package/dist/types/secrets/extension.d.ts +3 -2
- package/dist/types/spectrum/held.d.ts +6 -1
- package/dist/types/spectrum/mcp-login.d.ts +2 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -164,9 +164,9 @@ The first provider is AWS Bedrock with a Bedrock API key as the bearer token; th
|
|
|
164
164
|
|
|
165
165
|
**Budgets.** The settings state's `budgets` lists each subscription's weekly window as `{ provider, percent, window: 'weekly', resets }`: Adobe's from `/v1/usage`, then SuperGrok's, and `budget` is the first of them (Adobe's when both are there). SuperGrok's (`xaiUsage` in `src/supergrok.ts`, as in SLICC 6) is `GET https://cli-chat-proxy.grok.com/v1/billing?format=credits` with the xAI record's placeholder as the bearer. It's read only for an xAI sign-in (a record with an `expiresAt`, not `expired`; a pasted key has none) and only while the cors-free transport is up (`reach.free()`), since that host doesn't answer browsers. It's read at most once per five-minute poll for the same record, with an 8 s timeout. The route is undocumented, so the answer is read defensively: a body over 64 KiB, malformed JSON, or anything but a `USAGE_PERIOD_TYPE_WEEKLY` `currentPeriod` with a finite `creditUsagePercent` and a valid `end` gives no budget, and the percent is clamped to 0–100 and rounded to one decimal. The vault fills the token only where xAI's endpoints allow: until its built-in table has the billing route, it refuses the request before anything is sent, and xAI shows no budget. The `tray` and `monitor` adapters show the budget of the selected model's provider (the active agent's model), or the first budget when that provider has none, and pass its `provider` (spectrum labels `adobe` “Adobe” and `xai` “SuperGrok”). The Monitor's budget vital carries `provider` and `window` too, which spectrum's heading is built from, so its own label stays “Budget (weekly)”; its alert names the provider: “SuperGrok budget 96% used”. `test/integration/budget.test.mjs` checks the switch, the refused endpoint and an oversized answer.
|
|
166
166
|
|
|
167
|
-
**Held sign-in windows** (`src/spectrum/held.ts`, slicc-bios#772). A sign-in popup opens
|
|
167
|
+
**Held sign-in windows** (`src/spectrum/held.ts`, slicc-bios#772, and the baseline of slicc-bios#1607, bios 1.74.14). A sign-in popup opens on `about:blank#slicc-sign-in-<nonce>` (a random UUID), the way seven's own Adobe sign-in does. In this order, on the `slicc-held` BroadcastChannel: before `window.open`, the page asks seven's owner for a baseline with `{ type: 'base', marker: <nonce> }`, and the owner answers `{ type: 'based', marker }` once it has listed the targets of every linked browser host. Then the page opens the popup and asks to hold it with `{ type: 'hold', marker, based: true, expect: 1 }`, so the owner holds only a protected blank that is new since the baseline, never a leftover one: on a linked browser slicc-cli shows seven's popup as plain `about:blank`, and without a baseline the owner could hold a leftover blank and leave the real popup to a client with the Browser grant. The owner holds the target, so no CDP client can list or drive it, and answers `{ type, marker }`: `held` once it's held on every connected browser host, `none` when no host is connected (nothing can reach the popup), and `unheld` when a host is connected but the target wasn't found. When 6 s pass without `based` (a bios before 1.74.14, or no owner), the popup still opens only through the hold ask, without `based`, as before the baseline; it never opens unprotected. Cancel during the baseline opens nothing and closes the channel. The popup goes to the IdP or device page only on `held` or `none`. On `unheld` or after 6 s without an answer to the hold ask, the popup closes without navigating and the sign-in fails with “SLICC couldn't protect the sign-in window. Try again.”; on Cancel it never navigates either. The worst case is 12 s from the click to that refusal: 6 s for the baseline, then 6 s for the hold. A baseline that takes that long can outlast the click's activation, so the browser may block the popup; a device sign-in then shows its code and link, and an MCP sign-in asks to allow pop-ups.
|
|
168
168
|
|
|
169
|
-
**Subscription sign-ins.** xAI, Kimi For Coding and ChatGPT (`openai-codex`, shown as ChatGPT) sign in with pi-ai's own device-code flows (`DEVICE_SIGN_INS` in `src/sign-ins.ts`); xAI and Kimi keep API-key entry too, so their accounts are `auth: 'oauth'` with `secret: 'api-key'` (spectrum's “Use an API key instead”) and a `keyUrl`. Spectrum's Sign in calls `connect(id, undefined, undefined, { method: 'sign-in' })` in the click, and a pasted key `put`s first and calls `connect(id, undefined, fields, { method: 'key' })` (spectrum's `ConnectOptions`); without the fourth argument an `oauth` account signs in. The adapter opens a held popup (`slicc-sign-in`, see **Held sign-in windows**) before anything else
|
|
169
|
+
**Subscription sign-ins.** xAI, Kimi For Coding and ChatGPT (`openai-codex`, shown as ChatGPT) sign in with pi-ai's own device-code flows (`DEVICE_SIGN_INS` in `src/sign-ins.ts`); xAI and Kimi keep API-key entry too, so their accounts are `auth: 'oauth'` with `secret: 'api-key'` (spectrum's “Use an API key instead”) and a `keyUrl`. Spectrum's Sign in calls `connect(id, undefined, undefined, { method: 'sign-in' })` in the click, and a pasted key `put`s first and calls `connect(id, undefined, fields, { method: 'key' })` (spectrum's `ConnectOptions`); without the fourth argument an `oauth` account signs in. The adapter asks the owner for a baseline and opens a held popup (`slicc-sign-in`, see **Held sign-in windows**) before anything else, then asks the worker's `signIn(id)`, which adds the account, runs the provider's `auth.oauth.login` and answers `{ url, code }` once the provider gives its device code (an `https:` page only). While it waits the account is `signing-in` with `signIn: { url, code? }`, kept in the page and never in the replicated settings state; the prompt appears and the popup goes to `url` only once the popup is held, and spectrum shows `code` with Copy and a link to `url` when the browser blocked the popup. The adapter's `connect` call then waits in the worker for the token (a sign-in no `connect` claims within a minute is dropped) and hands the vault `grant { provider, name, response, settings? }`, `name` being the account's `vaultName` and `response` the token response built from pi-ai's credential, as bytes zeroed after the call; the token is never stored, logged, licked or put in the state, and pi-ai's own error texts, which can quote a token response, never leave the worker. A refusal reads “The sign-in was refused.”, a timeout, network failure or malformed answer “The sign-in didn't finish. Try again.”, the vault's `EEXIST` “This name holds another provider's key.”, and Cancel aborts at once with an `AbortError`. Signing in again is a rotation that keeps the placeholder, and over a pasted key the vault keeps that key restorable. The vault refreshes the token through `egress`; after `invalid_grant` its record is `expired` and the account offers Sign in again. ChatGPT's API reads the account id from the access token's JWT, which a placeholder isn't: the grant carries `settings: { CHATGPT_ACCOUNT_ID }` (every sign-in), the credential's env gets it from the record, and the worker hands pi-ai a carrier key `slicc.<claims>.<placeholder>` that the worker's fetch turns back into `Bearer <placeholder>` before the vault fills it, so pi-ai sends `chatgpt-account-id` itself; its turns use SSE, not WebSockets. Kimi's auth host answers browsers but its API needs the CORS-free transport; xAI's API answers browsers but its device endpoints don't, so an xAI sign-in needs the CORS-free transport while its key doesn't; ChatGPT's auth host answers browsers and its API doesn't. The flows load lazily from pi-ai: xAI's and Kimi's modules import nothing from Node, and openai-codex's imports `node:http` for its browser callback, which the device flow never runs, so slicc-bios's `node:*` stubs let it load.
|
|
170
170
|
|
|
171
171
|
**Adding providers.** The settings state's `providers` lists every provider seven can add (`ProviderOption`: `id`, `name`, `description`, `auth`, `keyUrl`, `needs`, `fields` and `vaultName`, sorted by name), and the spectrum adapter serves it as `providers()` with a `providers` event when it changes. `accounts` then lists only the added ones: Bedrock and Adobe start as added, `connect` adds a provider, and one with a vault record or stored fields counts as added too. The added list is `providers` in `/.slicc/accounts.json`. `vaultName` is the record name spectrum `put`s the key under: pi-ai's env name, or `<ID>_API_KEY` for providers that share one (Moonshot AI, OpenCode and the Qwen token plans), since a `put` under another provider's name would rebind that record; Bedrock's is `AWS_BEARER_TOKEN_BEDROCK` and Adobe's `ADOBE_IMS_TOKEN`. The agent finds a provider's record by its `provider`, never by name. Each provider has at most one secret, its key; `fields` are the non-secret inputs (`name`, `label`, `required`, `placeholder`, `help`, `customBase`, `vaultSetting`, `options` and `value`). `vaultSetting` names the vault record setting a field fills (slicc-vault's tenant-bound wildcards, V3), so the vault can bind a provider's wildcard endpoints to the user's own tenant: Cloudflare's `account` is `CLOUDFLARE_ACCOUNT_ID` and `gateway` `CLOUDFLARE_GATEWAY_ID`, and Azure's `endpoint` is `AZURE_OPENAI_RESOURCE_NAME` (spectrum applies it only to a bare resource name; an `https:` value stays a `customBase`). On an added account each field's `value` is its stored value, trimmed, so Settings can show it and knows a custom base URL to unregister after a reload; a field with a default carries that instead (Bedrock's `us-west-2`). Bedrock's `region` has `options`, the 21 regions where AWS supports Bedrock API keys (the bearer token seven uses; AWS's “Supported Regions … for Amazon Bedrock API keys”), labelled with AWS's names (`Europe (Frankfurt), eu-central-1`); a stored region outside the list comes first, under its own name, so a select never shows a region the account doesn't use. `disconnect(id)` keeps the row and its fields, so connecting again needs only the key, and `remove(id)` drops the row and its fields; for both, spectrum removes the vault record first. On an MCP row, `remove` disconnects it. `connect` with a secret is refused for every model account ("API keys are kept in seven's vault: update seven"); the only secret it still takes is an MCP sign-in's callback answer.
|
|
172
172
|
|
|
@@ -897,8 +897,9 @@ The agent worker never holds a secret's value. Values live in the vault (`vault.
|
|
|
897
897
|
- **The listing**, read in the home env at start and whenever `version` changes (pi-fnox's `fnox export`; nothing goes into the worker's environment), joins three commands by name, none of which prints a value:
|
|
898
898
|
- `fnox env --json --describe` gives the fnox config's keys (`kind: "secret"`), which are the `$NAME`s bash sees. It runs only with `--describe`: without it fnox prints values, so every command goes through one guard that refuses `fnox env` without `--describe`. `--for exec|shell` isn't passed, since fnox 1.39 ignores it when describing (both print the same keys).
|
|
899
899
|
- the vault's own `list` op on `/dev/sealed` (`exec 3<>/dev/sealed`, write `{"v":1,"op":"list"}`, read the reply) gives each sealed secret's placeholder, its `[exec]` mode from `/etc/slicc/secrets-policy.toml` and the rules the vault accepted. fnox's describe output has no placeholders, and the agent port's `records` has no `secret` records.
|
|
900
|
-
- `fnox proxy rules --json` gives the config's `[[proxy.rules]]`, shown
|
|
900
|
+
- `fnox proxy rules --json` gives the config's `[[proxy.rules]]`, shown for a secret the vault uses no rule of, each marked `in the fnox config but not in effect`. A config without `[proxy]` (exit 1, "No [proxy] configuration found") has no rules.
|
|
901
901
|
- **Shown as:** `- NAME = <placeholder>: <rules>; in every bash` for a sealed secret; a fnox key the vault doesn't hold reads `- NAME = $NAME: not sealed` (a plain fnox secret), and a sealed secret the config lacks says `not in the fnox config`.
|
|
902
|
+
- **No accept step.** The owner accepts a rule by approving the `sudo` that writes `/etc/fnox/config.toml`; nothing else in seven, Settings included, accepts or proposes rules. bios hands the vault the file whenever it changes, and the vault uses its rules at once while the file is trusted (root-owned, not writable by group or others, under root-owned directories, kernel users `enforce`) and the secret's `[secrets]` entry holds the secret's own placeholder, `NAME = { provider = "seven", value = "<placeholder>" }` (`sealed placeholder NAME` prints it). An entry without `value` is ignored with every rule naming it, though `fnox check` passes and `fnox proxy rules` lists the rules, and requests are then refused `no-rule` (bios's sentence, which asks for a rule). The vault's warning (`GITHUB_PAT: its value isn't a vault placeholder`) goes only to its `status.policy`, which Settings › Secrets doesn't show yet, so the section says it instead: a sealed secret whose rules are all only in the config gets `the vault uses none of these rules yet, and there is nothing for the user to accept: …` with the entry it needs, and points at `sealed list --json`, which shows the rules the vault uses now, since the listing is read only at start and when the vault's values change. `fnox set NAME --ask` writes its entry to `fnox.toml` in the current directory, which the vault never reads, so the section says to copy the entry into `/etc/fnox/config.toml` with sudo (#957).
|
|
902
903
|
- **Failures are loud.** When fnox is missing (exit 127), a command exits non-zero, `/dev/sealed` fails or a reply doesn't parse, the `secrets` section is "Secrets are unavailable: <reason>.", `/secrets` says the same, and the worker logs one `slicc-secrets: secrets are unavailable: <reason>` line until the reason changes. The reason is a fixed sentence: fnox's error `kind` (`config` reads "the fnox config has an error; check /etc/fnox/config.toml") or the vault's error `code`, never their message, since fnox quotes the offending config line and a plain secret's value can sit on it, which the vault's scrub doesn't know. The message goes only to that log line, redacted by the vault and cut to 200 characters. stderr is never read. Only a config with no keys and a vault with no sealed secrets shows "No secrets are configured".
|
|
903
904
|
- **Shell grants stay off while fnox would hand out unsealed values.** `fnox exec` also sets every config secret it may inject (`injectable.exec`, which is `env = true` and `env = "exec"`), and a plain or age secret's value isn't one the vault scrubs. So while any such key isn't in the vault's list, the wrapper isn't used, the section and `/secrets` say "Shell grants are off: fnox exec would also give every command the unsealed fnox secrets <names>; seal them or set env = false for them.", and one line is logged.
|
|
904
905
|
- **Prefer argv over shell.** In `/etc/slicc/secrets-policy.toml`, a secret used by one program should be `[exec] NAME = { argv = [["/absolute/program", …]] }` (or `true` / `any` when every non-shell program may see it). `{ shell = true }` is only for secrets every conversation command needs: while any listed secret has that grant, every bash runs as `fnox exec --shell-grants -- <argv>` and the vault reveals all shell-granted values to it. The agent never chooses the set; narrow policy instead of asking the model to pick env vars.
|
|
@@ -908,7 +909,7 @@ The agent worker never holds a secret's value. Values live in the vault (`vault.
|
|
|
908
909
|
- **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, or "Secrets unavailable" with the reason.
|
|
909
910
|
- **The 3.x store is wiped.** 3.x kept model and MCP keys in the IndexedDB database `slicc-agent-credentials`; 4.x doesn't migrate them. At start, before any model call, the worker reads only that database's record keys (never decrypting), deletes it, and keeps the accounts it found (`adobe` as Adobe, `amazon-bedrock` as Bedrock, `mcp:<server>|…` as the server, anything else by its providerId) in the session document `slicc.keys-moved`. A missing database, or no `indexedDB`, does nothing. The worker waits up to 3 s for the delete and claims the keys moved only once it succeeds. A delete blocked by an open 3.x tab shows no notice yet: if it succeeds later in the session (the tab closes) its accounts are added then, and otherwise the next start tries again. A delete that fails reports nothing. Once the vault's records are read, the accounts still without a record are the settings state's `moved`, and the spectrum adapter's `notices` port shows one notice, with model accounts first and MCP servers grouped after them: "Your keys moved to seven's vault. Add them again in Settings › Accounts: Adobe, Bedrock; MCP servers: github, jira." (or "…, and the MCP server github" for one). Dismissing it calls `AgentSettings.dismissMoved`, which marks the document, so it stays dismissed across reloads. An account without a record reads not connected. A model call that finds no credential ("Provider is not configured", "No API key") leads with "Adobe isn't connected." or "Bedrock isn't connected.", with "Connect it in Settings › Accounts." underneath instead of the raw error, and opens settings, and a send whose run finds no model because its account isn't connected (Adobe lists models only once signed in) shows the same error. "Your Adobe session has expired." is kept for a 401 from a token that exists. The settings state's `labels` names every model of a provider without a record from the agent's catalogue ("Claude Haiku 4.5 (US) on Bedrock"), and the adapter puts that name in the header of a reply whose model isn't in the picker, instead of the raw id.
|
|
910
911
|
- **For bios:** the agent's `notices` (keys moved) would replace bios's own port in `{ ...bios, ...createAgentModel(connection) }`, so pass that port in instead, as `createAgentModel(connection, { notices: biosPort })`. The returned port lists bios's notices and then the agent's, sends `act` and `dismiss` to whichever port listed the id (never dismissing one with `dismissible: false`), and passes on both ports' `notices` events. Without the option, it lists only the agent's.
|
|
911
|
-
- **Tests.** The worker never compiles values: `src/` takes only `import type { Hit }` from [`@ai-ecoverse/slicc-scrub`](https://www.npmjs.com/package/@ai-ecoverse/slicc-scrub), the vault's scrubber, and the package is a devDependency. [`@ai-ecoverse/slicc-vault`](https://www.npmjs.com/package/@ai-ecoverse/slicc-vault) is a devDependency for `npm run lint:vault-pi` only (the agent does not import it). The fake vault the tests use scrubs with that package, and its `vectors.json` (every form, line-wrapped base64 and hex included) runs through each scrub point and each cut. A suite-wide check asserts that no captured model request, entry, slot or memory file holds any form of a seeded value. `test/integration/secrets-fnox.test.mjs` runs the listing on the page kernel with `@ai-ecoverse/wasi-fnox` (a devDependency) and the fake vault's `/dev/sealed` side (`fakeSealed`: `list`, `placeholder`, `materialize`, `materializeConsume` and `ask`): a sealed secret in the section and `/secrets`, a shell grant reaching a command through `fnox exec --shell-grants`, shell grants kept off by an unsealed `env = true` secret, fnox missing, fnox exiting non-zero on a config error that quotes a plain value (which never reaches the prompt, `/secrets` or the transcript), an empty config, and the kernel's `sealed ask` (slicc-kernel 1.175 on): a revealed value reaches the command while the transcript and every model request hold only its placeholder, and a cancelled ask exits 1;
|
|
912
|
+
- **Tests.** The worker never compiles values: `src/` takes only `import type { Hit }` from [`@ai-ecoverse/slicc-scrub`](https://www.npmjs.com/package/@ai-ecoverse/slicc-scrub), the vault's scrubber, and the package is a devDependency. [`@ai-ecoverse/slicc-vault`](https://www.npmjs.com/package/@ai-ecoverse/slicc-vault) is a devDependency for `npm run lint:vault-pi` only (the agent does not import it). The fake vault the tests use scrubs with that package, and its `vectors.json` (every form, line-wrapped base64 and hex included) runs through each scrub point and each cut. A suite-wide check asserts that no captured model request, entry, slot or memory file holds any form of a seeded value. `test/integration/secrets-fnox.test.mjs` runs the listing on the page kernel with `@ai-ecoverse/wasi-fnox` (a devDependency) and the fake vault's `/dev/sealed` side (`fakeSealed`: `list`, `placeholder`, `materialize`, `materializeConsume` and `ask`): a sealed secret in the section and `/secrets`, a shell grant reaching a command through `fnox exec --shell-grants`, shell grants kept off by an unsealed `env = true` secret, fnox missing, fnox exiting non-zero on a config error that quotes a plain value (which never reaches the prompt, `/secrets` or the transcript), an empty config, and the kernel's `sealed ask` (slicc-kernel 1.175 on): a revealed value reaches the command while the transcript and every model request hold only its placeholder, and a cancelled ask exits 1; `fnox set NAME --ask` (wasi-fnox 1.45.0-2 on), which seals what the user typed and prints only its placeholder; and a sealed secret whose `[secrets]` entry has no `value`, whose rules the section shows as not in effect with the entry the vault needs, while `fnox set --ask` writes `./fnox.toml` and leaves `/etc/fnox/config.toml` alone.
|
|
912
913
|
|
|
913
914
|
## The kernel
|
|
914
915
|
|
|
@@ -9,8 +9,8 @@ import { exposedLine, listedLine, SECRETS_KIND, unavailableLine } from "./view.j
|
|
|
9
9
|
const SECRETS = "slicc-secrets";
|
|
10
10
|
const SECRETS_COMMAND = "/secrets";
|
|
11
11
|
const SHELL_GRANTS = ["fnox", "exec", "--shell-grants", "--"];
|
|
12
|
-
const MODEL_LINE =
|
|
13
|
-
const ASK_LINE = "When a secret you need is missing, ask the user for it: `fnox set NAME --ask`
|
|
12
|
+
const MODEL_LINE = 'Credentials are env vars (`$NAME`) holding placeholders, listed below with where each works (`fnox list` shows the fnox config). 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: the user approving that sudo is the only acceptance there is, and the vault uses the rules in it as soon as it is written (`sealed list --json` shows the rules it uses now; the list below is read at start and can lag behind). It uses the rules of a secret only while the file is root-owned and not writable by others, and its `[secrets]` entry holds the placeholder of that secret: `NAME = { provider = "seven", value = "<placeholder>" }` (`sealed placeholder NAME` prints it); without the `value` the vault ignores the entry and every rule naming it, though `fnox check` passes. `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. Prefer an argv grant in `/etc/slicc/secrets-policy.toml` (`NAME = { argv = [["/absolute/program"]] }`) for a secret one program needs; `{ shell = true }` hands it to every bash. 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.';
|
|
13
|
+
const ASK_LINE = "When a secret you need is missing, ask the user for it: `fnox set NAME --ask` seals it and writes its entry to `fnox.toml` in the current directory, which the vault doesn't read (copy the entry into `/etc/fnox/config.toml` with sudo before adding its rules there), and `sealed ask NAME` keeps it in the vault only (`--prompt TEXT` says why you need it). The user types the value in a dialog, and the command prints only its placeholder. `fnox set` always asks for a new value and replaces an existing one, so use it only for a missing secret. Add `--reveal` to `sealed ask` only when a tool needs the plaintext itself, not where the vault fills it in a header, and pipe it straight into that tool (`sealed ask NAME --reveal | tool --password-stdin`): the user must allow every reveal, and you still see only the placeholder. A non-zero exit means the user declined or the request ended; don't ask again unless the user wants you to.";
|
|
14
14
|
function leaves(value, out, set) {
|
|
15
15
|
if (typeof value === "string") {
|
|
16
16
|
out.push({ get: () => value, set });
|
|
@@ -73,6 +73,7 @@ async function scrubResult(result, scrub) {
|
|
|
73
73
|
...output === void 0 ? {} : { structuredOutput: output }
|
|
74
74
|
};
|
|
75
75
|
}
|
|
76
|
+
const unusedLine = (name, placeholder) => `the vault uses none of these rules yet, and there is nothing for the user to accept: it takes rules only from a root-owned \`/etc/fnox/config.toml\` whose \`[secrets]\` entry is \`${name} = { provider = "seven", value = "${placeholder}" }\`; fix the file with sudo, then \`sealed list --json\` shows the rules the vault uses`;
|
|
76
77
|
function where(name, granted) {
|
|
77
78
|
const rules = name.rules.map(
|
|
78
79
|
(rule) => [
|
|
@@ -80,13 +81,14 @@ function where(name, granted) {
|
|
|
80
81
|
rule.header ? `header ${rule.header}` : "",
|
|
81
82
|
rule.methods?.length ? rule.methods.join(" ") : "",
|
|
82
83
|
rule.paths?.length ? rule.paths.join(" ") : "",
|
|
83
|
-
rule.proposed ? "
|
|
84
|
+
rule.proposed ? "in the fnox config but not in effect" : ""
|
|
84
85
|
].filter(Boolean).join(", ")
|
|
85
86
|
);
|
|
87
|
+
const idle = name.placeholder !== null && name.rules.some((rule) => rule.proposed) ? [unusedLine(name.name, name.placeholder)] : [];
|
|
86
88
|
const shell = name.exec === "shell" && granted ? ["in every bash"] : [];
|
|
87
89
|
const sealed = name.placeholder === null ? ["not sealed"] : [];
|
|
88
90
|
const config = name.fnox ? [] : ["not in the fnox config"];
|
|
89
|
-
const parts = [...rules, ...shell, ...sealed, ...config];
|
|
91
|
+
const parts = [...rules, ...idle, ...shell, ...sealed, ...config];
|
|
90
92
|
return parts.length ? `: ${parts.join("; ")}` : "";
|
|
91
93
|
}
|
|
92
94
|
const NO_SECRETS = "No secrets are configured: the fnox config has no keys and the vault no sealed secrets.";
|
|
@@ -148,6 +150,7 @@ export {
|
|
|
148
150
|
secretsEntry,
|
|
149
151
|
secretsExtension,
|
|
150
152
|
shellGrants,
|
|
151
|
-
unavailableLine
|
|
153
|
+
unavailableLine,
|
|
154
|
+
unusedLine
|
|
152
155
|
};
|
|
153
156
|
//# sourceMappingURL=extension.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/secrets/extension.ts"],
|
|
4
|
-
"sourcesContent": ["import type { JsonValue } from '@earendil-works/chord';\nimport {\n defineExtension,\n type Extension,\n GenerationTask,\n hook,\n section,\n type ToolExecutionResult,\n ToolTask,\n} from '@earendil-works/pi-durable';\nimport type { Names, SecretListing, SecretName } from './names.ts';\nimport type { Scrub } from './scrub.ts';\nimport type { Vault } from './vault.ts';\nimport { exposedLine, listedLine, SECRETS_KIND, unavailableLine } from './view.ts';\n\nexport { exposedLine, listedLine, SECRETS_KIND, unavailableLine };\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, listed below with where each works (`fnox list` shows the fnox config). 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,
|
|
5
|
-
"mappings": "AACA;AAAA,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AAIP,SAAS,aAAa,YAAY,cAAc,uBAAuB;AAIhE,MAAM,UAAU;AAChB,MAAM,kBAAkB;AACxB,MAAM,eAAe,CAAC,QAAQ,QAAQ,kBAAkB,IAAI;AAE5D,MAAM,aACX;AAEK,MAAM,WACX;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,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,EAAE,CAAC,EAAG,QAAO;AAC3D,QAAM,QAAQ,CAAC,MAAM,OAAO;AAC1B,SAAK,IAAI,MAAM,EAAE,CAAW;AAAA,EAC9B,CAAC;AACD,QAAM,OAAO,OAAO;AACpB,MAAI,KAAM,MAAK,OAAO,GAAG,KAAK,QAAQ,GAAG,OAAO;AAChD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAI,OAAO,EAAE,QAAQ,KAAK,IAAI,CAAC;AAAA,IAC/B,GAAI,OAAO,cAAc,EAAE,YAAY,IAAI,CAAC;AAAA,IAC5C,GAAI,aAAa,SAAY,CAAC,IAAI,EAAE,SAAS,SAAS;AAAA,IACtD,GAAI,WAAW,SAAY,CAAC,IAAI,EAAE,kBAAkB,OAAO;AAAA,EAC7D;AACF;
|
|
4
|
+
"sourcesContent": ["import type { JsonValue } from '@earendil-works/chord';\nimport {\n defineExtension,\n type Extension,\n GenerationTask,\n hook,\n section,\n type ToolExecutionResult,\n ToolTask,\n} from '@earendil-works/pi-durable';\nimport type { Names, SecretListing, SecretName } from './names.ts';\nimport type { Scrub } from './scrub.ts';\nimport type { Vault } from './vault.ts';\nimport { exposedLine, listedLine, SECRETS_KIND, unavailableLine } from './view.ts';\n\nexport { exposedLine, listedLine, SECRETS_KIND, unavailableLine };\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, listed below with where each works (`fnox list` shows the fnox config). 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: the user approving that sudo is the only acceptance there is, and the vault uses the rules in it as soon as it is written (`sealed list --json` shows the rules it uses now; the list below is read at start and can lag behind). It uses the rules of a secret only while the file is root-owned and not writable by others, and its `[secrets]` entry holds the placeholder of that secret: `NAME = { provider = \"seven\", value = \"<placeholder>\" }` (`sealed placeholder NAME` prints it); without the `value` the vault ignores the entry and every rule naming it, though `fnox check` passes. `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. Prefer an argv grant in `/etc/slicc/secrets-policy.toml` (`NAME = { argv = [[\"/absolute/program\"]] }`) for a secret one program needs; `{ shell = true }` hands it to every bash. 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\nexport const ASK_LINE =\n \"When a secret you need is missing, ask the user for it: `fnox set NAME --ask` seals it and writes its entry to `fnox.toml` in the current directory, which the vault doesn't read (copy the entry into `/etc/fnox/config.toml` with sudo before adding its rules there), and `sealed ask NAME` keeps it in the vault only (`--prompt TEXT` says why you need it). The user types the value in a dialog, and the command prints only its placeholder. `fnox set` always asks for a new value and replaces an existing one, so use it only for a missing secret. Add `--reveal` to `sealed ask` only when a tool needs the plaintext itself, not where the vault fills it in a header, and pipe it straight into that tool (`sealed ask NAME --reveal | tool --password-stdin`): the user must allow every reveal, and you still see only the placeholder. A non-zero exit means the user declined or the request ended; don't ask again unless the user wants you to.\";\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.output ?? [])];\n const diagnostics = [...(result.diagnostics ?? [])];\n const copy = (value: JsonValue | undefined) =>\n value === undefined ? undefined : (structuredClone(value) as JsonValue);\n const details = copy(result.details);\n const structured = copy(result.structuredOutput);\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 let output = structured;\n if (structured !== undefined)\n leaves(structured, found, (next) => {\n output = 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.output as ToolExecutionResult['output'] & unknown[];\n if (kept) kept.splice(0, kept.length, ...content);\n return {\n ...result,\n ...(kept ? { output: kept } : {}),\n ...(result.diagnostics ? { diagnostics } : {}),\n ...(replaced === undefined ? {} : { details: replaced }),\n ...(output === undefined ? {} : { structuredOutput: output }),\n };\n}\n\nexport const unusedLine = (name: string, placeholder: string) =>\n `the vault uses none of these rules yet, and there is nothing for the user to accept: it takes rules only from a root-owned \\`/etc/fnox/config.toml\\` whose \\`[secrets]\\` entry is \\`${name} = { provider = \"seven\", value = \"${placeholder}\" }\\`; fix the file with sudo, then \\`sealed list --json\\` shows the rules the vault uses`;\n\nfunction where(name: SecretName, granted: boolean): 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 rule.proposed ? 'in the fnox config but not in effect' : '',\n ]\n .filter(Boolean)\n .join(', ')\n );\n const idle =\n name.placeholder !== null && name.rules.some((rule) => rule.proposed)\n ? [unusedLine(name.name, name.placeholder)]\n : [];\n const shell = name.exec === 'shell' && granted ? ['in every bash'] : [];\n const sealed = name.placeholder === null ? ['not sealed'] : [];\n const config = name.fnox ? [] : ['not in the fnox config'];\n const parts = [...rules, ...idle, ...shell, ...sealed, ...config];\n return parts.length ? `: ${parts.join('; ')}` : '';\n}\n\nexport const NO_SECRETS =\n 'No secrets are configured: the fnox config has no keys and the vault no sealed secrets.';\n\nexport function renderSecrets(listing: SecretListing): string {\n if (listing.error !== null) return unavailableLine(listing.error);\n if (!listing.names.length) return [NO_SECRETS, '', ASK_LINE].join('\\n');\n const granted = !listing.exposed.length;\n const lines = listing.names.map(\n (name) => `- ${name.name} = ${name.placeholder ?? `$${name.name}`}${where(name, granted)}`\n );\n const off = granted ? [] : ['', exposedLine(listing.exposed)];\n return [MODEL_LINE, ASK_LINE, '', ...lines, ...off].join('\\n');\n}\n\nexport function secretsEntry(listing: SecretListing) {\n return {\n kind: SECRETS_KIND,\n data: {\n names: structuredClone(listing.names) as unknown as JsonValue,\n error: listing.error,\n exposed: [...listing.exposed],\n },\n model: [{ role: 'user' as const, content: listedLine(listing), timestamp: Date.now() }],\n };\n}\n\nexport function granting(listing: SecretListing): boolean {\n return (\n listing.error === null &&\n !listing.exposed.length &&\n listing.names.some((name) => name.exec === 'shell')\n );\n}\n\nexport function shellGrants(names: Pick<Names, 'state'>) {\n return (argv: readonly string[]): readonly string[] =>\n granting(names.state.value) ? [...SHELL_GRANTS, ...argv] : argv;\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,EACE;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AAIP,SAAS,aAAa,YAAY,cAAc,uBAAuB;AAIhE,MAAM,UAAU;AAChB,MAAM,kBAAkB;AACxB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BAAgB,QAAQ,KAAK;AAAA,MACpC,OAAO,QAAQ;AAAA,MACf,SAAS,CAAC,GAAG,QAAQ,OAAO;AAAA,IAC9B;AAAA,IACA,OAAO,CAAC,EAAE,MAAM,QAAiB,SAAS,WAAW,OAAO,GAAG,WAAW,KAAK,IAAI,EAAE,CAAC;AAAA,EACxF;AACF;AAEO,SAAS,SAAS,SAAiC;AACxD,SACE,QAAQ,UAAU,QAClB,CAAC,QAAQ,QAAQ,UACjB,QAAQ,MAAM,KAAK,CAAC,SAAS,KAAK,SAAS,OAAO;AAEtD;AAEO,SAAS,YAAY,OAA6B;AACvD,SAAO,CAAC,SACN,SAAS,MAAM,MAAM,KAAK,IAAI,CAAC,GAAG,cAAc,GAAG,IAAI,IAAI;AAC/D;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/spectrum/held.js
CHANGED
|
@@ -6,28 +6,34 @@ const listen = (name) => new BroadcastChannel(name);
|
|
|
6
6
|
function markerUrl(marker) {
|
|
7
7
|
return `about:blank#${HELD_MARK}${marker}`;
|
|
8
8
|
}
|
|
9
|
-
function
|
|
9
|
+
function ask(message, answers, signal, options) {
|
|
10
10
|
return new Promise((resolve) => {
|
|
11
11
|
const channel = (options.listen ?? listen)(HELD_CHANNEL);
|
|
12
|
-
const finish = (
|
|
12
|
+
const finish = (answer) => {
|
|
13
13
|
clearTimeout(timer);
|
|
14
14
|
signal.removeEventListener("abort", stop);
|
|
15
15
|
channel.close();
|
|
16
|
-
resolve(
|
|
16
|
+
resolve(answer);
|
|
17
17
|
};
|
|
18
18
|
const stop = () => finish(false);
|
|
19
19
|
const timer = setTimeout(stop, options.wait ?? HOLD_WAIT_MS);
|
|
20
20
|
signal.addEventListener("abort", stop, { once: true });
|
|
21
21
|
channel.onmessage = ({ data }) => {
|
|
22
22
|
const answer = data;
|
|
23
|
-
if (answer?.marker !== marker) return;
|
|
24
|
-
if (
|
|
25
|
-
else if (answer.type === "unheld") finish(false);
|
|
23
|
+
if (answer?.marker !== message.marker || typeof answer.type !== "string") return;
|
|
24
|
+
if (Object.hasOwn(answers, answer.type)) finish(answers[answer.type]);
|
|
26
25
|
};
|
|
27
26
|
if (signal.aborted) stop();
|
|
28
|
-
else channel.postMessage(
|
|
27
|
+
else channel.postMessage(message);
|
|
29
28
|
});
|
|
30
29
|
}
|
|
30
|
+
function askBase(marker, signal, options = {}) {
|
|
31
|
+
return ask({ type: "base", marker }, { based: true }, signal, options);
|
|
32
|
+
}
|
|
33
|
+
function askHold(marker, signal, options = {}) {
|
|
34
|
+
const message = { type: "hold", marker, ...options.based ? { based: true, expect: 1 } : {} };
|
|
35
|
+
return ask(message, { held: true, none: true, unheld: false }, signal, options);
|
|
36
|
+
}
|
|
31
37
|
function refusal(held, refuse = () => {
|
|
32
38
|
}) {
|
|
33
39
|
const refused = held.then((ok) => {
|
|
@@ -46,6 +52,7 @@ export {
|
|
|
46
52
|
HELD_MARK,
|
|
47
53
|
HOLD_WAIT_MS,
|
|
48
54
|
UNHELD,
|
|
55
|
+
askBase,
|
|
49
56
|
askHold,
|
|
50
57
|
markerUrl,
|
|
51
58
|
refusal,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/spectrum/held.ts"],
|
|
4
|
-
"sourcesContent": ["export const HELD_CHANNEL = 'slicc-held';\nexport const HELD_MARK = 'slicc-sign-in-';\nexport const HOLD_WAIT_MS = 6000;\nexport const UNHELD = \"SLICC couldn't protect the sign-in window. Try again.\";\n\nexport interface HeldChannel {\n onmessage: ((event: { data: unknown }) => void) | null;\n postMessage(data: unknown): void;\n close(): void;\n}\n\nexport type Listen = (name: string) => HeldChannel;\n\nconst listen: Listen = (name) => new BroadcastChannel(name) as unknown as HeldChannel;\n\nexport function markerUrl(marker: string): string {\n return `about:blank#${HELD_MARK}${marker}`;\n}\n\
|
|
5
|
-
"mappings": "AAAO,MAAM,eAAe;AACrB,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,SAAS;AAUtB,MAAM,SAAiB,CAAC,SAAS,IAAI,iBAAiB,IAAI;AAEnD,SAAS,UAAU,QAAwB;AAChD,SAAO,eAAe,SAAS,GAAG,MAAM;AAC1C;
|
|
4
|
+
"sourcesContent": ["export const HELD_CHANNEL = 'slicc-held';\nexport const HELD_MARK = 'slicc-sign-in-';\nexport const HOLD_WAIT_MS = 6000;\nexport const UNHELD = \"SLICC couldn't protect the sign-in window. Try again.\";\n\nexport interface HeldChannel {\n onmessage: ((event: { data: unknown }) => void) | null;\n postMessage(data: unknown): void;\n close(): void;\n}\n\nexport type Listen = (name: string) => HeldChannel;\n\nconst listen: Listen = (name) => new BroadcastChannel(name) as unknown as HeldChannel;\n\nexport function markerUrl(marker: string): string {\n return `about:blank#${HELD_MARK}${marker}`;\n}\n\ntype Options = { listen?: Listen; wait?: number };\n\nfunction ask(\n message: { type: string; marker: string },\n answers: Readonly<Record<string, boolean>>,\n signal: AbortSignal,\n options: Options\n): Promise<boolean> {\n return new Promise((resolve) => {\n const channel = (options.listen ?? listen)(HELD_CHANNEL);\n const finish = (answer: boolean) => {\n clearTimeout(timer);\n signal.removeEventListener('abort', stop);\n channel.close();\n resolve(answer);\n };\n const stop = () => finish(false);\n const timer = setTimeout(stop, options.wait ?? HOLD_WAIT_MS);\n signal.addEventListener('abort', stop, { once: true });\n channel.onmessage = ({ data }) => {\n const answer = data as { type?: unknown; marker?: unknown } | null;\n if (answer?.marker !== message.marker || typeof answer.type !== 'string') return;\n if (Object.hasOwn(answers, answer.type)) finish(answers[answer.type]);\n };\n if (signal.aborted) stop();\n else channel.postMessage(message);\n });\n}\n\nexport function askBase(marker: string, signal: AbortSignal, options: Options = {}) {\n return ask({ type: 'base', marker }, { based: true }, signal, options);\n}\n\nexport function askHold(\n marker: string,\n signal: AbortSignal,\n options: Options & { based?: boolean } = {}\n): Promise<boolean> {\n const message = { type: 'hold', marker, ...(options.based ? { based: true, expect: 1 } : {}) };\n return ask(message, { held: true, none: true, unheld: false }, signal, options);\n}\n\nexport function refusal(held: Promise<boolean>, refuse: () => void = () => {}): Promise<void> {\n const refused = held.then((ok) => {\n if (ok) return;\n refuse();\n throw new Error(UNHELD);\n });\n refused.catch(() => undefined);\n return refused;\n}\n\nexport function unlessRefused<T>(work: Promise<T>, refused: Promise<void>): Promise<T> {\n return Promise.race([work, refused.then(() => work)]);\n}\n"],
|
|
5
|
+
"mappings": "AAAO,MAAM,eAAe;AACrB,MAAM,YAAY;AAClB,MAAM,eAAe;AACrB,MAAM,SAAS;AAUtB,MAAM,SAAiB,CAAC,SAAS,IAAI,iBAAiB,IAAI;AAEnD,SAAS,UAAU,QAAwB;AAChD,SAAO,eAAe,SAAS,GAAG,MAAM;AAC1C;AAIA,SAAS,IACP,SACA,SACA,QACA,SACkB;AAClB,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,UAAM,WAAW,QAAQ,UAAU,QAAQ,YAAY;AACvD,UAAM,SAAS,CAAC,WAAoB;AAClC,mBAAa,KAAK;AAClB,aAAO,oBAAoB,SAAS,IAAI;AACxC,cAAQ,MAAM;AACd,cAAQ,MAAM;AAAA,IAChB;AACA,UAAM,OAAO,MAAM,OAAO,KAAK;AAC/B,UAAM,QAAQ,WAAW,MAAM,QAAQ,QAAQ,YAAY;AAC3D,WAAO,i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"./held.js";
|
|
2
2
|
const MCP_CHANNEL = "slicc-mcp-oauth";
|
|
3
3
|
const MCP_NAME_KEY = "slicc-mcp-oauth:";
|
|
4
4
|
const SIGN_IN_TIMEOUT_MS = 5 * 60 * 1e3;
|
|
5
5
|
const browser = {
|
|
6
6
|
open: (url) => globalThis.open?.(url, "slicc-mcp-oauth", "popup,width=520,height=720") ?? null,
|
|
7
|
-
|
|
7
|
+
base: (marker, signal) => askBase(marker, signal),
|
|
8
|
+
hold: (marker, signal, based) => askHold(marker, signal, { based }),
|
|
8
9
|
channel: () => new BroadcastChannel(MCP_CHANNEL),
|
|
9
10
|
remember: (state, name) => {
|
|
10
11
|
const key = `${MCP_NAME_KEY}${state}`;
|
|
@@ -52,8 +53,12 @@ function untilAborted(promise, signal) {
|
|
|
52
53
|
function mcpLogin(host = browser) {
|
|
53
54
|
return async (providerId, signIn, options) => {
|
|
54
55
|
const marker = crypto.randomUUID();
|
|
56
|
+
const based = await host.base(marker, options.signal);
|
|
57
|
+
options.signal.throwIfAborted();
|
|
55
58
|
const popup = host.open(markerUrl(marker));
|
|
56
|
-
const refused = refusal(
|
|
59
|
+
const refused = refusal(
|
|
60
|
+
popup ? host.hold(marker, options.signal, based) : Promise.resolve(true)
|
|
61
|
+
);
|
|
57
62
|
const channel = host.channel();
|
|
58
63
|
let state;
|
|
59
64
|
try {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/spectrum/mcp-login.ts"],
|
|
4
|
-
"sourcesContent": ["import type { McpSignIn, SignIn } from '../services.ts';\nimport { askHold, markerUrl, refusal, unlessRefused } from './held.ts';\n\nexport const MCP_CHANNEL = 'slicc-mcp-oauth';\nexport const MCP_NAME_KEY = 'slicc-mcp-oauth:';\nexport const SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;\n\nexport interface Popup {\n location: { href: string };\n close(): void;\n}\n\nexport interface Channel {\n onmessage: ((event: { data: unknown }) => void) | null;\n close(): void;\n}\n\nexport interface SignInWindow {\n open(url: string): Popup | null;\n hold(marker: string, signal: AbortSignal): Promise<boolean>;\n}\n\nexport interface McpLoginHost extends SignInWindow {\n channel(): Channel;\n remember?(state: string, name: string | null): void;\n timeoutMs?: number;\n}\n\nconst browser: McpLoginHost = {\n open: (url) => globalThis.open?.(url, 'slicc-mcp-oauth', 'popup,width=520,height=720') ?? null,\n hold: (marker, signal) => askHold(marker, signal),\n channel: () => new BroadcastChannel(MCP_CHANNEL) as unknown as Channel,\n remember: (state, name) => {\n const key = `${MCP_NAME_KEY}${state}`;\n if (name === null) globalThis.localStorage?.removeItem(key);\n else globalThis.localStorage?.setItem(key, name);\n },\n};\n\nconst LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nexport function safeAuthorizationUrl(value: string): boolean {\n if (!URL.canParse(value)) return false;\n const url = new URL(value);\n return url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK.has(url.hostname));\n}\n\nfunction answered(channel: Channel, state: string, signal: AbortSignal, timeoutMs: number) {\n return new Promise<string>((resolve, reject) => {\n const done = () => {\n clearTimeout(timer);\n signal.removeEventListener('abort', stop);\n };\n const stop = () => {\n done();\n reject(signal.reason);\n };\n const timer = setTimeout(() => {\n done();\n reject(new Error('The sign-in window gave no answer. Try again.'));\n }, timeoutMs);\n signal.addEventListener('abort', stop, { once: true });\n channel.onmessage = ({ data }) => {\n const answer = data as { state?: unknown } | null;\n if (answer?.state !== state) return;\n done();\n resolve(JSON.stringify(answer));\n };\n });\n}\n\nexport function untilAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n signal.throwIfAborted();\n return new Promise<T>((resolve, reject) => {\n const stop = () => reject(signal.reason);\n signal.addEventListener('abort', stop, { once: true });\n promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', stop));\n });\n}\n\nexport function mcpLogin(host: McpLoginHost = browser) {\n return async (\n providerId: string,\n signIn: () => Promise<SignIn | McpSignIn | null>,\n options: { signal: AbortSignal }\n ): Promise<string> => {\n const marker = crypto.randomUUID();\n const popup = host.open(markerUrl(marker));\n const refused = refusal(popup ? host.hold(marker, options.signal) : Promise.resolve(true));\n const channel = host.channel();\n let state: string | undefined;\n try {\n const started = (await untilAborted(\n unlessRefused(signIn(), refused),\n options.signal\n )) as McpSignIn | null;\n if (!started?.url) throw new Error('This MCP server has no sign-in.');\n if (!safeAuthorizationUrl(started.url))\n throw new Error(\"The authorization server gave a sign-in address that isn't https.\");\n if (!popup)\n throw new Error('The browser blocked the sign-in window. Allow pop-ups for SLICC.');\n await untilAborted(refused, options.signal);\n state = started.state;\n host.remember?.(state, providerId.replace(/^mcp:/, ''));\n popup.location.href = started.url;\n return await answered(channel, state, options.signal, host.timeoutMs ?? SIGN_IN_TIMEOUT_MS);\n } finally {\n if (state) host.remember?.(state, null);\n channel.close();\n popup?.close();\n }\n };\n}\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,SAAS,WAAW,SAAS,qBAAqB;
|
|
4
|
+
"sourcesContent": ["import type { McpSignIn, SignIn } from '../services.ts';\nimport { askBase, askHold, markerUrl, refusal, unlessRefused } from './held.ts';\n\nexport const MCP_CHANNEL = 'slicc-mcp-oauth';\nexport const MCP_NAME_KEY = 'slicc-mcp-oauth:';\nexport const SIGN_IN_TIMEOUT_MS = 5 * 60 * 1000;\n\nexport interface Popup {\n location: { href: string };\n close(): void;\n}\n\nexport interface Channel {\n onmessage: ((event: { data: unknown }) => void) | null;\n close(): void;\n}\n\nexport interface SignInWindow {\n open(url: string): Popup | null;\n base(marker: string, signal: AbortSignal): Promise<boolean>;\n hold(marker: string, signal: AbortSignal, based: boolean): Promise<boolean>;\n}\n\nexport interface McpLoginHost extends SignInWindow {\n channel(): Channel;\n remember?(state: string, name: string | null): void;\n timeoutMs?: number;\n}\n\nconst browser: McpLoginHost = {\n open: (url) => globalThis.open?.(url, 'slicc-mcp-oauth', 'popup,width=520,height=720') ?? null,\n base: (marker, signal) => askBase(marker, signal),\n hold: (marker, signal, based) => askHold(marker, signal, { based }),\n channel: () => new BroadcastChannel(MCP_CHANNEL) as unknown as Channel,\n remember: (state, name) => {\n const key = `${MCP_NAME_KEY}${state}`;\n if (name === null) globalThis.localStorage?.removeItem(key);\n else globalThis.localStorage?.setItem(key, name);\n },\n};\n\nconst LOOPBACK = new Set(['localhost', '127.0.0.1', '[::1]']);\n\nexport function safeAuthorizationUrl(value: string): boolean {\n if (!URL.canParse(value)) return false;\n const url = new URL(value);\n return url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK.has(url.hostname));\n}\n\nfunction answered(channel: Channel, state: string, signal: AbortSignal, timeoutMs: number) {\n return new Promise<string>((resolve, reject) => {\n const done = () => {\n clearTimeout(timer);\n signal.removeEventListener('abort', stop);\n };\n const stop = () => {\n done();\n reject(signal.reason);\n };\n const timer = setTimeout(() => {\n done();\n reject(new Error('The sign-in window gave no answer. Try again.'));\n }, timeoutMs);\n signal.addEventListener('abort', stop, { once: true });\n channel.onmessage = ({ data }) => {\n const answer = data as { state?: unknown } | null;\n if (answer?.state !== state) return;\n done();\n resolve(JSON.stringify(answer));\n };\n });\n}\n\nexport function untilAborted<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n signal.throwIfAborted();\n return new Promise<T>((resolve, reject) => {\n const stop = () => reject(signal.reason);\n signal.addEventListener('abort', stop, { once: true });\n promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', stop));\n });\n}\n\nexport function mcpLogin(host: McpLoginHost = browser) {\n return async (\n providerId: string,\n signIn: () => Promise<SignIn | McpSignIn | null>,\n options: { signal: AbortSignal }\n ): Promise<string> => {\n const marker = crypto.randomUUID();\n const based = await host.base(marker, options.signal);\n options.signal.throwIfAborted();\n const popup = host.open(markerUrl(marker));\n const refused = refusal(\n popup ? host.hold(marker, options.signal, based) : Promise.resolve(true)\n );\n const channel = host.channel();\n let state: string | undefined;\n try {\n const started = (await untilAborted(\n unlessRefused(signIn(), refused),\n options.signal\n )) as McpSignIn | null;\n if (!started?.url) throw new Error('This MCP server has no sign-in.');\n if (!safeAuthorizationUrl(started.url))\n throw new Error(\"The authorization server gave a sign-in address that isn't https.\");\n if (!popup)\n throw new Error('The browser blocked the sign-in window. Allow pop-ups for SLICC.');\n await untilAborted(refused, options.signal);\n state = started.state;\n host.remember?.(state, providerId.replace(/^mcp:/, ''));\n popup.location.href = started.url;\n return await answered(channel, state, options.signal, host.timeoutMs ?? SIGN_IN_TIMEOUT_MS);\n } finally {\n if (state) host.remember?.(state, null);\n channel.close();\n popup?.close();\n }\n };\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,SAAS,SAAS,WAAW,SAAS,qBAAqB;AAE7D,MAAM,cAAc;AACpB,MAAM,eAAe;AACrB,MAAM,qBAAqB,IAAI,KAAK;AAwB3C,MAAM,UAAwB;AAAA,EAC5B,MAAM,CAAC,QAAQ,WAAW,OAAO,KAAK,mBAAmB,4BAA4B,KAAK;AAAA,EAC1F,MAAM,CAAC,QAAQ,WAAW,QAAQ,QAAQ,MAAM;AAAA,EAChD,MAAM,CAAC,QAAQ,QAAQ,UAAU,QAAQ,QAAQ,QAAQ,EAAE,MAAM,CAAC;AAAA,EAClE,SAAS,MAAM,IAAI,iBAAiB,WAAW;AAAA,EAC/C,UAAU,CAAC,OAAO,SAAS;AACzB,UAAM,MAAM,GAAG,YAAY,GAAG,KAAK;AACnC,QAAI,SAAS,KAAM,YAAW,cAAc,WAAW,GAAG;AAAA,QACrD,YAAW,cAAc,QAAQ,KAAK,IAAI;AAAA,EACjD;AACF;AAEA,MAAM,WAAW,oBAAI,IAAI,CAAC,aAAa,aAAa,OAAO,CAAC;AAErD,SAAS,qBAAqB,OAAwB;AAC3D,MAAI,CAAC,IAAI,SAAS,KAAK,EAAG,QAAO;AACjC,QAAM,MAAM,IAAI,IAAI,KAAK;AACzB,SAAO,IAAI,aAAa,YAAa,IAAI,aAAa,WAAW,SAAS,IAAI,IAAI,QAAQ;AAC5F;AAEA,SAAS,SAAS,SAAk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AAC7B,QAAI;AACJ,QAAI;AACF,YAAM,UAAW,MAAM;AAAA,QACrB,cAAc,OAAO,GAAG,OAAO;AAAA,QAC/B,QAAQ;AAAA,MACV;AACA,UAAI,CAAC,SAAS,IAAK,OAAM,IAAI,MAAM,iCAAiC;AACpE,UAAI,CAAC,qBAAqB,QAAQ,GAAG;AACnC,cAAM,IAAI,MAAM,mEAAmE;AACrF,UAAI,CAAC;AACH,cAAM,IAAI,MAAM,kEAAkE;AACpF,YAAM,aAAa,SAAS,QAAQ,MAAM;AAC1C,cAAQ,QAAQ;AAChB,WAAK,WAAW,OAAO,WAAW,QAAQ,SAAS,EAAE,CAAC;AACtD,YAAM,SAAS,OAAO,QAAQ;AAC9B,aAAO,MAAM,SAAS,SAAS,OAAO,QAAQ,QAAQ,KAAK,aAAa,kBAAkB;AAAA,IAC5F,UAAE;AACA,UAAI,MAAO,MAAK,WAAW,OAAO,IAAI;AACtC,cAAQ,MAAM;AACd,aAAO,MAAM;AAAA,IACf;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
} from "../sign-ins.js";
|
|
8
8
|
import { attempt } from "./attempt.js";
|
|
9
9
|
import { Emitter } from "./emitter.js";
|
|
10
|
-
import { askHold, markerUrl, refusal, unlessRefused } from "./held.js";
|
|
10
|
+
import { askBase, askHold, markerUrl, refusal, unlessRefused } from "./held.js";
|
|
11
11
|
import { mcpLogin, untilAborted } from "./mcp-login.js";
|
|
12
12
|
const SETTINGS_KEY = "slicc-agent.settings";
|
|
13
13
|
const defaults = {
|
|
@@ -23,7 +23,8 @@ const UNFINISHED = SIGN_IN_UNFINISHED;
|
|
|
23
23
|
const NOTHING_TO_CONNECT = "This MCP server has no sign-in to connect: it needs none, or it's off in mcp.json.";
|
|
24
24
|
const signInWindow = {
|
|
25
25
|
open: (url) => globalThis.open?.(url, "slicc-sign-in", "popup,width=520,height=720") ?? null,
|
|
26
|
-
|
|
26
|
+
base: (marker, signal) => askBase(marker, signal),
|
|
27
|
+
hold: (marker, signal, based) => askHold(marker, signal, { based })
|
|
27
28
|
};
|
|
28
29
|
function readable(error) {
|
|
29
30
|
if (error instanceof DOMException && error.name === "AbortError") return error;
|
|
@@ -207,17 +208,23 @@ class SettingsAdapter extends Emitter {
|
|
|
207
208
|
}
|
|
208
209
|
async #device(id, given) {
|
|
209
210
|
const marker = crypto.randomUUID();
|
|
210
|
-
const popup = this.#window.open(markerUrl(marker));
|
|
211
211
|
const controller = this.#begin(id);
|
|
212
212
|
const { signal } = controller;
|
|
213
|
-
|
|
214
|
-
const refused = refusal(
|
|
215
|
-
popup ? this.#window.hold(marker, signal) : Promise.resolve(true),
|
|
216
|
-
() => unheld.abort(new DOMException("The sign-in window was not held.", "AbortError"))
|
|
217
|
-
);
|
|
218
|
-
const context = withAbortSignal(signal, BACKGROUND_CONTEXT);
|
|
219
|
-
const discovery = withAbortSignal(AbortSignal.any([signal, unheld.signal]), BACKGROUND_CONTEXT);
|
|
213
|
+
let popup = null;
|
|
220
214
|
try {
|
|
215
|
+
const based = await this.#window.base(marker, signal);
|
|
216
|
+
signal.throwIfAborted();
|
|
217
|
+
popup = this.#window.open(markerUrl(marker));
|
|
218
|
+
const unheld = new AbortController();
|
|
219
|
+
const refused = refusal(
|
|
220
|
+
popup ? this.#window.hold(marker, signal, based) : Promise.resolve(true),
|
|
221
|
+
() => unheld.abort(new DOMException("The sign-in window was not held.", "AbortError"))
|
|
222
|
+
);
|
|
223
|
+
const context = withAbortSignal(signal, BACKGROUND_CONTEXT);
|
|
224
|
+
const discovery = withAbortSignal(
|
|
225
|
+
AbortSignal.any([signal, unheld.signal]),
|
|
226
|
+
BACKGROUND_CONTEXT
|
|
227
|
+
);
|
|
221
228
|
const started = await untilAborted(
|
|
222
229
|
unlessRefused(this.#settings.signIn(id, discovery), refused),
|
|
223
230
|
signal
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/spectrum/settings-port.ts"],
|
|
4
|
-
"sourcesContent": ["import type {\n Account,\n ModelOption,\n Settings,\n SettingsEvents,\n SettingsPort,\n} from '@ai-ecoverse/slicc-spectrum/ui';\nimport { BACKGROUND_CONTEXT, withAbortSignal } from '@earendil-works/chord/context';\nimport { preferredModel } from '../preferred.ts';\nimport type {\n AgentSettings,\n McpEdit,\n McpRefusals,\n ProviderOption,\n SettingsState,\n SignIn,\n} from '../services.ts';\nimport {\n type ConnectOptions,\n DEVICE_SIGN_INS,\n type DeviceSignIn,\n httpsUrl,\n SIGN_IN_UNFINISHED,\n} from '../sign-ins.ts';\nimport type { AgentAdapter } from './agent-port.ts';\nimport { attempt } from './attempt.ts';\nimport { Emitter } from './emitter.ts';\nimport { askHold, markerUrl, refusal, unlessRefused } from './held.ts';\nimport { mcpLogin, type SignInWindow, untilAborted } from './mcp-login.ts';\n\nexport const SETTINGS_KEY = 'slicc-agent.settings';\n\nconst defaults: Settings = {\n color: 'system',\n model: '',\n thinking: 'off',\n sendOnEnter: true,\n showThinking: false,\n diffStyle: 'unified',\n};\n\ntype Local = Omit<Settings, 'model' | 'thinking'>;\n\nexport type Sealed = { sealed: true };\n\nexport type Login = (\n providerId: string,\n signIn: () => Promise<SignIn | null>,\n options: { signal: AbortSignal }\n) => Promise<string | Sealed>;\n\nexport const SIGN_IN_NEEDS_VAULT = \"Adobe sign-in needs seven's vault: update seven\";\nexport const UNFINISHED = SIGN_IN_UNFINISHED;\nexport const NOTHING_TO_CONNECT =\n \"This MCP server has no sign-in to connect: it needs none, or it's off in mcp.json.\";\n\nconst signInWindow: SignInWindow = {\n open: (url) => globalThis.open?.(url, 'slicc-sign-in', 'popup,width=520,height=720') ?? null,\n hold: (marker, signal) => askHold(marker, signal),\n};\n\nexport function readable(error: unknown): Error {\n if (error instanceof DOMException && error.name === 'AbortError') return error;\n const text = (error instanceof Error ? error.message : String(error ?? '')).trim();\n if (!text) return new Error(UNFINISHED);\n const lead = /^[a-z]+\\b(?![-.@/])/.test(text) ? text[0].toUpperCase() + text.slice(1) : text;\n return new Error(/[.!?]$/.test(lead) ? lead : `${lead}.`);\n}\n\ntype Events = SettingsEvents & { providers: readonly ProviderOption[] };\n\nexport class SettingsAdapter extends Emitter<Events> implements SettingsPort {\n readonly #settings: AgentSettings;\n readonly #agent: AgentAdapter;\n readonly #storage: Pick<Storage, 'getItem' | 'setItem'> | null;\n readonly #login: Login | null;\n readonly #mcpLogin: Login;\n readonly #signing = new Map<string, AbortController>();\n readonly #prompts = new Map<string, DeviceSignIn>();\n readonly #window: SignInWindow;\n #local: Local;\n #offered = '';\n readonly #urls = new Map<string, string>();\n readonly addServer?: (name: string, entry: unknown) => Promise<McpEdit>;\n readonly removeServer?: (id: string) => Promise<McpEdit>;\n readonly refusals?: () => Promise<McpRefusals>;\n\n constructor(\n settings: AgentSettings,\n agent: AgentAdapter,\n storage: Pick<Storage, 'getItem' | 'setItem'> | null,\n login: Login | null = null,\n mcp: Login = mcpLogin() as Login,\n popups: SignInWindow = signInWindow,\n owner = false\n ) {\n super();\n if (owner) {\n this.addServer = (name, entry) => settings.addServer(name, entry, BACKGROUND_CONTEXT);\n this.removeServer = (id) => {\n this.cancel(id);\n return settings.removeServer(id, BACKGROUND_CONTEXT);\n };\n this.refusals = () => settings.refusals(BACKGROUND_CONTEXT);\n }\n this.#mcpLogin = mcp;\n this.#window = popups;\n this.#settings = settings;\n this.#agent = agent;\n this.#storage = storage;\n this.#login = login;\n const saved = JSON.parse(storage?.getItem(SETTINGS_KEY) ?? '{}') as Partial<Local>;\n const { model: _model, thinking: _thinking, ...local } = { ...defaults, ...saved };\n this.#local = local;\n this.#offered = JSON.stringify(this.providers());\n this.#locate();\n settings.state.subscribe(() => {\n this.#locate();\n this.emit('accounts', this.accounts());\n this.emit('settings', this.get());\n const offered = JSON.stringify(this.providers());\n if (offered === this.#offered) return;\n this.#offered = offered;\n this.emit('providers', this.providers());\n });\n agent.on('agents', () => this.emit('settings', this.get()));\n }\n\n #locate(): void {\n const servers = this.#state()\n .accounts.filter(({ group }) => group === 'mcp')\n .map(({ id }) => id);\n for (const id of this.#urls.keys()) if (!servers.includes(id)) this.#urls.delete(id);\n for (const id of servers) {\n void this.#settings\n .serverUrl?.(id, BACKGROUND_CONTEXT)\n .then((url) => {\n if ((url ?? undefined) === this.#urls.get(id)) return;\n if (url) this.#urls.set(id, url);\n else this.#urls.delete(id);\n this.emit('accounts', this.accounts());\n })\n .catch(() => undefined);\n }\n }\n\n #state(): SettingsState {\n return this.#settings.state.value ?? { models: [], accounts: [] };\n }\n\n get(): Settings {\n const id = this.#agent.active();\n const cone = this.#agent.list().find((row) => row.id === id) ?? this.#agent.list()[0];\n return { ...this.#local, model: cone?.model ?? '', thinking: cone?.thinking ?? 'off' };\n }\n\n update(patch: Partial<Settings>): void {\n const { model, thinking, ...local } = patch;\n const id = this.#agent.active();\n if (model !== undefined) this.#agent.setModel(id, model);\n if (thinking !== undefined) this.#agent.setThinking(id, thinking);\n this.#local = { ...this.#local, ...local };\n this.#storage?.setItem(SETTINGS_KEY, JSON.stringify(this.#local));\n this.emit('settings', this.get());\n }\n\n models(): readonly ModelOption[] {\n const choices = this.#state().models;\n const groups = Map.groupBy(choices, ({ id }) => id.slice(0, id.indexOf('/')));\n const chosen = new Set(\n [...groups].map(\n ([providerId, group]) =>\n preferredModel(\n providerId,\n group.map((choice) => ({ id: choice.id.slice(providerId.length + 1), choice }))\n )?.choice\n )\n );\n return choices.map((choice) => {\n const { id, label, provider, kind, reasoning, images } = choice;\n return {\n id,\n label,\n provider,\n kind,\n reasoning,\n ...(images === undefined ? {} : { images }),\n ...(chosen.has(choice) ? { default: true } : {}),\n };\n });\n }\n\n #offer(id: string) {\n const option = this.providers().find((candidate) => candidate.id === id);\n if (!option) return undefined;\n return {\n auth: option.auth === 'oauth' ? ('oauth' as const) : ('api-key' as const),\n store: 'vault' as const,\n group: 'providers' as const,\n };\n }\n\n providers(): readonly ProviderOption[] {\n return this.#state().providers ?? [];\n }\n\n async remove(id: string): Promise<void> {\n this.cancel(id);\n await this.#settings.remove(id, BACKGROUND_CONTEXT);\n }\n\n accounts(): readonly Account[] {\n return this.#state().accounts.map(({ needs, ...account }) => {\n const url = this.#urls.get(account.id);\n const located = url ? { ...account, url } : account;\n const prompt = this.#prompts.get(account.id);\n const shown = this.#signing.has(account.id)\n ? {\n ...located,\n status: 'signing-in' as const,\n ...(prompt ? { signIn: { ...prompt } } : {}),\n }\n : located;\n return needs ? { ...shown, needs } : shown;\n });\n }\n\n async connect(\n id: string,\n secret?: string,\n fields?: Record<string, string>,\n options?: ConnectOptions\n ): Promise<void> {\n const account =\n this.#state().accounts.find((candidate) => candidate.id === id) ?? this.#offer(id);\n const mcp = account?.group === 'mcp';\n if (mcp && account?.auth === 'local') throw new Error(NOTHING_TO_CONNECT);\n const given = fields ? { ...fields } : null;\n const keyed = options?.method === 'key';\n if (account?.auth === 'oauth' && DEVICE_SIGN_INS.has(id) && secret === undefined && !keyed)\n return this.#device(id, given);\n const login = account?.auth !== 'oauth' || keyed ? null : mcp ? this.#mcpLogin : this.#login;\n if (keyed) this.cancel(id);\n if (secret !== undefined) {\n await this.#settings.connect(id, secret, given, BACKGROUND_CONTEXT);\n return;\n }\n if (account?.auth === 'oauth' && !login && !keyed) throw new Error(`${id} needs a sign-in`);\n if (!login) {\n if (account?.store !== 'vault') throw new Error(`${id} needs an API key`);\n await this.#settings.connect(id, null, given, BACKGROUND_CONTEXT);\n return;\n }\n const answer = await this.#signIn(id, login);\n if (typeof answer === 'string') {\n if (!mcp) throw new Error(SIGN_IN_NEEDS_VAULT);\n await this.#settings.connect(id, answer, given, BACKGROUND_CONTEXT);\n return;\n }\n if (answer?.sealed !== true) throw new Error(UNFINISHED);\n await this.#settings.connect(id, null, given, BACKGROUND_CONTEXT);\n }\n\n #begin(id: string): AbortController {\n const controller = new AbortController();\n this.#signing\n .get(id)\n ?.abort(new DOMException('A newer sign-in replaced this one.', 'AbortError'));\n this.#signing.set(id, controller);\n this.#prompts.delete(id);\n this.emit('accounts', this.accounts());\n return controller;\n }\n\n #end(id: string, controller: AbortController): void {\n if (this.#signing.get(id) === controller) {\n this.#signing.delete(id);\n this.#prompts.delete(id);\n }\n this.emit('accounts', this.accounts());\n }\n\n async #device(id: string, given: Record<string, string> | null): Promise<void> {\n const marker = crypto.randomUUID();\n const popup = this.#window.open(markerUrl(marker));\n const controller = this.#begin(id);\n const { signal } = controller;\n const unheld = new AbortController();\n const refused = refusal(popup ? this.#window.hold(marker, signal) : Promise.resolve(true), () =>\n unheld.abort(new DOMException('The sign-in window was not held.', 'AbortError'))\n );\n const context = withAbortSignal(signal, BACKGROUND_CONTEXT);\n const discovery = withAbortSignal(AbortSignal.any([signal, unheld.signal]), BACKGROUND_CONTEXT);\n try {\n const started = (await untilAborted(\n unlessRefused(this.#settings.signIn(id, discovery), refused),\n signal\n )) as DeviceSignIn | null;\n if (!started || !httpsUrl(started.url)) throw new Error(UNFINISHED);\n await untilAborted(refused, signal);\n const code = typeof started.code === 'string' && started.code ? started.code : undefined;\n this.#prompts.set(id, { url: started.url, ...(code ? { code } : {}) });\n this.emit('accounts', this.accounts());\n if (popup) popup.location.href = started.url;\n await untilAborted(this.#settings.connect(id, null, given, context), signal);\n } catch (error) {\n signal.throwIfAborted();\n throw readable(error);\n } finally {\n popup?.close();\n this.#end(id, controller);\n }\n }\n\n async #signIn(id: string, login: Login): Promise<string | Sealed> {\n const controller = this.#begin(id);\n try {\n const key = await login(\n id,\n () => this.#settings.signIn(id, BACKGROUND_CONTEXT) as Promise<SignIn | null>,\n {\n signal: controller.signal,\n }\n ).catch((error: unknown) => {\n controller.signal.throwIfAborted();\n throw readable(error);\n });\n controller.signal.throwIfAborted();\n return key;\n } finally {\n this.#end(id, controller);\n }\n }\n\n cancel(id: string): void {\n const controller = this.#signing.get(id);\n if (!controller) return;\n this.#signing.delete(id);\n this.#prompts.delete(id);\n controller.abort(new DOMException('The sign-in was cancelled.', 'AbortError'));\n this.emit('accounts', this.accounts());\n }\n\n disconnect(id: string): void {\n attempt(this.#settings.disconnect(id, BACKGROUND_CONTEXT), 'disconnect accounts', (text) =>\n this.#agent.notify(text)\n );\n }\n}\n"],
|
|
5
|
-
"mappings": "AAOA,SAAS,oBAAoB,uBAAuB;AACpD,SAAS,sBAAsB;AAS/B;AAAA,EAEE;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,SAAS,WAAW,SAAS,qBAAqB;
|
|
4
|
+
"sourcesContent": ["import type {\n Account,\n ModelOption,\n Settings,\n SettingsEvents,\n SettingsPort,\n} from '@ai-ecoverse/slicc-spectrum/ui';\nimport { BACKGROUND_CONTEXT, withAbortSignal } from '@earendil-works/chord/context';\nimport { preferredModel } from '../preferred.ts';\nimport type {\n AgentSettings,\n McpEdit,\n McpRefusals,\n ProviderOption,\n SettingsState,\n SignIn,\n} from '../services.ts';\nimport {\n type ConnectOptions,\n DEVICE_SIGN_INS,\n type DeviceSignIn,\n httpsUrl,\n SIGN_IN_UNFINISHED,\n} from '../sign-ins.ts';\nimport type { AgentAdapter } from './agent-port.ts';\nimport { attempt } from './attempt.ts';\nimport { Emitter } from './emitter.ts';\nimport { askBase, askHold, markerUrl, refusal, unlessRefused } from './held.ts';\nimport { mcpLogin, type Popup, type SignInWindow, untilAborted } from './mcp-login.ts';\n\nexport const SETTINGS_KEY = 'slicc-agent.settings';\n\nconst defaults: Settings = {\n color: 'system',\n model: '',\n thinking: 'off',\n sendOnEnter: true,\n showThinking: false,\n diffStyle: 'unified',\n};\n\ntype Local = Omit<Settings, 'model' | 'thinking'>;\n\nexport type Sealed = { sealed: true };\n\nexport type Login = (\n providerId: string,\n signIn: () => Promise<SignIn | null>,\n options: { signal: AbortSignal }\n) => Promise<string | Sealed>;\n\nexport const SIGN_IN_NEEDS_VAULT = \"Adobe sign-in needs seven's vault: update seven\";\nexport const UNFINISHED = SIGN_IN_UNFINISHED;\nexport const NOTHING_TO_CONNECT =\n \"This MCP server has no sign-in to connect: it needs none, or it's off in mcp.json.\";\n\nconst signInWindow: SignInWindow = {\n open: (url) => globalThis.open?.(url, 'slicc-sign-in', 'popup,width=520,height=720') ?? null,\n base: (marker, signal) => askBase(marker, signal),\n hold: (marker, signal, based) => askHold(marker, signal, { based }),\n};\n\nexport function readable(error: unknown): Error {\n if (error instanceof DOMException && error.name === 'AbortError') return error;\n const text = (error instanceof Error ? error.message : String(error ?? '')).trim();\n if (!text) return new Error(UNFINISHED);\n const lead = /^[a-z]+\\b(?![-.@/])/.test(text) ? text[0].toUpperCase() + text.slice(1) : text;\n return new Error(/[.!?]$/.test(lead) ? lead : `${lead}.`);\n}\n\ntype Events = SettingsEvents & { providers: readonly ProviderOption[] };\n\nexport class SettingsAdapter extends Emitter<Events> implements SettingsPort {\n readonly #settings: AgentSettings;\n readonly #agent: AgentAdapter;\n readonly #storage: Pick<Storage, 'getItem' | 'setItem'> | null;\n readonly #login: Login | null;\n readonly #mcpLogin: Login;\n readonly #signing = new Map<string, AbortController>();\n readonly #prompts = new Map<string, DeviceSignIn>();\n readonly #window: SignInWindow;\n #local: Local;\n #offered = '';\n readonly #urls = new Map<string, string>();\n readonly addServer?: (name: string, entry: unknown) => Promise<McpEdit>;\n readonly removeServer?: (id: string) => Promise<McpEdit>;\n readonly refusals?: () => Promise<McpRefusals>;\n\n constructor(\n settings: AgentSettings,\n agent: AgentAdapter,\n storage: Pick<Storage, 'getItem' | 'setItem'> | null,\n login: Login | null = null,\n mcp: Login = mcpLogin() as Login,\n popups: SignInWindow = signInWindow,\n owner = false\n ) {\n super();\n if (owner) {\n this.addServer = (name, entry) => settings.addServer(name, entry, BACKGROUND_CONTEXT);\n this.removeServer = (id) => {\n this.cancel(id);\n return settings.removeServer(id, BACKGROUND_CONTEXT);\n };\n this.refusals = () => settings.refusals(BACKGROUND_CONTEXT);\n }\n this.#mcpLogin = mcp;\n this.#window = popups;\n this.#settings = settings;\n this.#agent = agent;\n this.#storage = storage;\n this.#login = login;\n const saved = JSON.parse(storage?.getItem(SETTINGS_KEY) ?? '{}') as Partial<Local>;\n const { model: _model, thinking: _thinking, ...local } = { ...defaults, ...saved };\n this.#local = local;\n this.#offered = JSON.stringify(this.providers());\n this.#locate();\n settings.state.subscribe(() => {\n this.#locate();\n this.emit('accounts', this.accounts());\n this.emit('settings', this.get());\n const offered = JSON.stringify(this.providers());\n if (offered === this.#offered) return;\n this.#offered = offered;\n this.emit('providers', this.providers());\n });\n agent.on('agents', () => this.emit('settings', this.get()));\n }\n\n #locate(): void {\n const servers = this.#state()\n .accounts.filter(({ group }) => group === 'mcp')\n .map(({ id }) => id);\n for (const id of this.#urls.keys()) if (!servers.includes(id)) this.#urls.delete(id);\n for (const id of servers) {\n void this.#settings\n .serverUrl?.(id, BACKGROUND_CONTEXT)\n .then((url) => {\n if ((url ?? undefined) === this.#urls.get(id)) return;\n if (url) this.#urls.set(id, url);\n else this.#urls.delete(id);\n this.emit('accounts', this.accounts());\n })\n .catch(() => undefined);\n }\n }\n\n #state(): SettingsState {\n return this.#settings.state.value ?? { models: [], accounts: [] };\n }\n\n get(): Settings {\n const id = this.#agent.active();\n const cone = this.#agent.list().find((row) => row.id === id) ?? this.#agent.list()[0];\n return { ...this.#local, model: cone?.model ?? '', thinking: cone?.thinking ?? 'off' };\n }\n\n update(patch: Partial<Settings>): void {\n const { model, thinking, ...local } = patch;\n const id = this.#agent.active();\n if (model !== undefined) this.#agent.setModel(id, model);\n if (thinking !== undefined) this.#agent.setThinking(id, thinking);\n this.#local = { ...this.#local, ...local };\n this.#storage?.setItem(SETTINGS_KEY, JSON.stringify(this.#local));\n this.emit('settings', this.get());\n }\n\n models(): readonly ModelOption[] {\n const choices = this.#state().models;\n const groups = Map.groupBy(choices, ({ id }) => id.slice(0, id.indexOf('/')));\n const chosen = new Set(\n [...groups].map(\n ([providerId, group]) =>\n preferredModel(\n providerId,\n group.map((choice) => ({ id: choice.id.slice(providerId.length + 1), choice }))\n )?.choice\n )\n );\n return choices.map((choice) => {\n const { id, label, provider, kind, reasoning, images } = choice;\n return {\n id,\n label,\n provider,\n kind,\n reasoning,\n ...(images === undefined ? {} : { images }),\n ...(chosen.has(choice) ? { default: true } : {}),\n };\n });\n }\n\n #offer(id: string) {\n const option = this.providers().find((candidate) => candidate.id === id);\n if (!option) return undefined;\n return {\n auth: option.auth === 'oauth' ? ('oauth' as const) : ('api-key' as const),\n store: 'vault' as const,\n group: 'providers' as const,\n };\n }\n\n providers(): readonly ProviderOption[] {\n return this.#state().providers ?? [];\n }\n\n async remove(id: string): Promise<void> {\n this.cancel(id);\n await this.#settings.remove(id, BACKGROUND_CONTEXT);\n }\n\n accounts(): readonly Account[] {\n return this.#state().accounts.map(({ needs, ...account }) => {\n const url = this.#urls.get(account.id);\n const located = url ? { ...account, url } : account;\n const prompt = this.#prompts.get(account.id);\n const shown = this.#signing.has(account.id)\n ? {\n ...located,\n status: 'signing-in' as const,\n ...(prompt ? { signIn: { ...prompt } } : {}),\n }\n : located;\n return needs ? { ...shown, needs } : shown;\n });\n }\n\n async connect(\n id: string,\n secret?: string,\n fields?: Record<string, string>,\n options?: ConnectOptions\n ): Promise<void> {\n const account =\n this.#state().accounts.find((candidate) => candidate.id === id) ?? this.#offer(id);\n const mcp = account?.group === 'mcp';\n if (mcp && account?.auth === 'local') throw new Error(NOTHING_TO_CONNECT);\n const given = fields ? { ...fields } : null;\n const keyed = options?.method === 'key';\n if (account?.auth === 'oauth' && DEVICE_SIGN_INS.has(id) && secret === undefined && !keyed)\n return this.#device(id, given);\n const login = account?.auth !== 'oauth' || keyed ? null : mcp ? this.#mcpLogin : this.#login;\n if (keyed) this.cancel(id);\n if (secret !== undefined) {\n await this.#settings.connect(id, secret, given, BACKGROUND_CONTEXT);\n return;\n }\n if (account?.auth === 'oauth' && !login && !keyed) throw new Error(`${id} needs a sign-in`);\n if (!login) {\n if (account?.store !== 'vault') throw new Error(`${id} needs an API key`);\n await this.#settings.connect(id, null, given, BACKGROUND_CONTEXT);\n return;\n }\n const answer = await this.#signIn(id, login);\n if (typeof answer === 'string') {\n if (!mcp) throw new Error(SIGN_IN_NEEDS_VAULT);\n await this.#settings.connect(id, answer, given, BACKGROUND_CONTEXT);\n return;\n }\n if (answer?.sealed !== true) throw new Error(UNFINISHED);\n await this.#settings.connect(id, null, given, BACKGROUND_CONTEXT);\n }\n\n #begin(id: string): AbortController {\n const controller = new AbortController();\n this.#signing\n .get(id)\n ?.abort(new DOMException('A newer sign-in replaced this one.', 'AbortError'));\n this.#signing.set(id, controller);\n this.#prompts.delete(id);\n this.emit('accounts', this.accounts());\n return controller;\n }\n\n #end(id: string, controller: AbortController): void {\n if (this.#signing.get(id) === controller) {\n this.#signing.delete(id);\n this.#prompts.delete(id);\n }\n this.emit('accounts', this.accounts());\n }\n\n async #device(id: string, given: Record<string, string> | null): Promise<void> {\n const marker = crypto.randomUUID();\n const controller = this.#begin(id);\n const { signal } = controller;\n let popup: Popup | null = null;\n try {\n const based = await this.#window.base(marker, signal);\n signal.throwIfAborted();\n popup = this.#window.open(markerUrl(marker));\n const unheld = new AbortController();\n const refused = refusal(\n popup ? this.#window.hold(marker, signal, based) : Promise.resolve(true),\n () => unheld.abort(new DOMException('The sign-in window was not held.', 'AbortError'))\n );\n const context = withAbortSignal(signal, BACKGROUND_CONTEXT);\n const discovery = withAbortSignal(\n AbortSignal.any([signal, unheld.signal]),\n BACKGROUND_CONTEXT\n );\n const started = (await untilAborted(\n unlessRefused(this.#settings.signIn(id, discovery), refused),\n signal\n )) as DeviceSignIn | null;\n if (!started || !httpsUrl(started.url)) throw new Error(UNFINISHED);\n await untilAborted(refused, signal);\n const code = typeof started.code === 'string' && started.code ? started.code : undefined;\n this.#prompts.set(id, { url: started.url, ...(code ? { code } : {}) });\n this.emit('accounts', this.accounts());\n if (popup) popup.location.href = started.url;\n await untilAborted(this.#settings.connect(id, null, given, context), signal);\n } catch (error) {\n signal.throwIfAborted();\n throw readable(error);\n } finally {\n popup?.close();\n this.#end(id, controller);\n }\n }\n\n async #signIn(id: string, login: Login): Promise<string | Sealed> {\n const controller = this.#begin(id);\n try {\n const key = await login(\n id,\n () => this.#settings.signIn(id, BACKGROUND_CONTEXT) as Promise<SignIn | null>,\n {\n signal: controller.signal,\n }\n ).catch((error: unknown) => {\n controller.signal.throwIfAborted();\n throw readable(error);\n });\n controller.signal.throwIfAborted();\n return key;\n } finally {\n this.#end(id, controller);\n }\n }\n\n cancel(id: string): void {\n const controller = this.#signing.get(id);\n if (!controller) return;\n this.#signing.delete(id);\n this.#prompts.delete(id);\n controller.abort(new DOMException('The sign-in was cancelled.', 'AbortError'));\n this.emit('accounts', this.accounts());\n }\n\n disconnect(id: string): void {\n attempt(this.#settings.disconnect(id, BACKGROUND_CONTEXT), 'disconnect accounts', (text) =>\n this.#agent.notify(text)\n );\n }\n}\n"],
|
|
5
|
+
"mappings": "AAOA,SAAS,oBAAoB,uBAAuB;AACpD,SAAS,sBAAsB;AAS/B;AAAA,EAEE;AAAA,EAEA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,eAAe;AACxB,SAAS,eAAe;AACxB,SAAS,SAAS,SAAS,WAAW,SAAS,qBAAqB;AACpE,SAAS,UAAyC,oBAAoB;AAE/D,MAAM,eAAe;AAE5B,MAAM,WAAqB;AAAA,EACzB,OAAO;AAAA,EACP,OAAO;AAAA,EACP,UAAU;AAAA,EACV,aAAa;AAAA,EACb,cAAc;AAAA,EACd,WAAW;AACb;AAYO,MAAM,sBAAsB;AAC5B,MAAM,aAAa;AACnB,MAAM,qBACX;AAEF,MAAM,eAA6B;AAAA,EACjC,MAAM,CAAC,QAAQ,WAAW,OAAO,KAAK,iBAAiB,4BAA4B,KAAK;AAAA,EACxF,MAAM,CAAC,QAAQ,WAAW,QAAQ,QAAQ,MAAM;AAAA,EAChD,MAAM,CAAC,QAAQ,QAAQ,UAAU,QAAQ,QAAQ,QAAQ,EAAE,MAAM,CAAC;AACpE;AAEO,SA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AA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -8,9 +8,10 @@ export { exposedLine, listedLine, SECRETS_KIND, unavailableLine };
|
|
|
8
8
|
export declare const SECRETS = "slicc-secrets";
|
|
9
9
|
export declare const SECRETS_COMMAND = "/secrets";
|
|
10
10
|
export declare const SHELL_GRANTS: readonly ['fnox', 'exec', '--shell-grants', '--'];
|
|
11
|
-
export declare const MODEL_LINE = "Credentials are env vars (`$NAME`) holding placeholders, listed below with where each works (`fnox list` shows the fnox config). 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,
|
|
12
|
-
export declare const ASK_LINE = "When a secret you need is missing, ask the user for it: `fnox set NAME --ask`
|
|
11
|
+
export declare const MODEL_LINE = "Credentials are env vars (`$NAME`) holding placeholders, listed below with where each works (`fnox list` shows the fnox config). 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: the user approving that sudo is the only acceptance there is, and the vault uses the rules in it as soon as it is written (`sealed list --json` shows the rules it uses now; the list below is read at start and can lag behind). It uses the rules of a secret only while the file is root-owned and not writable by others, and its `[secrets]` entry holds the placeholder of that secret: `NAME = { provider = \"seven\", value = \"<placeholder>\" }` (`sealed placeholder NAME` prints it); without the `value` the vault ignores the entry and every rule naming it, though `fnox check` passes. `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. Prefer an argv grant in `/etc/slicc/secrets-policy.toml` (`NAME = { argv = [[\"/absolute/program\"]] }`) for a secret one program needs; `{ shell = true }` hands it to every bash. 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.";
|
|
12
|
+
export declare const ASK_LINE = "When a secret you need is missing, ask the user for it: `fnox set NAME --ask` seals it and writes its entry to `fnox.toml` in the current directory, which the vault doesn't read (copy the entry into `/etc/fnox/config.toml` with sudo before adding its rules there), and `sealed ask NAME` keeps it in the vault only (`--prompt TEXT` says why you need it). The user types the value in a dialog, and the command prints only its placeholder. `fnox set` always asks for a new value and replaces an existing one, so use it only for a missing secret. Add `--reveal` to `sealed ask` only when a tool needs the plaintext itself, not where the vault fills it in a header, and pipe it straight into that tool (`sealed ask NAME --reveal | tool --password-stdin`): the user must allow every reveal, and you still see only the placeholder. A non-zero exit means the user declined or the request ended; don't ask again unless the user wants you to.";
|
|
13
13
|
export declare function scrubResult(result: ToolExecutionResult, scrub: Pick<Scrub, 'texts'>): Promise<ToolExecutionResult | undefined>;
|
|
14
|
+
export declare const unusedLine: (name: string, placeholder: string) => string;
|
|
14
15
|
export declare const NO_SECRETS = "No secrets are configured: the fnox config has no keys and the vault no sealed secrets.";
|
|
15
16
|
export declare function renderSecrets(listing: SecretListing): string;
|
|
16
17
|
export declare function secretsEntry(listing: SecretListing): {
|
|
@@ -11,9 +11,14 @@ export interface HeldChannel {
|
|
|
11
11
|
}
|
|
12
12
|
export type Listen = (name: string) => HeldChannel;
|
|
13
13
|
export declare function markerUrl(marker: string): string;
|
|
14
|
-
|
|
14
|
+
type Options = {
|
|
15
15
|
listen?: Listen;
|
|
16
16
|
wait?: number;
|
|
17
|
+
};
|
|
18
|
+
export declare function askBase(marker: string, signal: AbortSignal, options?: Options): Promise<boolean>;
|
|
19
|
+
export declare function askHold(marker: string, signal: AbortSignal, options?: Options & {
|
|
20
|
+
based?: boolean;
|
|
17
21
|
}): Promise<boolean>;
|
|
18
22
|
export declare function refusal(held: Promise<boolean>, refuse?: () => void): Promise<void>;
|
|
19
23
|
export declare function unlessRefused<T>(work: Promise<T>, refused: Promise<void>): Promise<T>;
|
|
24
|
+
export {};
|
|
@@ -16,7 +16,8 @@ export interface Channel {
|
|
|
16
16
|
}
|
|
17
17
|
export interface SignInWindow {
|
|
18
18
|
open(url: string): Popup | null;
|
|
19
|
-
|
|
19
|
+
base(marker: string, signal: AbortSignal): Promise<boolean>;
|
|
20
|
+
hold(marker: string, signal: AbortSignal, based: boolean): Promise<boolean>;
|
|
20
21
|
}
|
|
21
22
|
export interface McpLoginHost extends SignInWindow {
|
|
22
23
|
channel(): Channel;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-ecoverse/slicc-agent",
|
|
3
|
-
"version": "7.34.
|
|
3
|
+
"version": "7.34.3",
|
|
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",
|
|
@@ -72,13 +72,13 @@
|
|
|
72
72
|
"release": "semantic-release"
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
|
-
"@ai-ecoverse/slicc-jsh": "0.64.
|
|
76
|
-
"@ai-ecoverse/slicc-kernel": "1.
|
|
75
|
+
"@ai-ecoverse/slicc-jsh": "0.64.5",
|
|
76
|
+
"@ai-ecoverse/slicc-kernel": "1.191.2",
|
|
77
77
|
"@ai-ecoverse/slicc-scrub": "1.1.1",
|
|
78
78
|
"@ai-ecoverse/slicc-shared-web": "2.14.4",
|
|
79
79
|
"@ai-ecoverse/slicc-spectrum": "2.16.1",
|
|
80
|
-
"@ai-ecoverse/slicc-vault": "1.26.
|
|
81
|
-
"@ai-ecoverse/wasi-fnox": "1.
|
|
80
|
+
"@ai-ecoverse/slicc-vault": "1.26.3",
|
|
81
|
+
"@ai-ecoverse/wasi-fnox": "1.48.0-1",
|
|
82
82
|
"@ai-ecoverse/wasm-bash": "5.3.0-23",
|
|
83
83
|
"@ai-ecoverse/wasm-coreutils": "9.12.0-15",
|
|
84
84
|
"@ai-ecoverse/wasm-git": "2.55.0-22",
|