diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb05a65..a92cab7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -839,14 +839,13 @@ jobs: # dependency bump touches it), so a change to its `test:e2e:host` # script alone is exercised only by the nightly run. # The host seam lives under 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 - # sit beside it by name: the composition (lifecycle.ts, identity.ts), - # the host-module seam (cordis-context.ts), the remaining discovery - # patch (models-discovery.ts), and the two modules that still install - # host-level patches until P6/P10a move them under src/host/: the - # global fetch wrapper (fetch-patch.ts, whose order the probe reads - # as fetchInnermost) and the llm/stream hook (stream-hook.ts). Every + # adapter, the Settings graft, the discovery patch, the host-module + # loaders), and the modules whose behaviour depends on the real + # loader and apply order sit beside it: the composition + # (lifecycle.ts, identity.ts), the host-module seam + # (cordis-context.ts), the global fetch wrapper's stages under + # src/request/ (the patch whose order the probe reads as + # fetchInnermost) and, by name, the llm/stream hook (stream-hook.ts). Every # other row producer (the pure plane profile and model in # src/utils/, key-capture.ts, models-catalog.ts, config.ts, the # generated catalog) is covered on each pull request by the @@ -858,7 +857,7 @@ jobs: # reader its gate, prefix and cell come through (support/e2e-env.ts). # test/keyed-probes.test.ts compiles this pattern and checks it. # A here-string, not a pipe: see the e2e job's tier step. - if grep -Eq '^(src/host/|src/lifecycle\.ts$|src/identity\.ts$|src/cordis-context\.ts$|src/models-discovery\.ts$|src/fetch-patch\.ts$|src/stream-hook\.ts$|cordis\.patch\.yml$|test/e2e/host/|test/e2e/host-binary\.e2e\.ts$|test/support/host\.ts$|test/support/host-versions\.ts$|test/support/e2e-env\.ts$|scripts/host-drift\.ts$|\.github/workflows/ci\.yml$|\.github/actions/|vitest\.e2e\.config\.ts$|vite\.config\.ts$)' <<<"$changed"; then + if grep -Eq '^(src/host/|src/lifecycle\.ts$|src/identity\.ts$|src/cordis-context\.ts$|src/request/|src/stream-hook\.ts$|cordis\.patch\.yml$|test/e2e/host/|test/e2e/host-binary\.e2e\.ts$|test/support/host\.ts$|test/support/host-versions\.ts$|test/support/e2e-env\.ts$|scripts/host-drift\.ts$|\.github/workflows/ci\.yml$|\.github/actions/|vitest\.e2e\.config\.ts$|vite\.config\.ts$)' <<<"$changed"; then echo "run=true" >> "$GITHUB_OUTPUT" else echo "run=false" >> "$GITHUB_OUTPUT" diff --git a/AGENTS.md b/AGENTS.md index 9113b05..cba2c11 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,7 +57,7 @@ Host bundle (`lib/index.mjs`), a thin `apply` barrel over small modules: - `scripts/propose-host-bump.ts` · `scripts/host-bump.ts` — the nightly bump proposal (the same job, schedule only): plans each channel from the report's own reading (`bumpPlan`: `current`; `blocked` on any unread answer; `waiting` while the new `dsh` or pi is inside pnpm's one-day release-age window, which it never lifts; `range` for a cut that opens a prerelease tuple the peer ranges do not admit, moves the bridge's pi range or sits under a dist-tag the record type does not admit; else `data`; a dist-tag moves only with `dsh`, so a plan is `current` exactly when the report has no line for it) and, with `--write`, moves CONTRIBUTING's release-step-3 data and nothing else — the record (`withRecord`), alpha's pins (`channelManifest`), the README pair's "today" sentences (`withReadmePolicy`, a value both channels share left for review unless both records move it to the same value), the root lockfile and the rc relock — for CI to push as `chore/host-bump`, dispatching the floor cells (with the keyed e2e tier off) when `piFloor` or a family field moved. Both lockfiles hold one pi, so a proposed pi move carries every record (`coupleSharedPi`: a channel waiting only on its own young cut takes a pi-only move when its recorded pi range admits it; one that cannot, a dsh-only proposal included, holds the pi move as `blocked`). It never edits a measured table, and runs no test: the proposed pull request's CI is the run. CI writes the plan in a step with no token in its environment (which holds because nothing approves a dependency build script, so the install runs none of the cut's code; `test/host-drift.test.ts` names an approval in every source the pinned pnpm reads, which are `pnpm-workspace.yaml`, a `PNPM_CONFIG_*` variable and a CLI flag in the step, the proposer or the rc relock, and a pnpmfile at the root or named by any of them, and in the older spellings pnpm 12 ignores), and a second step pushes it; **an open proposal is the reviewer's**: one with the same target (the marker line its body ends with, `bumpTarget`: every proposed record in full, never the title) is left alone, and a newer target rebuilds the branch only while every commit on it is the nightly's own, as author and as committer (only this repository's own branch is the proposal). `host-bump.ts` is pure (`test/host-bump.test.ts`), the text half of `--write` included (`applyBumpTexts`: every edit, each README plan checked against the other channel's record now and as proposed; the CLI only writes what it returns and runs the installs); the CLI runs against a loopback registry in `test/mock/host-drift-cli.mock.ts` (its `--out` files, the pi coupling, and on a scratch copy through `--root` a successful `--write`'s `files` list and a failed one's put-back); the two CI steps are executed with stub tools in `test/host-drift.test.ts`. - `scripts/use-channel.ts` — switches the dev install: `rc` or `alpha` installs that channel's committed lockfile (unpatched pi at the newest version the bridge's range admits, what an npm user runs), and `--floor` the same cluster with pi at the range's floor, never committed. It restores every tracked file it touched, so a switch leaves no diff. Its pure half is `scripts/channel-manifest.ts` (`channelManifest`, `pinFor`, `workspaceWithPi`, and `withoutHostPackages`, the lockfile `rc --relock` starts from), held by `test/use-channel.test.ts`. A relock keeps the cordis family at the record's floors because `package.json` pins every member the install resolves (include, group and cosmokit too, which arrive transitively and would otherwise resolve to the newest patch inside their `~` ranges) and `pinFor` moves each with the channel. `rc --relock` belongs in the same commit as ANY change to `package.json`'s dependencies or `pnpm-workspace.yaml`'s catalog or overrides, not only a channel bump: the rc lockfile carries every specifier the root one does and CI installs it frozen, and `test/harness-channel.test.ts` fails, naming the command, when they disagree. Dependabot ignores the cluster and pi, which move only as a channel bump. **This repository carries no pi patch** (D14''): an npm install runs pi unpatched, the harness's patch reaches users only through the desktop app and touches nothing the plugin reads, and a version-keyed patch would break every pi bump. `test/architecture.test.ts` keeps it that way by failing if `src` ever reads a streamed tool-call delta, partial arguments or a thought signature. - `src/settings-table.ts` — the one field table: a row per setting (its kind, default, choice values, volatile flag and card group), from which `config.ts` derives the schema, the resolver, the config types, the defaults and the config-only list (`CONFIG_ONLY_FIELDS`), `settings-fields.ts` derives the card's field specs, `settings-copy.ts` checks the copy keys a card row implies, and `test/manifest.test.ts` holds `cordis.patch.yml`'s header to it (order, type labels, defaults, choice values). **Adding a setting is one row there plus its copy when the card shows it**, and a card row without its label, hint, option or group copy fails to compile. The schema descriptions and the config-only reasons are a second export, `SETTING_PROSE`, which only the host-side `config.ts` imports, so the bundler drops it from the page (`test/client-bundle.test.ts` pins that). -- `src/config.ts` · `src/config-values.ts` · `src/utils/guards.ts` — the schema, the resolver and their defaults, read off the table; dependency-free readers and type guards. `config.ts` is host-side: it imports schemastery, so the client imports the table and never the schema (`test/architecture.test.ts` checks the client graph never reaches it). The client bundle may import the other two, and it does — along with the contract and presentation modules (`contracts/*`, `settings-copy.ts`, `settings-fields.ts`, `settings-table.ts`, `usage-ui.ts`, `utils/usd.ts`, `utils/planes.ts` through `utils/request-shape.ts`). The rule is not a list of names: **the client may import a module that reaches nothing host-only** — no cordis context, no credential seam, no node built-in — and `test/architecture.test.ts`'s client-bundle block ("the client bundle reaches nothing host-only") is what enforces it: it walks the entry's import graph, and the unit suite fails the build rather than anyone having to remember. An earlier version of this line named two files as the only ones allowed, which the tree had already outgrown. +- `src/config.ts` · `src/config-values.ts` · `src/utils/guards.ts` — the schema, the resolver and their defaults, read off the table; dependency-free readers and type guards. `config.ts` is host-side: it imports schemastery, so the client imports the table and never the schema (`test/architecture.test.ts` checks the client graph never reaches it). The client bundle may import the other two, and it does — along with the contract and presentation modules (`contracts/*`, `settings-copy.ts`, `settings-fields.ts`, `settings-table.ts`, `usage-css.ts`, `usage-time.ts`, `usage-state.ts`, `usage-copy.ts`, `utils/usd.ts`, `utils/planes.ts` through `utils/request-shape.ts`). The rule is not a list of names: **the client may import a module that reaches nothing host-only** — no cordis context, no credential seam, no node built-in — and `test/architecture.test.ts`'s client-bundle block ("the client bundle reaches nothing host-only") is what enforces it: it walks the entry's import graph, and the unit suite fails the build rather than anyone having to remember. An earlier version of this line named two files as the only ones allowed, which the tree had already outgrown. ## `src/utils/` — pure by construction, enforced by test @@ -68,7 +68,7 @@ Host bundle (`lib/index.mjs`), a thin `apply` barrel over small modules: It is the same trick `test/architecture.test.ts` already uses for the client bundle's import graph, at finer grain. -**Why `utils` and not `decisions`/`pure`/subject folders.** `utils` is the name a reader already has for these, and needs no glossary. What stops it becoming the usual dumping ground is the gate above: `fetch-patch.ts` is 498 lines and everything in it is _arguably_ a utility, and the gate says no because it reads a context. Subject folders (`gateway/`, `identity/`) describe what code is _about_, which is a real second axis — adopt it when a folder outgrows reading, not at 37 modules. +**Why `utils` and not `decisions`/`pure`/subject folders.** `utils` is the name a reader already has for these, and needs no glossary. What stops it becoming the usual dumping ground is the gate above: the fetch patch (`src/request/`, about 900 lines over four stages and their composition) is _arguably_ all utility, and the gate says no because it reads a context. Subject folders (`gateway/`, `identity/`) describe what code is _about_, which is a real second axis — adopt it when a folder outgrows reading, not at 37 modules. **The pattern that made things untestable, and the fix.** Every offender was a decision computed inline from whatever was in scope: @@ -95,8 +95,8 @@ 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) | -| `planes.ts` | the route-to-plane rule (P7): `catalogPlaneForRoute` in `models-catalog.ts`, the inline rule in `request-shape.ts`'s `isZenProvider`, and the exact-route copies in `key-capture.ts`, `models-discovery.ts`, `purge-service.ts`, `credentials.ts`, `usage.ts` and the route claim and plane adapter | +| `credential-policy.ts` | the placeholder set in `key-capture.ts` and the meter's policy orders in the meter's discovery (now in `credentials.ts`), with the fill's order, the capture gate and L8's strike count new (P6) | +| `planes.ts` | the route-to-plane rule (P7): `catalogPlaneForRoute` in `models-catalog.ts`, the inline rule in `request-shape.ts`'s `isZenProvider`, and the exact-route copies in `key-capture.ts`, the discovery wrapper (now `host/discovery.ts`), `purge-service.ts`, `credentials.ts`, `usage.ts` and the route claim and plane adapter | | `usd.ts` | the two `formatUsd`s (P7), `go-limits.ts`'s allowance one and `session-cost.ts`'s metered one, as two named styles | | `client-generation.ts` | the header names in `request-shape.ts`'s `planeHeadersFor` and the User-Agent form in `identity.ts` (P7, L6), as the emulated row of a per-generation table | | `context-windows.ts` | new (P7, L11): measured context windows with their dates and evidence, shipped empty | @@ -104,12 +104,12 @@ It is the same trick `test/architecture.test.ts` already uses for the client bun `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 (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/stream-hook.ts` · `src/request/` · `src/tool-fallback.ts` — the `llm/stream` hook, the fetch interceptor, and the free-tier `read`/`bash` fallback. The interceptor is a composition of stages under `src/request/` (P10a), in the order they run: `claim.ts` (whether the request is the plugin's at all: a gateway URL or a configured route, never a foreign turn or a marked request, D27), `body.ts` (the body read once and parsed at most once, shared by the free-model check, the fallback and the debug names; a Buffer is read by the fallback only, on purpose; `maybeInjectCoreTools`, the fallback over a body handed in directly, is a thin wrapper over the same reader and gate, so its unit cases drive the code the patch runs), `credential.ts` (the fill through `credentials.ts`, and the gateway's answer settled back), `headers.ts` (the plane headers wherever the plane adapter did not set them per call, the User-Agent, and `callHeadersFor`, the per-call writer the adapter's `prepareHeaders` calls, OC5), and `patch-fetch.ts`, which composes them. No stage reads `process.env`, which `test/architecture.test.ts` pins for every file under `src/request/`, `lifecycle.ts` and the plane provider. The fallback treats an empty-schema `read`/`bash` as missing and replaces it, and gives a toolless chat-completions body `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 (`isGoPlaneUrl`, `planeForUrl`), whether a route is Zen to the meter (`isZenProvider`, over `planeForRoute`), 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`, its names read from the emulated row of `client-generation.ts`). 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/contracts/usage.ts` — credential extraction and its tier, quota discovery, the usage service, and the shared shape (with `USAGE_NAMESPACE`, and `parseUsageReading`, the client's reading parser: the vendor whitelist `parseGoUsage` plus the fields the Host attaches, the allowance, `quotaUnavailable` and the plane spend). -- `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 (with the one spec lookup, `specOn`/`specFor`, a plane's row then the plane-blind one, and `liveCatalogOn`), 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. +- `src/key-capture.ts` · `src/usage.ts` · `src/contracts/usage.ts` — credential extraction and its tier, the usage service, and the shared shape (with `USAGE_NAMESPACE`, `parseUsageReading`, the client's reading parser: the vendor whitelist `parseGoUsage` plus the fields the Host attaches, the allowance, `quotaUnavailable` and the plane spend; and `parseFailure`/`UsageFailure`, a refused read as the meter shows it). Quota discovery is `credentials.ts`'s fourth half. +- `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), the installation's store read, and the meter's discovery and key resolution (`discoverGoConfig`, `resolveGoBaseURL`, `resolveGoApiKey`, `resolveZenCreditInfo`; moved in from `go-discovery.ts` in P10a, held at a floor just under 100 for one unreachable guard, `result.status !== "fulfilled"` in `resolveGoKeyForRef`, since the credentials resolver never rejects; the move's other undriven branch, the reachable `readProviderRow` else for a nested `options` block with no usable key, is driven now, and `vite.config.ts` keeps the measured list). 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/host/discovery.ts` — the generated static shim, the OpenCode-catalog parser with SWR refresh (with the one spec lookup, `specOn`/`specFor`, a plane's row then the plane-blind one, and `liveCatalogOn`), 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 (both in `credentials.ts`), 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. **The general form, because this shape recurred twice in one session**: a sweep that resolves a name in the wrong CONTEXT reports a clean tree as broken. Grepping for callers without the defining file makes same-file calls look absent; resolving a doc's relative links from the repository root instead of from the file's own directory makes every link look dead. Both produced a list of confident findings and both were entirely wrong. A third instance is reading a UTC timestamp as local time and concluding that a workflow had not run since the previous evening, when it had run twenty minutes earlier — same shape, wrong context, confident conclusion. Before acting on a sweep, check that the thing being searched is the thing the claim is about, including the clock it is written in. @@ -124,10 +124,10 @@ It is the same trick `test/architecture.test.ts` already uses for the client bun - `src/purge-service.ts` · `src/contracts/purge.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/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/planes.ts` · `src/utils/usd.ts` · `src/utils/client-generation.ts` · `src/utils/context-windows.ts` — P7's one source per table, each held at 100% coverage. `planes.ts` is `PLANE_OF_ROUTE`, read exactly through `planeOfPlaneRoute` (the two owned routes, never an inherited key) or with relays through `planeForRoute` (`opencode-go` and `opencode-go-*` are Go, everything else Zen, case-sensitive), or indexed directly where the route is already a typed `PlaneRoute`; `test/planes.test.ts` scans `src` for a second copy of the rule in the spellings it names (a comparison against a plane route's literal, the relay half `startsWith("opencode-go…")`, a `case` label, and a quoted route paired with a plane's name in a table row, in either order and under any key name); each allowed file's count is exact, so a copy added inside an allowed file is seen and a copy that goes forces its allowance down. The scan is a tripwire for the spellings it names, not a proof: what passes it includes, for example, an unquoted key, a record with another key between the route and the plane, and a route built from parts, and the test plants each of those as a non-offender. (The relay predicate, `!provider.startsWith("opencode")` in `lifecycle.ts` and `fetch-patch.ts`, asks a different question and is left inline.) `usd.ts` is `formatUsd(value, style)`, `allowance` (a whole figure drops the cents, an unknown one is "—") or `metered` (always two decimals), and every caller names its style. `client-generation.ts` is `CLIENT_GENERATIONS`: the plugin emulates `1.x`, whose row `planeHeadersFor` and `identity.ts` read; the `2.x` row, and `sessionValue` in either row, is recorded and read by nothing; it pins no 2.x version (its User-Agent is a format, not a value), and no test or source writes a concrete 2.x literal (`pnpm run cli:version` refuses one). `context-windows.ts` is `MEASURED_CONTEXT_WINDOWS` and `measuredWindowFor`, read ahead of the catalog's window by `plane-model.ts`, and in the catalog's place in each field order by the discovery rows (so pi's window still wins on a route pi-ai serves); both take the table as a parameter, and a row is added only with its measurement. +- `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 (`host/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/planes.ts` · `src/utils/usd.ts` · `src/utils/client-generation.ts` · `src/utils/context-windows.ts` — P7's one source per table, each held at 100% coverage. `planes.ts` is `PLANE_OF_ROUTE`, read exactly through `planeOfPlaneRoute` (the two owned routes, never an inherited key) or with relays through `planeForRoute` (`opencode-go` and `opencode-go-*` are Go, everything else Zen, case-sensitive), or indexed directly where the route is already a typed `PlaneRoute`; `test/planes.test.ts` scans `src` for a second copy of the rule in the spellings it names (a comparison against a plane route's literal, the relay half `startsWith("opencode-go…")`, a `case` label, and a quoted route paired with a plane's name in a table row, in either order and under any key name); each allowed file's count is exact, so a copy added inside an allowed file is seen and a copy that goes forces its allowance down. The scan is a tripwire for the spellings it names, not a proof: what passes it includes, for example, an unquoted key, a record with another key between the route and the plane, and a route built from parts, and the test plants each of those as a non-offender. (The relay predicate, `!provider.startsWith("opencode")` in both writers of `request/headers.ts`, asks a different question and is left inline.) `usd.ts` is `formatUsd(value, style)`, `allowance` (a whole figure drops the cents, an unknown one is "—") or `metered` (always two decimals), and every caller names its style. `client-generation.ts` is `CLIENT_GENERATIONS`: the plugin emulates `1.x`, whose row `planeHeadersFor` and `identity.ts` read; the `2.x` row, and `sessionValue` in either row, is recorded and read by nothing; it pins no 2.x version (its User-Agent is a format, not a value), and no test or source writes a concrete 2.x literal (`pnpm run cli:version` refuses one). `context-windows.ts` is `MEASURED_CONTEXT_WINDOWS` and `measuredWindowFor`, read ahead of the catalog's window by `plane-model.ts`, and in the catalog's place in each field order by the discovery rows (so pi's window still wins on a route pi-ai serves); both take the table as a parameter, and a row is added only with its measurement. - `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/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; `credentials.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: `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. @@ -137,7 +137,7 @@ It is the same trick `test/architecture.test.ts` already uses for the client bun - A timing dependency every remote shares, worth knowing before debugging a row that will not appear: the mount is an async `$mount` started in an effect, and the card reads `ctx.remote.` SYNCHRONOUSLY when its injector builds the props. If the injector runs before the mount resolves, the service is not there yet and the surface renders nothing. More often the cause is a namespace with no client descriptor at all — the purge row and the store-inspection row each shipped that way — which `test/remote-contract.test.ts` now catches per method: it reads `REMOTE_CONTRACTS`, the client's descriptors and the services the plugin mounts on a real cordis `Context`. Each caller reports an empty lookup (`no opencodeStore service on the remote`, `no opencodeGoUsage service on the remote`, with the keys the remote does expose), so the symptom is a console line rather than a blank. And since P5 the host services go with the plugin's last activation: a reload unloads before it applies again, which leaves a short window in which a call finds no active Remote method (the meter's poll retries; a purge click there reports the host's refusal), and disabling the plugin withdraws all three, including the `opencodeGoUsage` instance the sibling `dsh-opencode-go` account page reads. -Web client bundle (`lib/client.js`): `src/settings-page.tsx` (entry, wiring only), the remote contracts (`src/contracts/*`), the `settings-*` card and its controls — including the store-inspection row, `src/settings-store-inspect.tsx` — and the meter — `src/usage-pill.tsx` (state), `src/usage-panel.tsx` (pure views), `src/usage-ui.ts` (logic and stylesheet). `test/architecture.test.ts` walks this graph from the entry and fails on a node built-in, the cordis runtime, pi, or `process.env`. +Web client bundle (`lib/client.js`): `src/settings-page.tsx` (entry, wiring only), the remote contracts (`src/contracts/*`), the `settings-*` card and its controls — including the store-inspection row, `src/settings-store-inspect.tsx` — and the meter — `src/usage-pill.tsx` (state), `src/usage-panel.tsx` (pure views), and the meter's pure modules: `src/usage-state.ts` (the ring, the window it answers for, each window's state), `src/usage-copy.ts` (wording and links), `src/usage-time.ts` (the reset countdown) and `src/usage-css.ts` (the stylesheet). `test/architecture.test.ts` walks this graph from the entry and fails on a node built-in, the cordis runtime, pi, or `process.env`. ## Commands diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 96f9349..6fc77e6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -84,7 +84,7 @@ 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 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). +- **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 and the meter's key resolution, both in `src/credentials.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 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. +- **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 discovery patch, 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` and `src/cordis-context.ts`, and the two that still carry host-level patches outside `src/host/` (`src/request/**`, the global fetch wrapper's stages, 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: @@ -148,7 +148,7 @@ The web profile wires this checkout with `link:`, so builds are picked up like t - **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. - **A test for a fix fails without it.** Before committing a regression test, revert the fix locally and watch it fail. -- **Meaningful coverage.** Every config field in the `SPECS` register (`src/settings-fields.ts`) needs both the on and off path where it has one; every passthrough claim needs a non-OpenCode URL test proving headers are untouched; helper functions exported from `usage-ui.ts` are asserted directly, not re-derived in the test. +- **Meaningful coverage.** Every config field in the `SPECS` register (`src/settings-fields.ts`) needs both the on and off path where it has one; every passthrough claim needs a non-OpenCode URL test proving headers are untouched; helper functions exported from the meter's pure modules (`usage-state.ts`, `usage-copy.ts`, `usage-time.ts`) are asserted directly, not re-derived in the test. - **A component with hooks needs a real mount.** Calling `Component(props)` returns an element and runs none of its state, so a hook-bearing component can have twenty passing cases and still be untested — `usage-pill.tsx` sat at 9% exactly that way, with the poll loop, retry and dismissal all uncovered. `test/usage-pill-mount.test.tsx` is the answer: a `// @vitest-environment jsdom` pragma scoped to that one file, so the rest of the suite keeps the fast node environment and the zero-dependency element-tree style. ### The coverage ratchet @@ -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`, `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. +`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 (`utils/credential-policy.ts`), the fetch patch's stages (`request/claim.ts`, `request/body.ts`, `request/credential.ts`, `request/headers.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`, `host/host-modules.ts` and the credential resolver (`credentials.ts`, whose one unreachable guard arrived with the meter's discovery in P10a) just below what they measure; and the three modules that install the plugin's effects on the host, `lifecycle.ts`, `stream-hook.ts` and the fetch patch's composition (`request/patch-fetch.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/docs/credentials.md b/docs/credentials.md index 7b18495..9d36826 100644 --- a/docs/credentials.md +++ b/docs/credentials.md @@ -248,7 +248,7 @@ Built, in the order this file sets out: **What a login buys is not the free tier, and the surface exists anyway.** The org is necessary and not sufficient: measured with this machine's own account — its session token, its active org, and every header captured from the real client — a free-tier model still answers `403 FreeTierError`, on both endpoints. The gate is not in the HTTP request, so it is either a client fingerprint or a signature sent only to the real host, and the error's own words may simply be true. A login is what the free tier is asked FOR; whether it is granted is a separate, unmeasured question. The first org is activated, matching the client. -- **The org on the request.** `fetch-patch.ts` sends `x-opencode-org-id` from a per-plane resolver — asked per request, because a login can arrive while the process runs — and invents no header when a plane's credential is a plain key, which is every key deployment. `credentialOrg` is the explicit fallback for a token that came from elsewhere. +- **The org on the request.** The fetch patch (`request/headers.ts`) sends `x-opencode-org-id` from a per-plane resolver — asked per request, because a login can arrive while the process runs — and invents no header when a plane's credential is a plain key, which is every key deployment. `credentialOrg` is the explicit fallback for a token that came from elsewhere. Built, and the account plane it serves: @@ -290,10 +290,10 @@ The shape it would read, taken from the schema rather than guessed: `credential( The two modules existed and were tested before anything called them. The wiring below is built: a config field with no reader is an empty switch, which this repository has already been audited for once, and the edits went together. 1. `src/config.ts` — `readOpencodeStore: false` in `CONFIG_DEFAULTS` (the object is alphabetical, so between `providers` and `sessionIdEnv`), the matching optional field on `PluginConfig`, and a `z.boolean().default(...).volatile()` row in the schema with a description that says what it reads and that it is off by default. -2. `src/go-discovery.ts` — one more entry in the step map `firstResolved` takes, and **last in every policy**, because the user's own declaration wins: `opencodeStore: () => readFromStore(ctx, plane)`. It resolves the path with `opencodeDatabasePath({ channel: process.env.OPENCODE_CHANNEL, env: process.env, home: os.homedir() }, os.tmpdir())`, reads with `readOpencodeCredentials`, picks the entry whose `integrationId` matches the plane, and answers `undefined` for everything else — a missing file included. +2. `src/go-discovery.ts` (now `src/credentials.ts`) — one more entry in the step map `firstResolved` takes, and **last in every policy**, because the user's own declaration wins: `opencodeStore: () => readFromStore(ctx, plane)`. It resolves the path with `opencodeDatabasePath({ channel: process.env.OPENCODE_CHANNEL, env: process.env, home: os.homedir() }, os.tmpdir())`, reads with `readOpencodeCredentials`, picks the entry whose `integrationId` matches the plane, and answers `undefined` for everything else — a missing file included. 3. `src/settings-fields.ts` — one `CARD_FIELDS` control, which is what makes the switch reachable. -4. **Which of the two mechanisms to use, now that both have been read.** `discoverGoConfig` walks `ctx.loader.entries()` and reads `entry.options.config`, but that is the PROVIDER REGISTRY — the rows that describe `opencode-go` and `opencode` — not this plugin's own configuration. This plugin's own config arrives as a VALUE: `fetch-patch.ts` receives `config: ResolvedPluginConfig` as a parameter, and `lifecycle.ts` is what passes it. So the new step should take the flag as an argument threaded from `lifecycle` rather than dig for it in the loader, and that means `resolveGoApiKey` needs one more parameter (it currently takes `ctx`, `targetProvider` and `policy`). -5. The config travels as VALUES rather than as a config object: `lifecycle.ts` resolves it with `resolveConfig` and passes fields down. `usage.ts:285` calls `resolveGoApiKey(...)` for the meter and `fetch-patch.ts:253` reads `config.keySource` directly for the headers, which is the precedent for how a field arrives. **The model-call path is now traced, and it is `fetch-patch.ts`**: the interceptor's Authorization fallback is what fills the `Bearer unused` sentinel the internal routes carry, so that is where a request's own key is resolved. The other one is `google-bridge.ts`'s `resolveApiKey`, the per-request resolver for the `opencode-google` route specifically — `responses-provider.ts` calls neither `resolveRoutedKey` (since deleted in 1.x: it was exported and never called from `src/`) nor `resolveApiKey`, as the grep said; it hands the bridge its inputs, and the flag travels that way. Both consult the store only after the captured key and the declared environment, so they agree with the meter. +4. **Which of the two mechanisms to use, now that both have been read.** `discoverGoConfig` walks `ctx.loader.entries()` and reads `entry.options.config`, but that is the PROVIDER REGISTRY — the rows that describe `opencode-go` and `opencode` — not this plugin's own configuration. This plugin's own config arrives as a VALUE: `fetch-patch.ts` (now the stages under `src/request/`) receives `config: ResolvedPluginConfig` as a parameter, and `lifecycle.ts` is what passes it. So the new step should take the flag as an argument threaded from `lifecycle` rather than dig for it in the loader, and that means `resolveGoApiKey` needs one more parameter (it currently takes `ctx`, `targetProvider` and `policy`). +5. The config travels as VALUES rather than as a config object: `lifecycle.ts` resolves it with `resolveConfig` and passes fields down. `usage.ts:285` calls `resolveGoApiKey(...)` for the meter and `fetch-patch.ts:253` reads `config.keySource` directly for the headers, which is the precedent for how a field arrives. **The model-call path is now traced, and it is `fetch-patch.ts`** (now `src/request/`): the interceptor's Authorization fallback is what fills the `Bearer unused` sentinel the internal routes carry, so that is where a request's own key is resolved. The other one is `google-bridge.ts`'s `resolveApiKey`, the per-request resolver for the `opencode-google` route specifically — `responses-provider.ts` calls neither `resolveRoutedKey` (since deleted in 1.x: it was exported and never called from `src/`) nor `resolveApiKey`, as the grep said; it hands the bridge its inputs, and the flag travels that way. Both consult the store only after the captured key and the declared environment, so they agree with the meter. 6. Tests: the step answers a key from a store this suite builds, answers `undefined` with the switch off, and still loses to a declared credential and to a captured one; the fetch patch fills its Authorization header from the store, per plane; and the bridge carries a stored login over the store. **One bug the wiring found, worth recording because the login reader masked it.** `google-bridge.ts` derived the plane with `String(route).startsWith("opencode-go")`, and `"opencode-google"` starts with `"opencode-go"` — so the Zen route was read as the Go one. `loginTokenReader` hid that by falling back to the other plane; an integration-id lookup does not, so the derivation is now an exact route comparison. @@ -334,7 +334,7 @@ Everything below is measured against the live gateway and a real installation, o | org on the request | **not needed** | **needed** — `x-opencode-org-id` | | session header | accepted, not required | **required** (`400 MissingSessionID` without) | -The org distinction is the one that matters most and was got wrong twice: it belongs to the **Go** plane only. `src/fetch-patch.ts` already scopes it per plane through `hooks.resolveOrg?.(gatewayPlaneFor(url))`. +The org distinction is the one that matters most and was got wrong twice: it belongs to the **Go** plane only. `src/request/headers.ts` already scopes it per plane through `resolveOrg?.(gatewayPlaneFor(url))`. ### The two sources, and which is which @@ -364,7 +364,7 @@ So the refusal is not about structure, data, headers, route, credential class or **Plane matters, and that is why the hide was scoped to Zen in the rounds it existed.** `step-5-preview-free` and `longcat-2.5-preview-free` appear on BOTH planes; `space-bunny` and `muse-spark-1.3-contributor` are Go's. So the exclusion was `provider === "zen" && id.endsWith("-free")` — never an id list and never global. -**That rule broke eleven tests, and they were not mechanical.** Several encode deliberate behaviour about which models are offered (`adds Space Bunny and removes retired 1.2`, `preserves Space Bunny while removing retired Muse 1.2 rows`), and `muse-spark-1.3-contributor-free` is the fixture six suites use for a responses-format model. Changing them is a design decision about what this plugin offers, not a rename; it was attempted and reverted rather than half-applied. The decision that followed — and stands — is to offer the ids and report the refusal per request, so no such rule exists in `src/models-discovery.ts` today. +**That rule broke eleven tests, and they were not mechanical.** Several encode deliberate behaviour about which models are offered (`adds Space Bunny and removes retired 1.2`, `preserves Space Bunny while removing retired Muse 1.2 rows`), and `muse-spark-1.3-contributor-free` is the fixture six suites use for a responses-format model. Changing them is a design decision about what this plugin offers, not a rename; it was attempted and reverted rather than half-applied. The decision that followed — and stands — is to offer the ids and report the refusal per request, so no such rule exists in `src/host/discovery.ts` (`src/models-discovery.ts` until P10a) today. ### What is measured about the free tier @@ -384,11 +384,11 @@ declared ← apiKeyEnv; "almost always", and overridden when a working oa store ← the local OpenCode CLI's database, only when neither is configured ``` -`src/fetch-patch.ts` implements exactly this. Do not invert it: a test named "fills the Authorization header from the installation's store, last" exists for that reason. +`src/credentials.ts` implements exactly this, for the fill the fetch patch's credential stage (`src/request/credential.ts`) asks. Do not invert it: a test named "fills the Authorization header from the installation's store, last" exists for that reason. ### What is open, and what is no longer -- **The free tier is refused on Zen for every shape this plugin can assemble, and the ids are offered anyway.** The plugin does not use a bare client — it reaches the gateway through the host's `llm-pi-ai` adapter — and that is what produced the claim this line used to make: that a session running on `opencode/step-5-preview-free` produces turns normally, so the adapter clears the gate. **It does not, and the run was made.** With this machine's session token, its active org and the complete header set the client sends, a free-tier Zen model answers `403 FreeTierError` on both endpoints — the measurement in the login section above, which postdates this one and contradicts it. What the adapter does clear is the PROTOCOL: the session that appeared to run on a free model was running on `global:step-5-preview`, this host's own model, not in OpenCode's catalog at all. `step-5-preview-free` produces turns **on the Go plane**, which has no free tier to gate and serves it by the subscription key — and Go's three are not the exception that proves a rule: Zen's free ids are offered too. The console's source shows the refusal is made by the vendor's inference service, which receives these requests keyless and answers for them; a refusal that names itself per request is what a reader should be given instead of an empty picker, so `src/models-discovery.ts` offers the ids and `fetch-patch.ts` passes the refusal through as `403 FreeTierError`, in the gateway's own words. +- **The free tier is refused on Zen for every shape this plugin can assemble, and the ids are offered anyway.** The plugin does not use a bare client — it reaches the gateway through the host's `llm-pi-ai` adapter — and that is what produced the claim this line used to make: that a session running on `opencode/step-5-preview-free` produces turns normally, so the adapter clears the gate. **It does not, and the run was made.** With this machine's session token, its active org and the complete header set the client sends, a free-tier Zen model answers `403 FreeTierError` on both endpoints — the measurement in the login section above, which postdates this one and contradicts it. What the adapter does clear is the PROTOCOL: the session that appeared to run on a free model was running on `global:step-5-preview`, this host's own model, not in OpenCode's catalog at all. `step-5-preview-free` produces turns **on the Go plane**, which has no free tier to gate and serves it by the subscription key — and Go's three are not the exception that proves a rule: Zen's free ids are offered too. The console's source shows the refusal is made by the vendor's inference service, which receives these requests keyless and answers for them; a refusal that names itself per request is what a reader should be given instead of an empty picker, so `src/host/discovery.ts` offers the ids and the fetch patch (`src/request/`) passes the refusal through as `403 FreeTierError`, in the gateway's own words. - **`auto-review` needs no change of its own.** It builds a bare options object and takes its route from `session.requestHeader()`, so it inherits whatever the session selected — which is why it failed on a free model the chat appeared to be using. Free models are offered, so a new selection can land there; the turn then stops with the gateway's own refusal, passed through verbatim rather than rewritten. **A session already on one keeps failing until the model is changed**, which is the same statement for the picker as for an existing selection. - **`readOpencodeAccount` is wired into both request paths through the shared login reader**, and the account token with its org was measured to serve a paid model (`200`). It does not help the free tier, which nothing does. - **The store is read per request with no cache**, deliberately: a rotation inside OpenCode should be picked up. It is also a SQLite open per keyless request. diff --git a/docs/engineering-notes.md b/docs/engineering-notes.md index 28897ab..faad73c 100644 --- a/docs/engineering-notes.md +++ b/docs/engineering-notes.md @@ -96,7 +96,7 @@ So the fix belongs here rather than in anyone's profile: the routes for the othe `catalog-data.ts` carries `provider_npm` only for models that override the default, so absence is meaningful for the models it ships and meaningless for anything else. A hand-listed model needs its protocol from somewhere: the catalog, a route that declares it, or a rule that reads it off the id. -**And the other half of I1: it is still OFFERED.** `models-discovery.ts` filters a route's listing with `isServableModel`, which asks the catalog for the model's SDK and treats a missing answer as servable — correctly, because absence means the completions default. For a model the catalog has never heard of, absence means the same thing by accident, so a hand-listed model is offered on a route that cannot serve it. The routing fix above moves it when it is chosen; this is the half that would stop it being offered at all, and the two belong together: I1 says a model that cannot work is not offered, and today that clause holds only for models the catalog describes. +**And the other half of I1: it is still OFFERED.** `host/discovery.ts` (`models-discovery.ts` until P10a) filters a route's listing with `isServableModel`, which asks the catalog for the model's SDK and treats a missing answer as servable — correctly, because absence means the completions default. For a model the catalog has never heard of, absence means the same thing by accident, so a hand-listed model is offered on a route that cannot serve it. The routing fix above moves it when it is chosen; this is the half that would stop it being offered at all, and the two belong together: I1 says a model that cannot work is not offered, and today that clause holds only for models the catalog describes. The check needs the plane, which it already has, and the family, which the id names — the same two facts the routing fix uses. What it must not do is read "no catalog entry" as "servable" without also asking whether any route on that plane speaks the protocol the id implies. @@ -494,7 +494,7 @@ Steps 1 and 2 alone changed nothing, and step 3 without 1 or 2 would have moved The plugin's turn state carries `model`, `parentValue`, `project`, `provider` and `value` (`src/turn-store.ts`), and none of them is a message id: `value` is the session's derived id, which is a different object from the message. The stream hook's `options` carries no message either — the adapter builds the body after the hook returns — so there is nothing at this layer to send. This section said for a round that "inventing a value would be worse than omitting the header", and the premise turned out to be the part that was wrong: the gateway reads this header as a metric (`packages/console/app/src/routes/zen/util/handler.ts:127-135`) and the console rewrites it to `x-opencode-request-id` before forwarding, so **what the header has to satisfy is its shape and its one-value-per-request lifecycle — not the CLI's own message table**, which nothing reads back. -So the plugin mints: `newOpenCodeMessageId` (`src/session.ts`) returns `msg_` + 12 hex + 14 base62 — the vendor's own skeleton — with the twelve hex carrying `milliseconds * 0x1000 + counter` modulo `2^48` and the suffix drawn from `randomBytes`. `stream-hook.ts` mints once per turn and stores it as `requestValue`; `fetch-patch.ts` sends it beside the client and project headers. Two properties were chosen deliberately: the value is random rather than derived from message content (a digest of the user's text travelling in a header would be a guessable fingerprint), and it is per-turn rather than per-message — the client repeats one id across a multi-step tool turn, and with no DSH message id reachable from this layer the turn is the largest unit that can honestly own one. The measurement in `docs/opencode-1.19-api.md` closed the question the other way: with the complete set sent — this header included — the free tier answered exactly as before. The header is correct to send, and it is not the gate. +So the plugin mints: `newOpenCodeMessageId` (`src/session.ts`) returns `msg_` + 12 hex + 14 base62 — the vendor's own skeleton — with the twelve hex carrying `milliseconds * 0x1000 + counter` modulo `2^48` and the suffix drawn from `randomBytes`. `stream-hook.ts` mints once per turn and stores it as `requestValue`; it travels in the plane headers' one table (`planeHeadersFor`), written per call by the plane adapter and by the fetch patch's header stage (`request/headers.ts`), beside the client and project headers. Two properties were chosen deliberately: the value is random rather than derived from message content (a digest of the user's text travelling in a header would be a guessable fingerprint), and it is per-turn rather than per-message — the client repeats one id across a multi-step tool turn, and with no DSH message id reachable from this layer the turn is the largest unit that can honestly own one. The measurement in `docs/opencode-1.19-api.md` closed the question the other way: with the complete set sent — this header included — the free tier answered exactly as before. The header is correct to send, and it is not the gate. ## A free model ran on /zen/v1 and may not run on /inference/v1 — measured, unresolved diff --git a/docs/improvement-plan.md b/docs/improvement-plan.md index 43f5092..a8f7bcc 100644 --- a/docs/improvement-plan.md +++ b/docs/improvement-plan.md @@ -39,7 +39,7 @@ Phases land as **stacked pull requests**. The open ones are rebased, each onto i | P7 | | `refactor:` one source per table | in review | **on P6**; one route-to-plane table (`src/utils/planes.ts`: `PLANE_OF_ROUTE`, the exact `planeOfPlaneRoute` and the relay-inclusive `planeForRoute`) with `planeForUrl` beside `isGoPlaneUrl`, one `formatUsd` with two named styles (`src/utils/usd.ts`), one spec lookup (`specOn`/`specFor` in `src/models-catalog.ts`) and `liveCatalogOn`, the last capitalised level name read from `effortName`; L6's client-generation table (`src/utils/client-generation.ts`, 1.x emulated, 2.x recorded and unread) and L11's measured-window table (`src/utils/context-windows.ts`, shipped empty); the Mistral rationale reworded to the plugin's own rule. No behaviour change: the caller pins (`test/plane-table.test.ts`, `test/usd-callers.test.tsx`, the level-name and User-Agent cases, a per-plane purge case, the credential variable's exact-route edges and the meter's no-key refusal per route) were green on the base and land unchanged | | P8 | | `fix:` the card says when its settings apply, over one settings table | in review | **on P7**; one field table (`src/settings-table.ts`: `SETTINGS`, a row per key, and `SETTING_PROSE`, its host-only prose) from which `config.ts` derives the schema, resolver, types, defaults and config-only list, `settings-fields.ts` the card specs, and `settings-copy.ts` checks the copy keys; `cordis.patch.yml`'s header held to it by order, type label, stated default and choice values; fifteen dead copy keys and the meter's `modelMarkers` prop deleted, the zh README's stale name for the card replaced by the package's `meta.title`, and the card says its settings apply on re-apply (performed on the real host in both channels: a volatile edit of the plugin's row commits in place and the plugin follows it only once re-applied). No setting changed: the schema, resolver and card pins (`test/settings-snapshot.test.ts`) were green on the base and land unchanged but for the named edits (the copy keys, `CONFIG_DEFAULTS`' `credentialOrg: undefined`, the resolved type's modifiers). Retitled from `refactor:` (P-H's, P5's and P6's precedent): under squash the pull request's title is the release signal and a `refactor` is hidden from the changelog, while the phase ships a visible card line and the README pair's re-apply sentence. No `!` and no BREAKING CHANGE footer (1.x minors only); the owner may keep `refactor:` at landing, and the card line then ships without a changelog entry | | P9 | | `refactor:` remote seam | in review | **on P8**; one builder (`defineRemote`, `src/contracts/remote.ts`) derives every descriptor and codec of the three contracts, which move into `src/contracts/` with `REMOTE_CONTRACTS` the one list the client mounts; `markRemote` writes each service's marker from its contract; `callRemote`/`unwrapRemote` are the one unwrap of the four client callers; `isGoUsage` deleted, `USAGE_NAMESPACE` and `parseUsageReading` added; `remote-contract` reads the contracts and the mounted services | -| P10a | | `refactor:` pure module moves | planned | | +| P10a | | `refactor:` pure module moves | in review | **on P9**; the discovery wrapper to `src/host/discovery.ts`; the meter's discovery and key resolution into `src/credentials.ts`; `usage-ui.ts` split into `usage-css.ts`, `usage-time.ts`, `usage-state.ts` and `usage-copy.ts`, with `parseFailure` in `src/contracts/usage.ts`; the fetch patch into stages under `src/request/` (claim, body, credential, headers, and `patch-fetch.ts` composing them), `callHeadersFor` beside the patch's own header stage, and a claimed request's body parsed once; no behaviour changed, and every name the door exports keeps its signature | | P10b | | `fix:` catalog state | planned | | | P11 | | `refactor:` UI on the primitives | planned | | | P12 | | `ci:` lint warnings gating | planned | | @@ -304,15 +304,15 @@ src/ host/ patch-method.ts wrap a host method: restore only if still current; delete when the original was inherited; can re-wrap on llm/adapters-updated (no site needs it yet) - discovery.ts discoverModels: pi's answer + the catalog's missing models (D3, D8); - in src/models-discovery.ts until P10a + discovery.ts discoverModels: pi's answer + the catalog's missing models (D3, D8) route-claim.ts internal/config filter (appended on the NEW core, F8): pi-ai never claims the planes; reconcile on 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) + request/ fetch patch stages: claim → body read (parsed at most once) → credential → + headers → body rewrite, composed by patch-fetch.ts credentials.ts gathers values; utils/credential-policy decides; CaptureStore per root utils/ pure: protocols, plane-model, plane-profile, model-metadata (reasoning, both vocabularies), credential-policy, request-shape, session-id, catalog-parse @@ -501,6 +501,12 @@ What stays private is pinned by contract tests against the real host packages: - `go-discovery` → `credentials.ts`; - split `usage-ui`; - `fetch-patch` → `request/`. + - **As landed.** Five moves, no behaviour change; every name `test/support/src.ts` exports keeps its signature, and each is declared in the module the door names. `src/models-discovery.ts` is `src/host/discovery.ts`, one file (its patch-site id, `dsh-opencode-patch/model-discovery`, is unchanged, since `reload` keys on it). `src/go-discovery.ts` is appended to `src/credentials.ts` in its own order, so the module has four halves: the capture store, the fill, the installation's store, and the meter's discovery and key resolution; its by-name reads of a provider row and `get("opencode", "zen")` moved with it, and `planes`' allowances follow the file at the same counts (2 comparisons, 1 pair). `src/usage-ui.ts` is four modules: `usage-css.ts` (the stylesheet, byte-identical), `usage-time.ts` (the reset countdown), `usage-state.ts` (the ring, the window the meter answers for, each window's state) and `usage-copy.ts` (wording and links); `parseFailure` and `UsageFailure` join `src/contracts/usage.ts`, and the `isZenProvider` re-export is gone (the pill imports it from `utils/request-shape.ts`). `src/fetch-patch.ts` is the stages under `src/request/`, in the order they run: `claim.ts`, `body.ts`, `credential.ts`, `headers.ts`, composed by `patch-fetch.ts` with the base's statement order kept line for line (the observe after the awaited body read, the version header before the wire-key read, the settle after the response, the debug entry's arguments inside its optional call). + - **L1's move.** `callHeadersFor`, the per-call writer the plane adapter's `prepareHeaders` calls, leaves `lifecycle.ts` for `request/headers.ts`, beside the patch's own header writer; the two share one origin builder. + - **The body, parsed once.** The base parsed a claimed body up to three times (the free-model check, the fallback, the debug names over the rewritten text). Now one lazy, memoised parse serves all three, and the fallback (`injectCoreToolsInto`, split out of `maybeInjectCoreTools`) rewrites the shared record in place, only on the path that injects. `maybeInjectCoreTools` keeps its signature and moves to `request/body.ts` as a one-line wrapper over `applyCoreTools` (the stage the patch runs), so the fallback's unit cases (`tool-fallback`, `free-tier-contract`, `plane-table`, `keyed-probes`) drive the live reader and gate rather than a second copy of them; the door names it from `request/body.ts`. `toolNamesOf` in `utils/request-shape.ts` is kept test-only for the door, as `modelIdOf` already was: the debug entry reads `toolNamesIn` over the shared record, and retargeting `request-shape`'s cases at it is left to a phase allowed to change test targets. The readers' disagreement about a Buffer is kept on purpose: the free-model check and the debug names read a string body only (`RequestBody.json`), the fallback a Buffer too (`RequestBody.decoded`). Three green pins hold that before the move (`fetch-patch-tools`' Buffer and string cases, `fetch-patch-observability`'s plain `Uint8Array`), each shown failing under the wrong unification (the free-model check reading a Buffer, the fallback's Buffer branch dropped, the debug names decoding bytes), and `fetch-patch-tools`' parse-count case, run with the body on the init and on a Request, is red on the base (the original text twice and the rewritten text once more) and green after; its zero-parse sibling (a keyed request no reader needs is never parsed) is green on both. + - **Four test files follow the layout by literal, no assertion changed:** `architecture` (the environment rule's file list is every module under `src/request/` plus the two others, with a case that the list holds `request/patch-fetch.ts`; the patch-method graph names `host/discovery.ts`), `planes` (the allowance keys name `credentials.ts`), `keyed-probes` (the e2e-host scope runs on `src/request/patch-fetch.ts` and `src/host/discovery.ts`; the keyed tier does not take `src/request/`), and `usage-pill-mount`, a jsdom test, which imports `STYLES` from `src/usage-css.ts` itself. Comment-only: `host-tokens`, `tool-fallback`, `lifecycle`, `readme-parity`, the four `go-discovery*` headers and the `test/support` headers that named a moved module. + - **CI scope.** The e2e-host scope step takes `src/request/` in place of `src/fetch-patch.ts`, and drops `src/models-discovery.ts` (now under `src/host/`). The keyed-probe tier's scope takes `src/host/`, so a pull request touching the discovery wrapper now arms the keyed probes, which `src/models-discovery.ts` did not: harmless, and a change in when they run. + - **Floors, re-measured on this tree.** `src/credentials.ts` from 100 to 99.5 / 99.5 / 100 / 99.5 (measured 252/253, 226/227, 46/46, 250/251): two undriven branches arrived with go-discovery, `result.status !== "fulfilled"` in `resolveGoKeyForRef` (unreachable: `readCredentialsResolver` never rejects) and the implicit else of `usableCredential(fromOptHeaders)` in `readProviderRow` (reachable, and undriven in go-discovery too); a green pin in `go-discovery`'s nested-options case (a nested block with no usable key answers no literal) now drives the second, so the floor excuses only the unreachable guard. `src/lifecycle.ts` to 97.6 / 82.3 / 100 / 97.5 (measured 42/43, 14/17, 13/13, 40/41: `callHeadersFor`'s covered code left, the same three unreachable branches stayed). The `src/fetch-patch.ts` floor is gone; `src/request/claim.ts`, `body.ts`, `credential.ts` and `headers.ts` carry 100, and `patch-fetch.ts` 100 / 96 / 100 / 100 (27 of 28 branches: the debug entry's `session: headers.get(SESSION_HEADER) ?? null`). 19. **P10b `fix:` catalog state.** - The parse is pure and returns `deprecated`, and a refresh replaces the maps. - The purge makes one edit per entry. @@ -544,7 +550,7 @@ How each phase changes now that it sits on `main` 1.8.0 and on both harness chan | 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). **As landed:** all of them, with the `piKnows` assertion dropped: no other row uses that pi premise, and a hard assertion on pi's data would gate every channel's run on a fact the plugin no longer reads, while `PROTOCOL_FOR_SDK` in `test/protocols.test.ts` pins the plugin's own rule; L6 and L11 as their rows below say. | | 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. **As landed:** they apply on re-apply, and the card says so once above its controls (`appliesOnReapply`), as both READMEs do; `host-planes` performs it on the real host in both channels (a volatile edit of the plugin's own row, then a re-apply). Reading per call is not a refactor: `lifecycle.ts` mounts the usage service at apply only when `usageEnabled` is on, copies `keySource` and `readOpencodeStore` into the services it builds, and the route claim reads `endpoint` once. The catalog's `lastError` on the card is carried to P10b: no health snapshot exists, `refreshCatalog` swallows its error, and the carrier would be a remote contract that P9 reshapes over catalog state that P10b rewrites. | | P9 | A loopback triple guard, only if a `webServer` route appears. **As landed:** no `webServer` route appeared; nothing built (L14). | -| 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`. | +| P10a | L1's per-call shaping is the first move of `fetch-patch` into `request/` (landed: `callHeadersFor` is in `request/headers.ts` beside the patch's own header stage). L4, carried from P6 and again from P10a (P-R2 measured nothing, and no keyed variants run was made in P10a): 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. The catalog's `lastError` on the card (L14), carried from P8: the refresh keeps its last error with the state it rewrites, and the card shows it beside the purge row. | | P11, P12 | Unchanged. | @@ -557,7 +563,7 @@ 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 | 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 | +| 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, and P10a ran no keyed variants (the sandbox blocks the gateway); carried on with the next variants run. P6 moved the header into the shared table (`planeHeadersFor`), so the decision is still 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 | Adopted in P7: `CLIENT_GENERATIONS` (`src/utils/client-generation.ts`) records each generation's User-Agent format, plane and relay session headers, parent and origin headers, what the session headers carry and its evidence; the plugin emulates 1.x, and `planeHeadersFor` and `identity.ts` read that row; the 2.x row is recorded and read by nothing, pins no 2.x version, and says its facts are recorded rather than measured. The self-disagreement was a stale comment (`SESSION_ID_HEADER`'s "always sent three of them"), now a pointer to the table, and three doc copies: `docs/upstream-findings.md` §0 and §1.2 now name the tag's `request.ts` branches and mark the `runner/llm.ts` block as an earlier, unreconciled reading (most likely of `dev`), its §1.3 consequence says two session headers on a plane and four on a relay, and `docs/deep-dive.md` §2's subagent example and `docs/engineering-notes.md`'s relay note follow the table. `sessionValue` is recorded and read by nothing, so a switch to 2.x also needs the affinity id plumbed in; it is not a one-word change | | 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 | @@ -783,7 +789,7 @@ The vendor's own first-party DSH plugin, `@opencode/console` 0.1.10 (`anomalyco/ - **Pin first, green on the base (`359ae87`) with no expectation changed:** `plane-table` (every caller's plane for a route and a URL: the meter's Zen test, the captured key's tier, the discovery wrapper's plane, the core-tool fallback's row, billing per route including the case-sensitive `OpenCode-Go`), `usd-callers` (the session's metered spend to the cent, and the allowance in both views), `model-metadata`'s level-name scan across files, `request-shape`'s User-Agent literal, `purge-service`'s per-plane case, `credentials`' declared-variable edges (an `opencode-go-*` relay off the planes takes the Zen variable; a URL on a plane decides alone, whatever the route is named) and `usage-service-readings`' no-key refusal for `opencode-google`, `opencode-go`, `opencode-go-relay` and `my-relay` (only the exact `opencode` overflows). Controls: swapping the credential reader for the relay-inclusive `planeForRoute`, or the meter's no-key check for `isZenProvider`, turns the last two red. - **The one pin-file edit:** `request-shape`'s import of `catalogPlaneForRoute`, renamed to `planeForRoute`. - **Red on the base, landing with the change:** `level-names` (one capitalised level literal and one capitalisation in `model-metadata.ts`'s code, both inside `effortName`; the count covers any capitalised level literal, one today (`"Off"`), and the base has a second `"Off"` in `reasoningFor`). -- **New with the change:** `planes` (the table, its readers, and two source scans, each counted per file and exactly, with a planted addition and a planted removal: the comparisons (the exact comparison, the relay half and a `case` label; allowances `utils/planes.ts` 2, `utils/protocols.ts` 2, `go-discovery.ts` 2), and a quoted route paired with a plane's name in a table row, in either order and under any key name (allowances `utils/planes.ts` 1, `go-discovery.ts` 1 until P10a), with the spellings it does not name planted as non-offenders), `usd`, `client-generation` (the emulated row's names rebuild `planeHeadersFor`'s output; the rest are record checks), `context-windows`, `plane-model`'s L11 case (a seeded window beats the catalog and pi, loses to the user's row and the override, and the other plane's row is ignored) and `models-discovery`'s (catalog-first, measured beats the catalog and pi; pi-first, pi still wins and measured beats the catalog; the other plane's row is ignored). +- **New with the change:** `planes` (the table, its readers, and two source scans, each counted per file and exactly, with a planted addition and a planted removal: the comparisons (the exact comparison, the relay half and a `case` label; allowances `utils/planes.ts` 2, `utils/protocols.ts` 2, `go-discovery.ts` 2, keyed to `credentials.ts` since P10a), and a quoted route paired with a plane's name in a table row, in either order and under any key name (allowances `utils/planes.ts` 1, `go-discovery.ts` 1, keyed to `credentials.ts` since P10a), with the spellings it does not name planted as non-offenders), `usd`, `client-generation` (the emulated row's names rebuild `planeHeadersFor`'s output; the rest are record checks), `context-windows`, `plane-model`'s L11 case (a seeded window beats the catalog and pi, loses to the user's row and the override, and the other plane's row is ignored) and `models-discovery`'s (catalog-first, measured beats the catalog and pi; pi-first, pi still wins and measured beats the catalog; the other plane's row is ignored). - **Test edits that are not pins:** `go-limits` and `session-cost` lose their `formatUsd` cases to `usd`; `protocols`' SDK-table title and its `piKnows` assertion, which is dropped (the plugin's rule is `PROTOCOL_FOR_SDK`'s), and `catalog`'s Mistral note, both reworded to the plugin's own rule. **P8** @@ -802,11 +808,17 @@ The vendor's own first-party DSH plugin, `@opencode/console` 0.1.10 (`anomalyco/ - **Rewritten:** `remote-contract`'s grep half (the services found by regex over `src/*.ts`) now reads `REMOTE_CONTRACTS`: the client registers exactly their descriptors (the contracts' own objects), and the plugin mounted on a real cordis `Context` resolves a service per contract whose `typertRemote` namespace is the contract's and whose `remoteMethods()` are exactly its methods, with one "is reachable" report per contract (a tripwire on the installer's own line). Its unique-ids, `readAccount` and one-parser-per-codec cases are kept. - **New with the change:** `remote-define` (the builder at 100%), `settings-remote`'s `findRemoteCall`, `unwrapRemote` (a table over every envelope shape, including a parser that answers `undefined`, `null` or throws) and `callRemote` (a zero-argument call, one argument passed as one, a rejection rejected), `remote-service`'s `markRemote` (the host's reader, the descriptor flags, a re-mark made twice inside one case, and a `@ts-expect-error` for a contract method the class lacks; each case on a class of its own), `remote-contract`'s D5 identity case and a per-method `typeof … === "function"` check in its mount loop (the marker is written from the contract, so the method list is equal by construction), `settings-remote`'s two cases for a throwing `remote` getter (never read when `ctx.get` resolves; read as no remote when it misses) and the miss case at the caller level in `settings-purge` and `settings-store` (`unavailable` where the base rejected) and in `settings-page`'s meter (its "no usage service" reason where the base threw out of the dock injector), `usage-contract`'s `parseUsageReading`, the D1–D4 cases in the four caller files (with D3's `null` error and wrapped form, and D4's invalid bare `{ value }`), and `architecture`'s client graph reaching `contracts/*` and three one-seam scans (the marker key in `host/remote.ts` only, the envelope reads in `settings-remote.ts` only, the `"opencodeGoUsage"` literal in `contracts/usage.ts` only), each with planted spellings. `src/contracts/remote.ts` carries a 100% per-file floor. +**P10a** + +- **Pin first, green on the base (`24e627d`) with no src edit:** `fetch-patch-tools`' "a Buffer body is rewritten by the fallback and still reported as a missing credential" and "one string body answers the free-model check, the fallback and the debug entry alike", and `fetch-patch-observability`'s "a body that is neither a string nor a Buffer is sent as it came and named as no tools". Controls on the base, each reverted: the free-model check decoding a Buffer fails the first; the fallback's Buffer branch dropped fails the first; the debug names decoding a `Uint8Array` fail the third. Added from the review, each green on the base by reading (the base's fallback wrote `content-length` only beside a rewrite, its debug names read a string body only, and its `readProviderRow` had the same nested-options walk): `fetch-patch-tools`' "a body the fallback does not rewrite goes out with no content-length of the patch's" (the fallback off, a paid model, an unreadable body; a control writing the length before the fallback decides fails it and eight `tool-fallback` cases); a paid-model Buffer carrying tools in `fetch-patch-observability`'s tool-names case, which names none (a control reading `decoded()` for the names fails it); a nested `options` block with no usable key in `go-discovery`'s nested-options case, which answers no literal; four near-miss negatives (`src/request.ts`, `src/requests/x.ts`, `src/utils/request-shape.ts`, `src/hosts/x.ts`) in `keyed-probes`' e2e-host scope case; and `fetch-patch-tools`' "a keyed request no reader needs is never parsed" (a key on the header each route reads, no debug hook, to `/zen/v1/messages` and to `/chat/completions` with the fallback off: no `JSON.parse` of the body text, the session header proving the request was claimed, and the fallback switched on as the known answer, one parse), run on a scratch export of the base and green there; a control that parses eagerly in `readBody`, and one that hoists the debug names out of their optional call, each fail it. +- **Red on the base, landing with the change:** `fetch-patch-tools`' "a claimed request's body is parsed once", run with the body on the init and on a Request (`JSON.parse` of the request's own text or of the text it went out as: 1 call after; the base parsed the original text twice and the rewritten text once more; a control that has the debug names parse the wire text fails both shapes), with its `vi.restoreAllMocks()` in the file's `afterEach`, which only that case's spy needs, `architecture`'s environment rule over `src/request/` (the folder does not exist on the base), `planes`' scans with the allowances keyed to `credentials.ts`, and `keyed-probes`' e2e-host scope case (the base's pattern does not match `src/request/patch-fetch.ts`). +- **Test edits that are not pins, path literals only:** `architecture`, `planes`, `keyed-probes` and `usage-pill-mount` (above, "As landed"); the door's blocks; comment-only edits in `host-tokens`, `tool-fallback` (its header names `request/body.ts`'s `maybeInjectCoreTools` and `withSentBody`'s reference check) and `test/support`. + ## 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 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). +**When it runs:** on dispatch, nightly, and on PRs that touch the host seam — `src/host/**` (the discovery wrapper among it since P10a) and, beside it, `src/lifecycle.ts`, `src/identity.ts` and `src/cordis-context.ts`, whose behaviour depends on the real loader and apply order, and the two that still carry host-level patches outside `src/host/` (`src/request/**`, the global fetch wrapper's stages since P10a, whose order the probe reads, installed by `src/host/global-fetch.ts` since P6, 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). **What it does:** diff --git a/docs/protocol-routing-and-merge.md b/docs/protocol-routing-and-merge.md index 380a7af..ceace42 100644 --- a/docs/protocol-routing-and-merge.md +++ b/docs/protocol-routing-and-merge.md @@ -97,7 +97,7 @@ The user sees a single OpenCode provider per plane and a single model list. Noth | One list | A plane lists the models its entry declares, and the whole catalog when it declares none (D3). A model's protocol is not part of what the user picks, so it cannot fall out of sync with the picker. | | Computed from data | `provider_npm` → protocol → base, rebuilt whenever the plane entry changes. Nothing is stored, so a catalog refresh changes routing with no migration. | | Registered by the plugin, configured in pi-ai | The plane entries stay in `llm-pi-ai`'s `providers` block; the plugin claims the two routes and leaves every other route to pi-ai. | -| One place adds the headers | `fetch-patch.ts` writes the origin proof, the session id and the project attribution for every claimed route, so those do not vary by protocol. | +| One place adds the headers | `request/headers.ts` writes the origin proof, the session id and the project attribution for every claimed route, so those do not vary by protocol. | Two guards keep the invisible half honest, because **a mechanism that silently drops a model looks exactly like a model that does not exist**: @@ -115,7 +115,7 @@ Four sources, in a fixed order, because they answer different questions: | `src/catalog-data.ts` (bundled shim) | "what can I offer before any network call?" | cold start, offline | | models.dev | "what is this model's canonical spec, price and display name?" | SWR refresh | | Gateway `/models` | "what does **this account** actually have?" | per listing request | -| `models-discovery.ts` | "what should `discoverModels` answer?" | per discovery call | +| `host/discovery.ts` | "what should `discoverModels` answer?" | per discovery call | **The merge is additive, and it never drops a row it cannot explain.** Adapter rows are preserved; canonical rows are appended when a model is missing; a row is omitted only when the registry itself marks it `status: "deprecated"`, a fact rather than a guess. Display names and prices come from models.dev, because a gateway listing carries ids and little else. @@ -137,9 +137,9 @@ What belongs here is only the part that is a routing consequence: the meter is a | :-- | :-- | | Which protocol and endpoint a model is served on | `utils/protocols.ts`, `utils/plane-model.ts`, `utils/plane-profile.ts` | | Serving the planes | `host/route-claim.ts`, `host/plane-provider.ts`, `host/describe-graft.ts` | -| Catalog merge | `models-catalog.ts`, `models-discovery.ts`, `catalog-data.ts` | +| Catalog merge | `models-catalog.ts`, `host/discovery.ts`, `catalog-data.ts` | | Allowance table | `go-limits-data.ts` (generated) | -| Credentials and the `/usage` endpoint | `go-discovery.ts`, `key-capture.ts` | +| Credentials and the `/usage` endpoint | `credentials.ts`, `key-capture.ts` | | The usage Host service | `usage.ts`, `contracts/usage.ts` | -| Meter state / views / logic | `usage-pill.tsx`, `usage-panel.tsx`, `usage-ui.ts` | +| Meter state / views / logic | `usage-pill.tsx`, `usage-panel.tsx`, `usage-state.ts`, `usage-copy.ts`, `usage-time.ts`, `usage-css.ts` | | Settings card and its summary | `settings-card.tsx`, `settings-usage.tsx` | diff --git a/docs/redirect-planes.md b/docs/redirect-planes.md index a51a813..17b1643 100644 --- a/docs/redirect-planes.md +++ b/docs/redirect-planes.md @@ -105,17 +105,17 @@ One model, every stage. The left column is what a user can see; the right column | # | The user sees | What runs | Where | | --: | :-- | :-- | :-- | -| 1 | a model in the picker | the picker lists the plane's declared models, or its servable catalog when the entry declares none (D3), with the generated shim answering cold and `models.opencode.ai` refreshing it. Settings' fetch offers pi's list plus the catalog models pi lacks | `catalog-data.ts` → `models-catalog.ts` → `utils/plane-profile.ts` (picker) · `models-discovery.ts` (Settings' fetch) | +| 1 | a model in the picker | the picker lists the plane's declared models, or its servable catalog when the entry declares none (D3), with the generated shim answering cold and `models.opencode.ai` refreshing it. Settings' fetch offers pi's list plus the catalog models pi lacks | `catalog-data.ts` → `models-catalog.ts` → `utils/plane-profile.ts` (picker) · `host/discovery.ts` (Settings' fetch) | | 2 | _(invisible)_ | each row carries the SDK the vendor ships (`provider_npm`). Nothing in the UI names it, and nothing the user sets can contradict it | the catalog | | 3 | one model selected | the composer sets `provider` + `model`; no route, protocol or endpoint appears anywhere in the interface | the host | | 4 | a turn starts | `llm/stream` fires; the hook claims the turn only for the routes this plugin declares, and leaves every other provider alone | `stream-hook.ts` | | 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 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` | +| 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` · `request/` · `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` | +| 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-state.ts` · `usage-copy.ts` · `usage-time.ts` · `usage-css.ts` | | 12 | a settings card | the same store feeds the configuration card; the meter's own switch is the only control that turns it off | `settings-page.tsx` · `settings-card.tsx` | Read the table as a chain of guarantees. Steps 1–3 are why the front end is one list; 4–8 are why it works without configuration; 9–12 are why the result is legible. Break any link and the failure surfaces somewhere far from its cause: diff --git a/docs/upstream-findings.md b/docs/upstream-findings.md index 04c4f8c..4ea8197 100644 --- a/docs/upstream-findings.md +++ b/docs/upstream-findings.md @@ -196,7 +196,7 @@ const ModelSchema = z.object({ Recorded in [`docs/engineering-notes.md`](./engineering-notes.md). OpenCode 1.19.5 sent `x-opencode-request` carrying the user message's id (`input.user.id` in `packages/opencode/src/session/llm/request.ts`, in the same branch as `x-opencode-client` and `x-opencode-project`); 2.x dropped it. This was blocked for a round because the turn state carries no message id — `value` is the session's derived id, a different object — and the hook's options carry none either, because the adapter builds the body after the hook returns. -**Lifted by minting rather than by plumbing a host value**: `newOpenCodeMessageId` in `src/session.ts` produces a fresh `msg_` + 12 hex + 14 base62 value per turn (clock + counter in the hex field, `randomBytes` in the suffix), `stream-hook.ts` stores it as `requestValue` in the turn state, and `fetch-patch.ts` sends it beside the client and project headers. A minted id is not literally the user's message id, and the trade is deliberate: nothing in either released tree reads the value back the way session affinity reads a session id — the console forwards it to the inference service as `x-opencode-request-id` for per-request accounting — so a well-formed value with the client's own lifecycle is as much as a request can honestly carry. Deriving it from message content was rejected rather than overlooked: a digest of the user's own text travelling in a header is a guessable fingerprint, and the vendor's ids are random. +**Lifted by minting rather than by plumbing a host value**: `newOpenCodeMessageId` in `src/session.ts` produces a fresh `msg_` + 12 hex + 14 base62 value per turn (clock + counter in the hex field, `randomBytes` in the suffix), `stream-hook.ts` stores it as `requestValue` in the turn state, and the plane headers' one table (`planeHeadersFor`, written per call by the plane adapter and by `request/headers.ts`) sends it beside the client and project headers. A minted id is not literally the user's message id, and the trade is deliberate: nothing in either released tree reads the value back the way session affinity reads a session id — the console forwards it to the inference service as `x-opencode-request-id` for per-request accounting — so a well-formed value with the client's own lifecycle is as much as a request can honestly carry. Deriving it from message content was rejected rather than overlooked: a digest of the user's own text travelling in a header is a guessable fingerprint, and the vendor's ids are random. One divergence worth recording: the client sends ONE id per user message, so a multi-step tool turn repeats the same value; this plugin mints per streamed turn, because nothing on this side of the adapter offers a DSH message id that would make the larger unit reachable. The header is therefore present and well-formed, but its grouping is the turn's rather than the message's. diff --git a/src/contracts/usage.ts b/src/contracts/usage.ts index 1e01548..f02f79f 100644 --- a/src/contracts/usage.ts +++ b/src/contracts/usage.ts @@ -373,3 +373,47 @@ export const usageRemote = defineRemote(USAGE_NAMESPACE, { result: usageReading, }, }); + +/** + * A failed usage read, normalized from whatever the Host remote threw. + * + * `configured === false` is the "no credential at all" state: a configuration + * fact rather than a fault, which the meter renders as nothing instead of an + * unavailable state the user cannot act on. + */ +export interface UsageFailure { + configured?: boolean; + message?: string; + retainPrevious: boolean; + /** Why the read failed; `auth` is a rejected credential, not an outage. */ + reason?: string; + source?: string; +} + +/** Normalize a Host remote rejection into a {@link UsageFailure}. */ +export const parseFailure = (error: unknown): UsageFailure => { + if ( + typeof error === "object" && + error !== null && + "code" in error && + error.code === "opencode-go/usage-unavailable" + ) { + const details = + "details" in error && isRecord(error.details) ? error.details : {}; + return { + ...(details.configured === false ? { configured: false } : {}), + message: + "message" in error && typeof error.message === "string" + ? error.message + : undefined, + reason: typeof details.reason === "string" ? details.reason : undefined, + retainPrevious: + details.retryable === true && details.retainPrevious === true, + source: typeof details.source === "string" ? details.source : undefined, + }; + } + return { + message: error instanceof Error ? error.message : String(error), + retainPrevious: false, + }; +}; diff --git a/src/credentials.ts b/src/credentials.ts index 4065b45..d7aa446 100644 --- a/src/credentials.ts +++ b/src/credentials.ts @@ -1,7 +1,9 @@ /** - * The fetch patch's credential resolver, and the store it learns keys into. + * Every credential the plugin reads: the fetch patch's resolver, the store it + * learns keys into, and the meter's discovery of the Go plan's key and + * endpoint. * - * Three effects, each over the pure rules in `utils/credential-policy.ts`: + * Four 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 @@ -14,12 +16,26 @@ * 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 wire is never replaced. 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. + * - **The meter's discovery and key resolution** (`discoverGoConfig`, + * `resolveGoBaseURL`, `resolveGoApiKey`, `resolveZenCreditInfo`). The Go + * plan's key and endpoint normally live in another plugin's row (an + * `llm-pi-ai` provider registry or a standalone `opencode-go` entry) rather + * than in this one, so this half reads what the composition already declares + * and falls back to a built-in default. There is deliberately **no** row + * setting for the credential reference: a knob here would duplicate the + * provider row's own `apiKeyEnv`, and the live request is the better source + * anyway (`key-capture.ts`). `usageBaseURL` remains as the one endpoint + * override. The sources are ordered against each other by `METER_ORDER`. + * + * The fill and the meter's key resolution both read the process environment, + * and both read it here: the fill nowhere else, the meter after the host's + * credentials service. Credential *capture* (pulling a key off a live request + * and classifying its tier) lives in `key-capture.ts`. * * Nothing here logs a key, and nothing here throws. * @@ -28,6 +44,8 @@ import os from "node:os"; +import { DEFAULT_USAGE_BASE_URL, DEFAULT_USAGE_KEY_ENV } from "./config.ts"; +import { loaderOfContext, readCredentialsResolver } from "./cordis-context.ts"; import { extractApiKeyFromHeaders, type KeyTier, @@ -40,12 +58,19 @@ import { FILL_ORDER, type FillSource, firstUsable, + firstUsableAsync, type KeySourcePolicy, mayCapture, + METER_ORDER, strike, usableKey, } from "./utils/credential-policy.ts"; import { isRecord } from "./utils/guards.ts"; +import { + foreignCredentialsRealm, + pluginMarkerOf, + type RealmSide, +} from "./utils/plane-ownership.ts"; import { planeOfPlaneRoute } from "./utils/planes.ts"; /** What the gateway's answer says about the key a request carried. */ @@ -527,3 +552,441 @@ export const createCredentials = ( }, }; }; + +/** Gateway settings found in other entries, if any. */ +export interface DiscoveredGoConfig { + baseURL?: string; + keyEnv?: string; + literalKey?: string; +} + +/** + * A configured string that is worth treating as a credential. + * + * Two rejections, and both are load-bearing rather than tidiness: + * + * - **Whitespace.** `apiKey: " "` is what a YAML file produces when someone + * indents a secret they then blank out. It passes a bare `length > 0`, and + * since `literal` is the FIRST step of both `auto` and `configured`, it would + * outrank a working stored credential. `config-values.ts:readString` already + * trims, so this is also where the two halves of the repo used to disagree. + * - **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. 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 => + usableKey(value) !== undefined; + +const readProviderRow = ( + row: Record, + into: DiscoveredGoConfig +): void => { + const keyEnv: unknown = row.apiKeyEnv; + if (typeof keyEnv === "string" && keyEnv.length > 0) { + into.keyEnv = keyEnv; + } + if (into.literalKey === undefined && usableCredential(row.apiKey)) { + into.literalKey = row.apiKey.trim(); + } + const baseURL: unknown = row.baseURL; + if (typeof baseURL === "string" && baseURL.length > 0) { + into.baseURL = baseURL; + } + + if (into.literalKey === undefined) { + const fromHeaders = extractApiKeyFromHeaders(row.headers); + if (usableCredential(fromHeaders)) { + into.literalKey = fromHeaders.trim(); + } + } + if (into.literalKey === undefined && isRecord(row.options)) { + if (usableCredential(row.options.apiKey)) { + into.literalKey = row.options.apiKey.trim(); + } else { + const fromOptHeaders = extractApiKeyFromHeaders(row.options.headers); + if (usableCredential(fromOptHeaders)) { + into.literalKey = fromOptHeaders.trim(); + } + } + } +}; + +/** A property read that a hostile or half-built value cannot throw out of. */ +const readSafely = (value: unknown, key: string): unknown => { + if (!isRecord(value)) { + return undefined; + } + try { + return Reflect.get(value, key); + } catch { + return undefined; + } +}; + +/** + * A provider row this discovery may read: a record that carries no other + * plugin's `x-opencode-plugin` marker (D27). A marked route belongs to the + * plugin that wrote it, and so do its key reference, its literal key and its + * base. + */ +const ownRow = (row: unknown): row is Record => + isRecord(row) && pluginMarkerOf(row) === undefined; + +/** + * Auto-discover OpenCode Go provider configuration from loaded Cordis + * entries (e.g. llm-pi-ai), honoring both shapes it ships in: a + * provider row inside a provider registry, and a standalone entry. + * + * Checks `targetProvider` first if specified, then falls back to `opencode-go` + * and `opencode` (Zen), or any provider pointing to `opencode.ai`. + * + * Later entries win, mirroring composition order. + * + * **Another plugin's entry is never read** (D27): a row whose credentials + * resolve in a realm this context does not resolve (the route claim's own + * rule, `utils/plane-ownership.ts`), and a provider row that carries the + * `x-opencode-plugin` marker. Its reference names a credential this context + * cannot see, or can see only by accident through the environment, and its + * base is that plugin's gateway: the meter sends neither the other plugin's + * token nor the user's own key there. + * + * @param ctx - the plugin context, mock or real. + * @param targetProvider - optional specific provider route id to prioritize. + */ +export const discoverGoConfig = ( + ctx: unknown, + targetProvider?: string +): DiscoveredGoConfig => { + const result: DiscoveredGoConfig = {}; + // The guard RETURNS the loader, so nothing re-reads a property that can throw. + const loader = loaderOfContext(ctx); + if (loader === undefined) { + return result; + } + const own: RealmSide = { + context: ctx, + options: readSafely( + readSafely(readSafely(ctx, "fiber"), "entry"), + "options" + ), + }; + const root = readSafely(ctx, "root"); + + for (const entry of loader.entries()) { + if (!isRecord(entry)) { + continue; + } + const options: unknown = entry.options; + if (!isRecord(options)) { + continue; + } + const config: unknown = options.config; + if (!isRecord(config)) { + continue; + } + if ( + foreignCredentialsRealm( + { context: readSafely(entry, "ctx"), options }, + own, + root + ) !== undefined + ) { + continue; + } + + // 1. Providers inside a provider registry like llm-pi-ai. + const providers: unknown = config.providers; + if (isRecord(providers)) { + if ( + typeof targetProvider === "string" && + targetProvider.length > 0 && + ownRow(providers[targetProvider]) + ) { + readProviderRow(providers[targetProvider], result); + continue; + } + if (ownRow(providers["opencode-go"])) { + readProviderRow(providers["opencode-go"], result); + } else if (ownRow(providers.opencode)) { + readProviderRow(providers.opencode, result); + } else { + for (const pRow of Object.values(providers)) { + if (ownRow(pRow)) { + const bUrl: unknown = pRow.baseURL; + if (typeof bUrl === "string" && bUrl.includes("opencode.ai")) { + readProviderRow(pRow, result); + break; + } + } + } + } + } + + // 2. Standalone provider entries like `id: opencode-go` or `id: opencode`. + if (!ownRow(config)) { + continue; + } + const { id, name } = options; + if ( + typeof targetProvider === "string" && + targetProvider.length > 0 && + (id === targetProvider || name === targetProvider) + ) { + readProviderRow(config, result); + continue; + } + if ( + targetProvider === undefined && + (id === "opencode-go" || + id === "opencode" || + name === "dsh-opencode-go" || + name === "dsh-opencode") + ) { + readProviderRow(config, result); + } + } + + return result; +}; + +/** + * Point a discovered base URL at the Go quota endpoint. + * + * **Both endpoint families have to land on the `zen/go` form, and that is + * measured rather than assumed.** The public quota route is + * `GET /zen/go/v1/usage` and there is no second one: the only route file in + * either major version is + * `packages/console/app/src/routes/zen/go/v1/usage.ts` (checked in 1.19.5 and + * 2.0.32), and the inference proxy's path table + * (`packages/console/app/src/lib/inference-proxy.ts`) lists + * `"GET /zen/go/v1/usage": "/go/v1/usage"` with no `/inference/.../usage` + * counterpart. + * + * The catalog now names the INFERENCE family for the `opencode` provider + * (`api: https://opencode.ai/inference/openai/v1`), so a base discovered from a + * provider row is very often that family. Rewriting only `zen/v1` left it + * untouched, and the meter then asked `…/inference/openai/v1/usage` — a path + * that does not exist — which is an unavailable meter with no explanation. + * + * A URL on neither family (a mirror, a self-hosted gateway) passes through + * untouched: this function does not invent an endpoint it was not given. + * + * @param url - candidate base URL. + */ +export const toGoBaseURL = (url: string): string => { + if (url.includes("opencode.ai/inference")) { + return DEFAULT_USAGE_BASE_URL; + } + if (url.includes("opencode.ai/zen/v1")) { + return url.replace("opencode.ai/zen/v1", "opencode.ai/zen/go/v1"); + } + return url; +}; + +/** + * Base URL for Go quota requests: an explicit non-default config wins, + * otherwise a discovered gateway URL, otherwise the configured default. + * + * @param ctx - the plugin context used for discovery. + * @param configured - the row's `usageBaseURL` setting. + * @param targetProvider - optional specific provider route id to prioritize. + */ +export const resolveGoBaseURL = ( + ctx: unknown, + configured: string, + targetProvider?: string +): string => { + if (configured.length > 0 && configured !== DEFAULT_USAGE_BASE_URL) { + return configured; + } + const discovered = discoverGoConfig(ctx, targetProvider); + if (discovered.baseURL !== undefined && discovered.baseURL.length > 0) { + return toGoBaseURL(discovered.baseURL); + } + return configured; +}; + +/** + * The effective credential reference for Go key lookups. + * + * The composition is the only place a reference comes from: an `apiKeyEnv` + * declared by the provider registry is honoured as-is, and the built-in default + * is the fallback. There is deliberately no row setting for this — a knob here + * would duplicate the provider row's own declaration, which is exactly the + * setting a user has already made once. + * + * @param discovered - result of {@link discoverGoConfig} (reuse when already computed). + */ +export const effectiveGoKeyRef = (discovered: DiscoveredGoConfig): string => + discovered.keyEnv ?? DEFAULT_USAGE_KEY_ENV; + +/** + * Resolve the Go API key without ever exposing it to the client. + * + * 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. + * + * @param ctx - the plugin context used for discovery and credentials. + * @param targetProvider - optional specific provider route id to prioritize. + * @param policy - which source wins when several resolve. + * @param readOpencodeStore - whether the installation's own store may be read + * as the last resort. Off by default. + * @returns the key, or `undefined` when nothing resolves — the caller raises + * the typed `MISSING_CREDENTIAL` error instead of a raw one. + */ +export const resolveGoApiKey = ( + ctx: unknown, + targetProvider?: string, + policy: KeySourcePolicy = "auto", + readOpencodeStore = false +): Promise => { + const discovered = discoverGoConfig(ctx, targetProvider); + 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: () => + resolveOpencodeStoreKey("opencode-go", readOpencodeStore), + }); +}; + +/** + * Resolve one credential reference through the credentials service, then the + * 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. + * + * @param ctx - the plugin context used for credentials. + * @param ref - credential reference to look up. + */ +const resolveRef = async ( + ctx: unknown, + ref: string +): Promise => { + const resolve = readCredentialsResolver(ctx); + if (resolve !== undefined) { + try { + const answer = await resolve(ref); + const hit = usableKey(answer?.value); + if (hit !== undefined) { + return hit; + } + } catch { + // Fall through to the environment. + } + } + return usableKey(process.env[ref]); +}; + +/** + * Whether a resolved value is a usable credential for the Go quota endpoint. + * + * There is no prefix test here any more, and the reason is measured rather than + * argued. This used to reject `oc_sk_…` on the belief that "Zen keys lack the + * OpenCode Go subscription entitlement and will 403 when sent to the Go quota + * endpoint". Probed live on 2026-10-08: an `oc_sk_…` key stored as + * `OPENCODE_GO_API_KEY` answers `/zen/go/v1/usage` with **HTTP 200 and real + * windows** — OpenCode issues that prefix for Go credentials too, so the prefix + * does not name a tier. + * + * The cost of the old guard was not a wasted request; it was the ONE credential + * that worked being thrown away, after which the meter fell through to + * `capturedAny` (or to no key at all) and drew an overflow card with no quota + * anywhere on it. `usage.ts`'s `403 EntitlementError` branch is what handles a + * credential that genuinely lacks Go entitlement — the endpoint's own answer, + * rather than a guess about a string. + */ +const isUsableGoKey = (value: string | undefined): value is string => + usableKey(value) !== undefined; + +/** + * Look one credential reference up for the Go quota endpoint. + * + * Zen keys (`OPENCODE_API_KEY` / `oc_sk_…`) are excluded because Zen keys lack + * the OpenCode Go subscription entitlement and will 403 when sent to the Go + * quota endpoint. That exclusion is why this is not just {@link resolveRef}: the + * routed-provider lookup below must accept a Zen key, because there the Zen tier + * is the target rather than a mistake. + * + * @param ctx - the plugin context used for credentials. + * @param ref - effective credential reference from {@link effectiveGoKeyRef}. + */ +export const resolveGoKeyForRef = async ( + ctx: unknown, + ref: string +): Promise => { + // Deduplicated rather than merely conditional: when the declared reference IS + // the built-in default — which is exactly the common case, since + // `effectiveGoKeyRef` falls back to it — `[ref, DEFAULT]` asks the credentials + // service the same question twice on every meter poll. Order is preserved, + // because order is the policy. + const candidates = + ref === "OPENCODE_API_KEY" || ref === DEFAULT_USAGE_KEY_ENV + ? [DEFAULT_USAGE_KEY_ENV] + : [ref, DEFAULT_USAGE_KEY_ENV]; + + // Every reference is tried through the credentials service before the + // environment is consulted at all, so a stored credential always beats a + // stale exported variable. + const resolve = readCredentialsResolver(ctx); + if (resolve !== undefined) { + const results = await Promise.allSettled( + candidates.map((candidate) => resolve(candidate)) + ); + for (const result of results) { + if (result.status !== "fulfilled") { + continue; + } + const value = result.value?.value; + if (isUsableGoKey(value)) { + return value; + } + } + } + + for (const candidate of candidates) { + const value = process.env[candidate]; + if (isUsableGoKey(value)) { + return value; + } + } + return undefined; +}; + +/** Result of resolving Zen credit/balance status. */ +export interface ZenCreditInfo { + isConfigured: boolean; +} + +/** + * Resolve whether OpenCode Zen pay-as-you-go is configured. + * + * Checks whether an OpenCode Zen key (`OPENCODE_API_KEY` or `oc_sk_...`) + * is configured in DSH credentials or environment. There is no endpoint to ask + * for a balance, so this answers "can the Go plan overflow into Zen credit?" + * rather than "how much credit is left". + * + * @param ctx - plugin context used for credentials service lookup. + */ +export const resolveZenCreditInfo = async ( + ctx: unknown +): Promise => { + if (usableKey(captureStoreFor(ctx).get("opencode", "zen")) !== undefined) { + return { isConfigured: true }; + } + + const zenKey = await resolveRef(ctx, "OPENCODE_API_KEY"); + return { isConfigured: zenKey !== undefined }; +}; diff --git a/src/fetch-patch.ts b/src/fetch-patch.ts deleted file mode 100644 index f15de27..0000000 --- a/src/fetch-patch.ts +++ /dev/null @@ -1,522 +0,0 @@ -/** - * The `fetch` patch: where OpenCode gateway traffic is recognized and fixed. - * - * Only requests the plugin claims (gateway URL match, or a configured - * 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 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 - */ - -import type { AsyncLocalStorage } from "node:async_hooks"; - -import { DEFAULT_GATEWAY_URLS, type ResolvedPluginConfig } from "./config.ts"; -import { - createCaptureStore, - createCredentials, - type FetchCredentials, -} from "./credentials.ts"; -import { extractApiKeyFromHeaders } from "./key-capture.ts"; -import { - type CatalogPlane, - enrichModelsResponse, - isModelsListingUrl, - specOn, -} from "./models-catalog.ts"; -import { - isOpenCodeSessionId, - OPENCODE_UA, - SESSION_HEADER, - digestOf, - sessionIdForRequest, -} from "./session.ts"; -import { maybeInjectCoreTools } from "./tool-fallback.ts"; -import type { ActiveTurnState } from "./turn-store.ts"; -import { needsFill, usableKey } from "./utils/credential-policy.ts"; -import { - ANTHROPIC_VERSION, - authHeaderFor, - gatewayPlaneFor, - headerSourceOf, - planeForUrl, - planeHeadersFor, - pluginMarkerOn, - projectHeaderOf, - requestUrlOf, - toolNamesOf, -} from "./utils/request-shape.ts"; - -/** - * Whether the model a body names is one the gateway admits with no key. - * - * The gateway's free-tier rule is per-model, not per-plane: `allowAnonymous` on - * the model entry admits a request with no key at all, or with the literal - * `public`, and the proxy strips it before forwarding - * (`packages/console/app/src/lib/inference-proxy.ts`, identical in 1.19 and 2.x; - * `docs/upstream-findings.md` §1.5). So "no credential resolved" is only a fault - * for a model that NEEDS one, and reporting it for a free model sends the reader - * to set a key they do not need. - * - * The body is read rather than assumed, because the model is the only thing that - * decides. A plane-level check would be wrong in both directions: the Zen plane - * offers free models, and so does Go, which serves them by subscription key. - * - * @param body - the request body, when there is one to read. - * @returns whether the model it names is flagged free. - */ -const isFreeModelBody = ( - body: RequestInit["body"], - plane: CatalogPlane -): boolean => { - if (typeof body !== "string" || body.length === 0) { - return false; - } - try { - const parsed: unknown = JSON.parse(body); - if (typeof parsed !== "object" || parsed === null) { - return false; - } - const model: unknown = (parsed as Record).model; - // Both JSON routes carry the id under `model`, the Responses API included. - if (typeof model !== "string" || model.length === 0) { - return false; - } - // **The plane's own flag.** A model can be free on one plane and not on the - // other, and this decides whether a credential is required — so the answer - // has to be the plane's. The plane-agnostic lookup searches Go first, which - // today agrees with the plane-aware one for every model in the catalog, and - // is wrong the day it does not. - const spec = specOn(plane, model); - return spec?.is_free === true; - } catch { - return false; - } -}; - -export const hasSessionHeader = ( - input: RequestInfo | URL, - init?: RequestInit -): boolean => { - const source = headerSourceOf(input, init); - if (source === undefined) { - return false; - } - try { - return new Headers(source).has(SESSION_HEADER); - } catch { - return false; - } -}; - -/** - * Determines if a request targets an OpenCode API endpoint. - * - * Two independent claims: a URL containing any configured gateway substring - * (works even with no active turn, which is what keeps session affinity for - * background calls), or a turn routed to a configured provider. - * - * @param url - the request URL. - * @param state - the active turn, when the request belongs to one. - * @param providers - configured provider route keys. - * @param gatewayUrls - URL substrings marking gateway traffic; blank entries - * are ignored, and the caller's absence of a list falls back to the default - * gateway markers. - */ -export const isOpenCodeRequest = ( - url: string, - state: ActiveTurnState | undefined, - providers: Set, - gatewayUrls: readonly string[] = DEFAULT_GATEWAY_URLS -): boolean => { - for (const marker of gatewayUrls) { - if (marker.length > 0 && url.includes(marker)) { - return true; - } - } - if (state !== undefined && providers.has(state.provider)) { - return true; - } - return false; -}; - -/** - * Wrap `fetch` so claimed OpenCode requests carry the gateway's expected - * headers and session id. - * - * @param original - the fetch implementation to wrap (usually `globalThis.fetch`). - * @param als - turn store consulted for the session id of the current turn. - * @param config - resolved plugin configuration. - */ -/** - * What the interceptor needs from the plugin beyond its configuration. - * - * An object rather than more positional parameters, because these are the - * plugin's own seams into the request path and there will be more of them. The - * configuration stays separate: it is what the deployment wrote, and these are - * what the running plugin knows. - */ -export interface FetchPatchHooks { - /** - * The org a plane's credential belongs to, when it has one. - * - * Asked per request rather than captured once, because a login can arrive - * while the process runs. The org is not a setting: it is part of the - * credential, and a request carrying a token without its org is answered as - * though the token were a plain key. - * - * @param plane - the gateway plane the request is bound for. - * @returns the org id, `wrk_...`, or undefined when the plane's credential has - * none — which is every key deployment, and the reason this is optional. - */ - readonly resolveOrg?: (plane: string) => string | undefined; - /** - * One entry per claimed request, for the debug file. - * - * The question it exists to answer is why a request that should have been - * patched was not, or was patched wrongly — which is invisible from the - * outside, because the gateway's answer for a malformed session id reads - * exactly like the answer for a bad credential. So it records what the - * 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 = ( - original: typeof fetch, - als: AsyncLocalStorage, - config: ResolvedPluginConfig, - hooks: FetchPatchHooks = {} -): typeof fetch => { - // 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 - // stepped aside (the realm, which the request cannot show, or the - // marker). Before the URL claim, which would otherwise take the request - // by its gateway URL alone. - if (state?.foreign === true) { - return original.call(this, input, init); - } - const url = requestUrlOf(input); - - if (!isOpenCodeRequest(url, state, config.providers, config.gatewayUrls)) { - return original.call(this, input, init); - } - - const headers = new Headers(headerSourceOf(input, init)); - - // **Another plugin's request goes out as it was sent** (D27). A route that - // 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 (pluginMarkerOn(headers) !== undefined) { - return original.call(this, input, init); - } - - // The body, read once, off whichever half carries it. DSH sends inference as - // fetch(new Request(url, { body })) — so init.body is undefined, and two - // things read it: the free-model check on the credential path below and the - // core-tool fallback after it. The free-model check used to read - // `init.body` alone, so for every DSH turn it answered "not free" and a - // keyless free model was reported as a missing credential. - let bodySource: "request" | "init" | "none" = "none"; - let bodyToPatch: RequestInit["body"] = init?.body; - if (bodyToPatch !== undefined) { - bodySource = "init"; - } else if (input instanceof Request) { - try { - bodyToPatch = await input.clone().text(); - bodySource = "request"; - } catch { - bodyToPatch = undefined; - } - } - - // 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); - const wireHeader = authHeaderFor(url); - // **The Anthropic protocol identifies itself by version**, and nothing below - // this plugin sends it: `@earendil-works/pi-ai`'s anthropic adapter sets - // `anthropic-beta` and `anthropic-dangerous-direct-browser-access` but not - // `anthropic-version` (measured against the installed package), while the - // official client's `@ai-sdk/anthropic` sends `2023-06-01` on every call. - // The vendor's own API treats a Messages request without it as a client error, - // so the plugin supplies it rather than depending on the adapter. - if (wireHeader === "x-api-key" && !headers.has("anthropic-version")) { - headers.set("anthropic-version", ANTHROPIC_VERSION); - } - 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 ${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 - // (`packages/opencode/src/provider/provider.ts:240`, `options: ok ? {} : - // { apiKey: "public" }`) and lets the SDK choose the header: `x-api-key` - // for `@ai-sdk/anthropic`, `x-goog-api-key` for `@ai-sdk/google`, - // `Authorization` for the openai family. Its only per-protocol header of - // its own is `anthropic-beta` (`:211-219`). - // - // A "Bearer fallback" used to be added here for the non-authorization - // shapes, so an Anthropic request carried BOTH headers. That is a - // credential on a header the protocol does not read, and it is not what - // the client does. - } else if ( - plane.length > 0 && - !warnedNoCredential.has(plane) && - // A free model is ADMITTED with no credential at all, so "no credential - // resolved" is not a failure there and saying it is sends the reader to - // a key they do not need. The gateway's own rule is per-model - // (`allowAnonymous` on the model entry, with no key or the literal - // `public` - `docs/upstream-findings.md` §1.5), so the model is asked - // rather than the plane. Keep the placeholder: the proxy strips it for - // an anonymous request anyway, so stripping it here would change nothing - // but would also deprive a keyless-but-paid model of a header to fill. - // - // A body the check cannot read answers "not free", which is the safe - // side - the warning is the status quo, not a new failure. - !isFreeModelBody(bodyToPatch, planeForUrl(url)) - ) { - 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: none", - `a key captured from a live request (policy ${config.keySource}): none`, - `${consulted.declaredName}: ${consulted.declaredSet ? "set" : "unset"}`, - `the installation's own store: ${ - consulted.storeRead ? "read" : "not enabled" - }`, - ]; - console.warn( - `[dsh-opencode-patch] no credential resolved for ${plane}; sending the adapter's placeholder, which the gateway answers with 401. Consulted: ${sources.join("; ")}.`, - "set a key on the route or its env var, or turn on readOpencodeStore to use the key an OpenCode installation already holds" - ); - } - } - - // 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); - } - } - - // 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); - } - - const newInit: RequestInit = { ...init, headers }; - let requestToSend = input; - - // 4. Core tool schema fallback for free-tier /responses models, over the - // body read above; a toolless chat-completions body also gets - // `tool_choice: "none"`. - let finalBody = bodyToPatch; - if (bodyToPatch !== undefined) { - const newBody = maybeInjectCoreTools(url, bodyToPatch, headers, { - enabled: config.injectCoreTools, - modelMarker: config.freeModelMarker, - }); - if (newBody !== bodyToPatch) { - finalBody = newBody; - if (bodySource === "request" && input instanceof Request) { - // The input Request already owns the old body — clone() so the - // caller's stream is never consumed, and send a new Request. - // `method` is restated so the lint can see it — the Request copy - // carries the same method either way. The instanceof repeat is - // there for the type checker. - requestToSend = new Request(input, { - body: newBody, - method: input.method, - }); - } else { - newInit.body = newBody; - } - } - } - - 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 - // the credential itself has no business in a log. - hooks.debug?.({ - auth: extractApiKeyFromHeaders(headers) !== undefined, - bodySource, - claimed: true, - org: headers.get("x-opencode-org-id") ?? null, - plane: gatewayPlaneFor(url), - request: headers.get("x-opencode-request") ?? null, - session: headers.get(SESSION_HEADER) ?? null, - sessionFormat: isOpenCodeSessionId(headers.get(SESSION_HEADER)), - status: response.status, - toolNames: toolNamesOf(finalBody), - url, - userAgent: headers.get("User-Agent") ?? null, - }); - - // **A 403 is passed through untouched, with the gateway's own words.** - // - // A revision remapped it to 400 here, so DSH's classifier would stop reading - // it as AUTH. That was the wrong trade: it rewrote a status the gateway - // chose, and the user asked for the opposite — keep the 403, keep the real - // message. Do not rewrite what the gateway said. The CODE is a separate - // matter, and not decided here: `classifyPiAiError` labels a 403 "AUTH", - // and the conversation replaces an AUTH failure's message with "API key is - // invalid" (both channels' `dsh-client-ui-chat`), so on the planes - // `PlaneAdapter` finishes the gateway's typed refusals as `FREE_TIER` or - // `MODEL_UNAVAILABLE` with these words, and this status except on - // Google-protocol models, whose failure text carries none - // (`src/utils/gateway-refusal.ts`). pi-ai's own routes keep the bridge's - // reading. - // - // Measured 403 shapes on this gateway, none of them about a credential: - // FreeTierError "…can only be used from within OpenCode…" - // server_error "Upstream request failed: Model access is disabled" - // WAF 1010 the request did not look like the OpenCode client - // The credential case is a 401 (`Missing API key`, `Invalid API key`). - const method = ( - init?.method ?? - (typeof Request !== "undefined" && input instanceof Request - ? input.method - : "GET") - ).toUpperCase(); - if ( - config.enrichModels && - method === "GET" && - isModelsListingUrl(url, config.gatewayUrls) - ) { - return enrichModelsResponse(url, response); - } - return response; - }; - return patchedFetch; -}; diff --git a/src/go-discovery.ts b/src/go-discovery.ts deleted file mode 100644 index cfff1eb..0000000 --- a/src/go-discovery.ts +++ /dev/null @@ -1,474 +0,0 @@ -/** - * OpenCode Go credential & gateway discovery. - * - * The Go plan's key and endpoint normally live in another plugin's row (an - * `llm-pi-ai` provider registry or a standalone `opencode-go` entry) rather - * than in this one, so this module reads what the composition already declares - * and falls back to a built-in default. There is deliberately **no** row setting - * for the credential reference: a knob here would duplicate the provider row's - * own `apiKeyEnv`, and the live request is the better source anyway - * (`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`, 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 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 { - firstUsableAsync, - METER_ORDER, - usableKey, -} from "./utils/credential-policy.ts"; -import { isRecord } from "./utils/guards.ts"; -import { - foreignCredentialsRealm, - pluginMarkerOf, - type RealmSide, -} from "./utils/plane-ownership.ts"; - -/** Gateway settings found in other entries, if any. */ -export interface DiscoveredGoConfig { - baseURL?: string; - keyEnv?: string; - literalKey?: string; -} - -/** - * A configured string that is worth treating as a credential. - * - * Two rejections, and both are load-bearing rather than tidiness: - * - * - **Whitespace.** `apiKey: " "` is what a YAML file produces when someone - * indents a secret they then blank out. It passes a bare `length > 0`, and - * since `literal` is the FIRST step of both `auto` and `configured`, it would - * outrank a working stored credential. `config-values.ts:readString` already - * trims, so this is also where the two halves of the repo used to disagree. - * - **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. 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 => - usableKey(value) !== undefined; - -const readProviderRow = ( - row: Record, - into: DiscoveredGoConfig -): void => { - const keyEnv: unknown = row.apiKeyEnv; - if (typeof keyEnv === "string" && keyEnv.length > 0) { - into.keyEnv = keyEnv; - } - if (into.literalKey === undefined && usableCredential(row.apiKey)) { - into.literalKey = row.apiKey.trim(); - } - const baseURL: unknown = row.baseURL; - if (typeof baseURL === "string" && baseURL.length > 0) { - into.baseURL = baseURL; - } - - if (into.literalKey === undefined) { - const fromHeaders = extractApiKeyFromHeaders(row.headers); - if (usableCredential(fromHeaders)) { - into.literalKey = fromHeaders.trim(); - } - } - if (into.literalKey === undefined && isRecord(row.options)) { - if (usableCredential(row.options.apiKey)) { - into.literalKey = row.options.apiKey.trim(); - } else { - const fromOptHeaders = extractApiKeyFromHeaders(row.options.headers); - if (usableCredential(fromOptHeaders)) { - into.literalKey = fromOptHeaders.trim(); - } - } - } -}; - -/** A property read that a hostile or half-built value cannot throw out of. */ -const readSafely = (value: unknown, key: string): unknown => { - if (!isRecord(value)) { - return undefined; - } - try { - return Reflect.get(value, key); - } catch { - return undefined; - } -}; - -/** - * A provider row this discovery may read: a record that carries no other - * plugin's `x-opencode-plugin` marker (D27). A marked route belongs to the - * plugin that wrote it, and so do its key reference, its literal key and its - * base. - */ -const ownRow = (row: unknown): row is Record => - isRecord(row) && pluginMarkerOf(row) === undefined; - -/** - * Auto-discover OpenCode Go provider configuration from loaded Cordis - * entries (e.g. llm-pi-ai), honoring both shapes it ships in: a - * provider row inside a provider registry, and a standalone entry. - * - * Checks `targetProvider` first if specified, then falls back to `opencode-go` - * and `opencode` (Zen), or any provider pointing to `opencode.ai`. - * - * Later entries win, mirroring composition order. - * - * **Another plugin's entry is never read** (D27): a row whose credentials - * resolve in a realm this context does not resolve (the route claim's own - * rule, `utils/plane-ownership.ts`), and a provider row that carries the - * `x-opencode-plugin` marker. Its reference names a credential this context - * cannot see, or can see only by accident through the environment, and its - * base is that plugin's gateway: the meter sends neither the other plugin's - * token nor the user's own key there. - * - * @param ctx - the plugin context, mock or real. - * @param targetProvider - optional specific provider route id to prioritize. - */ -export const discoverGoConfig = ( - ctx: unknown, - targetProvider?: string -): DiscoveredGoConfig => { - const result: DiscoveredGoConfig = {}; - // The guard RETURNS the loader, so nothing re-reads a property that can throw. - const loader = loaderOfContext(ctx); - if (loader === undefined) { - return result; - } - const own: RealmSide = { - context: ctx, - options: readSafely( - readSafely(readSafely(ctx, "fiber"), "entry"), - "options" - ), - }; - const root = readSafely(ctx, "root"); - - for (const entry of loader.entries()) { - if (!isRecord(entry)) { - continue; - } - const options: unknown = entry.options; - if (!isRecord(options)) { - continue; - } - const config: unknown = options.config; - if (!isRecord(config)) { - continue; - } - if ( - foreignCredentialsRealm( - { context: readSafely(entry, "ctx"), options }, - own, - root - ) !== undefined - ) { - continue; - } - - // 1. Providers inside a provider registry like llm-pi-ai. - const providers: unknown = config.providers; - if (isRecord(providers)) { - if ( - typeof targetProvider === "string" && - targetProvider.length > 0 && - ownRow(providers[targetProvider]) - ) { - readProviderRow(providers[targetProvider], result); - continue; - } - if (ownRow(providers["opencode-go"])) { - readProviderRow(providers["opencode-go"], result); - } else if (ownRow(providers.opencode)) { - readProviderRow(providers.opencode, result); - } else { - for (const pRow of Object.values(providers)) { - if (ownRow(pRow)) { - const bUrl: unknown = pRow.baseURL; - if (typeof bUrl === "string" && bUrl.includes("opencode.ai")) { - readProviderRow(pRow, result); - break; - } - } - } - } - } - - // 2. Standalone provider entries like `id: opencode-go` or `id: opencode`. - if (!ownRow(config)) { - continue; - } - const { id, name } = options; - if ( - typeof targetProvider === "string" && - targetProvider.length > 0 && - (id === targetProvider || name === targetProvider) - ) { - readProviderRow(config, result); - continue; - } - if ( - targetProvider === undefined && - (id === "opencode-go" || - id === "opencode" || - name === "dsh-opencode-go" || - name === "dsh-opencode") - ) { - readProviderRow(config, result); - } - } - - return result; -}; - -/** - * Point a discovered base URL at the Go quota endpoint. - * - * **Both endpoint families have to land on the `zen/go` form, and that is - * measured rather than assumed.** The public quota route is - * `GET /zen/go/v1/usage` and there is no second one: the only route file in - * either major version is - * `packages/console/app/src/routes/zen/go/v1/usage.ts` (checked in 1.19.5 and - * 2.0.32), and the inference proxy's path table - * (`packages/console/app/src/lib/inference-proxy.ts`) lists - * `"GET /zen/go/v1/usage": "/go/v1/usage"` with no `/inference/.../usage` - * counterpart. - * - * The catalog now names the INFERENCE family for the `opencode` provider - * (`api: https://opencode.ai/inference/openai/v1`), so a base discovered from a - * provider row is very often that family. Rewriting only `zen/v1` left it - * untouched, and the meter then asked `…/inference/openai/v1/usage` — a path - * that does not exist — which is an unavailable meter with no explanation. - * - * A URL on neither family (a mirror, a self-hosted gateway) passes through - * untouched: this function does not invent an endpoint it was not given. - * - * @param url - candidate base URL. - */ -export const toGoBaseURL = (url: string): string => { - if (url.includes("opencode.ai/inference")) { - return DEFAULT_USAGE_BASE_URL; - } - if (url.includes("opencode.ai/zen/v1")) { - return url.replace("opencode.ai/zen/v1", "opencode.ai/zen/go/v1"); - } - return url; -}; - -/** - * Base URL for Go quota requests: an explicit non-default config wins, - * otherwise a discovered gateway URL, otherwise the configured default. - * - * @param ctx - the plugin context used for discovery. - * @param configured - the row's `usageBaseURL` setting. - * @param targetProvider - optional specific provider route id to prioritize. - */ -export const resolveGoBaseURL = ( - ctx: unknown, - configured: string, - targetProvider?: string -): string => { - if (configured.length > 0 && configured !== DEFAULT_USAGE_BASE_URL) { - return configured; - } - const discovered = discoverGoConfig(ctx, targetProvider); - if (discovered.baseURL !== undefined && discovered.baseURL.length > 0) { - return toGoBaseURL(discovered.baseURL); - } - return configured; -}; - -/** - * The effective credential reference for Go key lookups. - * - * The composition is the only place a reference comes from: an `apiKeyEnv` - * declared by the provider registry is honoured as-is, and the built-in default - * is the fallback. There is deliberately no row setting for this — a knob here - * would duplicate the provider row's own declaration, which is exactly the - * setting a user has already made once. - * - * @param discovered - result of {@link discoverGoConfig} (reuse when already computed). - */ -export const effectiveGoKeyRef = (discovered: DiscoveredGoConfig): string => - discovered.keyEnv ?? DEFAULT_USAGE_KEY_ENV; - -/** - * Resolve the Go API key without ever exposing it to the client. - * - * 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. - * - * @param ctx - the plugin context used for discovery and credentials. - * @param targetProvider - optional specific provider route id to prioritize. - * @param policy - which source wins when several resolve. - * @param readOpencodeStore - whether the installation's own store may be read - * as the last resort. Off by default. - * @returns the key, or `undefined` when nothing resolves — the caller raises - * the typed `MISSING_CREDENTIAL` error instead of a raw one. - */ -export const resolveGoApiKey = ( - ctx: unknown, - targetProvider?: string, - policy: KeySourcePolicy = "auto", - readOpencodeStore = false -): Promise => { - const discovered = discoverGoConfig(ctx, targetProvider); - 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: () => - resolveOpencodeStoreKey("opencode-go", readOpencodeStore), - }); -}; - -/** - * Resolve one credential reference through the credentials service, then the - * 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. - * - * @param ctx - the plugin context used for credentials. - * @param ref - credential reference to look up. - */ -const resolveRef = async ( - ctx: unknown, - ref: string -): Promise => { - const resolve = readCredentialsResolver(ctx); - if (resolve !== undefined) { - try { - const answer = await resolve(ref); - const hit = usableKey(answer?.value); - if (hit !== undefined) { - return hit; - } - } catch { - // Fall through to the environment. - } - } - return usableKey(process.env[ref]); -}; - -/** - * Whether a resolved value is a usable credential for the Go quota endpoint. - * - * There is no prefix test here any more, and the reason is measured rather than - * argued. This used to reject `oc_sk_…` on the belief that "Zen keys lack the - * OpenCode Go subscription entitlement and will 403 when sent to the Go quota - * endpoint". Probed live on 2026-10-08: an `oc_sk_…` key stored as - * `OPENCODE_GO_API_KEY` answers `/zen/go/v1/usage` with **HTTP 200 and real - * windows** — OpenCode issues that prefix for Go credentials too, so the prefix - * does not name a tier. - * - * The cost of the old guard was not a wasted request; it was the ONE credential - * that worked being thrown away, after which the meter fell through to - * `capturedAny` (or to no key at all) and drew an overflow card with no quota - * anywhere on it. `usage.ts`'s `403 EntitlementError` branch is what handles a - * credential that genuinely lacks Go entitlement — the endpoint's own answer, - * rather than a guess about a string. - */ -const isUsableGoKey = (value: string | undefined): value is string => - usableKey(value) !== undefined; - -/** - * Look one credential reference up for the Go quota endpoint. - * - * Zen keys (`OPENCODE_API_KEY` / `oc_sk_…`) are excluded because Zen keys lack - * the OpenCode Go subscription entitlement and will 403 when sent to the Go - * quota endpoint. That exclusion is why this is not just {@link resolveRef}: the - * routed-provider lookup below must accept a Zen key, because there the Zen tier - * is the target rather than a mistake. - * - * @param ctx - the plugin context used for credentials. - * @param ref - effective credential reference from {@link effectiveGoKeyRef}. - */ -export const resolveGoKeyForRef = async ( - ctx: unknown, - ref: string -): Promise => { - // Deduplicated rather than merely conditional: when the declared reference IS - // the built-in default — which is exactly the common case, since - // `effectiveGoKeyRef` falls back to it — `[ref, DEFAULT]` asks the credentials - // service the same question twice on every meter poll. Order is preserved, - // because order is the policy. - const candidates = - ref === "OPENCODE_API_KEY" || ref === DEFAULT_USAGE_KEY_ENV - ? [DEFAULT_USAGE_KEY_ENV] - : [ref, DEFAULT_USAGE_KEY_ENV]; - - // Every reference is tried through the credentials service before the - // environment is consulted at all, so a stored credential always beats a - // stale exported variable. - const resolve = readCredentialsResolver(ctx); - if (resolve !== undefined) { - const results = await Promise.allSettled( - candidates.map((candidate) => resolve(candidate)) - ); - for (const result of results) { - if (result.status !== "fulfilled") { - continue; - } - const value = result.value?.value; - if (isUsableGoKey(value)) { - return value; - } - } - } - - for (const candidate of candidates) { - const value = process.env[candidate]; - if (isUsableGoKey(value)) { - return value; - } - } - return undefined; -}; - -/** Result of resolving Zen credit/balance status. */ -export interface ZenCreditInfo { - isConfigured: boolean; -} - -/** - * Resolve whether OpenCode Zen pay-as-you-go is configured. - * - * Checks whether an OpenCode Zen key (`OPENCODE_API_KEY` or `oc_sk_...`) - * is configured in DSH credentials or environment. There is no endpoint to ask - * for a balance, so this answers "can the Go plan overflow into Zen credit?" - * rather than "how much credit is left". - * - * @param ctx - plugin context used for credentials service lookup. - */ -export const resolveZenCreditInfo = async ( - ctx: unknown -): Promise => { - if (usableKey(captureStoreFor(ctx).get("opencode", "zen")) !== undefined) { - return { isConfigured: true }; - } - - const zenKey = await resolveRef(ctx, "OPENCODE_API_KEY"); - return { isConfigured: zenKey !== undefined }; -}; diff --git a/src/models-discovery.ts b/src/host/discovery.ts similarity index 96% rename from src/models-discovery.ts rename to src/host/discovery.ts index cf0ad67..8cec804 100644 --- a/src/models-discovery.ts +++ b/src/host/discovery.ts @@ -13,13 +13,11 @@ * the declared list (or the plane's catalog for an entry that declares none, * which this wrapper does not decide). * - * @module dsh-opencode-patch/models-discovery + * @module dsh-opencode-patch/host/discovery */ -import type { ResolvedPluginConfig } from "./config.ts"; -import type { CordisContext } from "./cordis-context.ts"; -import { patchMethod } from "./host/patch-method.ts"; -import type { RouteClaim } from "./host/route-claim.ts"; +import type { ResolvedPluginConfig } from "../config.ts"; +import type { CordisContext } from "../cordis-context.ts"; import { type CatalogModelSpec, type CatalogProvider, @@ -27,16 +25,18 @@ import { findModelSpecOn, isDeprecatedModelOn, liveCatalogOn, -} from "./models-catalog.ts"; +} from "../models-catalog.ts"; import { MEASURED_CONTEXT_WINDOWS, type MeasuredWindows, measuredWindowFor, -} from "./utils/context-windows.ts"; -import { isRecord } from "./utils/guards.ts"; -import { PLANE_OF_ROUTE, planeOfPlaneRoute } from "./utils/planes.ts"; -import { isPlaneRoute, isServableSdk } from "./utils/protocols.ts"; -import { planeForUrl } from "./utils/request-shape.ts"; +} from "../utils/context-windows.ts"; +import { isRecord } from "../utils/guards.ts"; +import { PLANE_OF_ROUTE, planeOfPlaneRoute } from "../utils/planes.ts"; +import { isPlaneRoute, isServableSdk } from "../utils/protocols.ts"; +import { planeForUrl } from "../utils/request-shape.ts"; +import { patchMethod } from "./patch-method.ts"; +import type { RouteClaim } from "./route-claim.ts"; /** * The patch sites this module installs, one id each. Two activations of the diff --git a/src/host/patch-method.ts b/src/host/patch-method.ts index ff5f93c..4838aec 100644 --- a/src/host/patch-method.ts +++ b/src/host/patch-method.ts @@ -2,7 +2,7 @@ * The one way this plugin wraps a method on a host object. * * Every instance patch in `src/` goes through {@link patchMethod}; today two - * sites: model discovery (`models-discovery.ts`) and the `settings.describe` + * sites: model discovery (`host/discovery.ts`) and the `settings.describe` * graft (`host/describe-graft.ts`). * Wrapping an INSTANCE is enough because the host resolves a service method per * call (F20: the gateway reads it with `Reflect.get` at dispatch), so a wrapper diff --git a/src/key-capture.ts b/src/key-capture.ts index 0a5b19f..81d8f30 100644 --- a/src/key-capture.ts +++ b/src/key-capture.ts @@ -8,8 +8,9 @@ * 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 + * Split out of the meter's discovery (now in `credentials.ts`), which keeps the + * *plan* side (which endpoint, which key reference, and the policy that orders + * the two sources). The seam is * deliberate: everything here is about a credential value, nothing here knows * what a provider row or a base URL looks like. * diff --git a/src/lifecycle.ts b/src/lifecycle.ts index a21eb4c..e212429 100644 --- a/src/lifecycle.ts +++ b/src/lifecycle.ts @@ -30,26 +30,29 @@ import { purgeRemote } from "./contracts/purge.ts"; import { storeRemote } from "./contracts/store.ts"; import { usageRemote } from "./contracts/usage.ts"; import { type CordisContext, readEntryOptions } from "./cordis-context.ts"; -import { captureStoreFor, createCredentials } from "./credentials.ts"; +import { + captureStoreFor, + createCredentials, + resolveGoBaseURL, +} 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 { + decorateModelDiscovery, + type DiscoveryClaim, +} from "./host/discovery.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"; -import { - decorateModelDiscovery, - type DiscoveryClaim, -} from "./models-discovery.ts"; import { OpencodeStoreService } from "./opencode-store-service.ts"; import { ModelPurgeService } from "./purge-service.ts"; +import { callHeadersFor } from "./request/headers.ts"; +import { patchFetch } from "./request/patch-fetch.ts"; import { createStreamHook } from "./stream-hook.ts"; import type { ActiveTurnState } from "./turn-store.ts"; import { GoUsageService } from "./usage.ts"; 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 => { @@ -169,44 +172,6 @@ const installFetchPatch = ( ); }; -/** - * 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 diff --git a/src/request/body.ts b/src/request/body.ts new file mode 100644 index 0000000..432ef14 --- /dev/null +++ b/src/request/body.ts @@ -0,0 +1,248 @@ +/** + * A claimed request's body: read once, parsed at most once, and rewritten by + * the free-tier core-tool fallback when its model needs it. + * + * DSH sends inference as `fetch(new Request(url, { body }))`, so `init.body` is + * undefined and the body has to be read off the Request. Three things read it: + * the free-model check on the credential path, the core-tool fallback, and the + * debug entry's tool names. They used to parse it once each; now the first + * reader parses it and the others share the record. + * + * **The readers do not agree about a Buffer, on purpose.** The fallback + * decodes one and rewrites it; the free-model check and the debug names read a + * string body only, so a Buffer is "not free" (the missing-credential report + * stays, the safe side) and names no tools until the fallback has rewritten it + * into a string. {@link RequestBody.json} is the string-only reading and + * {@link RequestBody.decoded} the fallback's. + * + * @module dsh-opencode-patch/request/body + */ + +import { type CatalogPlane, specOn } from "../models-catalog.ts"; +import { injectCoreToolsInto, isCoreToolUrl } from "../tool-fallback.ts"; +import { isRecord } from "../utils/guards.ts"; + +/** A claimed request's body, as the patch found it. */ +export interface RequestBody { + /** Which half of the call carried it. */ + readonly source: "request" | "init" | "none"; + /** The body as it came: the init's own, or the Request's text. */ + readonly raw: RequestInit["body"]; + /** + * The body parsed, when it is a string holding a JSON object: what the + * free-model check and the debug names read. Parsed on first ask, once. + */ + readonly json: () => Record | undefined; + /** + * The body parsed, when it is a string or a Buffer holding a JSON object: + * what the fallback reads. The same parse as {@link RequestBody.json}. + */ + readonly decoded: () => Record | undefined; +} + +/** The text a body holds, when it is a string or a Buffer. */ +const textOf = (raw: RequestInit["body"]): string | undefined => { + if (typeof raw === "string") { + return raw; + } + if (Buffer.isBuffer(raw)) { + return raw.toString("utf-8"); + } + return undefined; +}; + +/** A body over `raw`, its parse deferred to the first reader that asks. */ +const bodyOf = ( + source: RequestBody["source"], + raw: RequestInit["body"] +): RequestBody => { + let parsed: + | { readonly value: Record | undefined } + | undefined; + const decoded = (): Record | undefined => { + if (parsed === undefined) { + const text = textOf(raw); + let value: unknown; + if (text !== undefined && text.length > 0) { + try { + value = JSON.parse(text); + } catch { + value = undefined; + } + } + parsed = { value: isRecord(value) ? value : undefined }; + } + return parsed.value; + }; + return { + decoded, + json: () => (typeof raw === "string" ? decoded() : undefined), + raw, + source, + }; +}; + +/** + * Read a claimed request's body, off whichever half carries it. + * + * The init's body first; else the Request's, read from a clone so the + * caller's stream is never consumed. A Request whose body is already spent + * answers no body, and is sent as it stands. + * + * @param input - the request or URL `fetch` was called with. + * @param init - the call's init, when it had one. + */ +export const readBody = async ( + input: RequestInfo | URL, + init: RequestInit | undefined +): Promise => { + // The free-model check used to read `init.body` alone, so for every DSH + // turn it answered "not free" and a keyless free model was reported as a + // missing credential. + const own = init?.body; + if (own !== undefined) { + return bodyOf("init", own); + } + if (input instanceof Request) { + try { + return bodyOf("request", await input.clone().text()); + } catch { + return bodyOf("none", undefined); + } + } + return bodyOf("none", undefined); +}; + +/** + * Whether the model a body names is one the gateway admits with no key. + * + * The gateway's free-tier rule is per-model, not per-plane: `allowAnonymous` on + * the model entry admits a request with no key at all, or with the literal + * `public`, and the proxy strips it before forwarding + * (`packages/console/app/src/lib/inference-proxy.ts`, identical in 1.19 and 2.x; + * `docs/upstream-findings.md` §1.5). So "no credential resolved" is only a fault + * for a model that NEEDS one, and reporting it for a free model sends the reader + * to set a key they do not need. + * + * The body is read rather than assumed, because the model is the only thing that + * decides. A plane-level check would be wrong in both directions: the Zen plane + * offers free models, and so does Go, which serves them by subscription key. + * + * @param body - the request body, when there is one to read. + * @param plane - the plane the request's URL is bound for. + * @returns whether the model it names is flagged free. + */ +export const isFreeModelBody = ( + body: RequestBody, + plane: CatalogPlane +): boolean => { + // Both JSON routes carry the id under `model`, the Responses API included. + const model: unknown = body.json()?.model; + if (typeof model !== "string" || model.length === 0) { + return false; + } + // **The plane's own flag.** A model can be free on one plane and not on the + // other, and this decides whether a credential is required — so the answer + // has to be the plane's. The plane-agnostic lookup searches Go first, which + // today agrees with the plane-aware one for every model in the catalog, and + // is wrong the day it does not. + return specOn(plane, model)?.is_free === true; +}; + +/** The body a request goes out with, and the record it was written from. */ +export interface SentBody { + /** The body to send: the raw one, unless the fallback rewrote it. */ + readonly body: RequestInit["body"]; + /** The rewritten body's record; `undefined` when the body went as it came. */ + readonly record: Record | undefined; +} + +/** + * The free-tier core-tool fallback over a claimed request's body: `read` and + * `bash` for a free-tier model on `/responses` or `/chat/completions`, and + * `tool_choice: "none"` for a toolless completions body (`tool-fallback.ts`). + * + * @param url - the request URL. + * @param body - the body {@link readBody} read. + * @param headers - the outgoing headers, whose `content-length` tracks a + * rewritten body. + * @param options - whether the fallback is on and which marker scopes it. + */ +export const applyCoreTools = ( + url: string, + body: RequestBody, + headers: Headers, + options: { enabled: boolean; modelMarker: string } +): SentBody => { + const unchanged: SentBody = { body: body.raw, record: undefined }; + if (!options.enabled || !isCoreToolUrl(url)) { + return unchanged; + } + const record = body.decoded(); + if ( + record === undefined || + !injectCoreToolsInto(url, record, options.modelMarker) + ) { + return unchanged; + } + const text = JSON.stringify(record); + headers.set("content-length", Buffer.byteLength(text).toString()); + return { body: text, record }; +}; + +/** + * Inject `read` + `bash` schemas into a free-tier completions body. + * + * {@link applyCoreTools} over a body handed in directly, so the fallback's + * unit cases drive the reader and the gate the fetch patch runs rather than a + * second copy of them. A declared `read`/`bash` without `properties` is + * replaced, never duplicated; a chat-completions body that had no tools of + * its own also gets `tool_choice: "none"`, and a `/responses` body never gets + * a `tool_choice`. + * + * @param url - request URL (supports `/responses` and `/chat/completions`). + * @param body - the outgoing request body. + * @param headers - the mutable header bag whose `content-length` must track a + * rewritten body. + * @param options - whether injection is enabled and which model marker scopes it. + * @returns the (possibly rewritten) body; the original reference when untouched. + */ +export const maybeInjectCoreTools = ( + url: string, + body: RequestInit["body"], + headers: Headers, + options: { enabled: boolean; modelMarker: string } +): RequestInit["body"] => + applyCoreTools(url, bodyOf("init", body), headers, options).body; + +/** + * The call that sends a rewritten body. + * + * @param input - the request or URL `fetch` was called with. + * @param init - the outgoing init, the patch's headers in it. + * @param body - the body as it was read. + * @param sent - the body to send. + * @returns the input and init to call the wrapped `fetch` with. + */ +export const withSentBody = ( + input: RequestInfo | URL, + init: RequestInit, + body: RequestBody, + sent: SentBody +): { input: RequestInfo | URL; init: RequestInit } => { + if (sent.body === body.raw) { + return { init, input }; + } + if (body.source === "request" && input instanceof Request) { + // The input Request already owns the old body — clone() so the + // caller's stream is never consumed, and send a new Request. + // `method` is restated so the lint can see it — the Request copy + // carries the same method either way. The instanceof repeat is + // there for the type checker. + return { + init, + input: new Request(input, { body: sent.body, method: input.method }), + }; + } + return { init: { ...init, body: sent.body }, input }; +}; diff --git a/src/request/claim.ts b/src/request/claim.ts new file mode 100644 index 0000000..daf07d5 --- /dev/null +++ b/src/request/claim.ts @@ -0,0 +1,114 @@ +/** + * The fetch patch's first stage: whether a request is the plugin's to touch. + * + * Only requests the plugin claims (gateway URL match, or a configured + * 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. + * + * @module dsh-opencode-patch/request/claim + */ + +import { DEFAULT_GATEWAY_URLS, type ResolvedPluginConfig } from "../config.ts"; +import { SESSION_HEADER } from "../session.ts"; +import type { ActiveTurnState } from "../turn-store.ts"; +import { + headerSourceOf, + pluginMarkerOn, + requestUrlOf, +} from "../utils/request-shape.ts"; + +export const hasSessionHeader = ( + input: RequestInfo | URL, + init?: RequestInit +): boolean => { + const source = headerSourceOf(input, init); + if (source === undefined) { + return false; + } + try { + return new Headers(source).has(SESSION_HEADER); + } catch { + return false; + } +}; + +/** + * Determines if a request targets an OpenCode API endpoint. + * + * Two independent claims: a URL containing any configured gateway substring + * (works even with no active turn, which is what keeps session affinity for + * background calls), or a turn routed to a configured provider. + * + * @param url - the request URL. + * @param state - the active turn, when the request belongs to one. + * @param providers - configured provider route keys. + * @param gatewayUrls - URL substrings marking gateway traffic; blank entries + * are ignored, and the caller's absence of a list falls back to the default + * gateway markers. + */ +export const isOpenCodeRequest = ( + url: string, + state: ActiveTurnState | undefined, + providers: Set, + gatewayUrls: readonly string[] = DEFAULT_GATEWAY_URLS +): boolean => { + for (const marker of gatewayUrls) { + if (marker.length > 0 && url.includes(marker)) { + return true; + } + } + if (state !== undefined && providers.has(state.provider)) { + return true; + } + return false; +}; + +/** A claimed request: its URL, and a mutable copy of the headers it carried. */ +export interface ClaimedRequest { + readonly url: string; + readonly headers: Headers; +} + +/** + * Claim a request for the patch, or leave it to go out as it was sent. + * + * @param input - the request or URL `fetch` was called with. + * @param init - the call's init, when it had one. + * @param state - the active turn, when the request belongs to one. + * @param config - the deployment's providers and gateway markers. + * @returns the URL and a copy of the headers to shape, or `undefined` when the + * request is not the plugin's to touch. + */ +export const claimRequest = ( + input: RequestInfo | URL, + init: RequestInit | undefined, + state: ActiveTurnState | undefined, + config: Pick +): ClaimedRequest | undefined => { + // **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 + // stepped aside (the realm, which the request cannot show, or the + // marker). Before the URL claim, which would otherwise take the request + // by its gateway URL alone. + if (state?.foreign === true) { + return undefined; + } + const url = requestUrlOf(input); + + if (!isOpenCodeRequest(url, state, config.providers, config.gatewayUrls)) { + return undefined; + } + + const headers = new Headers(headerSourceOf(input, init)); + + // **Another plugin's request goes out as it was sent** (D27). A route that + // 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 (pluginMarkerOn(headers) !== undefined) { + return undefined; + } + return { headers, url }; +}; diff --git a/src/request/credential.ts b/src/request/credential.ts new file mode 100644 index 0000000..cc46562 --- /dev/null +++ b/src/request/credential.ts @@ -0,0 +1,202 @@ +/** + * The fetch patch's credential stage: fill an empty or placeholder key on a + * claimed request, and fold the gateway's answer back into the key's standing. + * + * Both halves go through `credentials.ts`, the one resolver: what this stage + * owns is which header a protocol reads its key from, the Anthropic version + * the protocol identifies itself by, and the once-per-plane report of a + * request that leaves with no credential. + * + * @module dsh-opencode-patch/request/credential + */ + +import type { FetchCredentials } from "../credentials.ts"; +import { isOpenCodeSessionId, SESSION_HEADER } from "../session.ts"; +import type { ActiveTurnState } from "../turn-store.ts"; +import { + type KeySourcePolicy, + needsFill, + usableKey, +} from "../utils/credential-policy.ts"; +import { + ANTHROPIC_VERSION, + authHeaderFor, + gatewayPlaneFor, + planeForUrl, +} from "../utils/request-shape.ts"; +import { isFreeModelBody, type RequestBody } from "./body.ts"; + +/** What {@link fillCredential} reads. */ +export interface FillInputs { + /** The claimed request's headers, written in place. */ + readonly headers: Headers; + readonly url: string; + /** The active turn, when the request belongs to one. */ + readonly state: ActiveTurnState | undefined; + readonly body: RequestBody; + readonly credentials: FetchCredentials; + /** The deployment's key-source policy, named in the report. */ + readonly keySource: KeySourcePolicy; + /** The planes already reported as missing a credential. */ + readonly warned: Set; +} + +/** What {@link fillCredential} found, for {@link settleCredential}. */ +export interface FilledCredential { + /** The request's own usable key, when it carried one the store may keep. */ + readonly requestKey: string | undefined; + /** The header the request's protocol reads its key from. */ + readonly wireHeader: string; +} + +/** + * Fill a claimed request's credential when its wire key is empty or a + * placeholder, or report once per plane that there was none to fill. + */ +export const fillCredential = ({ + body, + credentials, + headers, + keySource, + state, + url, + warned, +}: FillInputs): FilledCredential => { + // 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 were + // never claimed (`claim.ts`); 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); + const wireHeader = authHeaderFor(url); + // **The Anthropic protocol identifies itself by version**, and nothing below + // this plugin sends it: `@earendil-works/pi-ai`'s anthropic adapter sets + // `anthropic-beta` and `anthropic-dangerous-direct-browser-access` but not + // `anthropic-version` (measured against the installed package), while the + // official client's `@ai-sdk/anthropic` sends `2023-06-01` on every call. + // The vendor's own API treats a Messages request without it as a client error, + // so the plugin supplies it rather than depending on the adapter. + if (wireHeader === "x-api-key" && !headers.has("anthropic-version")) { + headers.set("anthropic-version", ANTHROPIC_VERSION); + } + 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 ${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 + // (`packages/opencode/src/provider/provider.ts:240`, `options: ok ? {} : + // { apiKey: "public" }`) and lets the SDK choose the header: `x-api-key` + // for `@ai-sdk/anthropic`, `x-goog-api-key` for `@ai-sdk/google`, + // `Authorization` for the openai family. Its only per-protocol header of + // its own is `anthropic-beta` (`:211-219`). + // + // A "Bearer fallback" used to be added here for the non-authorization + // shapes, so an Anthropic request carried BOTH headers. That is a + // credential on a header the protocol does not read, and it is not what + // the client does. + } else if ( + plane.length > 0 && + !warned.has(plane) && + // A free model is ADMITTED with no credential at all, so "no credential + // resolved" is not a failure there and saying it is sends the reader to + // a key they do not need. The gateway's own rule is per-model + // (`allowAnonymous` on the model entry, with no key or the literal + // `public` - `docs/upstream-findings.md` §1.5), so the model is asked + // rather than the plane. Keep the placeholder: the proxy strips it for + // an anonymous request anyway, so stripping it here would change nothing + // but would also deprive a keyless-but-paid model of a header to fill. + // + // A body the check cannot read answers "not free", which is the safe + // side - the warning is the status quo, not a new failure. + !isFreeModelBody(body, planeForUrl(url)) + ) { + warned.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: none", + `a key captured from a live request (policy ${keySource}): none`, + `${consulted.declaredName}: ${consulted.declaredSet ? "set" : "unset"}`, + `the installation's own store: ${ + consulted.storeRead ? "read" : "not enabled" + }`, + ]; + console.warn( + `[dsh-opencode-patch] no credential resolved for ${plane}; sending the adapter's placeholder, which the gateway answers with 401. Consulted: ${sources.join("; ")}.`, + "set a key on the route or its env var, or turn on readOpencodeStore to use the key an OpenCode installation already holds" + ); + } + } + return { requestKey, wireHeader }; +}; + +/** What {@link settleCredential} reads. */ +export interface SettleInputs extends FilledCredential { + readonly credentials: FetchCredentials; + /** The headers the request was sent with. */ + readonly headers: Headers; + readonly state: ActiveTurnState | undefined; + /** The gateway's status. */ + readonly status: number; + readonly url: string; +} + +/** + * Fold the gateway's answer into the standing of the key the request carried. + */ +export const settleCredential = ({ + credentials, + headers, + requestKey, + state, + status, + url, + wireHeader, +}: SettleInputs): void => { + // 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, + url, + }); +}; diff --git a/src/request/headers.ts b/src/request/headers.ts new file mode 100644 index 0000000..8152baf --- /dev/null +++ b/src/request/headers.ts @@ -0,0 +1,141 @@ +/** + * The plane headers (session, parent, org, origin), from the one table + * `planeHeadersFor` builds, written by two writers. + * + * - **Per call** ({@link callHeadersFor}): the plane adapter's + * `prepareHeaders` (OC5) writes them on a decorated turn's own requests, + * and marks the turn so the fetch patch leaves them alone (L1's per-call + * shaping). + * - **In the fetch patch** ({@link writePlaneHeaders}): a relay, a turnless + * URL-claimed request and a turn the plane adapter did not shape. On a turn + * the adapter shaped, 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/request/headers + */ + +import type { AsyncLocalStorage } from "node:async_hooks"; + +import type { ResolvedPluginConfig } from "../config.ts"; +import { + digestOf, + isOpenCodeSessionId, + OPENCODE_UA, + SESSION_HEADER, + sessionIdForRequest, +} from "../session.ts"; +import type { ActiveTurnState } from "../turn-store.ts"; +import { + gatewayPlaneFor, + type PlaneHeaderInputs, + planeHeadersFor, + projectHeaderOf, +} from "../utils/request-shape.ts"; + +/** The origin headers a turn carries, when the deployment sends them. */ +const originFor = ( + config: ResolvedPluginConfig, + state: ActiveTurnState | undefined +): PlaneHeaderInputs["origin"] => + config.injectOriginHeaders + ? { + client: config.originClient, + project: config.injectProject + ? projectHeaderOf(state?.project) + : undefined, + request: state?.requestValue, + } + : undefined; + +/** + * 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: originFor(config, state), + parent: state.parentValue, + relay: !state.provider.startsWith("opencode"), + session: state.value, + })) { + headers.set(name, value); + } + state.perCall = true; + }; + +/** What {@link writePlaneHeaders} reads. */ +export interface HeaderStageInputs { + /** The claimed request's headers, written in place. */ + readonly headers: Headers; + readonly url: string; + /** The active turn, when the request belongs to one. */ + readonly state: ActiveTurnState | undefined; + readonly config: ResolvedPluginConfig; + /** The pinned session id a deployment exported under `sessionIdEnv`. */ + readonly sessionPin: (name: string | undefined) => string | undefined; + /** The org a plane's credential belongs to, when the deployment knows it. */ + readonly resolveOrg?: (plane: string) => string | undefined; +} + +/** + * The fetch patch's header stage: the plane headers, unless the plane adapter + * shaped this request per call, and the User-Agent either way. + */ +export const writePlaneHeaders = ({ + config, + headers, + resolveOrg, + sessionPin, + state, + url, +}: HeaderStageInputs): void => { + // 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), + 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 ?? resolveOrg?.(gatewayPlaneFor(url)); + for (const [name, value] of planeHeadersFor({ + org, + origin: originFor(config, state), + parent: state?.parentValue, + relay: !(state?.provider ?? "").startsWith("opencode"), + session: sessionVal, + })) { + headers.set(name, value); + } + } + + // 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); + } +}; diff --git a/src/request/patch-fetch.ts b/src/request/patch-fetch.ts new file mode 100644 index 0000000..c75608a --- /dev/null +++ b/src/request/patch-fetch.ts @@ -0,0 +1,234 @@ +/** + * The `fetch` patch: where OpenCode gateway traffic is recognized and fixed. + * + * Only requests the plugin claims (gateway URL match, or a configured + * 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 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. + * + * The patch is a composition of stages, each a module of its own, in the + * order they run: the claim (`claim.ts`), the body read once (`body.ts`), the + * credential (`credential.ts`), the headers (`headers.ts`), then the body's + * fallback and the call. + * + * @module dsh-opencode-patch/request/patch-fetch + */ + +import type { AsyncLocalStorage } from "node:async_hooks"; + +import type { ResolvedPluginConfig } from "../config.ts"; +import { + createCaptureStore, + createCredentials, + type FetchCredentials, +} from "../credentials.ts"; +import { extractApiKeyFromHeaders } from "../key-capture.ts"; +import { enrichModelsResponse, isModelsListingUrl } from "../models-catalog.ts"; +import { isOpenCodeSessionId, SESSION_HEADER } from "../session.ts"; +import type { ActiveTurnState } from "../turn-store.ts"; +import { gatewayPlaneFor, toolNamesIn } from "../utils/request-shape.ts"; +import { applyCoreTools, readBody, withSentBody } from "./body.ts"; +import { claimRequest } from "./claim.ts"; +import { fillCredential, settleCredential } from "./credential.ts"; +import { writePlaneHeaders } from "./headers.ts"; + +/** + * What the interceptor needs from the plugin beyond its configuration. + * + * An object rather than more positional parameters, because these are the + * plugin's own seams into the request path and there will be more of them. The + * configuration stays separate: it is what the deployment wrote, and these are + * what the running plugin knows. + */ +export interface FetchPatchHooks { + /** + * The org a plane's credential belongs to, when it has one. + * + * Asked per request rather than captured once, because a login can arrive + * while the process runs. The org is not a setting: it is part of the + * credential, and a request carrying a token without its org is answered as + * though the token were a plain key. + * + * @param plane - the gateway plane the request is bound for. + * @returns the org id, `wrk_...`, or undefined when the plane's credential has + * none — which is every key deployment, and the reason this is optional. + */ + readonly resolveOrg?: (plane: string) => string | undefined; + /** + * One entry per claimed request, for the debug file. + * + * The question it exists to answer is why a request that should have been + * patched was not, or was patched wrongly — which is invisible from the + * outside, because the gateway's answer for a malformed session id reads + * exactly like the answer for a bad credential. So it records what the + * 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; +} + +/** + * Wrap `fetch` so claimed OpenCode requests carry the gateway's expected + * headers and session id. + * + * @param original - the fetch implementation to wrap (usually `globalThis.fetch`). + * @param als - turn store consulted for the session id of the current turn. + * @param config - resolved plugin configuration. + * @param hooks - the running plugin's seams into the request path. + */ +export const patchFetch = ( + original: typeof fetch, + als: AsyncLocalStorage, + config: ResolvedPluginConfig, + hooks: FetchPatchHooks = {} +): typeof fetch => { + // 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(); + const claimed = claimRequest(input, init, state, config); + if (claimed === undefined) { + return original.call(this, input, init); + } + const { headers, url } = claimed; + + // The body, read once, off whichever half carries it. Three things read + // it: the free-model check on the credential path, the core-tool fallback + // and the debug entry, and they share one parse. + const body = await readBody(input, init); + + const { requestKey, wireHeader } = fillCredential({ + body, + credentials, + headers, + keySource: config.keySource, + state, + url, + warned: warnedNoCredential, + }); + + writePlaneHeaders({ + config, + headers, + resolveOrg: hooks.resolveOrg, + sessionPin: (name) => credentials.sessionPin(name), + state, + url, + }); + + // 4. Core tool schema fallback for free-tier /responses models, over the + // body read above; a toolless chat-completions body also gets + // `tool_choice: "none"`. + const sent = applyCoreTools(url, body, headers, { + enabled: config.injectCoreTools, + modelMarker: config.freeModelMarker, + }); + const call = withSentBody(input, { ...init, headers }, body, sent); + + const response = await original.call(this, call.input, call.init); + + settleCredential({ + credentials, + headers, + requestKey, + state, + status: response.status, + url, + wireHeader, + }); + + // 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 + // the credential itself has no business in a log. + hooks.debug?.({ + auth: extractApiKeyFromHeaders(headers) !== undefined, + bodySource: body.source, + claimed: true, + org: headers.get("x-opencode-org-id") ?? null, + plane: gatewayPlaneFor(url), + request: headers.get("x-opencode-request") ?? null, + session: headers.get(SESSION_HEADER) ?? null, + sessionFormat: isOpenCodeSessionId(headers.get(SESSION_HEADER)), + status: response.status, + // What was SENT: the rewritten body's record, else the body as it came, + // which names tools only when it is a string. + toolNames: toolNamesIn(sent.record ?? body.json()), + url, + userAgent: headers.get("User-Agent") ?? null, + }); + + // **A 403 is passed through untouched, with the gateway's own words.** + // + // A revision remapped it to 400 here, so DSH's classifier would stop reading + // it as AUTH. That was the wrong trade: it rewrote a status the gateway + // chose, and the user asked for the opposite — keep the 403, keep the real + // message. Do not rewrite what the gateway said. The CODE is a separate + // matter, and not decided here: `classifyPiAiError` labels a 403 "AUTH", + // and the conversation replaces an AUTH failure's message with "API key is + // invalid" (both channels' `dsh-client-ui-chat`), so on the planes + // `PlaneAdapter` finishes the gateway's typed refusals as `FREE_TIER` or + // `MODEL_UNAVAILABLE` with these words, and this status except on + // Google-protocol models, whose failure text carries none + // (`src/utils/gateway-refusal.ts`). pi-ai's own routes keep the bridge's + // reading. + // + // Measured 403 shapes on this gateway, none of them about a credential: + // FreeTierError "…can only be used from within OpenCode…" + // server_error "Upstream request failed: Model access is disabled" + // WAF 1010 the request did not look like the OpenCode client + // The credential case is a 401 (`Missing API key`, `Invalid API key`). + const method = ( + init?.method ?? + (typeof Request !== "undefined" && input instanceof Request + ? input.method + : "GET") + ).toUpperCase(); + if ( + config.enrichModels && + method === "GET" && + isModelsListingUrl(url, config.gatewayUrls) + ) { + return enrichModelsResponse(url, response); + } + return response; + }; + return patchedFetch; +}; diff --git a/src/settings-usage.tsx b/src/settings-usage.tsx index 50fadba..b6082c8 100644 --- a/src/settings-usage.tsx +++ b/src/settings-usage.tsx @@ -33,7 +33,8 @@ import { findRemoteCall, unwrapRemote, } from "./settings-remote.ts"; -import { formatRelativeReset, getWindowState, resetLabel } from "./usage-ui.ts"; +import { getWindowState } from "./usage-state.ts"; +import { formatRelativeReset, resetLabel } from "./usage-time.ts"; import { isRecord } from "./utils/guards.ts"; import { backoffOver, retryUntilAnswered } from "./utils/retry.ts"; import { formatUsd } from "./utils/usd.ts"; diff --git a/src/tool-fallback.ts b/src/tool-fallback.ts index 439222e..8e7481f 100644 --- a/src/tool-fallback.ts +++ b/src/tool-fallback.ts @@ -238,73 +238,50 @@ export const isCoreToolModel = ( return coreToolDecision(row, modelId, marker); }; +/** Whether a URL is a chat-completions one, the route that takes a `tool_choice`. */ +const isCompletionsUrl = (url: string): boolean => + url.includes("/chat/completions") || url.includes("/completions"); + +/** + * Whether a URL is one of the two JSON routes the gateway checks `read` + + * `bash` on: `/responses` and `/chat/completions` (a toolless completions body + * 403s the same way). An Anthropic `/messages` URL names neither, which is why + * there are no Anthropic-dialect schemas here. + * + * @param url - the request URL. + */ +export const isCoreToolUrl = (url: string): boolean => + url.includes(RESPONSES_PATH) || isCompletionsUrl(url); + /** - * Inject `read` + `bash` schemas into a free-tier completions body. + * Inject `read` + `bash` schemas into a parsed free-tier body, in place. * - * A declared `read`/`bash` without `properties` is replaced, never duplicated; - * a chat-completions body that had no tools of its own also gets - * `tool_choice: "none"`, and a `/responses` body never gets a `tool_choice`. + * The record is changed only when the model is in scope, and then always: + * a body this answers `false` for is left exactly as it came, so a caller that + * reads the record afterwards reads what it was given. * * @param url - request URL (supports `/responses` and `/chat/completions`). - * @param body - the outgoing request body. - * @param headers - the mutable header bag whose `content-length` must track a - * rewritten body. - * @param options - whether injection is enabled and which model marker scopes it. - * @returns the (possibly rewritten) body; the original reference when untouched. + * @param parsed - the body, parsed; rewritten in place when this answers true. + * @param modelMarker - the configured free-tier marker. + * @returns whether the body was rewritten. */ -export const maybeInjectCoreTools = ( +export const injectCoreToolsInto = ( url: string, - body: RequestInit["body"], - headers: Headers, - options: { enabled: boolean; modelMarker: string } -): RequestInit["body"] => { - if (!options.enabled) { - return body; - } - // Both JSON routes: the gateway checks read+bash on /responses AND - // /chat/completions (a toolless completions body 403s the same way). An - // Anthropic `/messages` URL names neither, so it never gets this far — which - // is why there are no Anthropic-dialect schemas below. - const isResponses = url.includes(RESPONSES_PATH); - const isCompletions = - url.includes("/chat/completions") || url.includes("/completions"); - if (!isResponses && !isCompletions) { - return body; - } - if (body === undefined || body === null) { - return body; - } - let bodyStr: string | undefined; - if (typeof body === "string") { - bodyStr = body; - } else if (Buffer.isBuffer(body)) { - bodyStr = body.toString("utf-8"); - } else { - return body; - } - if (bodyStr.length === 0) { - return body; - } - let parsed: unknown; - try { - parsed = JSON.parse(bodyStr); - } catch { - return body; - } - if (!isRecord(parsed)) { - return body; - } + parsed: Record, + modelMarker: string +): boolean => { const modelProp: unknown = parsed.model; if (typeof modelProp !== "string") { - return body; + return false; } // The plane is the PATH's, not the route's: a relay serves its Go plane // under a path of the same shape, and the route id there is the user's own // name. const plane = planeForUrl(url); - if (!isCoreToolModel(modelProp, options.modelMarker, plane)) { - return body; + if (!isCoreToolModel(modelProp, modelMarker, plane)) { + return false; } + const isCompletions = isCompletionsUrl(url); const toolsProp: unknown = parsed.tools; // A malformed `tools` value cannot be merged with — replace it, the same // as an absent one, so the request leaves with schemas the gateway accepts. @@ -335,7 +312,5 @@ export const maybeInjectCoreTools = ( if (hadNoTools && isCompletions) { parsed.tool_choice = "none"; } - const newBodyStr = JSON.stringify(parsed); - headers.set("content-length", Buffer.byteLength(newBodyStr).toString()); - return newBodyStr; + return true; }; diff --git a/src/usage-copy.ts b/src/usage-copy.ts new file mode 100644 index 0000000..f9d8315 --- /dev/null +++ b/src/usage-copy.ts @@ -0,0 +1,154 @@ +/** + * The OpenCode Go quota meter's words and links: the actions the panel offers, + * the windows its breakdown names, and the copy its header, badge and tooltip + * render. Pure: the component owns state, this owns wording. + * + * @module dsh-opencode-patch/usage-copy + */ + +import type { GoUsage } from "./contracts/usage.ts"; +import type { AffectingWindowResult } from "./usage-state.ts"; + +/** + * Where a user acts on what this meter shows. The console is the ONLY place a + * balance appears: OpenCode exposes no credit endpoint and the payload carries + * no currency, so no dollar figure can be derived from a percentage. + * `AGENTS.md` → "OpenCode endpoints" records the probed surface behind that. + */ +export const GO_PLAN_URL = "https://opencode.ai/go"; +/** + * The console, which is also where a pay-as-you-go account is topped up. + * + * One URL for both, and deliberately so: it is the only destination verified to + * exist. Every path under `/console/` answers 200 because the console is a + * single-page app, so a probe cannot distinguish a real `/billing` route from a + * catch-all — and a top-up link that 404s in front of a user is worse than one + * that opens the page where top-up lives. + */ +export const CONSOLE_URL = "https://opencode.ai/console"; + +/** One action the panel can offer, as data so the two popovers share a body. */ +export interface PanelAction { + href: string; + labelKey: string; +} + +/** + * What to DO about the quota, rendered inside the GO layer — next to the windows + * it acts on, not parked under the shared footer. + * + * One link, not two. The limits doc went: the panel already names every window + * with its share and its reset time, so the document explained a list the user + * is looking at. A link that restates what is on screen is the same redundancy + * as a card that restates the badge — the doc is one click from the console for + * anyone who wants the policy. + * + * Zen has nothing to add: its single action IS the console on the footer row, + * labelled 充值 because that is what a pay-as-you-go user wants from it. + */ +export const panelActions = (isZen: boolean): readonly PanelAction[] => + isZen ? [] : [{ href: GO_PLAN_URL, labelKey: "usageUpgradePlan" }]; + +/** Markers for one quota window, driving both the breakdown rows and cards. */ +export const BREAKDOWN_WINDOWS: { + cardName: string; + key: "monthly" | "rolling" | "weekly"; + labelKey: string; +}[] = [ + { cardName: "5-Hour", key: "rolling", labelKey: "usage_rolling" }, + { cardName: "Weekly", key: "weekly", labelKey: "usage_weekly" }, + { cardName: "Monthly", key: "monthly", labelKey: "usage_monthly" }, +]; + +/** + * The localized copy the meter's header, badge and Zen card render. + * + * No tooltip line lives here: the trigger's hover explanation used to be a + * second composition off the same inputs, and that seam was the wrong place to + * hang two new keys an older dictionary had never heard of — they rendered raw + * the first boot a user took the new bundle with an old locale registration. + * The tooltip is `headline` until that API earns its own contract. + */ +export interface UsageCopy { + badgeText: string; + /** + * What the panel header names: the ACCOUNT, not its state. + * + * `OpenCode Go` beside `Go Plan` / the limit badge, exactly as `OpenCode Zen` + * sits beside `Pay-as-you-go`. The header used to carry `headline` — the + * ring's own figure — which made the one line that identifies the surface + * change every poll: it read `42% of Weekly used`, then `Monthly quota + * limited`. Both facts are already on screen (the badge, and each window's + * own row), so the line that should be stable was the one that moved. + */ + title: string; + /** + * The ring explained in words — what the GO trigger says on hover. + * + * It names the bottleneck window ("90% of Weekly used"). It is a sentence + * ABOUT A RING, which is why it cannot also be the Zen trigger's label: the + * Zen trigger shows session spend and has no ring, and binding it to this + * string is what made the hover say nothing but the account name. + */ + headline: string; + /** + * The trigger's hover label, per provider. + * + * A tooltip has to MEAN the number beside it. Go's number is a ring, so + * `headline` explains it. Zen's number is session spend, and the question that + * raises is "is this metered?" — answered here once, in words, rather than by + * repeating the panel header (which is `title`, and is already on screen). + */ + tooltip: string; + zenCardCredit: string; +} + +/** + * Derive the meter's user-facing copy from the active reading. + * + * Pure: the component owns state, this owns wording. `t` is the bound + * translator; `affecting` is the bottleneck window (or `undefined` while the + * first read is in flight). + */ +export const describeUsage = ( + _usage: GoUsage | undefined, + affecting: AffectingWindowResult | undefined, + isZen: boolean, + t: (key: string) => string +): UsageCopy => { + const isLimited = affecting?.window.status === "rate-limited"; + const percent = affecting?.window.percent ?? 0; + + const title = isZen ? t("zenPaygTitle") : t("goPlanTitle"); + + const headline = isLimited + ? `${affecting?.label} quota limited` + : `${percent}% of ${affecting?.label ?? "quota"} used`; + + // The trigger's hover label. Go's number IS a ring, so the headline explains + // it; Zen's number is session spend, which asks a different question — + // "is this metered?" — and gets the one honest answer we have. + const tooltip = isZen ? t("zenPaygTooltip") : headline; + + let badgeText: string; + if (isZen) { + badgeText = t("zenPaygBadge"); + } else if (isLimited) { + badgeText = t("usageLimited"); + } else { + // Nothing. The header already reads `OpenCode Go`, so a `Go Plan` chip + // beside it repeats the title and adds no fact — the same test every row in + // this panel has to pass. The chip still appears for `Limited`, where it + // says something the title does not. + badgeText = ""; + } + + // The Zen card renders on a GO route with overflow only (`usage-panel.tsx`), + // so these two have exactly the two states that card can be in: the plan is + // limited and the overflow is live, or the plan is fine and the balance is + // standing by. A Zen route never reaches them — there the badge already says + // pay-as-you-go, and OpenCode has no balance endpoint to report. + const zenCardCredit = isLimited ? "Active" : "Ready"; + + return { badgeText, headline, title, tooltip, zenCardCredit }; +}; diff --git a/src/usage-css.ts b/src/usage-css.ts new file mode 100644 index 0000000..ef30af9 --- /dev/null +++ b/src/usage-css.ts @@ -0,0 +1,459 @@ +/** + * The OpenCode Go quota meter's stylesheet, as one string the meter renders in + * a `