diff --git a/AGENTS.md b/AGENTS.md index 7549fad..ce23896 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,13 +94,15 @@ It is the same trick `test/architecture.test.ts` already uses for the client bun | `plane-profile.ts` | new (P-R1): one plane entry → pi-ai's profile shape | | `gateway-refusal.ts` | new (P-R3): the gateway's typed refusals → `FREE_TIER` or `MODEL_UNAVAILABLE` | | `config-run.ts` | new (P-R1): an `internal/config` run and a fiber's configs on either cordis core | +| `credential-policy.ts` | the placeholder set in `key-capture.ts` and the meter's policy orders in `go-discovery.ts`, with the fill's order, the capture gate and L8's strike count new (P6) | `google-replay.ts` lived here until P-R1, and went once a Go Gemini replay stayed on one provider label (`test/mock/plane-dispatch.mock.ts`). -- `src/session.ts` · `src/turn-store.ts` — the `ses_<12hex><14base62>` derivation and the `AsyncLocalStorage` turn store. -- `src/stream-hook.ts` · `src/fetch-patch.ts` · `src/tool-fallback.ts` — the `llm/stream` hook, the fetch interceptor, and the free-tier `read`/`bash` fallback (an empty-schema `read`/`bash` counts as missing and is replaced, and a toolless chat-completions body also gets `tool_choice: "none"`; never on Responses). -- `src/utils/request-shape.ts` — the fetch patch's PURE decisions, extracted so each branch is unit-testable on its own: which plane a URL belongs to, which credential header a protocol reads, the URL and header source of a `fetch` input, the model id and tool names a JSON body carries, and the Anthropic version constant. Everything here is a function of its arguments — no context, no globals, no I/O. The rule it encodes: **a predicate that lives in a closure cannot be exercised alone**, so its branches survive until some integration path happens to take them. `hasSessionHeader` and `isOpenCodeRequest` were exported and tested; their six private siblings were not, and that was the difference. -- `src/key-capture.ts` · `src/go-discovery.ts` · `src/usage.ts` · `src/usage-contract.ts` — credential extraction, quota discovery, the usage service, and the shared shape. +- `src/session.ts` · `src/turn-store.ts` — the `ses_<12hex><14base62>` derivation and the `AsyncLocalStorage` turn store (a turn's `perCall` flag says the plane adapter shaped its headers per call, OC5). +- `src/stream-hook.ts` · `src/fetch-patch.ts` · `src/tool-fallback.ts` — the `llm/stream` hook, the fetch interceptor (the credential fill through `credentials.ts`, the User-Agent, and the plane headers wherever the plane adapter did not set them per call; it reads no `process.env`, which `test/architecture.test.ts` pins for it, `lifecycle.ts` and the plane provider), and the free-tier `read`/`bash` fallback (an empty-schema `read`/`bash` counts as missing and is replaced, and a toolless chat-completions body also gets `tool_choice: "none"`; never on Responses). +- `src/utils/request-shape.ts` — the fetch patch's PURE decisions, extracted so each branch is unit-testable on its own: which plane a URL belongs to, which credential header a protocol reads, the URL and header source of a `fetch` input, the model id and tool names a JSON body carries, the Anthropic version constant, a request's `x-opencode-plugin` marker (`pluginMarkerOn`, D27's pass-through), and the one table of plane headers both the patch and the plane adapter's per-call seam write (`planeHeadersFor`). Everything here is a function of its arguments — no context, no globals, no I/O. The rule it encodes: **a predicate that lives in a closure cannot be exercised alone**, so its branches survive until some integration path happens to take them. `hasSessionHeader` and `isOpenCodeRequest` were exported and tested; their six private siblings were not, and that was the difference. +- `src/key-capture.ts` · `src/go-discovery.ts` · `src/usage.ts` · `src/usage-contract.ts` — credential extraction and its tier, quota discovery, the usage service, and the shared shape. +- `src/utils/credential-policy.ts` · `src/credentials.ts` — the credential rules every decider shares (P6), and their effects. The pure half holds the one placeholder filter (`usableKey`), the fill's and the meter's orders per policy, the capture gate (OC3: only a request of a turn the plugin decorated, never a foreign turn or a marked request) and L8's strike count (a captured key is dropped after a second well-formed 401 in a row on its plane, counted only on requests of decorated turns: the meter's own `/usage` poll and any other turnless request neither strike a key nor lift a drop). The effect half is the capture store, one per ROOT (`captureStoreFor(ctx)`, so a test's fresh `Context` is a fresh store and nothing process-wide needs clearing), the fetch patch's one resolver for an empty or placeholder wire key (`createCredentials`: observe, fill, settle, and the one read of the process environment the fill makes), and the installation's store read. The plane adapter never asks it: its key is pi-ai's rule (D20). `test/credential-parity.test.ts` pins all four deciders side by side and was written before the move. - `src/catalog-data.ts` · `src/models-catalog.ts` · `src/models-discovery.ts` — the generated static shim, the OpenCode-catalog parser with SWR refresh, and the Settings discovery wrapper (behind `enrichModels`; off, Fetch is pi's list and `NO_DISCOVERY` passes through): on a plane the plugin serves, Settings → Models → Fetch answers pi's list plus the catalog's servable, non-deprecated models pi lacks (D3, P3), and the catalog alone while pi-ai restarts. `catalog-data.ts` is **generated**; never hand-edit it. - A note on the sweep that found the two entries around here, because it nearly produced a false one: grepping for a symbol's callers while EXCLUDING the file that defines it makes every same-file call look like no call at all. `resolveGoKeyForRef` reads as unreferenced that way and is not — `resolveGoApiKey` calls it, and the usage service calls that. (An earlier version of this line said that is "how the Go endpoint keeps Zen keys away from itself"; there is no such exclusion, and the note below records why.) Check the defining file too before believing an export is dead. @@ -111,15 +113,16 @@ It is the same trick `test/architecture.test.ts` already uses for the client bun - `scripts/generator-kit.ts` · `scripts/catalog-shim.ts` — what the two generators and `scripts/verify-catalog.ts` share: their arguments (`generatorArgs`), the source read (`readSource`), and the ONE staleness rule (`stale`: canonical data differs; key order and formatting never count), with the exit and action it leads to (`outcome`: a file current in data and in text is never rewritten; without `--write` a template change is still `current`, and with `--write` current data in text that is not the renderer's is `rewrite`, which only the limits generator, the one whole-file renderer, does). `catalog-shim.ts` is the catalog generator's pure half — the renderer and the splices, moved verbatim, and `shimStale` over every export the shim carries, the plane and family endpoints included. `test/generators.test.ts` holds both, spawns both generators with `--from` (a source that disagrees with the shipped data exits 1, for the catalog the same ids with only a plane or a family endpoint moved; the limits generator's doc made from the shipped table and the catalog payload that reproduces the shim exit 0) and the limits generator's `--write` from a scratch copy of `scripts/` and `src/` (a template change rewritten, a moved figure written), round-trips each renderer through the formatter against the committed file (`scripts/go-limits-render.ts` is the limits generator's renderer), and spawns `verify-catalog` (offline only: `--from`, `--offline`), passing on the payload that reproduces the shim and failing on a moved endpoint. - `scripts/session-band.ts` — `verify-session-band.ts`'s pure half: the vendor's id construction, ported, the four band facts with the answer each must have (`bandMismatches`), and the verdict the script prints (`bandVerdict`): "CONFIRMED" only when there is no mismatch, otherwise one `MISMATCH:` line each and exit 1. The unit run makes the verdict fail on a planted derivation, spawns the script in its passing state, and spawns a scratch copy of it beside a `src/session.ts` whose derivation leaves the band, which prints the `MISMATCH:` line and exits 1. - `scripts/freshness-scope.ts` — which of CI's three freshness checks (`catalog:shim`, `limits:shim`, `cli:version`) a pull request is GATED on: the ones whose inputs (the check's script and the local modules it loads, walked from the source as Node loads it — types erased by Node's own stripper, specifiers read by `es-module-lexer` — plus `src/identity.ts` for the CLI version; never the generated files) its own diff touches. The rest only warn, because vendor drift is not the pull request's regression: for the two generated tables the nightly run regenerates them and proposes the refresh, and for the CLI version it warns and the bump is a human pull request, which then gates. The gates fail closed: each runs unless the scope step answered `report`. The CLI version's offline half — every copy in the tree agrees with the pin, `cli:version -- --copies` — gates every pull request, since it skips the generated tables and only the repository can break it. `test/freshness-scope.test.ts` walks the real generators, runs the scope step's own shell and the CLI it calls, and evaluates the workflow's step conditions. -- `src/host/route-claim.ts` · `src/host/plane-provider.ts` · `src/host/describe-graft.ts` · `src/host/host-modules.ts` — the plugin owns the plane routes (D13). The route claim appends ONE `internal/config` listener that reads either cordis core's call shape (`src/utils/config-run.ts`: `function (this: Fiber, raw, next)` on the OLD core, `(fiber, next)` with `this` null on the NEW one), calls `next()` exactly once, re-appends itself whenever pi-ai reaches `internal/status` ACTIVE so it stays inner to pi-ai's own checking listener (the new registration first, the old one released only once the host accepted it, so a refusal while the plugin's fiber is going away throws nothing into pi-ai's emit), and hands `llm-pi-ai`'s fiber a copy of what `next()` answered without the `opencode`/`opencode-go` entries it TAKES — an entry another plugin owns (D27: pi-ai's row resolving `credentials` in a realm the plugin's context does not, compared by the key each context reads off cordis's realm map so a group's `isolate` counts, or an entry carrying the `x-opencode-plugin` header, `src/utils/plane-ownership.ts`) stays pi-ai's, is logged once, and is never counted by a restart, a handback or the reconcile; a commit run releases at once a plane the plugin registered that its candidate no longer lets it take, so pi-ai's registration of it meets no duplicate; and the claim's read-only `steppedAside()` accessor makes the stream hook run such a turn undecorated under a `foreign` turn state (`turn-store.ts`), which the fetch patch passes through before its URL claim, as it does any marked request, and keeps the 1.x discovery wrapper off its Fetch; a commit run (the fiber's raw config, the loader's stored row config, or any run while the fiber is not ACTIVE) never throws, and every fiber config is read through the feature-detected accessors, validates a Settings edit to a plane with pi-ai's own checks, and registers the plane adapter for exactly the declared planes through `registerAdapter`/`handle.replace`; on dispose it hands the planes back by restarting pi-ai (never on a reload). `plane-provider.ts` is `PlaneAdapter`, a subclass of the host's `PiAiAdapter` over pi's own `createProvider` and four protocol implementations, with the credential seams that mirror pi-ai's (D20); its `prepareCall` stream and `stream` finish the gateway's typed refusals as `FREE_TIER` or `MODEL_UNAVAILABLE` with the gateway's words, and its status except on Google-protocol models, whose failure text carries none (`src/utils/gateway-refusal.ts`), because the conversation replaces an AUTH failure's message with "API key is invalid". Its stand-in (`test/support/route-claim-stand-in.ts`, driving `test/route-claim*.test.ts`; the new core's call-shape cases are in `test/route-claim-listener.test.ts`) builds fibers of both cores — `piFiber` (the OLD core's `_config` and resolved `config`, driven through `oldRun`) and `newPiFiber` (the NEW core's raw `config`, `rawConfig` and `effectiveConfig`, no `_config`, driven through the stand-in's `waterfall`, whose per-listener `next` throws on a second call, and its `internal/status` emit) — and `test/host-planes.test.ts` runs the claim on the installed host, whichever core it is. `describe-graft.ts` is the one read-only `settings.describe` wrapper that keeps Settings showing the planes (D18). `host-modules.ts` is where the host's own modules are found — pi-ai's on its loader entry, pi, dsh-llm and the loader from the wrapper's own tree — behind the replaceable seam in `src/cordis-context.ts` (`replaceHostModuleSource`), which is how tier A runs the claim. What a protocol sends, Google's thinking control included, is the host's pi's own (D26): where a host's pi lacks something the gateway needs, the suite records a `[HOST_LIMITATION]` row and skips the cases that would exercise it by pi's own exported predicate, never a version compare. +- `src/host/route-claim.ts` · `src/host/plane-provider.ts` · `src/host/describe-graft.ts` · `src/host/host-modules.ts` — the plugin owns the plane routes (D13). The route claim appends ONE `internal/config` listener that reads either cordis core's call shape (`src/utils/config-run.ts`: `function (this: Fiber, raw, next)` on the OLD core, `(fiber, next)` with `this` null on the NEW one), calls `next()` exactly once, re-appends itself whenever pi-ai reaches `internal/status` ACTIVE so it stays inner to pi-ai's own checking listener (the new registration first, the old one released only once the host accepted it, so a refusal while the plugin's fiber is going away throws nothing into pi-ai's emit), and hands `llm-pi-ai`'s fiber a copy of what `next()` answered without the `opencode`/`opencode-go` entries it TAKES — an entry another plugin owns (D27: pi-ai's row resolving `credentials` in a realm the plugin's context does not, compared by the key each context reads off cordis's realm map so a group's `isolate` counts, or an entry carrying the `x-opencode-plugin` header, `src/utils/plane-ownership.ts`) stays pi-ai's, is logged once, and is never counted by a restart, a handback or the reconcile; a commit run releases at once a plane the plugin registered that its candidate no longer lets it take, so pi-ai's registration of it meets no duplicate; and the claim's read-only `steppedAside()` accessor makes the stream hook run such a turn undecorated under a `foreign` turn state (`turn-store.ts`), which the fetch patch passes through before its URL claim, as it does any marked request, and keeps the 1.x discovery wrapper off its Fetch; a commit run (the fiber's raw config, the loader's stored row config, or any run while the fiber is not ACTIVE) never throws, and every fiber config is read through the feature-detected accessors, validates a Settings edit to a plane with pi-ai's own checks, and registers the plane adapter for exactly the declared planes through `registerAdapter`/`handle.replace`; on dispose it hands the planes back by restarting pi-ai (never on a reload). `plane-provider.ts` is `PlaneAdapter`, a subclass of the host's `PiAiAdapter` over pi's own `createProvider` and four protocol implementations, with the credential seams that mirror pi-ai's (D20), and pi-ai's `prepareHeaders` option, as pi-ai's own adapter has it (`planeRequestHeaders`): per call, the plane headers of the turn the stream hook decorated (OC5, written by `lifecycle.ts` from `planeHeadersFor`), then the host's `llm-pi-ai/request-headers` waterfall, so another plugin's contributor runs on the planes the plugin serves (OC4), detected by behaviour; its `prepareCall` stream and `stream` finish the gateway's typed refusals as `FREE_TIER` or `MODEL_UNAVAILABLE` with the gateway's words, and its status except on Google-protocol models, whose failure text carries none (`src/utils/gateway-refusal.ts`), because the conversation replaces an AUTH failure's message with "API key is invalid". Its stand-in (`test/support/route-claim-stand-in.ts`, driving `test/route-claim*.test.ts`; the new core's call-shape cases are in `test/route-claim-listener.test.ts`) builds fibers of both cores — `piFiber` (the OLD core's `_config` and resolved `config`, driven through `oldRun`) and `newPiFiber` (the NEW core's raw `config`, `rawConfig` and `effectiveConfig`, no `_config`, driven through the stand-in's `waterfall`, whose per-listener `next` throws on a second call, and its `internal/status` emit) — and `test/host-planes.test.ts` runs the claim on the installed host, whichever core it is. `describe-graft.ts` is the one read-only `settings.describe` wrapper that keeps Settings showing the planes (D18). `host-modules.ts` is where the host's own modules are found — pi-ai's on its loader entry, pi, dsh-llm and the loader from the wrapper's own tree — behind the replaceable seam in `src/cordis-context.ts` (`replaceHostModuleSource`), which is how tier A runs the claim. What a protocol sends, Google's thinking control included, is the host's pi's own (D26): where a host's pi lacks something the gateway needs, the suite records a `[HOST_LIMITATION]` row and skips the cases that would exercise it by pi's own exported predicate, never a version compare. - `src/host/remote.ts` — `installRemoteService`, the one installer for the usage, purge and store-inspection services. One service per root, alive while a live activation holds it, reading the latest live activation's options and disposed with the last; checked against the client contract's namespace after the mount settles and reported through the activation's logger; no `ctx.provide` fallback, because a provided value is invisible to the Gateway's discovery. - `src/purge-service.ts` · `src/purge-contract.ts` — the card's "purge deprecated models" action, and the shape it answers with. It **rewrites the profile**, deleting the declared model entries the live catalog has retired, through `configEditor` (the same service the settings UI writes with). That is deliberate: a read-time filter would leave the declaration in place, and then the only way to explain a missing row is to find the filter. One source of truth, and it is the configuration. It never rewrites a plane entry another plugin owns (D27: the `x-opencode-plugin` marker, or a row whose credentials resolve in a realm the service's context does not), nor a reference to a route only such entries declare. - `src/session-cost.ts` · `src/cordis-context.ts` · `src/debug.ts` — per-turn accounting, the typed host interfaces, and stream debug logging. -- `src/host/patch-method.ts` — `patchMethod`, the one way to wrap a method on a host object. A dispose restores only while its wrapper is still the current value (otherwise it becomes a pass-through under whatever wrapped on top), and deletes the own property when the original was inherited rather than assigning it back; a second install of the same site wraps the unpatched method instead of the first install. Identity is read from own descriptors, never from a property read, because cordis's traceable proxy answers a fresh proxy for every method read (`docs/engineering-notes.md`). `rewrapOnAdaptersUpdated` reinstalls a site on `llm/adapters-updated`, for a site that must follow the registry; none uses it yet. Every instance patch in `src/` goes through this module — today two sites: model discovery (`models-discovery.ts`) and the `settings.describe` graft (`host/describe-graft.ts`) — and `test/reload.test.ts` runs apply A, apply B, dispose A, dispose B on each. Two tripwires hold the rule. `test/architecture.test.ts` is textual: anywhere `apply()` reaches but the helper, it fails on a `Reflect.set`/`defineProperty`/`deleteProperty`/`setPrototypeOf`, an `Object.assign`/`defineProperty`/`defineProperties`/`setPrototypeOf` onto `llm`, an adapter, `settings` or `globalThis` (bare or through a property path such as `registration?.adapter`; a prototype swap shadows a method without leaving an own property), a dotted or bracketed assignment (through `?.` or `!` too) onto the first three, and `globalThis.x =` (the global `fetch` patch is the one named exemption, until P6); a write through a local alias or a cast receiver escapes it. The `apply()`-twice reload case is behavioural: it requires the helper's record on every own function `apply()` leaves on the stand-in's `llm` and `settings`. +- `src/host/global-fetch.ts` — `installGlobalFetch`, the plugin's one write to `globalThis.fetch` (P6). It reads the fetch it wraps inside the effect, keeps a chain of its links, turns a link disposed under another into a pass-through, and on a restore unwinds through disposed links, so apply A, apply B, dispose A, dispose B ends at the fetch that was there, in either order, and a function the plugin did not install is never replaced. It is the one named exemption of the host-write tripwire below, which stays while the patch keeps relays, listing enrichment, the credential fill, the body fallback and the User-Agent. +- `src/host/patch-method.ts` — `patchMethod`, the one way to wrap a method on a host object. A dispose restores only while its wrapper is still the current value (otherwise it becomes a pass-through under whatever wrapped on top), and deletes the own property when the original was inherited rather than assigning it back; a second install of the same site wraps the unpatched method instead of the first install. Identity is read from own descriptors, never from a property read, because cordis's traceable proxy answers a fresh proxy for every method read (`docs/engineering-notes.md`). `rewrapOnAdaptersUpdated` reinstalls a site on `llm/adapters-updated`, for a site that must follow the registry; none uses it yet. Every instance patch in `src/` goes through this module — today two sites: model discovery (`models-discovery.ts`) and the `settings.describe` graft (`host/describe-graft.ts`) — and `test/reload.test.ts` runs apply A, apply B, dispose A, dispose B on each. Two tripwires hold the rule. `test/architecture.test.ts` is textual: anywhere `apply()` reaches but the helper, it fails on a `Reflect.set`/`defineProperty`/`deleteProperty`/`setPrototypeOf`, an `Object.assign`/`defineProperty`/`defineProperties`/`setPrototypeOf` onto `llm`, an adapter, `settings` or `globalThis` (bare or through a property path such as `registration?.adapter`; a prototype swap shadows a method without leaving an own property), a dotted or bracketed assignment (through `?.` or `!` too) onto the first three, and `globalThis.x =` (the global `fetch` installer, `host/global-fetch.ts`, is the one named exemption); a write through a local alias or a cast receiver escapes it. The `apply()`-twice reload case is behavioural: it requires the helper's record on every own function `apply()` leaves on the stand-in's `llm` and `settings`. - `src/utils/config-run.ts` — an `internal/config` run and a fiber's three configs, read the same way on either cordis core, held at 100% coverage: `configRunOf` decodes the call (the fiber is `this` on the OLD shape, the first argument on the NEW one, `next` the last argument on both), `isFiber` is the structural fiber predicate (`fiber.ctx.fiber === fiber`), `rawConfigOf`/`effectiveConfigOf` are the feature-detected accessors (`rawConfig` else `_config`, `effectiveConfig` else `config`), `entryConfigOf` reads the loader's stored row config (`fiber.entry.options.config`), and `isCommitRun` tells a commit from an editor candidate by identity. `test/support/config-shape.ts` re-exports the predicate and the accessors, so a contract and the claim never read a fiber two ways. Told apart by the call and the fiber's own fields, never by a version. - `src/utils/protocols.ts` · `src/utils/model-metadata.ts` · `src/utils/plane-model.ts` · `src/utils/plane-profile.ts` · `src/utils/plane-ownership.ts` · `src/utils/gateway-refusal.ts` — the plane's pure decisions, each held at 100% coverage: the code a gateway refusal finishes with (its type token in pi's failure text, the status at the text's head; Google's text carries none), which declared plane entries the claim takes and which another plugin owns (the `credentials` realm each context resolves, read off cordis's realm map with the rows' labels as the fallback, and the `x-opencode-plugin` marker, D27; `go-discovery.ts` asks the same two questions so the meter never reads another plugin's entry), the SDK → protocol table and the per-protocol base tables (every value measured; see `docs/redirect-planes.md`), the reasoning efforts a model offers (D1), the pi model object one declared model becomes (protocol from the catalog, then the route's `api`, and the base from the endpoint family table, never from pi's own catalog, D16, D26; metadata from the user's row first, D17; the family `auto` resolves to, `AUTO_ENDPOINT_FAMILY`, P-R2), and the profile one plane entry becomes, with pi-ai's own checks and messages for every malformed field, never throwing; the default window and output tokens are the ones pi-ai's own `Config` fills in, never a copy (D17), and so are the image-count bounds (`maxRequestImages`, and `imageOffloadCountQuantum` derived from it as pi-ai's own profile resolution does) wherever the installed pi-ai's `Config` fills them and absent where it does not. - `src/attachment-services.ts` — optional attachment and filesystem services for the plane adapter's image requests, captured through Cordis child scopes. -- `src/opencode-paths.ts` — where an OpenCode installation keeps its files, ported from `~/dev/opencode`'s `global-roots.ts` (the directory) and `database-path.ts` (the filename). It takes `home`, `env` and `channel` as parameters and reads neither the environment nor the filesystem, which is what makes the Windows and Linux layouts testable from here. Two facts it encodes that are easy to get wrong: the directory is XDG on EVERY platform — macOS and Windows use `~/.local/share` too, and `os.homedir()` is the only platform-dependent call — and the FILENAME is not constant, being `$OPENCODE_DB`, else `opencode.db` on a stable channel, else `opencode-.db`. The database sits under `data` while the config sits under `config`, so one root cannot serve both. It is the foundation of the opt-in reader: `go-discovery.ts`'s `resolveOpencodeStoreKey` is what imports it, and nothing else does. +- `src/opencode-paths.ts` — where an OpenCode installation keeps its files, ported from `~/dev/opencode`'s `global-roots.ts` (the directory) and `database-path.ts` (the filename). It takes `home`, `env` and `channel` as parameters and reads neither the environment nor the filesystem, which is what makes the Windows and Linux layouts testable from here. Two facts it encodes that are easy to get wrong: the directory is XDG on EVERY platform — macOS and Windows use `~/.local/share` too, and `os.homedir()` is the only platform-dependent call — and the FILENAME is not constant, being `$OPENCODE_DB`, else `opencode.db` on a stable channel, else `opencode-.db`. The database sits under `data` while the config sits under `config`, so one root cannot serve both. It is the foundation of the opt-in reader: `credentials.ts`'s `resolveOpencodeStoreKey` imports it, and so does `opencode-store-service.ts` (the inspection's path); nothing else does. - `src/opencode-store.ts` — reading the credentials an OpenCode installation already holds, through `node:sqlite`. Two rules shape it: nothing throws (a missing file, a foreign schema and `:memory:` all answer `undefined`), and a value never leaves the return value — no log line, no error message, no client bundle. `node:sqlite` is host-only, which is what keeps the module on the host side of the bundle rule. It is reached only through `resolveOpencodeStoreKey`, which is the last step of every key-source policy and is off unless `readOpencodeStore` is on. Its second reader, `inspectOpencodeStore`, answers the _other_ question — "is there a credential here, and whose is it?" — with a sanitized summary (email, org, kind, expiry) and never the token, which is what lets the settings card show the evidence beside the permission. - **What the plugin page shows is `docs/detail.md`, not the README.** The page renders one document: the Markdown `meta.detail` in `locale/.json` names, else the whole `README.md`. This package declared nothing for years, so its page carried 461 lines of engineering notes above the settings card. It now declares a page per language that is **one image and nothing else** — a UI preview of the card and the meter (`docs/media/preview.svg`, `.zh.svg`) — which is the shape the upstream plugins use, because the header above the card already carries the title and the one-sentence description. The image is served from the package, so `files` has to ship it (the detail-image route reads package-relative paths). `test/plugin-detail.test.ts` holds the contract: a declared detail in every locale, a path that exists AND is shipped, an image that does the same, and a page that is the picture and nothing else. - `src/opencode-store-contract.ts` · `src/opencode-store-service.ts` — the inspection seam: the sanitized summary type both sides share, and the host service that produces it. The contract is pure data (no `node:`, no context), so the client bundle may import it; the service is the half that touches `node:sqlite` and the filesystem, and it rewrites the store path to `~`-relative before answering — a home directory is a fact about the machine, not about the plugin. `inspect` is declared through the `Object.defineProperty` marker rather than `@Remote`, for the reason `usage.ts` documents. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9ec3797..96f9349 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -83,8 +83,8 @@ Two tiers, both in-process: What every case does: - **Install the recording fetch before mounting** (`vi.stubGlobal("fetch", recordingFetch().fetch)`) and restore it with `vi.unstubAllGlobals()` after disposal: the plugin's fetch patch wraps whatever `fetch` is current when it mounts. The recording fetch answers `opencode.ai` and `models.opencode.ai` with a 401, refuses every other host, and keeps credential headers by length only. -- **Dispose in `afterEach`** (or a `finally`), and boot per case: a key the fetch patch captured in one case would change the next one's listing. -- **Credentials come from the fakes, not the environment.** The fakes (`fakeCredentials`, `fakeLaunchEnvironment`) are provided on the root, which is where pi-ai looks first. The plugin reads `OPENCODE_API_KEY`/`OPENCODE_GO_API_KEY` from the environment directly, so `bootTierB` blanks either one your shell exports for the life of the boot and restores it on dispose: the suite measures the keyless deployment whatever the shell holds, and the characterization's keyless `[BASELINE]` rows are the guard (they fail on a shell that exports a key if the blanking ever stops). That guard only fires where a key is exported: CI's unit job exports none, so there the blanking has nothing to do and nothing checks it. A case never sets them itself. +- **Dispose in `afterEach`** (or a `finally`), and boot per case: a key the fetch patch captured is kept per root, so a host shared between cases would carry one case's key into the next one's listing. +- **Credentials come from the fakes, not the environment.** The fakes (`fakeCredentials`, `fakeLaunchEnvironment`) are provided on the root, which is where pi-ai looks first. The plugin reads `OPENCODE_API_KEY`/`OPENCODE_GO_API_KEY` from the environment directly (the fill in `src/credentials.ts`, the meter in `src/go-discovery.ts`), so the suite runs keyless whatever your shell exports: `test/support/offline.ts`, a setup file of the unit and mock configs, unsets both before every file, so tier B always boots keyless there. `bootTierB` also blanks either one that is set for the life of the boot and restores it on dispose; under those two configs it has nothing to do, and it is the second line for a runner without that setup file. A tier-B case never sets them itself. A unit case that tests the declared source does set one, through `vi.stubEnv` or a plain assignment, and undoes it in its file's `afterEach` (`vi.unstubAllEnvs()` or a named `delete`), so the next file starts keyless again (the parity pin's meter contrast is one). - **Give tier-B cases 30 s**, and wait with a deadline (`waitForPlaneOwner`, 10 s by default, so a plane the plugin never claims fails by name inside the hook's budget), never a fixed sleep: the route claim registers the planes asynchronously, after pi-ai's commit. `piAiRestarts` counts pi-ai's restarts when a case needs to know how many the claim caused. - **A first row that fails does not hang the boot.** Tier B holds the second of pi-ai and the plugin until the first applies OR its fiber settles in any state, so a row whose config the schema rejects boots with that fiber FAILED (`fiber.await()` rethrows the real error) and the other row applied. @@ -101,7 +101,7 @@ What every case does: - **Cells, per channel, pi unpatched in both.** `npm` is the published host exactly as npm resolves it, cordis and pi included, what an npm user runs, and asserts the `newest` rows while its pi is the channel record's; a pi published since the record still has to sit in the bridge's range, but the per-model rows (a newer pi's own entry can still move a model's metadata where the catalog states none) are skipped with a warning, and the nightly `host-drift` job names the new pi. The listings before and after a turn, the save rows (the catalog-unknown id is accepted on the first try) and the row that the plane provider is built from the host prefix's own pi are asserted in every cell, since the plugin owns both planes there on either host core and none of them depends on which ids pi describes; a `[BASELINE]` row asserts that both planes are the plugin's `PlaneAdapter` whichever `internal/config` call shape the host dispatched (next bullet). `floor` is the tree the desktop app ships: npm `overrides` (`floorOverrides` in `host-versions.ts`) force the channel's whole cordis family (cordis, the loader, the include, group and timer plugins, cosmokit, schemastery) at the record's versions, which are the floors of the `~` ranges the published cluster declares (what the harness vendors at the tag), and pi with its telemetry package at the range's floor; the job and the e2e assert that npm applied each one, and the cell asserts every row of the channel's floor cell. In both cells the e2e also holds each cordis-family field to the floor of the range the installed published package declares for it, which no override rewrites, with one rule for cosmokit: its declarer is cordis, so it is checked only where the installed cordis is the record's, and elsewhere only the nightly drift report checks it (measured 2026-11-12, every cell's installed cordis is its record's, so cosmokit is checked in all four). It is cached by channel, `dsh` and a hash of those overrides, so a cache filled before the record or its overrides moved is never reused; the rest of the tree is what npm resolved when the cache was filled. The installed `dsh` must be the channel record's, so a prefix of the wrong channel fails by name. The save rows skip only where the host itself cannot save (next bullet). - **Settings' fetch.** The probe also records what Settings → Models → Fetch offers on each plane, through the gateway's Remote face. Every cell asserts the whole servable catalog, each id once, in the Remote's five fields, and the order: the list the prefix's own pi exports (`getBuiltinModels`, read from the prefix, not the checkout) first, then the catalog models that pi lacks. The wrapper complements a fetch only while the route claim has engaged (`RouteClaim.claiming()`), which it does on both host cores, so each row first asserts both planes on the plugin's `PlaneAdapter`. It reads engaged through a handover's window too, while the newly served row's restart is in flight: the fetch is complemented until the row unloads and the plane's catalog alone while it does, as in the mount's restart. Only a served row whose restart has settled still holding a plane (a call shape the claim's listener does not speak) leaves the fetch pi's own list. - **The host's own failures are recorded, not worked around.** Only the `npm` cell lets cordis float, as the published host's `~` ranges do for a user, and the job reports what it resolved. Where that leaves the host unable to run its own save path, the run records a `[HOST_LIMITATION]` row (titled with the channel and the `dsh`) and skips the save rows. It is detected from what the host answered, never from a version (D26): the plane edit and a control edit no plugin's listener reads (the probe's own entry) both fail with the same `TypeError` thrown by `@deepseek-ai/dsh-app-boot`; where the host saves, the row skips and a `[BASELINE]` row asserts the control was accepted. It was alpha's `0.2.2-alpha.2` as npm installed it: cordis `4.0.6-alpha.2` calls `internal/update` in a new shape while that `dsh-app-boot` registered its listener in the old one, so every config-editor save threw `next is not a function`. `0.2.2-alpha.3` and `0.2.2-rc.2` ship the cordis core their `dsh-app-boot` was written for: measured 2026-11-12, all four cells (both channels, `npm` and `floor`) save the control edit, so the row skips everywhere and the save rows run. The same core hands `internal/config` listeners the fiber and reads the config from `next()`, where the older one bound the fiber as `this` and passed the config; the route claim speaks both (`src/utils/config-run.ts`). The probe records the shape of every dispatch (`configHook`, the first; `configHooks`, a count per shape) with the claim's own fiber predicate, and a `[BASELINE]` row requires one known shape throughout and both planes on the plugin's `PlaneAdapter`. It was a `[KNOWN_DEFECT]` row asserting that pi-ai served both planes on the new core, with the rows that need the claim skipping by name, until the claim spoke that shape. -- **Triggers.** Dispatch and the nightly run take both cells of both channels. A pull request takes the `npm` cell of both channels, and only when it touches the host seam — `src/host/**` (the route claim, the plane adapter, the Settings graft, the host-module loaders) and the modules whose behaviour depends on the real loader and apply order beside it, `src/lifecycle.ts`, `src/identity.ts`, `src/cordis-context.ts` and `src/models-discovery.ts`, and the two modules that still install host-level patches until they move under `src/host/` (`src/fetch-patch.ts`, the global fetch wrapper whose order the probe reads, and `src/stream-hook.ts`) (every other row producer, such as the pure plane model and profile in `src/utils/`, `src/key-capture.ts`, `src/models-catalog.ts` or `src/config.ts`, is covered on each pull request by the in-process characterization of the same rows, and by the nightly run), `cordis.patch.yml`, `test/e2e/host/**`, `test/e2e/host-binary.e2e.ts`, `test/support/host.ts` (the rows the binary e2e asserts), `test/support/e2e-env.ts` (the reader the binary e2e's gate, prefix and cell come through; its channel is `host-versions.ts`'s `selectedHost`), `test/support/host-versions.ts` (what the job installs), `scripts/host-drift.ts` (the family table the binary e2e asserts against the installed manifests), `.github/workflows/ci.yml`, `.github/actions/` (the composite setup action, which holds the install), `vitest.e2e.config.ts` or `vite.config.ts` (the job's own steps and runner config; `vite.config.ts` also holds the pack config that builds `lib/index.mjs`, the bundle only this job loads into a real host, and the test settings the e2e config inherits) (scoped by a step: a workflow-level path filter would silence every other job; a diff the step cannot compute fails it rather than skipping the job). `package.json` is left out because every dependency bump touches it, so a change to its `test:e2e:host` script alone is exercised only by the nightly run. It needs no secret. +- **Triggers.** Dispatch and the nightly run take both cells of both channels. A pull request takes the `npm` cell of both channels, and only when it touches the host seam — `src/host/**` (the route claim, the plane adapter, the Settings graft, the host-module loaders) and the modules whose behaviour depends on the real loader and apply order beside it, `src/lifecycle.ts`, `src/identity.ts`, `src/cordis-context.ts` and `src/models-discovery.ts`, and the two modules that still carry host-level patches outside `src/host/` (`src/fetch-patch.ts`, the global fetch wrapper whose order the probe reads, installed by `src/host/global-fetch.ts`, and `src/stream-hook.ts`) (every other row producer, such as the pure plane model and profile in `src/utils/`, `src/key-capture.ts`, `src/models-catalog.ts` or `src/config.ts`, is covered on each pull request by the in-process characterization of the same rows, and by the nightly run), `cordis.patch.yml`, `test/e2e/host/**`, `test/e2e/host-binary.e2e.ts`, `test/support/host.ts` (the rows the binary e2e asserts), `test/support/e2e-env.ts` (the reader the binary e2e's gate, prefix and cell come through; its channel is `host-versions.ts`'s `selectedHost`), `test/support/host-versions.ts` (what the job installs), `scripts/host-drift.ts` (the family table the binary e2e asserts against the installed manifests), `.github/workflows/ci.yml`, `.github/actions/` (the composite setup action, which holds the install), `vitest.e2e.config.ts` or `vite.config.ts` (the job's own steps and runner config; `vite.config.ts` also holds the pack config that builds `lib/index.mjs`, the bundle only this job loads into a real host, and the test settings the e2e config inherits) (scoped by a step: a workflow-level path filter would silence every other job; a diff the step cannot compute fails it rather than skipping the job). `package.json` is left out because every dependency bump touches it, so a change to its `test:e2e:host` script alone is exercised only by the nightly run. It needs no secret. To run it locally, install a channel's host into a prefix outside the checkout, then point the suite at it (placeholder paths; `pnpm` must be on `PATH`). The first line reads the channel's record from `test/support/host-versions.ts`, the same way the CI job does, so the snippet never names a version itself: @@ -143,7 +143,7 @@ The web profile wires this checkout with `link:`, so builds are picked up like t - **No secret fixtures.** A session id a gateway, the mock or a live probe READS is derived at runtime (`openCodeSessionIdFor`) or read from `OPENCODE_SESSION_ID`, never written out; an opaque value a captured `fetch` only echoes, or a deliberately malformed input, may stay literal. An API key is never a fixture. `lib/` and `*.log` stay gitignored. - **Restore globals.** Tests that touch `globalThis.fetch` or `process.env` must restore them in `afterEach` (`vi.unstubAllGlobals()`, `delete process.env.…`). - **Offline by construction.** `test/support/offline.ts` refuses every non-loopback request in the unit and mock suites. The catalog's background revalidation used to reach `models.opencode.ai` dozens of times per run, so a networked runner's results could depend on the vendor's live catalog. A case that means to fetch stubs `fetch` itself. -- **No order dependence.** `test/support/reset-process-state.ts` clears the plugin's module-level stores (captured keys, session spend, the live catalog) after every test. A new module-level store gets a reset next to its siblings. `pnpm run test:shuffle` is how to check, and CI runs it. +- **No order dependence.** `test/support/reset-process-state.ts` clears the plugin's module-level stores (session spend, the live catalog) after every test. Captured keys are kept per composition root (`captureStoreFor`): a case seeds and reads the store of the context it resolves against, and a fresh `Context` starts empty. A new module-level store gets a reset next to its siblings. `pnpm run test:shuffle` is how to check, and CI runs it. - **Tests reach `src` through `test/support/src.ts`.** It re-exports, from each defining module, everything a test needs, so a module move or a barrel change edits one file instead of thirty. A new test imports from `./support/src.ts` (`../support/src.ts` under `test/mock` and `test/e2e`); add a missing name there rather than importing a `src` path. The exceptions are `vi.mock("../src/x.ts")` targets (and their `importOriginal` type), which must name the module; fresh-module re-imports after `vi.resetModules()`, whose subject is module identity; the architecture and public-API tests, whose subject is the `src` layout and the barrel; the jsdom (client) tests, which import the defining module directly, because `src.ts` re-exports the host graph (`node:sqlite`, pi, `lifecycle.ts`) and the next rule keeps that out of client tests; and the setup file `test/support/reset-process-state.ts`, which runs before the jsdom tests too. `test/architecture.test.ts` fails on a static or side-effect `src` import anywhere else, on a dynamic `import("../src/…")` in a file that never calls `vi.resetModules()`, and on a jsdom test that value-imports the door. Importing the door loads the whole `src` graph, host and client, so a module that fails to load fails every test that comes through it. - **Host-only fixtures stay out of shared helpers.** `test/test-helpers.ts` is imported by the jsdom (client) tests, so anything that needs `node:sqlite` or the filesystem belongs in `test/support/`, as `opencode-store-fixture.ts` does. It carries no contexts either. - **A unit test that means "the plugin, applied" mounts it on a real cordis `Context`.** `test/support/composition.ts`'s `mountPlugin` does what the Loader does — `ctx.plugin({ apply, Config, inject, name }, config)`, the module's own exports and the row's config, which makes the schema resolve the config and the fiber carry the plugin's name — so cordis decides when each part runs, a turn goes through `ctx.waterfall("llm/stream", …)` as `LlmRuntime` sends it, and `disposeMounted()` (in `afterEach`) undoes the plugin's effects through `fiber.dispose()`. A service under test gets `new Context()` with what it reads provided on it (one context per service: a cordis Service registers itself on the context it is built on). The mount passes those exports unchanged, so repeated activations on one root share one cordis runtime, as the Loader's do. The go-discovery and usage-service files serve their loader rows and credentials on `new Context()` too (`test/support/loader-rows.ts`). The one stand-in for the plugin's composition, `degradedHost`, is for a composition a real `Context` cannot be, because a real one registers what it is asked to and always has `plugin`: a `plugin` that registers nothing or throws, with and without `get` (the three unreachable-service diagnostics and a refused mount), a `plugin` whose fiber the case settles (`apply` waiting on the services' reports), and a composition with no `plugin` (with or without `provide`, which is never called). Module-level clause tests keep the object their function reads where a real host cannot be put in the state they need on demand: the route claim's stand-in host (`test/support/route-claim-stand-in.ts`: a LOADING or FAILED pi-ai, a null uid, a refusing registry), with `test/host-planes*.test.ts` covering the claim on the real host, `test/remote-service.test.ts`'s stand-in compositions for `installRemoteService`'s clauses (a `plugin` that throws, answers no fiber or answers a fiber the case settles; no `plugin`; no `effect`), and the `llm` objects the discovery, Settings-graft and reload seams wrap. The client entry's tests (`test/settings-page*.test.tsx`, `test/client-bundle.test.ts`) keep a hand-built settings host: the web runtime has no in-process tier, and the jsdom files must not load the door. `until` and `logLines` live in `test/support/cordis-wait.ts` (re-exported by `host.ts`), so a bare-`Context` unit file loads no host package through them. @@ -158,7 +158,7 @@ The web profile wires this checkout with `link:`, so builds are picked up like t - **Raise them when you genuinely add coverage** — a PR that lifts statements by a few points should lift the threshold with it, or the next contributor inherits a gate nobody re-measured. - **Never set one above the current measurement.** That does not make the suite better; it makes every subsequent PR fail until someone deletes tests. -`src/index.ts` is excluded from the report — it is a pure re-export barrel, and the coverage tools attribute an untaken re-export line to whichever file re-exports it, so leaving it in reports a hole nobody can fill while hiding real ones. Load-bearing modules carry their own per-file floors, so a well-covered average cannot hide one that stopped being exercised: `host/patch-method.ts`, `host/remote.ts`, the four pure plane modules (`utils/protocols.ts`, `utils/model-metadata.ts`, `utils/plane-model.ts`, `utils/plane-profile.ts`) and `utils/gateway-refusal.ts` at 100%, because each branch is a reload case, a mount outcome, a protocol, a precedence, one of pi-ai's checks, a refusal type or a text shape; `host/route-claim.ts`, `host/plane-provider.ts`, `host/describe-graft.ts` and `host/host-modules.ts` just below what they measure; and the three modules that install the plugin's effects on the host, `lifecycle.ts`, `stream-hook.ts` and `fetch-patch.ts`, just below what they measure too, with the branches no composition reaches named beside the floor. `test/architecture.test.ts` fails the build on a floor whose file no longer exists, which would otherwise be a floor on nothing. +`src/index.ts` is excluded from the report — it is a pure re-export barrel, and the coverage tools attribute an untaken re-export line to whichever file re-exports it, so leaving it in reports a hole nobody can fill while hiding real ones. Load-bearing modules carry their own per-file floors, so a well-covered average cannot hide one that stopped being exercised: `host/patch-method.ts`, `host/remote.ts`, `host/global-fetch.ts`, the credential rules and their resolver (`utils/credential-policy.ts`, `credentials.ts`), the four pure plane modules (`utils/protocols.ts`, `utils/model-metadata.ts`, `utils/plane-model.ts`, `utils/plane-profile.ts`) and `utils/gateway-refusal.ts` at 100%, because each branch is a reload case, a mount outcome, a disposal order, a credential source or strike, a protocol, a precedence, one of pi-ai's checks, a refusal type or a text shape; `host/route-claim.ts`, `host/plane-provider.ts`, `host/describe-graft.ts` and `host/host-modules.ts` just below what they measure; and the three modules that install the plugin's effects on the host, `lifecycle.ts`, `stream-hook.ts` and `fetch-patch.ts`, just below what they measure too, with the branches no composition reaches named beside the floor. `test/architecture.test.ts` fails the build on a floor whose file no longer exists, which would otherwise be a floor on nothing. ## The freshness checks in CI diff --git a/README.md b/README.md index 1110782..8bb4db1 100644 --- a/README.md +++ b/README.md @@ -259,7 +259,7 @@ Go usage Healthy Monthly allowance mimo-v2.6-flash · Go $60 · Plus $120 ⓘ ``` -**This build carries the API key path only.** There is no sign-in row and no device flow: a credential comes from the deployment's configuration, from a key captured on a live request, or — when `readOpencodeStore` is on — from the OpenCode installation's own store. The Console login (device flow, session store, credential pool) lives on the `v2` line and is deliberately not in `main`, so nothing here depends on a service the host may not mount. +**This build carries the API key path only.** There is no sign-in row and no device flow: a credential comes from the deployment's configuration, from a key captured on a live request, or — when `readOpencodeStore` is on — from the OpenCode installation's own store. A key is captured only from a request of a turn this plugin decorated, and only fills a request whose own key is empty or a placeholder; a captured key is dropped after the gateway refuses it twice in a row on its plane (a `401` on a well-formed session, with no success between, on a request of the plugin's own turns), and comes back once such a request carrying it is accepted. The Console login (device flow, session store, credential pool) lives on the `v2` line and is deliberately not in `main`, so nothing here depends on a service the host may not mount. **If the card looks like the previous build after updating, the host process has not restarted.** The host bundle is read once at process start, so a browser reload keeps running the previous `lib/index.mjs`; stop and restart `dsh web`. The row is the quickest way to tell, because it is new in the same build as everything else. @@ -411,6 +411,7 @@ OpenCode's own Console plugin (`npx @opencode/console setup deepseek-harness`) c - **Settings → Models → Fetch on a Console route is `llm-pi-ai`'s own list.** No catalog model is added to it, and while `llm-pi-ai` restarts the fetch fails as `llm-pi-ai`'s own does rather than answering the catalog; a plane entry of your own beside it keeps the catalog's models. - **The log says so once per route**, naming the realm or the header: `… dsh-opencode-patch leaves the route opencode to pi-ai`. - **A shared key name is read by both.** Only the credentials service is split into realms; the launch environment is not. `OPENCODE_API_KEY` (or `OPENCODE_GO_API_KEY`) exported in the environment is read by this plugin's meter and your own planes, and by `llm-pi-ai` for a Console route that names no key of its own. Keep the workspace token under the name the Console's setup gives it, which this plugin never reads. +- **The plugin records a key only from a turn it decorated.** A Console request — marked, on a turn of a Console route, or sent outside any turn — is never recorded, never used to fill another request, and never sent to the Go usage endpoint. - **The workspace's policies gate every turn and tool call**, this plugin's planes included: what the Console's workspace allows or blocks applies to a turn whichever plugin serves its route. - **The Console's setup takes an exported `OPENCODE_API_KEY` as its own credential**, ahead of its sign-in. If you use both, do not have `OPENCODE_API_KEY` exported in the shell that runs the Console's setup, or give the planes a key reference of their own (`apiKeyEnv` naming another variable, such as `OPENCODE_ZEN_API_KEY`). With a reference of their own, the Go meter's Zen-credit check still reads `OPENCODE_API_KEY` until a Zen turn has run, so it shows Zen credit as not configured until then. @@ -447,6 +448,8 @@ OpenCode's own Console plugin (`npx @opencode/console setup deepseek-harness`) c - **`@viztor/dsh-opencode` is deprecated, and still published.** It is a thin wrapper that re-exports `dsh-opencode-patch`, so an install on the old name keeps resolving; the registry marks it deprecated and points at the canonical name. New installs should use `dsh-opencode-patch` or `@viztor/dsh-opencode-patch`. - **A route another plugin owns is left to it.** A plane entry in `llm-pi-ai`'s row is served by `llm-pi-ai`, not by this plugin, when that row resolves credentials in a realm this plugin does not or the entry carries the `x-opencode-plugin` header — the shape OpenCode Console's setup writes — and no header, key or meter of this plugin's touches its traffic. In the released 1.x, a turn on such a route that the plugin moved onto one of its hidden Responses, Messages or Google routes was resolved with this plugin's credentials and failed for want of the Console's token, and every other turn on it carried this plugin's headers and had its key recorded for the meter; see [With OpenCode Console installed](#with-opencode-console-installed). - **The gateway's refusals are reported as what they are.** On the planes this plugin serves, a `FreeTierError` (403) or `FreeUsageLimitError` (429) now finishes the turn as `FREE_TIER`, and a `RegionError`, `ModelDeprecated` or `ModelProtocolUnsupported` as `MODEL_UNAVAILABLE`, each with the gateway's words, and its status except on Google-protocol models, whose failure text carries none. The conversation used to show "API key is invalid" for the 403s and "Request quota exhausted." for the usage cap, with the gateway's message dropped. Like the codes they replace, neither new code is in the host's retryable set, so a refused turn is still not resent. A free Chat Completions turn with no tools of its own now carries `tool_choice: none` beside the free tier's `read` and `bash`, and a `read` or `bash` declared with an empty schema is replaced by the full one. +- **A key seen on a request is kept only from the plugin's own turns, and dropped after two refusals.** The plugin used to record the key of every request it claimed, a request outside any turn included, and to replay the latest one onto any request a configured provider claimed; it now records a key only from a request of a turn it decorated, fills a request on neither plane only with a key its own route sent there and never fills a gateway request or the meter with such a relay key (a route named `opencode` or `opencode-go` is the exception: its key is that plane's even when its own `baseURL` points elsewhere, as a mirror's would be), and drops a captured key after the gateway refuses it twice in a row on its plane, on its own turns' requests: a request outside them, the usage meter's own poll included, never counts against a key. A blank exported key or a placeholder in the installation's store no longer goes out as a credential, and a blank or placeholder `OPENCODE_API_KEY` no longer counts as Zen credit for the meter's overflow card. Disabling two overlapping activations in either order now leaves the `fetch` that was there before them. +- **The planes' headers are set per call, and other plugins' `llm-pi-ai/request-headers` contributors run there.** On the planes this plugin serves, its session, origin and project headers are written through `llm-pi-ai`'s per-call header seam, as `llm-pi-ai`'s own routes write theirs, and another plugin's contributor to that seam now runs on them too: one that throws fails the turn with `REQUEST_HEADERS`, as it already did on `llm-pi-ai`'s routes. The seam first shipped in harness `0.2.2-alpha.3` and `0.2.2-rc.1`. The supported range is unchanged: on an older host (`0.2.2-alpha.2` or a `0.2.1` build), the plugin's own headers still go out, written by its fetch patch as before, and other plugins' contributors do not run on the planes there, because that host never asks for them (see the seam's floor below). - **Usage settings apply when the plugin is applied again, and disabling the plugin withdraws its services.** A change to `usageBaseURL`, `keySource` or `readOpencodeStore`, or turning `usageEnabled` off, takes effect the next time the plugin is applied: when it is disabled and enabled again, or when `dsh` restarts. The usage service used to keep the values it started with until `dsh` restarted, however often the plugin was disabled and enabled in between. Disabling the plugin now withdraws its usage, purge and store-inspection services instead of leaving them answering. ## 📜 Compatibility & Verification @@ -463,6 +466,8 @@ The harness publishes two **channels**, `alpha` and `rc`, and they are parallel The first clause covers the `0.2.1` line on both channels: its lower bound (`alpha.1`) sorts below every `rc` of the same line, so rc needs no separate entry. The second is **not** redundant — semver excludes prereleases unless a comparator in the same `major.minor.patch` tuple carries one, so `<0.3.0` alone would silently drop every `0.2.2-*` build, alpha and rc alike. Both clauses stop at `0.3.0`, which leaves the next line a separate decision rather than a silent widening. +**The request-headers seam's floor.** On the planes, the plugin writes its session, origin and project headers through `llm-pi-ai`'s per-call header seam (`llm-pi-ai/request-headers`) and runs other plugins' contributors to it there, as `llm-pi-ai`'s own routes do. The seam first shipped in `0.2.2-alpha.3` and `0.2.2-rc.1`; `0.2.2-alpha.2` and every `0.2.1` build lack it. The range above still admits them, on purpose: the plugin detects the seam by behaviour, never by version, and on a host without it the plugin's own headers still go out, written by its fetch patch as before, while other plugins' `llm-pi-ai/request-headers` contributors do not run on the planes, because that host never calls them. Refusing those hosts at install would change nothing at runtime, so the floor is stated here rather than in the peer. + The optional `@deepseek-ai/cordis` peer follows the typert range. Each line moved the host core: the `0.2.1` builds peer `~4.0.5` (or a `4.0.5` prerelease), the `0.2.2` alphas a `4.0.6` prerelease, and the `0.2.2` rcs `~4.1.0`. A fresh install takes the cordis the **newest** admitted typert build peers on, so a cordis peer that misses it fails with `ERESOLVE`; one that misses an older line's cordis fails beside a host already installed on that line. The peer therefore admits every one of them and stops at the next tuple: ``` @@ -477,7 +482,7 @@ No known defect of this plugin's is open on a supported host: both channels' lat | Surface | Target | | :-- | :-- | -| **Harness line** | **`0.2.1`** and the **`0.2.2`** prereleases, `alpha` and `rc` channels alike (peer: the range above) | +| **Harness line** | **`0.2.1`** and the **`0.2.2`** prereleases, `alpha` and `rc` channels alike (peer: the range above); other plugins' header contributors run on the planes from `0.2.2-alpha.3` and `0.2.2-rc.1` | | **Host core** | `@deepseek-ai/cordis` `4.0.4` up to `4.1.x`, including the `4.0.5` and `4.0.6` prereleases (optional peer: the range above) | | **Plugin package** | [`dsh-opencode-patch`](https://www.npmjs.com/package/dsh-opencode-patch) | | **Host profile** | DSH Web profile (`patchReload: live`) | diff --git a/README.zh-CN.md b/README.zh-CN.md index 92be0f2..9e08864 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -255,7 +255,7 @@ Go 用量 状态正常 月度额度 mimo-v2.6-flash · Go $60 · Plus $120 ⓘ ``` -**这个版本只带 API 密钥路径。** 没有登录行,也没有设备流:凭据来自部署的配置、来自从实际请求中捕获的密钥,或者——在开启 `readOpencodeStore` 时——来自 OpenCode 安装自身的存储。Console 登录(设备流、会话存储、凭据池)在 `v2` 线上,刻意不放进 `main`,因此这里不依赖宿主可能没有挂载的服务。 +**这个版本只带 API 密钥路径。** 没有登录行,也没有设备流:凭据来自部署的配置、来自从实际请求中捕获的密钥,或者——在开启 `readOpencodeStore` 时——来自 OpenCode 安装自身的存储。只有本插件补齐过的回合中的请求,其密钥才会被捕获,并且只用于填补自身密钥为空或为占位值的请求;网关在同一平面上连续两次拒绝某个已捕获的密钥(会话格式正确的 `401`,中间没有成功,且是插件自己回合中的请求)后,该密钥会被丢弃,直到这样一个携带它的请求再次被接受。Console 登录(设备流、会话存储、凭据池)在 `v2` 线上,刻意不放进 `main`,因此这里不依赖宿主可能没有挂载的服务。 **如果更新后卡片看起来还是上一版,说明宿主进程没有重启。** 宿主包只在进程启动时读取一次,所以浏览器刷新仍在运行上一版的 `lib/index.mjs`;请停止并重启 `dsh web`。这一行是最快的判断办法,因为它和其他所有改动在同一个版本里新加入。 @@ -405,6 +405,7 @@ OpenCode 官方的 Console 插件(`npx @opencode/console setup deepseek-harnes - **在 Console 的路由上,Settings → Models → Fetch 就是 `llm-pi-ai` 自己的列表。** 不会往里添加任何目录模型;`llm-pi-ai` 重启期间,获取会像 `llm-pi-ai` 自己那样失败,而不是回答目录;与之并列的你自己的平面条目仍会得到目录中的模型。 - **日志对每条路由说明一次**,并指出是凭据域还是请求头:`… dsh-opencode-patch leaves the route opencode to pi-ai`。 - **同名的密钥两边都会读到。** 只有凭据服务按域隔离,启动环境不隔离。环境中导出的 `OPENCODE_API_KEY`(或 `OPENCODE_GO_API_KEY`)会被本插件的计量和你自己的平面读取,也会被 `llm-pi-ai` 用于没有指定自己密钥的 Console 路由。请把工作区令牌保留在 Console 安装步骤给它的名字下,本插件从不读取这个名字。 +- **本插件只记录它补齐过的回合中的密钥。** Console 的请求——带标记的、属于 Console 路由回合的,或在任何回合之外发出的——从不被记录,从不用来填补其他请求,也从不被发往 Go 用量端点。 - **工作区的策略约束每个回合和每次工具调用**,包括本插件的平面:Console 工作区允许或禁止的内容,对一个回合都适用,无论哪个插件服务它的路由。 - **Console 的安装步骤会把导出的 `OPENCODE_API_KEY` 当作它自己的凭据**,优先于它的登录。如果两者都用,请不要在运行 Console 安装步骤的 shell 中导出 `OPENCODE_API_KEY`,或给平面一个自己的密钥引用(让 `apiKeyEnv` 指向另一个变量,例如 `OPENCODE_ZEN_API_KEY`)。使用自己的引用时,Go 计量的 Zen 余额检查在 Zen 回合运行之前仍读取 `OPENCODE_API_KEY`,所以在此之前会显示 Zen 余额未配置。 @@ -441,6 +442,8 @@ OpenCode 官方的 Console 插件(`npx @opencode/console setup deepseek-harnes - **`@viztor/dsh-opencode` 已弃用,但仍在发布。** 它是一个转导出 `dsh-opencode-patch` 的薄包装,所以用旧名的安装照常解析;registry 上标记为弃用并指向正式名称。新安装请用 `dsh-opencode-patch` 或 `@viztor/dsh-opencode-patch`。 - **其他插件拥有的路由留给它自己。** 当 `llm-pi-ai` 的配置行在本插件不解析凭据的凭据域中解析凭据,或者平面条目带有 `x-opencode-plugin` 请求头时(OpenCode Console 安装步骤写入的正是这种形状),该平面由 `llm-pi-ai` 而不是本插件服务,本插件的请求头、密钥与计量都不碰它的流量。在已发布的 1.x 中,这类路由上被本插件转到其隐藏的 Responses、Messages 或 Google 路由的轮次用本插件的凭据解析,因拿不到 Console 的令牌而失败,其余轮次则带上本插件的请求头,其密钥也被记录下来供计量使用;见[与 OpenCode Console 同时安装](#与-opencode-console-同时安装)。 - **网关的拒绝如实报告。** 在本插件服务的平面上,`FreeTierError`(403)或 `FreeUsageLimitError`(429)现在以 `FREE_TIER` 结束回合,`RegionError`、`ModelDeprecated` 或 `ModelProtocolUnsupported` 以 `MODEL_UNAVAILABLE` 结束,各自带有网关的原话,以及它的状态码(Google 协议的模型除外,其失败文本不带状态码)。过去对话对这些 403 显示“API 密钥无效”(API key is invalid),对用量上限显示“当前请求的额度已用尽”(Request quota exhausted.),网关的消息被丢弃。与被替换的代码一样,这两个新代码都不在宿主的可重试集合中,所以被拒绝的回合仍不会被重发。没有自带工具的免费 Chat Completions 回合现在在免费层的 `read` 与 `bash` 之外带上 `tool_choice: none`,以空 schema 声明的 `read` 或 `bash` 会被完整的定义替换。 +- **请求上的密钥只从插件自己的回合中保留,被拒绝两次后丢弃。** 过去插件会记录它认领的每个请求的密钥(包括任何回合之外的请求),并把最近一个回放到任意由配置的提供方认领的请求上;现在它只记录它补齐过的回合中请求的密钥,不在任一平面上的请求只用它自己的路由发往那里的密钥来填补,这样的中继密钥也从不用来填补网关请求或提供给用量计量(名为 `opencode` 或 `opencode-go` 的路由例外:即使它自己的 `baseURL` 指向别处,它的密钥也算作该平面的密钥,就像镜像那样),并且在网关于同一平面上连续两次拒绝某个已捕获的密钥后将其丢弃,只计算它自己回合中的请求:这些回合之外的请求(包括用量计量自己的轮询)从不计入对某个密钥的拒绝。导出的空白密钥或安装存储中的占位值不再作为凭据发出,空白或占位的 `OPENCODE_API_KEY` 也不再被当作计量浮层可用的 Zen 余额。以任意顺序停用两个相互重叠的激活,现在都会留下它们之前就在的那个 `fetch`。 +- **平面的请求头按调用设置,其他插件的 `llm-pi-ai/request-headers` 贡献者也在其上运行。** 在本插件服务的平面上,它的会话、来源与项目请求头通过 `llm-pi-ai` 的按调用请求头接口写入,与 `llm-pi-ai` 自己的路由写入方式相同;其他插件对该接口的贡献者现在也在这些平面上运行:抛出异常的贡献者会以 `REQUEST_HEADERS` 让回合失败,就像它在 `llm-pi-ai` 的路由上本来就会做的那样。该接口最早随 harness `0.2.2-alpha.3` 与 `0.2.2-rc.1` 发布。受支持的范围不变:在较早的宿主上(`0.2.2-alpha.2` 或 `0.2.1` 的构建),插件自己的请求头照样发出,仍由它的 fetch 补丁写入;其他插件的贡献者则不会在这些平面上运行,因为这样的宿主从不调用它们(见下文该接口的最低版本)。 - **用量设置在插件再次应用时生效,停用插件会撤下它的服务。** 修改 `usageBaseURL`、`keySource` 或 `readOpencodeStore`,或关闭 `usageEnabled`,在插件下一次被应用时生效:即停用后再启用,或 `dsh` 重启时。以前用量服务会一直沿用启动时的值,直到 `dsh` 重启,期间无论停用再启用多少次都不变。停用插件现在会撤下它的用量、清理与存储检查服务,而不是让它们继续应答。 ## 📜 兼容性与验证 @@ -457,6 +460,8 @@ Harness 按 `alpha` 与 `rc` 两个**通道**发布,它们是平行的发布 第一个子句覆盖两个通道上的 `0.2.1` 整条线:下界 `alpha.1` 排序低于同线的所有 `rc`,因此无需单独枚举 rc。第二个子句**并不多余**——除非同一 `major.minor.patch` 的某个比较符带有预发布号,semver 会把预发布版本排除在外,所以只写 `<0.3.0` 会悄悄丢掉所有 `0.2.2-*` 构建,alpha 与 rc 都一样。两个子句都止于 `0.3.0`,下一条线因此是一个单独的决定,而不是悄悄放宽。 +**请求头接口的最低版本。** 在平面上,插件通过 `llm-pi-ai` 的按调用请求头接口(`llm-pi-ai/request-headers`)写入自己的会话、来源与项目请求头,并在那里运行其他插件对该接口的贡献者,与 `llm-pi-ai` 自己的路由一样。该接口最早随 `0.2.2-alpha.3` 与 `0.2.2-rc.1` 发布;`0.2.2-alpha.2` 与所有 `0.2.1` 构建都没有它。上面的范围仍然接纳这些构建,这是有意为之:插件按行为检测该接口,从不依据版本号;在没有它的宿主上,插件自己的请求头照样发出,仍由它的 fetch 补丁写入,只是其他插件的 `llm-pi-ai/request-headers` 贡献者不会在这些平面上运行,因为这样的宿主从不调用它们。在安装时拒绝这些宿主,运行时什么也不会改变,所以这个最低版本写在这里,而不写进 peer。 + 可选的 `@deepseek-ai/cordis` peer 跟随 typert 的范围。每条线都推进了宿主内核:`0.2.1` 的构建依赖 `~4.0.5`(或 `4.0.5` 的预发布版本),`0.2.2` 的 alpha 依赖 `4.0.6` 的预发布版本,`0.2.2` 的 rc 依赖 `~4.1.0`。全新安装会采用**最新**被接纳的 typert 构建所依赖的那个 cordis,所以 cordis peer 漏掉它就会以 `ERESOLVE` 失败;漏掉较早某条线的 cordis,则会在已安装该线宿主的环境旁安装失败。因此这个 peer 接纳其中每一个,并止于下一个版本元组: ``` @@ -471,7 +476,7 @@ Harness 按 `alpha` 与 `rc` 两个**通道**发布,它们是平行的发布 | 层面 | 目标 | | :-- | :-- | -| **Harness 版本线** | **`0.2.1`** 与 **`0.2.2`** 预发布版本,`alpha` 与 `rc` 通道均可(peer:见上方范围) | +| **Harness 版本线** | **`0.2.1`** 与 **`0.2.2`** 预发布版本,`alpha` 与 `rc` 通道均可(peer:见上方范围);其他插件的请求头贡献者自 `0.2.2-alpha.3` 与 `0.2.2-rc.1` 起在平面上运行 | | **宿主内核** | `@deepseek-ai/cordis` 从 `4.0.4` 到 `4.1.x`,包括 `4.0.5` 与 `4.0.6` 的预发布版本(可选 peer:见上方范围) | | **插件包** | [`dsh-opencode-patch`](https://www.npmjs.com/package/dsh-opencode-patch) | | **宿主 profile** | DSH Web profile(`patchReload: live`) | diff --git a/docs/credentials.md b/docs/credentials.md index 5affe89..7b18495 100644 --- a/docs/credentials.md +++ b/docs/credentials.md @@ -13,15 +13,17 @@ The plugin's default is the deployment's own credential: whatever `apiKeyEnv` th a named apiKeyEnv → the credentials service (the launch environment only when no service is mounted) no reference → pi's own lookup (a Sign-in record under llm-pi-ai/, then OPENCODE_API_KEY) → the installation's store (opt-in) -**pi's own lookup reads `OPENCODE_API_KEY` on both planes** (pi 1.1.0's `providers/opencode.js` and `providers/opencode-go.js` both name that one variable). So a Go entry that names no reference authenticates every Go turn with the Zen key, and a Go key stored in DSH Credentials reaches a Go turn only as the entry's `apiKeyEnv: OPENCODE_GO_API_KEY`. Before P-R1 the Go plane's Responses, Messages and Google turns defaulted to `OPENCODE_GO_API_KEY`; that default went with the hidden routes, and the README's "Changed in 1.x" names it. The meter inherits the consequence: the fetch interceptor files the bearer of a Go-plane request as a Go key, and the meter's `auto` order puts that captured key ahead of the configured `OPENCODE_GO_API_KEY`, so after the first Go turn of a no-reference Go entry the meter sends the Zen key to the Go usage endpoint, which refuses it. `test/host-planes-credentials.test.ts` pins both turn cases on the Go plane, and the meter's switch from the Go key to the captured Zen key. +**pi's own lookup reads `OPENCODE_API_KEY` on both planes** (pi 1.1.0's `providers/opencode.js` and `providers/opencode-go.js` both name that one variable). So a Go entry that names no reference authenticates every Go turn with the Zen key, and a Go key stored in DSH Credentials reaches a Go turn only as the entry's `apiKeyEnv: OPENCODE_GO_API_KEY`. Before P-R1 the Go plane's Responses, Messages and Google turns defaulted to `OPENCODE_GO_API_KEY`; that default went with the hidden routes, and the README's "Changed in 1.x" names it. The meter inherits the consequence: the fetch interceptor files the bearer of a Go-plane request of a decorated turn as a Go key, and the meter's `auto` order puts that captured key ahead of the configured `OPENCODE_GO_API_KEY`, so after the first Go turn of a no-reference Go entry the meter sends the Zen key to the Go usage endpoint, which refuses it. `test/host-planes-credentials.test.ts` pins both turn cases on the Go plane, and the meter's switch from the Go key to the captured Zen key. A named reference that resolves nothing is `MISSING_CREDENTIAL`, and no request is sent; a credentials service that fails propagates its own error rather than reading as a missing key. A captured or literal key never answers for the adapter. The installation's store is read only when the deployment sets `readOpencodeStore`, only for a plane that names no reference, and only when pi's own lookup would find nothing: the resolver's answer is handed to pi as the request's explicit key, which pi lets win over its own lookup, so a store key returned any earlier would outrank a Sign-in record or an exported `OPENCODE_API_KEY`. -**The fetch interceptor's fallback is the second, narrower path.** It keeps real request auth untouched and fills only a missing or placeholder credential on gateway traffic, in this order: +**The fetch interceptor's fallback is the second, narrower path.** It keeps real request auth untouched and fills only a missing or placeholder credential on gateway traffic, through one resolver (`createCredentials` in `src/credentials.ts`, over the pure rules in `src/utils/credential-policy.ts`), in this order: - captured → declared environment key → installation key (opt-in) → nothing + the request's own key in another header → captured → declared environment key → installation key (opt-in) → nothing -The `configured` key-source policy skips the captured fallback; an API key already present in a request is never displaced. Two sources that are no longer in this branch — the DSH grant and the login session — are `v2` work. +The `configured` key-source policy skips the captured fallback; an API key already present in a request is never displaced. Every source's answer passes the one placeholder filter (`usableKey`) at the exit, so a blank exported key or a placeholder in the installation's store is no credential either. The declared key is the process environment's `OPENCODE_API_KEY`, or `OPENCODE_GO_API_KEY` on the Go plane, read in `src/credentials.ts` and nowhere else on the request path (`test/architecture.test.ts` pins that the fetch patch, the lifecycle and the plane provider read no `process.env`). Two sources that are no longer in this branch — the DSH grant and the login session — are `v2` work. + +**Which keys are captured, where they are kept, and how long (P6).** The capture store is one per composition root (`captureStoreFor(ctx)`), so the meter reads what the fill learned, two activations of the plugin share it, and another composition in the same process never does. A key is recorded only from a request of a turn the stream hook decorated (OC3): a request outside any turn — a Console call, another tool's background request — carries a token this plugin did not send, and is shaped by its URL, but its own token is never captured, never used to fill another request and never replayed to the meter. Such a request is not starved, though: a turnless request on a plane URL whose credential is empty or a placeholder is filled by the ordinary order like any other, a key captured on a decorated turn included, because that key is one the plugin itself sent. A turn on another plugin's plane and a request carrying an `x-opencode-plugin` marker go out untouched (D27). The two kinds of captured key never cross, in either direction: a request on neither plane, which a configured provider claims, is filled only with a key its own route sent to a URL on neither plane, never with a plane's key; and a key a route sent to a URL on neither plane (a relay's, sent to a third party) answers only that route's requests, never a plane request's fill or the meter, so dropping a plane's own key never hands the plane a relay's in its place. That rule is for a route not named after a plane: a route named `opencode` or `opencode-go` whose own `baseURL` points off the gateway is read as a mirror of that plane, so its key is filed by the route's name as that plane's key, both for what it records and for what fills it (`tierForRequest` falls back to the route name when the URL is on neither plane; `test/credentials.test.ts` pins the fallback). A captured key is dropped from its plane's lookups after the gateway refuses it twice in a row (L8): a `401` on a request of a decorated turn whose session id was well-formed, with no `2xx` between, since a malformed session draws the same `401 Invalid API key` whatever the key and one refusal has been seen followed by an acceptance. A dropped key is not recorded again until a request of a decorated turn that carried it as its own is accepted. No verification request is sent, and a request outside any decorated turn neither strikes a key nor lifts a drop (OC3): the meter's own `/usage` 401 drops nothing, because that endpoint refuses keys inference accepts. `test/credential-parity.test.ts` pins the four deciders — the fill, the meter, the Zen credit check and the plane adapter — side by side, and was written before the resolver was consolidated. Authentication follows the wire format: Bearer for OpenAI, `x-api-key` for Anthropic `/messages`, and `x-goog-api-key` for Google generation. Header extraction skips placeholders when another header carries a real key; placeholder detection is case-insensitive. The URL's pathname determines the plane, not query text or a conflicting turn provider. diff --git a/docs/deep-dive.md b/docs/deep-dive.md index 082996b..ac6543b 100644 --- a/docs/deep-dive.md +++ b/docs/deep-dive.md @@ -121,7 +121,7 @@ Two endpoint levels, and two ways to authenticate. The endpoints above are not p Authentication follows the **wire shape**, not the endpoint: the OpenAI planes (`/chat/completions`, `/responses`) send `Authorization: Bearer `; the Anthropic plane (`/messages`) sends `x-api-key: `. `extractApiKeyFromHeaders` reads `Authorization` first and falls back to `x-api-key` / `api-key`, which is what makes one credential usable no matter which plane the adapter routed the turn through. -Which key the Go meter sends (and when it earns a `403 EntitlementError`). The Go quota endpoint (`https://opencode.ai/zen/go/v1/usage`) is what the subscription windows come from. Under the default `keySource` (`auto`) `resolveGoApiKey` tries, in order: a literal `apiKey` on the Go entry, a key captured from a Go-plane request, the Go entry's `apiKeyEnv` (an `OPENCODE_API_KEY` reference is read as `OPENCODE_GO_API_KEY`, and with no reference that is the default), any captured Go-plane key, then the installation's store when the deployment opted in. The captured step is the turn's own key, so the meter agrees with the turn only when the Go entry names its reference: a Go entry without `apiKeyEnv` authenticates its turns with pi's `OPENCODE_API_KEY` (D20), the request patch files that bearer as a Go key, and from the first Go turn the meter sends the Zen key here. `keySource: configured` ("Declared key first") puts the reference ahead of the captured key; naming `apiKeyEnv: OPENCODE_GO_API_KEY` on the Go entry fixes the turn and the meter together. **A key prefix does not decide this.** An earlier guard refused `oc_sk_…` keys there on the belief that the prefix meant "Zen, no Go entitlement"; the same prefix answers `200` with real windows. What separates the tiers is the observed request, never the string: see [engineering-notes.md](./engineering-notes.md), "A credential prefix is not an entitlement". +Which key the Go meter sends (and when it earns a `403 EntitlementError`). The Go quota endpoint (`https://opencode.ai/zen/go/v1/usage`) is what the subscription windows come from. Under the default `keySource` (`auto`) `resolveGoApiKey` tries, in order: a literal `apiKey` on the Go entry, a key captured from a Go-plane request of a turn the plugin decorated (a request outside any such turn is never captured, and a captured key is dropped after a second well-formed 401 in a row), the Go entry's `apiKeyEnv` (an `OPENCODE_API_KEY` reference is read as `OPENCODE_GO_API_KEY`, and with no reference that is the default), any captured Go-plane key, then the installation's store when the deployment opted in. The captured step is the turn's own key, so the meter agrees with the turn only when the Go entry names its reference: a Go entry without `apiKeyEnv` authenticates its turns with pi's `OPENCODE_API_KEY` (D20), the request patch files that bearer as a Go key, and from the first Go turn the meter sends the Zen key here. `keySource: configured` ("Declared key first") puts the reference ahead of the captured key; naming `apiKeyEnv: OPENCODE_GO_API_KEY` on the Go entry fixes the turn and the meter together. **A key prefix does not decide this.** An earlier guard refused `oc_sk_…` keys there on the belief that the prefix meant "Zen, no Go entitlement"; the same prefix answers `200` with real windows. What separates the tiers is the observed request, never the string: see [engineering-notes.md](./engineering-notes.md), "A credential prefix is not an entitlement". ```json 403 {"type":"error","error":{"type":"EntitlementError","message":"OpenCode Go subscription required."}} diff --git a/docs/improvement-plan.md b/docs/improvement-plan.md index dd6cdbb..b9d49a5 100644 --- a/docs/improvement-plan.md +++ b/docs/improvement-plan.md @@ -35,7 +35,7 @@ Phases land as **stacked pull requests**. The open ones are rebased, each onto i | P-T3 | #173 | `ci:` CI and scripts | in review | **on `main` (9be88d6)**, which P-T2's merge left with this phase's base tree; shrank to what `main` had not done (one unit run, the build before `lib/`, tsx type-checked, one setup action, `check.ts` trimmed, `verify-*` exit codes, `.github/` and `*.sh` scanned) and gained the dist-tags and 2.x User-Agent read (L6) and the nightly bump proposal (an open proposal left to its reviewer); the checkout stays in each job, since a local action cannot bring its own, and the `check` job keeps its required-check name and the default install's coverage run | | P-R3 | | `fix:` honest refusals | in review | **new, on P-T3**, after P-R2's re-measure (run 43542273415): the gateway's typed refusals finish as `FREE_TIER` or `MODEL_UNAVAILABLE` on the planes, with the gateway's words and, except on Google, its status (L2, the UI claim verified on both channels' chat UI); L7's `tool_choice: none` and schema check; the OC6, OC8 and OC9 probe rows and OC10's README bullets. L9 and L10 land no code: the run answered no keyed 429, and left L10 unmeasured (the reasoning model was refused with and without the field, so the field was never read) | | P5 | | `fix:` the remote services follow the plugin's latest activation and go with its last | in review | **on P-R3**; `installRemoteService` (`src/host/remote.ts`) mounts the three services (usage, purge, store inspection), one per root while a live activation holds it, reading the latest live activation's options and disposed with the last activation, so the usage settings apply the next time the plugin is applied (a disable and re-enable, or a restart) and a disable withdraws all three; each mount is reported through the activation's logger once it has settled (no false "did not register" on a healthy boot, a refused mount said by name); the provide arm is dropped (`KNOWN_DEFECT P5` flipped); L1's warn-once, which treats any live patch of the plugin's as in place. Retitled from `refactor:`, because the README announces it and the changelog must carry it (P-H's precedent; a `refactor` is hidden from it); the owner may override at landing, and keeping `refactor:` drops the README pair with it | -| P6 | | `refactor:` the fetch patch's credential fill | planned | | +| P6 | | `fix:` the fetch patch's credential fill | in review | **on P5**; one resolver for an empty or placeholder wire key (`src/credentials.ts` over the pure `src/utils/credential-policy.ts`), a capture store per root that keeps a key only from a decorated turn (OC3) and drops it after a second well-formed 401 in a row (L8), the global fetch install in `src/host/global-fetch.ts` (any disposal order ends at the fetch that was there; both `KNOWN_DEFECT P6` assertions flipped), the plane headers set per call through pi-ai's `prepareHeaders` with the host's `llm-pi-ai/request-headers` waterfall run on the planes (OC4, OC5), the seam's floor stated in the README pair with the typert peer kept as it was (OC11), and a parity pin over the four deciders landed first. Retitled from `refactor:` (P-H's and P5's precedent): the pull request's title is the release signal under squash, a `refactor` is hidden from the changelog, and the phase carries behaviour changes the README pair announces (OC3, L8, the placeholder filter at every exit, the disposal order, the per-call headers). No `!` and no BREAKING CHANGE footer (1.x minors only). The peer narrowing was decided at landing: it landed as its own commit and was reverted at landing, keeping the old range, a decision taken for the owner and recorded as such (design item 14) | | P7 | | `refactor:` one source per table | planned | | | P8 | | `refactor:` settings table | planned | | | P9 | | `refactor:` remote seam | planned | | @@ -310,6 +310,8 @@ src/ commit; mount and teardown ordering (F14-F17) plane-provider.ts PlaneAdapter (extends the host's PiAiAdapter), registered as the declared planes remote.ts installRemoteService, markRemote + global-fetch.ts the one globalThis.fetch install: original read in the effect, disposed + links pass through and unwind in any order (P6) request/ fetch patch stages: claim → credential → headers → body (body parsed once) credentials.ts gathers values; utils/credential-policy decides; CaptureStore per root utils/ pure: protocols, plane-model, plane-profile, model-metadata (reasoning, both @@ -397,7 +399,7 @@ What stays private is pinned by contract tests against the real host packages: - **Shapes.** A resolved profile also carries the profile's pass-through fields (`compat`, `defaultContextWindow`, `defaultInput`, `defaultMaxTokens`, `headers`, `modelOverrides`, `thinkingBudgets`), and the `0.2.2` bridges add `maxRequestImages` and `imageOffloadCountQuantum`; a built pi provider exposes `getModels()` but no `api` map, so F10 is pinned by the API set `getModels()` answers, which includes Google on every supported pi (`1.3.0` and later). 6. **P-H `fix:` disabling or reloading the plugin restores the host methods it wrapped.** Its first title was `refactor: one way to patch a host method`; the subject of the commit that lands on `main` is the release signal (the pull request's title under a squash merge, the commit's own subject under the owner's rebase merge), and a `refactor` is hidden from the changelog, which would then never carry the restore below that the README's "Changed in 1.x" notes announce. Landed as: - - **The helper.** `src/host/patch-method.ts` (`patchMethod`) is the only way the plugin wraps a method on a host object. A dispose restores only while its own descriptor still holds its wrapper, deletes the own property when the original was inherited, and a same-site reinstall wraps the unpatched method. It carries a 100% per-file coverage floor, and two tripwires hold the "only way". The architecture rule is textual, over everything `apply()` reaches: a `Reflect.set`/`defineProperty`/`deleteProperty`/`setPrototypeOf`, an `Object.assign`/`defineProperty`/`defineProperties`/`setPrototypeOf` onto `llm`, an adapter, `settings` or `globalThis` (bare or through a property path such as `registration?.adapter`; a prototype swap shadows a method without leaving an own property), a dotted or bracketed assignment (through `?.` or `!` too) onto the first three, and `globalThis.x =` (the global `fetch` patch named as the one exemption, until P6); a write through a local alias or a cast receiver escapes it. The `apply()`-twice reload case is behavioural: a patch record required on every own function `apply()` leaves on the stand-in's `llm` and adapter, with `settings` added to the stand-in by P-R1 together with its site. + - **The helper.** `src/host/patch-method.ts` (`patchMethod`) is the only way the plugin wraps a method on a host object. A dispose restores only while its own descriptor still holds its wrapper, deletes the own property when the original was inherited, and a same-site reinstall wraps the unpatched method. It carries a 100% per-file coverage floor, and two tripwires hold the "only way". The architecture rule is textual, over everything `apply()` reaches: a `Reflect.set`/`defineProperty`/`deleteProperty`/`setPrototypeOf`, an `Object.assign`/`defineProperty`/`defineProperties`/`setPrototypeOf` onto `llm`, an adapter, `settings` or `globalThis` (bare or through a property path such as `registration?.adapter`; a prototype swap shadows a method without leaving an own property), a dotted or bracketed assignment (through `?.` or `!` too) onto the first three, and `globalThis.x =` (the global `fetch` patch named as the one exemption; P6 moved it into `src/host/global-fetch.ts`, where it stays); a write through a local alias or a cast receiver escapes it. The `apply()`-twice reload case is behavioural: a patch record required on every own function `apply()` leaves on the stand-in's `llm` and adapter, with `settings` added to the stand-in by P-R1 together with its site. - **The four migrated sites,** all in `models-discovery.ts`: `hideResponsesRoute` (the three listings), `decorateModelDiscovery`, `decorateModelInfo` and `decoratePlaneAdapters`. No wrapper's answer changed on a host that accepts the patch. The existing green pins of each site's behaviour in `test/models-discovery.test.ts` opened the phase and stayed unchanged; the five new cases there marked "a deliberate change in P-H" were added red: four over the three edge changes below (two for the adapter bullet: a frozen adapter and one refused method), and one for the helper's deletion of an inherited original (a class adapter's `resolveModel`, which the base assigned back as an own property). - **The reload test.** `test/reload.test.ts` runs apply A → apply B → dispose A → B intact → dispose B → originals restored exactly, and the reverse disposal order, for every site on own and inherited originals and on the real host (tier A). cordis itself disposes before it re-applies (`Fiber.update` → `restart` → `_unload` → `_reload`), so the overlapping sequence models two activations live at once (two rows) and the base's stacking, where a dispose restored nothing and the next activation wrapped the leftover. A stacked install leaks wherever the decoration reads config, which every site does: a reload whose config changed (the live answer is B's alone) pins discovery (`gatewayUrls`), model-info, both plane-adapter patches (`resolveModel`'s window and `modelOf`'s levels) and the listing's `listModels` (its per-activation keyless option, `hasCredential`, rather than config); the listing's `listProviders` capture is pinned by the `isRouteRegistered` reinstall case in `test/models-discovery.test.ts`. Structurally, for every key of every site, the second install is checked to have REPLACED the first (two live entries of one site id). A foreign wrapper on top with the newest install disposed first is run too. `apply()` itself is driven twice, first disposed first, on a stand-in context. All four sites failed it before the helper. - **Deliberate edge changes**, each pinned; none of the three is reachable with the real `LlmRuntime` and pi-ai adapter: the first two because both are extensible class instances, the third because the real `LlmRuntime` keeps its `adapters` map as an own property the traceable proxy hands through, and `isRouteRegistered` answers from that map before it reads the captured listing (the listing is the evidence only on a host without one): @@ -407,7 +409,7 @@ What stays private is pinned by contract tests against the real host packages: - **The measured identity trap.** On the real host the three `llm` disposers never restored: `ctx.llm` is cordis's traceable proxy, every method read answers a new shadow proxy, so `llm.x === decorated` was never true and reloads stacked wrappers. The helper reads identity from own descriptors (`docs/engineering-notes.md`). So on the real host a disable or a reload now restores the listing, discovery and model-info methods; before, each reload stacked a wrapper that kept the previous config's decisions, and a disable left them installed. The limit, recorded and pinned on tier A: a foreign plugin that wraps and later unwraps through `ctx.llm` puts back a shadow proxy, which the helper treats as foreign, so one correct pass-through stays as an own property. - **The plane adapters' composition.** pi-ai serves both planes from one adapter, so the per-route wraps became one patch per (adapter, method) that composes the adapter's plane routes in registry order. That keeps today's nesting, including the pi-ai-first `[INTENDED_CHANGE]` row where the Go plane's repaired base is Zen's. - **Re-wrap built, not wired.** `rewrapOnAdaptersUpdated` is tested but used by no site: on `decoratePlaneAdapters` it would wrap pi-ai's adapter in the plugin-first order and flip the `[KNOWN_DEFECT]` rows, and P-R1 deletes that site. - - **Left for P6:** the global `fetch` patch in `lifecycle.ts` stacks the same way (A, B, dispose A, dispose B leaves A's patched fetch installed), but it is a global, not a host service method. + - **Left for P6, and landed there:** the global `fetch` patch in `lifecycle.ts` stacked the same way (A, B, dispose A, dispose B left A's patched fetch installed), but it is a global, not a host service method; P6 moved it into `src/host/global-fetch.ts`, which unwinds through disposed links in any order. 7. **P-R1 `feat:` the plugin owns the plane routes.** In review. Landed as the design above (D1, D3, D5, D8, D13, D15-D21): `src/host/route-claim.ts`, `src/host/plane-provider.ts`, `src/host/describe-graft.ts` and `src/host/host-modules.ts` over the pure `src/utils/protocols.ts`, `model-metadata.ts`, `plane-model.ts` and `plane-profile.ts`, with `inject: []` at the root. Deleted: `responses-provider.ts`, `responses-routes.ts`, `google-bridge.ts`, `pi-provider.ts`, `utils/google-replay.ts` (a mock-gateway replay showed one provider label), the listing hide, the stream redirect, the model-info and plane-adapter decorations, and the D19 settings. Nine deliberate refinements of the text above: the describe wrapper is its own module on `patchMethod`; the host-module seam sits in `cordis-context.ts` with the loaders in `host/host-modules.ts`, and pi-ai's module is taken from its own loader entry during its commit run; the libraries (`loadHostPi`'s pi, dsh-llm, the loader) are found from the wrapper the loader resolves from the context's base URL, never from the plugin's own install, so a `link:`ed checkout runs on the host's copies too (the binary e2e asserts the pi root is the host prefix's); D20 mirrors pi-ai's exact rule (the launch environment only when no credentials service is mounted); `legacy` took pi's own base when pi filed the model under the same protocol on a `/zen` root (withdrawn in the restack, D26: the family table is the only base source); cost is catalog > pi > zero, because pi-ai's model row has no `cost` (D17's table puts it under the user's row), and nothing replaces `modelRoutes`' per-model protocol pin — the route-level `api` covers only ids the catalog does not classify (D26); only one pi-ai row's planes are stripped and served — the served row is sticky while it is live and declares a plane, and otherwise the first live row whose raw config declares one, else the first live row, so a re-enabled row that cordis appends to the end of the registry is still the one served, and the served row never moves between two live declaring rows, which would leave the one left behind stripped with nobody serving its planes — and another pi-ai row keeps and serves its own, reported once; when the served row changes (it was disposed or stopped declaring), what was built from the previous one is released and a new served row that already holds a plane is restarted once, as the mount does; the teardown and the stand-down wait for a LOADING pi-ai to settle and restart it if it resolved without a plane it declares (the text said "with pi-ai ACTIVE"), and the stand-down releases the plugin's handle first and happens whether or not a plane is declared, so a plane a later Settings save adds goes to pi-ai's own save check rather than to a refusal no retry can clear; and the characterization's fixture-sanity case derives `info` as D17 does, so `INFO_NOT_FROM_CATALOG` stays empty. The profiles' memo key holds the catalog's generation and a landed refresh re-runs the reconcile, so the live catalog reaches the profiles after boot without a plane edit. The PR body names every tagged row it flips. - **From the P-R1 review.** (a) **D1 for an effort list that names `none`:** on Chat Completions the `none` is Off's WIRE value (`thinkingLevelMap.off = "none"`, profile `reasoningEfforts.off = "none"`), as pi 1.1.0's own entries carry it, so Zen `mistral-large-4` and Go `hy3`/`hy4-preview` keep offering Off and send `reasoning_effort: "none"` for Off and for a turn with no level — what pi-ai served before P-R1. On Responses a listed `none` still offers no Off: pi's own entries disagree there (gpt-5.x pin `off: null`, gpt-6 carry `"none"`), a string `off` would become the request every no-level turn sends, and `opencode/gpt-5.4`'s `efforts` facet is `[BASELINE]` without Off, so it is the owner's call. **Open for the owner, not landed:** a `toggle` beside an `effort` list (Zen/Go `claude-haiku-5-5`, `deepseek-v4*`, `kimi-k3`, `qwen3.8-*`) offers the list's levels without Off, as the plugin did before P-R1 (`[BASELINE]`); pi alone offers Off on `claude-haiku-5-5`. Extending D1 to offer Off there moves `[BASELINE]` facets and changes the no-level request on Anthropic and Responses, so it needs a decision and its own characterization flips. (b) **D20 on the Go plane:** pi's lookup reads `OPENCODE_API_KEY` on both planes, so a Go entry without `apiKeyEnv` sends the Zen key on every protocol; before P-R1 Go's Responses, Messages and Google defaulted to `OPENCODE_GO_API_KEY`. D20 stands as written; the README's "Changed in 1.x" names the change and step 3 tells a Go user to name the reference, and `test/host-planes-credentials.test.ts` pins both cases. Changing the Go default would amend D20. (c) **A Settings save is judged with the last modules that loaded**, so a valid save in the window after a handover or pi-ai's partial dispose is not refused for timing; only a save before the mount's first load is. (d) **The Models store's join is a restatement**, like `hasProviderApiKey`: `modelsPageRows` in `test/support/host.ts` and the probe's `modelsJoin` restate `configured` and `apiKeyEnvOf` from `client/ui-settings-models/src/client/store.ts` (`joinProviderDirectory` and `read`, at the lines `modelsPageRows`' own doc cites, read at each channel record's tag), over the real host's `settings.describe({ redactSecrets: true })` and `listConfigurableProviders()` in tier B and on the binary. The client package is not added as a dependency: it would pull a client UI package into a node test for a three-line join. - **Restacked onto both channels (D14'', D22'', D26).** Merged P-H, so it runs on either channel's newest pi and each floor. One row table serves every host cell, since the plugin places, describes and routes every declared id itself; a row differs by cell only where the host decides (pi-ai's own defaults for the catalog-unknown id, per channel). Three removals of compensation for the host's pi: the Gemini level wrapper (`src/host/google-levels.ts`, its wiring, test, mock case, coverage floor and docs) goes, so the Google thinking control is pi's own; pi's catalog entry leaves the protocol order (catalog SDK, then the route's `api`, then completions) and the base (the family table only), so a pi that reshapes its catalog moves no turn; and `plane-profile.ts` restates none of pi-ai's default window and output tokens, reading back what pi-ai's `Config` filled. What the wrapper's removal exposes is recorded, not fixed: pi `1.1.0` (the `rc` floor, its desktop app's pi) sends the level-only Gemini 4 model a thinking budget on either plane (measured live on Go), a `[HOST_LIMITATION]` row in the in-process characterization and the binary e2e's floor cell, with the mock and live cases that need the level skipping by pi's own `usesGoogleThinkingLevel`, the READMEs' "Host limitations" list, and an upstream report. Measured on the published binaries: both cells of `rc` and the `alpha` floor serve the planes through the claim; on `alpha`'s npm cell cordis `4.0.6-alpha.2` handed `internal/config` listeners the fiber and read the config from `next()`, a contract the claim did not speak then, so pi-ai served the planes there — a `[KNOWN_DEFECT]` row (detected from the contract the probe saw dispatched), which became every cell's once both records moved to that core (`0.2.2-alpha.3`, `0.2.2-rc.2`). @@ -474,11 +476,15 @@ What stays private is pinned by contract tests against the real host packages: - **L1.** The stream hook warns once, on the first decorated turn that finds `globalThis.fetch` outside the plugin's live patches (`installFetchPatch` returns the predicate); a second live activation's patch wraps the first's, so it counts as in place. - **Rows it flips, all red on the base:** `KNOWN_DEFECT P5` (a composition with no `plugin` now reports `no ctx.plugin` and never provides), a reload's `usageBaseURL`, the latest of two live activations' settings, a disable withdrawing the three services, `usageEnabled: false` taking effect on reload, a refused mount on the activation's logger rather than cordis's line or the console, and a healthy boot's false "did not register". - **Known limitations.** (1) The usage settings follow a re-apply, not a Settings edit: every field of the row is `.volatile()`, a Settings write takes the loader's volatile-only path (no remount), and `resolveConfig` unwraps each node once at apply, so no part of the plugin follows such an edit until it is applied again (recorded under P8's restack row). (2) A reload leaves a short window between the old service's dispose and the new one's load in which a call finds no method; the meter's poll retries. (3) Two separately installed copies of the module keep two sets of slots: the second copy's mount is refused as a duplicate, and does not mount again when the first copy's row goes, until its own row is applied again (an unsupported setup that already collides on the route claim and the fetch patch). -14. **P6 `refactor:` the fetch patch's credential fill.** The adapter path is already D20. - - One resolver, for an empty or placeholder wire key only. - - A parity test over the deciders, with the adapter path as its own row: a rotated key takes effect, and a service failure propagates. - - A `CaptureStore` per root, evicting a key on 401. - - The global `fetch` patch reads its original inside the effect and restores only while it is still current, so apply A, apply B, dispose A, dispose B ends at the native `fetch`, in both orders. Today `lifecycle.ts` captures it in `apply()`, and the plugin's interceptor outlives a full disable after two overlapping activations (recorded in P-H). +14. **P6 `fix:` the fetch patch's credential fill.** In review. Retitled from `refactor:`, because the changelog must carry the behaviour changes the README pair announces. The adapter path was already D20 and stays pi-ai's rule: it never asks the resolver below. + - **A parity pin first.** `test/credential-parity.test.ts`, written and run against the tree before any `src/` edit, puts the four deciders side by side — the fetch patch's fill, the meter (`resolveGoApiKey`), the Zen credit check and the plane adapter — over one table of sources and the three policies, reaching them only through doors that survive the move (the plugin on a real `Context`, a decorated turn through `llm/stream`, the patched `fetch`, the exported resolvers, tier A). The adapter is its own row: a key rotated in the credentials service takes effect on the next call, and a credentials-service failure propagates with no request sent, while the meter over the same failing service answers the exported variable. Review edited the pin without touching an expectation: the policy type is derived from `KEY_SOURCE_POLICIES` (so it type-checks against the base on its own), the `afterEach` disposes the mounted plugin (`disposeMounted()`), and the header says so. The landed form was run on the base (6c599a5, P5's tip, through a `git archive` of it with only the pin copied in, `src/credentials.ts` absent there) and passed, 25 of 25, with a control that changes row (1)'s meter expectation from `env-go` failing there (3 of 25, one per policy). + - **One resolver, for an empty or placeholder wire key only.** `src/utils/credential-policy.ts` (pure, at 100%) holds the one placeholder filter (`usableKey`, applied once at every decider's exit, so a blank exported key or a placeholder in the installation's store is no credential), the fill's and the meter's orders per policy, the lazy step walk, the capture gate and L8's strike count. `src/credentials.ts` (at 100%) is the effect half: `createCredentials` observes a request's own key, fills an empty or placeholder one in `FILL_ORDER`, settles the gateway's answer and reads the pinned session id; it is the one place the fill reads the process environment, which stays the fill's source (D20's credentials-service rule stays the adapter's alone). `src/fetch-patch.ts`, `src/lifecycle.ts` and the plane provider read no `process.env`, pinned by `test/architecture.test.ts` with a planted read. go-discovery keeps `resolveRef`'s and `resolveGoKeyForRef`'s environment reads until P10a moves the module. + - **A `CaptureStore` per root.** `captureStoreFor(ctx)` keys a store on the context's root, so the meter reads what the fill learned, two activations share it, and two compositions never do; the module-level maps and `clearCapturedApiKeys` are gone, and so is its reset in `test/support/reset-process-state.ts`. A key is recorded only from a request of a turn the stream hook decorated (OC3), and a request on neither plane is filled only with a key its own route sent there; the other direction is closed too, since a key a route sent to a URL on neither plane answers only that route's lookup (`forRoute`), never a plane's fill or the meter, so L8's drop of a plane's own key cannot hand the plane a relay's key in its place (a tiered lookup admits only its own tier; it used to admit `unknown` too). That holds for a route not named after a plane: a route named `opencode`/`opencode-go` whose own `baseURL` is off the gateway is filed by its name as that plane's key, in both directions, which `test/credentials.test.ts` pins as deliberate (a mirror of the plane). A turnless request's own token is never captured, used to fill or replayed, while a turnless placeholder request on a plane URL is still filled in the ordinary order, a captured key included. A captured key is dropped from its plane's lookups after a second well-formed 401 in a row (L8) and is not recorded again until a decorated turn's request carrying it as its own is accepted; no verification request is sent. Both count only on requests of decorated turns: a turnless request, the meter's own `/usage` poll among them, neither strikes a key nor lifts a drop (OC3), since the usage endpoint refuses keys inference accepts. + - **The global `fetch` install.** `src/host/global-fetch.ts` reads the fetch it wraps inside the effect, turns a link disposed under another into a pass-through (the patch reads its `live` flag first) and unwinds through disposed links on a restore, so apply A, apply B, dispose A, dispose B ends at the fetch that was there, in both orders, a third party's function on top is never replaced, and L1's predicate reads only live links. Both of P5's `KNOWN_DEFECT P6` assertions are flipped. The host-write tripwire's one exemption moved with it (`host/global-fetch.ts: globalThis.fetch =`) and stays while the patch keeps relays, listing enrichment, the fill, the body fallback and the User-Agent. + - **The plane headers per call (OC4, OC5).** `PlaneAdapter` is built with pi-ai's `prepareHeaders`, as pi-ai's own adapter is: per call it writes the plane headers of the decorated turn from the one table the fetch patch writes from (`planeHeadersFor`), marks the turn `perCall`, then runs the host's `llm-pi-ai/request-headers` waterfall. Order: profile headers, the plugin's, the contributors', pi-ai's attribution. The fetch patch writes no plane header on a request of a marked turn that carries a well-formed session id, and still replaces a malformed one. The mechanism is the study's corrected one: a `ctx.on` listener never fires on routes the plugin claims, while the adapter's own option does, and runs under the turn's `AsyncLocalStorage` because pi-ai calls it inside the stream's generator. Detected by behaviour: where the host never calls the option, no turn is marked. + - **The peer range (OC11).** Decided at landing (taken for the owner, recorded as such): `@deepseek-ai/dsh-typert-protocol` keeps `>=0.2.1-alpha.1 <0.3.0 || >=0.2.2-0 <0.3.0`, and the seam's floor is stated in the README pair instead. The seam first shipped in 0.2.2-alpha.3 and 0.2.2-rc.1 (installed and run: 0.2.2-alpha.3 and rc.2; read off the published bridges: present in rc.1 and rc.3, absent in 0.2.2-alpha.2 and every 0.2.1 build). A narrowing to `>=0.2.2-alpha.3 <0.3.0` landed as its own commit and was reverted, for three reasons: #163, which widened the optional cordis peer to the 4.1 line, left its clauses for the 0.2.1 hosts' core (`~4.0.4 || >=4.0.5-0 <4.1.0`) in place; D26 says host gaps are feature-detected, never compared by version; and the plane adapter detects the seam by behaviour, so on a host without it the fetch patch still writes the plugin's session, origin and project headers (no turn is marked per call) and only other plugins' `llm-pi-ai/request-headers` contributors do not run on the planes, because the host never calls `prepareHeaders`. Refusing those hosts at install would buy nothing at runtime. `test/fetch-patch.test.ts` performs that fallback. + - **The per-call mark is per turn, on one activation's state (open).** `callHeadersFor` sets `perCall` on the turn state of the activation whose route claim built the adapter, for the rest of the turn. (a) A later request of that turn carrying a well-formed `x-opencode-session` is left unshaped by the fetch patch, whoever wrote the header. (b) With two live activations on one root (two entries of the plugin; cordis disposes before it re-applies), the other activation's stream hook has its own turn store with no mark, so its nested patch rewrites every plane header, a request-headers contributor's change and the minted `x-opencode-request` included; before P6 both patches rewrote them anyway, so nothing regressed. The tighter mechanism, when one is wanted, marks the request rather than the turn: the patch stands down only when the session on the wire equals the value the per-call seam wrote (`state.value`), or the mark is kept per root so every activation's patch sees it. + - **L4, not decided.** P-R2's rows measured nothing about `x-opencode-request`; it is sent as before, now from the shared header table, so the decision is one line when a variants run answers. The tier-A case that asserts it on every protocol is labelled a characterization, and the decision is carried to P10a's row with the next variants run. 15. **P7 `refactor:` one source per table.** One `planeForRoute` (four copies today), `formatUsd` and `specFor`; delete the duplicate `ALL_THINKING_LEVELS` and the capitalisation copies. 16. **P8 `refactor:` settings table.** It starts with a snapshot test of the derived `Config`. Then one field table drives the schema, resolver, types, card, copy and manifest. 17. **P9 `refactor:` remote seam.** `defineRemote`, `markRemote` and `callRemote`, with the parity test reading the contracts. @@ -526,11 +532,11 @@ How each phase changes now that it sits on `main` 1.8.0 and on both harness chan | P-T3 | **Shrank, as landed.** `main` had extracted the scripts' pure halves and written `docs/testing.md`; P-T3 did the rest: one unit run per install (the default install's is the coverage run, in the required `check` job) with an explicit build before every `lib/` reader, `test/**/*.tsx` type-checked, one composite setup action after each job's own checkout (the checkout cannot move into a local action), `check.ts` trimmed to freshness, the consumer install of both halves and the size tripwire (its file checks moved to `ci-wiring`, `package-checks`, `toolchain` and `no-local-paths`), the generators' one staleness rule, `verify-*` exit codes, and `no-local-paths` over `.github/` and `*.sh`. **New, as landed:** the CLI-version script reads the registry's dist-tags and refuses an unpinned 2.x User-Agent literal (L6; the client-generation table stays P7's); the nightly host-drift report proposes the bump pull request, moving CONTRIBUTING's release-step-3 data, dispatching the floor cells (keyed tier off) when `piFloor` or a family field moved, waiting a night for a cut inside pnpm's release-age window, never editing a measured table, proposing a new prerelease tuple as a range change, and leaving an open proposal with the same target (its body's marker, every proposed record) to its reviewer, with pi moved on every record or none (D22''). (L13's newest-pi cell is no longer P-T3's: under D14'' each channel's default install already is the newest pi.) | | P-R3 | **New**, after P-R2's re-measure: L2's error mapping in `prepareCall`, L7's `tool_choice` and schema check, L9's `providerRetryAfterMs`, and L10's Off through `none` if measured. Gains the console study's probe rows: OC9 (a raw, non-`ses_` session id, per plane, keyed and free), OC6 (the harness User-Agent against the CLI one, per plane, free and paid) and, beside OC9's, OC8's recorded session-only header set. Also OC10's paired README section ("With OpenCode Console installed") on what D27 ships and tests: the routes the plugin serves beside a Console-owned entry, the workspace's policies gating every turn, and an exported `OPENCODE_API_KEY` becoming the Console's credential. **As landed:** L2's codes (`FREE_TIER`, `MODEL_UNAVAILABLE`, chosen on the verified UI evidence) in `prepareCall` and `stream`, L7, the OC6, OC8 and OC9 rows with a free baseline, and OC10's two remaining bullets; L9 lands no code (run 43542273415 answered no keyed 429) and L10 none (unmeasured: the reasoning model was refused with and without the field). | | P5 | Unchanged, plus L1's warn-once when `globalThis.fetch` is no longer the patched function. **As landed:** `installRemoteService` (`src/host/remote.ts`) for the three services, with the latest live activation's options, disposal with the last activation, reports through the activation's logger after the mount settles, and no provide arm; L1's warn-once is the stream hook's, on the first decorated turn that finds `globalThis.fetch` outside the plugin's live patches (`installFetchPatch` returns the predicate, so two live activations' nested patches raise no warning). | -| P6 | L8: verify before evicting a key; L4's outcome (drop `x-opencode-request`, or send it only where it is accepted). From the console study: OC3 (capture a key only from a request the plugin decorated, and close the fill path that could reuse a captured token; the marker guard, never capturing from a request carrying `x-opencode-plugin`, landed with D27), OC4 (`prepareHeaders` on the plane adapter, so the host's `llm-pi-ai/request-headers` waterfall runs on the planes), OC5 (the plane's headers set per call through that option, not the global fetch patch), OC11 (the peer range says what the header seam needs), OC2's remainder (the marker pass-through, which landed with D27 and reads the header's presence today, moves into `src/utils/request-shape.ts`; its second rule is not adopted) and OC10's last sentence (the README's coexistence section gains that the meter and headers stay off Console traffic, once OC3's discriminator lands). | +| P6 | L8: verify before evicting a key; L4's outcome (drop `x-opencode-request`, or send it only where it is accepted). From the console study: OC3 (capture a key only from a request the plugin decorated, and close the fill path that could reuse a captured token; the marker guard, never capturing from a request carrying `x-opencode-plugin`, landed with D27), OC4 (`prepareHeaders` on the plane adapter, so the host's `llm-pi-ai/request-headers` waterfall runs on the planes), OC5 (the plane's headers set per call through that option, not the global fetch patch), OC11 (the peer range says what the header seam needs), OC2's remainder (the marker pass-through, which landed with D27 and reads the header's presence today, moves into `src/utils/request-shape.ts`; its second rule is not adopted) and OC10's last sentence (the README's coexistence section gains that the meter and headers stay off Console traffic, once OC3's discriminator lands). **As landed:** L8 adopted as its second arm (a second well-formed 401 in a row, no verification probe); L4 not decided (P-R2 measured nothing); OC3 met (capture only from a decorated turn, L8's strikes and drop lifts counted only on decorated turns too, the fill on neither plane closed to a plane's key, the meter reading the same per-root store); OC4 and OC5 met through `prepareHeaders` on `PlaneAdapter`; OC11 met by stating the seam's floor in the README pair, not by the peer (a narrowing landed and was reverted; see design item 14); OC2's remainder met (`pluginMarkerOn` in `src/utils/request-shape.ts`, still triggering on presence); OC10's last sentence met in the README pair. | | P7 | L6's client-generation table and L11's context-window overrides table; the `planeForRoute` copies now include `main`'s `isGoPlaneUrl` and `catalogPlaneForRoute` pair; the places that justify `@ai-sdk/mistral` → completions by "the plugin follows pi" (`docs/redirect-planes.md` §2, `docs/protocol-routing-and-merge.md`'s Mistral paragraph and its SDK table row, this plan's protocol row in the P-R1 design, the SDK table row in `README.md` and `README.zh-CN.md`, `test/protocols.test.ts`'s SDK-table case title and its `piKnows` assertion, which at most stays an informational pi characterization, and `test/catalog.test.ts`'s note that pi's data files the SDK as completions) are reworded to the plugin's own routing rule, since pi's catalog no longer decides a protocol (D26). | | P8 | The health snapshot shows the catalog's `lastError` on the card. From P5's review: every field of the row is `.volatile()`, and a Settings edit takes the loader's volatile-only path (`entry.update` → `_commitVolatile`, no remount), while `resolveConfig` unwraps each node once at apply; so no part of the plugin (the usage options, the fetch patch, the stream hook) follows a Settings edit until the plugin is applied again. P8 decides whether the settings table reads those values per call or says in the card that they apply on re-apply. | | P9 | A loopback triple guard, only if a `webServer` route appears. | -| P10a | L1's per-call shaping is the first move of `fetch-patch` into `request/`. | +| P10a | L1's per-call shaping is the first move of `fetch-patch` into `request/`. L4, carried from P6 (P-R2 measured nothing): with the next keyed variants run, drop `x-opencode-request` or send it only where it is accepted, which is one line in `planeHeadersFor` and one expectation in `test/host-planes-headers.test.ts`. | | P10b | L12's test; optionally emit `llm/models-updated` on refresh, a new host event. | | P11, P12 | Unchanged. | @@ -543,11 +549,11 @@ Two community plugins solve the same problem on the same host: [`FishBottle7/ope | L1 | **Shape plane traffic per call, not through the global fetch patch.** Put the derived session id, `x-opencode-client` and `x-opencode-project` into `options.headers`, and the core-tool fallback into `onPayload`, when wrapping each api in the plane provider; keep the fetch patch for URL-claimed relays, listing enrichment and P6's credential fill. Warn once when `globalThis.fetch` is no longer the patched function. | FB `packages/plugin/src/adapter/zen-adapter.ts` (`headers`, `onPayload`); FB `packages/plugin/src/pool/installer.ts` swaps `globalThis.fetch`, and our restore is identity-guarded. `docs/redirect-planes.md` claims the headers reach all four protocols; only the session header does. | P10a, P5 (the doc fix landed in P-R1, fa53d8e; P5's warn-once landed; per-call shaping is P10a's) | Adopt | | L2 | **Classify the gateway's refusals as non-retryable in `prepareCall`**, keeping status and body. The host maps 403 to `AUTH` and 429 to `RATE_LIMIT`, and retries a 429 five times. | SF `lib/errors.js`; FB `packages/plugin/src/adapter/events.ts`. FB's claim that `AUTH` makes the UI print "API key is invalid" is verified on both channels' `dsh-client-ui-chat` (`failureMessage`, `displayFailure`). | P-R3 | Adopted: `FREE_TIER` and `MODEL_UNAVAILABLE` on the planes | | L3 | **The free probe misreads the newer refusal.** A final 429 is always read as rate-limited; `429 FreeUsageLimitError` is the gate refusing, so it is its own verdict and is not retried. Also probe the root family `/inference/v1`. | SF `873e914` (the probe no longer counts a 429 as usable); FB `packages/plugin/src/adapter/catalog.ts` counts a 429 as a pass. | P-R2 | Adopt | -| L4 | **Measure `x-opencode-request` before keeping it.** We send a minted `msg_` id, and the keyed probes omit it, so it has never been measured. | FB `packages/plugin/src/adapter/ids.ts` ("any value is refused"); SF removed it; `docs/upstream-findings.md` says 2.x dropped it. | P-R2 rows, then P6 or P10a | Measure; drop it or send it only where accepted | +| L4 | **Measure `x-opencode-request` before keeping it.** We send a minted `msg_` id, and the keyed probes omit it, so it has never been measured. | FB `packages/plugin/src/adapter/ids.ts` ("any value is refused"); SF removed it; `docs/upstream-findings.md` says 2.x dropped it. | P-R2 rows, then P6 or P10a | Not decided: P-R2's rows measured nothing; carried to P10a with the next variants run. P6 moved the header into the shared table (`planeHeadersFor`), so the decision is one line | | L5 | **`x-opencode-project` has three conflicting claims:** the folder basename (ours, which also leaks the repository's name), `global` (FB), and a 40-hex digest (SF). | FB `packages/plugin/src/adapter/ids.ts`; SF `lib/protocol.js`. | P-R2 rows for all three, then default to `global` unless another is proven | Measure; probably change the default | | L6 | **One "client generation" table** for the User-Agent format, the header set and the session semantics. Our tree disagrees with itself about the affinity headers on plane routes, and SF ships the 2.x User-Agent format. | FB `packages/plugin/src/adapter/ids.ts`; SF `lib/protocol.js`; `src/fetch-patch.ts`; `docs/upstream-findings.md`. | P7, P-T3 | Adopt | | L7 | **Set `tool_choice` when injecting the gate tools, and check their schemas.** Ours injects and leaves `tool_choice` alone, and matches by name only, so a title or compaction call can end in a stub-tool call. | FB `packages/plugin/src/adapter/messages.ts`; SF `lib/protocol.js`. | P-R3 (or L1's `onPayload`) | Adopted in P-R3 | -| L8 | **Verify before evicting a key.** A malformed session header yields `401 Invalid API key`, and FB saw the same request refused and then accepted. Evict per plane only after one verification or a second well-formed 401. | FB `packages/plugin/src/pool/death-verify.ts`; `src/utils/session-id.ts`. | P6 | Adopt | +| L8 | **Verify before evicting a key.** A malformed session header yields `401 Invalid API key`, and FB saw the same request refused and then accepted. Evict per plane only after one verification or a second well-formed 401. | FB `packages/plugin/src/pool/death-verify.ts`; `src/utils/session-id.ts`. | P6 | Adopted in P6 as the second arm: a captured key is dropped per plane after a second well-formed 401 in a row with no 2xx between, both on requests of decorated turns, and not recorded again until a decorated turn's request carrying it as its own is accepted; no verification probe is sent, and a turnless request (the meter's `/usage` poll among them) neither strikes a key nor lifts a drop, so the meter's 401 drops nothing | | L9 | **Honour `Retry-After`.** dsh-llm accepts `providerRetryAfterMs` and `dsh-llm-pi-ai` never fills it. pi's `onResponse` exposes the headers only after a 2xx (and Google has none), so a refusal's header is visible only at the fetch layer. | SF `lib/errors.js`. | P-R2 records whether Go's 429s carry it; P-R3 fills it | Measured: run 43542273415 answered no keyed 429 (its `Retry-After` line is in §13), so nothing to fill; when one does, at the fetch layer (P6) | | L10 | **Offer Off on plain chat-completions reasoning models** through `reasoning_effort: "none"`; ours offers Off only for a few body formats. | FB `packages/plugin/src/adapter/zen-adapter.ts`; `src/utils/model-metadata.ts`. | P-R2 keyed probe, then P-R1's metadata | Unmeasured: run 43542273415's pair was refused before the field mattered, its control as much as `"none"` (Zen account 403, Go model-gone 410, a retired id); Off stays as P-R1's metadata offers it until a served reasoning completions model answers the pair | | L11 | **Context-window overrides with dated evidence.** FB keeps measured windows for two free models that differ from the catalog's; an understated window is the overflow trap. | FB `packages/plugin/src/adapter/catalog.ts`. | P7 | Low priority; the table pattern only | @@ -564,16 +570,16 @@ The vendor's own first-party DSH plugin, `@opencode/console` 0.1.10 (`anomalyco/ | # | Lesson | Evidence | Phase | Verdict | | :-- | :-- | :-- | :-- | :-- | | OC1 | **The route claim steps aside for a plane entry the Console owns.** `setup deepseek-harness` writes an `llm-pi-ai` patch row whose `providers` are the workspace's routes, under our two plane keys (`opencode` first, `opencode-go` second), each with `apiKeyEnv: OPENCODE_CONSOLE_TOKEN` and the marker header `x-opencode-plugin: opencode-console/`, and isolates pi-ai into the Console's `credentials` realm, the only one that resolves the token. Claimed by us, every Console turn on those keys failed with `MISSING_CREDENTIAL` before any I/O. | The setup CLI's bundle (`chunk-xs6kvyat.js`): the row `{ id: "llm-pi-ai", isolate: { credentials: … }, config: { providers: e.routes } }` and each route's `apiKeyEnv` and `headers`; its route order (`chunk-a2ds5vde.js`, `e === "opencode" ? 0 : e === "opencode-go" ? 1 : 2`); `dsh-plugin.js`'s credentials service answering `OPENCODE_CONSOLE_TOKEN` only; dsh-app-boot's patch apply (`target[key] = value`), which replaces the row's config. | Landed in P-R1 as D27 | Upheld by both skeptics, with details corrected: the setup skips the row when the patch file already configures `llm-pi-ai`, and ownership is detected from the row and the entry, never from a vendor name or a version. | -| OC2 | **The fetch patch must not touch traffic that carries another plugin's marker.** The global fetch patch claims every gateway URL, so a Console request that reaches it gains our headers and has its token captured. | `dsh-plugin.js`'s `requestHeaders` (`x-opencode-session` set only when the request carries `x-opencode-plugin`); the marker on every route the setup CLI builds; ours, `src/fetch-patch.ts` (`gatewayUrls`, the session fill). | Rule 1's pass-through landed in P-R1 as D27 (on the marker's presence); P6 moves the decision into `src/utils/request-shape.ts` | Not upheld as written. Survives: rule 1, a request carrying `x-opencode-plugin` reaches the original `fetch` untouched (no header writes, no credential fill, no key capture), decided in `src/utils/request-shape.ts` from the header's value, with red tests that perform the request. Dropped: rule 2 (never replace an existing `x-opencode-session`), which reverses the measured `401 Invalid API key` on a malformed id (L8), and the header list the lesson gave, which was wrong in two places. | -| OC3 | **Never capture the Console's workspace token.** Key capture records every non-placeholder key on a claimed request, and the Go meter's `auto` policy reads a captured key early, so the Console's policy-bound token would be replayed against the Go plane's `/usage`. | `dsh-plugin.js`'s credentials service (`source: "OpenCode Console"`); ours, `src/fetch-patch.ts` (`recordCapturedApiKey`), `src/go-discovery.ts` (`auto` reads `captured` second), `src/usage.ts` (`/usage`). | P6 | Upheld by both skeptics, with the discriminator corrected: capture only from a request the plugin decorated, the marker a second guard, and the fill path that could reuse a captured token closed in the same change. | -| OC4 | **Run the host's `llm-pi-ai/request-headers` waterfall on our planes.** pi-ai wires that waterfall only through `PiAiAdapter`'s `prepareHeaders` option, and `PlaneAdapter` is built without it, so no contributor runs on the routes the plugin owns. | dsh-llm-pi-ai's own `apply()` (`prepareHeaders: (request, headers) => ctx.waterfall("llm-pi-ai/request-headers", …)`) and its `requestHeaders(…, this.config.prepareHeaders)`; ours, `src/host/plane-provider.ts` (`new PlaneAdapter({ … })` with no `prepareHeaders`). | P6 | Upheld by both skeptics, with scope, rationale and priority corrected: after D27 the Console's routes are not ours, so the reason is any other contributor; where an adapter has no such option it is simply unused, detected by feature. | -| OC5 | **Set the planes' per-call headers through the host seam, not the global fetch patch.** The Console shapes its inference headers with no fetch patch, from a frozen request context that carries `sessionId` and `provider`. | `dsh-plugin.js` (`e.on("llm-pi-ai/request-headers", …)`); dsh-llm-pi-ai's frozen request context, after which attribution wins and a throw fails the call with `REQUEST_HEADERS`. | P6 | Not upheld as written. Survives: set the plane headers per call through OC4's `prepareHeaders` on our own `PlaneAdapter` (a `ctx.on` listener never fires on routes the plugin claimed), with today's derivation (`headerValueFor(request.sessionId, createdAt)`; a bare digest would re-key every session), never throwing, while the fetch patch keeps URL-claimed relays, listing enrichment, the credential fill, the tool-fallback body and any User-Agent override, so the `globalThis.fetch` exemption stays while any of that remains. Both skeptics placed this with L1 in P10a; the plan files it in P6, beside OC4. | +| OC2 | **The fetch patch must not touch traffic that carries another plugin's marker.** The global fetch patch claims every gateway URL, so a Console request that reaches it gains our headers and has its token captured. | `dsh-plugin.js`'s `requestHeaders` (`x-opencode-session` set only when the request carries `x-opencode-plugin`); the marker on every route the setup CLI builds; ours, `src/fetch-patch.ts` (`gatewayUrls`, the session fill). | Rule 1's pass-through landed in P-R1 as D27 (on the marker's presence); landed in P6: the read is `pluginMarkerOn` in `src/utils/request-shape.ts`, which answers the value, and the pass-through still triggers on presence, the fail-safe direction | Not upheld as written. Survives: rule 1, a request carrying `x-opencode-plugin` reaches the original `fetch` untouched (no header writes, no credential fill, no key capture), decided in `src/utils/request-shape.ts` from the header's value, with red tests that perform the request. Dropped: rule 2 (never replace an existing `x-opencode-session`), which reverses the measured `401 Invalid API key` on a malformed id (L8), and the header list the lesson gave, which was wrong in two places. | +| OC3 | **Never capture the Console's workspace token.** Key capture records every non-placeholder key on a claimed request, and the Go meter's `auto` policy reads a captured key early, so the Console's policy-bound token would be replayed against the Go plane's `/usage`. | `dsh-plugin.js`'s credentials service (`source: "OpenCode Console"`); ours, `src/fetch-patch.ts` (`recordCapturedApiKey`), `src/go-discovery.ts` (`auto` reads `captured` second), `src/usage.ts` (`/usage`). | Landed in P6: the capture gate (`mayCapture`) records a key only from a request of a decorated turn, never a foreign turn or a marked request; the fill on neither plane takes only its own route's key; the meter reads the same per-root store | Upheld by both skeptics, with the discriminator corrected: capture only from a request the plugin decorated, the marker a second guard, and the fill path that could reuse a captured token closed in the same change. | +| OC4 | **Run the host's `llm-pi-ai/request-headers` waterfall on our planes.** pi-ai wires that waterfall only through `PiAiAdapter`'s `prepareHeaders` option, and `PlaneAdapter` is built without it, so no contributor runs on the routes the plugin owns. | dsh-llm-pi-ai's own `apply()` (`prepareHeaders: (request, headers) => ctx.waterfall("llm-pi-ai/request-headers", …)`) and its `requestHeaders(…, this.config.prepareHeaders)`; ours, `src/host/plane-provider.ts` (`new PlaneAdapter({ … })` with no `prepareHeaders`). | Landed in P6: `PlaneAdapter` is built with `prepareHeaders` (`planeRequestHeaders`), which runs the waterfall where the context has one; a contributor's throw fails the call with `REQUEST_HEADERS` | Upheld by both skeptics, with scope, rationale and priority corrected: after D27 the Console's routes are not ours, so the reason is any other contributor; where an adapter has no such option it is simply unused, detected by feature. | +| OC5 | **Set the planes' per-call headers through the host seam, not the global fetch patch.** The Console shapes its inference headers with no fetch patch, from a frozen request context that carries `sessionId` and `provider`. | `dsh-plugin.js` (`e.on("llm-pi-ai/request-headers", …)`); dsh-llm-pi-ai's frozen request context, after which attribution wins and a throw fails the call with `REQUEST_HEADERS`. | Landed in P6: the plane headers are written per call from the decorated turn through the same option, before the contributors, and the fetch patch leaves a marked turn's well-formed request alone | Not upheld as written. Survives: set the plane headers per call through OC4's `prepareHeaders` on our own `PlaneAdapter` (a `ctx.on` listener never fires on routes the plugin claimed), with today's derivation (`headerValueFor(request.sessionId, createdAt)`; a bare digest would re-key every session), never throwing, while the fetch patch keeps URL-claimed relays, listing enrichment, the credential fill, the tool-fallback body and any User-Agent override, so the `globalThis.fetch` exemption stays while any of that remains. Both skeptics placed this with L1 in P10a; the plan files it in P6, beside OC4. | | OC6 | **User-Agent: the host contract says attribution wins, so decide rather than fight it.** pi-ai applies the harness User-Agent after every contributor, so the Console's traffic reaches the gateway with it; the plugin overrides it only through the global fetch patch. Whether the free tier needs the CLI's User-Agent has not been measured. | dsh-llm-pi-ai (`attributionHeaders()` applied after `prepare`); dsh-llm's attribution (`'user-agent': userAgent(identity)`); the Console's own User-Agent only on its Console API calls; ours, `src/fetch-patch.ts` (`headers.set("User-Agent", …)`). | P-R3 probe rows | Split. One skeptic upheld "measure, then let the owner decide"; the other held three facts overstated and the phase wrong. Survives: a keyed and a keyless row per plane, the harness User-Agent against the CLI's, free and paid. If the gateway accepts the harness one, dropping the override is an owner decision (a D-row and a `fix:` in a 1.x minor); if not, the override stays the one named exemption, with the reason written down. | | OC7 | **Characterize coexistence on the real host with a Console-shaped fixture.** Tier B boots the loader, which applies `isolate:` realms on every supported build, so the Console's shape can be reproduced with this repository's own code: a pi-ai row isolated into a realm, marked plane routes, and a local plugin in that realm providing `credentials`. | The loader's `isolate` (`GlobalRealm`, `'@' + this.label`); `ctx.get` following the realm on both cordis cores; `dsh-plugin.js`'s realm credentials. | Landed in P-R1 as D27 | Upheld by both skeptics, with the fixture amended: our own code, never the vendor's files, and a known answer beside it (an unmarked plane still claimed). It is `test/host-planes-foreign.test.ts`, on tier B's `realm` option. | | OC8 | **The vendor's minimal inference header set is evidence for L4 and L5.** On inference the Console sends two OpenCode headers, the raw session id and its marker, and its org header only on Console API calls. | `dsh-plugin.js`'s `requestHeaders`; the marker the setup CLI puts on each route; `x-org-id` only on the Console API client. | P-R3 probe row, beside OC9's | Not upheld as written. Survives: one recorded, never-asserted session-only row per plane (`x-opencode-session` and the User-Agent; no client, project or session-id header, and never the vendor's marker), which needs an omit list on `KeyedVariant`, read beside the free probe; a pass shows acceptance only. Dropped: the org-header half (a different header on a different endpoint), and deciding L4 and L5 from it, which P-R2's `KEYED_VARIANTS` already measure. | | OC9 | **Measure whether the gateway accepts a raw, non-`ses_` session id.** The Console and the vendor's Pi extension send the host's raw session id; the plugin derives `ses_<12hex><14base62>`, and L8 records a malformed id answering `401 Invalid API key`. | `dsh-plugin.js` (`p.set("x-opencode-session", a.sessionId)`, behind the marker); the Pi extension's `"x-opencode-session": d.sessionId`; the host's `sessionId: this.session.id`; ours, `src/utils/session-id.ts`. | P-R3 probe rows | Upheld by both skeptics, narrowed: the vendor's raw id travels only on workspace routes with the workspace token, so the row is per plane, keyed and free; the derivation stays unless the row passes on both planes and the free tier, and L8 must not read a well-formed foreign id as malformed. | -| OC10 | **Document coexistence and the shared `OPENCODE_API_KEY`.** With the Console set up, pi-ai's providers are the workspace's routes until `--remove`, and the Console reads `OPENCODE_API_KEY` first, as its own key. | The package's README ("the workspace's models replace the model providers you added"); the setup CLI's credential read (`e.env.OPENCODE_API_KEY` ahead of the stored sign-in). | A docs follow-up on D27 (the shipped, tested half), first in P-R3; the meter-and-headers sentence with P6 | Not upheld as written. Survives: a paired README section ("With OpenCode Console installed") stating only shipped, tested behaviour: which routes the plugin serves under D27, that the workspace's policies gate every turn and tool call (ours included), and that an exported `OPENCODE_API_KEY` becomes the Console's credential, so a user of both gives the planes their own reference. Not until code makes it true: that the meter and headers stay off Console traffic (OC2, OC3). The workspace-policy and `OPENCODE_API_KEY` bullets landed in P-R3. | -| OC11 | **Make the peer range say what the header seam needs.** OC4 and OC5 rely on `llm-pi-ai/request-headers`, which no 0.2.1 bridge has, while the `@deepseek-ai/dsh-typert-protocol` peer range still admits 0.2.1. | `package.json`'s `peerDependencies`; the 0.2.1 bridge carries no `request-headers`, the 0.2.2 ones do. | P6 | Split. One skeptic upheld it (a declaration, not a runtime version check, so D26 allows it); the other held that the proposed `>=0.2.2-0 <0.3.0` still admits a published build without the seam. Survives: narrow the declaration in the change that lands OC5, to a floor that has the seam, pinned beside the declaration checks in `test/harness-channel.test.ts`. | +| OC10 | **Document coexistence and the shared `OPENCODE_API_KEY`.** With the Console set up, pi-ai's providers are the workspace's routes until `--remove`, and the Console reads `OPENCODE_API_KEY` first, as its own key. | The package's README ("the workspace's models replace the model providers you added"); the setup CLI's credential read (`e.env.OPENCODE_API_KEY` ahead of the stored sign-in). | A docs follow-up on D27 (the shipped, tested half), first in P-R3; the meter-and-headers sentence landed in P6 (the README pair's "records a key only from a turn it decorated" bullet) | Not upheld as written. Survives: a paired README section ("With OpenCode Console installed") stating only shipped, tested behaviour: which routes the plugin serves under D27, that the workspace's policies gate every turn and tool call (ours included), and that an exported `OPENCODE_API_KEY` becomes the Console's credential, so a user of both gives the planes their own reference. Not until code makes it true: that the meter and headers stay off Console traffic (OC2, OC3). The workspace-policy and `OPENCODE_API_KEY` bullets landed in P-R3. | +| OC11 | **Make the peer range say what the header seam needs.** OC4 and OC5 rely on `llm-pi-ai/request-headers`, which no 0.2.1 bridge has, while the `@deepseek-ai/dsh-typert-protocol` peer range still admits 0.2.1. | `package.json`'s `peerDependencies`; the 0.2.1 bridge carries no `request-headers`, the 0.2.2 ones do. | Met in P6 in the README pair, not by the peer: the seam's floor (0.2.2-alpha.3, 0.2.2-rc.1) and what a host without it does are stated there, and the peer keeps admitting 0.2.1. A narrowing to `>=0.2.2-alpha.3 <0.3.0` landed and was reverted: the owner's #163 kept the cordis peer admitting the 0.2.1 core, D26 feature-detects host gaps rather than comparing versions, and the code shapes the planes' requests without the seam (the fetch patch writes the plugin's headers), so refusing those hosts at install buys nothing at runtime | Split. One skeptic upheld it (a declaration, not a runtime version check, so D26 allows it); the other held that the proposed `>=0.2.2-0 <0.3.0` still admits a published build without the seam. Survives: narrow the declaration in the change that lands OC5, to a floor that has the seam, pinned beside the declaration checks in `test/harness-channel.test.ts`. | | OC12 | **Cross-check the endpoint families and the served-catalog filter against the vendor's vocabulary.** The Console derives its gateway root from a `/(go/)?(anthropic/v1, openai/v1, google/v1beta or v1)` base and serves only chat models with tools and text output. | The setup CLI's root pattern and model filter (`chunk-a2ds5vde.js`); its api map and completions compat (`chunk-xs6kvyat.js`). | None | Not upheld as written. Survives: nothing to adopt; the vendor's shapes are all among P-R2's families, and pi already agrees with it on developer role and store for our planes. At most an optional, recorded `max_completion_tokens` completions row (a gap it finds is pi's, reported upstream as a `HOST_LIMITATION`, never patched here), and a P10b filter only as an owner decision on D3. | | OC13 | **Do not adopt: writing the user's patch file, providing `credentials`, reading the Console's sign-in.** The Console rewrites the user's patch file on setup and from its sync, provides a private `credentials` service in a loader realm, and holds an OAuth sign-in in its own data directory. | The setup CLI's bundle (the `# opencode-console:start/end` block it writes); `dsh-plugin.js` (`e.provide("credentials", …)`, its sync interval and its policy hooks). | None; under "Do not adopt" | Upheld by both skeptics, with one detail corrected: the sync rewrites the block only when its content changed, not on every tick. | @@ -759,13 +765,16 @@ The vendor's own first-party DSH plugin, `@opencode/console` 0.1.10 (`anomalyco/ **P6** -- **Unit:** apply A, apply B, dispose A, dispose B ends at the native `fetch`, in both orders (red on the base); with three activations, disposing the middle one and then the latest leaves the first one's patch current and raises no L1 warning, and disposing the first then ends at the native `fetch` (both of P5's `KNOWN_DEFECT P6` assertions in that case, flipped). +- **Pin first, green on the base with no expectation changed:** `credential-parity` (the four deciders over one table of sources and the three policies, and the adapter's own row: a rotated key on the next call, a credentials-service failure propagating); review's two edits (the derived policy type, the `afterEach` disposal) are recorded in design item 14, and the landed form was re-run on the base with a failing control. +- **Unit:** apply A, apply B, dispose A, dispose B ends at the native `fetch`, in both orders (red on the base); with three activations, disposing the middle one and then the latest leaves the first one's patch current and raises no L1 warning, and disposing the first then ends at the native `fetch` (both of P5's `KNOWN_DEFECT P6` assertions in that case, flipped); the same orders on real contexts in `global-fetch`, with a third party's function on top and a fetch swapped before the effect. +- **Red on the base:** `fetch-patch`'s OC3 cases (a turnless request's key is never recorded; a plane's key never fills a provider-claimed request on neither plane; a relay route's key never fills a plane request, not even after L8 drops the plane's own key), `go-discovery-keys`' OC3 case (the meter never answers a key sent to a URL on neither plane, under any policy; the base's tiered lookup admitted `unknown`), L8 (dropped at the second well-formed 401 in a row, per plane, back after an acceptance), the placeholder filter at the fill's exit (a stored `unused`, a blank exported key) and the meter's (`go-discovery-store`), OC5's per-call-shaped turn; `host-planes-foreign`'s turnless token never replayed by the meter on the real host; `host-planes-headers`' OC4 contributor on a tier-B plane turn (frozen request, the plugin's session header seen, its header on the wire, a throw failing with `REQUEST_HEADERS`) and OC5 on each protocol in tier A with the fetch patch out of the path; `architecture`'s `process.env` tripwire. +- **New with the change:** `credential-policy`, `credentials`, `global-fetch`, `planeRequestHeaders`, `pluginMarkerOn`/`planeHeadersFor`, the per-call writer (`callHeadersFor`) and the route claim building its adapter with `prepareHeaders`. ## End-to-end infrastructure ### The `e2e-host` job (`ci.yml`) -**When it runs:** on dispatch, nightly, and on PRs that touch the host seam — `src/host/**` and, beside it, `src/lifecycle.ts`, `src/identity.ts`, `src/cordis-context.ts` and `src/models-discovery.ts`, whose behaviour depends on the real loader and apply order, and the two modules that still install host-level patches until P6/P10a move them under `src/host/` (`src/fetch-patch.ts`, the global fetch wrapper whose order the probe reads, and `src/stream-hook.ts`) (every other row producer, such as the pure plane model and profile in `src/utils/`, `src/key-capture.ts`, `src/models-catalog.ts` or `src/config.ts`, is covered on each PR by the in-process characterization of the same rows, and by the nightly run) — `cordis.patch.yml`, `test/e2e/host/**`, `test/e2e/host-binary.e2e.ts`, `test/support/host.ts`, `test/support/e2e-env.ts` (the reader the binary e2e's gate, prefix and cell come through; its channel is `host-versions.ts`'s `selectedHost`), `test/support/host-versions.ts`, `scripts/host-drift.ts` (the family table the binary e2e asserts against the installed manifests), `.github/workflows/ci.yml`, `.github/actions/` (the composite setup action, which holds the install), `vitest.e2e.config.ts` or `vite.config.ts` (the pack config that builds `lib/index.mjs`, which only this job loads into a real host, and the test settings the e2e config inherits) (scoped by a step, since a workflow-level path filter would silence every job). +**When it runs:** on dispatch, nightly, and on PRs that touch the host seam — `src/host/**` and, beside it, `src/lifecycle.ts`, `src/identity.ts`, `src/cordis-context.ts` and `src/models-discovery.ts`, whose behaviour depends on the real loader and apply order, and the two modules that still carry host-level patches outside `src/host/` (`src/fetch-patch.ts`, the global fetch wrapper whose order the probe reads, installed by `src/host/global-fetch.ts` since P6, and `src/stream-hook.ts`, until P10a) (every other row producer, such as the pure plane model and profile in `src/utils/`, `src/key-capture.ts`, `src/models-catalog.ts` or `src/config.ts`, is covered on each PR by the in-process characterization of the same rows, and by the nightly run) — `cordis.patch.yml`, `test/e2e/host/**`, `test/e2e/host-binary.e2e.ts`, `test/support/host.ts`, `test/support/e2e-env.ts` (the reader the binary e2e's gate, prefix and cell come through; its channel is `host-versions.ts`'s `selectedHost`), `test/support/host-versions.ts`, `scripts/host-drift.ts` (the family table the binary e2e asserts against the installed manifests), `.github/workflows/ci.yml`, `.github/actions/` (the composite setup action, which holds the install), `vitest.e2e.config.ts` or `vite.config.ts` (the pack config that builds `lib/index.mjs`, which only this job loads into a real host, and the test settings the e2e config inherits) (scoped by a step, since a workflow-level path filter would silence every job). **What it does:** diff --git a/docs/redirect-planes.md b/docs/redirect-planes.md index a502697..5002c13 100644 --- a/docs/redirect-planes.md +++ b/docs/redirect-planes.md @@ -112,7 +112,7 @@ One model, every stage. The left column is what a user can see; the right column | 5 | _(invisible)_ | the session id is derived from `ses_` + the session's real `createdAt` + a hash suffix, and the session's `cwd` becomes the project name | `session.ts` · `cordis-context.ts` | | 6 | _(invisible)_ | **the model object is built**: `(plane, SDK) → protocol → base`, with metadata from the user's row first, then the catalog, then pi (D16, D17) | `utils/plane-profile.ts` → `utils/plane-model.ts` | | 7 | _(invisible)_ | the plane's adapter is the plugin's own subclass of the host's `PiAiAdapter`, registered for the plane route, with that plane's catalog and the credential pi-ai's own rule resolves (D20) | `host/route-claim.ts` → `host/plane-provider.ts` | -| 8 | _(invisible)_ | the request is intercepted and given what the gateway expects: origin proof (the client, the project, and the turn's message id), `x-opencode-session` always, parent-session lineage, and the free-tier `read`/`bash` schemas when the body lacks them | `fetch-patch.ts` · `tool-fallback.ts` | +| 8 | _(invisible)_ | the request is given what the gateway expects: origin proof (the client, the project, and the turn's message id), `x-opencode-session` always and parent-session lineage, written per call by the plane adapter's `prepareHeaders` (and by the fetch patch for a turn it did not shape); then the fetch patch fills an empty or placeholder key, sets the User-Agent, and adds the free-tier `read`/`bash` schemas when the body lacks them | `host/plane-provider.ts` · `fetch-patch.ts` · `credentials.ts` · `tool-fallback.ts` | | 9 | the reply streams in | the gateway answers; the plugin has changed nothing about the response | — | | 10 | a spend figure | the turn's usage event is priced per **plane**, so a Go turn and a Zen turn never share one number | `session-cost.ts` · `usage.ts` | | 11 | a quota ring or a spend pill | the meter polls the host service and renders the affecting window, or the session spend | `usage-pill.tsx` · `usage-panel.tsx` · `usage-ui.ts` | @@ -145,9 +145,9 @@ Measured 2026-10-10 by building one with pi's own protocol implementations and i **The Google path is the one a hand-declared route cannot reach.** Its protocol name is not in the wrapper's three-entry table, so no route may name it; a self-built provider dispatches to it without any special case — which is what the plane adapter is (`buildPlaneProvider`, P-R1). -**The session header reaches every protocol, and the rest of the gateway headers do not come from the provider.** `buildPlaneProvider` wraps each `api` with pi's own `withOpenCodeSessionHeader` before `createProvider`, and that is all it adds per call: pi's wrapper sets `x-opencode-session` from the turn's session id on all four protocols, and steps aside when the request already carries one. `x-opencode-client`, `x-opencode-project`, the derived `ses_` id and the User-Agent are set by the global fetch patch on the request the protocol sends, not on the call's options; moving them into each call (`options.headers`) is P10a's first move. +**The plane headers are set per call, through pi-ai's own header seam (P6, OC4 and OC5).** `PlaneAdapter` is built with pi-ai's `prepareHeaders` option, as pi-ai's own adapter is: pi-ai calls it once per call with a frozen request (`provider`, `model`, `baseURL`, `sessionId`) and the call's headers, after the profile's headers and before its attribution. The plugin's option (`planeRequestHeaders`) first writes the plane headers of the turn the stream hook decorated — `x-opencode-session` and `x-opencode-session-id` with the derived `ses_` id, the parent pair, the org, `x-opencode-client`, `x-opencode-request` and `x-opencode-project`, from the one table the fetch patch writes from (`planeHeadersFor`) — and marks the turn; then it runs the host's `llm-pi-ai/request-headers` waterfall, so another plugin's contributor runs on the planes as it does on pi-ai's own routes (one that throws fails the call with `REQUEST_HEADERS`). pi-ai hands the result to the protocol as `options.headers`, and all four protocols read them on both supported pi versions; `buildPlaneProvider` still wraps each `api` with pi's own `withOpenCodeSessionHeader`, which steps aside because the request already carries the derived id. The fetch patch then writes no plane header on a request of a marked turn that carries a well-formed session id, and still replaces a malformed one (L8). What stays in the fetch patch: the User-Agent (pi-ai's attribution wins after `prepareHeaders`, so the seam cannot carry it), `anthropic-version`, the credential fill, the free-tier tool fallback, listing enrichment, relays a deployment claims by URL, and a request outside any decorated turn. The seam is detected by behaviour: on a host whose adapter never calls the option, no turn is marked and the fetch patch shapes every request as before. `test/host-planes-headers.test.ts` drives both halves on the real host: a contributor registered on the root runs on a plane turn, and with the fetch patch out of the path a turn on each protocol still carries the derived session id and the plane headers. -**The User-Agent is one value on every protocol, Google's included.** The Google implementation sets an agent string of its own inside the protocol, but the fetch patch sets `User-Agent` on the request that protocol sends, which replaces whatever pi and the Google SDK put there rather than appending to it. The offline mock pins the wire value to `OPENCODE_UA` for the Google protocol on both planes (`test/mock/protocol-compat.mock.ts`), so the gateway never sees a combined value, and §13's keyed Google cells measure the agent string a turn actually sends. The question reopens only if P10a moves the agent into each call's options instead of the fetch patch. +**The User-Agent is one value on every protocol, Google's included.** The Google implementation sets an agent string of its own inside the protocol, but the fetch patch sets `User-Agent` on the request that protocol sends, which replaces whatever pi and the Google SDK put there rather than appending to it. The offline mock pins the wire value to `OPENCODE_UA` for the Google protocol on both planes (`test/mock/protocol-compat.mock.ts`), so the gateway never sees a combined value, and §13's keyed Google cells measure the agent string a turn actually sends. The question reopens only if the agent ever moves into each call's options instead of the fetch patch, which pi-ai's attribution, applied after `prepareHeaders`, rules out today. ## 10. A catalog route serves every protocol already diff --git a/docs/testing.md b/docs/testing.md index 1e66596..93c57c5 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -26,9 +26,9 @@ The rule for what belongs here, from `AGENTS.md`: **a predicate that lives in a Properties the unit and mock suites keep by construction rather than by care: -- **Offline.** `test/support/offline.ts` refuses every non-loopback request, so a networked runner cannot make a result depend on the vendor's live catalog. A case that means to fetch stubs `fetch` itself. +- **Offline.** `test/support/offline.ts` refuses every non-loopback request, so a networked runner cannot make a result depend on the vendor's live catalog. A case that means to fetch stubs `fetch` itself. The same file unsets `OPENCODE_API_KEY` and `OPENCODE_GO_API_KEY` before each file runs, so a key a developer exported cannot answer a case that expects none; a case that wants a key sets its own. - **No socket in the unit run.** A case that binds a port, even on loopback, belongs to the mock suite (`test/mock/*.mock.ts`), which has the timeouts a socket needs. The offline guard admits loopback, so it cannot hold this; `test/architecture.test.ts` does, failing the build on a runtime import of a socket module (`node:http`, `node:net`, …) or a `createServer(`, `.listen(` or `startMockGateway(` call in any unit test file or any `test/` module one of them loads, with a planted row of each kind. -- **Order-independent.** `test/support/reset-process-state.ts` clears the plugin's module-level stores (captured keys, session spend, the live catalog) after every test, and CI runs the suite shuffled (`pnpm run test:shuffle`; reproduce a failure with `--sequence.seed=`). A new module-level store gets a reset beside its siblings. +- **Order-independent.** `test/support/reset-process-state.ts` clears the plugin's module-level stores (session spend, the live catalog) after every test; captured keys are kept per composition root (`captureStoreFor`), so a case seeds and reads the store of the context it built, and a fresh `Context` starts empty, and CI runs the suite shuffled (`pnpm run test:shuffle`; reproduce a failure with `--sequence.seed=`). A new module-level store gets a reset beside its siblings. The one exception is the fetch installer's link chain (`src/host/global-fetch.ts`): it holds no answer a case reads, only links compared by identity against `globalThis.fetch` and unwound by their own disposers, so a case that disposes what it mounts (`disposeMounted`, `tierA.dispose()`) leaves nothing behind that another case can see. - **Engine-checked.** The suite refuses to start below `engines.node` and names both versions (`test/support/node-engine.ts`), because below the floor `node:sqlite` and the ICU strings the tests pin differ, and the failures read like regressions. - **Real contexts.** A service is built on `new Context()` with what it reads provided (`test/support/loader-rows.ts` serves loader rows and credentials there), and "the plugin, applied" is `mountPlugin` in `test/support/composition.ts`: the module's own `apply`, `Config`, `inject` and `name` mounted the way the Loader mounts them, a turn through `ctx.waterfall("llm/stream", …)`, teardown through `fiber.dispose()`. The one stand-in for the composition is `degradedHost`, for the compositions a real `Context` cannot be (a `plugin` that registers nothing or throws; a `plugin` whose fiber the case settles; no `plugin` at all). The route claim keeps its own stand-in host (`test/support/route-claim-stand-in.ts`) for the fiber states a real host cannot be put in on demand, and `test/remote-service.test.ts` keeps stand-in compositions for `installRemoteService`'s clauses (a `plugin` that throws, answers no fiber or answers a fiber the case settles; no `plugin`; no `effect`). - **Vendor-proof, where the helpers are used.** A catalog count or a vendor id breaks on the nightly refresh, so the catalog tests assert invariants (non-empty, unique ids, the generator's `is_free` rule, a paid row per served protocol, set differences between the planes), and a case that needs a row picks it by shape (`findCatalogRow`, `catalogRow`, `freeZenModel` in `test/support/catalogs.ts`) and reads its expected values off that row, or seeds a world of its own. This holds for the catalog tests, `tool-fallback`, `models-discovery` and the cases P-T2 and `main` brought; it is not yet true of every file. Older cases still look up a named id in the shipped tables with no skip (the Go allowance coverage case in `go-limits.test.ts`, the Gemini rows of `thinking-levels.test.ts`, `plane-model.test.ts`'s `specOf`), and converting them is an open follow-up. A case whose point IS a named id says so, and should skip by name once the catalog no longer carries it. diff --git a/src/cordis-context.ts b/src/cordis-context.ts index 2c9f1d8..d9b7e8d 100644 --- a/src/cordis-context.ts +++ b/src/cordis-context.ts @@ -50,6 +50,11 @@ export interface CordisContext { extend?: (meta?: Record) => CordisContext; get?: (name: string) => unknown; inject?: (deps: string[], cb: (scope: unknown) => void) => void; + /** + * Run an event's listeners in turn, each handing the value to the next; + * how pi-ai's own adapter runs `llm-pi-ai/request-headers`. + */ + waterfall?: (name: string, ...args: unknown[]) => unknown; /** * The ROOT context of this composition. * diff --git a/src/credentials.ts b/src/credentials.ts new file mode 100644 index 0000000..1236268 --- /dev/null +++ b/src/credentials.ts @@ -0,0 +1,528 @@ +/** + * The fetch patch's credential resolver, and the store it learns keys into. + * + * Three effects, each over the pure rules in `utils/credential-policy.ts`: + * + * - **The capture store**, one per root (`captureStoreFor`): the keys the + * plugin saw its own decorated turns send, filed by the plane and route + * they went to, and dropped again once the gateway refuses one twice in a + * row (L8). Per root rather than per process, so two compositions in one + * process never answer each other's lookups, and a test's fresh `Context` + * is a fresh store. + * - **The fill** (`createCredentials`): the one resolver for a claimed + * request whose credential header is empty or a placeholder. It reads the + * request's own key, a captured key, the plane's declared variable in the + * process environment and, when the deployment opted in, the + * installation's store, in the policy's order (`FILL_ORDER`). A real key on + * the wire is never replaced. This is the one place the fill reads the + * process environment; the plane adapter's key is pi-ai's rule over the + * host's services (D20), and never comes from here. + * - **The installation's store** (`resolveOpencodeStoreKey`): the credential + * an OpenCode installation already holds for a plane, read only when the + * deployment turned `readOpencodeStore` on. + * + * Nothing here logs a key, and nothing here throws. + * + * @module dsh-opencode-patch/credentials + */ + +import os from "node:os"; + +import { + extractApiKeyFromHeaders, + type KeyTier, + tierForRequest, +} from "./key-capture.ts"; +import { opencodeDatabasePath } from "./opencode-paths.ts"; +import { readOpencodeCredentials } from "./opencode-store.ts"; +import { + countsAsRefusal, + FILL_ORDER, + type FillSource, + firstUsable, + type KeySourcePolicy, + mayCapture, + strike, + usableKey, +} from "./utils/credential-policy.ts"; +import { isRecord } from "./utils/guards.ts"; + +/** What the gateway's answer says about the key a request carried. */ +export type KeyOutcome = "accepted" | "refused"; + +/** + * The keys the plugin's own decorated turns sent, read three ways. + * + * A lookup can be scoped by route or by tier; the tier map is what makes a + * lookup survive a renamed route. The most recently seen key is the last + * resort, and is why the tier argument matters: without it, "most recently + * seen" can hand the Go endpoint a Zen key. + */ +export interface CaptureStore { + /** + * File a key under the route and plane its request went to. A blank or + * placeholder value is ignored, and so is a key this store dropped for that + * plane until a request carrying it is accepted again. + * + * @param key - the key the request carried. + * @param provider - the turn's route, when known. + * @param url - the request URL, which decides the plane first. + */ + readonly record: (key: string, provider?: string, url?: string) => void; + /** + * A captured key by route or by tier. A tiered lookup answers only a key + * sent to that plane: a key a route sent to a URL on neither plane answers + * `forRoute` and an untiered lookup, never a plane's (OC3). A route named + * `opencode`/`opencode-go` is the exception: on a URL on neither plane its + * key is filed by the route's name as that plane's (a mirror's), so it + * answers that tier and not `forRoute`. + * + * @param provider - route id to try first, when the caller has one. + * @param tier - the tier the key must belong to. Pass it whenever the + * request already identifies one: omitting it lets the most recently seen + * key win, which may be for the other tier. A route-scoped hit is filtered + * by it too — naming a route is a preference, not a licence to ignore the + * tier. + */ + readonly get: (provider?: string, tier?: "go" | "zen") => string | undefined; + /** + * The key a route sent to a URL on neither plane, and only that (OC3): a + * key captured on a plane never answers a request the route claims + * elsewhere. A route named after a plane files no key here: off the + * gateway its key is that plane's, by the route-name fallback. + * + * @param provider - the route. + */ + readonly forRoute: (provider: string) => string | undefined; + /** + * Fold the gateway's answer into the key's standing (L8): an accepted key + * is cleared of strikes, a refused one gains a strike and is dropped from + * every lookup of its plane at the second in a row. A drop is lifted only + * by an acceptance of a request that may file the key (`recordable`, OC3): + * the key its own decorated turn sent. A key the fill supplied, accepted, + * leaves the drop where it is. + * + * @returns whether this answer lifted a drop, so the caller files the key + * again; a key the store neither holds nor dropped is left alone. + */ + readonly settle: ( + key: string, + provider: string | undefined, + url: string, + outcome: KeyOutcome, + recordable: boolean + ) => boolean; +} + +/** + * Whether a key classified as `tier` may answer a lookup for `wanted`: only a + * key of that tier, identically in all three lookup paths. + * + * `unknown` used to be admitted too, on the reading that an unclassifiable key + * was one never identified rather than one proved to be the other tier. Every + * key is filed with the URL its request went to, though, so an `unknown` key + * is one a route sent to a URL on NEITHER plane: a relay's or a mirror's, sent + * to a third party. Admitted, it filled placeholder plane requests and reached + * the Go `/usage` endpoint, and L8 could never drop it there (its strikes are + * kept under its route), so dropping the plane's own key handed the plane the + * relay's in its place. It answers its own route's lookup (`forRoute`) and an + * untiered one, and nothing else (OC3, both directions). + */ +const tierSatisfies = (tier: KeyTier, wanted: "go" | "zen"): boolean => + tier === wanted; + +/** + * The scope a key's strikes and drop are kept under: its plane for a key + * sent to the gateway, its route for one sent anywhere else. + */ +const scopeOf = (tier: KeyTier, provider: string | undefined): string => + tier === "unknown" ? `route:${provider ?? ""}` : tier; + +/** A capture store of its own; {@link captureStoreFor} hands one out per root. */ +export const createCaptureStore = (): CaptureStore => { + /** + * The route-scoped map carries the tier ALONGSIDE the key rather than only + * the key. It used to hold `string`, which made the route lookup the one + * path that ignored a requested tier: a Zen key seen while the Go route was + * in play came back verbatim, so it outranked every correctly-filtered + * source — and it is the FIRST captured step of both `auto` and `request`. + * Holding the tier is what lets the route lookup apply the same rule the + * other two already did. + */ + const byProvider = new Map(); + const byTier = new Map<"go" | "zen", string>(); + let latest: { key: string; provider?: string; tier: KeyTier } | undefined; + const strikes = new Map(); + const dropped = new Map(); + + /** Remove `key` from every lookup of `scope`. */ + const forget = (key: string, scope: string): void => { + for (const [provider, entry] of byProvider) { + if (entry.key === key && scopeOf(entry.tier, provider) === scope) { + byProvider.delete(provider); + } + } + for (const [tier, held] of byTier) { + if (held === key && tier === scope) { + byTier.delete(tier); + } + } + if ( + latest !== undefined && + latest.key === key && + scopeOf(latest.tier, latest.provider) === scope + ) { + latest = undefined; + } + }; + + /** Whether `key` answers any lookup of `scope`. */ + const holds = (key: string, scope: string): boolean => + [...byProvider].some( + ([provider, entry]) => + entry.key === key && scopeOf(entry.tier, provider) === scope + ) || + [...byTier].some(([tier, held]) => held === key && tier === scope) || + (latest?.key === key && scopeOf(latest.tier, latest.provider) === scope); + + return { + forRoute: (provider) => { + const entry = byProvider.get(provider); + return entry?.tier === "unknown" ? entry.key : undefined; + }, + get: (provider, tier) => { + if (typeof provider === "string" && provider.length > 0) { + const direct = byProvider.get(provider); + if ( + direct !== undefined && + (tier === undefined || tierSatisfies(direct.tier, tier)) + ) { + return direct.key; + } + } + if (tier !== undefined) { + const held = byTier.get(tier); + if (held !== undefined) { + return held; + } + } + return latest !== undefined && + (tier === undefined || tierSatisfies(latest.tier, tier)) + ? latest.key + : undefined; + }, + record: (raw, provider, url) => { + const key = usableKey(raw); + if (key === undefined) { + return; + } + // Deliberately NOT the meter's route-first precedence (`resolveGoApiKey`): + // a key seen on a live request is classified by the request that + // carried it, not by the route the user named. See `tierForRequest`. + const tier = tierForRequest(url, provider); + if (dropped.get(scopeOf(tier, provider)) === key) { + return; + } + if (typeof provider === "string" && provider.length > 0) { + byProvider.set(provider, { key, tier }); + } + if (tier !== "unknown") { + byTier.set(tier, key); + } + latest = { key, provider, tier }; + }, + settle: (key, provider, url, outcome, recordable) => { + const scope = scopeOf(tierForRequest(url, provider), provider); + const wasDropped = dropped.get(scope) === key; + if (!wasDropped && !holds(key, scope)) { + return false; + } + if (wasDropped) { + if (outcome === "accepted" && recordable) { + dropped.delete(scope); + return true; + } + return false; + } + if (outcome === "accepted") { + strikes.delete(scope); + return false; + } + const current = strikes.get(scope); + const next = strike(current?.key === key ? current.n : 0, "refused"); + if (next.evict) { + strikes.delete(scope); + forget(key, scope); + dropped.set(scope, key); + } else { + strikes.set(scope, { key, n: next.strikes }); + } + return false; + }, + }; +}; + +/** One store per root; see {@link captureStoreFor}. */ +const stores = new WeakMap(); + +/** A property read that a hostile or half-built value cannot throw out of. */ +const rootOf = (ctx: unknown): object | undefined => { + if (!isRecord(ctx)) { + return undefined; + } + try { + const root: unknown = Reflect.get(ctx, "root"); + return isRecord(root) ? root : ctx; + } catch { + return ctx; + } +}; + +/** + * The capture store of a context's root: every activation, scope and service + * of one composition shares it, and another composition never does. + * + * @param ctx - any context of the composition, real or a stand-in; a value + * that is not an object gets a store of its own that nothing else reads. + */ +export const captureStoreFor = (ctx: unknown): CaptureStore => { + const root = rootOf(ctx); + if (root === undefined) { + return createCaptureStore(); + } + let store = stores.get(root); + if (store === undefined) { + store = createCaptureStore(); + stores.set(root, store); + } + return store; +}; + +/** + * The database path the installation itself would use. + * + * Resolved per call rather than cached, because the two facts it depends on — + * the ambient environment and the home directory — belong to the process at + * request time. + * + * @returns the path the store readers take, which may be `:memory:`. + */ +const opencodeStorePath = (): string => + opencodeDatabasePath( + { + channel: process.env.OPENCODE_CHANNEL, + env: process.env, + home: os.homedir(), + }, + os.tmpdir() + ); + +/** + * The credential the OpenCode installation already holds for a plane. + * + * The path is resolved the way the installation resolves it, from the ambient + * environment and the user's home, because that is where those facts live at + * request time. Nothing here throws and nothing here logs: a machine without + * OpenCode is the ordinary case, and a secret never reaches a message. + * + * @param plane - the integration id to match: `opencode` (Zen) or + * `opencode-go`. + * @param enabled - the deployment's opt-in. When false this answers + * `undefined` without touching the filesystem, which is the default. + * @returns the stored value, or `undefined` when the switch is off, the store + * is absent or unreadable, or it holds nothing for this plane. + */ +export const resolveOpencodeStoreKey = ( + plane: string, + enabled: boolean +): string | undefined => { + if (!enabled || plane.length === 0) { + return undefined; + } + const credentials = readOpencodeCredentials(opencodeStorePath()); + return credentials?.find((entry) => entry.integrationId === plane)?.value; +}; + +/** + * What the fill consulted, for the no-credential report. Presence, never + * values. The request's own key and a captured key are not reported: every + * policy's order consults both ahead of the declared variable (`FILL_ORDER`), + * so either one present fills the wire and no report follows. + */ +export interface FillConsulted { + /** The plane's declared variable. */ + readonly declaredName: string; + /** + * Whether that variable is set at all, a placeholder included: the report + * must not send the reader to set a variable that is set to the wrong value. + */ + readonly declaredSet: boolean; + readonly storeRead: boolean; +} + +/** The fill's answer. */ +export interface FillDecision { + readonly key?: string; + readonly source?: FillSource; + readonly consulted: FillConsulted; +} + +/** The fetch patch's one credential resolver. */ +export interface FetchCredentials { + /** + * The request's own usable key, recorded only when the request belongs to a + * turn the plugin decorated and to no other plugin (OC3). + */ + readonly observe: (request: { + readonly headers: Headers; + readonly url: string; + readonly provider?: string; + readonly decorated: boolean; + readonly foreign: boolean; + readonly marked: boolean; + }) => string | undefined; + /** The key for an empty or placeholder wire key, in the policy's order. */ + readonly fillKey: (request: { + readonly plane: string; + readonly url: string; + readonly provider?: string; + readonly requestKey?: string; + }) => FillDecision; + /** + * The gateway's answer to a request of a decorated turn, folded into the + * standing of the key it carried (L8). A 2xx accepts it; a 401 on a + * well-formed session refuses it; anything else says nothing about the key. + * A request outside any decorated turn says nothing either way (OC3): the + * meter's own `/usage` poll, a Console call or another tool's background + * request neither strikes a key nor lifts a drop. The usage endpoint + * refuses keys inference accepts, so its 401 is no evidence about a turn's + * key. + */ + readonly settle: (sent: { + readonly key?: string; + readonly url: string; + readonly provider?: string; + readonly status: number; + readonly sessionWellFormed: boolean; + /** The request belongs to a turn the plugin decorated. */ + readonly decorated: boolean; + /** The key was the request's own, and the request's keys may be kept. */ + readonly recordable: boolean; + }) => void; + /** The pinned session id a deployment exported under `sessionIdEnv`. */ + readonly sessionPin: (name: string | undefined) => string | undefined; +} + +/** What {@link createCredentials} takes. */ +export interface CredentialInputs { + readonly store: CaptureStore; + readonly keySource: KeySourcePolicy; + readonly readOpencodeStore: boolean; + /** The process environment by default; a test hands its own. */ + readonly environment?: (name: string) => string | undefined; + /** + * The installation's store for a plane, consulted only when the deployment + * opted in and every earlier step answered nothing. The real store + * ({@link resolveOpencodeStoreKey}) by default; a test hands its own to see + * when it is read. + */ + readonly storeReader?: (plane: string) => string | undefined; +} + +/** + * The fetch patch's resolver over one capture store. + * + * @param inputs - the store, the policy, the store opt-in, the environment. + * @returns the resolver. + */ +export const createCredentials = ( + inputs: CredentialInputs +): FetchCredentials => { + const environment = + inputs.environment ?? ((name: string) => process.env[name]); + const storeReader = + inputs.storeReader ?? + ((plane: string) => resolveOpencodeStoreKey(plane, true)); + const { store } = inputs; + return { + fillKey: ({ plane, provider, requestKey, url }) => { + // The captured key is looked up by tier as well as by provider: a user + // may have named the route anything, and a provider-id miss must not + // hide a key that is already known to work. A request on neither plane + // takes only the key its own route sent there (OC3). Under the + // `configured` policy the declared credential wins outright, so the + // capture is skipped entirely. + const tier = tierForRequest(url, provider); + let captured: string | undefined; + if (inputs.keySource !== "configured") { + if (tier !== "unknown") { + captured = store.get(provider, tier); + } else if (provider !== undefined) { + captured = store.forRoute(provider); + } + } + // Only a known gateway plane may ask for its own variable: a configured + // provider can also claim other URLs, which take the Zen one, as they + // always have. + const declaredName = + plane === "opencode-go" || + (plane.length === 0 && provider === "opencode-go") + ? "OPENCODE_GO_API_KEY" + : "OPENCODE_API_KEY"; + const declared = environment(declaredName); + // **API key only.** The credential ladder ends at the installation's own + // store: a login (device flow, session, credential pool) is v2 work and + // does not live here. `readOpencodeStore` is off unless the deployment + // opted in. + const decided = firstUsable(FILL_ORDER[inputs.keySource], { + captured: () => captured, + declared: () => declared, + request: () => requestKey, + store: () => + inputs.readOpencodeStore ? storeReader(plane) : undefined, + }); + return { + consulted: { + declaredName, + declaredSet: declared !== undefined && declared.length > 0, + storeRead: inputs.readOpencodeStore, + }, + ...(decided === undefined + ? {} + : { key: decided.key, source: decided.step }), + }; + }, + observe: ({ decorated, foreign, headers, marked, provider, url }) => { + const key = usableKey(extractApiKeyFromHeaders(headers)); + if (key !== undefined && mayCapture({ decorated, foreign, marked })) { + store.record(key, provider, url); + } + return key; + }, + sessionPin: (name) => + name === undefined || name.length === 0 ? undefined : environment(name), + settle: ({ + decorated, + key, + provider, + recordable, + sessionWellFormed, + status, + url, + }) => { + const sent = usableKey(key); + if (sent === undefined || !decorated) { + return; + } + if (status >= 200 && status < 300) { + if (store.settle(sent, provider, url, "accepted", recordable)) { + store.record(sent, provider, url); + } + return; + } + if (countsAsRefusal({ keySent: true, sessionWellFormed, status })) { + store.settle(sent, provider, url, "refused", recordable); + } + }, + }; +}; diff --git a/src/fetch-patch.ts b/src/fetch-patch.ts index 9b84945..49f8551 100644 --- a/src/fetch-patch.ts +++ b/src/fetch-patch.ts @@ -5,9 +5,17 @@ * provider on the active turn) are touched; everything else returns through * the original `fetch` byte-identical, and so does a request of another * plugin's (D27): one issued inside a turn the stream hook marked `foreign`, - * or one that carries an `x-opencode-plugin` marker. For claimed requests the patch - * restores the session header, the CLI User-Agent, and the gateway origin - * headers, and runs the free-tier core-tool fallback over the body. + * or one that carries an `x-opencode-plugin` marker. For claimed requests the + * patch fills an empty or placeholder credential (`credentials.ts`, the one + * resolver), restores the CLI User-Agent, and runs the free-tier core-tool + * fallback over the body. + * + * The plane headers (session, parent, org, origin) are written here for a + * relay, a turnless URL-claimed request and a turn the plane adapter did not + * shape. On a turn whose requests the plane adapter shaped per call (OC5, + * `prepareHeaders` in `host/plane-provider.ts`) the patch writes none of them + * while the request carries a well-formed session id: the adapter's are the + * plugin's own, and a contributor's change to them is the contributor's. * * @module dsh-opencode-patch/fetch-patch */ @@ -15,14 +23,12 @@ import type { AsyncLocalStorage } from "node:async_hooks"; import { DEFAULT_GATEWAY_URLS, type ResolvedPluginConfig } from "./config.ts"; -import { resolveOpencodeStoreKey } from "./go-discovery.ts"; import { - extractApiKeyFromHeaders, - getCapturedApiKey, - isPlaceholderApiKey, - recordCapturedApiKey, - tierForRequest, -} from "./key-capture.ts"; + createCaptureStore, + createCredentials, + type FetchCredentials, +} from "./credentials.ts"; +import { extractApiKeyFromHeaders } from "./key-capture.ts"; import { type CatalogPlane, enrichModelsResponse, @@ -31,26 +37,24 @@ import { isModelsListingUrl, } from "./models-catalog.ts"; import { - isOpenCodeMessageId, isOpenCodeSessionId, OPENCODE_UA, - PARENT_SESSION_ALT_HEADER, - PARENT_SESSION_HEADER, - SESSION_AFFINITY_HEADER, SESSION_HEADER, - SESSION_ID_HEADER, digestOf, sessionIdForRequest, } from "./session.ts"; import { maybeInjectCoreTools } from "./tool-fallback.ts"; import type { ActiveTurnState } from "./turn-store.ts"; -import { PLUGIN_MARKER_HEADER } from "./utils/plane-ownership.ts"; +import { needsFill, usableKey } from "./utils/credential-policy.ts"; import { ANTHROPIC_VERSION, authHeaderFor, gatewayPlaneFor, headerSourceOf, isGoPlaneUrl, + planeHeadersFor, + pluginMarkerOn, + projectHeaderOf, requestUrlOf, toolNamesOf, } from "./utils/request-shape.ts"; @@ -188,6 +192,18 @@ export interface FetchPatchHooks { * interceptor SAW and what it SENT, never the credential itself. */ readonly debug?: (entry: Record) => void; + /** + * The credential resolver and the capture store it learns into. The plugin + * hands the one of its root (`captureStoreFor`), so the meter reads what + * the fill learned; absent, the patch keeps a store of its own. + */ + readonly credentials?: FetchCredentials; + /** + * Whether this patch is still live. A patch disposed while another wraps it + * stays in the chain as a pass-through link (`host/global-fetch.ts`), so a + * request through it reaches the fetch underneath untouched. + */ + readonly live?: () => boolean; } export const patchFetch = ( @@ -199,11 +215,21 @@ export const patchFetch = ( // One report per plane for the no-credential case, because this runs on every // gateway request and the same missing credential would otherwise log on each. const warnedNoCredential = new Set(); + const credentials = + hooks.credentials ?? + createCredentials({ + keySource: config.keySource, + readOpencodeStore: config.readOpencodeStore, + store: createCaptureStore(), + }); const patchedFetch = async function patchedFetch( this: unknown, input: RequestInfo | URL, init?: RequestInit ): Promise { + if (hooks.live?.() === false) { + return original.call(this, input, init); + } const state = als.getStore(); // **A turn another plugin owns goes out as it was sent** (D27): the // stream hook marks a turn on a stepped-aside plane, whichever rule @@ -225,7 +251,7 @@ export const patchFetch = ( // plugin wrote through pi-ai carries its marker, and its credential comes // from a realm this plugin does not share: no header of ours, no key fill // and no key capture, so its token is never recorded or replayed. - if (headers.has(PLUGIN_MARKER_HEADER)) { + if (pluginMarkerOn(headers) !== undefined) { return original.call(this, input, init); } @@ -248,16 +274,19 @@ export const patchFetch = ( } } - // Capture the API key from the request headers so that quota monitoring, - // usage display, and key resolution don't have to rely purely on static env vars. - const extracted = extractApiKeyFromHeaders(headers); - const requestKey = - extracted === undefined || isPlaceholderApiKey(extracted) - ? undefined - : extracted; - if (requestKey !== undefined) { - recordCapturedApiKey(requestKey, state?.provider, url); - } + // The request's own key, recorded only when this request belongs to a turn + // the plugin decorated (OC3): a key on a turnless request — a Console + // call, another tool's background request — was not sent by the plugin, + // and is never kept or replayed. A foreign turn and a marked request + // returned above; the rule still takes both, so it is one function. + const requestKey = credentials.observe({ + decorated: state !== undefined, + foreign: false, + headers, + marked: false, + provider: state?.provider, + url, + }); // Ensure an Authorization header is present if the caller omitted it or provided a dummy value. const plane = gatewayPlaneFor(url); @@ -272,50 +301,23 @@ export const patchFetch = ( if (wireHeader === "x-api-key" && !headers.has("anthropic-version")) { headers.set("anthropic-version", ANTHROPIC_VERSION); } - const authHeader = headers.get(wireHeader); - const wireKey = authHeader?.replace(/^Bearer\s+/iu, "").trim(); - if ( - wireKey === undefined || - wireKey.length === 0 || - isPlaceholderApiKey(wireKey) - ) { - // The captured key is looked up by tier as well as by provider: a user - // may have named the route anything, and a provider-id miss must not hide - // a key that is already known to work. Under the `configured` policy the - // declared credential wins outright, so the capture is skipped entirely. - const tier = tierForRequest(url, state?.provider); - const captured = - config.keySource === "configured" - ? undefined - : getCapturedApiKey( - state?.provider, - tier === "unknown" ? undefined : tier - ); - // Explicit request auth (including x-api-key) and declared sources win. - // Only a known gateway plane may ask for a login: a configured provider - // can also claim other URLs, which must not receive an account token. - const declared = - plane === "opencode-go" || - (plane.length === 0 && state?.provider === "opencode-go") - ? process.env.OPENCODE_GO_API_KEY - : process.env.OPENCODE_API_KEY; - const explicit = - requestKey ?? - captured ?? - (declared === undefined || - declared.length === 0 || - isPlaceholderApiKey(declared) - ? undefined - : declared); - // **API key only.** The credential ladder ends at the installation's own - // store: a login (device flow, session, credential pool) is v2 work and does - // not live here. `readOpencodeStore` is off unless the deployment opted in. - const fallbackKey = - explicit ?? resolveOpencodeStoreKey(plane, config.readOpencodeStore); - if (typeof fallbackKey === "string" && fallbackKey.length > 0) { + const wireKey = headers + .get(wireHeader) + ?.replace(/^Bearer\s+/iu, "") + .trim(); + if (needsFill(wireKey)) { + const decision = credentials.fillKey({ + plane, + provider: state?.provider, + requestKey, + url, + }); + if (decision.key !== undefined) { headers.set( wireHeader, - wireHeader === "authorization" ? `Bearer ${fallbackKey}` : fallbackKey + wireHeader === "authorization" + ? `Bearer ${decision.key}` + : decision.key ); // **One credential, on the protocol's own header, and nothing else.** // The official client passes the key as an SDK option @@ -346,16 +348,16 @@ export const patchFetch = ( !isFreeModelBody(bodyToPatch, isGoPlaneUrl(url) ? "go" : "zen") ) { warnedNoCredential.add(plane); + const { consulted } = decision; + // The request's own key and a captured one answer "none" by + // construction: every policy consults both ahead of the declared + // variable, so either one present would have filled the wire. const sources: string[] = [ - `a key on the request: ${requestKey === undefined ? "none" : "present"}`, - `a key captured from a live request (policy ${config.keySource}): ${ - captured === undefined ? "none" : "present" - }`, - `${plane === "opencode-go" ? "OPENCODE_GO_API_KEY" : "OPENCODE_API_KEY"}: ${ - declared === undefined || declared.length === 0 ? "unset" : "set" - }`, + "a key on the request: none", + `a key captured from a live request (policy ${config.keySource}): none`, + `${consulted.declaredName}: ${consulted.declaredSet ? "set" : "unset"}`, `the installation's own store: ${ - config.readOpencodeStore ? "read" : "not enabled" + consulted.storeRead ? "read" : "not enabled" }`, ]; console.warn( @@ -365,90 +367,51 @@ export const patchFetch = ( } } - // 1. Session headers, as the version this plugin emulates sends them. - // - // Read from the 1.x line's last release, v1.19.5, in - // `packages/opencode/src/session/llm/request.ts`: `x-opencode-session-id` - // and `x-opencode-session` both carry `sessionID`, and the affinity pair - // belongs to relays. 2.x splits the first of those into an affinity id; the - // plugin emulates 1.19.5, so it follows 1.19.5. - // - // Which ENDPOINT the request goes to is the deployment's, not this block's: - // measured, either key serves a paid model on either endpoint - they are two - // paths into one gateway - so nothing here has to pick one. `x-opencode- - // request` is the one header of the set this plugin does not send, because - // the CLI fills it from its own user id and the turn store has no equivalent. - const envName = - config.sessionIdEnv !== undefined && config.sessionIdEnv.length > 0 - ? config.sessionIdEnv - : undefined; - const sessionVal = sessionIdForRequest( - state?.value, - headers.get(SESSION_HEADER), - envName === undefined ? undefined : process.env[envName], - digestOf - ); - headers.set("x-opencode-session-id", sessionVal); - headers.set(SESSION_HEADER, sessionVal); - // The affinity pair belongs to the OTHER branch in 1.19.5: for a provider - // that does not start with `opencode` - a relay a deployment claimed by URL - - // the client sends `x-session-affinity` and `X-Session-Id`; for an OpenCode - // plane it sends `x-opencode-session` instead and nothing else. This plugin - // sent all three everywhere, which is neither generation's behaviour. - if (!(state?.provider ?? "").startsWith("opencode")) { - headers.set(SESSION_AFFINITY_HEADER, sessionVal); - headers.set(SESSION_ID_HEADER, sessionVal); - } - - // 1b. Parent session header: injected for subagents and child sessions - if (state?.parentValue !== undefined) { - headers.set(PARENT_SESSION_HEADER, state.parentValue); - headers.set(PARENT_SESSION_ALT_HEADER, state.parentValue); + // The plane headers (`planeHeadersFor`, the one table the per-call seam + // writes from too). On a turn the plane adapter shaped per call (OC5) a + // request that carries a well-formed session id keeps the headers it was + // given; a malformed one is still replaced, because the gateway answers + // it with `401 Invalid API key` (L8), whoever wrote it. + const shaped = + state?.perCall === true && + isOpenCodeSessionId(headers.get(SESSION_HEADER)); + if (!shaped) { + const sessionVal = sessionIdForRequest( + state?.value, + headers.get(SESSION_HEADER), + credentials.sessionPin(config.sessionIdEnv), + digestOf + ); + // The org: the configured one wins, because it is the one thing here + // the user said out loud; the hook is the deployment's own source. + const org = + config.credentialOrg ?? hooks.resolveOrg?.(gatewayPlaneFor(url)); + for (const [name, value] of planeHeadersFor({ + org, + origin: config.injectOriginHeaders + ? { + client: config.originClient, + project: config.injectProject + ? projectHeaderOf(state?.project) + : undefined, + request: state?.requestValue, + } + : undefined, + parent: state?.parentValue, + relay: !(state?.provider ?? "").startsWith("opencode"), + session: sessionVal, + })) { + headers.set(name, value); + } } - // 2. User-Agent: injected / restored when enabled, with user override support + // User-Agent: injected / restored when enabled, with user override + // support, whoever shaped the rest — attribution wins after pi-ai's + // `prepareHeaders`, so the per-call seam cannot carry it. if (config.injectUserAgent) { headers.set("User-Agent", config.userAgent ?? OPENCODE_UA); } - // 2b. The org, when this plane's credential belongs to one. A session token - // needs the org it belongs to — measured on a paid model: `200` with it, - // `403` without — and the free tier is refused with or without one, which is - // a gate no header cleared. - // The configured org wins, because it is the one thing here the user said out - // loud. The hook is the deployment's own source (an account that ships with - // the profile); there is no login to infer one from. - const org = - config.credentialOrg ?? hooks.resolveOrg?.(gatewayPlaneFor(url)); - if (org !== undefined && org.length > 0) { - headers.set("x-opencode-org-id", org); - } - - // 3. Client & Project origin headers: injected when enabled - if (config.injectOriginHeaders) { - headers.set("x-opencode-client", config.originClient); - - // The message id, the one header of the captured set this block omitted. - // Read from v1.19.5's `request.ts`: `"x-opencode-request": input.user.id`, - // in the same branch as the client and project headers. The console reads - // it for per-request metrics and rewrites it to `x-opencode-request-id` - // before the request reaches the inference service - // (`inference-proxy.ts`); the turn store carries the value because a - // request cannot know its own message id. - const requestValue = state?.requestValue; - if (requestValue !== undefined && isOpenCodeMessageId(requestValue)) { - headers.set("x-opencode-request", requestValue); - } - - if (config.injectProject) { - const project = - state?.project !== undefined && state.project.length > 0 - ? state.project - : "global"; - headers.set("x-opencode-project", project); - } - } - const newInit: RequestInit = { ...init, headers }; let requestToSend = input; @@ -481,6 +444,27 @@ export const patchFetch = ( const response = await original.call(this, requestToSend, newInit); + // What the gateway said about the key a request of a decorated turn + // carried (L8): a key the plugin captured is dropped after a second + // well-formed 401 in a row, and comes back once a request of a decorated + // turn carrying it as its own is accepted. A turnless request (the + // meter's `/usage` poll among them) settles nothing (OC3). + const sentKey = usableKey( + headers.get(wireHeader)?.replace(/^Bearer\s+/iu, "") + ); + credentials.settle({ + decorated: state !== undefined, + key: sentKey, + provider: state?.provider, + // A dropped key comes back only on a request that may file it: its + // own key, on a turn the plugin decorated (OC3). + recordable: + state !== undefined && sentKey !== undefined && sentKey === requestKey, + sessionWellFormed: isOpenCodeSessionId(headers.get(SESSION_HEADER)), + status: response.status, + url, + }); + // One line per request the interceptor touched, so a run that misbehaves can // be read back instead of guessed at. Presence, never values: whether a // credential, a session and an org were SENT is what explains an answer, and diff --git a/src/go-discovery.ts b/src/go-discovery.ts index 2f76f05..cfff1eb 100644 --- a/src/go-discovery.ts +++ b/src/go-discovery.ts @@ -10,25 +10,24 @@ * (`key-capture.ts`). `usageBaseURL` remains as the one endpoint override. * * Credential *capture* — pulling a key off a live request and classifying its - * tier — lives in `key-capture.ts`. This module owns the plan side: which - * endpoint, which credential reference, and the policy that orders the two - * sources against each other. + * tier — lives in `key-capture.ts`, and the store it is kept in, one per + * root, in `credentials.ts`. This module owns the plan side: which endpoint, + * which credential reference, and the policy that orders the sources against + * each other (`METER_ORDER`, in `utils/credential-policy.ts`). * * @module dsh-opencode-patch/go-discovery */ -import os from "node:os"; - import type { KeySourcePolicy } from "./config-values.ts"; import { DEFAULT_USAGE_BASE_URL, DEFAULT_USAGE_KEY_ENV } from "./config.ts"; import { loaderOfContext, readCredentialsResolver } from "./cordis-context.ts"; +import { captureStoreFor, resolveOpencodeStoreKey } from "./credentials.ts"; +import { extractApiKeyFromHeaders } from "./key-capture.ts"; import { - extractApiKeyFromHeaders, - getCapturedApiKey, - isPlaceholderApiKey, -} from "./key-capture.ts"; -import { opencodeDatabasePath } from "./opencode-paths.ts"; -import { readOpencodeCredentials } from "./opencode-store.ts"; + firstUsableAsync, + METER_ORDER, + usableKey, +} from "./utils/credential-policy.ts"; import { isRecord } from "./utils/guards.ts"; import { foreignCredentialsRealm, @@ -56,15 +55,15 @@ export interface DiscoveredGoConfig { * - **Placeholders.** `Bearer unused` is not a typo — it is what this plugin's * own keyless routes carry, and what the README tells users to write. It is a * deliberate stand-in for "this route needs a key injected later", so it must - * never be mistaken for the key itself. `recordCapturedApiKey` already refuses + * never be mistaken for the key itself. The capture store already refuses * one; a discovered literal has to refuse it too, or the meter's first step * hands the gateway a placeholder and the poll fails with a 401 that reads * like a missing subscription. + * + * Both are `usableKey`'s, the one filter every decider shares. */ const usableCredential = (value: unknown): value is string => - typeof value === "string" && - value.trim().length > 0 && - !isPlaceholderApiKey(value.trim()); + usableKey(value) !== undefined; const readProviderRow = ( row: Record, @@ -309,129 +308,10 @@ export const resolveGoBaseURL = ( export const effectiveGoKeyRef = (discovered: DiscoveredGoConfig): string => discovered.keyEnv ?? DEFAULT_USAGE_KEY_ENV; -/** - * One lookup step a policy can consult. - * - * `captured` is scoped to the route in hand; `capturedAny` accepts a key - * captured under any route. They are separate steps so `auto` can keep - * credentials ahead of the any-route fallback, exactly as it always has. - * - * `opencodeStore` is the installation's own store, and it is LAST in every - * policy rather than placed among them: everything the user declared — a - * literal, a captured request, a named reference — outranks anything inferred - * from another program's files. - */ -type KeySourceStep = - | "captured" - | "capturedAny" - | "configured" - | "literal" - | "opencodeStore"; - -/** - * The lookup order each policy imposes — the only thing the user is choosing - * between. - * - * `auto` reproduces the original precedence exactly, so the default is not a - * behaviour change: composition first, then a captured key in the right tier, - * then credentials/env, then any captured key. `request` promotes both captured - * steps above the declared sources; `configured` does the reverse. - * - * The captured steps read only keys filed under the Go plane, in all three - * policies — but a key is filed by the plane its request went to, not by what - * it is entitled to. Nothing here can tell a Zen key from a Go key: a Go entry - * without `apiKeyEnv` sends pi's `OPENCODE_API_KEY` on its turns (D20), that - * bearer is filed as a Go key, and `auto` then sends it to the Go usage - * endpoint, which refuses it. Naming the reference on the Go entry is the fix. - * - * The store is appended to all three, and to none of them in the middle: the - * policy orders the sources the user declared, and the installation's store is - * never one of those. - */ -const KEY_SOURCE_ORDER: Record = { - auto: ["literal", "captured", "configured", "capturedAny", "opencodeStore"], - configured: [ - "literal", - "configured", - "captured", - "capturedAny", - "opencodeStore", - ], - request: [ - "captured", - "capturedAny", - "literal", - "configured", - "opencodeStore", - ], -}; - -/** First non-empty result from a policy's steps, or `undefined`. */ -const firstResolved = async ( - order: readonly KeySourceStep[], - steps: Record unknown> -): Promise => { - for (const step of order) { - // Sequential on purpose: the order IS the policy, and a later step must not - // run (or be able to throw) once an earlier one has answered. - // oxlint-disable-next-line no-await-in-loop -- see above; order is the contract. - const value: unknown = await steps[step](); - if (typeof value === "string" && value.length > 0) { - return value; - } - } - return undefined; -}; - -/** - * The database path the installation itself would use. - * - * Resolved per call rather than cached, because the two facts it depends on — - * the ambient environment and the home directory — belong to the process at - * request time. - * - * @returns the path the store readers take, which may be `:memory:`. - */ -const opencodeStorePath = (): string => - opencodeDatabasePath( - { - channel: process.env.OPENCODE_CHANNEL, - env: process.env, - home: os.homedir(), - }, - os.tmpdir() - ); - -/** - * The credential the OpenCode installation already holds for a plane. - * - * The path is resolved the way the installation resolves it, from the ambient - * environment and the user's home, because that is where those facts live at - * request time. Nothing here throws and nothing here logs: a machine without - * OpenCode is the ordinary case, and a secret never reaches a message. - * - * @param plane - the integration id to match: `opencode` (Zen) or - * `opencode-go`. - * @param enabled - the deployment's opt-in. When false this answers - * `undefined` without touching the filesystem, which is the default. - * @returns the stored value, or `undefined` when the switch is off, the store - * is absent or unreadable, or it holds nothing for this plane. - */ -export const resolveOpencodeStoreKey = ( - plane: string, - enabled: boolean -): string | undefined => { - if (!enabled || plane.length === 0) { - return undefined; - } - const credentials = readOpencodeCredentials(opencodeStorePath()); - return credentials?.find((entry) => entry.integrationId === plane)?.value; -}; - /** * Resolve the Go API key without ever exposing it to the client. * - * Order is {@link KEY_SOURCE_ORDER}`[policy]`; with the default `auto` that is + * Order is `METER_ORDER[policy]`; with the default `auto` that is * a literal `apiKey` discovered in another entry, then a captured key for the * Go tier, then the credential service and environment, then any captured key, * and last the installation's own store when the deployment opted in. @@ -451,9 +331,10 @@ export const resolveGoApiKey = ( readOpencodeStore = false ): Promise => { const discovered = discoverGoConfig(ctx, targetProvider); - return firstResolved(KEY_SOURCE_ORDER[policy], { - captured: () => getCapturedApiKey(targetProvider, "go"), - capturedAny: () => getCapturedApiKey(undefined, "go"), + const store = captureStoreFor(ctx); + return firstUsableAsync(METER_ORDER[policy], { + captured: () => store.get(targetProvider, "go"), + capturedAny: () => store.get(undefined, "go"), configured: () => resolveGoKeyForRef(ctx, effectiveGoKeyRef(discovered)), literal: () => discovered.literalKey, opencodeStore: () => @@ -463,7 +344,9 @@ export const resolveGoApiKey = ( /** * Resolve one credential reference through the credentials service, then the - * environment. + * environment, each answer through the one filter (`usableKey`): a blank or a + * placeholder is no credential, and a service that answers one falls through + * to the environment, as {@link resolveGoKeyForRef} does. * * Never throws: a failing credentials service degrades to the env path. * @@ -477,16 +360,16 @@ const resolveRef = async ( const resolve = readCredentialsResolver(ctx); if (resolve !== undefined) { try { - const hit = await resolve(ref); - if (hit?.value !== undefined && hit.value.length > 0) { - return hit.value; + const answer = await resolve(ref); + const hit = usableKey(answer?.value); + if (hit !== undefined) { + return hit; } } catch { // Fall through to the environment. } } - const fromEnv = process.env[ref]; - return fromEnv !== undefined && fromEnv.length > 0 ? fromEnv : undefined; + return usableKey(process.env[ref]); }; /** @@ -508,7 +391,7 @@ const resolveRef = async ( * rather than a guess about a string. */ const isUsableGoKey = (value: string | undefined): value is string => - value !== undefined && value.length > 0 && !isPlaceholderApiKey(value); + usableKey(value) !== undefined; /** * Look one credential reference up for the Go quota endpoint. @@ -582,8 +465,7 @@ export interface ZenCreditInfo { export const resolveZenCreditInfo = async ( ctx: unknown ): Promise => { - const capturedZen = getCapturedApiKey("opencode", "zen"); - if (capturedZen !== undefined && capturedZen.length > 0) { + if (usableKey(captureStoreFor(ctx).get("opencode", "zen")) !== undefined) { return { isConfigured: true }; } diff --git a/src/host/global-fetch.ts b/src/host/global-fetch.ts new file mode 100644 index 0000000..f09dfd6 --- /dev/null +++ b/src/host/global-fetch.ts @@ -0,0 +1,103 @@ +/** + * The plugin's one write to `globalThis.fetch`, and how it is undone. + * + * Activations of the plugin on one root nest their patches: each wraps + * whatever `globalThis.fetch` is when its effect runs, which is the previous + * activation's patch while that one is live. Undoing them in any order has to + * end at the fetch that was there before the first, which a plain "restore + * what I wrapped, if I am still current" cannot do: disposing the earlier + * activation first skips its restore (it is not current), and the later one + * then restores the earlier one's patch, which outlives both. + * + * So the installer keeps a chain of its links: + * + * - the original is read INSIDE the effect, so a fetch swapped between + * `apply` and the effect is the one wrapped; + * - a link disposed while something sits on top of it stays in place as a + * pass-through (the patch reads its `live` flag first), so whatever wraps + * it still reaches the fetch underneath; + * - a link disposed while it is current restores what it wrapped, and keeps + * unwinding while the function now in place is a disposed link of its own; + * - a function the plugin did not install is never replaced or removed. + * + * @module dsh-opencode-patch/host/global-fetch + */ + +import type { CordisContext } from "../cordis-context.ts"; +import { isFetchFunction } from "../utils/guards.ts"; + +/** One installed patch: what it wrapped, and whether its activation is live. */ +interface Link { + readonly original: typeof fetch; + readonly patched: typeof fetch; + readonly activation: { live: boolean }; +} + +/** Every link not yet unwound, in install order. Module-level: one per process, as `globalThis` is. */ +const chain: Link[] = []; + +const UNAVAILABLE = + "[dsh-opencode-patch] globalThis.fetch is unavailable; cannot inject x-opencode-session"; + +/** + * Install one activation's fetch patch, restored on the activation's dispose. + * + * @param ctx - the activation's context; the patch lives in its effect. + * @param build - wraps the fetch in place at effect time; `live` answers + * false once the activation is disposed, so a link left in the chain passes + * through. + * @param announce - called once the patch is in place. + * @returns `undefined` when there is no fetch to wrap (the caller then + * attaches nothing that needs one); otherwise whether `globalThis.fetch` is + * a live patch of the plugin's, this activation's own or one that wraps it + * (L1). + */ +export const installGlobalFetch = ( + ctx: CordisContext, + build: (original: typeof fetch, live: () => boolean) => typeof fetch, + announce: () => void +): (() => boolean) | undefined => { + if (!isFetchFunction(globalThis.fetch)) { + ctx.logger?.warn?.(UNAVAILABLE); + return undefined; + } + ctx.effect?.(() => { + const original: unknown = globalThis.fetch; + if (!isFetchFunction(original)) { + ctx.logger?.warn?.(UNAVAILABLE); + return () => { + // Nothing was installed, so there is nothing to restore. + }; + } + const activation = { live: true }; + const link: Link = { + activation, + original, + patched: build(original, () => activation.live), + }; + globalThis.fetch = link.patched; + chain.push(link); + announce(); + return () => { + activation.live = false; + if (globalThis.fetch !== link.patched) { + // Something wraps this link: it stays, passing through, until the + // function on top of it unwinds to it. + return; + } + let current: Link | undefined = link; + while (current !== undefined) { + chain.splice(chain.indexOf(current), 1); + globalThis.fetch = current.original; + current = chain.find( + (below) => + !below.activation.live && below.patched === globalThis.fetch + ); + } + }; + }, "dsh-opencode-patch.fetch-patch"); + return () => + chain.some( + (link) => link.activation.live && link.patched === globalThis.fetch + ); +}; diff --git a/src/host/plane-provider.ts b/src/host/plane-provider.ts index 0adc547..b0d2452 100644 --- a/src/host/plane-provider.ts +++ b/src/host/plane-provider.ts @@ -26,6 +26,13 @@ * both are restated here over the same seams, keyed by pi-ai's exported * `recordKeyFor`, and the key resolution mirrors pi-ai's exactly (D20). * + * The adapter is also built with pi-ai's `prepareHeaders` option, as pi-ai's + * own adapter is ({@link planeRequestHeaders}): per call, the plugin writes + * the plane headers from the turn the stream hook decorated (OC5), and then + * runs the host's `llm-pi-ai/request-headers` waterfall, so another plugin's + * contributor runs on the planes the plugin serves as it does on pi-ai's own + * routes (OC4). pi-ai applies its attribution after both. + * * @module dsh-opencode-patch/host/plane-provider */ @@ -35,7 +42,7 @@ import { type HostModules, readLaunchEnvironment, } from "../cordis-context.ts"; -import { resolveOpencodeStoreKey } from "../go-discovery.ts"; +import { resolveOpencodeStoreKey } from "../credentials.ts"; import { reclassifyRefusals } from "../utils/gateway-refusal.ts"; import { isAsyncIterableLike, @@ -102,6 +109,8 @@ export interface PlaneAdapterInputs { model: string; reason: string; }) => void; + /** pi-ai's per-call header seam; see {@link planeRequestHeaders}. */ + readonly prepareHeaders?: (request: unknown, headers: Headers) => Headers; } /** The error code of a thrown value, when it has one. */ @@ -260,9 +269,60 @@ export const createPlaneAdapter = (inputs: PlaneAdapterInputs): object => { ...(inputs.onReplayDegrade === undefined ? {} : { onReplayDegrade: inputs.onReplayDegrade }), + ...(inputs.prepareHeaders === undefined + ? {} + : { prepareHeaders: inputs.prepareHeaders }), }); }; +/** + * The plane adapter's `prepareHeaders`: the plugin's plane headers, then the + * host's `llm-pi-ai/request-headers` waterfall, exactly as pi-ai's own + * `apply` wires the option for its adapter. + * + * The order is profile headers (pi-ai sets them before calling this), the + * plugin's plane headers, the contributors, and pi-ai's attribution last — + * the place profile headers hold on pi-ai's own routes. A contributor can + * therefore see, and change, what the plugin set. + * + * Detected by behaviour, never by a host version: the waterfall runs only + * where the context has one, and a host whose adapter never calls this option + * leaves the turn unflagged, so the fetch patch shapes it as it always has. + * + * @param ctx - the plugin context whose `waterfall` runs the contributors. + * @param shape - writes the plugin's plane headers for the current turn; it + * never throws out of here, because an unshaped turn is still shaped by the + * fetch patch. + * @returns the option; a contributor's throw propagates, and pi-ai fails the + * call with `REQUEST_HEADERS`, as on its own routes. + */ +export const planeRequestHeaders = + (ctx: unknown, shape?: (headers: Headers) => void) => + (request: unknown, headers: Headers): Headers => { + try { + shape?.(headers); + } catch { + // Never throws: an unshaped turn is shaped by the fetch patch. + } + if (!isRecord(ctx) || !isFunctionLike(ctx.waterfall)) { + return headers; + } + const prepared: unknown = Reflect.apply(ctx.waterfall, ctx, [ + "llm-pi-ai/request-headers", + request, + headers, + () => headers, + ]); + if (!(prepared instanceof Headers)) { + // What pi-ai's own route does with such an answer: its attribution + // write fails, and the call with it (`REQUEST_HEADERS`). + throw new TypeError( + "a llm-pi-ai/request-headers contributor answered something other than Headers" + ); + } + return prepared; + }; + /** A pi credential, as pi-ai maps one from a stored record. */ type PiCredential = Readonly>; diff --git a/src/host/route-claim.ts b/src/host/route-claim.ts index 991fb8b..259b797 100644 --- a/src/host/route-claim.ts +++ b/src/host/route-claim.ts @@ -135,6 +135,7 @@ import { planeApiKeyResolver, planeAuth, type PlaneProfileLike, + planeRequestHeaders, } from "./plane-provider.ts"; /** cordis `FiberState`. */ @@ -280,11 +281,15 @@ const codeOf = (error: unknown): unknown => * * @param ctx - the plugin context (its root fiber). * @param config - the plugin's resolved settings. + * @param seams - what the plugin hands the adapter beyond its settings: + * `callHeaders` writes the plane headers of the current turn per call + * (OC5), ahead of the host's `llm-pi-ai/request-headers` waterfall (OC4). * @returns the claim's readers and its mount. */ export const installRouteClaim = ( ctx: CordisContext, - config: Pick + config: Pick, + seams: { readonly callHeaders?: (headers: Headers) => void } = {} ): RouteClaim => { const state = { active: true, @@ -529,6 +534,7 @@ export const installRouteClaim = ( `unusable replay state on assistant history for route "${provider}/${model}"; sending that message as provider-neutral content (${reason})` ); }, + prepareHeaders: planeRequestHeaders(ctx, seams.callHeaders), profiles: () => state.profiles, resolveApiKey: planeApiKeyResolver(ctx, modules, config, auth), resolveAttachments: images.resolveAttachments, diff --git a/src/key-capture.ts b/src/key-capture.ts index cd03fbe..2a610e2 100644 --- a/src/key-capture.ts +++ b/src/key-capture.ts @@ -1,11 +1,12 @@ /** - * Credential capture: what a key *is*, and where it was last seen. + * Credential capture: what a key *is*, and which account it belongs to. * * The plugin can learn a key two ways — observed on a live request, or resolved - * from declared configuration — and this module owns the first: pulling a - * credential out of whatever header shape carried it, classifying which account - * tier it belongs to, and remembering it so later lookups do not have to fall - * back to a static environment variable that may have gone stale. + * from declared configuration — and this module reads the first: pulling a + * credential out of whatever header shape carried it, and classifying which + * account tier it belongs to. Remembering it is the capture store's, one per + * root (`credentials.ts`), and what counts as a credential at all is + * `utils/credential-policy.ts`'s. * * Split out of `go-discovery.ts`, which keeps the *plan* side (which endpoint, * which key reference, and the policy that orders the two sources). The seam is @@ -15,42 +16,13 @@ * @module dsh-opencode-patch/key-capture */ +import { isPlaceholderApiKey } from "./utils/credential-policy.ts"; import { isRecord } from "./utils/guards.ts"; import { gatewayPlaneFor } from "./utils/request-shape.ts"; /** Account tiers a captured credential can belong to. */ export type KeyTier = "go" | "zen" | "unknown"; -/** - * Bearer values the DSH adapter emits when it holds no real credential, plus the - * gateway's own keyless sentinel. - * - * These are the exact strings the Authorization fallback exists to repair, so - * they must never be *recorded* as a captured key: doing so overwrites a working - * key with a dummy one, and every later lookup then re-injects the dummy. - * - * `public` is not an adapter placeholder — it is the gateway's own literal for a - * keyless request, the vendor's own path for a model whose entry allows - * anonymous use. The proxy treats no key and the literal alike, strips it and - * forwards keylessly (`packages/console/app/src/lib/inference-proxy.ts`, both - * 1.19 and 2.x: `const anonymous = !key || key === "public"`). What the service - * behind the proxy answers is its own decision — the Zen free tier is refused - * there — but the sentinel must never become a credential: capturing it would - * forward `Bearer public`, turning an anonymous request into an authenticated - * one. See `docs/upstream-findings.md` §1.5. - */ -const PLACEHOLDER_API_KEYS: ReadonlySet = new Set([ - "null", - "none", - "public", - "undefined", - "unused", -]); - -/** Whether a value is one of the adapter's placeholder credentials. */ -export const isPlaceholderApiKey = (key: string): boolean => - PLACEHOLDER_API_KEYS.has(key.trim().toLowerCase()); - /** * Which account tier a request belongs to. * @@ -162,114 +134,3 @@ export const extractApiKeyFromHeaders = ( candidates.find((value) => !isPlaceholderApiKey(value)) ?? candidates[0] ); }; - -/** - * The capture store, read three ways. - * - * A lookup can be scoped by route (`capturedKeysByProvider`) or by tier - * (`capturedKeysByTier`); the tier map is what makes a lookup survive a renamed - * route. `latestCapturedKey` is the last resort, and is why the tier argument - * matters: without it, "most recently seen" can hand the Go endpoint a Zen key. - * - * The route-scoped map carries the tier ALONGSIDE the key rather than only the - * key. It used to hold `string`, which made the route lookup the one path that - * ignored a requested tier: a Zen key seen while the Go route was in play came - * back verbatim, so it outranked every correctly-filtered source — and it is the - * FIRST captured step of both `auto` and `request`. Holding the tier is what lets - * the route lookup apply the same rule the other two already did. - */ -const capturedKeysByProvider = new Map< - string, - { key: string; tier: KeyTier } ->(); -const capturedKeysByTier = new Map<"go" | "zen", string>(); -let latestCapturedKey: - | { key: string; provider?: string; tier: KeyTier } - | undefined; - -/** - * Whether a key classified as `tier` may answer a lookup for `wanted`. - * - * `unknown` is deliberately permissive, and identically so in all three lookup - * paths: an unclassifiable key is one we never identified, not one we proved to - * be the other tier. Filtering on "not the opposite" instead would make the - * guess fail closed and hide working keys. - */ -const tierSatisfies = (tier: KeyTier, wanted: "go" | "zen"): boolean => - tier === wanted || tier === "unknown"; - -/** - * Record an API key captured from live HTTP request headers or provider configurations. - * - * A blank or placeholder value is ignored rather than stored. - */ -export const recordCapturedApiKey = ( - rawKey: string, - provider?: string, - url?: string -): void => { - const key = rawKey.trim(); - if (key.length === 0 || isPlaceholderApiKey(key)) { - return; - } - // Deliberately NOT the meter's route-first precedence (`resolveGoApiKey`): a - // key seen on a live request is classified by the request that carried it, - // not by the route the user named. See `tierForRequest`. - const tier = tierForRequest(url, provider); - - if (typeof provider === "string" && provider.length > 0) { - capturedKeysByProvider.set(provider, { key, tier }); - } - if (tier !== "unknown") { - capturedKeysByTier.set(tier, key); - } - latestCapturedKey = { key, provider, tier }; -}; - -/** - * Retrieve a previously captured API key by provider or tier. - * - * @param provider - route id to try first, when the caller has one. - * @param tier - the tier the key must belong to. Pass it whenever the request - * already identifies one: omitting it lets the most recently seen key win, - * which may be for the other tier. A route-scoped hit is filtered by it too — - * naming a route is a preference, not a licence to ignore the tier. - */ -export const getCapturedApiKey = ( - provider?: string, - tier?: "go" | "zen" -): string | undefined => { - if (typeof provider === "string" && provider.length > 0) { - const direct = capturedKeysByProvider.get(provider); - if ( - direct !== undefined && - direct.key.length > 0 && - (tier === undefined || tierSatisfies(direct.tier, tier)) - ) { - return direct.key; - } - } - if (tier !== undefined) { - const byTier = capturedKeysByTier.get(tier); - if (byTier !== undefined && byTier.length > 0) { - return byTier; - } - } - if ( - latestCapturedKey !== undefined && - latestCapturedKey.key.length > 0 && - (tier === undefined || tierSatisfies(latestCapturedKey.tier, tier)) - ) { - return latestCapturedKey.key; - } - return undefined; -}; - -/** - * Clear all captured API keys (primarily used in test teardown). - */ -export const clearCapturedApiKeys = (): void => { - capturedKeysByProvider.clear(); - capturedKeysByTier.clear(); - latestCapturedKey = undefined; -}; diff --git a/src/lifecycle.ts b/src/lifecycle.ts index b07adb4..4059b5a 100644 --- a/src/lifecycle.ts +++ b/src/lifecycle.ts @@ -6,11 +6,11 @@ * * | installer | side effect | * | ------------------------ | --------------------------------------------- | - * | {@link installRouteClaim} | own the `opencode`/`opencode-go` routes (D13) | + * | {@link installRouteClaim} | own the `opencode`/`opencode-go` routes (D13), with the per-call plane headers (OC4, OC5) | * | {@link installDescribeGraft} | keep Settings showing the planes (D18) | * | {@link logRenameNotice} | one-time notice for legacy rows | * | {@link installRemoteServices} | the usage, purge and store-inspection services, through {@link installRemoteService} | - * | {@link installFetchPatch} | wrap `globalThis.fetch` (returns `undefined` if none) | + * | {@link installFetchPatch} | wrap `globalThis.fetch` through {@link installGlobalFetch}, with the credential resolver of the root (returns `undefined` if none) | * | {@link installStreamHook} | capture turn state on `llm/stream`; warn once if fetch was replaced (L1) | * | {@link installDiscovery} | complement Settings' model discovery with the catalog (D3) | * @@ -27,10 +27,12 @@ import { resolveConfig, } from "./config.ts"; import { type CordisContext, readEntryOptions } from "./cordis-context.ts"; +import { captureStoreFor, createCredentials } from "./credentials.ts"; import { recordDebug } from "./debug.ts"; import { patchFetch } from "./fetch-patch.ts"; import { resolveGoBaseURL } from "./go-discovery.ts"; import { installDescribeGraft } from "./host/describe-graft.ts"; +import { installGlobalFetch } from "./host/global-fetch.ts"; import { installRemoteService } from "./host/remote.ts"; import { installRouteClaim } from "./host/route-claim.ts"; import { LEGACY_NAME, LEGACY_PKG } from "./identity.ts"; @@ -46,18 +48,8 @@ import { createStreamHook } from "./stream-hook.ts"; import type { ActiveTurnState } from "./turn-store.ts"; import { usageRemote } from "./usage-contract.ts"; import { GoUsageService } from "./usage.ts"; -import { isFetchFunction, isFunctionLike, isRecord } from "./utils/guards.ts"; - -/** - * The fetch patches of this module's live activations. Two live activations - * nest (the later one wraps the earlier one's patch), so an activation's own - * patch still runs while `globalThis.fetch` is ANY of these; a function outside - * the set reads as a replacement (L1). One such function still calls through: - * a disposed patch that a later activation's restore put back (P6's stale - * restore, which takes three overlapping activations on one root, the middle - * one disposed first), so that case warns although the patch runs. - */ -const livePatches = new Set(); +import { isFunctionLike, isRecord } from "./utils/guards.ts"; +import { planeHeadersFor, projectHeaderOf } from "./utils/request-shape.ts"; /** Tell a row still configured under the pre-rename id/package to update. */ const logRenameNotice = (ctx: CordisContext): void => { @@ -107,7 +99,11 @@ const installRemoteServices = ( /** * Wrap `globalThis.fetch` so claimed OpenCode traffic carries session affinity - * and the gateway headers, restoring it on dispose. + * and the gateway headers, restoring it on dispose in any order + * ({@link installGlobalFetch}). + * + * The credential resolver reads and writes the capture store of the root, so + * the meter reads what the fill learned and two activations share it. * * @returns `undefined` when there is no fetch to wrap. The caller then stops: * the stream hook and discovery must not attach, or turns would run without @@ -121,64 +117,96 @@ const installFetchPatch = ( config: ResolvedPluginConfig, als: AsyncLocalStorage ): (() => boolean) | undefined => { - const originalFetch: unknown = globalThis.fetch; - if (!isFetchFunction(originalFetch)) { - ctx.logger?.warn?.( - "[dsh-opencode-patch] globalThis.fetch is unavailable; cannot inject x-opencode-session" - ); - return undefined; - } - - const patched = patchFetch(originalFetch, als, config, { - // The configured value wins, because it is the one thing here the user said - // out loud. There is no login to infer an org from: this build carries the - // API key path only. - resolveOrg: () => config.credentialOrg, - // One JSONL line per request the interceptor touched, when the deployment - // asked for debugging. It is the only way to see a request that was patched - // wrongly: the gateway's answer for a malformed session id reads exactly - // like its answer for a bad credential. - // **The FILE is written when the deployment named a file.** `debug` is the - // console switch ("Log injected streamed calls"), and `debugFile` is the - // path — so a deployment that set only the path asked for the file, and - // the two halves of one JSONL log must not have different gates. - // - // They did: the stream hook wrote its entries whenever a path was set, and - // this one required `debug` as well. So the README's own example — `debug: - // false` beside a `debugFile` path — produced a file holding the stream - // entries and none of the per-request ones, which is the half that says - // what the interceptor did. - ...(config.debugFile === undefined - ? {} - : { - debug: (entry: Record) => { - void recordDebug(ctx, config.debugFile ?? "", entry); - }, - }), + const credentials = createCredentials({ + keySource: config.keySource, + readOpencodeStore: config.readOpencodeStore, + store: captureStoreFor(ctx), }); - - ctx.effect?.(() => { - globalThis.fetch = patched; - livePatches.add(patched); - // Console as well as the logger: the logger's default exporter only buffers, - // so a boot line that says "the plugin loaded" has to reach stdout to be worth - // anything when someone is checking whether a build was picked up. - console.info( - `[dsh-opencode-patch] active for providers [${[...config.providers].join( - ", " - )}]` - ); - return () => { - livePatches.delete(patched); - if (globalThis.fetch === patched) { - globalThis.fetch = originalFetch; - } - }; - }, "dsh-opencode-patch.fetch-patch"); - - return () => livePatches.has(globalThis.fetch); + return installGlobalFetch( + ctx, + (original, live) => + patchFetch(original, als, config, { + credentials, + live, + // The configured value wins, because it is the one thing here the + // user said out loud. There is no login to infer an org from: this + // build carries the API key path only. + resolveOrg: () => config.credentialOrg, + // One JSONL line per request the interceptor touched, when the + // deployment asked for debugging. It is the only way to see a request + // that was patched wrongly: the gateway's answer for a malformed + // session id reads exactly like its answer for a bad credential. + // **The FILE is written when the deployment named a file.** `debug` + // is the console switch ("Log injected streamed calls"), and + // `debugFile` is the path — so a deployment that set only the path + // asked for the file, and the two halves of one JSONL log must not + // have different gates. + // + // They did: the stream hook wrote its entries whenever a path was + // set, and this one required `debug` as well. So the README's own + // example — `debug: false` beside a `debugFile` path — produced a file + // holding the stream entries and none of the per-request ones, which + // is the half that says what the interceptor did. + ...(config.debugFile === undefined + ? {} + : { + debug: (entry: Record) => { + void recordDebug(ctx, config.debugFile ?? "", entry); + }, + }), + }), + () => { + // Console as well as the logger: the logger's default exporter only + // buffers, so a boot line that says "the plugin loaded" has to reach + // stdout to be worth anything when someone is checking whether a build + // was picked up. + console.info( + `[dsh-opencode-patch] active for providers [${[ + ...config.providers, + ].join(", ")}]` + ); + } + ); }; +/** + * The plane headers of the current turn, written per call by the plane + * adapter's `prepareHeaders` (OC5): the values the stream hook derived for the + * turn, from the one table the fetch patch writes from. A request outside any + * turn the plugin decorated, or on another plugin's plane, gets none, and the + * turn is marked so the fetch patch leaves what was set here alone. + * + * @param als - the turn store the stream hook fills. + * @param config - the plugin's settings. + * @returns the writer `installRouteClaim` hands the adapter. + */ +export const callHeadersFor = + (als: AsyncLocalStorage, config: ResolvedPluginConfig) => + (headers: Headers): void => { + const state = als.getStore(); + if (state === undefined || state.foreign === true) { + return; + } + for (const [name, value] of planeHeadersFor({ + org: config.credentialOrg, + origin: config.injectOriginHeaders + ? { + client: config.originClient, + project: config.injectProject + ? projectHeaderOf(state.project) + : undefined, + request: state.requestValue, + } + : undefined, + parent: state.parentValue, + relay: !state.provider.startsWith("opencode"), + session: state.value, + })) { + headers.set(name, value); + } + state.perCall = true; + }; + /** * Capture turn state (session id, project, parent) on every streamed turn, * except a turn on a plane the route claim left to another plugin (D27), and @@ -228,7 +256,9 @@ const installDiscovery = ( * Order matters: * 1. the route claim, first, so its teardown is the first effect and runs * last, and its `internal/config` listener is in place before any pi-ai - * config run this activation can see; + * config run this activation can see; its adapter writes the plane headers + * per call from the turn store the stream hook fills (OC5), which is read + * per call, so the hook attaching later is no gap; * 2. the Settings graft, which reads the claim's committed entries; * 3. the rename notice and the remote services, before the fetch patch, so * a composition without `globalThis.fetch` still gets a working meter; @@ -254,7 +284,9 @@ export const apply = async ( const config = resolveConfig(rawConfig); const als = new AsyncLocalStorage(); - const claim = installRouteClaim(ctx, config); + const claim = installRouteClaim(ctx, config, { + callHeaders: callHeadersFor(als, config), + }); installDescribeGraft(ctx, claim); logRenameNotice(ctx); const services = installRemoteServices(ctx, config); diff --git a/src/models-catalog.ts b/src/models-catalog.ts index 4c96fb9..79b75f4 100644 --- a/src/models-catalog.ts +++ b/src/models-catalog.ts @@ -200,8 +200,9 @@ let refreshPromise: * The live maps, the retired-id sets and the refresh bookkeeping are module * state for the life of the process, which is right for the host and wrong for * a test: a case that refreshes from a fixture would otherwise decide what every - * later case in the file sees. The sibling resets are `clearCapturedApiKeys` and - * `clearSessionUsageStore`. + * later case in the file sees. The sibling reset is `clearSessionUsageStore`; + * captured keys are kept per root (`captureStoreFor`), so a fresh `Context` + * needs none. */ export const resetCatalogState = (): void => { activeGoCatalog = new Map(OPENCODE_GO_CATALOG.map((m) => [m.id, m])); diff --git a/src/stream-hook.ts b/src/stream-hook.ts index e425d31..6667b78 100644 --- a/src/stream-hook.ts +++ b/src/stream-hook.ts @@ -128,8 +128,7 @@ export const createStreamHook = ( * this activation's own or a later one wrapping it (L1): the predicate its * installer returns, read per decorated turn. A turn decorated after * something replaced it carries the session and gateway headers only if the - * replacement calls through, so the hook says so, once. A disposed patch - * that P6's stale restore put back reads as a replacement too. + * replacement calls through, so the hook says so, once. */ fetchInPlace: () => boolean = () => true ): StreamHandler => { diff --git a/src/turn-store.ts b/src/turn-store.ts index 911ec63..7d3c9d4 100644 --- a/src/turn-store.ts +++ b/src/turn-store.ts @@ -22,6 +22,13 @@ export interface ActiveTurnState { foreign?: true; model?: string; parentValue?: string; + /** + * Set by the plane adapter's `prepareHeaders` when it shaped this turn's + * request headers per call (OC5). The fetch patch then writes no plane + * header on a request of the turn that carries a well-formed session id. + * Per turn, and only ever set by a host that called the option. + */ + perCall?: true; project?: string; provider: string; /** diff --git a/src/utils/credential-policy.ts b/src/utils/credential-policy.ts new file mode 100644 index 0000000..c12d8c9 --- /dev/null +++ b/src/utils/credential-policy.ts @@ -0,0 +1,266 @@ +/** + * The credential rules every decider shares, as pure functions. + * + * Four places answer "which key?" — the fetch patch's fill for an empty or + * placeholder wire key, the Go meter, the Zen credit check and the plane + * adapter (D20) — and they used to carry their own copies of the same rules: + * which values are not credentials, the order a policy imposes, and when a key + * seen on the wire may be kept. This module is the one copy of each; the + * effects that read a header, the environment, a store or a service live in + * `credentials.ts` and ask here. + * + * Everything here is a function of its arguments: no context, no globals, no + * I/O. + * + * @module dsh-opencode-patch/utils/credential-policy + */ + +/** + * The policy that orders the credential sources, as `config-values.ts` + * declares it. Restated rather than imported, because a utility imports + * nothing outside this folder; a test pins the two lists equal. + */ +export type KeySourcePolicy = "auto" | "configured" | "request"; + +/** + * Bearer values the DSH adapter emits when it holds no real credential, plus the + * gateway's own keyless sentinel. + * + * These are the exact strings the Authorization fallback exists to repair, so + * they must never be *recorded* as a captured key: doing so overwrites a working + * key with a dummy one, and every later lookup then re-injects the dummy. + * + * `public` is not an adapter placeholder — it is the gateway's own literal for a + * keyless request, the vendor's own path for a model whose entry allows + * anonymous use. The proxy treats no key and the literal alike, strips it and + * forwards keylessly (`packages/console/app/src/lib/inference-proxy.ts`, both + * 1.19 and 2.x: `const anonymous = !key || key === "public"`). What the service + * behind the proxy answers is its own decision — the Zen free tier is refused + * there — but the sentinel must never become a credential: capturing it would + * forward `Bearer public`, turning an anonymous request into an authenticated + * one. See `docs/upstream-findings.md` §1.5. + */ +export const PLACEHOLDER_API_KEYS: ReadonlySet = new Set([ + "null", + "none", + "public", + "undefined", + "unused", +]); + +/** Whether a value is one of the adapter's placeholder credentials. */ +export const isPlaceholderApiKey = (key: string): boolean => + PLACEHOLDER_API_KEYS.has(key.trim().toLowerCase()); + +/** + * The one filter: a value worth sending as a credential, trimmed, or + * `undefined`. + * + * Every decider's answer leaves through here, so a blank (`" "` is what a + * YAML file produces when someone indents a secret they then blank out) or a + * placeholder never reaches the wire or the usage endpoint, whichever source + * produced it — a declared variable, the credentials service, a captured + * request or the installation's store. + * + * @param value - anything a source answered. + * @returns the trimmed key, or `undefined`. + */ +export const usableKey = (value: unknown): string | undefined => { + if (typeof value !== "string") { + return undefined; + } + const key = value.trim(); + return key.length === 0 || isPlaceholderApiKey(key) ? undefined : key; +}; + +/** + * Whether the key on the wire needs the fill: none, blank, or a placeholder. + * A real key the caller sent is never replaced. + * + * @param wireKey - the key the request's credential header carries. + */ +export const needsFill = (wireKey: string | undefined): boolean => + usableKey(wireKey) === undefined; + +/** One source the fill can consult. */ +export type FillSource = "captured" | "declared" | "request" | "store"; + +/** + * The fill's order per policy. + * + * The request's own key first (a real one in another credential header), then + * a key captured on a decorated turn, then the plane's declared variable, and + * the installation's store last. `configured` drops the captured step: the + * declared credential wins outright, and a captured key never fills. + */ +export const FILL_ORDER: Readonly< + Record +> = { + auto: ["request", "captured", "declared", "store"], + configured: ["request", "declared", "store"], + request: ["request", "captured", "declared", "store"], +}; + +/** + * One lookup step the meter can consult. + * + * `captured` is scoped to the route in hand; `capturedAny` accepts a key + * captured under any route. They are separate steps so `auto` can keep + * credentials ahead of the any-route fallback, exactly as it always has. + * + * `opencodeStore` is the installation's own store, and it is LAST in every + * policy rather than placed among them: everything the user declared — a + * literal, a captured request, a named reference — outranks anything inferred + * from another program's files. + */ +export type MeterSource = + | "captured" + | "capturedAny" + | "configured" + | "literal" + | "opencodeStore"; + +/** + * The lookup order each policy imposes on the meter — the only thing the user + * is choosing between. + * + * `auto` reproduces the original precedence exactly, so the default is not a + * behaviour change: composition first, then a captured key in the right tier, + * then credentials/env, then any captured key. `request` promotes both captured + * steps above the declared sources; `configured` does the reverse. + * + * The captured steps read only keys filed under the Go plane, in all three + * policies — but a key is filed by the plane its request went to, not by what + * it is entitled to. Nothing here can tell a Zen key from a Go key: a Go entry + * without `apiKeyEnv` sends pi's `OPENCODE_API_KEY` on its turns (D20), that + * bearer is filed as a Go key, and `auto` then sends it to the Go usage + * endpoint, which refuses it. Naming the reference on the Go entry is the fix. + * + * The store is appended to all three, and to none of them in the middle: the + * policy orders the sources the user declared, and the installation's store is + * never one of those. + */ +export const METER_ORDER: Readonly< + Record +> = { + auto: ["literal", "captured", "configured", "capturedAny", "opencodeStore"], + configured: [ + "literal", + "configured", + "captured", + "capturedAny", + "opencodeStore", + ], + request: [ + "captured", + "capturedAny", + "literal", + "configured", + "opencodeStore", + ], +}; + +/** + * The first usable answer of a policy's steps, in order, or `undefined`. + * + * Lazy: a later step's thunk is not called once an earlier one has answered, + * so a source the policy did not reach is never read. The filter is applied + * here, once, at the exit. + * + * @param order - the steps, in the policy's order. + * @param steps - one thunk per step. + * @returns the step that answered and its key, or `undefined`. + */ +export const firstUsable = ( + order: readonly Step[], + steps: Readonly unknown>> +): { readonly step: Step; readonly key: string } | undefined => { + for (const step of order) { + const key = usableKey(steps[step]()); + if (key !== undefined) { + return { key, step }; + } + } + return undefined; +}; + +/** + * {@link firstUsable} over steps that may answer a promise, awaited in order. + * + * Sequential on purpose: the order IS the policy, and a later step must not + * run (or be able to throw) once an earlier one has answered. + * + * @param order - the steps, in the policy's order. + * @param steps - one thunk per step. + * @returns the first usable key, or `undefined`. + */ +export const firstUsableAsync = async ( + order: readonly Step[], + steps: Readonly unknown>> +): Promise => { + for (const step of order) { + // oxlint-disable-next-line no-await-in-loop -- see above; order is the contract. + const key = usableKey(await steps[step]()); + if (key !== undefined) { + return key; + } + } + return undefined; +}; + +/** + * Whether a key seen on a request may be recorded (OC3). + * + * Only a request of a turn the stream hook decorated: the plugin then knows + * the route the key was sent for, and the key is one the turn's own adapter + * sent. A request outside any such turn — a Console call, another plugin's + * background request — carries a token the plugin did not send, and a turn + * on a plane another plugin owns (`foreign`) or a request carrying a plugin's + * marker is that plugin's (D27). The fetch patch returns before this for the + * last two; they are inputs here so the rule is one function. + */ +export const mayCapture = (request: { + readonly decorated: boolean; + readonly foreign: boolean; + readonly marked: boolean; +}): boolean => request.decorated && !request.foreign && !request.marked; + +/** + * How many well-formed 401s in a row drop a captured key (L8). + * + * Not one: the gateway answers a malformed session header with `401 Invalid + * API key`, and the same request has been seen refused and then accepted, so + * one refusal does not prove the key bad. A second refusal in a row, with a + * well-formed session and no success between, does. + */ +export const EVICT_AFTER = 2; + +/** + * One answer folded into a captured key's strike count. + * + * @param strikes - the count so far. + * @param outcome - `accepted` for a 2xx, `refused` for a well-formed 401. + * @returns the new count, and whether the key is to be dropped. + */ +export const strike = ( + strikes: number, + outcome: "accepted" | "refused" +): { readonly strikes: number; readonly evict: boolean } => { + if (outcome === "accepted") { + return { evict: false, strikes: 0 }; + } + const next = strikes + 1; + return { evict: next >= EVICT_AFTER, strikes: next }; +}; + +/** + * Whether an answer counts against the key it was sent with: a 401, on a + * request whose session id was well-formed (a malformed one draws the same + * 401 whatever the key), that carried a key at all. + */ +export const countsAsRefusal = (answer: { + readonly status: number; + readonly sessionWellFormed: boolean; + readonly keySent: boolean; +}): boolean => + answer.status === 401 && answer.sessionWellFormed && answer.keySent; diff --git a/src/utils/request-shape.ts b/src/utils/request-shape.ts index 2e5e819..c7dd859 100644 --- a/src/utils/request-shape.ts +++ b/src/utils/request-shape.ts @@ -16,6 +16,15 @@ */ import { isRecord } from "./guards.ts"; +import { PLUGIN_MARKER_HEADER } from "./plane-ownership.ts"; +import { + isOpenCodeMessageId, + PARENT_SESSION_ALT_HEADER, + PARENT_SESSION_HEADER, + SESSION_AFFINITY_HEADER, + SESSION_HEADER, + SESSION_ID_HEADER, +} from "./session-id.ts"; /** * The PATH of a gateway URL, whether it is absolute or a bare path. @@ -273,3 +282,119 @@ export const isZenProvider = (provider?: string): boolean => { } return !(lower === "opencode-go" || lower.startsWith("opencode-go-")); }; + +/** + * The value of a request's `x-opencode-plugin` marker, `""` included, or + * `undefined` when it carries none (OC2's rule 1, D27). + * + * A route another plugin wrote through pi-ai carries the marker, and its + * request goes out as it was sent. The pass-through triggers on PRESENCE, any + * value an empty one included, matching `pluginMarkerOf` on a provider row: + * a marker the patch cannot read is still another plugin's, which is the + * fail-safe direction. + * + * @param headers - the request's headers. + * @returns the marker's value, or `undefined`. + */ +export const pluginMarkerOn = (headers: Headers): string | undefined => + headers.get(PLUGIN_MARKER_HEADER) ?? undefined; + +/** + * The `x-opencode-project` value for a turn: its project name, or `global` + * for a turn that has none, as the client sends for a session outside any + * project. + * + * @param project - the folder name the stream hook derived, when it did. + */ +export const projectHeaderOf = (project: string | undefined): string => + project !== undefined && project.length > 0 ? project : "global"; + +/** What {@link planeHeadersFor} builds the plane headers from. */ +export interface PlaneHeaderInputs { + /** The session id, as the request will carry it. */ + readonly session: string; + /** The parent session's id, for a subagent or child session. */ + readonly parent?: string; + /** Whether the route is a relay a deployment claimed (not an `opencode*` route). */ + readonly relay: boolean; + /** The org the plane's credential belongs to, when it has one. */ + readonly org?: string; + /** The origin headers, when the deployment sends them. */ + readonly origin?: { + readonly client: string; + /** The turn's message id; dropped unless it is in the client's `msg_` shape. */ + readonly request?: string; + /** The project name, when the deployment sends one. */ + readonly project?: string; + }; +} + +/** + * The plane headers one request carries, in the order they are written: the + * one table both the fetch patch and the plane adapter's per-call seam (OC5) + * write from. + * + * 1. **Session headers, as the version this plugin emulates sends them.** Read + * from the 1.x line's last release, v1.19.5, in + * `packages/opencode/src/session/llm/request.ts`: `x-opencode-session-id` + * and `x-opencode-session` both carry `sessionID`, and the affinity pair + * belongs to relays. 2.x splits the first of those into an affinity id; the + * plugin emulates 1.19.5, so it follows 1.19.5. Which ENDPOINT the request + * goes to is the deployment's, not this table's: measured, either key + * serves a paid model on either endpoint — they are two paths into one + * gateway. + * 2. **The affinity pair belongs to the OTHER branch in 1.19.5:** for a + * provider that does not start with `opencode` — a relay a deployment + * claimed by URL — the client sends `x-session-affinity` and + * `X-Session-Id`; for an OpenCode plane it sends `x-opencode-session` + * instead and nothing else. + * 3. The parent pair, for subagents and child sessions. + * 4. **The org, when this plane's credential belongs to one.** A session token + * needs the org it belongs to — measured on a paid model: `200` with it, + * `403` without — and the free tier is refused with or without one. + * 5. **The origin headers**, when enabled: the client; the message id, read + * from v1.19.5's `request.ts` (`"x-opencode-request": input.user.id`, in + * the same branch as the client and project headers), which the console + * reads for per-request metrics and rewrites to `x-opencode-request-id` + * before the request reaches the inference service (`inference-proxy.ts`); + * and the project. L4 is still open: P-R2's rows measured nothing about + * the message id, so it is sent as it always was, and this line is where a + * decision to drop or gate it lands. + * + * @param inputs - the session, parent, relay flag, org and origin. + * @returns the headers, as `[name, value]` pairs in write order. + */ +export const planeHeadersFor = ( + inputs: PlaneHeaderInputs +): readonly (readonly [string, string])[] => { + const { origin, org, parent, relay, session } = inputs; + const headers: (readonly [string, string])[] = [ + ["x-opencode-session-id", session], + [SESSION_HEADER, session], + ]; + if (relay) { + headers.push( + [SESSION_AFFINITY_HEADER, session], + [SESSION_ID_HEADER, session] + ); + } + if (parent !== undefined) { + headers.push( + [PARENT_SESSION_HEADER, parent], + [PARENT_SESSION_ALT_HEADER, parent] + ); + } + if (org !== undefined && org.length > 0) { + headers.push(["x-opencode-org-id", org]); + } + if (origin !== undefined) { + headers.push(["x-opencode-client", origin.client]); + if (isOpenCodeMessageId(origin.request)) { + headers.push(["x-opencode-request", origin.request]); + } + if (origin.project !== undefined) { + headers.push(["x-opencode-project", origin.project]); + } + } + return headers; +}; diff --git a/test/architecture.test.ts b/test/architecture.test.ts index 1bd61c0..7d6d08d 100644 --- a/test/architecture.test.ts +++ b/test/architecture.test.ts @@ -593,6 +593,49 @@ describe("architecture · the host bundle mutates no registry it does not own", }); }); +describe("architecture · the request path reads no environment of its own (P6)", () => { + /** + * The fetch patch, the lifecycle and the plane provider take every value + * they need as a parameter or a service: the fill's one read of the process + * environment lives in `credentials.ts`, and the plane adapter's in the + * host's launch environment (D20). Comments are stripped first, as in the + * utilities' rule. Textual, like the repository's other environment rules: + * a read through an alias (`process["env"]`, `const { env } = process`) + * escapes it. + */ + const FILES = ["fetch-patch.ts", "lifecycle.ts", "host/plane-provider.ts"]; + const readsEnv = (source: string): boolean => + /process\.env/u.test(stripComments(source)); + + it("flags a planted read, so a pass means something", () => { + expect(readsEnv("const k = process.env.X;")).toBe(true); + expect(readsEnv("// process.env.X\nconst k = 1;")).toBe(false); + }); + + it.each(FILES)("%s never reads process.env", (file) => { + expect(readsEnv(readFileSync(join(SRC_DIR, file), "utf8"))).toBe(false); + }); + + /** Whether a source writes a capture store: a `.record(` call. */ + const writesStore = (source: string): boolean => + /\.record\(/u.test(stripComments(source)); + + it("flags a planted store write, so a pass means something", () => { + expect( + writesStore("captureStoreFor(ctx).record(key, provider, url);") + ).toBe(true); + expect(writesStore("store.record(k);")).toBe(true); + expect(writesStore("// store.record(k)\nconst recorded = 1;")).toBe(false); + }); + + it("a capture store is written from src/credentials.ts only", () => { + const writers = filesUnder(SRC_DIR).filter((file) => + writesStore(readFileSync(join(SRC_DIR, file), "utf8")) + ); + expect(writers).toEqual(["credentials.ts"]); + }); +}); + describe("architecture · host methods are wrapped only through patchMethod", () => { /** The host half's composition root: everything `apply()` can run. */ const ENTRY = "lifecycle.ts"; @@ -625,10 +668,13 @@ describe("architecture · host methods are wrapped only through patchMethod", () /** * Named exemptions, each `: `. The global `fetch` - * patch stacks the same way but is a global, not a host service method, and - * P6 owns it (docs/improvement-plan.md). + * patch is a global, not a host service method: P6 moved it into its own + * installer, which reads the original inside the effect and unwinds through + * disposed links in any order (`host/global-fetch.ts`). The exemption stays + * while the patch keeps relays, listing enrichment, the credential fill, the + * free-tier body fallback and the User-Agent (docs/improvement-plan.md). */ - const EXEMPT = new Set(["lifecycle.ts: globalThis.fetch ="]); + const EXEMPT = new Set(["host/global-fetch.ts: globalThis.fetch ="]); /** Every host write in `source`, as `: `. */ const hostWritesIn = (file: string, source: string): string[] => diff --git a/test/credential-parity.test.ts b/test/credential-parity.test.ts new file mode 100644 index 0000000..bd95154 --- /dev/null +++ b/test/credential-parity.test.ts @@ -0,0 +1,422 @@ +/** + * Every credential decider in `src/`, side by side: where they agree, and + * where the design says they differ. + * + * Four deciders answer "which key?" today: + * + * | decider | where | reads | + * | :-- | :-- | :-- | + * | the fill | the fetch patch, for an empty or placeholder wire key | the request, a captured key, the process environment, the installation's store | + * | the meter | `resolveGoApiKey` | a discovered literal, a captured key, the credentials service then the environment, the store | + * | Zen credit | `resolveZenCreditInfo` | a captured Zen key, then `OPENCODE_API_KEY` (on the base, without the placeholder filter: row (5) does not cover it, and `go-discovery-keys.test.ts` holds that case) | + * | the adapter | `PlaneAdapter` (D20) | pi-ai's own rule: the named reference through the credentials service, else pi's lookup, the store last | + * + * This file is a PIN: it was written and run against the tree before the + * resolver was consolidated (P6), and no expectation in it changes with that + * change. Review edited it twice without touching an expectation (the policy + * type derived from `KEY_SOURCE_POLICIES`, and `disposeMounted()` in the + * `afterEach`), and the landed form was run on the base again. It reaches the deciders only through doors that survive the move — the plugin + * mounted on a real `Context`, a decorated turn through cordis's own + * `llm/stream` waterfall, the patched `globalThis.fetch`, the meter's and the + * credit's exported resolvers, and tier A for the adapter — and a captured key + * is only ever seeded the way the plugin learns one: a decorated turn that + * sends it. + * + * @module test/credential-parity.test + */ +import { Context } from "@deepseek-ai/cordis"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { disposeMounted, mountPlugin } from "./support/composition.ts"; +import { offline, turn } from "./support/host-planes.ts"; +import { + fakeCredentials, + mountTierA, + type TierA, + waitForPlaneOwner, +} from "./support/host.ts"; +import { + createOpencodeStore, + type FixtureStore, +} from "./support/opencode-store-fixture.ts"; +import { + KEY_SOURCE_POLICIES, + resolveGoApiKey, + resolveZenCreditInfo, +} from "./support/src.ts"; +import { collectUnknown, urlOf } from "./test-helpers.ts"; + +/** + * The policy, derived from the list the door has always exported, so the pin + * type-checks against the base on its own. + */ +type KeySourcePolicy = (typeof KEY_SOURCE_POLICIES)[number]; + +const GO_URL = "https://opencode.ai/zen/go/v1/chat/completions"; +const ZEN_URL = "https://opencode.ai/zen/v1/chat/completions"; + +/** What the wrapped fetch saw on each request, credential values included. */ +let sent: { url: string; authorization: string | null }[] = []; +let stores: FixtureStore[] = []; +let tierA: TierA | undefined; + +beforeEach(() => { + // The process environment the fill and the meter read: blank, so a key a + // developer exported cannot answer a case. + vi.stubEnv("OPENCODE_API_KEY", ""); + vi.stubEnv("OPENCODE_GO_API_KEY", ""); + sent = []; + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + sent.push({ + authorization: new Headers(init?.headers).get("authorization"), + url: urlOf(input), + }); + return Response.json({}); + }) + ); +}); + +afterEach(async () => { + try { + await disposeMounted(); + await tierA?.dispose(); + } finally { + tierA = undefined; + for (const store of stores.splice(0)) { + store.cleanup(); + } + stores = []; + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + } +}); + +/** A credentials service answering `refs` by name, or throwing for every ref. */ +const credentialsService = ( + refs: Readonly> +): { resolve: (ref: string) => Promise } => ({ + resolve: async (ref) => { + const value = refs[ref]; + return value === undefined ? undefined : { source: "fake", value }; + }, +}); + +/** The installation's own store, holding a key per plane, and the reader pointed at it. */ +const installationStore = (go: string, zen: string): void => { + const store = createOpencodeStore([ + { integrationId: "opencode-go", value: go }, + { integrationId: "opencode", value: zen }, + ]); + stores.push(store); + vi.stubEnv("XDG_DATA_HOME", store.root); +}; + +/** The plugin, mounted with `policy`, on a root that may hold a credentials service. */ +const compose = async ( + policy: KeySourcePolicy, + options: { + readonly refs?: Readonly>; + readonly readOpencodeStore?: boolean; + } = {} +): Promise => { + const ctx = new Context(); + if (options.refs !== undefined) { + ctx.provide("credentials", credentialsService(options.refs) as never); + } + await mountPlugin({ + config: { + keySource: policy, + readOpencodeStore: options.readOpencodeStore ?? false, + }, + ctx, + }); + return ctx; +}; + +/** + * One decorated turn that sends `bearer` to `url`, the way an adapter sends + * its request: through the patched `globalThis.fetch`, inside the stream + * hook's turn. + * + * @returns the `Authorization` the wrapped fetch saw. + */ +const decoratedTurn = async ( + ctx: Context, + provider: string, + url: string, + bearer: string +): Promise => { + const before = sent.length; + const downstream = async function* downstream() { + await globalThis.fetch(url, { + body: JSON.stringify({ model: "parity-model" }), + headers: { authorization: `Bearer ${bearer}` }, + method: "POST", + }); + yield { type: "finish" }; + }; + await collectUnknown( + ( + ctx as unknown as { + waterfall: (event: string, ...args: unknown[]) => unknown; + } + ).waterfall( + "llm/stream", + { provider, sessionId: "parity" }, + downstream + ) as AsyncIterable + ); + return sent.slice(before).at(-1)?.authorization ?? null; +}; + +/** The fill's answer for a placeholder Go request inside a decorated turn. */ +const goFill = (ctx: Context): Promise => + decoratedTurn(ctx, "opencode-go", GO_URL, "unused"); + +describe("credential parity: one table, four deciders (fill, meter, Zen credit, adapter)", () => { + describe.each(KEY_SOURCE_POLICIES)("policy %s", (policy) => { + it("(1) only OPENCODE_GO_API_KEY exported: the fill and the meter both answer it", async () => { + vi.stubEnv("OPENCODE_GO_API_KEY", "env-go"); + const ctx = await compose(policy); + expect(await goFill(ctx)).toBe("Bearer env-go"); + expect(await resolveGoApiKey(ctx, "opencode-go", policy)).toBe("env-go"); + }); + + it("(2) only the credentials service holds the ref: the fill leaves the placeholder and warns once, the meter resolves it", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => { + // captured below + }); + const ctx = await compose(policy, { + refs: { OPENCODE_GO_API_KEY: "svc-go" }, + }); + expect(await goFill(ctx)).toBe("Bearer unused"); + expect(await goFill(ctx)).toBe("Bearer unused"); + const reports = warn.mock.calls + .map(([message]) => String(message)) + .filter((message) => message.includes("no credential resolved")); + expect(reports).toHaveLength(1); + for (const source of [ + "a key on the request: none", + `a key captured from a live request (policy ${policy}): none`, + "OPENCODE_GO_API_KEY: unset", + "the installation's own store: not enabled", + ]) { + expect(reports[0]).toContain(source); + } + expect(await resolveGoApiKey(ctx, "opencode-go", policy)).toBe("svc-go"); + }); + + it("(3) a key seen on a decorated Go turn: the fill takes it unless the policy is configured; the meter follows its order", async () => { + // Without a declared key: `configured` still reaches the captured step + // in the meter, never in the fill. + const bare = await compose(policy); + expect(await decoratedTurn(bare, "opencode-go", GO_URL, "seen-go")).toBe( + "Bearer seen-go" + ); + expect(await goFill(bare)).toBe( + policy === "configured" ? "Bearer unused" : "Bearer seen-go" + ); + expect(await resolveGoApiKey(bare, "opencode-go", policy)).toBe( + "seen-go" + ); + + // With a declared key beside it: `request` and `auto` put the captured + // key first in both, `configured` the declared one. + vi.stubEnv("OPENCODE_GO_API_KEY", "env-go"); + const declared = await compose(policy); + await decoratedTurn(declared, "opencode-go", GO_URL, "seen-go"); + const expected = policy === "configured" ? "env-go" : "seen-go"; + expect(await goFill(declared)).toBe(`Bearer ${expected}`); + expect(await resolveGoApiKey(declared, "opencode-go", policy)).toBe( + expected + ); + }); + + it("(4) a key seen on a decorated Zen turn never answers a Go lookup, and is Zen credit", async () => { + const ctx = await compose(policy); + await decoratedTurn(ctx, "opencode", ZEN_URL, "seen-zen"); + expect(await goFill(ctx)).toBe("Bearer unused"); + expect(await resolveGoApiKey(ctx, "opencode-go", policy)).toBeUndefined(); + expect(await resolveGoApiKey(ctx, undefined, policy)).toBeUndefined(); + const credit = await resolveZenCreditInfo(ctx); + expect(credit.isConfigured).toBe(true); + }); + + it("(5) placeholders in every declared source: no decider answers", async () => { + vi.stubEnv("OPENCODE_API_KEY", "unused"); + vi.stubEnv("OPENCODE_GO_API_KEY", "public"); + const ctx = await compose(policy, { + refs: { OPENCODE_API_KEY: "none", OPENCODE_GO_API_KEY: "unused" }, + }); + // A placeholder on a decorated turn is never recorded either. + await decoratedTurn(ctx, "opencode-go", GO_URL, "public"); + expect(await goFill(ctx)).toBe("Bearer unused"); + expect(await decoratedTurn(ctx, "opencode", ZEN_URL, "unused")).toBe( + "Bearer unused" + ); + expect(await resolveGoApiKey(ctx, "opencode-go", policy)).toBeUndefined(); + }); + + it("(6) the installation's store, opted in: last in the fill and in the meter", async () => { + installationStore("store-go", "store-zen"); + const alone = await compose(policy, { readOpencodeStore: true }); + expect(await goFill(alone)).toBe("Bearer store-go"); + expect(await decoratedTurn(alone, "opencode", ZEN_URL, "unused")).toBe( + "Bearer store-zen" + ); + expect(await resolveGoApiKey(alone, "opencode-go", policy, true)).toBe( + "store-go" + ); + + vi.stubEnv("OPENCODE_GO_API_KEY", "env-go"); + const declared = await compose(policy, { readOpencodeStore: true }); + expect(await goFill(declared)).toBe("Bearer env-go"); + expect(await resolveGoApiKey(declared, "opencode-go", policy, true)).toBe( + "env-go" + ); + }); + + it("(7) a real key on the wire is never replaced by any source", async () => { + installationStore("store-go", "store-zen"); + vi.stubEnv("OPENCODE_GO_API_KEY", "env-go"); + vi.stubEnv("OPENCODE_API_KEY", "env-zen"); + const ctx = await compose(policy, { + readOpencodeStore: true, + refs: { OPENCODE_GO_API_KEY: "svc-go" }, + }); + await decoratedTurn(ctx, "opencode-go", GO_URL, "seen-go"); + expect(await decoratedTurn(ctx, "opencode-go", GO_URL, "wire-go")).toBe( + "Bearer wire-go" + ); + expect(await decoratedTurn(ctx, "opencode", ZEN_URL, "wire-zen")).toBe( + "Bearer wire-zen" + ); + }); + }); +}); + +describe( + "credential parity: the adapter path, its own row (tier A, D20)", + { timeout: 30_000 }, + () => { + /** Tier A with the plugin and one Zen plane entry; `entry` extends it. */ + const mount = async ( + credentials: ReturnType, + entry: Record = {}, + plugin: Record = {} + ): Promise => { + offline(); + tierA = await mountTierA({ + credentials, + plugin, + providers: { + opencode: { models: [{ id: "deepseek-v4-pro" }], ...entry }, + }, + }); + await waitForPlaneOwner(tierA.llm, ["opencode"]); + return tierA; + }; + + /** One turn on the plane, through the host's own stream path. */ + const planeTurn = (tier: TierA) => + turn(tier.llm, "opencode", "deepseek-v4-pro"); + + it("a key rotated in the credentials service takes effect on the next call, with no remount", async () => { + const credentials = fakeCredentials({ refs: { OPENCODE_API_KEY: "k1" } }); + const tier = await mount(credentials, { + apiKeyEnv: "OPENCODE_API_KEY", + }); + const first = await planeTurn(tier); + await ( + credentials.service.set as unknown as ( + ref: string, + value: string + ) => Promise + )("OPENCODE_API_KEY", "k2-longer"); + const second = await planeTurn(tier); + expect(first.requests[0]?.headers.authorization).toBe("Bearer k1".length); + expect(second.requests[0]?.headers.authorization).toBe( + "Bearer k2-longer".length + ); + }); + + it("a credentials-service failure propagates: no request, an error that is not a missing key", async () => { + const credentials = fakeCredentials(); + (credentials.service as Record).resolve = () => + Promise.reject(new Error("vault down")); + const tier = await mount(credentials, { + apiKeyEnv: "OPENCODE_API_KEY", + }); + const { drained, requests } = await planeTurn(tier); + expect(requests).toEqual([]); + expect(drained.finish?.kind).toBe("error"); + expect(drained.finish?.code).not.toBe("MISSING_CREDENTIAL"); + expect(drained.failureMessage ?? drained.error).toMatch(/vault down/u); + + // The contrast the table documents: the meter, over the same failing + // service, does not throw, and answers the exported variable. + vi.stubEnv("OPENCODE_GO_API_KEY", "env-go"); + expect(await resolveGoApiKey(tier.ctx, "opencode-go")).toBe("env-go"); + }); + + it("a key seen on a turn never answers the adapter for a ref that resolves nothing", async () => { + const tier = await mount(fakeCredentials(), { + apiKeyEnv: "OPENCODE_API_KEY", + }); + // A decorated turn on the plane route that sends its own key: the fill + // and the meter may learn it, the adapter never reads it. + const downstream = async function* downstream() { + await globalThis.fetch(ZEN_URL, { + body: JSON.stringify({ model: "deepseek-v4-pro" }), + headers: { authorization: "Bearer seen-zen" }, + method: "POST", + }); + yield { type: "finish" }; + }; + await collectUnknown( + ( + tier.ctx as unknown as { + waterfall: (event: string, ...args: unknown[]) => unknown; + } + ).waterfall( + "llm/stream", + { provider: "opencode", sessionId: "parity" }, + downstream + ) as AsyncIterable + ); + const credit = await resolveZenCreditInfo(tier.ctx); + expect(credit.isConfigured).toBe(true); + const { drained, requests } = await planeTurn(tier); + expect(drained.finish?.code).toBe("MISSING_CREDENTIAL"); + expect(requests).toEqual([]); + }); + + it("the installation's store answers the adapter only when no ref is named and pi's own lookup finds nothing", async () => { + installationStore("store-go", "store-zen-longer"); + const bare = await mount( + fakeCredentials(), + {}, + { readOpencodeStore: true } + ); + const fromStore = await planeTurn(bare); + expect(fromStore.requests[0]?.headers.authorization).toBe( + "Bearer store-zen-longer".length + ); + await bare.dispose(); + tierA = undefined; + + const piLookup = await mount( + fakeCredentials({ refs: { OPENCODE_API_KEY: "svc-zen" } }), + {}, + { readOpencodeStore: true } + ); + const fromPi = await planeTurn(piLookup); + expect(fromPi.requests[0]?.headers.authorization).toBe( + "Bearer svc-zen".length + ); + }); + } +); diff --git a/test/credential-policy.test.ts b/test/credential-policy.test.ts new file mode 100644 index 0000000..9eb6449 --- /dev/null +++ b/test/credential-policy.test.ts @@ -0,0 +1,208 @@ +/** + * `utils/credential-policy.ts` — the credential rules every decider shares. + * + * Pure, so every rule is asserted by calling it: the one placeholder filter, + * the fill's and the meter's orders, the lazy step walk, the capture gate and + * L8's strike count. The performing cases — the fill and the meter applying + * the filter at their exits — are in `fetch-patch.test.ts` and + * `go-discovery-store.test.ts`; the parity across deciders is + * `credential-parity.test.ts`. + * + * @module test/credential-policy.test + */ +import { describe, expect, it, vi } from "vitest"; + +import { + countsAsRefusal, + EVICT_AFTER, + FILL_ORDER, + firstUsable, + firstUsableAsync, + isPlaceholderApiKey, + KEY_SOURCE_POLICIES, + mayCapture, + METER_ORDER, + needsFill, + PLACEHOLDER_API_KEYS, + strike, + usableKey, +} from "./support/src.ts"; + +describe("credential policy · the one placeholder filter", () => { + it.each([ + ["undefined", undefined], + ["an empty string", ""], + ["whitespace", " "], + ["the adapter's placeholder", "unused"], + ["the gateway's keyless sentinel, padded and cased", " Public "], + ["null", "null"], + ["none", "none"], + ["the string undefined", "undefined"], + ["a non-string", 42], + ["an object", { key: "k" }], + ])("%s is no credential", (_label, value) => { + expect(usableKey(value)).toBeUndefined(); + }); + + it("answers a real key, trimmed", () => { + expect(usableKey(" k ")).toBe("k"); + expect(usableKey("oc_sk_real")).toBe("oc_sk_real"); + }); + + it("names the five placeholders, matched case-insensitively and trimmed", () => { + expect([...PLACEHOLDER_API_KEYS].toSorted()).toEqual([ + "none", + "null", + "public", + "undefined", + "unused", + ]); + expect(isPlaceholderApiKey(" UNUSED ")).toBe(true); + expect(isPlaceholderApiKey("sk-real")).toBe(false); + }); + + it("asks for the fill only when the wire key is no credential", () => { + expect(needsFill(undefined)).toBe(true); + expect(needsFill("")).toBe(true); + expect(needsFill("unused")).toBe(true); + expect(needsFill(" ")).toBe(true); + expect(needsFill("sk-real")).toBe(false); + }); +}); + +describe("credential policy · the orders", () => { + it("restates the three policies config-values declares, in any order", () => { + expect(Object.keys(FILL_ORDER).toSorted()).toEqual( + [...KEY_SOURCE_POLICIES].toSorted() + ); + expect(Object.keys(METER_ORDER).toSorted()).toEqual( + [...KEY_SOURCE_POLICIES].toSorted() + ); + }); + + it("the fill: the request, a captured key unless configured, the declared variable, the store last", () => { + expect(FILL_ORDER).toEqual({ + auto: ["request", "captured", "declared", "store"], + configured: ["request", "declared", "store"], + request: ["request", "captured", "declared", "store"], + }); + }); + + it("the meter: the original precedence under auto, the store last in all three", () => { + expect(METER_ORDER).toEqual({ + auto: [ + "literal", + "captured", + "configured", + "capturedAny", + "opencodeStore", + ], + configured: [ + "literal", + "configured", + "captured", + "capturedAny", + "opencodeStore", + ], + request: [ + "captured", + "capturedAny", + "literal", + "configured", + "opencodeStore", + ], + }); + }); +}); + +describe("credential policy · the step walk", () => { + it("answers the first usable step, filtered once at the exit, and reads no later one", () => { + const later = vi.fn(() => "later"); + expect( + firstUsable(["a", "b", "c"] as const, { + a: () => "unused", + b: () => " key ", + c: later, + }) + ).toEqual({ key: "key", step: "b" }); + expect(later).not.toHaveBeenCalled(); + }); + + it("answers undefined when no step does", () => { + expect( + firstUsable(["a", "b"] as const, { a: () => null, b: () => " " }) + ).toBeUndefined(); + }); + + it("awaits each step in order, and runs no later one once an earlier answered", async () => { + const order: string[] = []; + const later = vi.fn(async () => "later"); + await expect( + firstUsableAsync(["a", "b", "c"] as const, { + a: async () => { + order.push("a"); + return "public"; + }, + b: () => { + order.push("b"); + return "k"; + }, + c: later, + }) + ).resolves.toBe("k"); + expect(order).toEqual(["a", "b"]); + expect(later).not.toHaveBeenCalled(); + await expect( + firstUsableAsync(["a"] as const, { a: async () => null }) + ).resolves.toBeUndefined(); + }); +}); + +describe("credential policy · whose key may be kept (OC3)", () => { + it.each([ + [true, false, false, true], + [true, false, true, false], + [true, true, false, false], + [true, true, true, false], + [false, false, false, false], + [false, false, true, false], + [false, true, false, false], + [false, true, true, false], + ])( + "decorated %s, foreign %s, marked %s: %s", + (decorated, foreign, marked, expected) => { + expect(mayCapture({ decorated, foreign, marked })).toBe(expected); + } + ); +}); + +describe("credential policy · how long a key is kept (L8)", () => { + it("drops a key at the second refusal in a row, and not before", () => { + expect(EVICT_AFTER).toBe(2); + expect(strike(0, "refused")).toEqual({ evict: false, strikes: 1 }); + expect(strike(1, "refused")).toEqual({ evict: true, strikes: 2 }); + }); + + it("an acceptance clears the count", () => { + expect(strike(1, "accepted")).toEqual({ evict: false, strikes: 0 }); + expect(strike(0, "accepted")).toEqual({ evict: false, strikes: 0 }); + }); + + it("counts only a 401 on a well-formed session that carried a key", () => { + expect( + countsAsRefusal({ keySent: true, sessionWellFormed: true, status: 401 }) + ).toBe(true); + // A malformed session draws the same 401 whatever the key. + expect( + countsAsRefusal({ keySent: true, sessionWellFormed: false, status: 401 }) + ).toBe(false); + expect( + countsAsRefusal({ keySent: false, sessionWellFormed: true, status: 401 }) + ).toBe(false); + for (const status of [200, 403, 429, 500]) { + expect( + countsAsRefusal({ keySent: true, sessionWellFormed: true, status }) + ).toBe(false); + } + }); +}); diff --git a/test/credentials.test.ts b/test/credentials.test.ts new file mode 100644 index 0000000..f332449 --- /dev/null +++ b/test/credentials.test.ts @@ -0,0 +1,541 @@ +/** + * `credentials.ts` — the capture store per root, and the fetch patch's one + * resolver over it. + * + * The store is driven directly (filing, the three lookups, the route-only + * lookup, L8's strikes, the drop and its lifting, one store per root), and the + * resolver with an environment of the case's own (the capture gate, the fill + * order per policy, the report of what was consulted, the settle). + * + * @module test/credentials.test + */ +import { Context } from "@deepseek-ai/cordis"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { createOpencodeStore } from "./support/opencode-store-fixture.ts"; +import { + captureStoreFor, + createCaptureStore, + createCredentials, + type KeySourcePolicy, + resolveOpencodeStoreKey, +} from "./support/src.ts"; + +const GO = "https://opencode.ai/zen/go/v1/chat/completions"; +const ZEN = "https://opencode.ai/zen/v1/chat/completions"; +const RELAY = "https://relay.example/v1/chat/completions"; + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe("credentials · the capture store", () => { + it("files a key by route and plane, and answers the three lookups", () => { + const store = createCaptureStore(); + store.record("go-k", "opencode-go", GO); + store.record("zen-k", "opencode", ZEN); + expect(store.get("opencode-go", "go")).toBe("go-k"); + expect(store.get(undefined, "go")).toBe("go-k"); + expect(store.get(undefined, "zen")).toBe("zen-k"); + // The latest key, with no tier asked. + expect(store.get()).toBe("zen-k"); + // A route-scoped hit is filtered by the tier asked. + expect(store.get("opencode", "go")).toBe("go-k"); + expect(store.get("nobody")).toBe("zen-k"); + }); + + it("ignores a blank or placeholder key, and trims a real one", () => { + const store = createCaptureStore(); + store.record(" ", "opencode-go", GO); + store.record("unused", "opencode-go", GO); + expect(store.get(undefined, "go")).toBeUndefined(); + store.record(" go-k ", "", GO); + expect(store.get(undefined, "go")).toBe("go-k"); + // An empty route files nothing by route. + expect(store.forRoute("")).toBeUndefined(); + }); + + it("answers a route's own key on neither plane, and only that (OC3)", () => { + const store = createCaptureStore(); + store.record("go-k", "my-relay", GO); + expect(store.forRoute("my-relay")).toBeUndefined(); + store.record("relay-k", "my-relay", RELAY); + expect(store.forRoute("my-relay")).toBe("relay-k"); + expect(store.forRoute("other")).toBeUndefined(); + // The plane's own key still answers its plane, with the relay's beside it. + expect(store.get(undefined, "go")).toBe("go-k"); + }); + + it("OC3 — a key sent to a URL on neither plane answers no plane lookup, by route, by tier or as the latest", () => { + const store = createCaptureStore(); + store.record("relay-k", "my-relay", RELAY); + expect(store.get(undefined, "go")).toBeUndefined(); + expect(store.get(undefined, "zen")).toBeUndefined(); + expect(store.get("my-relay", "go")).toBeUndefined(); + // The known answers: its route's own lookup, and an untiered one. + expect(store.forRoute("my-relay")).toBe("relay-k"); + expect(store.get("my-relay")).toBe("relay-k"); + expect(store.get()).toBe("relay-k"); + }); + + it("a route named after a plane files its key under that plane even on a URL on neither plane (the name fallback, deliberate)", () => { + // A plane route may carry its own baseURL; one that points off the + // gateway is read as a mirror of the plane it is named after, so its key + // is that plane's key in both directions. The OC3 relay rule is for a + // route NOT named after a plane. + const store = createCaptureStore(); + store.record("mirror-go", "opencode-go", RELAY); + expect(store.get(undefined, "go")).toBe("mirror-go"); + expect(store.get(undefined, "zen")).toBeUndefined(); + expect(store.forRoute("opencode-go")).toBeUndefined(); + store.record("mirror-zen", "opencode", RELAY); + expect(store.get(undefined, "zen")).toBe("mirror-zen"); + }); + + it("OC3 / L8 — dropping a plane's key never lets a relay's key answer that plane", () => { + const store = createCaptureStore(); + store.record("go-k", "opencode-go", GO); + store.record("relay-k", "my-relay", RELAY); + expect(store.get(undefined, "go")).toBe("go-k"); + store.settle("go-k", "opencode-go", GO, "refused", false); + store.settle("go-k", "opencode-go", GO, "refused", false); + expect(store.get(undefined, "go")).toBeUndefined(); + expect(store.get("opencode-go", "go")).toBeUndefined(); + expect(store.forRoute("my-relay")).toBe("relay-k"); + }); + + it("drops a key after a second refusal in a row on its plane, and lifts the drop on an acceptance", () => { + const store = createCaptureStore(); + store.record("k", "opencode-go", GO); + store.record("z", "opencode", ZEN); + expect(store.settle("k", "opencode-go", GO, "refused", false)).toBe(false); + expect(store.get(undefined, "go")).toBe("k"); + // An acceptance between clears the strike. + store.settle("k", "opencode-go", GO, "accepted", false); + store.settle("k", "opencode-go", GO, "refused", false); + expect(store.get(undefined, "go")).toBe("k"); + store.settle("k", "opencode-go", GO, "refused", false); + expect(store.get(undefined, "go")).toBeUndefined(); + expect(store.get("opencode-go", "go")).toBeUndefined(); + // Per plane: the Zen key stands. + expect(store.get(undefined, "zen")).toBe("z"); + // Dropped: not filed again, and a further refusal changes nothing… + store.record("k", "opencode-go", GO); + expect(store.get(undefined, "go")).toBeUndefined(); + expect(store.settle("k", "opencode-go", GO, "refused", false)).toBe(false); + // …and an acceptance of a request that may not file it (a key the fill + // supplied) leaves the drop where it is… + expect(store.settle("k", "opencode-go", GO, "accepted", false)).toBe(false); + store.record("k", "opencode-go", GO); + expect(store.get(undefined, "go")).toBeUndefined(); + // …until a request that carried it as its own is accepted. + expect(store.settle("k", "opencode-go", GO, "accepted", true)).toBe(true); + store.record("k", "opencode-go", GO); + expect(store.get(undefined, "go")).toBe("k"); + }); + + it("a strike counts against the key that drew it, not the next one", () => { + const store = createCaptureStore(); + store.record("a", "opencode-go", GO); + store.settle("a", "opencode-go", GO, "refused", false); + store.record("b", "opencode-go", GO); + store.settle("b", "opencode-go", GO, "refused", false); + expect(store.get(undefined, "go")).toBe("b"); + }); + + it("drops a relay key by its route, and leaves a key it never held alone", () => { + const store = createCaptureStore(); + store.record("r", "my-relay", RELAY); + expect(store.settle("never", "my-relay", RELAY, "refused", false)).toBe( + false + ); + store.settle("r", "my-relay", RELAY, "refused", false); + store.settle("r", "my-relay", RELAY, "refused", false); + expect(store.forRoute("my-relay")).toBeUndefined(); + expect(store.get()).toBeUndefined(); + // With no route at all, the scope is the route-less one. + store.record("n", undefined, RELAY); + expect(store.get()).toBe("n"); + store.settle("n", undefined, RELAY, "refused", false); + store.settle("n", undefined, RELAY, "refused", false); + expect(store.get()).toBeUndefined(); + }); + + it("drops a key held only under its plane, with no route and not the latest", () => { + const store = createCaptureStore(); + store.record("k", undefined, GO); + store.record("z", "opencode", ZEN); + store.settle("k", undefined, GO, "refused", false); + store.settle("k", undefined, GO, "refused", false); + expect(store.get(undefined, "go")).toBeUndefined(); + expect(store.get(undefined, "zen")).toBe("z"); + }); + + it("dropping a key leaves a route's entry for the other plane alone", () => { + const store = createCaptureStore(); + store.record("k", "opencode-go", GO); + store.record("k", "opencode", ZEN); + store.settle("k", "opencode-go", GO, "refused", false); + store.settle("k", "opencode-go", GO, "refused", false); + expect(store.get(undefined, "go")).toBeUndefined(); + expect(store.get("opencode", "zen")).toBe("k"); + }); +}); + +describe("credentials · one store per root", () => { + it("two roots never share a store; two contexts of one root do", async () => { + const one = new Context(); + const two = new Context(); + captureStoreFor(one).record("k", "opencode-go", GO); + expect(captureStoreFor(two).get(undefined, "go")).toBeUndefined(); + let child: unknown; + const fiber = one.plugin( + { + apply: (ctx: unknown) => { + child = ctx; + }, + name: "child-of-one", + } as never, + {} as never + ); + await fiber.await(); + expect(child).not.toBe(one); + expect(captureStoreFor(child).get(undefined, "go")).toBe("k"); + await fiber.dispose(); + }); + + it("a stand-in without a root keys on itself, and a non-object gets a store nobody else reads", () => { + const standIn = {}; + captureStoreFor(standIn).record("k", "opencode-go", GO); + expect(captureStoreFor(standIn).get(undefined, "go")).toBe("k"); + expect(captureStoreFor({ root: standIn }).get(undefined, "go")).toBe("k"); + const throwing = { + get root(): never { + throw new Error("hostile"); + }, + }; + captureStoreFor(throwing).record("t", "opencode-go", GO); + expect(captureStoreFor(throwing).get(undefined, "go")).toBe("t"); + captureStoreFor(null).record("x", "opencode-go", GO); + expect(captureStoreFor(null).get(undefined, "go")).toBeUndefined(); + }); +}); + +describe("credentials · the fill's resolver", () => { + /** A resolver over a fresh store and an environment of the case's own. */ + const resolver = ( + keySource: KeySourcePolicy = "auto", + env: Readonly> = {}, + readOpencodeStore = false, + storeReader?: (plane: string) => string | undefined + ) => { + const store = createCaptureStore(); + const reads: string[] = []; + return { + credentials: createCredentials({ + environment: (name) => { + reads.push(name); + return env[name]; + }, + keySource, + readOpencodeStore, + store, + ...(storeReader === undefined ? {} : { storeReader }), + }), + reads, + store, + }; + }; + + it("observe: answers the request's own usable key, and records it only from a decorated turn of the plugin's", () => { + const { credentials, store } = resolver(); + const headers = new Headers({ authorization: "Bearer seen" }); + const request = { + decorated: true, + foreign: false, + headers, + marked: false, + provider: "opencode-go", + url: GO, + }; + expect(credentials.observe({ ...request, decorated: false })).toBe("seen"); + expect(credentials.observe({ ...request, foreign: true })).toBe("seen"); + expect(credentials.observe({ ...request, marked: true })).toBe("seen"); + expect(store.get(undefined, "go")).toBeUndefined(); + expect(credentials.observe(request)).toBe("seen"); + expect(store.get(undefined, "go")).toBe("seen"); + expect( + credentials.observe({ + ...request, + headers: new Headers({ authorization: "Bearer unused" }), + }) + ).toBeUndefined(); + }); + + it.each([ + ["auto", "request-k"], + ["request", "request-k"], + ["configured", "request-k"], + ] as const)( + "fill under %s: the request's own key first", + (policy, expected) => { + const { credentials, store } = resolver(policy, { + OPENCODE_GO_API_KEY: "env-go", + }); + store.record("captured-go", "opencode-go", GO); + expect( + credentials.fillKey({ + plane: "opencode-go", + provider: "opencode-go", + requestKey: "request-k", + url: GO, + }) + ).toMatchObject({ key: expected, source: "request" }); + } + ); + + it.each([ + ["auto", "captured-go", "captured"], + ["request", "captured-go", "captured"], + ["configured", "env-go", "declared"], + ] as const)( + "fill under %s: a captured key unless configured", + (policy, key, source) => { + const { credentials, store } = resolver(policy, { + OPENCODE_GO_API_KEY: "env-go", + }); + store.record("captured-go", "opencode-go", GO); + expect( + credentials.fillKey({ + plane: "opencode-go", + provider: "opencode-go", + url: GO, + }) + ).toMatchObject({ key, source }); + } + ); + + it("fill: the declared variable is the plane's, or the Zen one off the planes", () => { + const env = { OPENCODE_API_KEY: "env-zen", OPENCODE_GO_API_KEY: "env-go" }; + const { credentials } = resolver("auto", env); + expect(credentials.fillKey({ plane: "opencode-go", url: GO }).key).toBe( + "env-go" + ); + expect(credentials.fillKey({ plane: "opencode", url: ZEN }).key).toBe( + "env-zen" + ); + expect( + credentials.fillKey({ plane: "", provider: "opencode-go", url: RELAY }) + .key + ).toBe("env-go"); + expect( + credentials.fillKey({ plane: "", provider: "my-relay", url: RELAY }).key + ).toBe("env-zen"); + }); + + it("fill: a route named after a plane takes that plane's capture on a URL on neither plane (the name fallback)", () => { + const { credentials, store } = resolver(); + store.record("go-k", "opencode-go", GO); + expect( + credentials.fillKey({ plane: "", provider: "opencode-go", url: RELAY }) + ).toMatchObject({ key: "go-k", source: "captured" }); + }); + + it("fill: a request on neither plane takes only its own route's key", () => { + const { credentials, store } = resolver(); + store.record("go-k", "opencode-go", GO); + expect( + credentials.fillKey({ plane: "", provider: "my-relay", url: RELAY }).key + ).toBeUndefined(); + expect(credentials.fillKey({ plane: "", url: RELAY }).key).toBeUndefined(); + store.record("relay-k", "my-relay", RELAY); + expect( + credentials.fillKey({ plane: "", provider: "my-relay", url: RELAY }) + ).toMatchObject({ key: "relay-k", source: "captured" }); + }); + + it("fill: the real installation store answers last, and only when opted in", () => { + const fixture = createOpencodeStore([ + { integrationId: "opencode-go", value: "store-go" }, + ]); + vi.stubEnv("XDG_DATA_HOME", fixture.root); + try { + // The real store, by default. + const off = resolver("auto", {}, false); + expect( + off.credentials.fillKey({ plane: "opencode-go", url: GO }).key + ).toBe(undefined); + const on = resolver("auto", {}, true); + expect( + on.credentials.fillKey({ plane: "opencode-go", url: GO }) + ).toMatchObject({ key: "store-go", source: "store" }); + const declared = resolver("auto", { OPENCODE_GO_API_KEY: "env" }, true); + expect( + declared.credentials.fillKey({ plane: "opencode-go", url: GO }).key + ).toBe("env"); + expect(resolveOpencodeStoreKey("", true)).toBeUndefined(); + } finally { + fixture.cleanup(); + } + }); + + it("fill: the store is never read when an earlier step answers or the deployment did not opt in, and read once when it is reached", () => { + const planes: string[] = []; + const reader = (plane: string): string => { + planes.push(plane); + return "store-go"; + }; + const fill = ( + env: Readonly>, + readOpencodeStore: boolean, + requestKey?: string, + seed?: string + ) => { + const { credentials, store } = resolver( + "auto", + env, + readOpencodeStore, + reader + ); + if (seed !== undefined) { + store.record(seed, "opencode-go", GO); + } + return credentials.fillKey({ + plane: "opencode-go", + provider: "opencode-go", + ...(requestKey === undefined ? {} : { requestKey }), + url: GO, + }); + }; + // Opted out: never read, though nothing else answers. + expect(fill({}, false).key).toBeUndefined(); + // Each earlier step answering: never read. + expect(fill({}, true, "own").source).toBe("request"); + expect(fill({}, true, undefined, "seen").source).toBe("captured"); + expect(fill({ OPENCODE_GO_API_KEY: "env" }, true).source).toBe("declared"); + expect(planes).toEqual([]); + // Reached: read once, for the request's plane. + expect(fill({}, true)).toMatchObject({ key: "store-go", source: "store" }); + expect(planes).toEqual(["opencode-go"]); + }); + + it("fill: reports what it consulted, a placeholder variable as set", () => { + const { credentials } = resolver("auto", { OPENCODE_API_KEY: "unused" }); + const decision = credentials.fillKey({ plane: "opencode", url: ZEN }); + expect(decision.key).toBeUndefined(); + expect(decision.source).toBeUndefined(); + expect(decision.consulted).toEqual({ + declaredName: "OPENCODE_API_KEY", + declaredSet: true, + storeRead: false, + }); + const blank = resolver("auto", { OPENCODE_API_KEY: "" }); + expect( + blank.credentials.fillKey({ plane: "opencode", url: ZEN }).consulted + .declaredSet + ).toBe(false); + }); + + it("settle: two well-formed 401s drop a captured key; a 2xx brings back one the request itself carried", () => { + const { credentials, store } = resolver(); + store.record("k", "opencode-go", GO); + const sent = { + decorated: true, + key: "k", + provider: "opencode-go", + recordable: false, + sessionWellFormed: true, + status: 401, + url: GO, + }; + credentials.settle(sent); + credentials.settle(sent); + expect(store.get(undefined, "go")).toBeUndefined(); + // Accepted on a request that carried it as its own: filed again. + credentials.settle({ ...sent, recordable: true, status: 204 }); + expect(store.get(undefined, "go")).toBe("k"); + + // Accepted, but not the request's own key: the drop stays, and the + // request's own observation does not file it either (OC3). + const other = resolver(); + other.store.record("k", "opencode-go", GO); + other.credentials.settle(sent); + other.credentials.settle(sent); + other.credentials.settle({ ...sent, status: 200 }); + expect(other.store.get(undefined, "go")).toBeUndefined(); + other.store.record("k", "opencode-go", GO); + expect(other.store.get(undefined, "go")).toBeUndefined(); + }); + + it("settle: a request outside any decorated turn neither strikes a key nor lifts a drop (OC3)", () => { + const { credentials, store } = resolver(); + store.record("k", "opencode-go", GO); + const turnless = { + decorated: false, + key: "k", + provider: undefined, + recordable: false, + sessionWellFormed: true, + status: 401, + url: "https://opencode.ai/zen/go/v1/usage", + }; + credentials.settle(turnless); + credentials.settle(turnless); + credentials.settle(turnless); + expect(store.get(undefined, "go")).toBe("k"); + // The known answer: the same two refusals on a decorated turn drop it… + const decorated = { ...turnless, decorated: true, provider: "opencode-go" }; + credentials.settle(decorated); + credentials.settle(decorated); + expect(store.get(undefined, "go")).toBeUndefined(); + // …and a turnless acceptance does not lift the drop. + credentials.settle({ ...turnless, status: 200 }); + store.record("k", "opencode-go", GO); + expect(store.get(undefined, "go")).toBeUndefined(); + }); + + it("settle: a 401 on a malformed session, another status, or no key says nothing about the key", () => { + const { credentials, store } = resolver(); + store.record("k", "opencode-go", GO); + const sent = { + decorated: true, + key: "k", + provider: "opencode-go", + recordable: false, + sessionWellFormed: false, + status: 401, + url: GO, + }; + credentials.settle(sent); + credentials.settle(sent); + credentials.settle({ ...sent, sessionWellFormed: true, status: 403 }); + credentials.settle({ ...sent, sessionWellFormed: true, status: 500 }); + credentials.settle({ ...sent, key: undefined, sessionWellFormed: true }); + credentials.settle({ ...sent, key: "unused", sessionWellFormed: true }); + expect(store.get(undefined, "go")).toBe("k"); + // The known answer: the same two 401s on a well-formed session drop it. + credentials.settle({ ...sent, sessionWellFormed: true }); + credentials.settle({ ...sent, sessionWellFormed: true }); + expect(store.get(undefined, "go")).toBeUndefined(); + }); + + it("sessionPin: the deployment's pinned id, read from its environment", () => { + const { credentials, reads } = resolver("auto", { PIN: "ses_pinned" }); + expect(credentials.sessionPin(undefined)).toBeUndefined(); + expect(credentials.sessionPin("")).toBeUndefined(); + expect(credentials.sessionPin("PIN")).toBe("ses_pinned"); + expect(reads).toEqual(["PIN"]); + }); + + it("reads the process environment when no environment is handed in", () => { + vi.stubEnv("OPENCODE_GO_API_KEY", "process-go"); + const credentials = createCredentials({ + keySource: "auto", + readOpencodeStore: false, + store: createCaptureStore(), + }); + expect(credentials.fillKey({ plane: "opencode-go", url: GO }).key).toBe( + "process-go" + ); + }); +}); diff --git a/test/fetch-patch-headers.test.ts b/test/fetch-patch-headers.test.ts index e097e4c..65e9059 100644 --- a/test/fetch-patch-headers.test.ts +++ b/test/fetch-patch-headers.test.ts @@ -14,7 +14,6 @@ import { SESSION_AFFINITY_HEADER, SESSION_HEADER, SESSION_ID_HEADER, - clearCapturedApiKeys, hasSessionHeader, isOpenCodeSessionId, openCodeSessionIdFor, @@ -38,7 +37,6 @@ afterEach(() => { delete process.env.OPENCODE_GO_API_KEY; delete process.env.OPENCODE_SESSION_ID; delete process.env.XDG_DATA_HOME; - clearCapturedApiKeys(); }); describe("patchFetch · headers", () => { diff --git a/test/fetch-patch-observability.test.ts b/test/fetch-patch-observability.test.ts index 22baf7d..4546211 100644 --- a/test/fetch-patch-observability.test.ts +++ b/test/fetch-patch-observability.test.ts @@ -10,7 +10,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { OPENCODE_UA, SESSION_HEADER, - clearCapturedApiKeys, getLiveGoCatalog, isOpenCodeSessionId, openCodeSessionIdFor, @@ -26,7 +25,6 @@ afterEach(() => { delete process.env.OPENCODE_GO_API_KEY; delete process.env.OPENCODE_SESSION_ID; delete process.env.XDG_DATA_HOME; - clearCapturedApiKeys(); }); describe("patchFetch · observability", () => { diff --git a/test/fetch-patch-tools.test.ts b/test/fetch-patch-tools.test.ts index c7f0632..3d49e14 100644 --- a/test/fetch-patch-tools.test.ts +++ b/test/fetch-patch-tools.test.ts @@ -17,7 +17,6 @@ import { DUMMY_BASH_TOOL, DUMMY_READ_TOOL, SESSION_HEADER, - clearCapturedApiKeys, findModelSpecOn, openCodeSessionIdFor, patchFetch, @@ -37,7 +36,6 @@ afterEach(() => { delete process.env.OPENCODE_GO_API_KEY; delete process.env.OPENCODE_SESSION_ID; delete process.env.XDG_DATA_HOME; - clearCapturedApiKeys(); }); describe("patchFetch · core tools", () => { diff --git a/test/fetch-patch.test.ts b/test/fetch-patch.test.ts index 4174002..89e98bb 100644 --- a/test/fetch-patch.test.ts +++ b/test/fetch-patch.test.ts @@ -19,10 +19,14 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { freeZenModel, payload, shimFor } from "./support/catalogs.ts"; import { createOpencodeStore } from "./support/opencode-store-fixture.ts"; import { - clearCapturedApiKeys, + callHeadersFor, + type CaptureStore, + createCaptureStore, + createCredentials, + type FetchPatchHooks, findModelSpecOn, - getCapturedApiKey, - recordCapturedApiKey, + OPENCODE_UA, + openCodeSessionIdFor, patchFetch, refreshCatalog, resolveConfig, @@ -41,9 +45,28 @@ afterEach(() => { delete process.env.OPENCODE_GO_API_KEY; delete process.env.OPENCODE_SESSION_ID; delete process.env.XDG_DATA_HOME; - clearCapturedApiKeys(); }); +/** + * A capture store of the case's own, and the hooks that hand the patch a + * resolver over it, so a case can seed and read what the patch learned. + */ +const storeFor = ( + config: ReturnType = resolveConfig() +): { readonly store: CaptureStore; readonly hooks: FetchPatchHooks } => { + const store = createCaptureStore(); + return { + hooks: { + credentials: createCredentials({ + keySource: config.keySource, + readOpencodeStore: config.readOpencodeStore, + store, + }), + }, + store, + }; +}; + describe("patchFetch · another plugin's request (D27)", () => { /** * A route another plugin writes through pi-ai carries its @@ -68,7 +91,8 @@ describe("patchFetch · another plugin's request (D27)", () => { seen.push(args); return Response.json({ ok: true }); }) as unknown as typeof fetch; - const patched = patchFetch(original, als, resolveConfig(), {}); + const { hooks, store } = storeFor(); + const patched = patchFetch(original, als, resolveConfig(), hooks); const init: RequestInit = { body: JSON.stringify({ messages: [], model: "deepseek-v4-pro" }), headers: { authorization: "Bearer realm-token", [header]: "x/1" }, @@ -80,8 +104,8 @@ describe("patchFetch · another plugin's request (D27)", () => { expect(seen[0]?.[0]).toBe(url); expect(seen[0]?.[1]).toBe(init); expect(new Headers(init.headers).has(SESSION_HEADER)).toBe(false); - expect(getCapturedApiKey("opencode-go")).toBeUndefined(); - expect(getCapturedApiKey(undefined, "go")).toBeUndefined(); + expect(store.get("opencode-go")).toBeUndefined(); + expect(store.get(undefined, "go")).toBeUndefined(); } ); @@ -93,7 +117,8 @@ describe("patchFetch · another plugin's request (D27)", () => { seen.push(args); return Response.json({ ok: true }); }) as unknown as typeof fetch; - const patched = patchFetch(original, als, resolveConfig(), {}); + const { hooks, store } = storeFor(); + const patched = patchFetch(original, als, resolveConfig(), hooks); const url = "https://opencode.ai/zen/go/v1/chat/completions"; const init: RequestInit = { body: JSON.stringify({ messages: [], model: "deepseek-v4-pro" }), @@ -104,15 +129,16 @@ describe("patchFetch · another plugin's request (D27)", () => { await als.run(foreign as ActiveTurnState, () => patched(url, init)); expect(seen[0]?.[0]).toBe(url); expect(seen[0]?.[1]).toBe(init); - expect(getCapturedApiKey("opencode-go")).toBeUndefined(); - expect(getCapturedApiKey(undefined, "go")).toBeUndefined(); + expect(store.get("opencode-go")).toBeUndefined(); + expect(store.get(undefined, "go")).toBeUndefined(); // Outside the foreign turn the gateway URL is claimed: headers are - // written and the key is captured. + // written. The key is not captured: no turn of the plugin's sent it + // (OC3). await patched(url, init); const sent = seen[1]?.[1] as RequestInit | undefined; expect(sent).not.toBe(init); expect(new Headers(sent?.headers).get(SESSION_HEADER)).toBeTruthy(); - expect(getCapturedApiKey(undefined, "go")).toBe("realm-token"); + expect(store.get(undefined, "go")).toBeUndefined(); }); it("passes a marked Request through as the same object, and still patches the unmarked one (the known answer)", async () => { @@ -122,7 +148,8 @@ describe("patchFetch · another plugin's request (D27)", () => { seen.push(args); return Response.json({ ok: true }); }) as unknown as typeof fetch; - const patched = patchFetch(original, als, resolveConfig(), {}); + const { hooks, store } = storeFor(); + const patched = patchFetch(original, als, resolveConfig(), hooks); const url = "https://opencode.ai/zen/go/v1/chat/completions"; const marked = new Request(url, { body: "{}", @@ -135,7 +162,7 @@ describe("patchFetch · another plugin's request (D27)", () => { await als.run(turn, () => patched(marked)); expect(seen[0]?.[0]).toBe(marked); expect(seen[0]?.[1]).toBeUndefined(); - expect(getCapturedApiKey(undefined, "go")).toBeUndefined(); + expect(store.get(undefined, "go")).toBeUndefined(); const plain = new Request(url, { body: "{}", headers: { authorization: "Bearer user-go-key" }, @@ -144,7 +171,7 @@ describe("patchFetch · another plugin's request (D27)", () => { await als.run(turn, () => patched(plain)); const sent = seen[1]?.[1] as RequestInit | undefined; expect(new Headers(sent?.headers).get(SESSION_HEADER)).toBeTruthy(); - expect(getCapturedApiKey(undefined, "go")).toBe("user-go-key"); + expect(store.get(undefined, "go")).toBe("user-go-key"); }); }); @@ -413,15 +440,16 @@ describe("patchFetch · credentials", () => { // not look at the model (it reads the request's key, then the captured // one, then the declared one), so the id below is a neutral uncatalogued // one: the subject is the placeholder, not the tier. A placeholder is never - // forwarded (P6 owns the fill). + // forwarded (the fill's one filter, `usableKey`, in `credentials.ts`). // // A key captured from the user's own plane route, on the endpoint family the // catalog now names. const als = new AsyncLocalStorage(); const { capture, mockFetch } = createCaptureFetch(); - const patched = patchFetch(mockFetch, als, resolveConfig()); + const { hooks, store } = storeFor(); + const patched = patchFetch(mockFetch, als, resolveConfig(), hooks); - recordCapturedApiKey("oc_sk_zen_key", "opencode"); + store.record("oc_sk_zen_key", "opencode"); // Read through `Headers`, because the patch hands the adapter a `Headers` // instance rather than the plain object it was given. const auth = (init?: RequestInit): string | null => @@ -446,9 +474,10 @@ describe("patchFetch · credentials", () => { it("captures API key from request headers on intercepted OpenCode requests", async () => { const als = new AsyncLocalStorage(); const { mockFetch } = createCaptureFetch(); - const patched = patchFetch(mockFetch, als, resolveConfig()); + const { hooks, store } = storeFor(); + const patched = patchFetch(mockFetch, als, resolveConfig(), hooks); - expect(getCapturedApiKey("opencode-go")).toBeUndefined(); + expect(store.get("opencode-go")).toBeUndefined(); await als.run( { provider: "opencode-go", value: "ses_header_key" }, @@ -463,26 +492,25 @@ describe("patchFetch · credentials", () => { } ); - expect(getCapturedApiKey("opencode-go")).toBe("sk-intercepted-go-key-xyz"); - expect(getCapturedApiKey(undefined, "go")).toBe( - "sk-intercepted-go-key-xyz" - ); + expect(store.get("opencode-go")).toBe("sk-intercepted-go-key-xyz"); + expect(store.get(undefined, "go")).toBe("sk-intercepted-go-key-xyz"); }); it("picks the captured key for the request's TIER, not the most recent one", async () => { const als = new AsyncLocalStorage(); const { capture, mockFetch } = createCaptureFetch(); - const patched = patchFetch(mockFetch, als, resolveConfig()); + const { hooks, store } = storeFor(); + const patched = patchFetch(mockFetch, als, resolveConfig(), hooks); // A Go key captured first… - recordCapturedApiKey( + store.record( "sk-go-key-aaa", "opencode-go", "https://opencode.ai/zen/go/v1/chat/completions" ); // …then a Zen key, so "most recently seen" is now the WRONG tier for a Go // call. A Zen key sent to the Go quota endpoint is rejected outright. - recordCapturedApiKey( + store.record( "oc_sk_zen_key_bbb", "opencode", "https://opencode.ai/zen/v1/messages" @@ -530,16 +558,19 @@ describe("patchFetch · credentials", () => { ]); process.env.XDG_DATA_HOME = store.root; const als = new AsyncLocalStorage(); + const captured = createCaptureStore(); const call = async ( config: ReturnType, url: string ): Promise => { const { capture, mockFetch } = createCaptureFetch(); - await patchFetch( - mockFetch, - als, - config - )(url, { + await patchFetch(mockFetch, als, config, { + credentials: createCredentials({ + keySource: config.keySource, + readOpencodeStore: config.readOpencodeStore, + store: captured, + }), + })(url, { headers: { Authorization: "Bearer unused" }, method: "POST", }); @@ -570,7 +601,7 @@ describe("patchFetch · credentials", () => { ); delete process.env.OPENCODE_API_KEY; - recordCapturedApiKey("oc_sk_captured", "opencode", zen); + captured.record("oc_sk_captured", "opencode", zen); expect(await call(resolveConfig({ readOpencodeStore: true }), zen)).toBe( "Bearer oc_sk_captured" ); @@ -587,7 +618,8 @@ describe("patchFetch · credentials", () => { const reportFor = async ( config: ReturnType, url: string, - init: RequestInit + init: RequestInit, + store: CaptureStore = createCaptureStore() ): Promise<{ authorization: string | null; line: string | undefined }> => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); const { capture, mockFetch } = createCaptureFetch(); @@ -596,7 +628,14 @@ describe("patchFetch · credentials", () => { await patchFetch( mockFetch, new AsyncLocalStorage(), - config + config, + { + credentials: createCredentials({ + keySource: config.keySource, + readOpencodeStore: config.readOpencodeStore, + store, + }), + } )(url, init); lines = warn.mock.calls.map((args) => args.map(String).join(" ")); } finally { @@ -633,11 +672,13 @@ describe("patchFetch · credentials", () => { it("under the configured policy a captured key never fills the wire, and the report says so", async () => { const url = "https://opencode.ai/zen/v1/responses"; - recordCapturedApiKey("sk-captured", "opencode", url); + const store = createCaptureStore(); + store.record("sk-captured", "opencode", url); const { authorization, line } = await reportFor( resolveConfig({ keySource: "configured" }), url, - { body: JSON.stringify({ model: paidZenModel() }), method: "POST" } + { body: JSON.stringify({ model: paidZenModel() }), method: "POST" }, + store ); expect(authorization).toBeNull(); expect(line).toContain( @@ -682,3 +723,483 @@ describe("patchFetch · credentials", () => { } }); }); + +describe("patchFetch · whose key, and for how long (P6)", () => { + const GO = "https://opencode.ai/zen/go/v1/chat/completions"; + const ZEN = "https://opencode.ai/zen/v1/chat/completions"; + /** A decorated Go turn, with a session id the gateway accepts. */ + const goTurn = { + provider: "opencode-go", + value: openCodeSessionIdFor("p6-go"), + }; + const zenTurn = { + provider: "opencode", + value: openCodeSessionIdFor("p6-zen"), + }; + + /** + * A wrapped fetch that records the credential each request carried and + * answers the next status of `statuses` (200 once they run out). + */ + const gateway = (statuses: number[] = []) => { + const auth: (string | null)[] = []; + const seen: Headers[] = []; + const original = (async (_input: RequestInfo | URL, init?: RequestInit) => { + const headers = new Headers(init?.headers); + seen.push(headers); + auth.push(headers.get("authorization") ?? headers.get("x-api-key")); + return Response.json({}, { status: statuses.shift() ?? 200 }); + }) as unknown as typeof fetch; + return { auth, original, seen }; + }; + + const send = ( + patched: typeof fetch, + url: string, + bearer?: string + ): Promise => + patched(url, { + body: JSON.stringify({ model: "p6-model" }), + headers: + bearer === undefined ? {} : { authorization: `Bearer ${bearer}` }, + method: "POST", + }); + + it("OC3 — a key on a claimed request outside any turn of the plugin's is never recorded", async () => { + const als = new AsyncLocalStorage(); + const wire = gateway(); + const { hooks, store } = storeFor(); + const patched = patchFetch(wire.original, als, resolveConfig(), hooks); + // Turnless: the URL claim still writes the session header. + await send(patched, GO, "realm-token"); + expect(wire.seen[0]?.get(SESSION_HEADER)).toBeTruthy(); + // …but the key it carried is nobody's to keep, or to replay. + expect(store.get(undefined, "go")).toBeUndefined(); + expect(store.get("opencode-go")).toBeUndefined(); + await als.run(goTurn, () => send(patched, GO, "unused")); + expect(wire.auth[1]).toBe("Bearer unused"); + // The known answer: the same key inside a decorated turn is recorded. + await als.run(goTurn, () => send(patched, GO, "turn-token")); + expect(store.get("opencode-go", "go")).toBe("turn-token"); + await als.run(goTurn, () => send(patched, GO, "unused")); + expect(wire.auth[3]).toBe("Bearer turn-token"); + }); + + it("OC3 — a key captured on a plane never fills a provider-claimed request to a URL on neither plane", async () => { + const als = new AsyncLocalStorage(); + const wire = gateway(); + const patched = patchFetch( + wire.original, + als, + resolveConfig({ providers: ["my-relay"] }) + ); + const relay = { provider: "my-relay", value: openCodeSessionIdFor("r") }; + const relayUrl = "https://relay.example/v1/chat/completions"; + await als.run(goTurn, () => send(patched, GO, "go-key")); + await als.run(relay, () => send(patched, relayUrl, "unused")); + expect(wire.auth[1]).toBe("Bearer unused"); + // The known answer: a key the relay route itself sent there fills it. + await als.run(relay, () => send(patched, relayUrl, "relay-key")); + await als.run(relay, () => send(patched, relayUrl, "unused")); + expect(wire.auth[3]).toBe("Bearer relay-key"); + }); + + it("OC3 / L8 — a relay route's key never fills a plane request, not even once the plane's own key is dropped", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + const als = new AsyncLocalStorage(); + const statuses: number[] = []; + const wire = gateway(statuses); + const { hooks, store } = storeFor( + resolveConfig({ providers: ["my-relay"] }) + ); + const patched = patchFetch( + wire.original, + als, + resolveConfig({ providers: ["my-relay"] }), + hooks + ); + const relay = { provider: "my-relay", value: openCodeSessionIdFor("r") }; + const relayUrl = "https://relay.example/v1/chat/completions"; + await als.run(goTurn, () => send(patched, GO, "go-key")); + await als.run(relay, () => send(patched, relayUrl, "relay-key")); + // The known answer: the plane's own key fills a placeholder there. + await als.run(goTurn, () => send(patched, GO, "unused")); + expect(wire.auth.at(-1)).toBe("Bearer go-key"); + // Two well-formed 401s drop it… + statuses.push(401, 401); + await als.run(goTurn, () => send(patched, GO, "unused")); + await als.run(goTurn, () => send(patched, GO, "unused")); + // …and the relay's key, the latest one seen, does not take its place. + await als.run(goTurn, () => send(patched, GO, "unused")); + expect(wire.auth.at(-1)).toBe("Bearer unused"); + await send(patched, GO, "unused"); + expect(wire.auth.at(-1)).toBe("Bearer unused"); + // It still fills its own route's request. + await als.run(relay, () => send(patched, relayUrl, "unused")); + expect(wire.auth.at(-1)).toBe("Bearer relay-key"); + expect(store.forRoute("my-relay")).toBe("relay-key"); + }); + + it("L8 — a captured key is dropped after a second well-formed 401 in a row, per plane, and not before", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const als = new AsyncLocalStorage(); + const statuses: number[] = []; + const wire = gateway(statuses); + const patched = patchFetch(wire.original, als, resolveConfig()); + const fill = async (turn: ActiveTurnState, url: string, status: number) => { + statuses.push(status); + await als.run(turn, () => send(patched, url, "unused")); + return wire.auth.at(-1); + }; + await als.run(goTurn, () => send(patched, GO, "k")); + await als.run(zenTurn, () => send(patched, ZEN, "z")); + // One 401: the key stays. + expect(await fill(goTurn, GO, 401)).toBe("Bearer k"); + // A 2xx clears the strike, so another single 401 still does not drop it. + expect(await fill(goTurn, GO, 200)).toBe("Bearer k"); + expect(await fill(goTurn, GO, 401)).toBe("Bearer k"); + // The second 401 in a row drops it. + expect(await fill(goTurn, GO, 401)).toBe("Bearer k"); + expect(await fill(goTurn, GO, 200)).toBe("Bearer unused"); + expect( + warn.mock.calls.some(([line]) => + String(line).includes("no credential resolved for opencode-go") + ) + ).toBe(true); + // Per plane: the Zen key captured beside it still fills a Zen request. + expect(await fill(zenTurn, ZEN, 200)).toBe("Bearer z"); + }); + + /** + * A patch whose captured Go key `k` was dropped by two well-formed 401s on + * decorated turns, and a `fill` that sends a placeholder on a decorated Go + * turn and answers what reached the wire. + */ + const droppedKey = async () => { + const als = new AsyncLocalStorage(); + const statuses: number[] = []; + const wire = gateway(statuses); + const { hooks, store } = storeFor(); + const patched = patchFetch(wire.original, als, resolveConfig(), hooks); + const sendIn = async ( + turn: ActiveTurnState | undefined, + url: string, + bearer: string, + status: number + ) => { + statuses.push(status); + await (turn === undefined + ? send(patched, url, bearer) + : als.run(turn, () => send(patched, url, bearer))); + return wire.auth.at(-1); + }; + await sendIn(goTurn, GO, "k", 200); + await sendIn(goTurn, GO, "unused", 401); + await sendIn(goTurn, GO, "unused", 401); + expect(await sendIn(goTurn, GO, "unused", 200)).toBe("Bearer unused"); + return { + fill: () => sendIn(goTurn, GO, "unused", 200), + sendIn, + store, + }; + }; + + it("L8 — a dropped key comes back only when a decorated turn's own request carrying it is accepted", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + const { fill, sendIn } = await droppedKey(); + // Refused: the drop stands, and the turn's observation does not file it. + await sendIn(goTurn, GO, "k", 401); + expect(await fill()).toBe("Bearer unused"); + // Accepted: the answer files it again, from the settle and not the + // observation (which refuses a dropped key). + await sendIn(goTurn, GO, "k", 200); + expect(await fill()).toBe("Bearer k"); + }); + + it("L8 / OC3 — a dropped key the fill supplied, accepted, stays dropped: the declared variable's rotation is what the next fill sends", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + const { fill, store } = await droppedKey(); + // The declared variable holds the dropped key: the fill sends it, and the + // gateway accepts it, but the request did not carry it as its own. + process.env.OPENCODE_GO_API_KEY = "k"; + expect(await fill()).toBe("Bearer k"); + expect(store.get(undefined, "go")).toBeUndefined(); + // Rotated: had the acceptance filed k again, the captured step would + // outrank the declared one and send the stale key. + process.env.OPENCODE_GO_API_KEY = "k2"; + expect(await fill()).toBe("Bearer k2"); + }); + + it("L8 — a 401 on a malformed session id strikes nothing, while the same 401s on a well-formed one drop the key", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const als = new AsyncLocalStorage(); + const statuses: number[] = []; + const wire = gateway(statuses); + const { hooks, store } = storeFor(); + const patched = patchFetch(wire.original, als, resolveConfig(), hooks); + // A turn whose session value the gateway reads as malformed; the patch + // sends it as it is. + const malformed = { provider: "opencode-go", value: "ses_x" }; + await als.run(goTurn, () => send(patched, GO, "k")); + for (const _ of [1, 2, 3]) { + statuses.push(401); + // oxlint-disable-next-line no-await-in-loop -- the turns are sequential. + await als.run(malformed, () => send(patched, GO, "unused")); + } + expect(wire.seen.at(-1)?.get(SESSION_HEADER)).toBe("ses_x"); + expect(wire.auth.at(-1)).toBe("Bearer k"); + expect(store.get(undefined, "go")).toBe("k"); + // The known answer: two 401s on a well-formed session drop it. + statuses.push(401, 401); + await als.run(goTurn, () => send(patched, GO, "unused")); + await als.run(goTurn, () => send(patched, GO, "unused")); + expect(store.get(undefined, "go")).toBeUndefined(); + warn.mockRestore(); + }); + + it("OC3 — a turnless placeholder request on a plane URL is still filled with a key a decorated turn sent, and its own token is never kept", async () => { + const als = new AsyncLocalStorage(); + const wire = gateway(); + const { hooks, store } = storeFor(); + const patched = patchFetch(wire.original, als, resolveConfig(), hooks); + await als.run(goTurn, () => send(patched, GO, "k")); + // Turnless, with the placeholder: the plugin's own key fills it. + await send(patched, GO, "unused"); + expect(wire.auth.at(-1)).toBe("Bearer k"); + // Turnless, with a token of its own: sent as it is, never kept… + await send(patched, GO, "realm-token"); + expect(wire.auth.at(-1)).toBe("Bearer realm-token"); + expect(store.get(undefined, "go")).toBe("k"); + // …and never used to fill the next one. + await send(patched, GO, "unused"); + expect(wire.auth.at(-1)).toBe("Bearer k"); + }); + + it("OC3 — a turnless accepted request carrying a dropped key does not lift the drop", async () => { + vi.spyOn(console, "warn").mockImplementation(() => {}); + const { fill, sendIn } = await droppedKey(); + await sendIn(undefined, GO, "k", 200); + expect(await fill()).toBe("Bearer unused"); + // Had the turnless answer lifted it, this refused decorated request would + // have filed it on the way out; it does not. + await sendIn(goTurn, GO, "k", 401); + expect(await fill()).toBe("Bearer unused"); + }); + + it("OC3 / L8 — the meter's own /usage 401s drop nothing: a turnless refusal is no evidence about a turn's key", async () => { + const als = new AsyncLocalStorage(); + const statuses: number[] = []; + const wire = gateway(statuses); + const { hooks, store } = storeFor(); + const patched = patchFetch(wire.original, als, resolveConfig(), hooks); + const usage = "https://opencode.ai/zen/go/v1/usage"; + await als.run(goTurn, () => send(patched, GO, "k")); + expect(store.get("opencode-go", "go")).toBe("k"); + for (const _ of [1, 2, 3]) { + statuses.push(401); + // oxlint-disable-next-line no-await-in-loop -- the polls are sequential. + await patched(usage, { headers: { authorization: "Bearer k" } }); + } + // The poll was claimed (it carries the patch's session header)… + expect(wire.seen.at(-1)?.get(SESSION_HEADER)).toMatch(/^ses_/u); + // …and the key still fills a Go turn. + expect(store.get("opencode-go", "go")).toBe("k"); + await als.run(goTurn, () => send(patched, GO, "unused")); + expect(wire.auth.at(-1)).toBe("Bearer k"); + // The known answer: two refusals on decorated turns do drop it. + statuses.push(401, 401); + await als.run(goTurn, () => send(patched, GO, "unused")); + await als.run(goTurn, () => send(patched, GO, "unused")); + expect(store.get("opencode-go", "go")).toBeUndefined(); + }); + + it("a disposed link passes every request through untouched: no header, no fill, no capture", async () => { + process.env.OPENCODE_API_KEY = "declared-zen"; + const als = new AsyncLocalStorage(); + const calls: { input: unknown; init: unknown }[] = []; + const original = (async (input: unknown, init?: unknown) => { + calls.push({ init, input }); + return Response.json({}); + }) as unknown as typeof fetch; + const store = createCaptureStore(); + const credentials = createCredentials({ + keySource: "auto", + readOpencodeStore: false, + store, + }); + let live = false; + const patched = patchFetch(original, als, resolveConfig(), { + credentials, + live: () => live, + }); + const init = { + body: JSON.stringify({ model: "p6-model" }), + headers: { authorization: "Bearer real-key" }, + method: "POST", + }; + const placeholder = { + ...init, + headers: { authorization: "Bearer unused" }, + }; + await als.run(goTurn, () => patched(ZEN, init)); + await als.run(goTurn, () => patched(ZEN, placeholder)); + expect(calls[0]?.input).toBe(ZEN); + expect(calls[0]?.init).toBe(init); + expect(calls[1]?.init).toBe(placeholder); + expect(store.get("opencode-go")).toBeUndefined(); + expect(store.get(undefined, "zen")).toBeUndefined(); + // The known answer: the same link, live, decorates and captures. + live = true; + await als.run(goTurn, () => patched(ZEN, init)); + expect(calls[2]?.init).not.toBe(init); + const decorated = calls[2]?.init as RequestInit | undefined; + expect(new Headers(decorated?.headers).get(SESSION_HEADER)).toBe( + goTurn.value + ); + expect(store.get(undefined, "zen")).toBe("real-key"); + }); + + it("the placeholder filter applies to the installation's store: a stored `unused` fills nothing, and the report fires", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const store = createOpencodeStore([ + { integrationId: "opencode-go", value: "unused" }, + ]); + process.env.XDG_DATA_HOME = store.root; + try { + const wire = gateway(); + await send( + patchFetch( + wire.original, + new AsyncLocalStorage(), + resolveConfig({ readOpencodeStore: true }) + ), + GO + ); + expect(wire.auth[0]).toBeNull(); + expect( + warn.mock.calls.some(([line]) => + String(line).includes("no credential resolved for opencode-go") + ) + ).toBe(true); + } finally { + store.cleanup(); + } + }); + + it("a blank exported key is no key: nothing fills the wire, and the report fires", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + process.env.OPENCODE_API_KEY = " "; + const wire = gateway(); + await send( + patchFetch( + wire.original, + new AsyncLocalStorage(), + resolveConfig() + ), + ZEN + ); + expect(wire.auth[0]).toBeNull(); + expect( + warn.mock.calls.some(([line]) => + String(line).includes("no credential resolved for opencode;") + ) + ).toBe(true); + }); + + it("OC5 — on a per-call-shaped turn the patch writes no plane header, still fills the key and the User-Agent, and still replaces a malformed session id", async () => { + process.env.OPENCODE_API_KEY = "declared-zen"; + const als = new AsyncLocalStorage(); + const wire = gateway(); + const patched = patchFetch(wire.original, als, resolveConfig()); + const ses = openCodeSessionIdFor("p6-percall"); + const theirs = openCodeSessionIdFor("someone-else"); + const shaped = { + perCall: true, + project: "p", + provider: "opencode", + value: ses, + } as ActiveTurnState; + const request = (session: string) => + patched(ZEN, { + body: "{}", + headers: { + authorization: "Bearer unused", + "x-opencode-project": "theirs", + "x-opencode-session": session, + }, + method: "POST", + }); + await als.run(shaped, () => request(theirs)); + const [kept] = wire.seen; + expect(kept?.get(SESSION_HEADER)).toBe(theirs); + expect(kept?.get("x-opencode-project")).toBe("theirs"); + expect(kept?.has("x-opencode-session-id")).toBe(false); + expect(kept?.get("user-agent")).toBe(OPENCODE_UA); + expect(kept?.get("authorization")).toBe("Bearer declared-zen"); + // A malformed id is still replaced, with every plane header from the turn. + await als.run(shaped, () => request("oc5-raw")); + const [, rewritten] = wire.seen; + expect(rewritten?.get(SESSION_HEADER)).toBe(ses); + expect(rewritten?.get("x-opencode-session-id")).toBe(ses); + expect(rewritten?.get("x-opencode-project")).toBe("p"); + // The known answer: without the flag the first request is rewritten. + const { perCall: _dropped, ...unshaped } = shaped; + await als.run(unshaped as ActiveTurnState, () => request(theirs)); + expect(wire.seen[2]?.get(SESSION_HEADER)).toBe(ses); + expect(wire.seen[2]?.get("x-opencode-project")).toBe("p"); + }); + + it("OC11 — on a host without the request-headers seam, where prepareHeaders is never called, the patch still writes the plugin's session and plane headers on a plane turn", async () => { + // 0.2.2-alpha.2 and every 0.2.1 build never call the adapter's + // `prepareHeaders`, so the turn the stream hook decorated is never + // marked per call and the request reaches the patch with pi's headers + // only. The peer still admits those hosts (OC11 is met in the README + // pair), and this is what keeps the plugin's headers on their wire. + process.env.OPENCODE_API_KEY = "declared-zen"; + const als = new AsyncLocalStorage(); + const config = resolveConfig(); + const wire = gateway(); + const patched = patchFetch(wire.original, als, config); + const ses = openCodeSessionIdFor("p6-no-seam"); + const turn = { + project: "p", + provider: "opencode", + value: ses, + } as ActiveTurnState; + const callHeaders = callHeadersFor(als, config); + const piHeaders = (): Headers => + new Headers({ + authorization: "Bearer unused", + "content-type": "application/json", + }); + + // No seam: the host sends pi's headers as they are. + await als.run(turn, () => + patched(ZEN, { body: "{}", headers: piHeaders(), method: "POST" }) + ); + expect(turn.perCall).toBeUndefined(); + const [fallback] = wire.seen; + expect(fallback?.get(SESSION_HEADER)).toMatch( + /^ses_[0-9a-f]{12}[0-9A-Za-z]{14}$/u + ); + expect(fallback?.get(SESSION_HEADER)).toBe(ses); + expect(fallback?.get("x-opencode-session-id")).toBe(ses); + expect(fallback?.get("x-opencode-client")).toBe("cli"); + expect(fallback?.get("x-opencode-project")).toBe("p"); + expect(fallback?.get("user-agent")).toBe(OPENCODE_UA); + expect(fallback?.get("authorization")).toBe("Bearer declared-zen"); + + // The known answer: with the seam, the host calls `prepareHeaders`, the + // turn is marked, and the patch leaves the per-call headers as written. + const seamed = { ...turn } as ActiveTurnState; + await als.run(seamed, () => { + const headers = piHeaders(); + callHeaders(headers); + headers.set("x-opencode-project", "per-call"); + return patched(ZEN, { body: "{}", headers, method: "POST" }); + }); + expect(seamed.perCall).toBe(true); + expect(wire.seen[1]?.get(SESSION_HEADER)).toBe(ses); + expect(wire.seen[1]?.get("x-opencode-project")).toBe("per-call"); + }); +}); diff --git a/test/global-fetch.test.ts b/test/global-fetch.test.ts new file mode 100644 index 0000000..925e28f --- /dev/null +++ b/test/global-fetch.test.ts @@ -0,0 +1,237 @@ +/** + * `host/global-fetch.ts` — the plugin's one write to `globalThis.fetch`, on + * real cordis contexts. + * + * Each activation is a fiber of a real `Context`, so its effect runs and its + * disposer is cordis's own. The patch each one installs is a tagging wrapper + * that passes through once its activation is gone, which is what the + * installer hands it `live` for; a request through the chain reports which + * live links it went through. + * + * @module test/global-fetch.test + */ +import { Context, type Fiber } from "@deepseek-ai/cordis"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { offlineFetch } from "./support/offline.ts"; +import { type CordisContext, installGlobalFetch } from "./support/src.ts"; + +/** The links a request went through, outermost first. */ +const TRAIL = "x-trail"; + +/** The stub every case starts from: it answers the trail it was handed. */ +const stub = (async (_input: RequestInfo | URL, init?: RequestInit) => + new Response(new Headers(init?.headers).get(TRAIL) ?? "")) as typeof fetch; + +/** A patch that adds its name to the trail while live, and passes through once not. */ +const tagging = + (name: string) => + (original: typeof fetch, live: () => boolean): typeof fetch => + (async (input: RequestInfo | URL, init?: RequestInit) => { + if (!live()) { + return original(input, init); + } + const headers = new Headers(init?.headers); + headers.set(TRAIL, `${headers.get(TRAIL) ?? ""}${name}`); + return original(input, { ...init, headers }); + }) as typeof fetch; + +/** The trail a request through the current fetch reports. */ +const trail = async (): Promise => { + const response = await globalThis.fetch("http://127.0.0.1:9/"); + return response.text(); +}; + +const fibers: Fiber[] = []; + +afterEach(async () => { + for (const fiber of fibers.splice(0).toReversed()) { + await fiber.dispose(); + } + vi.restoreAllMocks(); + globalThis.fetch = offlineFetch; +}); + +/** One activation on `root`, installing a tagging patch named `name`. */ +const activate = async ( + root: Context, + name: string, + logs: string[] = [] +): Promise<{ fiber: Fiber; inPlace: (() => boolean) | undefined }> => { + let inPlace: (() => boolean) | undefined; + const fiber = root.plugin( + { + apply: (ctx: unknown) => { + const context = ctx as CordisContext; + inPlace = installGlobalFetch( + { + effect: context.effect?.bind(context), + logger: { + warn: (line: string) => { + logs.push(line); + }, + }, + } as CordisContext, + tagging(name), + () => { + logs.push(`announce ${name}`); + } + ); + }, + name: `activation-${name}`, + } as never, + {} as never + ); + fibers.push(fiber); + await fiber.await(); + return { fiber, inPlace }; +}; + +describe("installGlobalFetch", () => { + it("one activation: wraps the fetch in place, announces, and restores it on dispose", async () => { + globalThis.fetch = stub; + const root = new Context(); + const logs: string[] = []; + const a = await activate(root, "A", logs); + expect(logs).toEqual(["announce A"]); + expect(await trail()).toBe("A"); + expect(a.inPlace?.()).toBe(true); + await a.fiber.dispose(); + expect(globalThis.fetch).toBe(stub); + expect(a.inPlace?.()).toBe(false); + }); + + it.each([ + ["the earlier first", 0], + ["the later first", 1], + ] as const)( + "apply A, apply B, dispose both (%s) ends at the fetch that was there", + async (_order, first) => { + globalThis.fetch = stub; + const root = new Context(); + const a = await activate(root, "A"); + const b = await activate(root, "B"); + expect(await trail()).toBe("BA"); + const [early, late] = first === 0 ? [a, b] : [b, a]; + await early.fiber.dispose(); + // The remaining activation's patch still runs; the disposed one passes + // through wherever it sits. + expect(await trail()).toBe(first === 0 ? "B" : "A"); + expect(late.inPlace?.()).toBe(true); + await late.fiber.dispose(); + expect(globalThis.fetch).toBe(stub); + } + ); + + it("three activations, the middle one disposed first and then the latest: the first is current again", async () => { + globalThis.fetch = stub; + const root = new Context(); + const a = await activate(root, "A"); + const b = await activate(root, "B"); + const c = await activate(root, "C"); + await b.fiber.dispose(); + expect(await trail()).toBe("CA"); + await c.fiber.dispose(); + expect(await trail()).toBe("A"); + expect(a.inPlace?.()).toBe(true); + await a.fiber.dispose(); + expect(globalThis.fetch).toBe(stub); + }); + + it("a third party's function on top is left alone on dispose, and still reaches the original through the pass-through link", async () => { + globalThis.fetch = stub; + const root = new Context(); + const a = await activate(root, "A"); + const underneath = globalThis.fetch; + const theirs = vi.fn((input: RequestInfo | URL, init?: RequestInit) => + underneath(input, init) + ) as unknown as typeof fetch; + globalThis.fetch = theirs; + expect(a.inPlace?.()).toBe(false); + await a.fiber.dispose(); + expect(globalThis.fetch).toBe(theirs); + expect(await trail()).toBe(""); + expect(theirs).toHaveBeenCalledTimes(1); + }); + + it("wraps the fetch in place when the effect runs, not when it was installed", async () => { + globalThis.fetch = stub; + const root = new Context(); + const swapped = (async () => new Response("swapped")) as typeof fetch; + let inPlace: (() => boolean) | undefined; + const fiber = root.plugin( + { + apply: (ctx: unknown) => { + const context = ctx as CordisContext; + inPlace = installGlobalFetch( + { + effect: (callback: () => unknown, label?: string) => { + globalThis.fetch = swapped; + context.effect?.(callback, label); + }, + } as CordisContext, + tagging("A"), + () => { + // announced + } + ); + }, + name: "activation-late", + } as never, + {} as never + ); + fibers.push(fiber); + await fiber.await(); + expect(await trail()).toBe("swapped"); + expect(inPlace?.()).toBe(true); + await fiber.dispose(); + expect(globalThis.fetch).toBe(swapped); + }); + + it("installs nothing, and warns, when there is no fetch at install or by effect time", async () => { + const logs: string[] = []; + vi.stubGlobal("fetch", undefined); + const root = new Context(); + const none = await activate(root, "A", logs); + expect(none.inPlace).toBeUndefined(); + expect(logs).toEqual([ + "[dsh-opencode-patch] globalThis.fetch is unavailable; cannot inject x-opencode-session", + ]); + vi.unstubAllGlobals(); + + globalThis.fetch = stub; + const gone: string[] = []; + const fiber = root.plugin( + { + apply: (ctx: unknown) => { + const context = ctx as CordisContext; + installGlobalFetch( + { + effect: (callback: () => unknown, label?: string) => { + globalThis.fetch = undefined as unknown as typeof fetch; + context.effect?.(callback, label); + }, + logger: { + warn: (line: string) => { + gone.push(line); + }, + }, + } as CordisContext, + tagging("B"), + () => { + gone.push("announce B"); + } + ); + }, + name: "activation-gone", + } as never, + {} as never + ); + fibers.push(fiber); + await fiber.await(); + expect(gone).toEqual([ + "[dsh-opencode-patch] globalThis.fetch is unavailable; cannot inject x-opencode-session", + ]); + expect(globalThis.fetch).toBeUndefined(); + }); +}); diff --git a/test/go-discovery-base-url.test.ts b/test/go-discovery-base-url.test.ts index 051bb41..8d708e3 100644 --- a/test/go-discovery-base-url.test.ts +++ b/test/go-discovery-base-url.test.ts @@ -15,7 +15,6 @@ import { } from "./support/loader-rows.ts"; import { DEFAULT_USAGE_BASE_URL, - clearCapturedApiKeys, resolveGoBaseURL, toGoBaseURL, } from "./support/src.ts"; @@ -31,7 +30,6 @@ afterEach(() => { delete process.env.DSH_TEST_GO_KEY; delete process.env.OPENCODE_API_KEY; delete process.env.OPENCODE_GO_API_KEY; - clearCapturedApiKeys(); }); describe("toGoBaseURL and resolveGoBaseURL", () => { diff --git a/test/go-discovery-keys.test.ts b/test/go-discovery-keys.test.ts index 67d1180..0919d06 100644 --- a/test/go-discovery-keys.test.ts +++ b/test/go-discovery-keys.test.ts @@ -22,12 +22,10 @@ import { DEFAULT_USAGE_KEY_ENV, type DiscoveredGoConfig, KEY_SOURCE_POLICIES, - clearCapturedApiKeys, + captureStoreFor, discoverGoConfig, effectiveGoKeyRef, - getCapturedApiKey, isPlaceholderApiKey, - recordCapturedApiKey, resolveGoApiKey, resolveGoKeyForRef, resolveZenCreditInfo, @@ -36,17 +34,23 @@ import { /** * Restore every piece of ambient state these cases touch. * - * A leaked env var or a leftover captured key silently breaks whichever file - * runs next, so the hook lives in this file and not only in the old monolith. + * A leaked env var silently breaks whichever file runs next, so the hook lives + * in this file and not only in the old monolith. Captured keys are kept per + * root: each case seeds the store of the composition it resolves against. */ afterEach(() => { // Named deletes rather than a loop: the names are the contract. delete process.env.DSH_TEST_GO_KEY; delete process.env.OPENCODE_API_KEY; delete process.env.OPENCODE_GO_API_KEY; - clearCapturedApiKeys(); }); +/** Seed a key into a composition's capture store, as a decorated turn would. */ +const seed = (context: T, key: string, provider: string, url: string): T => { + captureStoreFor(context).record(key, provider, url); + return context; +}; + describe("effectiveGoKeyRef", () => { it("uses the composition's reference and defaults when there is none", () => { // The reference is never a row setting: it is the provider row's own @@ -96,15 +100,25 @@ describe("resolveGoApiKey: which source the policy selects", () => { // The default policy is byte-for-byte the original precedence: what the // composition declares is what the user configured on purpose. process.env.OPENCODE_GO_API_KEY = "sk-env"; - recordCapturedApiKey("sk-captured", "opencode-go", GO_REQUEST); - expect(await resolveGoApiKey(withLiteral())).toBe("sk-literal"); + const context = seed( + withLiteral(), + "sk-captured", + "opencode-go", + GO_REQUEST + ); + expect(await resolveGoApiKey(context)).toBe("sk-literal"); }); it("request: a captured key is promoted above both declared sources", async () => { // The whole point of the policy — a rotated live key beats a pinned one. process.env.OPENCODE_GO_API_KEY = "sk-env"; - recordCapturedApiKey("sk-captured", "opencode-go", GO_REQUEST); - expect(await resolveGoApiKey(withLiteral(), undefined, "request")).toBe( + const context = seed( + withLiteral(), + "sk-captured", + "opencode-go", + GO_REQUEST + ); + expect(await resolveGoApiKey(context, undefined, "request")).toBe( "sk-captured" ); }); @@ -113,17 +127,23 @@ describe("resolveGoApiKey: which source the policy selects", () => { // The opposite choice, for a pinned or CI deployment: the declared // credential is the contract, whatever the last request happened to carry. process.env.OPENCODE_GO_API_KEY = "sk-env"; - recordCapturedApiKey("sk-captured", "opencode-go", GO_REQUEST); - expect(await resolveGoApiKey(withLiteral(), undefined, "configured")).toBe( + const literal = seed( + withLiteral(), + "sk-captured", + "opencode-go", + GO_REQUEST + ); + expect(await resolveGoApiKey(literal, undefined, "configured")).toBe( "sk-literal" ); - expect(await resolveGoApiKey(bare(), undefined, "configured")).toBe( + const context = seed(bare(), "sk-captured", "opencode-go", GO_REQUEST); + expect(await resolveGoApiKey(context, undefined, "configured")).toBe( "sk-env" ); - expect(await resolveGoApiKey(bare(), undefined, "auto")).toBe( + expect(await resolveGoApiKey(context, undefined, "auto")).toBe( "sk-captured" ); - expect(await resolveGoApiKey(bare(), undefined, "request")).toBe( + expect(await resolveGoApiKey(context, undefined, "request")).toBe( "sk-captured" ); }); @@ -131,9 +151,9 @@ describe("resolveGoApiKey: which source the policy selects", () => { it("every policy falls back to a key captured under a route it no longer names", async () => { // A user who renames their Go route would otherwise lose the only working // key they have: the tier lookup must find it by account, not by route id. - recordCapturedApiKey("sk-rotated", "my-relay", GO_REQUEST); + const context = seed(bare(), "sk-rotated", "my-relay", GO_REQUEST); for (const policy of KEY_SOURCE_POLICIES) { - expect(await resolveGoApiKey(bare(), "opencode-go", policy)).toBe( + expect(await resolveGoApiKey(context, "opencode-go", policy)).toBe( "sk-rotated" ); } @@ -162,8 +182,8 @@ describe("resolveGoApiKey: which source the policy selects", () => { // not. delete process.env.OPENCODE_GO_API_KEY; delete process.env.OPENCODE_API_KEY; - recordCapturedApiKey("oc_sk_zen", "opencode", ZEN_REQUEST); - expect(await resolveGoApiKey(bare(), "opencode-go", "configured")).toBe( + const zen = seed(bare(), "oc_sk_zen", "opencode", ZEN_REQUEST); + expect(await resolveGoApiKey(zen, "opencode-go", "configured")).toBe( undefined ); }); @@ -338,19 +358,28 @@ describe("resolveZenCreditInfo", () => { it("accepts a captured Zen key as configured credit", async () => { // The captured Zen key is the rotation-proof answer, and it is checked // before any host lookup so a live turn settles the question immediately. - recordCapturedApiKey("oc_sk_captured", "opencode", ZEN_REQUEST); - const captured = await resolveZenCreditInfo(composition()); + const context = seed( + composition(), + "oc_sk_captured", + "opencode", + ZEN_REQUEST + ); + // With nothing in the environment, so the capture really did answer. + const captured = await resolveZenCreditInfo(context); expect(captured.isConfigured).toBe(true); - // Even with nothing in the environment, so the capture really did answer. + // The store is the composition's: another root learned nothing, and + // neither did a context that is none at all. + const other = await resolveZenCreditInfo(composition()); + expect(other.isConfigured).toBe(false); const noContext = await resolveZenCreditInfo(null); - expect(noContext.isConfigured).toBe(true); + expect(noContext.isConfigured).toBe(false); }); it("does not count a Go key as Zen credit", async () => { // Go credit cannot overflow into Zen: the overflow card is only drawn when // the Zen plane is the one that would be charged. - recordCapturedApiKey("sk-go", "opencode-go", GO_REQUEST); - const goOnly = await resolveZenCreditInfo(composition()); + const context = seed(composition(), "sk-go", "opencode-go", GO_REQUEST); + const goOnly = await resolveZenCreditInfo(context); expect(goOnly.isConfigured).toBe(false); }); @@ -377,14 +406,37 @@ describe("resolveZenCreditInfo", () => { const blank = await resolveZenCreditInfo(probe.context); expect(blank.isConfigured).toBe(false); }); + + it("a placeholder or a blank is no Zen credit, from the environment or the credentials service (P6)", async () => { + // The one filter applies at this decider's exit too: a placeholder Zen + // key would otherwise draw the overflow card for a key that is none. + for (const value of ["unused", "none", " "]) { + process.env.OPENCODE_API_KEY = value; + // oxlint-disable-next-line no-await-in-loop -- one value at a time. + const exported = await resolveZenCreditInfo(composition()); + expect(exported.isConfigured, JSON.stringify(value)).toBe(false); + delete process.env.OPENCODE_API_KEY; + // oxlint-disable-next-line no-await-in-loop -- one value at a time. + const served = await resolveZenCreditInfo( + withCredentials({ OPENCODE_API_KEY: value }).context + ); + expect(served.isConfigured, JSON.stringify(value)).toBe(false); + } + // A placeholder the service answers falls through to the environment. + process.env.OPENCODE_API_KEY = "oc_sk_env"; + const fallsThrough = await resolveZenCreditInfo( + withCredentials({ OPENCODE_API_KEY: "unused" }).context + ); + expect(fallsThrough.isConfigured).toBe(true); + }); }); describe("gaps characterised while pinning the policy", () => { it("never lets a placeholder become the credential the meter sends", async () => { // This repo's README tells users to write exactly `authorization: Bearer // unused` on a keyless route, and `readProviderRow` used to copy that header - // into `literalKey` with none of the placeholder check - // `recordCapturedApiKey` applies. Because `literal` is the first step of + // into `literalKey` with none of the placeholder check the capture store + // applies. Because `literal` is the first step of // both `auto` and `configured`, the sentinel outranked a working stored // credential AND a working captured key, so the meter authenticated as // `Bearer unused` on every poll and the 401 read like a missing @@ -396,7 +448,7 @@ describe("gaps characterised while pinning the policy", () => { }), ]); process.env.OPENCODE_GO_API_KEY = "sk-real-env-key"; - recordCapturedApiKey("sk-real-captured", "opencode-go", GO_REQUEST); + seed(context, "sk-real-captured", "opencode-go", GO_REQUEST); expect(isPlaceholderApiKey("unused")).toBe(true); // The sentinel is not a credential at any point of discovery… @@ -429,9 +481,8 @@ describe("gaps characterised while pinning the policy", () => { expect(isPlaceholderApiKey("PUBLIC")).toBe(true); // Never captured from a live request, however it arrives. - clearCapturedApiKeys(); - recordCapturedApiKey("public", "opencode-go", GO_REQUEST); - expect(getCapturedApiKey("opencode-go")).toBeUndefined(); + const captured = seed(composition(), "public", "opencode-go", GO_REQUEST); + expect(captureStoreFor(captured).get("opencode-go")).toBeUndefined(); // And never used as a declared env credential, so a free turn goes out // keyless rather than carrying the sentinel. @@ -456,41 +507,65 @@ describe("gaps characterised while pinning the policy", () => { // `request`. Reachable whenever a request left the Go route carrying a Zen // key (a `OPENCODE_GO_API_KEY` mislabelled to the Zen secret, say). // - // Fixed in `getCapturedApiKey`: the route-scoped map now stores the tier + // Fixed in the capture store's `get`: the route-scoped map now stores the tier // alongside the key and applies the same rule as the other two lookups. // Naming a route is a PREFERENCE, not a licence to ignore the tier. // Under any other route id it was always filtered correctly: - clearCapturedApiKeys(); - recordCapturedApiKey("oc_sk_zen", "my-relay", ZEN_REQUEST); + const relay = seed(composition(), "oc_sk_zen", "my-relay", ZEN_REQUEST); expect( - await resolveGoApiKey(composition(), "opencode-go", "request") + await resolveGoApiKey(relay, "opencode-go", "request") ).toBeUndefined(); expect( - await resolveGoKeyForRef(composition(), DEFAULT_USAGE_KEY_ENV) + await resolveGoKeyForRef(relay, DEFAULT_USAGE_KEY_ENV) ).toBeUndefined(); // Filed under the Go route id it is now filtered identically, so no policy // can surface it. - clearCapturedApiKeys(); - recordCapturedApiKey("oc_sk_zen", "opencode-go", ZEN_REQUEST); + const misfiled = seed( + composition(), + "oc_sk_zen", + "opencode-go", + ZEN_REQUEST + ); for (const policy of KEY_SOURCE_POLICIES) { expect( - await resolveGoApiKey(composition(), "opencode-go", policy), + await resolveGoApiKey(misfiled, "opencode-go", policy), `policy ${policy} sent a Zen key to the Go endpoint` ).toBeUndefined(); } // And a correctly-classified key filed under the same route id still // answers — the filter rejects the wrong tier, not the right one. - clearCapturedApiKeys(); - recordCapturedApiKey("sk-go-key", "opencode-go", GO_REQUEST); - expect(await resolveGoApiKey(composition(), "opencode-go", "auto")).toBe( + const filed = seed(composition(), "sk-go-key", "opencode-go", GO_REQUEST); + expect(await resolveGoApiKey(filed, "opencode-go", "auto")).toBe( "sk-go-key" ); }); + it("OC3 — the meter never answers a key a route sent to a URL on neither plane", async () => { + // A relay's key went to a third party, not to the gateway, so neither the + // route-scoped nor the any-route captured step may hand it to Go's + // `/usage`, under any policy. + const relay = seed( + composition(), + "sk-relay", + "my-relay", + "https://relay.example/v1/chat/completions" + ); + for (const policy of KEY_SOURCE_POLICIES) { + expect( + await resolveGoApiKey(relay, "my-relay", policy), + `policy ${policy} sent a relay key to the Go endpoint` + ).toBeUndefined(); + expect(await resolveGoApiKey(relay, undefined, policy)).toBeUndefined(); + } + // The known answer: the same key sent to the Go plane is the meter's. + const go = seed(composition(), "sk-relay", "my-relay", GO_REQUEST); + expect(await resolveGoApiKey(go, undefined, "auto")).toBe("sk-relay"); + }); + it("never sends a whitespace-only credential to the Go endpoint", async () => { - // CHARACTERISED, NOT ENDORSED. `readProviderRow` and `firstResolved` both + // CHARACTERISED, NOT ENDORSED. `readProviderRow` and the meter's step loop both // ask only whether a value is a non-empty *string*, so a row carrying // `apiKey: " "` — what a YAML value with trailing whitespace parses to — // declares a credential that is whitespace. It is the first step of `auto` @@ -502,7 +577,7 @@ describe("gaps characterised while pinning the policy", () => { registryEntry("opencode-go", { apiKey: " " }), ]); process.env.OPENCODE_GO_API_KEY = "sk-real-env-key"; - recordCapturedApiKey("sk-real-captured", "opencode-go", GO_REQUEST); + seed(context, "sk-real-captured", "opencode-go", GO_REQUEST); // Same guard as the placeholder above: a blanked-but-indented secret must // not reach the wire under ANY policy, not only the ones that happen to diff --git a/test/go-discovery-store.test.ts b/test/go-discovery-store.test.ts index f0d6397..5cafed7 100644 --- a/test/go-discovery-store.test.ts +++ b/test/go-discovery-store.test.ts @@ -13,8 +13,7 @@ import { type FixtureStore, } from "./support/opencode-store-fixture.ts"; import { - clearCapturedApiKeys, - recordCapturedApiKey, + captureStoreFor, resolveGoApiKey, resolveOpencodeStoreKey, } from "./support/src.ts"; @@ -22,15 +21,14 @@ import { /** * Restore every piece of ambient state these cases touch. * - * A leaked env var or a leftover captured key silently breaks whichever file - * runs next, so the hook lives in this file and not only in the old monolith. + * A leaked env var silently breaks whichever file runs next, so the hook lives + * in this file and not only in the old monolith. */ afterEach(() => { // Named deletes rather than a loop: the names are the contract. delete process.env.DSH_TEST_GO_KEY; delete process.env.OPENCODE_API_KEY; delete process.env.OPENCODE_GO_API_KEY; - clearCapturedApiKeys(); }); describe("go-discovery: the installation's own store, and where it sits", () => { @@ -91,9 +89,14 @@ describe("go-discovery: the installation's own store, and where it sits", () => it("still loses to a key captured from a live request", async () => { withStore([{ integrationId: "opencode-go", value: "sk-fixture-go" }]); - recordCapturedApiKey("sk-captured-go", "opencode-go", GO_REQUEST); + const context = composition(); + captureStoreFor(context).record( + "sk-captured-go", + "opencode-go", + GO_REQUEST + ); await expect( - resolveGoApiKey(composition(), undefined, "auto", true) + resolveGoApiKey(context, undefined, "auto", true) ).resolves.toBe("sk-captured-go"); }); @@ -118,4 +121,15 @@ describe("go-discovery: the installation's own store, and where it sits", () => resolveGoApiKey(composition(), undefined, "auto", true) ).resolves.toBeUndefined(); }); + + it("a placeholder in the store is no credential: the meter resolves nothing", async () => { + // The one placeholder filter applies at the meter's exit too, whichever + // source answered: a stored `unused` must not reach the usage endpoint. + withStore([{ integrationId: "opencode-go", value: "unused" }]); + for (const policy of ["auto", "request", "configured"] as const) { + await expect( + resolveGoApiKey(composition(), undefined, policy, true) + ).resolves.toBeUndefined(); + } + }); }); diff --git a/test/go-discovery.test.ts b/test/go-discovery.test.ts index 4383c74..5a934d7 100644 --- a/test/go-discovery.test.ts +++ b/test/go-discovery.test.ts @@ -19,8 +19,9 @@ * characterised rather than endorsed; see the comments for the reason. * * Offline and deterministic: no network, no clocks, and every case restores - * `process.env` and the captured-key store in `afterEach`, because a leaked env - * var silently breaks every file that runs after this one. + * `process.env` in `afterEach`, because a leaked env var silently breaks every + * file that runs after this one; captured keys are kept per root, so a case's + * own context starts with none. * * This file holds which entry and which row field the Go config is read from; * its siblings hold the base URL (`go-discovery-base-url`), the key ladder @@ -40,20 +41,19 @@ import { standaloneEntry, ZEN_BASE, } from "./support/loader-rows.ts"; -import { clearCapturedApiKeys, discoverGoConfig } from "./support/src.ts"; +import { discoverGoConfig } from "./support/src.ts"; /** * Restore every piece of ambient state these cases touch. * - * A leaked env var or a leftover captured key silently breaks whichever file - * runs next, so the hook lives in this file and not only in the old monolith. + * A leaked env var silently breaks whichever file runs next, so the hook lives + * in this file and not only in the old monolith. */ afterEach(() => { // Named deletes rather than a loop: the names are the contract. delete process.env.DSH_TEST_GO_KEY; delete process.env.OPENCODE_API_KEY; delete process.env.OPENCODE_GO_API_KEY; - clearCapturedApiKeys(); }); describe("discoverGoConfig: which entry the credential comes from", () => { diff --git a/test/harness-channel.test.ts b/test/harness-channel.test.ts index c2fba49..f2e6e51 100644 --- a/test/harness-channel.test.ts +++ b/test/harness-channel.test.ts @@ -235,6 +235,15 @@ describe("harness channel alignment · declarations", () => { // silently drops every `0.2.2-*` build, alpha and rc alike. Both clauses // stop at 0.3.0, which leaves the next line a separate decision rather than // a silent widening. + // + // The range deliberately does NOT follow the `llm-pi-ai/request-headers` + // seam (OC11). That seam first shipped in 0.2.2-alpha.3 and 0.2.2-rc.1 and + // is absent from 0.2.2-alpha.2 and every 0.2.1 build (a grep of each + // published bridge, 2026-11-15), but the plane adapter detects it by + // behaviour, and on a host without it the fetch patch still writes the + // plugin's own headers; only other plugins' contributors do not run on the + // planes there. Host gaps are feature-detected, never compared by version + // (D26), so the seam's floor is stated in the README pair instead. const peer = manifest().peerDependencies?.["@deepseek-ai/dsh-typert-protocol"]; expect(peer).toBeDefined(); @@ -254,6 +263,7 @@ describe("harness channel alignment · declarations", () => { "0.2.2-alpha.3", "0.2.2-rc.1", "0.2.2-rc.2", + "0.2.2-rc.3", "0.2.2", ...Object.values(CHANNELS).map((record) => record.dsh), ]), @@ -292,8 +302,8 @@ describe("harness channel alignment · declarations", () => { // `~4.0.6-alpha.2` although no 4.0.6 prerelease satisfies it, because the // prerelease-tuple rule npm resolves under is not part of an overlap. // - // Both tables are recorded from the registry on 2026-11-04, and 0.2.2-rc.2 - // on 2026-11-12 (`npm view + // Both tables are recorded from the registry on 2026-11-04, 0.2.2-rc.2 on + // 2026-11-12 and 0.2.2-rc.3 on 2026-11-15 (`npm view // @deepseek-ai/dsh-typert-protocol@ peerDependencies` for every build // on the 0.2.1 and 0.2.2 lines; `npm view @deepseek-ai/cordis versions`). // A new typert build joins the first with its cordis range, and a new @@ -322,6 +332,7 @@ describe("harness channel alignment · declarations", () => { "0.2.2-alpha.3": "~4.0.6-alpha.2", "0.2.2-rc.1": "~4.1.0", "0.2.2-rc.2": "~4.1.0", + "0.2.2-rc.3": "~4.1.0", }; const peers = manifest().peerDependencies ?? {}; const typertPeer = peers["@deepseek-ai/dsh-typert-protocol"] ?? ""; @@ -359,6 +370,7 @@ describe("harness channel alignment · declarations", () => { expect(refused("~4.0.4 || >=4.0.5-0 <4.1.0 || >=4.0.6-0 <4.1.0")).toEqual([ "typert@0.2.2-rc.1 -> cordis@4.1.0", "typert@0.2.2-rc.2 -> cordis@4.1.0", + "typert@0.2.2-rc.3 -> cordis@4.1.0", ]); expect(refused("~4.0.4 || >=4.0.5-0 <4.1.0 || ~4.1.0")).toEqual( expect.arrayContaining(["typert@0.2.2-alpha.3 -> cordis@4.0.6-alpha.2"]) diff --git a/test/host-planes-config.test.ts b/test/host-planes-config.test.ts index c3df8e6..2a2725c 100644 --- a/test/host-planes-config.test.ts +++ b/test/host-planes-config.test.ts @@ -32,7 +32,6 @@ import { type TierA, type TierB, } from "./support/host.ts"; -import { clearCapturedApiKeys } from "./support/src.ts"; let tierA: TierA | undefined; let tierB: TierB | undefined; @@ -45,7 +44,6 @@ afterEach(async () => { } finally { tierA = undefined; tierB = undefined; - clearCapturedApiKeys(); vi.restoreAllMocks(); vi.unstubAllGlobals(); } diff --git a/test/host-planes-credentials.test.ts b/test/host-planes-credentials.test.ts index 467f11a..7453665 100644 --- a/test/host-planes-credentials.test.ts +++ b/test/host-planes-credentials.test.ts @@ -31,12 +31,7 @@ import { createOpencodeStore, type FixtureStore, } from "./support/opencode-store-fixture.ts"; -import { - clearCapturedApiKeys, - getCapturedApiKey, - recordCapturedApiKey, - resolveGoApiKey, -} from "./support/src.ts"; +import { captureStoreFor, resolveGoApiKey } from "./support/src.ts"; let tierA: TierA | undefined; @@ -50,7 +45,6 @@ afterEach(async () => { } finally { tierA = undefined; tierB = undefined; - clearCapturedApiKeys(); vi.restoreAllMocks(); vi.unstubAllGlobals(); } @@ -150,7 +144,9 @@ describe("host planes · credentials (tier A, D20)", { timeout: 30_000 }, () => "deepseek-v4-pro" ); expect(requests[0]?.url).toContain("/inference/go/"); - expect(getCapturedApiKey("opencode-go", "go")).toBe(refs.OPENCODE_API_KEY); + expect(captureStoreFor(tierA.ctx).get("opencode-go", "go")).toBe( + refs.OPENCODE_API_KEY + ); expect(await resolveGoApiKey(tierA.ctx, "opencode-go")).toBe( refs.OPENCODE_API_KEY ); @@ -289,10 +285,14 @@ describe("host planes · credentials (tier A, D20)", { timeout: 30_000 }, () => }); it("a captured key never answers for a named ref that resolves nothing", async () => { - recordCapturedApiKey("opencode", "cap"); const tier = await mountWith(fakeCredentials(), { apiKeyEnv: "OPENCODE_API_KEY", }); + captureStoreFor(tier.ctx).record( + "cap", + "opencode", + "https://opencode.ai/zen/v1/chat/completions" + ); const { drained, requests } = await turn( tier.llm, "opencode", diff --git a/test/host-planes-foreign.test.ts b/test/host-planes-foreign.test.ts index 898fadc..83f9e88 100644 --- a/test/host-planes-foreign.test.ts +++ b/test/host-planes-foreign.test.ts @@ -49,9 +49,8 @@ import { waitForPlaneOwner, } from "./support/host.ts"; import { - clearCapturedApiKeys, + captureStoreFor, discoverGoConfig, - getCapturedApiKey, getLiveGoCatalog, getLiveZenCatalog, isDeprecatedModelOn, @@ -61,6 +60,7 @@ import { resolveGoApiKey, SESSION_HEADER, } from "./support/src.ts"; +import { collectUnknown } from "./test-helpers.ts"; /** The realm label the fixture isolates pi-ai's credentials into. */ const REALM = "console-test-realm"; @@ -111,7 +111,6 @@ afterEach(async () => { } finally { tierA = undefined; tierB = undefined; - clearCapturedApiKeys(); vi.restoreAllMocks(); vi.unstubAllGlobals(); vi.unstubAllEnvs(); @@ -313,9 +312,9 @@ describe( ); expect(realm.calls).toContainEqual(["resolve", TOKEN_REF]); expect(tier.credentials.calls).not.toContainEqual(["resolve", TOKEN_REF]); - expect(getCapturedApiKey("opencode-go")).toBeUndefined(); - expect(getCapturedApiKey(undefined, "go")).toBeUndefined(); - expect(getCapturedApiKey(undefined, "zen")).toBeUndefined(); + expect(captureStoreFor(tier.ctx).get("opencode-go")).toBeUndefined(); + expect(captureStoreFor(tier.ctx).get(undefined, "go")).toBeUndefined(); + expect(captureStoreFor(tier.ctx).get(undefined, "zen")).toBeUndefined(); }); it("the realm alone is enough: unmarked entries in a realm the plugin does not share stay pi-ai's, and their turns leave as pi-ai alone sends them, with nothing captured", async () => { @@ -366,10 +365,10 @@ describe( } expect(realm.calls).toContainEqual(["resolve", TOKEN_REF]); for (const plane of PLANES) { - expect(getCapturedApiKey(plane)).toBeUndefined(); + expect(captureStoreFor(tier.ctx).get(plane)).toBeUndefined(); } - expect(getCapturedApiKey(undefined, "go")).toBeUndefined(); - expect(getCapturedApiKey(undefined, "zen")).toBeUndefined(); + expect(captureStoreFor(tier.ctx).get(undefined, "go")).toBeUndefined(); + expect(captureStoreFor(tier.ctx).get(undefined, "zen")).toBeUndefined(); }); it("a Settings save on a realm plane is judged by pi-ai's own check, not the plugin's", async () => { @@ -526,14 +525,14 @@ describe( for (const header of OURS) { expect(go.requests[0]?.headers).not.toHaveProperty(header); } - expect(getCapturedApiKey("opencode-go")).toBeUndefined(); - expect(getCapturedApiKey(undefined, "go")).toBeUndefined(); - expect(getCapturedApiKey(undefined, "zen")).toBeUndefined(); + expect(captureStoreFor(tierA.ctx).get("opencode-go")).toBeUndefined(); + expect(captureStoreFor(tierA.ctx).get(undefined, "go")).toBeUndefined(); + expect(captureStoreFor(tierA.ctx).get(undefined, "zen")).toBeUndefined(); // The known answer: the unmarked plane is decorated, and its key is // captured, as before. const zen = await turn(tierA.llm, "opencode"); expect(zen.requests[0]?.headers[SESSION_HEADER]).toMatch(/^ses_/u); - expect(getCapturedApiKey("opencode")).toBe("zen-k"); + expect(captureStoreFor(tierA.ctx).get("opencode")).toBe("zen-k"); }); } ); @@ -1513,3 +1512,66 @@ describe( ); } ); + +describe( + "host planes · a token the plugin did not send is never replayed (tier A, OC3)", + { timeout: 30_000 }, + () => { + it("an unmarked, turnless gateway request carrying a token is never replayed by the meter", async () => { + // A Console-style request: on the gateway's URL, outside any turn the + // plugin decorated, with no marker. The URL claim still shapes it, but + // its token is not the plugin's to keep. + offline(); + tierA = await mountTierA({ + plugin: {}, + providers: { "opencode-go": { models: [{ id: MODEL }] } }, + }); + await waitForPlaneOwner(tierA.llm, ["opencode-go"]); + await globalThis.fetch("https://opencode.ai/zen/go/v1/models", { + headers: { authorization: "Bearer console-token" }, + }); + expect(wire.requests.at(-1)?.headers[SESSION_HEADER]).toBeTruthy(); + for (const policy of ["auto", "request", "configured"] as const) { + expect( + await resolveGoApiKey(tierA.ctx, "opencode-go", policy), + policy + ).toBeUndefined(); + } + // The known answer: the same token, sent by a request of a turn the + // plugin decorated (cordis's own `llm/stream` waterfall, through the + // patched fetch), is what the meter of this root answers. So the store + // the meter reads is the one the patch writes. + const downstream = async function* downstream() { + await globalThis.fetch( + "https://opencode.ai/zen/go/v1/chat/completions", + { + body: JSON.stringify({ model: MODEL }), + headers: { authorization: "Bearer console-token" }, + method: "POST", + } + ); + yield { type: "finish" }; + }; + await collectUnknown( + ( + tierA.ctx as unknown as { + waterfall: (event: string, ...args: unknown[]) => unknown; + } + ).waterfall( + "llm/stream", + { provider: "opencode-go", sessionId: "oc3-control" }, + downstream + ) as AsyncIterable + ); + expect(wire.requests.at(-1)?.headers.authorization).toBe( + "Bearer console-token".length + ); + for (const policy of ["auto", "request", "configured"] as const) { + expect( + await resolveGoApiKey(tierA.ctx, "opencode-go", policy), + policy + ).toBe("console-token"); + } + }); + } +); diff --git a/test/host-planes-headers.test.ts b/test/host-planes-headers.test.ts new file mode 100644 index 0000000..8ec3274 --- /dev/null +++ b/test/host-planes-headers.test.ts @@ -0,0 +1,198 @@ +/** + * The plane's per-call headers, on the real host (OC4, OC5). + * + * pi-ai shapes a request's headers through its adapter's `prepareHeaders` + * option, which its own `apply` wires to the `llm-pi-ai/request-headers` + * waterfall; the plugin's `PlaneAdapter` is built with one too, so a + * contributor of another plugin's runs on the planes the plugin serves (OC4), + * and the plugin sets its own plane headers there, per call, before any + * contributor (OC5). The fetch patch then leaves a per-call-shaped request's + * plane headers alone. + * + * Tier B registers a contributor on the root before any row mounts, as a + * plugin of the composition would; tier A replaces `globalThis.fetch` after + * the mount with a recorder that never calls through, so the fetch patch is + * out of the path and what reaches the wire is what the adapter sent. + * + * @module test/host-planes-headers.test + */ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { disposeBooted, offline, wire } from "./support/host-planes.ts"; +import { + bootTierB, + drainStream, + fakeCredentials, + mountTierA, + recordingFetch, + type TierA, + type TierB, + waitForPlaneOwner, +} from "./support/host.ts"; +import { DEFAULT_ORIGIN_CLIENT, openCodeSessionIdFor } from "./support/src.ts"; + +let tierA: TierA | undefined; +let tierB: TierB | undefined; + +afterEach(async () => { + try { + await tierA?.dispose(); + await tierB?.dispose(); + await disposeBooted(); + } finally { + tierA = undefined; + tierB = undefined; + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + } +}); + +const MODEL = "deepseek-v4-pro"; +const ZEN_BASE = "https://opencode.ai/inference/openai/v1"; + +describe( + "host planes · a request-headers contributor runs on the planes the plugin serves (tier B, OC4)", + { timeout: 30_000 }, + () => { + it("is called once per call with pi-ai's frozen request, sees the plugin's session header, and its own header reaches the wire", async () => { + const seen: unknown[] = []; + let sawSession: string | null = null; + offline(); + tierB = await bootTierB({ + credentials: fakeCredentials({ refs: { OPENCODE_API_KEY: "k" } }), + prepare: (root) => { + root.on( + "llm-pi-ai/request-headers" as never, + ((request: unknown, headers: Headers, next: () => Headers) => { + seen.push(request); + sawSession = headers.get("x-opencode-session"); + headers.set("x-contributor", "1"); + headers.set("x-opencode-project", "from-listener"); + return next(); + }) as never + ); + }, + providers: { + opencode: { apiKeyEnv: "OPENCODE_API_KEY", models: [{ id: MODEL }] }, + }, + }); + await waitForPlaneOwner(tierB.llm, ["opencode"]); + const before = wire.requests.length; + await drainStream(tierB.llm, "opencode", MODEL, { + sessionId: "oc4-session", + }); + const sent = wire.requests + .slice(before) + .filter((request) => !request.url.startsWith("https://models.")); + expect(seen).toHaveLength(1); + const [request] = seen as Record[]; + expect(Object.isFrozen(request)).toBe(true); + expect(request?.provider).toBe("opencode"); + expect(request?.model).toBe(MODEL); + expect(request?.sessionId).toBe("oc4-session"); + expect(request?.baseURL).toBe(ZEN_BASE); + expect(sawSession).toBe(openCodeSessionIdFor("oc4-session")); + expect(sent).toHaveLength(1); + expect(sent[0]?.headers["x-contributor"]).toBe("1"); + expect(sent[0]?.headers["x-opencode-project"]).toBe("from-listener"); + expect(sent[0]?.headers["x-opencode-session"]).toBe( + openCodeSessionIdFor("oc4-session") + ); + }); + + it("a contributor that throws fails the turn with REQUEST_HEADERS and sends nothing, as on pi-ai's own routes", async () => { + offline(); + tierB = await bootTierB({ + credentials: fakeCredentials({ refs: { OPENCODE_API_KEY: "k" } }), + prepare: (root) => { + root.on( + "llm-pi-ai/request-headers" as never, + (() => { + throw new Error("policy"); + }) as never + ); + }, + providers: { + opencode: { apiKeyEnv: "OPENCODE_API_KEY", models: [{ id: MODEL }] }, + }, + }); + await waitForPlaneOwner(tierB.llm, ["opencode"]); + const before = wire.requests.length; + const drained = await drainStream(tierB.llm, "opencode", MODEL); + const sent = wire.requests + .slice(before) + .filter((request) => !request.url.startsWith("https://models.")); + expect(drained.finish?.code).toBe("REQUEST_HEADERS"); + expect(sent).toEqual([]); + }); + } +); + +describe( + "host planes · the plane headers are set per call, with the fetch patch out of the path (tier A, OC5)", + { timeout: 30_000 }, + () => { + /** + * One characterized model per protocol on Zen, and one Go row, each with + * the path its protocol posts to: asserted on the request, so a catalog + * move of an id cannot quietly drop a protocol from the table. + */ + const ROWS = [ + ["opencode", "deepseek-v4-pro", "/chat/completions"], + ["opencode", "gpt-5.4", "/responses"], + ["opencode", "claude-haiku-5-5", "/messages"], + ["opencode", "gemini-3-flash", ":streamGenerateContent"], + ["opencode-go", "minimax-m3", "/messages"], + ] as const; + + it.each(ROWS)( + "%s/%s (%s) carries the derived session id and the plane headers", + async (route, model, path) => { + offline(); + tierA = await mountTierA({ + credentials: fakeCredentials({ + refs: { OPENCODE_API_KEY: "k", OPENCODE_GO_API_KEY: "g" }, + }), + plugin: {}, + providers: { + opencode: { + apiKeyEnv: "OPENCODE_API_KEY", + models: ROWS.filter(([plane]) => plane === "opencode").map( + ([, id]) => ({ id }) + ), + }, + "opencode-go": { + apiKeyEnv: "OPENCODE_GO_API_KEY", + models: [{ id: "minimax-m3" }], + }, + }, + }); + await waitForPlaneOwner(tierA.llm); + // Out of the path: a recorder that never calls through to the patch. + const recorder = recordingFetch(); + vi.stubGlobal("fetch", recorder.fetch); + await drainStream(tierA.llm, route, model, { sessionId: "oc5" }); + const sent = recorder.requests.filter( + (request) => !request.url.startsWith("https://models.") + ); + expect(sent).toHaveLength(1); + expect(new URL(sent[0]?.url ?? "").pathname, sent[0]?.url).toMatch( + new RegExp(`${path.replace(".", "\\.")}$`, "u") + ); + const headers = sent[0]?.headers ?? {}; + const derived = openCodeSessionIdFor("oc5"); + expect(headers["x-opencode-session"]).toBe(derived); + expect(headers["x-opencode-session-id"]).toBe(derived); + expect(headers["x-opencode-client"]).toBe(DEFAULT_ORIGIN_CLIENT); + expect(headers["x-opencode-project"]).toBe("global"); + // L4, a characterization rather than a decision (P-R2 measured + // nothing; carried to P10a): a minted `msg_` id, sent on every + // protocol. Dropping it is this line and `planeHeadersFor`. + expect(headers["x-opencode-request"]).toMatch( + /^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/u + ); + expect(headers["x-session-affinity"]).toBeUndefined(); + } + ); + } +); diff --git a/test/host-planes.test.ts b/test/host-planes.test.ts index a5987e4..84da9a8 100644 --- a/test/host-planes.test.ts +++ b/test/host-planes.test.ts @@ -56,7 +56,6 @@ import { } from "./support/host.ts"; import { apply, - clearCapturedApiKeys, Config, inject, LEGACY_NAME, @@ -77,7 +76,6 @@ afterEach(async () => { } finally { tierA = undefined; tierB = undefined; - clearCapturedApiKeys(); vi.restoreAllMocks(); vi.unstubAllGlobals(); } diff --git a/test/keyed-probes.test.ts b/test/keyed-probes.test.ts index 2012de3..52c1e54 100644 --- a/test/keyed-probes.test.ts +++ b/test/keyed-probes.test.ts @@ -20,7 +20,7 @@ import { AsyncLocalStorage } from "node:async_hooks"; import { readdirSync, readFileSync } from "node:fs"; import { attributionHeaders } from "@deepseek-ai/dsh-llm"; -import { afterEach, describe, expect, it } from "vitest"; +import { describe, expect, it } from "vitest"; import { handleGatewayRequest } from "./mock/opencode-gateway.ts"; import { @@ -61,7 +61,6 @@ import { type ActiveTurnState, authHeaderFor, type CatalogModelSpec, - clearCapturedApiKeys, CONFIG_DEFAULTS, isOpenCodeMessageId, isOpenCodeSessionId, @@ -114,11 +113,6 @@ const GO = [ spec("go-gemini", "@ai-sdk/google"), ]; -// The fetch-patch case below captures the key it sends, process-wide. -afterEach(() => { - clearCapturedApiKeys(); -}); - describe("keyed probes · the tier", () => { it.each([ [undefined, "full"], diff --git a/test/lifecycle.test.ts b/test/lifecycle.test.ts index 9967460..312f903 100644 --- a/test/lifecycle.test.ts +++ b/test/lifecycle.test.ts @@ -17,7 +17,7 @@ */ import { AsyncLocalStorage } from "node:async_hooks"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, readFile, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -33,7 +33,9 @@ import { } from "./support/composition.ts"; import { offlineFetch } from "./support/offline.ts"; import { + type ActiveTurnState, apply, + callHeadersFor, findModelSpecOn, getSessionUsage, inspectPatch, @@ -224,13 +226,10 @@ describe("apply (plugin lifecycle)", () => { ); await second.dispose(); - // KNOWN_DEFECT P6: disposing the first activation while the second's patch - // is on top skips the first's restore (it restores only while current), - // and the second then restores to the first's patch — which outlives both. - // P6 flips this assertion; until then the case owns the stub underneath - // and removes it, so the leftover cannot reach the next case. - expect(globalThis.fetch?.name, "KNOWN_DEFECT P6").toBe(PATCHED_FETCH); - vi.unstubAllGlobals(); + // Disposing the first activation while the second's patch is on top turns + // the first into a pass-through link, and the second's restore unwinds + // through it to the fetch that was there before either. + expect(globalThis.fetch).toBe(replacementFetch); }); it("a reload keeps every remote service reachable", async () => { @@ -493,8 +492,9 @@ describe("apply (plugin lifecycle)", () => { ]); const binding = usage().typertRemote; - // Latest first, so the fetch patches unwind cleanly (the other order is - // P6's). The service is the same one, now reading the remaining row's. + // Latest first (either order unwinds the fetch patches since P6, + // `src/host/global-fetch.ts`). The service is the same one, now reading + // the remaining row's. urls.length = 0; await second.dispose(); expect(usage().typertRemote, "the same service").toBe(binding); @@ -710,12 +710,11 @@ describe("apply (plugin lifecycle)", () => { } }); - it("three activations, the middle one disposed first: the remaining one warns though its patch runs (KNOWN_DEFECT P6)", async () => { - // pC wraps pB wraps pA. Disposing B leaves pC current; disposing C then - // restores the fetch C wrapped, the disposed pB, which no live activation - // holds. pB still calls through to pA, so A's turn carries its header, - // but A's predicate reads pB as a replacement and warns (L1). + it("three activations, the middle one disposed first: the remaining one's patch is current and it does not warn", async () => { + // pC wraps pB wraps pA. Disposing B leaves pB as a pass-through link under + // pC; disposing C then unwinds through pB to pA, which is A's own patch. echoHeaders(); + const stub = globalThis.fetch; const first = await mountPlugin(); const second = await mountPlugin({ ctx: first.ctx }); const third = await mountPlugin({ ctx: first.ctx }); @@ -731,22 +730,53 @@ describe("apply (plugin lifecycle)", () => { expect((headers as Record)["x-opencode-session"]).toBe( openCodeSessionIdFor("l1-three") ); - // KNOWN_DEFECT P6: the stale restore put a disposed patch back, so this - // reads one warning; P6's chain-aware restore flips it to none. expect( first .lines() - .filter((line) => line.includes("globalThis.fetch is no longer")), - "KNOWN_DEFECT P6" - ).toHaveLength(1); + .filter((line) => line.includes("globalThis.fetch is no longer")) + ).toHaveLength(0); await first.fiber.dispose(); - // The disposed pB outlives every activation (the same defect); the case - // owns the stub underneath and removes it, so the leftover cannot reach - // the next case. - expect(globalThis.fetch?.name, "KNOWN_DEFECT P6").toBe(PATCHED_FETCH); - vi.unstubAllGlobals(); + expect(globalThis.fetch).toBe(stub); }); + it.each([ + ["the earlier first", "first"], + ["the later first", "second"], + ] as const)( + "apply A, apply B, dispose A and B (%s) ends at the fetch that was there", + async (_order, disposedFirst) => { + vi.stubGlobal("fetch", replacementFetch); + const tmpDir = await mkdtemp(path.join(tmpdir(), "dsh-opencode-order-")); + try { + const fileA = path.join(tmpDir, "a.jsonl"); + const fileB = path.join(tmpDir, "b.jsonl"); + const a = await mountPlugin({ config: { debugFile: fileA } }); + const b = await mountPlugin({ + config: { debugFile: fileB }, + ctx: a.ctx, + }); + const [early, late] = disposedFirst === "first" ? [a, b] : [b, a]; + await early.fiber.dispose(); + if (disposedFirst === "first") { + // B's patch still runs, and A's link under it passes through: a + // claimed request is recorded by B and never by A. + await globalThis.fetch( + "https://opencode.ai/zen/v1/chat/completions", + { body: "{}", method: "POST" } + ); + const content = await waitForFileContent(fileB); + expect(content).toContain('"claimed":true'); + const written = await readFile(fileA, "utf-8").catch(() => ""); + expect(written).not.toContain('"claimed":true'); + } + await late.fiber.dispose(); + expect(globalThis.fetch).toBe(replacementFetch); + } finally { + await rm(tmpDir, { force: true, recursive: true }); + } + } + ); + it("apply waits for the remote services' reports before it settles", async () => { // cordis waits for `apply`'s promise; the services' reports are part of // it, so a mount still loading keeps the activation pending and its @@ -1246,3 +1276,82 @@ describe("apply (plugin lifecycle)", () => { ).toBe(openCodeSessionIdFor("explicit-parent")); }); }); + +describe("callHeadersFor · the plane headers the adapter writes per call (OC5)", () => { + const SES = openCodeSessionIdFor("per-call"); + const PARENT = openCodeSessionIdFor("per-call-parent"); + const MSG = "msg_0123456789abCCCCCCCCCCCCCC"; + + /** The headers one call writes inside `state`, and the state after it. */ + const written = ( + state: ActiveTurnState | undefined, + config = resolveConfig() + ): { + headers: Record; + state: ActiveTurnState | undefined; + } => { + const als = new AsyncLocalStorage(); + const headers = new Headers({ "x-profile": "1" }); + const write = callHeadersFor(als, config); + if (state === undefined) { + write(headers); + } else { + als.run(state, () => { + write(headers); + }); + } + return { headers: Object.fromEntries(headers), state }; + }; + + it("writes the turn's plane headers from the one table, and marks the turn", () => { + const { headers, state } = written({ + parentValue: PARENT, + project: "repo", + provider: "opencode", + requestValue: MSG, + value: SES, + }); + expect(headers).toEqual({ + "x-opencode-client": "cli", + "x-opencode-parent-session-id": PARENT, + "x-opencode-project": "repo", + "x-opencode-request": MSG, + "x-opencode-session": SES, + "x-opencode-session-id": SES, + "x-parent-session-id": PARENT, + "x-profile": "1", + }); + expect(state?.perCall).toBe(true); + }); + + it("follows the settings: the org, no project, no origin headers", () => { + const base = { provider: "opencode-go", value: SES } as ActiveTurnState; + expect( + written({ ...base }, resolveConfig({ credentialOrg: "wrk_1" })).headers[ + "x-opencode-org-id" + ] + ).toBe("wrk_1"); + expect( + written({ ...base }, resolveConfig({ injectProject: false })).headers + ).not.toHaveProperty("x-opencode-project"); + expect( + written({ ...base, project: "" }).headers["x-opencode-project"] + ).toBe("global"); + const bare = written( + { ...base }, + resolveConfig({ injectOriginHeaders: false }) + ); + expect(Object.keys(bare.headers).toSorted()).toEqual([ + "x-opencode-session", + "x-opencode-session-id", + "x-profile", + ]); + }); + + it("writes nothing outside a turn the plugin decorated, or on another plugin's turn", () => { + expect(written(undefined).headers).toEqual({ "x-profile": "1" }); + const foreign = written({ foreign: true, provider: "opencode", value: "" }); + expect(foreign.headers).toEqual({ "x-profile": "1" }); + expect(foreign.state?.perCall).toBeUndefined(); + }); +}); diff --git a/test/mock/plane-dispatch.mock.ts b/test/mock/plane-dispatch.mock.ts index e67f211..4645857 100644 --- a/test/mock/plane-dispatch.mock.ts +++ b/test/mock/plane-dispatch.mock.ts @@ -40,11 +40,7 @@ import { type TierA, waitForPlaneOwner, } from "../support/host.ts"; -import { - clearCapturedApiKeys, - headerValueFor, - OPENCODE_ZEN_CATALOG, -} from "../support/src.ts"; +import { headerValueFor, OPENCODE_ZEN_CATALOG } from "../support/src.ts"; import { usesCatalogThinkingLevels } from "../support/thinking-levels.ts"; import { urlOf } from "../test-helpers.ts"; import { startMockGateway, type MockGateway } from "./gateway-server.ts"; @@ -224,7 +220,6 @@ afterAll(async () => { beforeEach(() => { gateway.requests.length = 0; - clearCapturedApiKeys(); }); afterEach(async () => { diff --git a/test/mock/plane-refusals.mock.ts b/test/mock/plane-refusals.mock.ts index 7547934..a363719 100644 --- a/test/mock/plane-refusals.mock.ts +++ b/test/mock/plane-refusals.mock.ts @@ -42,11 +42,7 @@ import { type TierA, waitForPlaneOwner, } from "../support/host.ts"; -import { - clearCapturedApiKeys, - FREE_TIER_CODE, - MODEL_UNAVAILABLE_CODE, -} from "../support/src.ts"; +import { FREE_TIER_CODE, MODEL_UNAVAILABLE_CODE } from "../support/src.ts"; import { urlOf } from "../test-helpers.ts"; import { startMockGateway, type MockGateway } from "./gateway-server.ts"; import { fixtureModel, GO_KEY, ZEN_KEY } from "./helpers.ts"; @@ -220,7 +216,6 @@ afterAll(async () => { beforeEach(() => { gateway.requests.length = 0; refusal = undefined; - clearCapturedApiKeys(); }); afterEach(() => { diff --git a/test/mock/protocol-compat.mock.ts b/test/mock/protocol-compat.mock.ts index 338e9ac..55f05b9 100644 --- a/test/mock/protocol-compat.mock.ts +++ b/test/mock/protocol-compat.mock.ts @@ -34,7 +34,6 @@ import { import { OPENCODE_UA, SESSION_HEADER, - clearCapturedApiKeys, OPENCODE_FAMILY_API, planeModelFor, resolveConfig, @@ -77,7 +76,6 @@ afterAll(async () => { beforeEach(() => { gateway.requests.length = 0; - clearCapturedApiKeys(); }); afterEach(() => { diff --git a/test/mock/protocol-endpoints.mock.ts b/test/mock/protocol-endpoints.mock.ts index 36fd03e..1f9e4f0 100644 --- a/test/mock/protocol-endpoints.mock.ts +++ b/test/mock/protocol-endpoints.mock.ts @@ -42,7 +42,6 @@ import { } from "../support/keyless-matrix.ts"; import { ANTHROPIC_VERSION, - clearCapturedApiKeys, DEFAULT_USAGE_BASE_URL, LEGACY_PLANE_API, OPENCODE_FAMILY_API, @@ -83,7 +82,6 @@ afterAll(async () => { beforeEach(() => { gateway.requests.length = 0; - clearCapturedApiKeys(); vi.stubEnv("OPENCODE_API_KEY", ZEN_KEY); vi.stubEnv("OPENCODE_GO_API_KEY", GO_KEY); }); diff --git a/test/mock/request-shapes.mock.ts b/test/mock/request-shapes.mock.ts index 1375f5d..50c8db6 100644 --- a/test/mock/request-shapes.mock.ts +++ b/test/mock/request-shapes.mock.ts @@ -34,7 +34,6 @@ import { type ResolvedPluginConfig, SESSION_AFFINITY_HEADER, SESSION_HEADER, - clearCapturedApiKeys, DUMMY_READ_TOOL_FUNCTION, isOpenCodeSessionId, newOpenCodeMessageId, @@ -79,7 +78,6 @@ afterAll(async () => { beforeEach(() => { gateway.requests.length = 0; forced = undefined; - clearCapturedApiKeys(); vi.stubEnv("OPENCODE_API_KEY", ZEN_KEY); vi.stubEnv("OPENCODE_GO_API_KEY", GO_KEY); }); @@ -467,7 +465,6 @@ describe("keyless: free models still answer", () => { // so the request must go out with no credential and still succeed. vi.stubEnv("OPENCODE_API_KEY", ""); vi.stubEnv("OPENCODE_GO_API_KEY", ""); - clearCapturedApiKeys(); const response = await als.run(sessionTurn(), () => post( diff --git a/test/plane-provider.test.ts b/test/plane-provider.test.ts index e5f505e..e4ad681 100644 --- a/test/plane-provider.test.ts +++ b/test/plane-provider.test.ts @@ -34,6 +34,7 @@ import { planeApiKeyResolver, planeAuth, planeProfileFor, + planeRequestHeaders, relabelEfforts, } from "./support/src.ts"; @@ -804,3 +805,95 @@ describe("plane-provider · buildPlaneProvider", () => { } }); }); + +describe("plane-provider · planeRequestHeaders (OC4, OC5)", () => { + /** A context whose `waterfall` records its arguments and runs the last one. */ + const recordingContext = () => { + const calls: unknown[][] = []; + return { + calls, + ctx: { + waterfall: (...args: unknown[]) => { + calls.push(args); + const next = args.at(-1) as () => unknown; + return next(); + }, + }, + }; + }; + + it("shapes the headers, then runs the host's request-headers waterfall over them", () => { + const { calls, ctx } = recordingContext(); + const request = Object.freeze({ model: "m", provider: "opencode" }); + const headers = new Headers({ "x-profile": "1" }); + const prepare = planeRequestHeaders(ctx, (shaped) => { + shaped.set("x-opencode-session", "ses_x"); + }); + const answered = prepare(request, headers); + expect(answered).toBe(headers); + expect(headers.get("x-opencode-session")).toBe("ses_x"); + expect(headers.get("x-profile")).toBe("1"); + expect(calls).toHaveLength(1); + const [event, passed, carried, next] = calls[0] ?? []; + expect(event).toBe("llm-pi-ai/request-headers"); + expect(passed).toBe(request); + expect(carried).toBe(headers); + expect((next as () => unknown)()).toBe(headers); + }); + + it("answers the shaped headers themselves where the context has no waterfall", () => { + const headers = new Headers(); + expect(planeRequestHeaders({}, (h) => h.set("a", "1"))({}, headers)).toBe( + headers + ); + expect(headers.get("a")).toBe("1"); + expect(planeRequestHeaders(undefined)({}, headers)).toBe(headers); + expect(planeRequestHeaders({ waterfall: "no" })({}, headers)).toBe(headers); + }); + + it("never throws of its own: a shape that throws leaves the headers as they were, and the waterfall still runs", () => { + const { calls, ctx } = recordingContext(); + const headers = new Headers({ "x-profile": "1" }); + const answered = planeRequestHeaders(ctx, () => { + throw new Error("shape"); + })({}, headers); + expect(answered).toBe(headers); + expect([...headers]).toEqual([["x-profile", "1"]]); + expect(calls).toHaveLength(1); + }); + + it("a contributor's throw propagates, and so does an answer that is not Headers, as on pi-ai's own routes", () => { + const throwing = { + waterfall: () => { + throw new Error("policy"); + }, + }; + expect(() => planeRequestHeaders(throwing)({}, new Headers())).toThrow( + "policy" + ); + const wrong = { waterfall: () => ({ set: () => null }) }; + expect(() => planeRequestHeaders(wrong)({}, new Headers())).toThrow( + TypeError + ); + }); + + it("createPlaneAdapter hands pi-ai the option when given one, and leaves it absent otherwise", async () => { + const host = await modules(); + const base = { + auth: planeAuth({}, host.piAi.recordKeyFor, host.libraries), + effortNames: () => ({}), + modules: host, + profiles: () => new Map(), + resolveApiKey: async () => "k", + }; + const prepareHeaders = planeRequestHeaders({}); + const withOption = createPlaneAdapter({ ...base, prepareHeaders }) as { + config: Record; + }; + expect(withOption.config.prepareHeaders).toBe(prepareHeaders); + const without = createPlaneAdapter(base) as { + config: Record; + }; + expect(Object.hasOwn(without.config, "prepareHeaders")).toBe(false); + }); +}); diff --git a/test/reload.test.ts b/test/reload.test.ts index cad7959..bb0b8f5 100644 --- a/test/reload.test.ts +++ b/test/reload.test.ts @@ -565,8 +565,9 @@ describe("reload · through apply()", { timeout: 15_000 }, () => { }); it("apply() twice, the first disposed first: every host method the plugin patched is restored exactly", async () => { - // The global fetch is patched too, and stacks the same way; it is not a host - // service method and is not asserted here (P6 owns it). + // The global fetch is patched too, but not through `patchMethod`: it is not + // a host service method, and its installer (`src/host/global-fetch.ts`) + // unwinds in any order; `test/global-fetch.test.ts` holds that. vi.stubGlobal("fetch", vi.fn()); vi.spyOn(console, "info").mockImplementation(() => { // Silenced: the activation line. diff --git a/test/request-shape.test.ts b/test/request-shape.test.ts index 78ba3f7..10c0ee2 100644 --- a/test/request-shape.test.ts +++ b/test/request-shape.test.ts @@ -18,6 +18,8 @@ import { isGoPlaneUrl, isZenProvider, modelIdOf, + planeHeadersFor, + pluginMarkerOn, requestUrlOf, toolNamesOf, } from "./support/src.ts"; @@ -275,3 +277,80 @@ describe("request-shape · constants", () => { expect(ANTHROPIC_VERSION).toBe("2023-06-01"); }); }); + +describe("request-shape · pluginMarkerOn (OC2)", () => { + it("reads the marker's value in any case, an empty one included", () => { + expect(pluginMarkerOn(new Headers({ "X-OpenCode-Plugin": "x/1" }))).toBe( + "x/1" + ); + expect(pluginMarkerOn(new Headers({ "x-opencode-plugin": "" }))).toBe(""); + expect(pluginMarkerOn(new Headers())).toBeUndefined(); + }); +}); + +describe("request-shape · planeHeadersFor, the one table of plane headers", () => { + const SES = "ses_0123456789abAAAAAAAAAAAAAA"; + const PARENT = "ses_0123456789abBBBBBBBBBBBBBB"; + const MSG = "msg_0123456789abCCCCCCCCCCCCCC"; + + it("a plane: the two session headers, and no affinity pair", () => { + expect(planeHeadersFor({ relay: false, session: SES })).toEqual([ + ["x-opencode-session-id", SES], + ["x-opencode-session", SES], + ]); + }); + + it("a relay: the affinity pair after them", () => { + expect(planeHeadersFor({ relay: true, session: SES })).toEqual([ + ["x-opencode-session-id", SES], + ["x-opencode-session", SES], + ["x-session-affinity", SES], + ["x-session-id", SES], + ]); + }); + + it("everything, in write order: parent pair, org, then the origin headers", () => { + expect( + planeHeadersFor({ + org: "wrk_1", + origin: { client: "cli", project: "p", request: MSG }, + parent: PARENT, + relay: false, + session: SES, + }) + ).toEqual([ + ["x-opencode-session-id", SES], + ["x-opencode-session", SES], + ["x-opencode-parent-session-id", PARENT], + ["x-parent-session-id", PARENT], + ["x-opencode-org-id", "wrk_1"], + ["x-opencode-client", "cli"], + ["x-opencode-request", MSG], + ["x-opencode-project", "p"], + ]); + }); + + it("drops a blank org, a request id not in the client's shape, and an absent project; no origin means none of the three", () => { + expect( + planeHeadersFor({ + org: "", + origin: { client: "cli", request: "not-a-message-id" }, + relay: false, + session: SES, + }).map(([name]) => name) + ).toEqual([ + "x-opencode-session-id", + "x-opencode-session", + "x-opencode-client", + ]); + expect( + planeHeadersFor({ org: "wrk_1", relay: false, session: SES }).map( + ([name]) => name + ) + ).toEqual([ + "x-opencode-session-id", + "x-opencode-session", + "x-opencode-org-id", + ]); + }); +}); diff --git a/test/route-claim.test.ts b/test/route-claim.test.ts index 7441855..7495461 100644 --- a/test/route-claim.test.ts +++ b/test/route-claim.test.ts @@ -256,6 +256,38 @@ describe("route-claim · Settings' fetch follows the claim's engagement", () => expect(answered).not.toStrictEqual(mergeDiscoveredModels(pis, "zen")); }); + it("builds the plane adapter with pi-ai's prepareHeaders, which writes the seam's call headers (OC4, OC5)", async () => { + useTestModules(); + let held: Record = { deepseek: {}, opencode: zen }; + const pi = newPiFiber(); + Object.defineProperty(pi, "effectiveConfig", { + get: () => ({ providers: { get: () => held } }), + }); + const host = standIn({ fibers: () => [pi] }); + pi.restart = vi.fn(async () => { + const resolved = host.waterfall(pi, () => pi.rawConfig) as { + providers: Record; + }; + held = resolved.providers; + }); + const callHeaders = vi.fn((headers: Headers) => { + headers.set("x-opencode-session", "ses_from_the_seam"); + }); + const claim = installRouteClaim(host.ctx, config, { callHeaders }); + await claim.mounted; + await flush(); + const adapter = host.llm.registerAdapter.mock.calls[0]?.[1] as { + config: { + prepareHeaders?: (request: unknown, headers: Headers) => Headers; + }; + }; + expect(typeof adapter.config.prepareHeaders).toBe("function"); + const headers = new Headers(); + expect(adapter.config.prepareHeaders?.({}, headers)).toBe(headers); + expect(callHeaders).toHaveBeenCalledWith(headers); + expect(headers.get("x-opencode-session")).toBe("ses_from_the_seam"); + }); + it("a handover's window: while the newly served new-core row's restart is in flight, claiming() stays true and Settings' fetch is complemented before it unloads and the plane's catalog alone while it does, as in the mount's restart", async () => { useTestModules(); // The served row resolved without its plane (the listener was in place). diff --git a/test/support/composition.ts b/test/support/composition.ts index 7ce9767..ae85ed3 100644 --- a/test/support/composition.ts +++ b/test/support/composition.ts @@ -110,9 +110,9 @@ export const mountPlugin = async ( /** * Dispose every fiber {@link mountPlugin} mounted, latest first, so the - * patched `fetch` never leaks into the next case. Latest first is the order - * that unwinds nested patches cleanly; the other order is P6's open defect - * (an earlier activation's patch outlives two overlapping ones). + * patched `fetch` never leaks into the next case. Either order unwinds nested + * patches to the fetch that was there (`src/host/global-fetch.ts`, P6); + * latest first is the one a reader expects. */ export const disposeMounted = async (): Promise => { const fibers = [...live].toReversed(); diff --git a/test/support/host.ts b/test/support/host.ts index 369f5b8..6534af4 100644 --- a/test/support/host.ts +++ b/test/support/host.ts @@ -52,11 +52,13 @@ * snapshot ({@link fakeLaunchEnvironment}) on the root, which is where pi-ai * looks first (`launchEnvironmentOf` reads `ctx.get("launchEnvironment")` * before it falls back to `process.env`). The plugin itself still reads - * `process.env.OPENCODE_API_KEY`/`OPENCODE_GO_API_KEY` in its fetch patch and - * its quota discovery (`src/fetch-patch.ts`, `src/go-discovery.ts`), so tier B blanks either - * one a contributor's shell exports for the life of the boot and restores it - * on dispose: the suite measures the keyless deployment whatever the shell - * holds. + * `process.env.OPENCODE_API_KEY`/`OPENCODE_GO_API_KEY` in its fill and its + * quota discovery (`src/credentials.ts`, `src/go-discovery.ts`), so tier B + * blanks either one that is set for the life of the boot and restores it on + * dispose: the suite measures the keyless deployment whatever the shell + * holds. Under the unit and mock configs `test/support/offline.ts` has already + * unset both, so this is the second line, for a runner without that setup + * file. * * **Offline.** {@link recordingFetch} answers every `opencode.ai` request with a * 401 and refuses every other host. Install it with `vi.stubGlobal("fetch", …)` @@ -1604,7 +1606,7 @@ export const AMBIENT_KEYS = [ ] as const; /** - * Blank the keys the plugin reads directly (`src/fetch-patch.ts`, + * Blank the keys the plugin reads directly (`src/credentials.ts`, * `src/go-discovery.ts`) for the life of one boot, so a contributor's exported * key cannot turn the keyless rows into keyed ones. An empty value is what the * plugin reads as "no key". Only a key that IS set is touched, and the diff --git a/test/support/offline.ts b/test/support/offline.ts index 68f6a9a..79a4ca0 100644 --- a/test/support/offline.ts +++ b/test/support/offline.ts @@ -1,5 +1,6 @@ /** - * Keep the unit and mock suites off the network. + * Keep the unit and mock suites off the network, and off the developer's + * exported OpenCode keys. * * Both are documented as offline, and they were not: every `getLive*Catalog` * read on a stale catalog — which is every read in a fresh test process — @@ -46,3 +47,14 @@ export const offlineFetch = async ( }; globalThis.fetch = offlineFetch as typeof fetch; + +/** + * Off the developer's keys as well as the network: a key exported in the + * shell that runs the suite would answer every case that expects no declared + * credential (the fill's placeholder, the no-credential report, the meter's + * `configured` step). Unset once per file, before any case runs; a case that + * wants a key sets or stubs its own. CI exports neither in the unit run, so + * this changes nothing there. + */ +delete process.env.OPENCODE_API_KEY; +delete process.env.OPENCODE_GO_API_KEY; diff --git a/test/support/reset-process-state.ts b/test/support/reset-process-state.ts index 781347b..a7e376d 100644 --- a/test/support/reset-process-state.ts +++ b/test/support/reset-process-state.ts @@ -1,14 +1,18 @@ /** * Reset the plugin's process-wide stores after every test. * - * Vitest isolates FILES, not the tests inside one, and the plugin keeps three - * stores at module level for the life of the process: the keys the fetch patch - * captured, the per-session spend, and the live catalog. A case that leaves any - * of them behind makes the next case's answer depend on run order — a captured - * key turns a "no credential" case into a "credential resolved" one, a recorded - * session becomes the meter's fallback reading, and a fixture refresh changes - * every catalog count after it. Measured: with the suite shuffled, seeds 42 and - * 1234 failed three catalog cases on exactly that. + * Vitest isolates FILES, not the tests inside one, and the plugin keeps two + * stores at module level for the life of the process: the per-session spend, + * and the live catalog. A case that leaves either behind makes the next case's + * answer depend on run order — a recorded session becomes the meter's + * fallback reading, and a fixture refresh changes every catalog count after + * it. Measured: with the suite shuffled, seeds 42 and 1234 failed three + * catalog cases on exactly that. The keys the fetch patch captures are kept + * per root (`captureStoreFor`), so a case's fresh `Context` is a fresh store + * and there is nothing to clear. The fetch installer's link chain + * (`src/host/global-fetch.ts`) needs no reset either: its links are compared + * by identity against `globalThis.fetch` and unwound by their own disposers, + * so a leftover link answers nothing another case reads. * * `pnpm run test:shuffle` runs the suite in a random order to keep it that way. * @@ -19,12 +23,10 @@ */ import { afterEach } from "vitest"; -import { clearCapturedApiKeys } from "../../src/key-capture.ts"; import { resetCatalogState } from "../../src/models-catalog.ts"; import { clearSessionUsageStore } from "../../src/session-cost.ts"; afterEach(() => { - clearCapturedApiKeys(); clearSessionUsageStore(); resetCatalogState(); }); diff --git a/test/support/src.ts b/test/support/src.ts index 32d318c..8714b90 100644 --- a/test/support/src.ts +++ b/test/support/src.ts @@ -61,12 +61,14 @@ export { readStringList, unwrapNode, } from "../../src/config-values.ts"; +export type { KeySourcePolicy } from "../../src/config-values.ts"; // config.ts export { Config, CONFIG_DEFAULTS, DEFAULT_FREE_MODEL_MARKER, + DEFAULT_ORIGIN_CLIENT, DEFAULT_USAGE_BASE_URL, DEFAULT_USAGE_KEY_ENV, resolveConfig, @@ -93,6 +95,20 @@ export type { PiAiModule, } from "../../src/cordis-context.ts"; +// credentials.ts +export { + captureStoreFor, + createCaptureStore, + createCredentials, + resolveOpencodeStoreKey, +} from "../../src/credentials.ts"; +export type { + CaptureStore, + CredentialInputs, + FetchCredentials, + FillDecision, +} from "../../src/credentials.ts"; + // debug.ts export { recordDebug } from "../../src/debug.ts"; @@ -111,7 +127,6 @@ export { resolveGoApiKey, resolveGoBaseURL, resolveGoKeyForRef, - resolveOpencodeStoreKey, resolveZenCreditInfo, toGoBaseURL, } from "../../src/go-discovery.ts"; @@ -154,9 +169,13 @@ export { hostError, planeApiKeyResolver, planeAuth, + planeRequestHeaders, relabelEfforts, } from "../../src/host/plane-provider.ts"; +// host/global-fetch.ts +export { installGlobalFetch } from "../../src/host/global-fetch.ts"; + // host/route-claim.ts export { installRouteClaim } from "../../src/host/route-claim.ts"; @@ -183,16 +202,12 @@ export { // key-capture.ts export { - clearCapturedApiKeys, extractApiKeyFromHeaders, - getCapturedApiKey, - isPlaceholderApiKey, - recordCapturedApiKey, tierForRequest, } from "../../src/key-capture.ts"; // lifecycle.ts -export { apply } from "../../src/lifecycle.ts"; +export { apply, callHeadersFor } from "../../src/lifecycle.ts"; // models-catalog.ts export { @@ -529,10 +544,33 @@ export { isGoPlaneUrl, isZenProvider, modelIdOf, + planeHeadersFor, + pluginMarkerOn, + projectHeaderOf, requestUrlOf, toolNamesOf, } from "../../src/utils/request-shape.ts"; +// utils/credential-policy.ts +export { + countsAsRefusal, + EVICT_AFTER, + FILL_ORDER, + firstUsable, + firstUsableAsync, + isPlaceholderApiKey, + mayCapture, + METER_ORDER, + needsFill, + PLACEHOLDER_API_KEYS, + strike, + usableKey, +} from "../../src/utils/credential-policy.ts"; +export type { + FillSource, + MeterSource, +} from "../../src/utils/credential-policy.ts"; + // utils/retry.ts export { backoffOver, retryUntilAnswered } from "../../src/utils/retry.ts"; export type { RetryOptions, RetryTimer } from "../../src/utils/retry.ts"; diff --git a/test/usage-service-credentials.test.ts b/test/usage-service-credentials.test.ts index 52c226b..90245d4 100644 --- a/test/usage-service-credentials.test.ts +++ b/test/usage-service-credentials.test.ts @@ -7,12 +7,12 @@ import { Context } from "@deepseek-ai/cordis"; import { afterEach, describe, expect, it, vi } from "vitest"; +import { disposeMounted, mountPlugin } from "./support/composition.ts"; import { withCredentials } from "./support/loader-rows.ts"; import { GoUsageService, - clearCapturedApiKeys, clearSessionUsageStore, - recordCapturedApiKey, + captureStoreFor, } from "./support/src.ts"; import { contextWithEntries, @@ -22,13 +22,14 @@ import { okBody, stubFetch, } from "./support/usage-fixture.ts"; -import { headerOf } from "./test-helpers.ts"; +import { collectUnknown, headerOf, urlOf } from "./test-helpers.ts"; -afterEach(() => { +afterEach(async () => { + await disposeMounted(); + vi.unstubAllEnvs(); vi.unstubAllGlobals(); delete process.env.OPENCODE_API_KEY; delete process.env.OPENCODE_GO_API_KEY; - clearCapturedApiKeys(); clearSessionUsageStore(); }); @@ -80,19 +81,25 @@ describe("GoUsageService credential failures", () => { // one; if the service ignored it, `request` setups would silently keep // polling with a stale credential. process.env.OPENCODE_GO_API_KEY = "sk-env-key"; - recordCapturedApiKey( - "sk-captured-key", - "opencode-go", - "https://opencode.ai/zen/go/v1/chat/completions" - ); + // One composition per service, each having seen the same key on a Go + // turn: the capture store is the root's, and a service is the root's too. + const seen = (): Context => { + const context = contextWithEntries([]); + captureStoreFor(context).record( + "sk-captured-key", + "opencode-go", + "https://opencode.ai/zen/go/v1/chat/completions" + ); + return context; + }; const pinned = stubFetch(() => new Response(okBody())); - await new GoUsageService(contextWithEntries([]), { + await new GoUsageService(seen(), { keySource: "configured", }).read(); expect(headerOf(pinned.init, "authorization")).toBe("Bearer sk-env-key"); const rotated = stubFetch(() => new Response(okBody())); - await new GoUsageService(contextWithEntries([]), { + await new GoUsageService(seen(), { keySource: "request", }).read(); expect(headerOf(rotated.init, "authorization")).toBe( @@ -164,3 +171,79 @@ describe("usage service: the read that a silent meter depends on", () => { expect(usage.quotaUnavailable ?? false).toBe(false); }); }); + +const GO_CHAT = `${GO_ENDPOINT}/chat/completions`; + +describe("the mounted meter and the capture store (P6: OC3, L8)", () => { + /** + * The meter the plugin mounts reads the key the fill learned on a decorated + * turn of the same root, and its own `/usage` poll is no evidence about + * that key: the usage endpoint refuses keys inference accepts, so its 401 + * never drops one (docs/credentials.md). Through the plugin as the Loader + * mounts it, the meter as `ctx.get("opencodeGoUsage")` answers it, and the + * patched `globalThis.fetch` the meter's own request goes through. + */ + it("reads the key a decorated Go turn sent, and two refused polls leave it in place", async () => { + vi.stubEnv("OPENCODE_API_KEY", ""); + vi.stubEnv("OPENCODE_GO_API_KEY", ""); + const sent: { url: string; authorization: string | null }[] = []; + vi.stubGlobal( + "fetch", + vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = urlOf(input); + sent.push({ + authorization: new Headers(init?.headers).get("authorization"), + url, + }); + return Response.json( + {}, + { status: url.endsWith("/usage") ? 401 : 200 } + ); + }) + ); + const { ctx } = await mountPlugin({ config: { usageEnabled: true } }); + const goTurn = async (bearer: string): Promise => { + const downstream = async function* downstream() { + await globalThis.fetch(GO_CHAT, { + body: JSON.stringify({ model: "meter-model" }), + headers: { authorization: `Bearer ${bearer}` }, + method: "POST", + }); + yield { type: "finish" }; + }; + await collectUnknown( + ( + ctx as unknown as { + waterfall: (event: string, ...args: unknown[]) => unknown; + } + ).waterfall( + "llm/stream", + { provider: "opencode-go", sessionId: "meter" }, + downstream + ) as AsyncIterable + ); + return sent.at(-1)?.authorization ?? null; + }; + const usage = ctx.get("opencodeGoUsage" as never) as unknown as { + read: () => Promise; + }; + // Nothing captured yet: the meter has no key and says so. + await expect(usage.read()).rejects.toThrow(/not configured/u); + expect(sent).toHaveLength(0); + + expect(await goTurn("sk-turn-go")).toBe("Bearer sk-turn-go"); + for (const _ of [1, 2]) { + // oxlint-disable-next-line no-await-in-loop -- the polls are sequential. + await expect(usage.read()).rejects.toThrow(); + expect(sent.at(-1)).toEqual({ + authorization: "Bearer sk-turn-go", + url: GO_USAGE_URL, + }); + } + // Two refused polls later, the key still fills a Go turn's placeholder, + // and the meter still reads it. + expect(await goTurn("unused")).toBe("Bearer sk-turn-go"); + await expect(usage.read()).rejects.toThrow(); + expect(sent.at(-1)?.authorization).toBe("Bearer sk-turn-go"); + }); +}); diff --git a/test/usage-service-failures.test.ts b/test/usage-service-failures.test.ts index 110ea21..1fac6a7 100644 --- a/test/usage-service-failures.test.ts +++ b/test/usage-service-failures.test.ts @@ -5,7 +5,7 @@ */ import { afterEach, describe, expect, it, vi } from "vitest"; -import { clearCapturedApiKeys, clearSessionUsageStore } from "./support/src.ts"; +import { clearSessionUsageStore } from "./support/src.ts"; import { failureOf, GO_USAGE_URL, @@ -18,7 +18,6 @@ afterEach(() => { vi.unstubAllGlobals(); delete process.env.OPENCODE_API_KEY; delete process.env.OPENCODE_GO_API_KEY; - clearCapturedApiKeys(); clearSessionUsageStore(); }); diff --git a/test/usage-service-readings.test.ts b/test/usage-service-readings.test.ts index a4d83c3..d8a298d 100644 --- a/test/usage-service-readings.test.ts +++ b/test/usage-service-readings.test.ts @@ -7,7 +7,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { freeZenModel } from "./support/catalogs.ts"; import { - clearCapturedApiKeys, clearSessionUsageStore, findModelSpecOn, GO_MODEL_LIMITS, @@ -46,7 +45,6 @@ afterEach(() => { vi.unstubAllGlobals(); delete process.env.OPENCODE_API_KEY; delete process.env.OPENCODE_GO_API_KEY; - clearCapturedApiKeys(); clearSessionUsageStore(); }); diff --git a/test/usage-service.test.ts b/test/usage-service.test.ts index fa0925d..67ad7e7 100644 --- a/test/usage-service.test.ts +++ b/test/usage-service.test.ts @@ -7,8 +7,9 @@ * typed failure the composer meter reacts to. * * Offline by construction: `fetch` is stubbed per case, the endpoint and the - * credential are injected, and the two pieces of ambient state a read consults - * (captured keys, session spend) are cleared after every case. + * credential are injected, and the ambient state a read consults (session + * spend) is cleared after every case; captured keys are kept per root, so a + * case's own context starts with none. * * This file holds the service's construction, the endpoint it builds and the * identity it sends; its siblings hold credential failures @@ -24,7 +25,6 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { GoUsageService, OPENCODE_PATCH_USER_AGENT, - clearCapturedApiKeys, clearSessionUsageStore, } from "./support/src.ts"; import { @@ -42,7 +42,6 @@ afterEach(() => { vi.unstubAllGlobals(); delete process.env.OPENCODE_API_KEY; delete process.env.OPENCODE_GO_API_KEY; - clearCapturedApiKeys(); clearSessionUsageStore(); }); diff --git a/test/usage.test.ts b/test/usage.test.ts index 153c68f..10a1f33 100644 --- a/test/usage.test.ts +++ b/test/usage.test.ts @@ -6,25 +6,30 @@ * @module test/usage.test */ -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { - clearCapturedApiKeys, + type CaptureStore, + createCaptureStore, extractApiKeyFromHeaders, - getCapturedApiKey, isPlaceholderApiKey, parseGoUsage, parseUsageQuery, - recordCapturedApiKey, tierForRequest, } from "./support/src.ts"; +/** A capture store of the case's own; the plugin keeps one per root. */ +let store: CaptureStore = createCaptureStore(); + +beforeEach(() => { + store = createCaptureStore(); +}); + afterEach(() => { vi.unstubAllGlobals(); delete process.env.OPENCODE_SESSION_ID; delete process.env.OPENCODE_GO_API_KEY; delete process.env.OPENCODE_API_KEY; - clearCapturedApiKeys(); }); describe("OpenCode Go Usage", () => { @@ -112,12 +117,12 @@ describe("OpenCode Go Usage", () => { }); it("never records a placeholder as a captured key", () => { - recordCapturedApiKey( + store.record( "sk-real-key-111", "opencode-go", "https://opencode.ai/zen/go/v1/chat/completions" ); - expect(getCapturedApiKey("opencode-go", "go")).toBe("sk-real-key-111"); + expect(store.get("opencode-go", "go")).toBe("sk-real-key-111"); // The adapter's dummy values must not overwrite a working key: capturing // one poisons every later lookup, which then re-injects the dummy. @@ -129,14 +134,14 @@ describe("OpenCode Go Usage", () => { " UNUSED ", ]) { expect(isPlaceholderApiKey(placeholder)).toBe(true); - recordCapturedApiKey( + store.record( placeholder, "opencode-go", "https://opencode.ai/zen/go/v1/chat/completions" ); } - expect(getCapturedApiKey("opencode-go", "go")).toBe("sk-real-key-111"); - expect(getCapturedApiKey(undefined, "go")).toBe("sk-real-key-111"); + expect(store.get("opencode-go", "go")).toBe("sk-real-key-111"); + expect(store.get(undefined, "go")).toBe("sk-real-key-111"); expect(isPlaceholderApiKey("sk-real-key-111")).toBe(false); expect(isPlaceholderApiKey("oc_sk_real")).toBe(false); @@ -160,21 +165,19 @@ describe("OpenCode Go Usage", () => { // The reproduction: read prefix-first, this key was filed under Zen. The // meter's Go lookup then missed it, and a Zen request carrying a // placeholder was handed the Go key. - recordCapturedApiKey( + store.record( "oc_sk_GOKEY_fixture", "opencode-go", "https://opencode.ai/zen/go/v1/chat/completions" ); - expect(getCapturedApiKey("opencode-go", "go")).toBe( - "oc_sk_GOKEY_fixture" - ); - expect(getCapturedApiKey(undefined, "zen")).toBeUndefined(); + expect(store.get("opencode-go", "go")).toBe("oc_sk_GOKEY_fixture"); + expect(store.get(undefined, "zen")).toBeUndefined(); }); it("does not claim a foreign sk- key for the Go account", () => { // An OpenAI key on a relay a deployment routes through the patch. Read by // prefix it was filed as Go and offered to every Go request. - recordCapturedApiKey( + store.record( "sk-openai-fixture", "my-relay", "https://relay.example/v1/chat/completions" @@ -183,7 +186,7 @@ describe("OpenCode Go Usage", () => { tierForRequest("https://relay.example/v1/chat/completions", "my-relay") ).toBe("unknown"); // Unknown stays answerable by route, as before, but is not filed by tier. - expect(getCapturedApiKey("my-relay")).toBe("sk-openai-fixture"); + expect(store.get("my-relay")).toBe("sk-openai-fixture"); }); it("trusts the URL above the provider route id", () => { diff --git a/vite.config.ts b/vite.config.ts index 8fba57e..b04804e 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -328,6 +328,30 @@ export default defineConfig({ functions: 100, lines: 99, }, + // The credential rules every decider shares, and the store and + // resolver over them (P6): every branch is a policy, a source, a + // capture gate or a strike, so all of them are covered. + "src/utils/credential-policy.ts": { + statements: 100, + branches: 100, + functions: 100, + lines: 100, + }, + "src/credentials.ts": { + statements: 100, + branches: 100, + functions: 100, + lines: 100, + }, + // The one write to `globalThis.fetch` (P6): every branch is a disposal + // order, a third party on top, or a fetch missing at install or at + // effect time, each driven on real contexts. + "src/host/global-fetch.ts": { + statements: 100, + branches: 100, + functions: 100, + lines: 100, + }, // The one installer for the remote services (P5): every branch is // driven, on a real context or a stand-in composition, so 100. "src/host/remote.ts": { @@ -362,7 +386,14 @@ export default defineConfig({ // floor above, its throwing `plugin`, throwing `get` and non-string // binding namespace covered there by `test/remote-service.test.ts`'s // stand-in compositions), which left lifecycle.ts at 98.07 / 85.71 / - // 100 / 97.95: the same unreachable branches in a smaller file. What + // 100 / 97.95: the same unreachable branches in a smaller file. P6 + // moved the fetch install to `host/global-fetch.ts` (held at 100 above) + // and added the per-call plane headers, driven by their own unit cases, + // leaving lifecycle.ts at 98.03 / 88 / 100 / 97.95 (22 of 25 branches), + // and moved the credential fill to `credentials.ts`; the no-credential + // report's two "present" arms, which no request could reach (either + // key fills the wire, so no report follows), went with it, leaving + // fetch-patch.ts at 100 / 99.06 / 100 / 100 (106 of 107). What // is left uncovered no composition reaches, and is named here, by // expression rather than line, rather than driven through a stand-in: // - lifecycle.ts: the debug hook's `config.debugFile ?? ""` behind its @@ -371,15 +402,12 @@ export default defineConfig({ // - stream-hook.ts: the two `headerValueFor(…) ?? // fallbackSessionId(…)` fallbacks for a non-empty string or numeric // session id, since `headerValueFor` never answers `undefined` there; - // - fetch-patch.ts: the no-credential report's `requestKey === - // undefined ? "none" : "present"` and `captured === undefined ? - // "none" : "present"` arms, since either key fills the wire and no - // report follows, and the debug entry's `session: + // - fetch-patch.ts: the debug entry's `session: // headers.get(SESSION_HEADER) ?? null` after the patch set the // header. "src/lifecycle.ts": { statements: 98, - branches: 85.5, + branches: 87.9, functions: 100, lines: 97.5, }, @@ -391,7 +419,7 @@ export default defineConfig({ }, "src/fetch-patch.ts": { statements: 100, - branches: 97.5, + branches: 99, functions: 100, lines: 100, },