diff --git a/README.md b/README.md index 61ca20a..83b2e12 100644 --- a/README.md +++ b/README.md @@ -140,12 +140,14 @@ Like middleware, these run on the requests agents send, but in magpie's Bun host |---|---| | [powercontext](packages/powercontext) | [PowerContext](https://github.com/oceanbase/powercontext) recall and opt-in completed-conversation capture; no client MCP or skill required | | [nowledge-mem](packages/nowledge-mem) | [Nowledge Mem](https://mem.nowledge.co) recall, Context Bundle or Working Memory, per-harness provenance and opt-in conversation import as Mem Threads, automatic for every harness behind Magpie | +| [aelios](packages/aelios) | [Aelios](https://github.com/wusaki0723/Aelios) recall before each turn from your own Aelios on Cloudflare, and opt-in recording of each turn so Aelios can remember it | Use the same plugin management commands as middleware: ```sh magpie plugin add @magpie-community/gateway-powercontext magpie plugin add @magpie-community/gateway-nowledge-mem +magpie plugin add @magpie-community/gateway-aelios ``` Installed plugins use **Plugins › Installed › Options** and the normal on/off diff --git a/packages/aelios/README.md b/packages/aelios/README.md new file mode 100644 index 0000000..0ec00d4 --- /dev/null +++ b/packages/aelios/README.md @@ -0,0 +1,261 @@ +# Aelios plugin for Magpie + +[Aelios](https://github.com/wusaki0723/Aelios) is a layered long-term memory +you deploy yourself on Cloudflare: it recalls what fits each turn, keeps what +was said, and tidies it overnight. This plugin brings it to **every agent +behind Magpie**: before each turn, the memory Aelios recalls for it is added +after the user's message; after the reply, and only if you turn `record` on, +the turn is handed to Aelios to remember. Your agents keep whatever models and +subscriptions they use in Magpie; nothing has to point at an Aelios gateway. + +```mermaid +sequenceDiagram + participant Agent as Any agent + participant Magpie + participant Plugin as Aelios hook + participant Aelios as Your Aelios Worker + participant Model + Agent->>Magpie: Request + Magpie->>Plugin: onRequest + alt the user said something + Plugin->>Aelios: POST /v1/hook/recall (slimmed request) + Aelios-->>Plugin: memory patch + Plugin-->>Magpie: patch added after the last user message + else a tool step or helper request + Plugin-->>Magpie: request unchanged + end + Magpie->>Model: One inference request + Model-->>Agent: Live reply through Magpie + Magpie--)Plugin: onResponse (completed reply) + opt record is on + Plugin--)Aelios: POST /v1/hook/record (slimmed request + reply) + end +``` + +The package declares `magpie.hooks: "./aelios.hooks.mjs"`, Magpie's +asynchronous Bun hook entry. It is not gateway middleware and has no OpenCode +provider. It needs **Magpie 0.1.1273 or newer** and Bun; from **Magpie +0.1.2210** the key Magpie writes into your own agents on this computer +(`magpie-key`) counts as yours too. + +## Before you start + +1. **Deploy Aelios yourself.** Follow the + [Aelios README](https://github.com/wusaki0723/Aelios#readme). The plugin + needs an Aelios that has the hook endpoints, `POST /v1/hook/recall` and + `POST /v1/hook/record`, including the recall endpoint's explicit `record` + permission added in [commit a57269c](https://github.com/sakisakisa-design/Aelios/commit/a57269c) + ([Aelios PR #102](https://github.com/wusaki0723/Aelios/pull/102)). + Deploy that commit or a later version containing it; omitting `record` + saves no user message or remember-now memory. An older Aelios without these endpoints + answers 404; the plugin then leaves requests alone and shows *unavailable*. +2. **Add your agents' model names to the assistant's main models** in Aelios + `/admin` (or use `*`). The plugin checks the authorized main-model list + locally; unmatched requests are not sent and show *unbound*. To keep GPT + and Claude in separate spaces, set each assistant's + main models separately in `/admin`. + +## Install and configure + +```sh +magpie plugin add @magpie-community/gateway-aelios +``` + +Then open **Plugins › Aelios** in Magpie. On first use, enter the server URL +and API key and click **Connect and test**. The plugin saves through Magpie, +confirms the saved settings, then opens its local service page with automatic +testing enabled. If saving cannot be confirmed, your edits stay in the form +and the page does not navigate. + +Once configured, the page shows the saved URL, a **Change connection** control, +and the recall/record switches (*Recall memory* on, *Record conversations* off +by default). Configured settings do not mean the connection has been verified. +**View matching list / retest** opens the local service page, which tests the +saved connection and shows the server-authorized assistants and their main +model matching rules through read-only `GET /v1/hook/identities`. This list needs +an Aelios version containing that endpoint. If the list is unavailable (including +on older Workers), hooks pause without sending conversations and show *unavailable*. The service +page has a button back to settings. Testing +sends empty messages; it creates no dialogue and records nothing. + +**Assistant assignment** defaults to **Automatic**. The plugin uses Aelios's +authorized matching list to select the first assistant whose main-model pattern +matches locally. Unmatched turns are not sent. If the list is unavailable, +recall and recording pause with status *unavailable*. Existing `identity` or +`routes` are shown as **Custom** and retain their routing priority. The collapsed **Advanced +settings** section contains the default/fallback identity, ordered identity +routes, agent filter, API key environment variable and remote-request switch. +You can continue editing those settings there; ordinary saves preserve them. +No hand-written JSON is needed. + +The same options can still be set from the command line: + +```sh +magpie plugin options aelios '{"serverUrl":"https://.workers.dev","gatewayTimeoutMs":5000}' +``` + +Give it your Aelios API key in Magpie's environment as `AELIOS_API_KEY`, or as +`apiKey` in the options. The key is sent as `Authorization: Bearer ` to +your `serverUrl` only, never through a redirect. + +Set `gatewayTimeoutMs` as above: without it Magpie gives a hook 1 second, and +the plugin then gives Aelios a little under that. The page fills in 5000 when +the setting is absent. + +To use a separate assistant space (recommended while you try it out), create +one in Aelios `/admin` and set `"identity": ""`. + +## Route models to separate identities + +Create `gpt-husband` and `claude-husband` identities in Aelios `/admin`, then +configure the plugin: + +```json +{ + "serverUrl": "https://.workers.dev", + "gatewayTimeoutMs": 5000, + "record": true, + "routes": [ + { "models": ["gpt-*"], "identity": "gpt-husband" }, + { "models": ["claude-*"], "identity": "claude-husband" } + ] +} +``` + +Routes are checked in order; **the first match wins**, ahead of the top-level +`identity`. Model patterns match the whole name, case insensitively, with `*` +matching any characters. Both the full Magpie model name and the suffix after +its last `/` are tried, so `openai/gpt-5` matches `gpt-*`. Other punctuation +is literal. The request body's model is used if Magpie provides no model. + +A route can also select exact Magpie agent ids: +`{"agents":["codex"],"models":["gpt-*"],"identity":"gpt-husband"}`. +When both selectors are present, **both must match**. Agent ids are case +sensitive; `*` has no special meaning in an agent id. The top-level `agents` +option still limits which requests the plugin handles. + +With nonempty `routes`, an unmatched request uses only an explicitly configured +top-level `identity`. Without that fallback, both recall and recording are +skipped, preventing accidental use of the server's default identity. Omit +`routes` or use `[]`: the top-level `identity` is used when set; otherwise the +plugin selects the first authorized assistant whose main models match locally. +Unmatched requests are not sent. Custom identities and route targets must also +be authorized and match the request model in the server's main-model list. + +**Separate identities need separate Aelios memory namespaces.** Give these +identities different `namespace` values and avoid shared `readNamespaces` if +they must not recall each other's memories. Routing chooses an identity; it +does not create identities or isolate spaces that Aelios is configured to +share. Each identity's Aelios `models` whitelist must also allow its actual +model names (or `*`), including provider-prefixed names when sent; the plugin's +route patterns do not configure that server whitelist. + +Routing also applies to tool continuations and `recall: false`. The original +identity, model, agent, session and slimmed request are saved before recall, +so recording uses the same exchange metadata even if the response context or +route options change. Recording still requires the current `record` permission +and the current origin and top-level agent restrictions. Recall backoff is +separate for each resolved identity. + +## What is sent + +Recall sends a **slimmed copy** of the request: roles and message text, tool +names, and the session id. Historical tool calls keep only their type and +name; their arguments and input are never sent. It does **not** send system +prompts or instructions, what tools returned (tool results are sent empty), +images, files or audio (replaced by `[image]`, `[file]`, `[audio]`), or thinking. +Only turns where the user said something are recalled; tool steps are not +sent for recall. + +**`record` is off by default.** Recall sends `record: false`, so Aelios +searches existing memories without saving the user's words or creating new +memories. This requires an Aelios hook endpoint that honors the `record` +permission; upgrade older hook endpoints before using the plugin. +If you want Aelios to remember your conversations, turn it on: + +```sh +magpie plugin options aelios '{"serverUrl":"https://.workers.dev","gatewayTimeoutMs":5000,"record":true}' +``` + +With `record` on, after each reply the slimmed request and a **slimmed reply** +are sent to Aelios: what you said, what the assistant said, the arguments of +its tool calls, and the completion status. Thinking/redacted-thinking blocks, +Responses reasoning items and summaries, Chat reasoning fields, signatures, +encrypted content and other provider metadata are omitted before the secret +check and before export. Tool results are not sent. For coding agents +(Claude Code, Codex, OpenCode, …) Aelios replaces code blocks with `[code]`. +If the current user text looks like it contains a credential (an API key, a +token, a private key, `password=`…), the entire turn skips both recall and +recording, even with `record: false`, so read-only recall cannot upload it. +Historical text that matches the same check is replaced with the fixed marker +`[credential omitted]` in the slimmed copy, preserving the message structure. +A later ordinary user turn can recall and record normally; a credential in +history does not disable memory for the rest of the conversation. The original +request sent to the model is untouched by this sanitization. A credential in +the completed reply's retained text or tool arguments still skips recording. +The reply delivered to the client remains unchanged. Each +record is sent once and never retried. + +## Things to know + +- **Don't double up.** If an agent already uses an Aelios gateway as its + upstream, it gets memory there; exclude it here with `agents` or every turn + is recorded twice. +- **Tools.** The plugin adds no tools. For `recall` / `remember` tools, add + Aelios's `/mcp` endpoint in Magpie's **Library › MCP**. +- **Who it serves.** By default only direct requests on this computer + (`local`) and Magpie's own key for your agents (`magpie-key`) are handled. + Other gateway keys (possibly a friend's), remote requests and requests of + unknown origin are left alone unless you set `allowRemote`. +- **Fails open.** If Aelios is slow, down, refuses the key or is too old, the + request goes to the model as it came. After a timeout, connection failure, + 5xx, 404 or 401, recall pauses for `recallBackoffMs` before trying again. A + client that cancels does not count. +- Gemini requests are not supported yet and pass through untouched, as do + Responses requests that continue server-side state + (`previous_response_id`, `conversation`). + +## Options + +| Option | Default | | +|---|---|---| +| `serverUrl` | none | Your Aelios Worker. Without it nothing is sent. HTTPS only (plain HTTP allowed for `localhost`, `127.0.0.1`, `[::1]`); no user, password, query or fragment in the URL. | +| `apiKey` | none | Aelios API key. Without it, the variable named by `apiKeyEnv` is used. Without either, nothing is sent. | +| `apiKeyEnv` | `AELIOS_API_KEY` | Environment variable that holds the key. | +| `identity` | none | Aelios assistant space slug; fallback for unmatched routes. Without routes and when empty, the plugin selects the first authorized assistant whose main models match locally; unmatched requests are not sent. Custom identities must also be authorized and match the model. | +| `routes` | none | Up to 64 identity routes in priority order. Each needs a valid ASCII identity slug (max 64 characters; Aelios reserved slugs excluded) and nonempty `models` and/or `agents` arrays. Model patterns are nonblank strings up to 200 characters; agents are nonblank exact ids. Nonempty routes without a match or explicit `identity` skip recall and recording. | +| `agents` | all | Only these Magpie agent ids, e.g. `["claude","claude-desktop"]`. Empty means all. Other ids include `qwen` and `kimi`; legacy `claude-code` remains supported as an exact id. | +| `recall` | `true` | Recall before each turn. | +| `record` | `false` | Record each turn after the reply. | +| `allowRemote` | `false` | Also handle other gateway keys, remote and unknown origins (recall and record). | +| `gatewayTimeoutMs` | Magpie's 1000 | How long Magpie waits for the hook, 100–10000 ms. Set it to about 5000. | +| `requestTimeoutMs` | `4000` | Deadline of one recall request to Aelios, 50–9000 ms, kept just under `gatewayTimeoutMs`. Records have their own 10 s. | +| `recallBackoffMs` | `30000` | After a failure, how long recall is paused (0 turns the pause off). | +| `port` | `3481` | Loopback port of the settings page's connection test. Change it only if that port is taken. | + +Invalid options make the hook stand aside (*invalid*); the key never appears +in a report or error. + +## Status codes + +Magpie's Plugins page shows one code per request, never any content: +`ready` (memory added, with its size), `empty` (nothing relevant), +`unbound` (not a main model, or the key has no such assistant), +`unauthorized` (Aelios refused the key, or there is none), `unavailable` +(timeout, 5xx, missing hook endpoints or authorized matching list, or paused after a failure), +`invalid` (bad options or an answer the plugin can't read) and `skipped` +(origin or agent not handled, a tool step, Gemini, server-side Responses +state). + +## Development + +```sh +bun test ./*.test.mjs # Aelios faked with fetch; no network, no key +``` + +The settings page is `page/settings.html` with `page/settings.js`, `page/form.js`, +`page/style.css` and `page/i18n.js`; the connection test is `service.mjs` and +`probe.mjs`. `page.test.mjs` drives the browser script in a small `node:vm` +harness, so the form's validation, the option merge and the save/test paths are +covered without a browser. Magpie frames a page with `allow-scripts` but not +`allow-forms`, so saving is a button click and never a form submit. diff --git a/packages/aelios/admission.test.mjs b/packages/aelios/admission.test.mjs new file mode 100644 index 0000000..f77c35d --- /dev/null +++ b/packages/aelios/admission.test.mjs @@ -0,0 +1,219 @@ +import { afterEach, beforeEach, expect, test } from "bun:test" +import { flush, onRequest, onResponse, reset } from "./aelios.hooks.mjs" + +const originalFetch = globalThis.fetch +const originalNow = Date.now +let calls, metadata +const identity = (slug = "default", mainModels = ["main-*"]) => ({ slug, name: slug, mainModels }) +const bodyFor = (protocol, tool = false) => protocol === "responses" + ? { model: "main-1", input: tool ? [{ type: "function_call_output", call_id: "c", output: "result" }] : "private user dialogue" } + : { model: "main-1", messages: tool + ? protocol === "anthropic" + ? [{ role: "user", content: [{ type: "tool_result", tool_use_id: "c", content: "result" }] }] + : [{ role: "tool", tool_call_id: "c", content: "result" }] + : [{ role: "user", content: "private user dialogue" }] } +function context(protocol = "chat", options = {}, model = "main-1") { + const reports = [] + return { protocol, model, agent: "codex", origin: "local", state: {}, success: true, + options: { serverUrl: "https://aelios.example", apiKey: "synthetic-key", record: true, ...options }, + report: code => reports.push(code), reports } +} +const getCalls = () => calls.filter(c => c.init.method === "GET") +const postCalls = () => calls.filter(c => c.init.method === "POST") +async function turn(c, body = bodyFor(c.protocol)) { + await onRequest(body, c) + onResponse({ choices: [{ message: { content: "answer" } }] }, c) + await flush() +} +beforeEach(() => { + reset() + calls = [] + metadata = () => Response.json({ identities: [identity()] }) + globalThis.fetch = async (url, init) => { + calls.push({ url: String(url), init, body: init.body && JSON.parse(init.body) }) + if (init.method === "GET") return metadata(url, init) + return Response.json(String(url).endsWith("recall") ? { memory: "empty" } : { recorded: true }) + } +}) +afterEach(() => { globalThis.fetch = originalFetch; Date.now = originalNow; reset() }) + +for (const protocol of ["chat", "anthropic", "responses"]) { + for (const mode of ["normal", "recordOnly", "tool"]) { + test(`${protocol} ${mode}: unbound sends metadata only and never records`, async () => { + const c = context(protocol, mode === "recordOnly" ? { recall: false } : {}, "unbound-model") + await turn(c, bodyFor(protocol, mode === "tool")) + expect(getCalls()).toHaveLength(1) + expect(postCalls()).toHaveLength(0) + expect(c.reports).toEqual(["unbound"]) + expect(c.state.aelios).toBeUndefined() + }) + test(`${protocol} ${mode}: admitted identity is pinned for recall and record`, async () => { + const c = context(protocol, mode === "recordOnly" ? { recall: false } : {}) + await turn(c, bodyFor(protocol, mode === "tool")) + expect(getCalls()).toHaveLength(1) + expect(postCalls().length).toBe(mode === "normal" ? 2 : 1) + expect(postCalls().every(call => call.body.identity === "default")).toBe(true) + }) + } +} + +test("automatic selection uses first model match and literal anchored case-insensitive glob with basename", async () => { + metadata = () => Response.json({ identities: [identity("wrong", ["main"]), identity("first", ["MAIN.*"]), identity("second", ["*"])] }) + const c = context("chat", {}, "vendor/main.123") + await turn(c) + expect(postCalls().every(call => call.body.identity === "first")).toBe(true) + reset(); calls.length = 0 + metadata = () => Response.json({ identities: [identity("literal", ["main.+"])] }) + await turn(context("chat", {}, "main.123")) + expect(postCalls()).toHaveLength(0) +}) + +for (const selected of ["absent", "wrong-model"]) { + test(`explicit identity ${selected} cannot borrow another identity's model permission`, async () => { + metadata = () => Response.json({ identities: [identity(), identity("wrong-model", ["other-*"])] }) + const c = context("chat", { identity: selected }) + await turn(c) + expect(postCalls()).toHaveLength(0) + expect(c.reports).toEqual(["unbound"]) + }) +} +test("configured routes select identity before metadata admission", async () => { + metadata = () => Response.json({ identities: [identity(), identity("routed", ["main-*"])] }) + const c = context("chat", { identity: "absent", routes: [{ agents: ["codex"], models: ["main-*"], identity: "routed" }] }) + await turn(c) + expect(postCalls().every(call => call.body.identity === "routed")).toBe(true) + calls.length = 0; reset() + metadata = () => Response.json({ identities: [identity()] }) + await turn(context("chat", c.options)) + expect(postCalls()).toHaveLength(0) +}) + +test("cache shares across selected identities but isolates server and key", async () => { + metadata = () => Response.json({ identities: [identity(), identity("another")] }) + await turn(context()) + await turn(context("chat", { identity: "another" })) + expect(getCalls()).toHaveLength(1) + await turn(context("chat", { apiKey: "second-key" })) + await turn(context("chat", { serverUrl: "https://second.example" })) + expect(getCalls()).toHaveLength(3) + reset() + await turn(context()) + expect(getCalls()).toHaveLength(4) +}) + +test("TTL refresh failure removes cached permission and failure has short backoff", async () => { + let now = originalNow() + Date.now = () => now + await turn(context()) + now += 60_001 + metadata = () => new Response(null, { status: 401 }) + calls.length = 0 + const c = context() + await turn(c) + await turn(context()) + expect(getCalls()).toHaveLength(1) + expect(postCalls()).toHaveLength(0) + expect(c.reports).toEqual(["unauthorized"]) + now += 5001 + metadata = () => Response.json({ identities: [identity()] }) + await turn(context()) + expect(getCalls()).toHaveLength(2) + expect(postCalls()).toHaveLength(2) +}) + +test("concurrent admission deduplicates metadata lookup", async () => { + let release + metadata = () => new Promise(resolve => { release = resolve }) + const a = context(), b = context() + const work = [onRequest(bodyFor("chat"), a), onRequest(bodyFor("chat"), b)] + expect(getCalls()).toHaveLength(1) + release(Response.json({ identities: [identity()] })) + await Promise.all(work) + expect(postCalls()).toHaveLength(2) +}) + +for (const [status, code] of [[401, "unauthorized"], [403, "unbound"], [404, "unavailable"], [500, "unavailable"]]) { + test(`metadata ${status} fails closed with ${code}`, async () => { + metadata = () => new Response(null, { status }) + const c = context() + await turn(c) + expect(postCalls()).toHaveLength(0) + expect(c.reports).toEqual([code]) + }) +} +for (const invalid of [null, {}, { identities: [{}] }, { identities: [identity("x", [3])] }, { identities: [ { slug: "x", mainModels: ["*"] } ] }, { identities: Array(257).fill(identity()) }]) { + test(`malformed metadata ${JSON.stringify(invalid).slice(0, 75)} fails closed`, async () => { + metadata = () => Response.json(invalid) + const c = context() + await turn(c) + expect(postCalls()).toHaveLength(0) + expect(c.reports).toEqual(["invalid"]) + }) +} +test("metadata body has a byte limit", async () => { + metadata = () => new Response(JSON.stringify({ padding: "x".repeat(256 * 1024), identities: [identity()] })) + const c = context() + await turn(c) + expect(postCalls()).toHaveLength(0) + expect(c.reports).toEqual(["invalid"]) +}) +test("metadata request authenticates GET without dialogue and refuses redirects", async () => { + await turn(context("chat", { apiKey: "bearer existing", serverUrl: "https://aelios.example/base" })) + const call = getCalls()[0] + expect(call.url).toBe("https://aelios.example/base/v1/hook/identities") + expect(call.init.headers.Authorization).toBe("bearer existing") + expect(call.init.redirect).toBe("error") + expect(call.init.body).toBeUndefined() +}) +test("missing key sends no metadata or dialogue", async () => { + const c = context("chat", { apiKey: undefined, apiKeyEnv: "AELIOS_ADMISSION_ABSENT_KEY" }) + await turn(c) + expect(calls).toHaveLength(0) + expect(c.reports).toEqual(["unauthorized"]) +}) +for (const stalled of ["fetch", "body"]) { + test(`metadata deadline covers stalled ${stalled}, even if transport ignores abort`, async () => { + let signal + metadata = (_url, init) => { + signal = init.signal + return stalled === "fetch" ? new Promise(() => {}) : new Response(new ReadableStream({ start() {} })) + } + const c = context("chat", { requestTimeoutMs: 50 }) + const start = performance.now() + await turn(c) + expect(performance.now() - start).toBeLessThan(500) + expect(signal.aborted).toBe(true) + expect(postCalls()).toHaveLength(0) + expect(c.reports).toEqual(["unavailable"]) + }) +} +for (const recall of [true, false]) { + test(`admission preserves Claude thinking and signatures in the actual request (recall ${recall})`, async () => { + const body = { model: "main-1", thinking: { type: "enabled", budget_tokens: 4096 }, messages: [ + { role: "assistant", content: [ + { type: "thinking", thinking: "private reasoning", signature: "opaque-signature" }, + { type: "redacted_thinking", data: "opaque-redacted-data" }, + ] }, { role: "user", content: "private user dialogue" }, + ] } + const original = structuredClone(body) + await turn(context("anthropic", { recall }), body) + expect(body).toEqual(original) + reset(); calls.length = 0 + metadata = () => Response.json({ identities: [] }) + await turn(context("anthropic", { recall }), body) + expect(body).toEqual(original) + expect(postCalls()).toHaveLength(0) + }) +} + +test("onResponse keeps admitted identity after cache expiry without metadata", async () => { + const c = context("chat", { recall: false }) + await onRequest(bodyFor("chat"), c) + Date.now = () => originalNow() + 120_000 + metadata = () => { throw new Error("must not refresh on response") } + c.options.identity = "changed-after-admission" + onResponse({ choices: [{ message: { content: "answer" } }] }, c) + await flush() + expect(getCalls()).toHaveLength(1) + expect(postCalls()[0].body.identity).toBe("default") +}) diff --git a/packages/aelios/aelios.hooks.mjs b/packages/aelios/aelios.hooks.mjs new file mode 100644 index 0000000..5fe7f16 --- /dev/null +++ b/packages/aelios/aelios.hooks.mjs @@ -0,0 +1,458 @@ +// Aelios (github.com/wusaki0723/Aelios) long-term memory for every agent +// behind magpie, as a gateway request hook. Before a request goes to its +// model, the user's turn is given what Aelios recalls for it; after the reply, +// and only when `record` is on, the turn is handed to Aelios to remember. +// +// {"serverUrl": "https://.workers.dev", "apiKeyEnv": "AELIOS_API_KEY", +// "identity": "", "agents": [], "recall": true, "record": false, "allowRemote": false, +// "gatewayTimeoutMs": 5000, "requestTimeoutMs": 4000, "recallBackoffMs": 30000} +// +// Aelios decides what a turn is and what to recall (POST /v1/hook/recall) +// and what to keep (POST /v1/hook/record); the hook sends a slimmed copy of +// the request (slim.mjs) and puts the memory it gets back after the last +// user message. Anything that goes wrong leaves the request as it came. +import { createHash } from "node:crypto" +import { aeliosProtocol, appendPatch, hasSecret, humanTurn, lastUserText, serverState, slim, slimReply, spoken } from "./slim.mjs" + +const version = "0.1.0" +const maxResponseBytes = 256 << 10 +const maxRecordBytes = 2 << 20 +const recordTimeoutMs = 10_000 +// magpie's host gives a hook this long when gatewayTimeoutMs isn't set +const hostDefaultTimeoutMs = 1000 +// the host's report() takes byte counts up to this +const maxReportBytes = 32768 +const maxServices = 64 + +// The only codes magpie accepts. An error's own text could hold a key or +// what someone said, so nothing else ever leaves the hook. +class Failure extends Error { + constructor(code) { + super(`Aelios ${code}`) + this.code = code + } +} + +// magpie's Bun host is long-lived: this lasts till the plugin is reloaded. +const backoff = new Map() +const inflight = new Set() +const identitiesCache = new Map() +const identitiesTTL = 60_000 +const identitiesRetryMs = 5000 +export function reset() { + backoff.clear() + inflight.clear() + identitiesCache.clear() +} +// flush waits for the records already sent (tests use it). +export function flush() { + return Promise.allSettled([...inflight]) +} + +export async function onRequest(body, ctx) { + const report = (code, bytes) => { try { ctx.report?.(code, bytes) } catch { /* never fails the request */ } } + // A skipped or invalid request must never reuse an earlier turn's identity. + if (ctx.state) delete ctx.state.aelios + let o + try { + o = options(ctx.options) + } catch { + // the host rolls back and the request goes on as it came + report("invalid") + throw new Failure("invalid") + } + try { + return await recall(body, ctx, o, report) + } catch { + // fail open: whatever happened, the request goes on unchanged + return undefined + } +} + +async function recall(body, ctx, o, report) { + if (!o || !allowed(ctx, o)) { + report("skipped") + return + } + const protocol = aeliosProtocol(ctx.protocol) + if (!protocol || !body || typeof body !== "object") { + report("skipped") + return + } + const slimmed = slim(body, protocol) + if (hasSecret(lastUserText(slimmed, protocol))) { + if (ctx.state) delete ctx.state.aelios + report("skipped") + return + } + const original = payload(ctx, o, protocol, slimmed, body) + const route = o.routes?.find((r) => + (!r.agents || r.agents.includes(original.agent)) && + (!r.models || r.models.some((pattern) => modelMatches(pattern, original.model)))) + if (route) original.identity = route.identity + else if (o.routes?.length && !o.identity) { + report("skipped") + return + } + if (!o.apiKey) { + report("unauthorized") + return + } + // Admission carries no dialogue. Bound metadata and recall together to the + // request budget, including record-only requests and tool continuations. + const deadline = Math.max(50, Math.min(o.requestTimeoutMs, (o.gatewayTimeoutMs ?? hostDefaultTimeoutMs) - 50)) + const started = Date.now() + const metadata = await authorizedIdentities(o, deadline) + ctx.signal?.throwIfAborted() + if (metadata.code) { + report(metadata.code) + return + } + const identity = metadata.identities.find((item) => + (!original.identity || item.slug === original.identity) && + item.mainModels.some((pattern) => modelMatches(pattern, original.model))) + if (!identity) { + report("unbound") + return + } + // Fix the selection for recall AND record: the server's ordering can change. + original.identity = identity.slug + if (ctx.state) ctx.state.aelios = { admitted: true, protocol, slimmed, payload: original } + o = { ...o, identity: original.identity } + if (serverState(body, protocol) || !humanTurn(slimmed, protocol) || !o.recall) { + report("skipped") + return + } + const key = serviceKey(o) + if ((backoff.get(key) ?? 0) > Date.now()) { + report("unavailable") + return + } + const remaining = deadline - (Date.now() - started) + if (remaining <= 0) { + report("unavailable") + return + } + let r + try { + r = await post(o, "v1/hook/recall", { ...original, record: o.record }, ctx.signal, remaining) + } catch (error) { + if (ctx.signal?.aborted) return // the client went away: not Aelios's failure + trip(key, o) + report("unavailable") + return + } + if (r.status === 401) { + trip(key, o) + report("unauthorized") + return + } + if (r.status === 403) { + report("unbound") + return + } + if (r.status === 404 || r.status >= 500) { + // 404: an Aelios without the hook endpoints + trip(key, o) + report("unavailable") + return + } + if (r.status < 200 || r.status >= 300 || !r.body || typeof r.body !== "object") { + report("invalid") + return + } + const { memory, patch } = r.body + if (memory === "off") { + report("unbound") + return + } + if (memory === "skipped" || memory === "stateful") { + report("skipped") + return + } + if (memory === "unavailable") { + report("unavailable") + return + } + if (memory === "empty" || (memory === "injected" && (typeof patch !== "string" || !patch.trim()))) { + report("empty") + return + } + if (memory !== "injected" || typeof patch !== "string") { + report("invalid") + return + } + ctx.signal?.throwIfAborted() + if (!appendPatch(body, protocol, patch)) { + report("empty") + return + } + report("ready", Math.min(utf8(patch), maxReportBytes)) + return body +} + +export function onResponse(reply, ctx) { + const report = (code, bytes) => { try { ctx.report?.(code, bytes) } catch { /* nothing to fail */ } } + try { + const state = ctx.state?.aelios + if (!state?.admitted || !state.payload?.identity) return + let o + try { o = options(ctx.options) } catch { return } + if (!o || !o.record || !allowed(ctx, o) || !o.apiKey) { + report("skipped") + return + } + const recordedReply = slimReply(reply, state.protocol) + if (hasSecret(lastUserText(state.slimmed, state.protocol)) || hasSecret(spoken(recordedReply))) { + report("skipped") + return + } + const body = { + ...state.payload, + reply: recordedReply, + success: ctx.success === true, + } + if (typeof reply?.model === "string" && reply.model) body.upstream_model = reply.model + let size + try { size = utf8(JSON.stringify(body)) } catch { return } + if (size > maxRecordBytes) { + report("skipped") + return + } + // Fire and forget, on a deadline of its own rather than the request's: + // the host doesn't wait for it, and it is sent once, never retried. + const sent = post(o, "v1/hook/record", body, undefined, recordTimeoutMs).then((r) => { + if (r.status === 401) report("unauthorized") + else if (r.status === 403 || r.body?.reason === "off") report("unbound") + else if (r.status >= 200 && r.status < 300 && r.body?.recorded === true) report("ready", Math.min(size, maxReportBytes)) + else if (r.status >= 200 && r.status < 300) report("skipped") + else report("unavailable") + }, () => report("unavailable")).finally(() => inflight.delete(sent)) + inflight.add(sent) + } catch { + // nothing here can change what the client got + } +} + +function allowed(ctx, o) { + if (o.agents && !o.agents.includes(ctx.agent)) return false + if (ctx.origin === "local" || ctx.origin === "magpie-key") return true + // other gateway keys (maybe a friend's), remote and unknown origins + return o.allowRemote +} + +function payload(ctx, o, protocol, slimmed, body) { + const out = { protocol } + const model = typeof ctx.model === "string" && ctx.model ? ctx.model : typeof body?.model === "string" ? body.model : undefined + if (model) out.model = model + if (typeof ctx.agent === "string" && ctx.agent) out.agent = ctx.agent + if (typeof ctx.session === "string" && ctx.session) out.session = ctx.session + if (o.identity) out.identity = o.identity + out.body = slimmed + return out +} + +// Only '*' is special; punctuation in a model name is always literal. +function modelMatches(pattern, model) { + if (!model) return false + const regex = new RegExp("^" + pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*") + "$", "i") + return regex.test(model) || regex.test(model.slice(model.lastIndexOf("/") + 1)) +} + +function options(raw = {}, env = process.env) { + raw = raw && typeof raw === "object" ? raw : {} + const text = (v) => { + if (v === undefined || v === null || v === "") return undefined + if (typeof v !== "string" || !v.trim()) throw new Failure("invalid") + return v.trim() + } + const bool = (name, fallback) => { + if (raw[name] === undefined || raw[name] === null) return fallback + if (typeof raw[name] !== "boolean") throw new Failure("invalid") + return raw[name] + } + const int = (name, fallback, min, max) => { + const v = raw[name] ?? fallback + if (v === undefined) return undefined + if (!Number.isInteger(v) || v < min || v > max) throw new Failure("invalid") + return v + } + const serverUrl = text(raw.serverUrl) + // validated even without a server, so a mistake shows up at once + const recall = bool("recall", true) + const record = bool("record", false) + const allowRemote = bool("allowRemote", false) + const gatewayTimeoutMs = int("gatewayTimeoutMs", undefined, 100, 10_000) + const requestTimeoutMs = int("requestTimeoutMs", 4000, 50, 9000) + const recallBackoffMs = int("recallBackoffMs", 30_000, 0, 3_600_000) + let agents + if (raw.agents !== undefined && raw.agents !== null) { + if (!Array.isArray(raw.agents) || !raw.agents.every((a) => typeof a === "string" && a.trim())) throw new Failure("invalid") + agents = raw.agents.length ? raw.agents.map((a) => a.trim()) : undefined + } + const identity = text(raw.identity) + if (identity !== undefined && identity.length > 128) throw new Failure("invalid") + let routes + if (raw.routes !== undefined) { + if (!Array.isArray(raw.routes) || raw.routes.length > 64) throw new Failure("invalid") + routes = raw.routes.map((route) => { + if (!route || typeof route !== "object" || Array.isArray(route) || + typeof route.identity !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(route.identity) || + ["v1", "api", "admin", "health", "mcp", "memory-mcp", "memory-admin", "guide-dog"].includes(route.identity.toLowerCase())) + throw new Failure("invalid") + const selectors = {} + for (const name of ["models", "agents"]) { + if (route[name] === undefined) continue + if (!Array.isArray(route[name]) || !route[name].length || + !route[name].every((v) => typeof v === "string" && v.trim() && (name !== "models" || v.length <= 200))) + throw new Failure("invalid") + selectors[name] = route[name].map((v) => v.trim()) + } + if (!selectors.models && !selectors.agents) throw new Failure("invalid") + return { identity: route.identity, ...selectors } + }) + } + const apiKeyEnv = text(raw.apiKeyEnv) ?? "AELIOS_API_KEY" + const apiKey = text(raw.apiKey) ?? text(env[apiKeyEnv]) + if (!serverUrl) return + let server + try { + server = new URL(serverUrl) + } catch { + throw new Failure("invalid") + } + // a key is never sent in clear text to another machine, kept in a URL + // that logs show, or followed through a redirect + const local = ["localhost", "127.0.0.1", "[::1]"].includes(server.hostname) + if (server.username || server.password || server.search || server.hash || + !(server.protocol === "https:" || (server.protocol === "http:" && local))) + throw new Failure("invalid") + server.pathname = server.pathname.replace(/\/+$/, "") + "/" + return { server, apiKey, identity, routes, agents, recall, record, allowRemote, gatewayTimeoutMs, requestTimeoutMs, recallBackoffMs } +} + +// Cache authorization by service and credential, never by a selected identity. +// Failed refreshes replace stale permissions and retry after a short backoff. +async function authorizedIdentities(o, timeoutMs) { + const key = createHash("sha256").update([o.server.href, o.apiKey].join("\0")).digest("hex") + let entry = identitiesCache.get(key) + if (!entry || (!entry.pending && entry.expires <= Date.now())) { + entry = { pending: true } + identitiesCache.set(key, entry) + entry.promise = fetchIdentities(o, timeoutMs).then((result) => { + entry.pending = false + entry.expires = Date.now() + (result.code ? identitiesRetryMs : identitiesTTL) + return result + }) + while (identitiesCache.size > maxServices) identitiesCache.delete(identitiesCache.keys().next().value) + } + // An already pending lookup may have a longer deadline than this caller. + let timer + try { + return await Promise.race([entry.promise, new Promise((resolve) => { + timer = setTimeout(() => resolve({ code: "unavailable" }), timeoutMs) + })]) + } finally { clearTimeout(timer) } +} + +async function fetchIdentities(o, timeoutMs) { + const controller = new AbortController() + let timer + const work = async () => { + const r = await fetch(new URL("v1/hook/identities", o.server), { + method: "GET", redirect: "error", signal: controller.signal, + headers: { Authorization: /^bearer\s/i.test(o.apiKey) ? o.apiKey : `Bearer ${o.apiKey}`, "User-Agent": `magpie-aelios/${version}` }, + }) + if (controller.signal.aborted) { + r.body?.cancel().catch(() => {}) + return { code: "unavailable" } + } + if (r.status !== 200) { + r.body?.cancel().catch(() => {}) + return { code: r.status === 401 ? "unauthorized" : r.status === 403 ? "unbound" : r.status === 404 || r.status === 429 || r.status >= 500 ? "unavailable" : "invalid" } + } + const data = await json(r, controller.signal) + if (!data || !Array.isArray(data.identities) || data.identities.length > 256) return { code: "invalid" } + const identities = [] + for (const item of data.identities) { + if (!item || typeof item.slug !== "string" || !item.slug || item.slug.length > 128 || + typeof item.name !== "string" || item.name.length > 512 || + !Array.isArray(item.mainModels) || item.mainModels.length > 256 || + !item.mainModels.every((model) => typeof model === "string" && model.length <= 512)) return { code: "invalid" } + identities.push({ slug: item.slug, mainModels: [...item.mainModels] }) + } + return { identities } + } + try { + return await Promise.race([work(), new Promise((resolve) => { + timer = setTimeout(() => { controller.abort(); resolve({ code: "unavailable" }) }, timeoutMs) + })]) + } catch { return { code: "unavailable" } } + finally { clearTimeout(timer) } +} + +// post sends JSON to the configured server only and reads at most 256 KiB +// of the answer. It throws only when no answer came (network, deadline, +// cancellation, an answer cut off); any status comes back. +async function post(o, route, body, signal, timeoutMs) { + const own = new AbortController() + const timer = setTimeout(() => own.abort(), timeoutMs) + timer.unref?.() + const combined = signal ? AbortSignal.any([signal, own.signal]) : own.signal + try { + combined.throwIfAborted() + const headers = { "Content-Type": "application/json", "User-Agent": `magpie-aelios/${version}` } + headers.Authorization = /^bearer\s/i.test(o.apiKey) ? o.apiKey : `Bearer ${o.apiKey}` + const r = await fetch(new URL(route, o.server), { method: "POST", headers, body: JSON.stringify(body), signal: combined, redirect: "error" }) + if (r.status < 200 || r.status >= 300) { + try { await r.body?.cancel() } catch { /* already gone */ } + return { status: r.status, body: undefined } + } + return { status: r.status, body: await json(r) } + } finally { + clearTimeout(timer) + } +} + +async function json(r, signal) { + const reader = r.body?.getReader() + if (!reader) return undefined + const cancel = () => { reader.cancel().catch(() => {}) } + signal?.addEventListener("abort", cancel, { once: true }) + const chunks = [] + let size = 0 + try { + if (Number(r.headers.get("content-length")) > maxResponseBytes) { + cancel() + return undefined + } + for (;;) { + signal?.throwIfAborted() + const { value, done } = await reader.read() + if (done) break + size += value.byteLength + if (size > maxResponseBytes) { + try { await reader.cancel() } catch { /* already gone */ } + return undefined + } + chunks.push(value) + } + } finally { + signal?.removeEventListener("abort", cancel) + try { reader.releaseLock() } catch { /* released */ } + } + try { + return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))) + } catch { + return undefined + } +} + +function trip(key, o) { + if (!o.recallBackoffMs) return + backoff.delete(key) + backoff.set(key, Date.now() + o.recallBackoffMs) + while (backoff.size > maxServices) backoff.delete(backoff.keys().next().value) +} +function serviceKey(o) { return createHash("sha256").update([o.server.href, o.apiKey ?? "", o.identity ?? ""].join("\0")).digest("hex") } +function utf8(text) { return Buffer.byteLength(text, "utf8") } diff --git a/packages/aelios/aelios.test.mjs b/packages/aelios/aelios.test.mjs new file mode 100644 index 0000000..9cfef73 --- /dev/null +++ b/packages/aelios/aelios.test.mjs @@ -0,0 +1,821 @@ +// Runs the hook the way magpie's gateway calls it, against an Aelios faked +// with fetch: no server, no key of anyone's and no network. +import { afterEach, beforeEach, expect, test } from "bun:test" +import { flush, onRequest, onResponse, reset } from "./aelios.hooks.mjs" + +const realFetch = globalThis.fetch +const KEY = "synthetic-aelios-key" +const PATCH = "synthetic recalled fact" +const calls = [] +const identitySlugs = [ + "default", "magpie-test", "gpt-husband", "claude-husband", "selected", + "wrong-model", "wrong-agent-case", "first", "second", "agent-only", "fallback", + "stale", "changed", "changed-default", "valid", +] +const metadata = () => Response.json({ identities: identitySlugs.map((slug) => ({ slug, name: slug, mainModels: ["*"] })) }) +let routes = {} + +function mock(extra = {}) { + routes = { + "/v1/hook/identities": metadata, + "/v1/hook/recall": () => Response.json({ memory: "injected", patch: PATCH, recall_id: "rcl_1", remember: "none" }), + "/v1/hook/record": () => Response.json({ recorded: true, exchange_id: "gw_req_1", completion: "complete" }), + ...extra, + } + globalThis.fetch = async (url, init = {}) => { + const path = new URL(String(url)).pathname + const body = typeof init.body === "string" ? JSON.parse(init.body) : undefined + calls.push({ url: String(url), path, init, body }) + if (!routes[path]) throw new Error(`unexpected ${path}`) + return routes[path](body, init) + } +} +const of = (path) => calls.filter((c) => c.path === path) +const dialogue = () => calls.filter((c) => /\/v1\/hook\/(recall|record)$/.test(c.path)) +function checkMetadata(path = "/v1/hook/identities", key = KEY) { + const [call] = of(path) + expect(of(path)).toHaveLength(1) + expect(call.init.method).toBe("GET") + expect(call.init.redirect).toBe("error") + expect(call.init.headers.Authorization).toBe(`Bearer ${key}`) + expect(call.init.body).toBeUndefined() + expect(call.body).toBeUndefined() +} +const hang = (_body, init) => new Promise((_, reject) => init.signal.addEventListener("abort", () => reject(init.signal.reason))) + +function ctx(protocol, extra = {}) { + const reports = [] + const c = { + protocol, model: "claude-opus-4-5", stream: true, path: "/v1/messages", origin: "local", agent: "claude", + session: "session-a", cwd: "/tmp/x", query: "", state: {}, signal: new AbortController().signal, + report: (code, bytes) => reports.push(bytes === undefined ? [code] : [code, bytes]), + ...extra, + options: { serverUrl: "https://aelios.example.workers.dev", apiKey: KEY, ...extra.options }, + } + return [c, reports] +} + +beforeEach(() => reset()) +afterEach(() => { globalThis.fetch = realFetch; calls.length = 0 }) + +const anthropicString = () => ({ model: "claude-opus-4-5", stream: true, system: "sys", tools: [{ name: "Bash", input_schema: {} }], tool_choice: { type: "auto" }, + messages: [{ role: "user", content: "earlier" }, { role: "assistant", content: "ok" }, { role: "user", content: "Where do I live?" }] }) +const anthropicArray = () => ({ model: "claude-opus-4-5", stream: true, + messages: [{ role: "user", content: [{ type: "text", text: "env" }, { type: "text", text: "Where do I live?", cache_control: { type: "ephemeral" } }] }] }) +const chat = () => ({ model: "gpt-5", stream: false, tools: [{ type: "function", function: { name: "f", parameters: {} } }], tool_choice: "auto", + messages: [{ role: "system", content: "sys" }, { role: "user", content: "Where do I live?" }] }) +const responsesString = () => ({ model: "gpt-5", stream: true, instructions: "x", input: "Where do I live?" }) +const responsesArray = () => ({ model: "gpt-5", stream: true, input: [{ type: "message", role: "user", content: [{ type: "input_text", text: "Where do I live?" }] }] }) +const anthropicTool = () => ({ model: "claude-opus-4-5", stream: true, messages: [ + { role: "user", content: "Fix it" }, + { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Bash", input: { command: "ls" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "a.ts b.ts" }] }, +] }) + +test("the shipped hook and settings service use separate host entry points", async () => { + const pkg = await Bun.file(new URL("./package.json", import.meta.url)).json() + expect(pkg.name).toBe("@magpie-community/gateway-aelios") + expect(pkg.main).toBe("./service.mjs") + expect(pkg.magpie.page.file).toBe("page/settings.html") + expect(pkg.magpie.page.service).toEqual({ port: 3481, option: "port" }) + expect(pkg.exports).toBeUndefined() + expect(pkg.magpie.middleware).toBeUndefined() + expect(pkg.magpie.gateway).toBeUndefined() + expect(pkg.magpie.hooks).toBe("./aelios.hooks.mjs") + expect(Object.hasOwn(pkg.magpie.options, "serverUrl")).toBe(false) + expect(pkg.files).toEqual(["aelios.hooks.mjs", "slim.mjs", "service.mjs", "probe.mjs", "page", "README.md"]) + const entry = await import(pkg.magpie.hooks) + expect(entry.onRequest).toBe(onRequest) + expect(entry.onResponse).toBe(onResponse) +}) + +const placements = [ + ["anthropic", "messages string", anthropicString, (b) => b.messages[2].content, (v) => expect(v).toBe(`Where do I live?\n\n${PATCH}`)], + ["anthropic", "messages array", anthropicArray, (b) => b.messages[0].content, (v) => expect(v).toEqual([ + { type: "text", text: "env" }, + { type: "text", text: "Where do I live?", cache_control: { type: "ephemeral" } }, + { type: "text", text: PATCH }, + ])], + ["chat", "chat", chat, (b) => b.messages[1].content, (v) => expect(v).toBe(`Where do I live?\n\n${PATCH}`)], + ["responses", "responses string input", responsesString, (b) => b.input, (v) => expect(v).toBe(`Where do I live?\n\n${PATCH}`)], + ["responses", "responses array input", responsesArray, (b) => b.input[0].content, (v) => expect(v).toEqual([ + { type: "input_text", text: "Where do I live?" }, { type: "input_text", text: PATCH }])], +] + +for (const [protocol, name, make, pick, check] of placements) { + test(`${name}: memory goes after the last user message; model, stream and tools stay`, async () => { + mock() + const original = make() + const [c, reports] = ctx(protocol) + const out = await onRequest(structuredClone(original), c) + expect(out).toBeDefined() + check(pick(out)) + // what the host would roll back on + for (const key of ["model", "stream", "tools", "tool_choice"]) expect(JSON.stringify(out[key])).toBe(JSON.stringify(original[key])) + // everything before the last message is untouched + if (original.messages) expect(out.messages.slice(0, -1)).toEqual(original.messages.slice(0, -1)) + expect(reports).toEqual([["ready", Buffer.byteLength(PATCH)]]) + checkMetadata() + expect(calls).toHaveLength(2) + expect(calls[0].path).toBe("/v1/hook/identities") + const [call] = of("/v1/hook/recall") + expect(call.body.identity).toBe("default") + expect(call.url).toBe("https://aelios.example.workers.dev/v1/hook/recall") + expect(call.init.method).toBe("POST") + expect(call.init.redirect).toBe("error") + expect(call.init.headers.Authorization).toBe(`Bearer ${KEY}`) + expect(call.body.protocol).toBe({ anthropic: "messages", chat: "chat", responses: "responses" }[protocol]) + expect(call.body.model).toBe("claude-opus-4-5") + expect(call.body.agent).toBe("claude") + expect(call.body.session).toBe("session-a") + // slimmed: no system prompt or instructions travel + expect(JSON.stringify(call.body.body)).not.toContain('"sys"') + expect(call.body.body.system).toBeUndefined() + expect(call.body.body.instructions).toBeUndefined() + expect(c.state.aelios.slimmed).toEqual(call.body.body) + }) +} + +test("identity and a server path prefix are passed through", async () => { + mock({ "/base/v1/hook/identities": metadata, "/base/v1/hook/recall": () => Response.json({ memory: "empty", patch: "" }) }) + const [c, reports] = ctx("anthropic", { options: { serverUrl: "https://a.example/base/", identity: "magpie-test" } }) + expect(await onRequest(anthropicString(), c)).toBeUndefined() + checkMetadata("/base/v1/hook/identities") + expect(of("/base/v1/hook/identities")[0].url).toBe("https://a.example/base/v1/hook/identities") + expect(of("/base/v1/hook/recall")[0].body.identity).toBe("magpie-test") + expect(reports).toEqual([["empty"]]) +}) + +test("the key can come from AELIOS_API_KEY or a named variable", async () => { + mock() + process.env.AELIOS_TEST_KEY = "from-env" + try { + const [c] = ctx("chat", { options: { apiKey: undefined, apiKeyEnv: "AELIOS_TEST_KEY" } }) + await onRequest(chat(), c) + checkMetadata("/v1/hook/identities", "from-env") + expect(of("/v1/hook/recall")[0].init.headers.Authorization).toBe("Bearer from-env") + } finally { + delete process.env.AELIOS_TEST_KEY + } +}) + +test("no key: nothing is sent", async () => { + mock() + const [c, reports] = ctx("chat", { options: { apiKey: undefined, apiKeyEnv: "AELIOS_NOT_SET_ANYWHERE" } }) + expect(await onRequest(chat(), c)).toBeUndefined() + expect(calls).toHaveLength(0) + expect(reports).toEqual([["unauthorized"]]) +}) + +test("a tool step sends no recall, and onResponse records it", async () => { + mock() + const [c, reports] = ctx("anthropic", { options: { record: true } }) + const req = anthropicTool() + expect(await onRequest(structuredClone(req), c)).toBeUndefined() + checkMetadata() + expect(calls).toHaveLength(1) + expect(dialogue()).toHaveLength(0) + expect(reports).toEqual([["skipped"]]) + const reply = { id: "msg_1", type: "message", role: "assistant", model: "claude-opus-4-5-20260101", content: [{ type: "text", text: "Two files." }], stop_reason: "end_turn" } + onResponse(reply, { ...c, success: true, request: req }) + await flush() + const [rec] = of("/v1/hook/record") + expect(rec.body).toEqual({ + protocol: "messages", model: "claude-opus-4-5", agent: "claude", session: "session-a", identity: "default", + body: c.state.aelios.slimmed, + reply: { model: reply.model, content: reply.content, stop_reason: reply.stop_reason }, + success: true, upstream_model: "claude-opus-4-5-20260101", + }) + expect(rec.body.body.messages[2].content).toEqual([{ type: "tool_result", content: "" }]) + expect(reports.at(-1)[0]).toBe("ready") +}) + +for (const record of [undefined, false, true]) { + test(`recall explicitly sends recording permission (${record ?? "default"})`, async () => { + mock() + const [c] = ctx("chat", { options: record === undefined ? {} : { record } }) + await onRequest(chat(), c) + expect(of("/v1/hook/recall")[0].body.record).toBe(record === true) + }) +} + +for (const record of [false, true]) { + test(`credentials prevent both recall and response export (record ${record})`, async () => { + mock() + const [c, reports] = ctx("chat", { options: { record } }) + // Even stale request state must not allow an onResponse export. + c.state.aelios = { protocol: "chat", slimmed: { messages: [] } } + const req = { messages: [{ role: "user", content: "password=synthetic-review-only" }] } + expect(await onRequest(req, c)).toBeUndefined() + expect(c.state.aelios).toBeUndefined() + onResponse({ choices: [{ message: { content: "ok" } }] }, { ...c, success: true }) + await flush() + expect(calls).toHaveLength(0) + expect(reports).toEqual([["skipped"]]) + }) +} + +test("transport-wrapped human speech reaches recall and receives memory", async () => { + mock() + const [c] = ctx("chat") + const text = 'What is my favorite food?' + const req = { messages: [{ role: "user", content: text }] } + expect(await onRequest(req, c)).toBeDefined() + expect(of("/v1/hook/recall")).toHaveLength(1) + expect(req.messages[0].content).toBe(`${text}\n\n${PATCH}`) +}) + +test("record is off by default: onResponse sends nothing", async () => { + mock() + const [c] = ctx("chat") + await onRequest(chat(), c) + calls.length = 0 + onResponse({ choices: [{ message: { role: "assistant", content: "Paris" } }] }, { ...c, success: true }) + await flush() + expect(calls).toHaveLength(0) +}) + +test("a failed reply is still recorded, with success false", async () => { + mock() + const [c] = ctx("chat", { options: { record: true } }) + await onRequest(chat(), c) + onResponse(null, { ...c, success: false }) + await flush() + const [rec] = of("/v1/hook/record") + expect(rec.body.success).toBe(false) + expect(rec.body.reply).toBeNull() +}) + +test("a turn with a secret in it is not recorded", async () => { + mock() + const [c, reports] = ctx("chat", { options: { record: true } }) + const req = { ...chat(), messages: [{ role: "user", content: "my api_key = sk-abcdefghijklmnopqrstu please store it" }] } + await onRequest(req, c) + onResponse({ choices: [{ message: { role: "assistant", content: "ok" } }] }, { ...c, success: true }) + await flush() + expect(of("/v1/hook/record")).toHaveLength(0) + expect(reports.at(-1)).toEqual(["skipped"]) + // and a secret in the reply too + const [c2] = ctx("chat", { options: { record: true } }) + await onRequest(chat(), c2) + onResponse({ choices: [{ message: { role: "assistant", content: "use ghp_abcdefghijklmnopqrstuvwxyz0123" } }] }, { ...c2, success: true }) + await flush() + expect(of("/v1/hook/record")).toHaveLength(0) +}) + +test("a record that fails is not retried and changes nothing", async () => { + mock({ "/v1/hook/record": () => new Response("down", { status: 503 }) }) + const [c, reports] = ctx("chat", { options: { record: true } }) + await onRequest(chat(), c) + expect(onResponse({ choices: [] }, { ...c, success: true })).toBeUndefined() + await flush() + expect(of("/v1/hook/record")).toHaveLength(1) + expect(reports.at(-1)).toEqual(["unavailable"]) +}) + +for (const origin of ["gateway-key", "remote", undefined]) { + test(`origin ${origin}: nothing is sent unless allowRemote`, async () => { + mock() + const [c, reports] = ctx("chat", { origin, options: { record: true } }) + expect(await onRequest(chat(), c)).toBeUndefined() + onResponse({ choices: [] }, { ...c, success: true }) + await flush() + expect(calls).toHaveLength(0) + expect(reports[0]).toEqual(["skipped"]) + + const [c2] = ctx("chat", { origin, options: { record: true, allowRemote: true } }) + expect(await onRequest(chat(), c2)).toBeDefined() + onResponse({ choices: [] }, { ...c2, success: true }) + await flush() + expect(of("/v1/hook/recall")).toHaveLength(1) + expect(of("/v1/hook/record")).toHaveLength(1) + }) +} + +test("magpie-key, magpie's own key on this computer, counts as the owner's", async () => { + mock() + const [c] = ctx("chat", { origin: "magpie-key" }) + expect(await onRequest(chat(), c)).toBeDefined() +}) + +test("agents limits which agents are handled", async () => { + mock() + const [c, reports] = ctx("chat", { agent: "codex", options: { agents: ["claude"], record: true } }) + expect(await onRequest(chat(), c)).toBeUndefined() + onResponse({ choices: [] }, { ...c, success: true }) + await flush() + expect(calls).toHaveLength(0) + expect(reports).toEqual([["skipped"]]) + const [c2] = ctx("chat", { agent: "claude", options: { agents: ["claude"] } }) + expect(await onRequest(chat(), c2)).toBeDefined() + const [c3] = ctx("chat", { agent: "codex", options: { agents: [] } }) + expect(await onRequest(chat(), c3)).toBeDefined() +}) + +test("no serverUrl: nothing is sent", async () => { + mock() + const [c, reports] = ctx("chat", { options: { serverUrl: undefined, record: true } }) + expect(await onRequest(chat(), c)).toBeUndefined() + onResponse({ choices: [] }, { ...c, success: true }) + await flush() + expect(calls).toHaveLength(0) + expect(reports).toEqual([["skipped"]]) +}) + +test("gemini is skipped", async () => { + mock() + const [c, reports] = ctx("gemini") + expect(await onRequest({ contents: [{ role: "user", parts: [{ text: "hi" }] }] }, c)).toBeUndefined() + expect(calls).toHaveLength(0) + expect(reports).toEqual([["skipped"]]) + expect(c.state.aelios).toBeUndefined() +}) + +test("a Responses request that continues server-side state is skipped", async () => { + mock() + const [c, reports] = ctx("responses") + expect(await onRequest({ ...responsesString(), previous_response_id: "resp_1" }, c)).toBeUndefined() + checkMetadata() + expect(calls).toHaveLength(1) + expect(dialogue()).toHaveLength(0) + expect(reports).toEqual([["skipped"]]) +}) + +test("recall off: no recall request", async () => { + mock() + const [c] = ctx("chat", { options: { recall: false } }) + expect(await onRequest(chat(), c)).toBeUndefined() + checkMetadata() + expect(calls).toHaveLength(1) + expect(dialogue()).toHaveLength(0) +}) + +test("bad options throw invalid (the host rolls back) without the key in the error", async () => { + mock() + for (const options of [ + { serverUrl: "http://aelios.example.com" }, + { serverUrl: "https://user:pw@aelios.example.com" }, + { serverUrl: "https://aelios.example.com/?k=1" }, + { serverUrl: "https://aelios.example.com/#x" }, + { serverUrl: "not a url" }, + { requestTimeoutMs: 10 }, + { requestTimeoutMs: 9001 }, + { record: "yes" }, + { agents: "claude" }, + { gatewayTimeoutMs: 50 }, + ]) { + const [c, reports] = ctx("chat", { options }) + let error + try { await onRequest(chat(), c) } catch (e) { error = e } + expect(error?.message).toBe("Aelios invalid") + expect(String(error?.stack)).not.toContain(KEY) + expect(reports).toEqual([["invalid"]]) + } + // plain http is fine on this machine + const [c] = ctx("chat", { options: { serverUrl: "http://127.0.0.1:8787" } }) + routes["/v1/hook/recall"] = () => Response.json({ memory: "empty", patch: "" }) + await onRequest(chat(), c) + expect(of("/v1/hook/recall")[0].url).toBe("http://127.0.0.1:8787/v1/hook/recall") + checkMetadata() + expect(calls).toHaveLength(2) +}) + +const identityRoutes = [ + { models: ["gpt-*"], identity: "gpt-husband" }, + { models: ["claude-*"], identity: "claude-husband" }, +] + +for (const [protocol, model, agent, make, identity] of [ + ["chat", "gpt-5", "codex", chat, "gpt-husband"], + ["anthropic", "claude-opus-4-5", "claude", anthropicString, "claude-husband"], +]) { + test(`${model}: recall and record use its isolated identity`, async () => { + mock({ "/v1/hook/recall": (body) => Response.json({ memory: "injected", patch: `${body.identity}` }) }) + const [c] = ctx(protocol, { model, agent, options: { routes: identityRoutes, record: true } }) + const req = make() + const original = structuredClone(req) + await onRequest(req, c) + onResponse({ content: [{ type: "text", text: "ok" }] }, { ...c, success: true, request: req }) + await flush() + expect(of("/v1/hook/recall")[0].body.identity).toBe(identity) + expect(of("/v1/hook/record")[0].body.identity).toBe(identity) + expect(JSON.stringify(req)).toContain(`${identity}`) + for (const key of ["model", "stream", "tools", "tool_choice", "system", "instructions"]) expect(req[key]).toEqual(original[key]) + expect(of("/v1/hook/record")[0].body.body).toEqual(of("/v1/hook/recall")[0].body.body) + }) +} + +for (const [pattern, model, matches] of [ + ["gpt-*", "provider/nested/GPT-5", true], + ["PROVIDER/*/gpt-*", "provider/nested/gpt-5", true], + ["gpt-*", "other-gpt-5", false], + ["gpt-5", "gpt-5-extra", false], + ["gpt-5.1+test", "gpt-5.1+test", true], + ["gpt-5.1+test", "gpt-5X11test", false], +]) { + test(`model pattern ${pattern} matches ${model}: ${matches}`, async () => { + mock() + const [c] = ctx("chat", { model, options: { routes: [{ models: [pattern], identity: "selected" }] } }) + await onRequest(chat(), c) + expect(dialogue()).toHaveLength(matches ? 1 : 0) + if (matches) { + checkMetadata() + expect(of("/v1/hook/recall")[0].body.identity).toBe("selected") + } else expect(calls).toHaveLength(0) + }) +} + +test("agent and model selectors require AND; the first matching route wins", async () => { + mock() + const routing = [ + { models: ["claude-*"], agents: ["codex"], identity: "wrong-model" }, + { models: ["gpt-*"], agents: ["Codex"], identity: "wrong-agent-case" }, + { models: ["gpt-*"], agents: ["codex"], identity: "first" }, + { models: ["gpt-*"], identity: "second" }, + ] + const [c] = ctx("chat", { model: "gpt-5", agent: "codex", options: { routes: routing } }) + await onRequest(chat(), c) + expect(of("/v1/hook/recall")[0].body.identity).toBe("first") + const [agentOnly] = ctx("chat", { model: "other", agent: "codex", options: { routes: [{ agents: ["codex"], identity: "agent-only" }] } }) + await onRequest(chat(), agentOnly) + checkMetadata() + expect(calls).toHaveLength(3) + expect(of("/v1/hook/recall")[1].body.identity).toBe("agent-only") +}) + +for (const identity of [undefined, "fallback"]) { + test(`unmatched routes ${identity ? "use explicit fallback" : "skip recall and record, including stale state"}`, async () => { + mock() + const [c, reports] = ctx("chat", { model: "other", options: { routes: identityRoutes, identity, record: true } }) + c.state.aelios = { payload: { identity: "stale" }, slimmed: {} } + await onRequest(chat(), c) + onResponse({ choices: [] }, { ...c, success: true }) + await flush() + expect(dialogue()).toHaveLength(identity ? 2 : 0) + if (identity) { + checkMetadata() + expect(calls).toHaveLength(3) + for (const call of dialogue()) expect(call.body.identity).toBe(identity) + } + else { + expect(calls).toHaveLength(0) + expect(c.state.aelios).toBeUndefined() + expect(reports).toEqual([["skipped"]]) + } + }) +} + +for (const routes of [undefined, []]) { + test(`routes ${JSON.stringify(routes)} automatically select the first admitted identity`, async () => { + mock() + const [c] = ctx("chat", { options: { routes, record: true } }) + await onRequest(chat(), c) + onResponse({ choices: [] }, { ...c, success: true }) + await flush() + checkMetadata() + expect(calls).toHaveLength(3) + expect(dialogue()).toHaveLength(2) + for (const call of dialogue()) expect(call.body.identity).toBe("default") + }) +} + +for (const [name, make, protocol, model] of [ + ["tool continuation", anthropicTool, "anthropic", "claude-opus-4-5"], + ["recall:false", chat, "chat", "gpt-5"], +]) { + test(`${name} still resolves routing and records with original metadata`, async () => { + mock() + const [c] = ctx(protocol, { model, options: { routes: identityRoutes, record: true, recall: name !== "recall:false" } }) + await onRequest(make(), c) + checkMetadata() + expect(calls).toHaveLength(1) + expect(dialogue()).toHaveLength(0) + onResponse({ choices: [] }, { ...c, success: true }) + await flush() + expect(calls).toHaveLength(2) + expect(dialogue()).toHaveLength(1) + expect(of("/v1/hook/recall")).toHaveLength(0) + expect(of("/v1/hook/record")[0].body.identity).toBe(model.startsWith("gpt") ? "gpt-husband" : "claude-husband") + }) +} + +test("payload is pinned before recall awaits; changed response context and routes cannot redirect recording", async () => { + let release + let entered + const recalling = new Promise((resolve) => { entered = resolve }) + mock({ "/v1/hook/recall": () => new Promise((resolve) => { + release = () => resolve(Response.json({ memory: "empty" })) + entered() + }) }) + const [c] = ctx("chat", { model: "provider/gpt-5", agent: "codex", options: { routes: identityRoutes, record: true } }) + const pending = onRequest(chat(), c) + await recalling + expect(c.state.aelios.payload.identity).toBe("gpt-husband") + c.model = "claude-opus-4-5" + c.agent = "claude" + c.session = "different-session" + c.options.routes = [{ models: ["*"], identity: "changed" }] + c.options.identity = "changed-default" + release() + await pending + c.state = JSON.parse(JSON.stringify(c.state)) + onResponse({ model: "actual-upstream", choices: [] }, { ...c, request: { model: "other" }, success: true }) + await flush() + const { record, ...original } = of("/v1/hook/recall")[0].body + const { reply, success, upstream_model, ...recorded } = of("/v1/hook/record")[0].body + expect(recorded).toEqual(original) + expect(recorded).toMatchObject({ identity: "gpt-husband", model: "provider/gpt-5", agent: "codex", session: "session-a" }) + expect(upstream_model).toBe("actual-upstream") +}) + +for (const change of [{ record: false }, { agents: ["different"] }, { allowRemote: false }]) { + test(`response still checks current permission ${JSON.stringify(change)}`, async () => { + mock() + const [c] = ctx("chat", { model: "gpt-5", options: { routes: identityRoutes, record: true } }) + await onRequest(chat(), c) + onResponse({ choices: [] }, { ...c, origin: "allowRemote" in change ? "remote" : "local", options: { ...c.options, ...change } }) + await flush() + expect(of("/v1/hook/record")).toHaveLength(0) + }) +} + +test("backoff is isolated by resolved identity on the same server and key", async () => { + mock({ "/v1/hook/recall": (body) => body.identity === "gpt-husband" ? new Response("", { status: 503 }) : Response.json({ memory: "empty" }) }) + for (const model of ["gpt-5", "claude-opus-4-5", "gpt-6", "claude-sonnet-4-5"]) { + const [c] = ctx("chat", { model, options: { routes: identityRoutes } }) + await onRequest(chat(), c) + } + checkMetadata() + expect(of("/v1/hook/recall").map((call) => call.body.identity)).toEqual(["gpt-husband", "claude-husband", "claude-husband"]) +}) + +test("invalid routes always fail with a fixed error and zero network, clearing stale state", async () => { + mock() + const valid = { models: ["gpt-*"], identity: "gpt-husband" } + for (const routes of [ + null, {}, "routes", Array(65).fill(valid), [null], [[]], ["route"], [{}], + [{ ...valid, identity: "" }], [{ ...valid, identity: " " }], [{ ...valid, identity: "a".repeat(65) }], + ...["/path", "with space", "é", "_leading", "admin", "V1"].map((identity) => [{ ...valid, identity }]), + [{ identity: "valid" }], [{ ...valid, models: [] }], [{ ...valid, models: "gpt-*" }], + ...[null, 12, "", " ", "x".repeat(201)].map((pattern) => [{ ...valid, models: [pattern] }]), + [{ ...valid, agents: [] }], [{ ...valid, agents: null }], [{ ...valid, agents: [""] }], [{ ...valid, agents: [1] }], + ]) { + const [c, reports] = ctx("chat", { options: { routes, record: true } }) + c.state.aelios = { payload: { identity: "stale" }, slimmed: {} } + await expect(onRequest(chat(), c)).rejects.toThrow("Aelios invalid") + onResponse({ choices: [] }, c) + await flush() + expect(c.state.aelios).toBeUndefined() + expect(reports).toEqual([["invalid"]]) + expect(calls).toHaveLength(0) + } +}) + +const answers = [ + ["401", () => new Response("", { status: 401 }), "unauthorized", true], + ["403", () => new Response("", { status: 403 }), "unbound", false], + ["memory off", () => Response.json({ memory: "off" }), "unbound", false], + ["memory empty", () => Response.json({ memory: "empty", patch: "" }), "empty", false], + ["memory skipped", () => Response.json({ memory: "skipped" }), "skipped", false], + ["memory stateful", () => Response.json({ memory: "stateful" }), "skipped", false], + ["memory unavailable", () => Response.json({ memory: "unavailable", patch: "" }), "unavailable", false], + ["400", () => new Response("", { status: 400 }), "invalid", false], + ["not JSON", () => new Response("", { status: 200 }), "invalid", false], + ["too large", () => new Response("x".repeat((256 << 10) + 1), { status: 200 }), "invalid", false], +] +for (const [name, answer, code, backsOff] of answers) { + test(`${name}: ${code}, the request goes on as it came${backsOff ? ", and recall backs off" : ""}`, async () => { + mock({ "/v1/hook/recall": answer }) + const [c, reports] = ctx("chat") + const req = chat() + expect(await onRequest(structuredClone(req), c)).toBeUndefined() + expect(reports).toEqual([[code]]) + const [c2] = ctx("chat") + await onRequest(chat(), c2) + expect(of("/v1/hook/recall")).toHaveLength(backsOff ? 1 : 2) + }) +} + +const failures = [ + ["a timeout", hang], + ["a 500", () => new Response("", { status: 500 })], + ["a 502", () => new Response("", { status: 502 })], + ["a 404 (Aelios without hook endpoints)", () => new Response("Not found", { status: 404 })], + ["a refused connection", () => { throw new TypeError("connect ECONNREFUSED") }], +] +for (const [name, answer] of failures) { + test(`${name}: unavailable, passes through, backs off, then tries again`, async () => { + mock({ "/v1/hook/recall": answer }) + const options = { requestTimeoutMs: 50, recallBackoffMs: 150 } + const [c, reports] = ctx("chat", { options }) + expect(await onRequest(chat(), c)).toBeUndefined() + expect(reports).toEqual([["unavailable"]]) + // in backoff: nothing sent + const [c2, reports2] = ctx("chat", { options }) + expect(await onRequest(chat(), c2)).toBeUndefined() + expect(of("/v1/hook/recall")).toHaveLength(1) + expect(reports2).toEqual([["unavailable"]]) + // after it: asked again, and a healthy answer is used + await Bun.sleep(170) + routes["/v1/hook/recall"] = () => Response.json({ memory: "injected", patch: PATCH }) + const [c3, reports3] = ctx("chat", { options }) + expect(await onRequest(chat(), c3)).toBeDefined() + expect(of("/v1/hook/recall")).toHaveLength(2) + expect(reports3[0][0]).toBe("ready") + }) +} + +test("the hook's own deadline ends before the host's (default 1000 ms)", async () => { + mock({ "/v1/hook/recall": hang }) + const [c] = ctx("chat", { options: { requestTimeoutMs: 9000, gatewayTimeoutMs: 200 } }) + const started = Date.now() + await onRequest(chat(), c) + expect(Date.now() - started).toBeLessThan(400) +}) + +test("a client that cancels does not trip the backoff", async () => { + mock({ "/v1/hook/recall": hang }) + const ac = new AbortController() + const [c, reports] = ctx("chat", { signal: ac.signal }) + const pending = onRequest(chat(), c) + setTimeout(() => ac.abort(), 10) + expect(await pending).toBeUndefined() + expect(reports).toEqual([]) + routes["/v1/hook/recall"] = () => Response.json({ memory: "injected", patch: PATCH }) + const [c2] = ctx("chat") + expect(await onRequest(chat(), c2)).toBeDefined() + expect(of("/v1/hook/recall")).toHaveLength(2) +}) + +test("only the seven codes magpie accepts are reported, with no content", async () => { + const allowed = new Set(["ready", "empty", "unbound", "unauthorized", "unavailable", "invalid", "skipped"]) + const seen = [] + for (const [, answer] of [...answers, ...failures.slice(1)]) { + reset() + mock({ "/v1/hook/recall": answer }) + const [c, reports] = ctx("chat", { options: { record: true } }) + await onRequest(chat(), c) + onResponse({ choices: [{ message: { content: "x" } }] }, { ...c, success: true }) + await flush() + seen.push(...reports) + } + expect(seen.length).toBeGreaterThan(0) + for (const [code, bytes] of seen) { + expect(allowed.has(code)).toBe(true) + expect(bytes === undefined || (Number.isInteger(bytes) && bytes >= 0 && bytes <= 32768)).toBe(true) + } +}) + +test("a slimmed request is the same at recall and at record, so Aelios hashes one exchange", async () => { + mock() + const [c] = ctx("anthropic", { options: { record: true } }) + const req = anthropicString() + const sent = await onRequest(structuredClone(req), c) + // ctx.request is the request after injection; the record still carries the pre-injection slim copy + onResponse({ content: [{ type: "text", text: "Paris" }] }, { ...c, success: true, request: sent }) + await flush() + expect(JSON.stringify(of("/v1/hook/record")[0].body.body)).toBe(JSON.stringify(of("/v1/hook/recall")[0].body.body)) + expect(JSON.stringify(of("/v1/hook/record")[0].body.body)).not.toContain(PATCH) +}) + + +// The request history is sanitized; fresh speech fields consumed by +// OutputCollector, including speech tool arguments, survive reply slimming. +const privacyProtocols = [ + { + protocol: "anthropic", key: "messages", + calls: [ + { role: "assistant", content: [{ type: "tool_use", name: "Edit", input: { file_path: "/synthetic-private.ts", old_string: "old", new_string: "const token = getToken(req)" } }] }, + { role: "assistant", content: [{ type: "server_tool_use", name: "Write", input: { content: "interface Opts { apiKey: string }; password=synthetic-history-only" } }] }, + ], + reply: (text) => ({ content: [{ type: "tool_use", name: "send_message", input: { text } }] }), + }, + { + protocol: "chat", key: "messages", + calls: [{ role: "assistant", tool_calls: [ + { type: "function", function: { name: "Edit", arguments: '{"new_string":"const token = getToken(req)","file_path":"/synthetic-private.ts"}' } }, + { type: "function", function: { name: "Write", arguments: '{"content":"interface Opts { apiKey: string }; password=synthetic-history-only"}' } }, + ] }], + reply: (text) => ({ choices: [{ message: { tool_calls: [{ type: "function", function: { name: "send_message", arguments: JSON.stringify({ text }) } }] } }] }), + }, + { + protocol: "responses", key: "input", + calls: [ + { type: "function_call", name: "Edit", arguments: '{"new_string":"const token = getToken(req)","file_path":"/synthetic-private.ts"}' }, + { type: "custom_tool_call", name: "Write", input: "interface Opts { apiKey: string }; password=synthetic-history-only" }, + ], + reply: (text) => ({ output: [{ type: "function_call", name: "send_message", arguments: JSON.stringify({ text }) }, { type: "custom_tool_call", name: "send_message", input: text }] }), + }, +] + +for (const { protocol, key, calls: history, reply } of privacyProtocols) { + test(`${protocol}: historical Edit/Write arguments never export; next turn recalls and fresh speech stays intact`, async () => { + mock() + const [c] = ctx(protocol, { options: { record: true } }) + const req = { [key]: [{ role: "user", content: "Fix the code" }, ...history, { role: "user", content: "What is for dinner?" }] } + const before = structuredClone(req) + expect(await onRequest(req, c)).toBeDefined() + const fresh = reply("synthetic speech for the recipient") + const originalReply = structuredClone(fresh) + onResponse(fresh, { ...c, success: true }) + await flush() + expect(of("/v1/hook/recall")).toHaveLength(1) + expect(of("/v1/hook/record")).toHaveLength(1) + const recalled = of("/v1/hook/recall")[0].body.body + const recorded = of("/v1/hook/record")[0].body + expect(recorded.body).toEqual(recalled) + expect(recorded.reply).toEqual(protocol === "chat" + ? { choices: [{ message: { role: "assistant", content: [], tool_calls: originalReply.choices[0].message.tool_calls } }] } + : originalReply) + expect(fresh).toEqual(originalReply) + const wire = JSON.stringify(recorded.body) + for (const privateText of ["getToken", "Opts", "synthetic-history-only", "synthetic-private", "old_string", "new_string", "arguments"]) expect(wire).not.toContain(privateText) + expect(JSON.stringify(recalled[key])).not.toContain('"input":') + expect(wire).toContain("Edit") + expect(wire).toContain("Write") + expect(req[key].slice(0, -1)).toEqual(before[key].slice(0, -1)) + }) + + for (const record of [false, true]) { + test(`${protocol}: historical secret text is omitted and ordinary current turn recalls (record ${record})`, async () => { + mock() + const [c] = ctx(protocol, { options: { record } }) + const req = { [key]: [ + { role: "user", content: "password=synthetic-history-only" }, + { role: "assistant", content: [{ type: "text", text: "sk-abcdefghijklmnopqrstuvwxyz" }, { type: "text", text: "safe context" }] }, + { role: "user", content: "What do you remember?" }, + ] } + expect(await onRequest(req, c)).toBeDefined() + onResponse(reply("safe speech"), { ...c, success: true }) + await flush() + expect(of("/v1/hook/recall")).toHaveLength(1) + expect(of("/v1/hook/record")).toHaveLength(record ? 1 : 0) + for (const call of dialogue()) { + const wire = JSON.stringify(call.body) + expect(wire).not.toContain("synthetic-history-only") + expect(wire).not.toContain("sk-abcdefghijklmnopqrstuvwxyz") + expect(call.body.body[key][0].content).toBe("[credential omitted]") + expect(call.body.body[key][1].content).toEqual([{ type: "text", text: "[credential omitted]" }, { type: "text", text: "safe context" }]) + } + }) + + test(`${protocol}: current credential skips whole turn and next human turn recovers (record ${record})`, async () => { + mock() + const [c] = ctx(protocol, { options: { record } }) + const secret = { role: "user", content: [{ type: "text", text: "token=synthetic-current-only" }] } + const req = { [key]: [secret] } + expect(await onRequest(req, c)).toBeUndefined() + expect(req[key][0]).toEqual(secret) + expect(c.state.aelios).toBeUndefined() + onResponse(reply("safe speech"), { ...c, success: true }) + await flush() + expect(calls).toHaveLength(0) + const next = { [key]: [secret, { role: "assistant", content: "ok" }, { role: "user", content: "What should I eat?" }] } + expect(await onRequest(next, c)).toBeDefined() + onResponse(reply("safe speech"), { ...c, success: true }) + await flush() + expect(of("/v1/hook/recall")).toHaveLength(1) + expect(of("/v1/hook/record")).toHaveLength(record ? 1 : 0) + for (const call of dialogue()) expect(JSON.stringify(call.body)).not.toContain("synthetic-current-only") + }) + } + + test(`${protocol}: secret in fresh speech arguments still prevents recording`, async () => { + mock() + const [c, reports] = ctx(protocol, { options: { record: true } }) + await onRequest({ [key]: [{ role: "user", content: "Say hello" }] }, c) + onResponse(reply("token=synthetic-reply-only"), { ...c, success: true }) + await flush() + expect(of("/v1/hook/recall")).toHaveLength(1) + expect(of("/v1/hook/record")).toHaveLength(0) + expect(reports.at(-1)).toEqual(["skipped"]) + }) +} + +test("tool-only final user records safely after a credential-bearing human turn", async () => { + mock() + const [c] = ctx("anthropic", { options: { record: true } }) + const req = anthropicTool() + req.messages[0].content = "password=synthetic-prior-human" + expect(await onRequest(req, c)).toBeUndefined() + onResponse({ content: [{ type: "text", text: "Done" }] }, { ...c, success: true }) + await flush() + expect(of("/v1/hook/recall")).toHaveLength(0) + expect(of("/v1/hook/record")).toHaveLength(1) + expect(of("/v1/hook/record")[0].body.body.messages[0].content).toBe("[credential omitted]") + expect(JSON.stringify(of("/v1/hook/record")[0].body)).not.toContain("synthetic-prior-human") +}) + +test("legacy claude-code remains an exact supported agent id", async () => { + mock() + const [c] = ctx("anthropic", { agent: "claude-code", options: { agents: ["claude-code"] } }) + expect(await onRequest(anthropicString(), c)).toBeDefined() + expect(of("/v1/hook/recall")[0].body.agent).toBe("claude-code") +}) + +test("ordinary generation max_token text still recalls", async () => { + mock() + const [c] = ctx("chat") + expect(await onRequest({ messages: [{ role: "user", content: "Use max_token: 4000" }] }, c)).toBeDefined() + expect(of("/v1/hook/recall")).toHaveLength(1) +}) diff --git a/packages/aelios/package.json b/packages/aelios/package.json new file mode 100644 index 0000000..a62d30b --- /dev/null +++ b/packages/aelios/package.json @@ -0,0 +1,51 @@ +{ + "name": "@magpie-community/gateway-aelios", + "version": "0.1.0", + "description": "Aelios long-term memory for every agent behind magpie: recall before each turn, optional recording after it", + "type": "module", + "files": [ + "aelios.hooks.mjs", + "slim.mjs", + "service.mjs", + "probe.mjs", + "page", + "README.md" + ], + "keywords": [ + "magpie", + "magpie-gateway", + "aelios", + "memory", + "llm-gateway" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/aelios" + }, + "magpie": { + "hooks": "./aelios.hooks.mjs", + "options": { + "apiKeyEnv": "AELIOS_API_KEY", + "gatewayTimeoutMs": 5000, + "requestTimeoutMs": 4000, + "recallBackoffMs": 30000, + "record": false, + "port": 3481 + }, + "page": { + "title": "Aelios", + "file": "page/settings.html", + "icon": "page/icon.svg", + "service": { "port": 3481, "option": "port" } + } + }, + "main": "./service.mjs", + "scripts": { + "check": "bun test ./*.test.mjs" + }, + "engines": { + "bun": ">=1.4.2" + } +} diff --git a/packages/aelios/page.test.mjs b/packages/aelios/page.test.mjs new file mode 100644 index 0000000..f75f500 --- /dev/null +++ b/packages/aelios/page.test.mjs @@ -0,0 +1,186 @@ +import { test, expect } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import vm from 'node:vm'; +const source = (name) => readFileSync(new URL(`./page/${name}`, import.meta.url), 'utf8'); +const context = vm.createContext({ URL }); +vm.runInContext(source('form.js'), context); +const build = context.aeliosForm.build; +const values = (changes = {}) => ({ url: 'https://example.test/base', key: '', keyEnv: '', identity: '', agents: '', recall: true, record: false, allowRemote: false, routes: [], ...changes }); + +test('form preserves advanced options and supplies a usable default gateway timeout', () => { + const next = build({ custom: { kept: true }, requestTimeoutMs: 4200 }, values()); + expect(JSON.parse(JSON.stringify(next))).toEqual({ custom: { kept: true }, requestTimeoutMs: 4200, serverUrl: 'https://example.test/base', gatewayTimeoutMs: 5000, recall: true, record: false, allowRemote: false }); + expect(build({ gatewayTimeoutMs: 7000 }, values()).gatewayTimeoutMs).toBe(7000); + expect(build({}, values({ url: '' })).serverUrl).toBeUndefined(); +}); +test('form validates URL and authentication before writing', () => { + for (const url of ['http://remote.test', 'https://user:pass@example.test', 'https://example.test/?key=x', 'https://example.test/#x', 'invalid']) expect(() => build({}, values({ url }))).toThrow('invalidUrl'); + for (const url of ['http://localhost:1234', 'http://127.0.0.1:3481', 'http://[::1]:1234']) expect(build({}, values({ url })).serverUrl).toBeTruthy(); + expect(build({}, values({ key: 'Bearer secret', keyEnv: 'OTHER_KEY' })).apiKey).toBe('secret'); + expect(() => build({}, values({ key: 'bad key' }))).toThrow('invalidKey'); + expect(() => build({}, values({ identity: 'x'.repeat(129) }))).toThrow('invalidIdentity'); +}); +test('route validation mirrors hook identities, priority and selector limits', () => { + const route = { identity: 'my-identity', models: 'claude-*, gpt-*', agents: 'codex', original: { custom: 'kept' } }; + const next = build({}, values({ routes: [route, { ...route, identity: 'second' }] })); + expect(JSON.parse(JSON.stringify(next.routes))).toEqual([{ custom: 'kept', identity: 'my-identity', models: ['claude-*', 'gpt-*'], agents: ['codex'] }, { custom: 'kept', identity: 'second', models: ['claude-*', 'gpt-*'], agents: ['codex'] }]); + for (const identity of ['admin', 'V1', 'memory-mcp', '-bad', 'x'.repeat(65)]) expect(() => build({}, values({ routes: [{ ...route, identity }] }))).toThrow('invalidRoute'); + expect(() => build({}, values({ routes: [{ ...route, models: '', agents: '' }] }))).toThrow('missingSelector'); + expect(() => build({}, values({ routes: [{ ...route, models: 'a,,b' }] }))).toThrow('invalidSelectors'); + expect(() => build({}, values({ routes: [{ ...route, models: 'x'.repeat(201) }] }))).toThrow('invalidSelectors'); + expect(build({}, values({ routes: [{ ...route, models: 'x'.repeat(200) }] })).routes).toHaveLength(1); + expect(build({}, values({ routes: Array.from({ length: 64 }, () => route) })).routes).toHaveLength(64); + expect(() => build({}, values({ routes: Array.from({ length: 65 }, () => route) }))).toThrow('tooManyRoutes'); +}); +test('preserved invalid timing options are rejected', () => { + for (const options of [{ gatewayTimeoutMs: 99 }, { requestTimeoutMs: 9001 }, { recallBackoffMs: -1 }, { gatewayTimeoutMs: '5000' }]) expect(() => build(options, values())).toThrow('invalidAdvanced'); +}); + +class Element { + constructor(tag = 'div') { this.tagName = tag.toUpperCase(); this.dataset = {}; this.children = []; this.value = ''; this.checked = false; this.type = ''; this.hidden = false; this.attributes = {}; this.open = false; this.parentElement = null; } + closest(selector) { return this.tagName.toLowerCase() === selector ? this : this.parentElement?.closest(selector) || null; } + append(...children) { for (const child of children) child.parentElement = this; this.children.push(...children); } + replaceChildren(...children) { this.children = children; } + setAttribute(key, value) { this.attributes[key] = value; } + removeAttribute(key) { delete this.attributes[key]; } + addEventListener() {} + focus() {} +} +async function setup(initial = {}, setMode = 'success') { + const elements = new Map(); const document = { documentElement: new Element('html'), title: '', createElement: (tag) => new Element(tag), querySelectorAll: () => [], getElementById: (id) => { + if (elements.has(id)) return elements.get(id); + const visit = (node) => node.id === id ? node : node.children.map(visit).find(Boolean); + return [...elements.values()].map(visit).find(Boolean); + } }; + const stack = []; + for (const token of source('settings.html').matchAll(/<(\/?)([a-z][\w-]*)([^>]*)>/gi)) { + const [, closing, tag, attributes] = token; + if (closing) { stack.pop(); continue; } + const node = new Element(tag); + const id = /\bid="([^"]+)"/.exec(attributes)?.[1]; + if (id) { node.id = id; elements.set(id, node); } + node.open = /\bopen\b/.test(attributes); node.hidden = /\bhidden\b/.test(attributes); + stack.at(-1)?.append(node); + if (!['meta', 'link', 'input', 'br', 'hr', 'img'].includes(tag)) stack.push(node); + } + elements.get('key').type = 'password'; + let options = structuredClone(initial), sets = 0, reads = 0, target; + const magpie = { theme: { lang: 'zh-CN' }, service: '', ready: Promise.resolve(), onTheme(fn) { this.onThemeChange = fn; }, options: { + async get() { reads++; return structuredClone(options); }, + async set(next) { sets++; if (setMode !== 'reject') options = structuredClone(next); if (setMode !== 'success') throw new Error('bridge failed'); return next; } + } }; + const sandbox = vm.createContext({ URL, setTimeout: (fn) => setTimeout(fn, 0), document, navigator: { language: 'en' }, magpie, location: { assign: (url) => { target = url; } } }); + sandbox.window = sandbox; + for (const name of ['i18n.js', 'form.js', 'settings.js']) vm.runInContext(source(name), sandbox); + await new Promise((resolve) => setTimeout(resolve, 0)); + return { elements, magpie, async connect() { await elements.get('connect').onclick(); }, async save() { await elements.get('save').onclick(); }, async submit() { await elements.get('form').onsubmit({ preventDefault() {} }); }, async test() { await elements.get('test').onclick(); }, updateOptions(next) { options = next; }, get options() { return options; }, get sets() { return sets; }, get reads() { return reads; }, get target() { return target; } }; +} +test('first connection shows only connection controls and advanced settings stay collapsed', async () => { + const page = await setup(); + expect(page.elements.get('connection-editor').open).toBe(true); + expect(page.elements.get('connection-summary').hidden).toBe(true); + expect(page.elements.get('daily-settings').hidden).toBe(true); + expect(page.elements.get('saved-actions').hidden).toBe(true); + expect(page.elements.get('advanced').open).toBe(false); + for (const id of ['identity', 'routes', 'agents', 'key-env', 'allow-remote']) { + expect(page.elements.get(id).closest('details').id).toBe('advanced'); + } + expect(page.elements.get('assignment-summary').textContent).toContain('自动'); + expect(page.elements.get('assignment-summary').textContent).toContain('主模型匹配'); + expect(source('settings.html')).toContain('placeholder="claude, codex"'); + expect(source('settings.js')).not.toContain('claude-code, codex'); +}); +test('configured connection is collapsed and clearly distinguishes configuration from verification', async () => { + const page = await setup({ serverUrl: 'https://example.test/base' }); + expect(page.elements.get('connection-editor').open).toBe(false); + expect(page.elements.get('connection-summary').hidden).toBe(false); + expect(page.elements.get('configured-url').textContent).toBe('https://example.test/base'); + expect(page.elements.get('change-connection').textContent).toBe('更改连接'); + expect(page.elements.get('daily-settings').hidden).toBe(false); + expect(source('i18n.js')).toContain('已配置不代表已验证连接'); +}); +test('custom identity and routes remain visible in the summary and survive ordinary saves', async () => { + for (const custom of [{ identity: 'personal' }, { routes: [{ identity: 'work', models: ['gpt-*'], custom: 1 }] }, { identity: 'fallback', routes: [{ identity: 'work', agents: ['claude'] }] }]) { + const page = await setup({ serverUrl: 'https://example.test', ...custom }); + expect(page.elements.get('advanced').open).toBe(false); + expect(page.elements.get('assignment-summary').textContent).toContain('自定义'); + if (custom.identity) expect(page.elements.get('assignment-summary').textContent).toContain(custom.identity); + if (custom.routes) expect(page.elements.get('assignment-summary').textContent).toContain('身份路由: 1'); + page.elements.get('record').checked = true; + await page.save(); + expect(page.options.identity).toEqual(custom.identity); + expect(page.options.routes).toEqual(custom.routes); + } +}); +test('first connect saves then opens automatic testing, and a failed save never navigates', async () => { + for (const mode of ['success', 'write-then-reject', 'reject']) { + const page = await setup({}, mode); + page.elements.get('url').value = 'https://example.test'; + page.elements.get('key').value = 'test-key'; + await page.connect(); + expect(page.sets).toBe(1); + if (mode === 'reject') { + expect(page.target).toBeUndefined(); + expect(page.elements.get('connection-editor').open).toBe(true); + expect(page.elements.get('url').value).toBe('https://example.test'); + expect(page.elements.get('result').dataset.message).toBe('saveFailed'); + } else { + expect(page.options.serverUrl).toBe('https://example.test/'); + expect(page.target).toBe('http://127.0.0.1:3481/test?lang=zh&auto=1'); + } + } + const blank = await setup(); await blank.connect(); + expect(blank.sets).toBe(0); expect(blank.target).toBeUndefined(); +}); + +test('saving is a click, never a form submit, because Magpie frames forbid forms', async () => { + const html = source('settings.html'); + expect(/Stored in Magpie’s local plugin settings. Leave blank to use the environment variable. + + +

Assistant assignment

+
Advanced settings +
+ +
+

Identity routes

First match wins. Move a route up to give it priority.

+

Match models and/or agents with comma-separated selectors. Models support * and ignore case; agents match exactly. If both are set, both must match. Unmatched requests are skipped unless a default identity is set.

+

No routes. Aelios uses the default identity, or selects by model automatically.

Up to 64 routes. Each route needs an identity and at least one selector.
+
+ +
Other advanced settings are preserved. Connection tests use saved settings.
+

Recall sends conversation context to your configured Aelios service even when recording is off. Connection testing opens Magpie’s local service page.

+ diff --git a/packages/aelios/page/settings.js b/packages/aelios/page/settings.js new file mode 100644 index 0000000..82acfff --- /dev/null +++ b/packages/aelios/page/settings.js @@ -0,0 +1,205 @@ +(() => { + 'use strict'; + const $ = (id) => document.getElementById(id); + const { languageFor, translate } = aeliosI18n; + let language = 'en', busy = false, confirmed = false, savedOptions = null, baseline = '', routes = []; + const t = (key) => translate(language, key); + const text = (value) => typeof value === 'string' ? value : ''; + const list = (value) => Array.isArray(value) ? value.join(', ') : ''; + function message(key, error = false) { + const el = $('result'); + el.dataset.message = key; el.dataset.error = String(error); el.textContent = t(key); el.hidden = false; + } + function collect() { + return { + url: $('url').value, key: $('key').value, keyEnv: $('key-env').value, + identity: $('identity').value, agents: $('agents').value, + recall: $('recall').checked, record: $('record').checked, allowRemote: $('allow-remote').checked, + routes: routes.map((route) => ({ identity: route.identity, models: route.models, agents: route.agents, original: route.original })) + }; + } + const fingerprint = () => JSON.stringify(collect()); + const dirty = () => fingerprint() !== baseline; + function paintAssignment() { + const identity = $('identity').value.trim(); + $('assignment-summary').textContent = identity || routes.length + ? `${t('customAssignment')}${identity ? ` · ${t('fallback')}: ${identity}` : ''}${routes.length ? ` · ${t('routes')}: ${routes.length}` : ''}` + : t('automaticAssignment'); + } + function paintConnection() { + const configured = Boolean(text(savedOptions?.serverUrl).trim()); + $('connection-summary').hidden = !configured; + $('configured-url').textContent = text(savedOptions?.serverUrl); + $('connection-editor').open = !configured; + $('change-connection').textContent = t(configured ? 'changeConnection' : 'connectionIntro'); + $('daily-settings').hidden = !configured; + $('saved-actions').hidden = !configured; + } + function paintState() { + const key = busy ? 'saving' : dirty() ? 'unsaved' : 'loaded'; + $('state').dataset.message = key; $('state').textContent = t(key); $('state').dataset.dirty = String(dirty()); + $('save').disabled = busy || !savedOptions; + $('test').disabled = busy || !savedOptions; + $('connect').disabled = busy || !savedOptions; + paintAssignment(); + $('editor').disabled = busy || !savedOptions; + $('add-route').disabled = busy || routes.length >= 64; + } + function secret() { + const shown = $('key').type === 'text'; + $('show-key').textContent = t(shown ? 'hide' : 'show'); + $('show-key').setAttribute('aria-label', `${t(shown ? 'hide' : 'show')} ${t('key')}`); + $('show-key').setAttribute('aria-pressed', String(shown)); + } + function routeButton(key, symbol, action, disabled) { + const button = document.createElement('button'); + button.type = 'button'; button.className = 'quiet route-action'; button.textContent = symbol; + button.title = t(key); button.setAttribute('aria-label', t(key)); button.disabled = disabled; + button.onclick = action; + return button; + } + function renderRoutes() { + $('routes').replaceChildren(); + $('empty-routes').hidden = routes.length > 0; + routes.forEach((route, index) => { + const row = document.createElement('fieldset'); row.className = 'route'; + const legend = document.createElement('legend'); legend.textContent = `${t('priority')} ${index + 1}`; row.append(legend); + const actions = document.createElement('div'); actions.className = 'route-actions'; + const move = (offset) => { + [routes[index], routes[index + offset]] = [routes[index + offset], routes[index]]; + renderRoutes(); changed(); $(`route-${index + offset}-identity`).focus(); + }; + actions.append(routeButton('up', '↑', () => move(-1), index === 0), routeButton('down', '↓', () => move(1), index === routes.length - 1), routeButton('remove', '×', () => { + routes.splice(index, 1); renderRoutes(); changed(); + if (routes.length) $(`route-${Math.min(index, routes.length - 1)}-identity`).focus(); else $('add-route').focus(); + }, false)); + row.append(actions); + const fields = document.createElement('div'); fields.className = 'route-fields'; + for (const [name, label, placeholder] of [['identity', 'routeIdentity', 'personal'], ['models', 'models', 'claude-*, gpt-*'], ['agents', 'routeAgents', 'claude, codex']]) { + const wrapper = document.createElement('label'); const caption = document.createElement('span'); caption.textContent = t(label); + const input = document.createElement('input'); input.id = `route-${index}-${name}`; input.value = route[name]; input.placeholder = placeholder; input.autocomplete = 'off'; input.spellcheck = false; + if (name === 'identity') input.maxLength = 64; + input.oninput = () => { route[name] = input.value; changed(); }; + wrapper.append(caption, input); fields.append(wrapper); + } + row.append(fields); $('routes').append(row); + }); + $('add-route').disabled = busy || routes.length >= 64; + } + function fill(options) { + $('url').value = text(options.serverUrl); $('key').value = text(options.apiKey); $('key').type = 'password'; + $('key-env').value = text(options.apiKeyEnv); $('identity').value = text(options.identity); $('agents').value = list(options.agents); + $('recall').checked = options.recall !== false; $('record').checked = options.record === true; $('allow-remote').checked = options.allowRemote === true; + routes = Array.isArray(options.routes) ? options.routes.map((route) => ({ identity: text(route?.identity), models: list(route?.models), agents: list(route?.agents), original: route && typeof route === 'object' ? { ...route } : {} })) : []; + renderRoutes(); secret(); baseline = fingerprint(); paintConnection(); paintState(); + } + function changed() { + document.querySelectorAll('[aria-invalid="true"]').forEach((el) => el.removeAttribute('aria-invalid')); + $('result').hidden = true; paintState(); + } + function paint() { + language = languageFor(window.magpie?.theme?.lang || navigator.language); + document.documentElement.lang = language === 'zh' ? 'zh-CN' : 'en'; + document.title = language === 'zh' ? 'Aelios · 设置' : 'Aelios · Settings'; + document.querySelectorAll('[data-t]').forEach((el) => { el.textContent = t(el.dataset.t); }); + document.querySelectorAll('[data-message]').forEach((el) => { el.textContent = t(el.dataset.message); }); + secret(); renderRoutes(); if (savedOptions) { + $('change-connection').textContent = t(text(savedOptions.serverUrl).trim() ? 'changeConnection' : 'connectionIntro'); + paintState(); + } + } + $('show-key').onclick = () => { $('key').type = $('key').type === 'password' ? 'text' : 'password'; secret(); }; + $('form').addEventListener('input', (event) => { if (!event.target.closest('.route')) changed(); }); + $('add-route').onclick = () => { + if (routes.length >= 64) return; + routes.push({ identity: '', models: '', agents: '', original: {} }); renderRoutes(); changed(); $(`route-${routes.length - 1}-identity`).focus(); + }; + // Magpie frames a page with allow-scripts but not allow-forms, so a submit + // button is blocked before the handler runs. Save is a click, and the form + // never submits; Enter in a text field saves through the same path. + $('form').onsubmit = (event) => event.preventDefault(); + $('form').addEventListener('keydown', (event) => { + if (event.key !== 'Enter' || event.target.closest('.route') || !['INPUT'].includes(event.target.tagName) || event.target.type === 'checkbox') return; + event.preventDefault(); + if (!text(savedOptions?.serverUrl).trim()) connect(); else save(); + }); + async function save() { + if (busy || !savedOptions) return; + const values = collect(); + try { aeliosForm.build(savedOptions, values); } catch (error) { validationError(error); return; } + busy = true; paintState(); message('saving'); + let candidate; + try { + const latest = await magpie.options.get(); + candidate = aeliosForm.build(latest, values); + await magpie.options.set(candidate); + // Read the authoritative state even after an acknowledged write. + savedOptions = await magpie.options.get(); confirmed = true; + fill(savedOptions); message('saved'); return true; + } catch (error) { + try { + savedOptions = await magpie.options.get(); confirmed = true; + // A write can succeed even when the bridge response is rejected. + if (candidate && equivalent(candidate, savedOptions)) { fill(savedOptions); message('saved'); return true; } + else if (error.field || ['invalidAdvanced', 'invalidOptions'].includes(error.message)) validationError(error); + else message('saveFailed', true); + } catch { confirmed = false; message('reconcileFailed', true); } + } finally { busy = false; paintState(); } + } + $('save').onclick = save; + function equivalent(a, b) { + if (a === b) return true; + if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false; + const keys = Object.keys(a); if (keys.length !== Object.keys(b).length) return false; + return keys.every((key) => Object.hasOwn(b, key) && equivalent(a[key], b[key])); + } + function validationError(error) { + message(error.message || 'invalidOptions', true); + const field = error.field && $(error.field); + if (field) { + field.setAttribute('aria-invalid', 'true'); + const details = field.closest('details'); if (details) details.open = true; + field.focus(); + } + } + function openTest() { + const port = savedOptions.port; + const localService = `http://127.0.0.1:${Number.isInteger(port) && port > 0 && port <= 65535 ? port : 3481}`; + const target = new URL(`${magpie.service || localService}`.replace(/\/+$/, '') + '/test'); + target.searchParams.set('lang', language); + target.searchParams.set('auto', '1'); + location.assign(target.href); + } + async function connect() { + if (busy || !savedOptions) return; + if (!$('url').value.trim()) { validationError({ message: 'invalidUrl', field: 'url' }); return; } + if (await save()) { + // options.set restarts Magpie's plugin host. Its acknowledgement precedes + // the local listener; let the host bind before navigating the frame. + busy = true; paintState(); + await new Promise(resolve => setTimeout(resolve, 1000)); + try { openTest(); } catch { message('testFailed', true); } + finally { busy = false; paintState(); } + } + } + $('connect').onclick = connect; + $('test').onclick = async () => { + if (busy || !savedOptions) return; + if (dirty() || !confirmed) { message('saveFirst', true); return; } + busy = true; paintState(); + try { + savedOptions = await magpie.options.get(); confirmed = true; + // A different window may have changed the saved options; reflect those. + fill(savedOptions); + openTest(); + } catch { message('testFailed', true); } + finally { busy = false; paintState(); } + }; + paint(); + if (!window.magpie) { message('bridgeFailed', true); $('state').textContent = t('bridgeFailed'); return; } + magpie.ready.then(async () => { + paint(); magpie.onTheme(paint); + try { savedOptions = await magpie.options.get(); confirmed = true; fill(savedOptions); } + catch { message('loadFailed', true); $('state').dataset.message = 'loadFailed'; $('state').textContent = t('loadFailed'); } + }).catch(() => { message('bridgeFailed', true); $('state').dataset.message = 'bridgeFailed'; $('state').textContent = t('bridgeFailed'); }); +})(); diff --git a/packages/aelios/page/style.css b/packages/aelios/page/style.css new file mode 100644 index 0000000..06a44c9 --- /dev/null +++ b/packages/aelios/page/style.css @@ -0,0 +1,95 @@ +/* Magpie's bridge supplies base typography, colours and controls. */ +*, *::before, *::after { box-sizing: border-box; } +[hidden] { display: none !important; } +main { max-width: 720px; } + +.page-head { display: flex; align-items: flex-start; gap: 10px; margin: 0 0 18px; } +.page-head > div { flex: 1; min-width: 0; } +.page-head h1 { font-size: 15px; } +.page-head p { margin: 2px 0 0; } +.badge { flex: none; padding-top: 2px; color: var(--magpie-muted); font-size: 11.5px; } +.badge[data-dirty="true"] { color: var(--magpie-accent); } + +fieldset { margin: 0; padding: 0; border: 0; min-width: 0; } +.panel { padding: 0 0 18px; } +.panel + .panel { padding-top: 18px; border-top: 1px solid var(--magpie-line); } +.section-head h2 { margin: 0; } +.section-head p { margin: 3px 0 14px; color: var(--magpie-muted); } + +.fields { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; } +.wide { grid-column: 1 / -1; } +label { display: block; min-width: 0; } +label > span { display: block; margin-bottom: 5px; font-size: 12px; } +label > small, small { display: block; margin-top: 5px; } +label input:not([type="checkbox"]) { display: block; width: 100%; min-width: 0; } +input::placeholder { color: var(--magpie-faint); } + +.secret { display: flex; align-items: center; gap: 6px; } +.secret input { flex: 1; min-width: 0; } +.secret button { flex: none; } + +.toggle-row { display: flex; align-items: center; gap: 12px; min-height: 30px; padding: 5px 0; cursor: pointer; } +.toggle-row > span { flex: 1; min-width: 0; } +.toggle-row strong { display: block; font-size: 12px; font-weight: 500; } +.toggle-row small { margin-top: 2px; } + +/* magpie's switch, as Plugins draws it */ +input[role="switch"] { + appearance: none; -webkit-appearance: none; position: relative; flex: none; + width: 32px; height: 19px; margin: 0; padding: 0; border: 0; border-radius: 10px; + background: var(--magpie-line); cursor: pointer; + transition: background .2s cubic-bezier(.2, .8, .2, 1); +} +input[role="switch"]::before { + content: ""; position: absolute; top: 2px; left: 2px; width: 15px; height: 15px; + border-radius: 50%; background: #fff; box-shadow: 0 1px 2px #00000040; + transition: transform .22s cubic-bezier(.2, .8, .2, 1); +} +input[role="switch"]:checked { background: var(--magpie-fg); } +input[role="switch"]:checked::before { transform: translateX(13px); } +input[role="switch"]:disabled { opacity: .5; cursor: default; } + +#configured-url { overflow-wrap: anywhere; } +#connection-editor summary { cursor: pointer; } +#connect { margin-top: 14px; } +.advanced section { margin-top: 18px; } + +.notice { margin: 0 0 12px; color: var(--magpie-muted); font-size: 12px; max-width: 74ch; } + +#routes { display: grid; gap: 10px; } +.route { + position: relative; padding: 10px 12px; + border: 1px solid var(--magpie-line); border-radius: 10px; background: var(--magpie-card); +} +.route legend { padding: 0 4px; color: var(--magpie-muted); font-size: 11px; } +.route-actions { position: absolute; top: 6px; right: 8px; display: flex; gap: 2px; } +.route-action { + width: 24px; height: 22px; padding: 0; font-size: 12px; line-height: 1; + color: var(--magpie-muted); background: transparent; border-color: transparent; +} +.route-action:hover:not(:disabled) { color: var(--magpie-fg); border-color: var(--magpie-line); } +.route-fields { display: grid; grid-template-columns: 1fr 1.4fr 1fr; gap: 10px; } +.empty { margin: 0 0 12px; color: var(--magpie-muted); font-size: 12px; } +.route-limit { margin-top: 8px; } +#add-route { margin-top: 10px; } + +.advanced { padding: 0 0 18px; } +.advanced summary { cursor: pointer; font-size: 12px; color: var(--magpie-muted); } +.advanced[open] summary { margin-bottom: 10px; } + +footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding-top: 14px; border-top: 1px solid var(--magpie-line); } +footer > div { min-width: 0; } +footer small { margin-top: 0; } +.actions { flex: none; display: flex; gap: 8px; } +#save { background: var(--magpie-accent); color: var(--magpie-accent-fg); border-color: transparent; font-weight: 500; } +#save:hover:not(:disabled) { filter: brightness(1.08); } +#result { margin: 0 0 8px; padding: 6px 9px; border-radius: 6px; background: var(--magpie-accent-soft); color: var(--magpie-fg); font-size: 12px; } +#result[data-error="true"] { background: color-mix(in srgb, var(--magpie-red) 12%, var(--magpie-card)); color: var(--magpie-red); } +.privacy { margin: 14px 0 0; color: var(--magpie-muted); font-size: 11.5px; max-width: 74ch; } + +@media (max-width: 620px) { + .fields, .route-fields { grid-template-columns: 1fr; } + .wide { grid-column: auto; } + footer { align-items: stretch; flex-direction: column; } + .actions { justify-content: flex-end; } +} \ No newline at end of file diff --git a/packages/aelios/probe.mjs b/packages/aelios/probe.mjs new file mode 100644 index 0000000..2026c45 --- /dev/null +++ b/packages/aelios/probe.mjs @@ -0,0 +1,168 @@ +// A manual settings-page probe: no dialogue and never a record endpoint. +const MAX_BYTES = 16 * 1024 +const reserved = new Set(["v1", "api", "admin", "health", "mcp", "memory-mcp", "memory-admin", "guide-dog"]) +class Failure extends Error { + constructor(code) { super(code); this.code = code } +} +const texts = { + en: { + confirm: "Test the saved Aelios connection? This sends empty messages and creates no dialogue records.", + scope: "Explicit identities are checked once each. Automatic selection only checks the connection; it cannot verify all model mappings.", + run: "Test connection", back: "Back to settings", testing: "Testing…", failed: "Connection failed", + connected: "Connection and explicit identity permissions verified", connection_only: "Connection verified; model mappings were not checked", + unauthorized: "API key rejected or missing", forbidden: "Identity permission denied", endpoint404: "Hook endpoint not found", + timeout: "Test timed out", invalid: "Invalid settings or response", unavailable: "Service unavailable", checked: "Identities checked", noService: "The local test service did not answer.", + }, + zh: { + confirm: "测试已保存的 Aelios 连接?测试只发送空消息,不会创建对话记录。", + scope: "每个明确指定的身份只检查一次。自动选择身份时只检查连接,无法验证所有模型映射。", + run: "测试连接", back: "返回设置", testing: "正在测试…", failed: "连接失败", + connected: "连接和指定身份权限已验证", connection_only: "连接已验证;未检查模型映射", + unauthorized: "API 密钥缺失或被拒绝", forbidden: "没有身份访问权限", endpoint404: "未找到 Hook 接口", + timeout: "测试超时", invalid: "设置或响应无效", unavailable: "服务不可用", checked: "已检查身份数", noService: "本地测试服务没有响应。", + }, +} +export function textsFor(lang) { return texts[lang] ?? texts.en } + +// Display-only metadata, read through the same local service as the probe. +// An older Worker may not offer this endpoint; it must not break recall. +export async function readIdentities(raw = {}, fetcher = globalThis.fetch, timeoutMs = 5000, env = process.env) { + const controller = new AbortController() + let timer + try { + if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 9000) throw new Failure('invalid') + const o = settings(raw, env) + const work = async () => { + const response = await fetcher(new URL('v1/hook/identities', o.server), { + method: 'GET', redirect: 'error', signal: controller.signal, + headers: { Authorization: /^bearer\s/i.test(o.apiKey) ? o.apiKey : `Bearer ${o.apiKey}` }, + }) + if (response.status !== 200) { + response.body?.cancel().catch(() => {}) + return { available: false, code: response.status === 404 ? 'unsupported' : 'unavailable' } + } + const data = await readJSON(response, controller.signal) + if (!data || !Array.isArray(data.identities) || data.identities.length > 256) throw new Failure('invalid') + const identities = data.identities.map(item => { + if (!item || typeof item.slug !== 'string' || item.slug.length > 128 || + typeof item.name !== 'string' || item.name.length > 512 || + !Array.isArray(item.mainModels) || item.mainModels.length > 256 || + !item.mainModels.every(model => typeof model === 'string' && model.length <= 512)) throw new Failure('invalid') + return { slug: item.slug, name: item.name, mainModels: item.mainModels } + }) + return { available: true, identities } + } + return await Promise.race([work(), new Promise((_, reject) => { + timer = setTimeout(() => { controller.abort(); reject(new Failure('timeout')) }, timeoutMs) + })]) + } catch { return { available: false, code: controller.signal.aborted ? 'timeout' : 'unavailable' } } + finally { clearTimeout(timer) } +} + +function settings(raw, env) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Failure("invalid") + const text = (value) => { + if (value === undefined || value === null || value === "") return undefined + if (typeof value !== "string" || !value.trim()) throw new Failure("invalid") + return value.trim() + } + let server + try { server = new URL(text(raw.serverUrl)) } catch { throw new Failure("invalid") } + const local = ["localhost", "127.0.0.1", "[::1]"].includes(server.hostname) + if (server.username || server.password || server.search || server.hash || + !(server.protocol === "https:" || (server.protocol === "http:" && local))) throw new Failure("invalid") + server.pathname = server.pathname.replace(/\/+$/, "") + "/" + const apiKeyEnv = text(raw.apiKeyEnv) ?? "AELIOS_API_KEY" + const apiKey = text(raw.apiKey) ?? text(env[apiKeyEnv]) + if (!apiKey) throw new Failure("unauthorized") + if (/[\r\n]/.test(apiKey)) throw new Failure("invalid") + const identity = text(raw.identity) + if (identity && identity.length > 128) throw new Failure("invalid") + const identities = new Set() + if (raw.routes !== undefined) { + if (!Array.isArray(raw.routes) || raw.routes.length > 64) throw new Failure("invalid") + for (const route of raw.routes) { + if (!route || typeof route !== "object" || Array.isArray(route) || + typeof route.identity !== "string" || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/.test(route.identity) || + reserved.has(route.identity.toLowerCase())) throw new Failure("invalid") + let selectors = false + for (const name of ["models", "agents"]) { + if (route[name] === undefined) continue + if (!Array.isArray(route[name]) || !route[name].length || !route[name].every(value => + typeof value === "string" && value.trim() && (name !== "models" || value.length <= 200))) throw new Failure("invalid") + selectors = true + } + if (!selectors) throw new Failure("invalid") + identities.add(route.identity) + } + } + if (identity) identities.add(identity) + return { server, apiKey, identities: [...identities] } +} + +async function readJSON(response, signal) { + const reader = response.body?.getReader() + if (!reader) throw new Failure("invalid") + const chunks = [] + let size = 0 + const cancel = () => { reader.cancel().catch(() => {}) } + signal.addEventListener("abort", cancel, { once: true }) + try { + if (Number(response.headers.get("content-length")) > MAX_BYTES) throw new Failure("invalid") + for (;;) { + signal.throwIfAborted() + const { value, done } = await reader.read() + if (done) break + size += value.byteLength + if (size > MAX_BYTES) throw new Failure("invalid") + chunks.push(value) + } + try { return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks))) } + catch { throw new Failure("invalid") } + } finally { + signal.removeEventListener("abort", cancel) + cancel() + reader.releaseLock() + } +} + +// One deadline bounds the entire test, including streaming the response and all +// identities. The race also bounds fetch mocks/transports that ignore abort. +export async function testConnection(raw = {}, fetcher = globalThis.fetch, timeoutMs = 5000, env = process.env) { + const started = Date.now() + let checkedIdentities = 0 + let timer + const controller = new AbortController() + const result = (ok, code) => ({ ok, code, checkedIdentities, ms: Date.now() - started }) + try { + if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 9000) throw new Failure("invalid") + const o = settings(raw, env) + const work = async () => { + for (const identity of o.identities.length ? o.identities : [undefined]) { + controller.signal.throwIfAborted() + const body = { protocol: "chat", model: "magpie-aelios-connection-probe", body: { messages: [] }, record: false } + if (identity) body.identity = identity + const response = await fetcher(new URL("v1/hook/recall", o.server), { + method: "POST", redirect: "error", signal: controller.signal, + headers: { "content-type": "application/json", Authorization: /^bearer\s/i.test(o.apiKey) ? o.apiKey : `Bearer ${o.apiKey}` }, + body: JSON.stringify(body), + }) + if (controller.signal.aborted) { response.body?.cancel().catch(() => {}); throw new Failure("timeout") } + if (response.status !== 200) { + response.body?.cancel().catch(() => {}) + throw new Failure(({ 401: "unauthorized", 403: "forbidden", 404: "endpoint404" })[response.status] ?? (response.status >= 500 || response.status === 429 ? "unavailable" : "invalid")) + } + const data = await readJSON(response, controller.signal) + if (!data || !["off", "skipped"].includes(data.memory) || data.patch !== "" || data.recall_id !== null || data.remember !== "none") throw new Failure("invalid") + checkedIdentities++ + } + return result(true, o.identities.length ? "connected" : "connection_only") + } + const deadline = new Promise((_, reject) => { + timer = setTimeout(() => { controller.abort(); reject(new Failure("timeout")) }, timeoutMs) + }) + return await Promise.race([work(), deadline]) + } catch (error) { + return result(false, controller.signal.aborted ? "timeout" : error instanceof Failure ? error.code : "unavailable") + } finally { clearTimeout(timer) } +} diff --git a/packages/aelios/probe.test.mjs b/packages/aelios/probe.test.mjs new file mode 100644 index 0000000..b1652f2 --- /dev/null +++ b/packages/aelios/probe.test.mjs @@ -0,0 +1,143 @@ +import { expect, test } from "bun:test" +import { readIdentities, testConnection, textsFor } from "./probe.mjs" + +const saved = { serverUrl: "https://aelios.example/base/", apiKey: "secret-test-key" } +const quiet = (memory = "skipped") => Response.json({ memory, patch: "", recall_id: null, remember: "none" }) +const noEnv = {} + +test('matching list uses authenticated read-only endpoint and projects display metadata only', async () => { + const result = await readIdentities(saved, async (url, init) => { + expect(String(url)).toBe('https://aelios.example/base/v1/hook/identities') + expect(init.method).toBe('GET') + expect(init.body).toBeUndefined() + expect(init.redirect).toBe('error') + expect(init.headers.Authorization).toBe('Bearer secret-test-key') + return Response.json({ identities: [{ slug: 'first', name: 'Assistant', mainModels: ['gpt-*'], namespace: 'never-display' }], secret: 'never-display' }) + }, 1000, noEnv) + expect(result).toEqual({ available: true, identities: [{ slug: 'first', name: 'Assistant', mainModels: ['gpt-*'] }] }) + expect(JSON.stringify(result)).not.toContain('never-display') +}) + +test('matching list tolerates older Workers and bounds malformed or hanging responses', async () => { + expect(await readIdentities(saved, async () => new Response('private', { status: 404 }), 1000, noEnv)).toEqual({ available: false, code: 'unsupported' }) + for (const data of [{ identities: [{}] }, { identities: Array(257).fill({}) }, { identities: [{ slug: 'ok', name: 'ok', mainModels: [1] }] }]) { + expect((await readIdentities(saved, async () => Response.json(data), 1000, noEnv)).available).toBe(false) + } + expect(await readIdentities(saved, async () => new Promise(() => {}), 10, noEnv)).toEqual({ available: false, code: 'timeout' }) +}) + +test("empty-input probe checks every distinct route identity plus fallback without records or dialogue", async () => { + const requests = [] + const options = { ...saved, identity: "fallback", record: true, routes: [ + { identity: "first", models: ["model-*"] }, { identity: "second", agents: ["agent"] }, + { identity: "first", models: ["other"] }, + ] } + const result = await testConnection(options, async (url, init) => { + requests.push({ url: String(url), init }) + return quiet(requests.length % 2 ? "off" : "skipped") + }, 1000, noEnv) + expect(result).toEqual({ ok: true, code: "connected", checkedIdentities: 3, ms: expect.any(Number) }) + expect(requests.map(r => JSON.parse(r.init.body).identity)).toEqual(["first", "second", "fallback"]) + for (const { url, init } of requests) { + expect(url).toBe("https://aelios.example/base/v1/hook/recall") + expect(init.method).toBe("POST") + expect(init.redirect).toBe("error") + expect(init.headers.Authorization).toBe("Bearer secret-test-key") + expect(JSON.parse(init.body)).toEqual({ protocol: "chat", model: "magpie-aelios-connection-probe", body: { messages: [] }, record: false, identity: expect.any(String) }) + } + expect(JSON.stringify(result)).not.toContain(saved.apiKey) +}) + +test("automatic identity reports connection-only scope", async () => { + const result = await testConnection(saved, async (_url, init) => { + expect(JSON.parse(init.body).identity).toBeUndefined() + return quiet("off") + }, 1000, noEnv) + expect(result).toEqual(expect.objectContaining({ ok: true, code: "connection_only", checkedIdentities: 1 })) + expect(textsFor("en").scope).toContain("cannot verify all model mappings") + expect(textsFor("zh").scope).toContain("无法验证所有模型映射") +}) + +test("API keys resolve from saved key, selected environment, or default environment and are required", async () => { + for (const [options, env, expected] of [ + [saved, { AELIOS_API_KEY: "other" }, "Bearer secret-test-key"], + [{ serverUrl: saved.serverUrl, apiKeyEnv: "SELECTED" }, { SELECTED: "env-key" }, "Bearer env-key"], + [{ serverUrl: saved.serverUrl }, { AELIOS_API_KEY: "Bearer default-key" }, "Bearer default-key"], + ]) { + expect((await testConnection(options, async (_url, init) => { + expect(init.headers.Authorization).toBe(expected) + return quiet() + }, 1000, env)).ok).toBe(true) + } + let calls = 0 + const result = await testConnection({ serverUrl: saved.serverUrl }, async () => { calls++; return quiet() }, 1000, noEnv) + expect(result.code).toBe("unauthorized") + expect(calls).toBe(0) +}) + +test("URL validation permits HTTPS or loopback HTTP only, without credentials, query or fragment", async () => { + for (const serverUrl of ["https://example.com", "http://localhost:1234", "http://127.0.0.1:1234", "http://[::1]:1234"]) { + expect((await testConnection({ ...saved, serverUrl }, async () => quiet(), 1000, noEnv)).ok).toBe(true) + } + for (const serverUrl of ["", "invalid", "ftp://example.com", "http://example.com", "http://localhost.evil", "https://user:pass@example.com", "https://example.com/?apiKey=secret", "https://example.com/#fragment"]) { + let called = false + const result = await testConnection({ ...saved, serverUrl }, async () => { called = true; return quiet() }, 1000, noEnv) + expect(result.code).toBe("invalid") + expect(called).toBe(false) + } +}) + +test("fixed status codes never expose remote bodies or errors", async () => { + for (const [status, code] of [[401, "unauthorized"], [403, "forbidden"], [404, "endpoint404"], [400, "invalid"], [302, "invalid"], [429, "unavailable"], [503, "unavailable"]]) { + const result = await testConnection(saved, async () => new Response(`remote dialogue ${saved.apiKey}`, { status }), 1000, noEnv) + expect(result).toEqual({ ok: false, code, checkedIdentities: 0, ms: expect.any(Number) }) + expect(JSON.stringify(result)).not.toContain(saved.apiKey) + } + expect((await testConnection(saved, async () => { throw new Error(`sensitive ${saved.apiKey}`) }, 1000, noEnv)).code).toBe("unavailable") +}) + +test("invalid response shape and non-quiet outcomes are rejected", async () => { + for (const body of [{}, { memory: "injected", patch: "private dialogue" }, { memory: "off" }, { memory: "skipped", patch: "private", recall_id: null, remember: "none" }, { memory: "off", patch: "", recall_id: "record", remember: "none" }]) { + expect((await testConnection(saved, async () => Response.json(body), 1000, noEnv)).code).toBe("invalid") + } + expect((await testConnection(saved, async () => new Response("invalid JSON"), 1000, noEnv)).code).toBe("invalid") +}) + +test("read bound cancels oversized streams, including declared lengths", async () => { + for (const declared of [false, true]) { + let cancelled = false + const response = new Response(new ReadableStream({ + start(controller) { controller.enqueue(new Uint8Array(16385)) }, + cancel() { cancelled = true }, + }), { headers: declared ? { "content-length": "16385" } : {} }) + expect((await testConnection(saved, async () => response, 1000, noEnv)).code).toBe("invalid") + expect(cancelled).toBe(true) + } +}) + +test("deadline bounds hung fetch and streaming body, aborts and cancels reads", async () => { + let signal + const hung = await testConnection(saved, async (_url, init) => { signal = init.signal; return new Promise(() => {}) }, 20, noEnv) + expect(hung.code).toBe("timeout") + expect(signal.aborted).toBe(true) + let cancelled = false + const streamed = await testConnection(saved, async () => new Response(new ReadableStream({ cancel() { cancelled = true } })), 20, noEnv) + expect(streamed.code).toBe("timeout") + expect(cancelled).toBe(true) + expect(streamed.ms).toBeLessThan(500) +}) + +test("routes are limited to 64 plus fallback, malformed saved routes fail before fetch", async () => { + const routes = Array.from({ length: 64 }, (_, i) => ({ identity: `identity-${i}`, models: ["*"] })) + expect((await testConnection({ ...saved, routes, identity: "fallback" }, async () => quiet(), 1000, noEnv)).checkedIdentities).toBe(65) + for (const routes of [Array(65).fill({ identity: "valid", models: ["*"] }), [{ identity: "admin", models: ["*"] }], [{ identity: "valid" }], [{ identity: "valid", models: [] }], "bad"]) { + const result = await testConnection({ ...saved, routes }, async () => { throw new Error("must not fetch") }, 1000, noEnv) + expect(result.code).toBe("invalid") + } +}) + +test("failure after a successful identity preserves only count and fixed status", async () => { + let calls = 0 + const result = await testConnection({ ...saved, identity: "fallback", routes: [{ identity: "first", models: ["*"] }] }, async () => ++calls === 1 ? quiet() : new Response("secret second identity", { status: 403 }), 1000, noEnv) + expect(result).toEqual({ ok: false, code: "forbidden", checkedIdentities: 1, ms: expect.any(Number) }) +}) diff --git a/packages/aelios/reply.test.mjs b/packages/aelios/reply.test.mjs new file mode 100644 index 0000000..ceb8767 --- /dev/null +++ b/packages/aelios/reply.test.mjs @@ -0,0 +1,60 @@ +import { afterEach, expect, test } from 'bun:test' +import { flush, onRequest, onResponse, reset } from './aelios.hooks.mjs' +const realFetch = globalThis.fetch +const fixtures = [ + ['anthropic', { messages: [{ role: 'user', content: 'An ordinary question' }] }, { + model: 'test', stop_reason: 'end_turn', content: [ + { type: 'thinking', thinking: 'OPENAI_API_KEY=sk-proj-syntheticSecret123456', signature: 'OPAQUE_SIGNATURE' }, + { type: 'redacted_thinking', data: 'OPAQUE_REDACTED' }, + { type: 'text', text: 'Ordinary answer', signature: 'OPAQUE_TEXT_SIGNATURE' }, + { type: 'tool_use', id: 't', name: 'lookup', input: { query: 'ordinary' } }, + ], + }], + ['responses', { input: 'An ordinary question' }, { + model: 'test', status: 'completed', output: [ + { type: 'reasoning', summary: [{ type: 'summary_text', text: 'ghp_syntheticSecretToken1234567890' }], encrypted_content: 'OPAQUE_ENCRYPTED' }, + { type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'Ordinary answer', annotations: [{ text: 'OPAQUE_ANNOTATION' }] }] }, + { type: 'function_call', name: 'lookup', arguments: '{"query":"ordinary"}' }, + { type: 'custom_tool_call', name: 'lookup', input: 'ordinary' }, + ], + }], + ['chat', { messages: [{ role: 'user', content: 'An ordinary question' }] }, { + model: 'test', choices: [{ index: 0, finish_reason: 'stop', message: { + role: 'assistant', content: 'Ordinary answer', reasoning_content: 'password=syntheticSecret123', + reasoning: 'OPAQUE_REASONING', signature: 'OPAQUE_SIGNATURE', encrypted_content: 'OPAQUE_ENCRYPTED', + tool_calls: [{ type: 'function', function: { name: 'lookup', arguments: '{"query":"ordinary"}' } }], + } }], + }], +] +afterEach(() => { globalThis.fetch = realFetch; reset() }) +for (const [protocol, request, reply] of fixtures) { + test(`${protocol}: reasoning credentials and opaque fields never leave the response hook`, async () => { + reset() + const calls = [] + globalThis.fetch = async (url, init) => { + if (String(url).endsWith('/identities')) return Response.json({ identities: [{ slug: 'test', name: 'Test', mainModels: ['*'] }] }) + calls.push({ url: String(url), body: JSON.parse(init.body) }) + return Response.json(String(url).endsWith('/recall') ? { memory: 'empty' } : { recorded: true }) + } + const ctx = { protocol, model: 'test', origin: 'local', success: true, state: {}, + options: { serverUrl: 'https://example.test', apiKey: 'synthetic-key', record: true } } + const before = structuredClone(reply) + await onRequest(request, ctx) + onResponse(reply, ctx) + await flush() + const record = calls.find(call => call.url.endsWith('/record')) + expect(record).toBeDefined() + const sent = JSON.stringify(record.body.reply) + expect(sent).toContain('Ordinary answer') + expect(sent).toContain('lookup') + for (const omitted of ['syntheticSecret', 'OPAQUE_', 'thinking', 'reasoning', 'signature', 'encrypted_content']) expect(sent).not.toContain(omitted) + expect(reply).toEqual(before) + // A credential in retained visible speech must still block the whole record. + const unsafe = structuredClone(reply) + if (protocol === 'anthropic') unsafe.content.push({ type: 'text', text: 'password=visibleSecret' }) + else if (protocol === 'responses') unsafe.output.push({ type: 'message', role: 'assistant', content: [{ type: 'output_text', text: 'password=visibleSecret' }] }) + else unsafe.choices[0].message.content = 'password=visibleSecret' + onResponse(unsafe, ctx); await flush() + expect(calls.filter(call => call.url.endsWith('/record'))).toHaveLength(1) + }) +} diff --git a/packages/aelios/service.mjs b/packages/aelios/service.mjs new file mode 100644 index 0000000..7b1c015 --- /dev/null +++ b/packages/aelios/service.mjs @@ -0,0 +1,134 @@ +// Magpie settings pages cannot fetch (connect-src 'none'). Their Connect or +// Test click navigates to this loopback page, which probes saved options only. +import { randomBytes, timingSafeEqual } from "node:crypto" +import { readIdentities, testConnection, textsFor } from "./probe.mjs" + +const DEFAULT_PORT = 3481 +const TOKEN_HEADER = "x-aelios-token" +let running +let pluginOptions = {} +let token + +function page(lang, auto = false) { + const t = textsFor(lang) + const zh = lang === "zh" + const labels = zh ? { title: "助手匹配列表", name: "助手", models: "主模型匹配规则", empty: "未配置主模型", unavailable: "当前服务未提供匹配列表;请升级 Aelios 后重试。", rules: "自动分配复用 Aelios 的主模型规则,按列表顺序选择首个匹配的助手。支持 *、忽略大小写,同时匹配完整模型名及最后 / 后的名称。插件先按授权匹配列表在本地筛选;未匹配时不发送对话。列表不可用时暂停回忆和记录,并显示 unavailable。", override: "当前设置包含自定义身份或路由;它们优先于自动分配。", auto: "连接成功后显示此密钥可访问的助手。" } : { title: "Assistant mappings", name: "Assistant", models: "Main model patterns", empty: "No main models configured", unavailable: "This service does not provide mappings. Upgrade Aelios and retry.", rules: "Automatic assignment uses Aelios main model rules, choosing the first matching assistant in order. Patterns support *, ignore case, and match the full model name or the name after its last /. The plugin filters locally using the authorized matching list; unmatched turns are not sent. If the list is unavailable, recall and recording pause with status unavailable.", override: "Custom identity or route settings are active and take priority over automatic assignment.", auto: "After connecting, this page lists the assistants available to this key." } + return ` + + + +Aelios + +

Aelios

${auto ? labels.auto : t.confirm}

${t.scope}

+ +

+ +` +} +function hostOK(req, port = running?.port) { + const host = String(req.headers.get("host") ?? "").toLowerCase() + return !!port && (host === `127.0.0.1:${port}` || host === `localhost:${port}`) +} +function originOK(req, port = running?.port) { + const origin = req.headers.get("origin") + return !!port && (origin === null || origin === "null" || origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`) +} +function tokenOK(req) { + const got = Buffer.from(req.headers.get(TOKEN_HEADER) ?? "") + const want = Buffer.from(token ?? "") + return want.length > 0 && got.length === want.length && timingSafeEqual(got, want) +} +function cors(req) { + return req.headers.get("origin") === "null" ? { + "access-control-allow-origin": "null", "access-control-allow-headers": TOKEN_HEADER, + "access-control-allow-methods": "POST, OPTIONS", vary: "Origin", + } : {} +} +async function handle(req) { + if (!hostOK(req)) return new Response("Forbidden", { status: 403 }) + const url = new URL(req.url) + const headers = { "cache-control": "no-store", "x-content-type-options": "nosniff", "referrer-policy": "no-referrer" } + if (url.pathname === "/test" && req.method === "GET") { + if ([...url.searchParams.keys()].some(key => !["lang", "auto"].includes(key)) || (url.searchParams.has('auto') && url.searchParams.get('auto') !== '1')) return new Response("Invalid request", { status: 400, headers }) + return new Response(page(url.searchParams.get("lang"), url.searchParams.get('auto') === '1'), { headers: { ...headers, "content-type": "text/html; charset=utf-8" } }) + } + if (url.pathname === "/api/test" && ["POST", "OPTIONS"].includes(req.method)) { + if (!originOK(req) || (req.method === "POST" && !tokenOK(req))) return new Response("Forbidden", { status: 403, headers }) + if (url.search || req.body !== null) return new Response("Invalid request", { status: 400, headers }) + if (req.method === "OPTIONS") return new Response(null, { status: 204, headers: { ...headers, ...cors(req) } }) + const options = structuredClone(pluginOptions) + const result = await testConnection(options) + if (result.ok) { + result.mapping = await readIdentities(options) + result.custom = Boolean(options.identity || options.routes?.length) + } + return Response.json(result, { headers: { ...headers, ...cors(req) } }) + } + return new Response("Not found", { status: 404, headers }) +} +export default { + id: "magpie-aelios", + async server(_input, options) { + pluginOptions = options && typeof options === "object" ? structuredClone(options) : {} + if (running) return {} + const port = Number(pluginOptions.port ?? DEFAULT_PORT) + if (!Number.isInteger(port) || port < 1024 || port > 65535) { + console.error("[aelios] invalid connection test port") + return {} + } + try { + token = randomBytes(32).toString("hex") + running = Bun.serve({ hostname: "127.0.0.1", port, fetch: handle }) + console.log(`[aelios] connection test on http://127.0.0.1:${running.port}/test`) + } catch { + // Neither options nor runtime errors (which might contain secrets) escape. + console.error("[aelios] connection test service could not start") + } + return {} + }, +} +export const _internal = { + hostOK, originOK, + stop() { running?.stop(true); running = undefined; pluginOptions = {}; token = undefined }, +} diff --git a/packages/aelios/service.test.mjs b/packages/aelios/service.test.mjs new file mode 100644 index 0000000..b7541ac --- /dev/null +++ b/packages/aelios/service.test.mjs @@ -0,0 +1,102 @@ +import { expect, test } from "bun:test" +import { request } from "node:http" +import service, { _internal } from "./service.mjs" + +const req = headers => ({ headers: { get: name => headers[name.toLowerCase()] ?? null } }) + +test("Host and Origin accept only the service loopback authority or sandbox origin", () => { + for (const host of ["localhost:3481", "127.0.0.1:3481"]) expect(_internal.hostOK(req({ host }), 3481)).toBe(true) + for (const host of [undefined, "evil.example:3481", "127.0.0.1:3482", "localhost:3481.evil"]) expect(_internal.hostOK(req({ host }), 3481)).toBe(false) + for (const origin of [undefined, "null", "http://localhost:3481", "http://127.0.0.1:3481"]) expect(_internal.originOK(req({ origin }), 3481)).toBe(true) + for (const origin of ["https://localhost:3481", "http://evil.example", "http://localhost:3482"]) expect(_internal.originOK(req({ origin }), 3481)).toBe(false) +}) + +test("actual Bun loopback service requires a click, CSRF, Host and Origin and probes saved options only", async () => { + const allocator = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response() }) + const port = allocator.port + allocator.stop(true) + const realFetch = globalThis.fetch + const requests = [] + globalThis.fetch = async (url, init) => { + requests.push({ url: String(url), init }) + if (init.method === 'GET') return Response.json({ identities: [{ slug: 'saved-person', name: '', mainModels: ['gpt-*'] }], selection: 'first_matching_main_model', unmatched: 'memory_off' }) + return Response.json({ memory: "skipped", patch: "", recall_id: null, remember: "none" }) + } + const send = (method, path, headers = {}, body) => new Promise((resolve, reject) => { + const outgoing = request({ host: "127.0.0.1", port, method, path, headers }, response => { + let data = "" + response.on("data", chunk => { data += chunk }) + response.on("end", () => resolve({ status: response.statusCode, headers: response.headers, body: data })) + }) + outgoing.on("error", reject) + outgoing.end(body) + }) + try { + expect(service.id).toBe("magpie-aelios") + expect(await service.server(undefined, { port, serverUrl: "https://saved.example", apiKey: "saved-secret-key", identity: "saved-person" })).toEqual({}) + const own = `127.0.0.1:${port}` + const page = await send("GET", "/test?lang=zh", { host: own }) + expect(page.status).toBe(200) + expect(page.body).toContain("测试连接") + expect(page.body).toContain("history.back()") + expect(page.body).toContain('addEventListener("click", test)') + expect(page.body).toContain('cell.textContent = value') + const automatic = await send('GET', '/test?lang=zh&auto=1', { host: own }) + expect(automatic.status).toBe(200) + expect(automatic.body).toContain('test();') + expect((await send('GET', '/test?auto=evil', { host: own })).status).toBe(400) + expect(page.body).not.toContain("saved-secret-key") + expect(page.body).not.toContain("saved.example") + expect(page.headers["cache-control"]).toBe("no-store") + expect(requests).toHaveLength(0) + const token = page.body.match(/name="aelios-token" content="([0-9a-f]{64})"/)[1] + const authorized = { host: own, origin: "null", "x-aelios-token": token } + expect((await send("GET", "/test?lang=en", { host: own })).body).toContain("Test connection") + expect((await send("GET", "/test", { host: `evil.example:${port}` })).status).toBe(403) + for (const headers of [ + { ...authorized, host: `evil.example:${port}` }, { ...authorized, origin: "http://evil.example" }, + { ...authorized, "x-aelios-token": "0".repeat(64) }, { host: own, origin: "null" }, + ]) expect((await send("POST", "/api/test", headers)).status).toBe(403) + expect((await send("OPTIONS", "/api/test", { host: own, origin: "http://evil.example" })).status).toBe(403) + expect((await send("OPTIONS", "/api/test", { host: own, origin: "null" })).headers["access-control-allow-origin"]).toBe("null") + expect((await send("POST", "/api/test?serverUrl=https://evil.example&apiKey=evil", authorized)).status).toBe(400) + expect((await send("GET", "/test?apiKey=evil", { host: own })).status).toBe(400) + expect((await send("POST", "/api/test", { ...authorized, "content-type": "application/json" }, JSON.stringify({ apiKey: "evil", serverUrl: "https://evil.example" }))).status).toBe(400) + expect((await send("GET", "/api/test", authorized)).status).toBe(404) + expect(requests).toHaveLength(0) + const result = await send("POST", "/api/test", authorized) + expect(result.status).toBe(200) + expect(JSON.parse(result.body)).toEqual({ ok: true, code: "connected", checkedIdentities: 1, ms: expect.any(Number), custom: true, mapping: { available: true, identities: [{ slug: 'saved-person', name: '', mainModels: ['gpt-*'] }] } }) + expect(result.headers["access-control-allow-origin"]).toBe("null") + expect(result.body).not.toContain("saved-secret-key") + expect(requests).toHaveLength(2) + expect(requests[1].url).toBe('https://saved.example/v1/hook/identities') + expect(requests[0].url).toBe("https://saved.example/v1/hook/recall") + expect(requests[0].init.headers.Authorization).toBe("Bearer saved-secret-key") + expect(JSON.parse(requests[0].init.body)).toEqual({ protocol: "chat", model: "magpie-aelios-connection-probe", body: { messages: [] }, record: false, identity: "saved-person" }) + await service.server(undefined, { port, serverUrl: "https://updated.example", apiKey: "updated-secret" }) + expect((await send("POST", "/api/test", { ...authorized, origin: `http://${own}` })).status).toBe(200) + expect(requests[2].url).toBe("https://updated.example/v1/hook/recall") + globalThis.fetch = async () => new Response("sensitive remote dialogue saved-secret-key", { status: 401 }) + const failure = await send("POST", "/api/test", authorized) + expect(JSON.parse(failure.body).code).toBe("unauthorized") + expect(failure.body).not.toContain("sensitive") + expect(failure.body).not.toContain("secret") + } finally { + _internal.stop() + globalThis.fetch = realFetch + } +}) + +test("real fetch refuses redirects without forwarding credentials", async () => { + let redirected = 0 + const destination = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => { redirected++; return new Response() } }) + const redirector = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null, { status: 302, headers: { location: `http://127.0.0.1:${destination.port}/stolen` } }) }) + try { + const { testConnection } = await import("./probe.mjs") + const result = await testConnection({ serverUrl: `http://127.0.0.1:${redirector.port}`, apiKey: "redirect-secret" }) + expect(result.code).toBe("unavailable") + expect(redirected).toBe(0) + expect(JSON.stringify(result)).not.toContain("redirect-secret") + } finally { redirector.stop(true); destination.stop(true) } +}) diff --git a/packages/aelios/slim.mjs b/packages/aelios/slim.mjs new file mode 100644 index 0000000..ca64d41 --- /dev/null +++ b/packages/aelios/slim.mjs @@ -0,0 +1,313 @@ +// What the Aelios hook sends and how it puts recalled memory back, kept apart +// from the hook so it can be tested on its own. Everything here is a pure +// function of its input: the same request always slims to the same bytes, +// which is what lets Aelios hash a turn to the same exchange id at recall +// time and again at record time. + +// magpie's protocol names, as Aelios calls them. Gemini is not supported yet. +const protocols = { anthropic: "messages", chat: "chat", responses: "responses" } +export function aeliosProtocol(protocol) { + return protocols[protocol] ?? null +} + +const placeholders = { + image: "[image]", image_url: "[image]", input_image: "[image]", + document: "[file]", file: "[file]", input_file: "[file]", + audio: "[audio]", input_audio: "[audio]", +} +const thinking = new Set(["thinking", "redacted_thinking", "reasoning"]) + +const object = (v) => !!v && typeof v === "object" && !Array.isArray(v) +const isText = (p) => object(p) && ["text", "input_text", "output_text"].includes(p.type) && typeof p.text === "string" + +// One content block of a message, or undefined to drop it. +function block(p) { + if (!object(p)) return undefined + if (isText(p)) return { type: p.type, text: p.text } + if (thinking.has(p.type)) return undefined + if (placeholders[p.type]) return { type: "text", text: placeholders[p.type] } + if (p.type === "tool_use" || p.type === "server_tool_use") { + const out = { type: p.type } + if (typeof p.name === "string") out.name = p.name + return out + } + // tool_result, mcp_tool_result, web_search_tool_result, …: the structure + // stays, what the tool returned does not + if (typeof p.type === "string" && /(^|_)tool_result$/.test(p.type)) return { type: p.type, content: "" } + return undefined +} + +function content(c) { + if (typeof c === "string") return c + if (!Array.isArray(c)) return "" + return c.map(block).filter(Boolean) +} + +function messagesItem(m) { + if (!object(m) || typeof m.role !== "string") return undefined + return { role: m.role, content: content(m.content) } +} + +function chatItem(m) { + if (!object(m) || typeof m.role !== "string") return undefined + // system prompts are not what anyone said in the conversation + if (m.role === "system" || m.role === "developer") return undefined + if (m.role === "tool") return { role: "tool", content: "" } + const out = { role: m.role, content: content(m.content) } + if (Array.isArray(m.tool_calls) && m.tool_calls.length) { + out.tool_calls = m.tool_calls.filter(object).map((t) => ({ + type: typeof t.type === "string" ? t.type : "function", + function: { name: typeof t.function?.name === "string" ? t.function.name : "" }, + })) + } + return out +} + +function responsesItem(item) { + if (!object(item)) return undefined + const type = typeof item.type === "string" ? item.type : undefined + if (type === "reasoning") return undefined + if (!type || type === "message" || type === "input_message") { + if (typeof item.role !== "string" || item.role === "system" || item.role === "developer") return undefined + const out = {} + if (type) out.type = type + out.role = item.role + out.content = content(item.content) + return out + } + if (type === "function_call") { + return { type, name: typeof item.name === "string" ? item.name : "" } + } + if (type === "custom_tool_call") { + return { type, name: typeof item.name === "string" ? item.name : "" } + } + if (/_output$/.test(type)) return { type, output: "" } + // other items (item_reference, local_shell_call, web_search_call, …) + // keep only what kind they are + return { type } +} + +function tool(t, protocol) { + if (!object(t)) return undefined + if (protocol === "chat") { + const out = {} + if (typeof t.type === "string") out.type = t.type + out.function = { name: typeof t.function?.name === "string" ? t.function.name : typeof t.name === "string" ? t.name : "" } + return out + } + const out = {} + // Responses' built-in tools (local_shell, apply_patch) have a type and no name + if (protocol === "responses" && typeof t.type === "string") out.type = t.type + if (typeof t.name === "string") out.name = t.name + return Object.keys(out).length ? out : undefined +} + +// slim keeps roles, text and tool names. Historical tool arguments and +// results never leave the plugin; speech is collected from the new reply. +// Credential-bearing historical text keeps its structure with a fixed marker. +export function slim(body, protocol) { + const src = object(body) ? body : {} + const out = {} + if (protocol === "responses") { + if (typeof src.input === "string") out.input = src.input + else out.input = (Array.isArray(src.input) ? src.input : []).map(responsesItem).filter(Boolean) + } else { + const item = protocol === "chat" ? chatItem : messagesItem + out.messages = (Array.isArray(src.messages) ? src.messages : []).map(item).filter(Boolean) + } + const list = items(out, protocol) + for (const [index, item] of list.entries()) { + // Only the final item can be the current user turn. Never search backward + // past a tool result or assistant message for an earlier human turn. + if (index === list.length - 1 && item.role === "user" && + (!item.type || ["message", "input_message"].includes(item.type))) continue + if (typeof item.content === "string") item.content = historicalText(item.content) + else if (Array.isArray(item.content)) { + item.content = item.content.map((part) => isText(part) ? { ...part, text: historicalText(part.text) } : part) + } + } + if (Array.isArray(src.tools)) out.tools = src.tools.map((t) => tool(t, protocol)).filter(Boolean) + if (typeof src.metadata?.session_id === "string") out.metadata = { session_id: src.metadata.session_id } + if (protocol === "responses") { + if (typeof src.previous_response_id === "string" && src.previous_response_id) out.previous_response_id = src.previous_response_id + if (src.conversation !== undefined && src.conversation !== null) out.conversation = typeof src.conversation === "string" ? src.conversation : true + } + return out +} + +export function items(body, protocol) { + if (protocol === "responses") return typeof body.input === "string" ? [{ role: "user", content: body.input }] : Array.isArray(body.input) ? body.input : [] + return Array.isArray(body.messages) ? body.messages : [] +} + +// A Responses request that continues state kept on the provider's side: +// Aelios can't see that history, so it neither recalls nor records it. +export function serverState(body, protocol) { + return protocol === "responses" && !!(body.previous_response_id || body.conversation || + items(body, protocol).some((i) => object(i) && i.type === "item_reference")) +} + +function historicalText(text) { + return hasSecret(text) ? "[credential omitted]" : text +} + +// The final user item's text, including instruction wrappers for the secret +// guard. A tool-only final item has no new user text, even after a human turn. +export function lastUserText(body, protocol) { + const last = items(body, protocol).at(-1) + if (!object(last) || last.role !== "user" || + (last.type && !["message", "input_message"].includes(last.type))) return "" + return visible(last.content) +} + +function visible(c) { + if (typeof c === "string") return c + if (!Array.isArray(c)) return "" + return c.filter(isText).map((p) => p.text).join("\n") +} +// Match Aelios's cleanMessageText instruction wrappers. Ordinary XML and +// transport messages contain the person's words and must remain visible. +function humanText(text) { + const instruction = (tag) => { + const name = tag.toLowerCase() + return name === "recap" || /[-_]reminder$/.test(name) || /^(system|local|command|agent|task|hook)[-_]/.test(name) + } + const transport = (tag, attrs) => /wecom|wechat|weixin/i.test(tag) || + (/message/i.test(tag) && /\b(?:from|sender|sender_id|msg_id|message_id)\s*=/i.test(attrs)) + const closed = /<([a-zA-Z][\w:-]*)\b([^>]*)>([\s\S]*?)<\/\1\s*>/gi + // Unwrap transport envelopes before inspecting their instruction blocks. + text = text.replace(closed, (full, tag, attrs, inner) => transport(tag, attrs) ? inner : full) + const hasClose = (after, tag) => new RegExp(``, "i").test(after) + const open = /<([a-zA-Z][\w:-]*)\b([^>]*?)>/gi + for (const match of text.matchAll(open)) { + if (match[0].endsWith("/>") || !transport(match[1], match[2])) continue + const after = text.slice(match.index + match[0].length) + if (!hasClose(after, match[1])) { + text = text.slice(0, match.index) + after + break + } + } + text = text.replace(/<([a-zA-Z][\w:-]*)\b[^>]*\/>/gi, (full, tag) => instruction(tag) ? "" : full) + .replace(closed, (full, tag) => instruction(tag) ? "" : full) + for (const match of text.matchAll(open)) { + if (match[0].endsWith("/>") || !instruction(match[1]) || /^time[-_]reminder$/i.test(match[1])) continue + if (!hasClose(text.slice(match.index + match[0].length), match[1])) { + text = text.slice(0, match.index) + break + } + } + return text.replace(/(?:^|\n)user stepped away;?\s*returning\.\s*recap:[\s\S]*$/i, "") + .replace(/(?:^|\n)recap:\s*<[\s\S]*$/i, "") + .replace(/(?:^|\n)today:\s*\d{4}-\d{2}-\d{2}\b[\s\S]*current working directory[\s\S]*$/i, "") + .split("\n").filter((line) => !/^(已回(?:她|他|你|完)?|已回复|已发送|已送达)[。.!!]*$/u.test(line.replace(/\s+/g, ""))).join("\n").trim() +} + +// humanTurn is a local first guess at Aelios's classifyTurn on a slimmed +// body: the last item is the user's, with text of their own, and not just a +// tool result. Aelios decides in the end; this only saves a request for +// every tool step. +export function humanTurn(slimmed, protocol) { + const list = items(slimmed, protocol) + const last = list.at(-1) + if (!object(last) || last.role !== "user") return false + if (last.type && !["message", "input_message"].includes(last.type)) return false + const text = humanText(visible(last.content)) + if (!text) return false + return true +} + +// appendPatch adds the recalled memory after the last user message, the +// way Aelios's own gateway does (appendMemory): a string grows by two +// newlines and the patch, an array gets one more text block. Earlier +// messages and every cache_control marker are left as they are. +export function appendPatch(body, protocol, patch) { + if (!patch) return false + if (protocol === "responses" && typeof body.input === "string") { + body.input += `\n\n${patch}` + return true + } + const list = items(body, protocol) + const last = list.at(-1) + if (!object(last) || last.role !== "user") return false + if (typeof last.content === "string") last.content += `\n\n${patch}` + else if (Array.isArray(last.content) || last.content === undefined) last.content = [...(last.content ?? []), { type: protocol === "responses" ? "input_text" : "text", text: patch }] + else return false + return true +} + +// Only fields consumed by Aelios's OutputCollector cross the record boundary. +// Never copy provider reasoning, signatures, encrypted blobs or arbitrary metadata. +export function slimReply(reply, protocol) { + if (!object(reply)) return null + const out = {} + for (const name of ['model', 'status', 'stop_reason']) if (typeof reply[name] === 'string') out[name] = reply[name] + if (reply.error) out.error = true + const replyContent = value => typeof value === 'string' ? value : Array.isArray(value) + ? value.filter(isText).map(part => ({ type: part.type, text: part.text })) : [] + if (protocol === 'messages') { + out.content = (Array.isArray(reply.content) ? reply.content : []).flatMap(part => { + if (isText(part)) return [{ type: part.type, text: part.text }] + if (object(part) && part.type === 'tool_use') return [{ type: 'tool_use', name: part.name, input: structuredClone(part.input) }] + return [] + }) + } else if (protocol === 'chat') { + out.choices = (Array.isArray(reply.choices) ? reply.choices : []).filter(object).map(choice => { + const message = object(choice.message) ? choice.message : {} + const clean = { role: 'assistant', content: replyContent(message.content) } + if (Array.isArray(message.tool_calls)) clean.tool_calls = message.tool_calls.filter(object).map(call => ({ + type: 'function', function: { name: call.function?.name, arguments: structuredClone(call.function?.arguments) }, + })) + return { index: choice.index, finish_reason: choice.finish_reason, message: clean } + }) + } else if (protocol === 'responses') { + out.output = (Array.isArray(reply.output) ? reply.output : []).flatMap(item => { + if (!object(item)) return [] + if (item.type === 'message' && item.role === 'assistant') return [{ type: 'message', role: 'assistant', content: replyContent(item.content) }] + if (item.type === 'function_call') return [{ type: item.type, name: item.name, arguments: structuredClone(item.arguments) }] + if (item.type === 'custom_tool_call') return [{ type: item.type, name: item.name, input: structuredClone(item.input) }] + return [] + }) + } + return out +} + +// What the assistant said in a reply (each protocol's non-streaming shape): +// its text and the arguments of its tool calls, for the secret check. +export function spoken(reply) { + const out = [] + if (!object(reply)) return out + const take = (v) => { if (typeof v === "string") out.push(v); else if (v !== undefined) out.push(v) } + for (const p of Array.isArray(reply.content) ? reply.content : []) { + if (isText(p)) take(p.text) + else if (object(p) && p.type === "tool_use") take(p.input) + } + for (const c of Array.isArray(reply.choices) ? reply.choices : []) { + const m = c?.message + if (!object(m)) continue + take(typeof m.content === "string" ? m.content : visible(m.content)) + for (const t of Array.isArray(m.tool_calls) ? m.tool_calls : []) take(t?.function?.arguments) + } + for (const item of Array.isArray(reply.output) ? reply.output : []) { + if (!object(item)) continue + if (item.type === "message") take(visible(item.content)) + else if (item.type === "function_call") take(item.arguments) + else if (item.type === "custom_tool_call") take(item.input) + } + return out +} + +// A turn that looks like it holds a credential is not recorded at all +// (masking part of it could still leave the rest on the server). The same +// patterns PowerContext's hook checks. +const secret = /(?:(?:^|[^A-Za-z0-9])(?!(?:max_tokens?|input_tokens|output_tokens)["']?\s*[:=])(?:[A-Za-z0-9]+[_-])*(?:api[_-]?key|access[_-]?key|access[_-]?token|(? secret.test(`${key}: ${typeof item === "string" ? item : "[value]"}`) || hasSecret(item)) +} diff --git a/packages/aelios/slim.test.mjs b/packages/aelios/slim.test.mjs new file mode 100644 index 0000000..1d6fefe --- /dev/null +++ b/packages/aelios/slim.test.mjs @@ -0,0 +1,248 @@ +// slim, the turn guess, the patch and the secret check, on their own: pure +// functions, no hook, no network. +import { expect, test } from "bun:test" +import { aeliosProtocol, appendPatch, hasSecret, humanTurn, lastUserText, serverState, slim, spoken } from "./slim.mjs" + +const big = (n) => "x".repeat(n) + +// A Claude Code shaped request of about 80 KB: a long system prompt, many +// tools with schemas, file contents in tool results, thinking and an image. +function claudeCode() { + const tools = Array.from({ length: 18 }, (_, i) => ({ + name: ["Bash", "Edit", "Read", "Write", "Grep", "Glob"][i % 6] + (i >= 6 ? i : ""), + description: big(900), + input_schema: { type: "object", properties: { a: { type: "string", description: big(300) } } }, + })) + return { + model: "claude-opus-4-5", stream: true, max_tokens: 32000, + system: [{ type: "text", text: big(12000), cache_control: { type: "ephemeral" } }], + tools, + metadata: { user_id: "user_abc", session_id: "sess-1" }, + thinking: { type: "enabled", budget_tokens: 8000 }, + messages: [ + { role: "user", content: [{ type: "text", text: "" + big(3000) + "" }, { type: "text", text: "Please fix the login bug" }] }, + { role: "assistant", content: [ + { type: "thinking", thinking: big(4000), signature: big(400) }, + { type: "text", text: "Looking at it." }, + { type: "tool_use", id: "toolu_1", name: "Read" }, + ] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_1", content: big(20000) }] }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_2", name: "Write", input: { file_path: "/src/big.ts", content: big(20000) } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_2", content: [{ type: "text", text: big(2000) }] }] }, + { role: "assistant", content: [{ type: "text", text: "Fixed." }] }, + { role: "user", content: [ + { type: "image", source: { type: "base64", media_type: "image/png", data: big(4000) } }, + { type: "text", text: "Thanks! Now the logout one.", cache_control: { type: "ephemeral" } }, + ] }, + ], + } +} + +test("protocols map to Aelios's names; gemini isn't supported", () => { + expect(aeliosProtocol("anthropic")).toBe("messages") + expect(aeliosProtocol("chat")).toBe("chat") + expect(aeliosProtocol("responses")).toBe("responses") + expect(aeliosProtocol("gemini")).toBeNull() +}) + +test("slim is pure: the same request gives the same bytes, and the input is untouched", () => { + const body = claudeCode() + const before = JSON.stringify(body) + const a = JSON.stringify(slim(body, "messages")) + const b = JSON.stringify(slim(structuredClone(body), "messages")) + expect(a).toBe(b) + expect(JSON.stringify(body)).toBe(before) +}) + +test("slim makes an 80 KB Claude Code request much smaller and keeps only what was said", () => { + const body = claudeCode() + const size = Buffer.byteLength(JSON.stringify(body)) + expect(size).toBeGreaterThan(75_000) + const s = slim(body, "messages") + const wire = JSON.stringify(s) + expect(Buffer.byteLength(wire)).toBeLessThan(size / 5) + expect(Object.keys(s).sort()).toEqual(["messages", "metadata", "tools"]) + expect(s.metadata).toEqual({ session_id: "sess-1" }) + expect(s.tools[0]).toEqual({ name: "Bash" }) + expect(wire).not.toContain("cache_control") + expect(wire).not.toContain("thinking") + expect(wire).not.toContain("signature") + expect(s.messages[1].content).toEqual([{ type: "text", text: "Looking at it." }, { type: "tool_use", name: "Read" }]) + expect(s.messages[2].content).toEqual([{ type: "tool_result", content: "" }]) + // every historical tool call keeps its name, not its arguments + expect(s.messages[3].content).toEqual([{ type: "tool_use", name: "Write" }]) + expect(s.messages[6].content).toEqual([{ type: "text", text: "[image]" }, { type: "text", text: "Thanks! Now the logout one." }]) +}) + +test("chat: system prompts and tool output go, tool calls and names stay", () => { + const s = slim({ + model: "gpt", temperature: 0, tool_choice: "auto", + tools: [{ type: "function", function: { name: "send_message", description: "d", parameters: {} } }], + messages: [ + { role: "system", content: "sys" }, + { role: "user", content: [{ type: "text", text: "hi" }, { type: "image_url", image_url: { url: "data:x" } }] }, + { role: "assistant", content: null, reasoning_content: "hmm", tool_calls: [{ id: "c1", type: "function", function: { name: "send_message" } }] }, + { role: "tool", tool_call_id: "c1", content: "sent ok" }, + ], + }, "chat") + expect(s).toEqual({ + messages: [ + { role: "user", content: [{ type: "text", text: "hi" }, { type: "text", text: "[image]" }] }, + { role: "assistant", content: "", tool_calls: [{ type: "function", function: { name: "send_message" } }] }, + { role: "tool", content: "" }, + ], + tools: [{ type: "function", function: { name: "send_message" } }], + }) +}) + +test("responses: string input, items, reasoning dropped, outputs emptied, server state kept", () => { + expect(slim({ instructions: "x", input: "hello", store: false }, "responses")).toEqual({ input: "hello" }) + const s = slim({ + instructions: "x", previous_response_id: "resp_1", + tools: [{ type: "function", name: "shell", parameters: {} }, { type: "local_shell" }], + input: [ + { type: "message", role: "developer", content: "dev" }, + { type: "message", role: "user", content: [{ type: "input_text", text: "run it" }, { type: "input_image", image_url: "x" }] }, + { type: "reasoning", summary: [], encrypted_content: "zzz" }, + { type: "function_call", call_id: "c", name: "shell" }, + { type: "function_call_output", call_id: "c", output: "file list" }, + { type: "item_reference", id: "msg_1" }, + ], + }, "responses") + expect(s).toEqual({ + input: [ + { type: "message", role: "user", content: [{ type: "input_text", text: "run it" }, { type: "text", text: "[image]" }] }, + { type: "function_call", name: "shell" }, + { type: "function_call_output", output: "" }, + { type: "item_reference" }, + ], + tools: [{ type: "function", name: "shell" }, { type: "local_shell" }], + previous_response_id: "resp_1", + }) + expect(serverState(s, "responses")).toBe(true) + expect(serverState({ input: "hi" }, "responses")).toBe(false) + expect(serverState({ messages: [], previous_response_id: "x" }, "messages")).toBe(false) +}) + +test("humanTurn: the user's own words, not a tool result or an envelope", () => { + expect(humanTurn(slim(claudeCode(), "messages"), "messages")).toBe(true) + const tool = { messages: [{ role: "user", content: [{ type: "tool_result", content: "" }] }] } + expect(humanTurn(tool, "messages")).toBe(false) + const toolWithReminder = { messages: [{ role: "user", content: [{ type: "tool_result", content: "" }, { type: "text", text: "todo list changed" }] }] } + expect(humanTurn(toolWithReminder, "messages")).toBe(false) + expect(humanTurn({ messages: [{ role: "assistant", content: "x" }] }, "messages")).toBe(false) + expect(humanTurn({ messages: [{ role: "tool", content: "" }] }, "chat")).toBe(false) + expect(humanTurn({ input: "hi" }, "responses")).toBe(true) + expect(humanTurn({ input: [{ type: "function_call_output", output: "" }] }, "responses")).toBe(false) + expect(humanTurn({ input: [{ type: "message", role: "user", content: [{ type: "input_text", text: "go" }] }] }, "responses")).toBe(true) + expect(humanTurn({ messages: [] }, "messages")).toBe(false) +}) + +test("humanTurn retains ordinary XML and transport speech but skips instruction wrappers", () => { + const human = (text) => humanTurn({ messages: [{ role: "user", content: text }] }, "chat") + for (const text of [ + "What is my favorite food?", + 'What is my favorite food?', + "Where do I live?", + 'Where do I live?', + "environment\nWhere do I live?", + ]) expect(human(text)).toBe(true) + for (const text of [ + "environment", + "unclosed environment", + "", + "earlier conversation", + 'environment', + "machine only", + "user stepped away; returning. recap: machine context", + "已发送。", + ]) expect(human(text)).toBe(false) +}) + +test("appendPatch follows Aelios's appendMemory for each shape", () => { + const str = { messages: [{ role: "user", content: "a" }, { role: "assistant", content: "b" }, { role: "user", content: "c" }] } + expect(appendPatch(str, "messages", "MEM")).toBe(true) + expect(str.messages[0].content).toBe("a") + expect(str.messages[2].content).toBe("c\n\nMEM") + + const arr = { messages: [{ role: "user", content: [{ type: "text", text: "c", cache_control: { type: "ephemeral" } }] }] } + appendPatch(arr, "messages", "MEM") + expect(arr.messages[0].content).toEqual([{ type: "text", text: "c", cache_control: { type: "ephemeral" } }, { type: "text", text: "MEM" }]) + + const r1 = { input: "hi" } + appendPatch(r1, "responses", "MEM") + expect(r1.input).toBe("hi\n\nMEM") + const r2 = { input: [{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] }] } + appendPatch(r2, "responses", "MEM") + expect(r2.input[0].content.at(-1)).toEqual({ type: "input_text", text: "MEM" }) + + expect(appendPatch({ messages: [{ role: "assistant", content: "x" }] }, "chat", "MEM")).toBe(false) + expect(appendPatch(str, "messages", "")).toBe(false) +}) + +test("hasSecret catches common credentials, not ordinary talk", () => { + for (const s of ["my key is sk-abcdefghijklmnop", "AKIAABCDEFGHIJKLMNOP", "ghp_abcdefghijklmnopqrstuvwxyz", "password=hunter2", + "AIza" + "a".repeat(35), "xoxb-1234567890-abc", "-----BEGIN RSA PRIVATE KEY-----"]) expect(hasSecret(s)).toBe(true) + expect(hasSecret({ input: { token: "abc123" } })).toBe(true) + expect(hasSecret(slim(claudeCode(), "messages"))).toBe(false) + expect(hasSecret("Let's talk about the weather tomorrow")).toBe(false) +}) + +test("spoken takes text and tool arguments from each reply shape", () => { + expect(spoken({ content: [{ type: "thinking", thinking: "t" }, { type: "text", text: "a" }, { type: "tool_use", name: "x", input: { b: 1 } }] })).toEqual(["a", { b: 1 }]) + expect(spoken({ choices: [{ message: { content: "a", tool_calls: [{ function: { arguments: "{}" } }] } }] })).toEqual(["a", "{}"]) + expect(spoken({ output: [{ type: "message", content: [{ type: "output_text", text: "a" }] }, { type: "function_call", arguments: "{}" }] })).toEqual(["a", "{}"]) + expect(spoken(null)).toEqual([]) +}) + + +test("history credentials are omitted by text block, current text stays intact, and slimming stays pure", () => { + for (const protocol of ["messages", "chat", "responses"]) { + const messages = [ + { role: "user", content: "password=synthetic-history-only" }, + { role: "assistant", content: [{ type: "text", text: "token=getToken()" }, { type: "text", text: "safe context" }] }, + { role: "user", content: [{ type: "text", text: "token=synthetic-current-only" }] }, + ] + const body = protocol === "responses" ? { input: messages } : { messages } + const before = JSON.stringify(body) + const result = slim(body, protocol) + const list = protocol === "responses" ? result.input : result.messages + expect(list[0].content).toBe("[credential omitted]") + expect(list[1].content).toEqual([{ type: "text", text: "[credential omitted]" }, { type: "text", text: "safe context" }]) + expect(lastUserText(result, protocol)).toBe("token=synthetic-current-only") + expect(JSON.stringify(result)).toBe(JSON.stringify(slim(body, protocol))) + expect(JSON.stringify(body)).toBe(before) + } +}) + +test("lastUserText only reads the final user item, never a prior human turn", () => { + const human = { role: "user", content: "password=synthetic-history-only" } + for (const protocol of ["messages", "chat", "responses"]) { + for (const last of [ + { role: "user", content: [{ type: "tool_result", content: "hidden tool text" }] }, + { role: "assistant", content: "reply" }, + protocol === "responses" ? { type: "function_call_output", output: "tool text" } : { role: "tool", content: "tool text" }, + ]) { + const list = [human, last] + const body = protocol === "responses" ? { input: list } : { messages: list } + expect(lastUserText(slim(body, protocol), protocol)).toBe("") + } + } + expect(lastUserText({ input: "token=synthetic-current" }, "responses")).toBe("token=synthetic-current") +}) + +test("generation token parameters do not weaken real token detection", () => { + for (const key of ["max_token", "max_tokens", "input_tokens", "output_tokens"]) { + expect(hasSecret(`${key}: 4000`)).toBe(false) + expect(hasSecret({ [key]: 4000 })).toBe(false) + expect(hasSecret(`${key}: 4000 token=synthetic-secret`)).toBe(true) + expect(hasSecret(`${key}: sk-abcdefghijklmnop`)).toBe(true) + } + for (const text of ["token=getToken()", "token=synthetic-secret", "api_token=synthetic-secret", "my_token=synthetic-secret"]) expect(hasSecret(text)).toBe(true) +}) + +test("Responses custom tool history loses input, while new reply speech keeps it", () => { + const call = { type: "custom_tool_call", name: "send_message", input: "synthetic speech" } + expect(slim({ input: [call] }, "responses")).toEqual({ input: [{ type: "custom_tool_call", name: "send_message" }] }) + expect(spoken({ output: [call] })).toEqual(["synthetic speech"]) +}) diff --git a/registry.json b/registry.json index 67c2cd2..34266e2 100644 --- a/registry.json +++ b/registry.json @@ -6,6 +6,8 @@ "summary": { "en": "Recall from your PowerContext service and optionally save complete conversations. Configure the service URL first; capture is off by default.", "zh": "从自己的 PowerContext 服务召回记忆,并按需存回完整对话。先配置服务地址;对话存回默认关闭。" } }, { "package": "@magpie-community/gateway-nowledge-mem", "name": "Nowledge Mem", "kind": "middleware", "community": true, "summary": { "en": "Give every harness behind Magpie Nowledge Mem automatically: recall and the Context Bundle (or Working Memory) before each request, per-harness provenance, optional import of completed conversations as Mem Threads, and a real connection test in the page. A local or remote Mem; saving conversations is off by default.", "zh": "让 Magpie 后面的每个 harness 自动接入 Nowledge Mem:每次请求前召回记忆与 Context Bundle(缺失时用 Working Memory),记录来自哪个 harness,按需把已完成的对话导入为 Mem Thread,并在页面中提供真实的连接测试。本机或远端 Mem 都可用;对话导入默认关闭。" } }, + { "package": "@magpie-community/gateway-aelios", "name": "Aelios", "kind": "middleware", "community": true, + "summary": { "en": "Long-term memory from your own Aelios on Cloudflare: recall before each turn for every agent behind magpie, and optionally record the conversation so Aelios can learn it. Set it up on the plugin's own page, with a connection test and per-model or per-agent routing to separate assistants. Recording is off by default.", "zh": "接入你自己部署在 Cloudflare 上的 Aelios 长期记忆:magpie 后面的每个 agent 每轮自动召回,按需把对话交给 Aelios 记住。在插件自己的页面里配置,可选择连接测试,并按模型或客户端分流到不同的助手。记录默认关闭。" } }, { "package": "@magpie-community/opencode-copilot-auth", "name": "GitHub Copilot", "icon": "githubcopilot", "providers": ["github-copilot"], "community": true, "summary": { "en": "GitHub Copilot on GitHub.com or GitHub Enterprise, with premium request or credit usage, remaining allowance and quota reset dates.", "zh": "GitHub Copilot:支持 GitHub.com 与 GitHub Enterprise,显示高级请求或积分用量、剩余额度和重置时间。" } }, { "package": "@magpie-community/opencode-joycode-auth", "name": "JoyCode", "providers": ["joycode"], "community": true,