diff --git a/AGENTS.md b/AGENTS.md index ce23896..d8210a7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -56,7 +56,7 @@ Host bundle (`lib/index.mjs`), a thin `apply` barrel over small modules: - `scripts/report-host-drift.ts` — the nightly harness-drift report (CI's `host-drift` job, schedule and dispatch only): reads the registry the way the records are defined (`dsh` as the newest build any dist-tag carries on the record's line, or a newer stable release under the tag the record names for its line graduating, `graduatesUnder`; pi's range, floor and newest, and every cordis-family member at the floor of the range the tagged cluster declares) and prints one `::warning::` per compared field that moved, exiting 0 whatever it finds, because a channel moving is the harness's release, not a regression. Its rules are `scripts/host-drift.ts` (`readChannel`, the one reading, and `hostDrift`, both pure), held by `test/host-drift.test.ts` with known answers and the job's evaluated condition, and its CLI by `test/mock/host-drift-cli.mock.ts` against a loopback registry (it binds a socket, so it is the mock suite's). The packument reads are `scripts/registry-view.ts`, shared with the proposal below. - `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/config.ts` · `src/config-values.ts` · `src/utils/guards.ts` — the schema and its defaults; dependency-free readers and type guards. The client bundle may import these, and it does — along with the contract and presentation modules (`usage-contract.ts`, `settings-copy.ts`, `settings-fields.ts`, `usage-ui.ts`, `go-limits.ts`, `opencode-store-contract.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 and its defaults; dependency-free readers and type guards. The client bundle may import these, and it does — along with the contract and presentation modules (`usage-contract.ts`, `settings-copy.ts`, `settings-fields.ts`, `usage-ui.ts`, `utils/usd.ts`, `utils/planes.ts` through `utils/request-shape.ts`, `opencode-store-contract.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 @@ -95,20 +95,24 @@ It is the same trick `test/architecture.test.ts` already uses for the client bun | `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 | +| `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 | `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/utils/request-shape.ts` — the fetch patch's PURE decisions, extracted so each branch is unit-testable on its own: which plane a URL belongs to, which credential header a protocol reads, the URL and header source of a `fetch` input, the model id and tool names a JSON body carries, the Anthropic version constant, a request's `x-opencode-plugin` marker (`pluginMarkerOn`, D27's pass-through), and the one table of plane headers both the patch and the plane adapter's per-call seam write (`planeHeadersFor`). Everything here is a function of its arguments — no context, no globals, no I/O. The rule it encodes: **a predicate that lives in a closure cannot be exercised alone**, so its branches survive until some integration path happens to take them. `hasSessionHeader` and `isOpenCodeRequest` were exported and tested; their six private siblings were not, and that was the difference. +- `src/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/usage-contract.ts` — credential extraction and its tier, quota discovery, the usage service, and the shared shape. - `src/utils/credential-policy.ts` · `src/credentials.ts` — the credential rules every decider shares (P6), and their effects. The pure half holds the one placeholder filter (`usableKey`), the fill's and the meter's orders per policy, the capture gate (OC3: only a request of a turn the plugin decorated, never a foreign turn or a marked request) and L8's strike count (a captured key is dropped after a second well-formed 401 in a row on its plane, counted only on requests of decorated turns: the meter's own `/usage` poll and any other turnless request neither strike a key nor lift a drop). The effect half is the capture store, one per ROOT (`captureStoreFor(ctx)`, so a test's fresh `Context` is a fresh store and nothing process-wide needs clearing), the fetch patch's one resolver for an empty or placeholder wire key (`createCredentials`: observe, fill, settle, and the one read of the process environment the fill makes), and the installation's store read. The plane adapter never asks it: its key is pi-ai's rule (D20). `test/credential-parity.test.ts` pins all four deciders side by side and was written before the move. -- `src/catalog-data.ts` · `src/models-catalog.ts` · `src/models-discovery.ts` — the generated static shim, the OpenCode-catalog parser with SWR refresh, and the Settings discovery wrapper (behind `enrichModels`; off, Fetch is pi's list and `NO_DISCOVERY` passes through): on a plane the plugin serves, Settings → Models → Fetch answers pi's list plus the catalog's servable, non-deprecated models pi lacks (D3, P3), and the catalog alone while pi-ai restarts. `catalog-data.ts` is **generated**; never hand-edit it. +- `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. **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. -- `src/go-limits.ts` — the allowance lookup, the label normalization and the money formatting. **One lookup, and it is the tested one**: `attachAllowance` in `usage.ts` used to inline the same expression, and the copy nothing called was the tested one; it now goes through `allowanceFor`. The row's label is the model the allowance belongs to — the picked one, by the catalog's spelling — because a figure beside another model's name states something false about the money. +- `src/go-limits.ts` — the allowance lookup and the label normalization; the money formatting is `utils/usd.ts`'s `allowance` style. **One lookup, and it is the tested one**: `attachAllowance` in `usage.ts` used to inline the same expression, and the copy nothing called was the tested one; it now goes through `allowanceFor`. The row's label is the model the allowance belongs to — the picked one, by the catalog's spelling — because a figure beside another model's name states something false about the money. - `src/go-limits-data.ts` — the Go plan allowances, per model and per tier, **generated** from the vendor's own page by `scripts/generate-go-limits.ts`; never hand-edit it, and regenerate with `pnpm run limits:shim -- --write`. The scheduled freshness job is what notices when the page moves, which it did: the docs went under `/v2/docs/console/` and serve HTML now, so the generator reads a table off that page rather than the markdown it used to. Then the old URL answered 200 again with a body that has no tab sections (2026-11-07), so the sources are asked in turn, the moved page first (`firstDoc`), and a 2xx answer is read by what its body carries; the status alone is never trusted (`docFrom`, both in `scripts/go-limits-html.ts`). Then the page carried three allowance tables where it had carried two (2026-11-12), so each is chosen by the plan label the page attaches to it rather than by position or count (`chooseTables`): the tab its panel names, else the panel's own label, else the heading before it (one inside another tab's panel labels nothing outside it), Go and Go Plus each exactly once, tables labelled with another plan ignored, and only two tables with no plan label and no tab label (a heading that names no plan is not one) kept in the measured order. The Starlight tab markup that labelling reads is assumed, not measured, until a live run logs it: every log line names each table's label, rows and first row. Both old URLs now redirect to `https://opencode.ai/docs/console/go/`, which is the one asked first. - `scripts/generator-kit.ts` · `scripts/catalog-shim.ts` — what the two generators and `scripts/verify-catalog.ts` share: their arguments (`generatorArgs`), the source read (`readSource`), and the ONE staleness rule (`stale`: canonical data differs; key order and formatting never count), with the exit and action it leads to (`outcome`: a file current in data and in text is never rewritten; without `--write` a template change is still `current`, and with `--write` current data in text that is not the renderer's is `rewrite`, which only the limits generator, the one whole-file renderer, does). `catalog-shim.ts` is the catalog generator's pure half — the renderer and the splices, moved verbatim, and `shimStale` over every export the shim carries, the plane and family endpoints included. `test/generators.test.ts` holds both, spawns both generators with `--from` (a source that disagrees with the shipped data exits 1, for the catalog the same ids with only a plane or a family endpoint moved; the limits generator's doc made from the shipped table and the catalog payload that reproduces the shim exit 0) and the limits generator's `--write` from a scratch copy of `scripts/` and `src/` (a template change rewritten, a moved figure written), round-trips each renderer through the formatter against the committed file (`scripts/go-limits-render.ts` is the limits generator's renderer), and spawns `verify-catalog` (offline only: `--from`, `--offline`), passing on the payload that reproduces the shim and failing on a moved endpoint. - `scripts/session-band.ts` — `verify-session-band.ts`'s pure half: the vendor's id construction, ported, the four band facts with the answer each must have (`bandMismatches`), and the verdict the script prints (`bandVerdict`): "CONFIRMED" only when there is no mismatch, otherwise one `MISMATCH:` line each and exit 1. The unit run makes the verdict fail on a planted derivation, spawns the script in its passing state, and spawns a scratch copy of it beside a `src/session.ts` whose derivation leaves the band, which prints the `MISMATCH:` line and exits 1. @@ -119,6 +123,7 @@ It is the same trick `test/architecture.test.ts` already uses for the client bun - `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/utils/config-run.ts` — an `internal/config` run and a fiber's three configs, read the same way on either cordis core, held at 100% coverage: `configRunOf` decodes the call (the fiber is `this` on the OLD shape, the first argument on the NEW one, `next` the last argument on both), `isFiber` is the structural fiber predicate (`fiber.ctx.fiber === fiber`), `rawConfigOf`/`effectiveConfigOf` are the feature-detected accessors (`rawConfig` else `_config`, `effectiveConfig` else `config`), `entryConfigOf` reads the loader's stored row config (`fiber.entry.options.config`), and `isCommitRun` tells a commit from an editor candidate by identity. `test/support/config-shape.ts` re-exports the predicate and the accessors, so a contract and the claim never read a fiber two ways. Told apart by the call and the fiber's own fields, never by a version. - `src/utils/protocols.ts` · `src/utils/model-metadata.ts` · `src/utils/plane-model.ts` · `src/utils/plane-profile.ts` · `src/utils/plane-ownership.ts` · `src/utils/gateway-refusal.ts` — the plane's pure decisions, each held at 100% coverage: the code a gateway refusal finishes with (its type token in pi's failure text, the status at the text's head; Google's text carries none), which declared plane entries the claim takes and which another plugin owns (the `credentials` realm each context resolves, read off cordis's realm map with the rows' labels as the fallback, and the `x-opencode-plugin` marker, D27; `go-discovery.ts` asks the same two questions so the meter never reads another plugin's entry), the SDK → protocol table and the per-protocol base tables (every value measured; see `docs/redirect-planes.md`), the reasoning efforts a model offers (D1), the pi model object one declared model becomes (protocol from the catalog, then the route's `api`, and the base from the endpoint family table, never from pi's own catalog, D16, D26; metadata from the user's row first, D17; the family `auto` resolves to, `AUTO_ENDPOINT_FAMILY`, P-R2), and the profile one plane entry becomes, with pi-ai's own checks and messages for every malformed field, never throwing; the default window and output tokens are the ones pi-ai's own `Config` fills in, never a copy (D17), and so are the image-count bounds (`maxRequestImages`, and `imageOffloadCountQuantum` derived from it as pi-ai's own profile resolution does) wherever the installed pi-ai's `Config` fills them and absent where it does not. - `src/attachment-services.ts` — optional attachment and filesystem services for the plane adapter's image requests, captured through Cordis child scopes. diff --git a/README.md b/README.md index 8bb4db1..bd6c1fb 100644 --- a/README.md +++ b/README.md @@ -166,7 +166,7 @@ Zen's provider-level SDK is `@ai-sdk/openai-compatible`. models.dev names a **di | `@ai-sdk/openai` | 32 | OpenAI Responses | | `@ai-sdk/anthropic` | 18 | Anthropic Messages | | `@ai-sdk/google` | 10 | Google Generative AI | -| `@ai-sdk/mistral` | 1 | OpenAI Chat Completions, as pi's own data files it | +| `@ai-sdk/mistral` | 1 | OpenAI Chat Completions, the plugin's own rule for this SDK | Counts are the **89** active `opencode` models in `models.opencode.ai` as of 2026-11-16 — everything else the vendor lists is deprecated or retired, and the patch ships only what the gateway still serves. The same 89 are bundled offline in `src/catalog-data.ts`, so every one of them routes correctly before the first catalog refresh; regenerate that file with `pnpm run catalog:shim -- --write` (without `--write` it only checks). diff --git a/README.zh-CN.md b/README.zh-CN.md index 9e08864..ac3d36b 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -164,7 +164,7 @@ Zen 的 provider 级 SDK 是 `@ai-sdk/openai-compatible`。models.dev **只在 | `@ai-sdk/openai` | 32 | OpenAI Responses | | `@ai-sdk/anthropic` | 18 | Anthropic Messages | | `@ai-sdk/google` | 10 | Google Generative AI | -| `@ai-sdk/mistral` | 1 | OpenAI Chat Completions(与 pi 自己的数据一致) | +| `@ai-sdk/mistral` | 1 | OpenAI Chat Completions(插件自己对该 SDK 的规则) | 数量为 `models.opencode.ai` 中 `opencode` 的 89 个**在用**模型,统计于 2026-11-16 —— 其余已废弃或下架,补丁只内置网关仍在服务的部分。同样这 89 个模型离线内置在 `src/catalog-data.ts`,因此在第一次 catalog 刷新之前它们每一个路由都是正确的;用 `pnpm run catalog:shim -- --write` 重新生成该文件(不加 `--write` 时只做检查)。 diff --git a/docs/deep-dive.md b/docs/deep-dive.md index ac6543b..4d8f9ca 100644 --- a/docs/deep-dive.md +++ b/docs/deep-dive.md @@ -49,14 +49,15 @@ When DSH spawns subagents (`subagent` / `subagent_fork`), each child runs in a s ▼ spawns subagent [Child DSH Session: "session-xyz"] ──> [ses_<12hex><14base62>] -Outgoing subagent request: - x-opencode-session: ses_<14base62> +Outgoing subagent request on an OpenCode plane: x-opencode-session-id: ses_<14base62> - x-session-affinity: ses_<14base62> + x-opencode-session: ses_<14base62> x-opencode-parent-session-id: ses_<14base62> x-parent-session-id: ses_<14base62> ``` +A relay adds `x-session-affinity` and `X-Session-Id` after the plane pair, both carrying the child's id; which headers go where is recorded once, in `CLIENT_GENERATIONS` (`src/utils/client-generation.ts`). + This lineage lets upstream servers optimize prompt caching across agent teams and delegation workflows. ### 3. Dynamic workspace project attribution diff --git a/docs/engineering-notes.md b/docs/engineering-notes.md index 59a77ae..28897ab 100644 --- a/docs/engineering-notes.md +++ b/docs/engineering-notes.md @@ -456,7 +456,7 @@ So the round that "fixed the tool schemas" renamed `filePath` to `path` and adde Other deltas the comparison establishes, none of them acted on yet: - `x-opencode-request` **is** sent by 1.19.5 (the user message id) and was dropped in 2.x. This plugin omitted it for a round — the turn store held no message id — and now sends one minted per turn in the same shape; the section below records how and why. -- `x-session-affinity` and `X-Session-Id` are **not** sent for `opencode*` providers in 1.19.5 — they are the other branch, for relays. This plugin sends them on every claimed request. +- `x-session-affinity` and `X-Session-Id` are **not** sent for `opencode*` providers in 1.19.5 — they are the other branch, for relays. This plugin sent them on every claimed request when this was written; it now sends them on a relay only, as `CLIENT_GENERATIONS["1.x"]` (`src/utils/client-generation.ts`) records. - `User-Agent` is `opencode/` in 1.19.5, and `opencode///` in 2.x. The plugin sends `opencode/1.19.5 ai-sdk/provider-utils/… runtime/bun/…`, which is neither. - Chat bodies use `max_tokens` in 1.19.5 and `max_completion_tokens` in 2.x. - `b3` is absent in **both** generations, and `traceparent` appears only under `experimental.openTelemetry` — so neither belongs in the plugin's request on the evidence available. diff --git a/docs/improvement-plan.md b/docs/improvement-plan.md index b9d49a5..276accf 100644 --- a/docs/improvement-plan.md +++ b/docs/improvement-plan.md @@ -36,7 +36,7 @@ Phases land as **stacked pull requests**. The open ones are rebased, each onto i | P-R3 | | `fix:` honest refusals | in review | **new, on P-T3**, after P-R2's re-measure (run 43542273415): the gateway's typed refusals finish as `FREE_TIER` or `MODEL_UNAVAILABLE` on the planes, with the gateway's words and, except on Google, its status (L2, the UI claim verified on both channels' chat UI); L7's `tool_choice: none` and schema check; the OC6, OC8 and OC9 probe rows and OC10's README bullets. L9 and L10 land no code: the run answered no keyed 429, and left L10 unmeasured (the reasoning model was refused with and without the field, so the field was never read) | | P5 | | `fix:` the remote services follow the plugin's latest activation and go with its last | in review | **on P-R3**; `installRemoteService` (`src/host/remote.ts`) mounts the three services (usage, purge, store inspection), one per root while a live activation holds it, reading the latest live activation's options and disposed with the last activation, so the usage settings apply the next time the plugin is applied (a disable and re-enable, or a restart) and a disable withdraws all three; each mount is reported through the activation's logger once it has settled (no false "did not register" on a healthy boot, a refused mount said by name); the provide arm is dropped (`KNOWN_DEFECT P5` flipped); L1's warn-once, which treats any live patch of the plugin's as in place. Retitled from `refactor:`, because the README announces it and the changelog must carry it (P-H's precedent; a `refactor` is hidden from it); the owner may override at landing, and keeping `refactor:` drops the README pair with it | | P6 | | `fix:` the fetch patch's credential fill | in review | **on P5**; one resolver for an empty or placeholder wire key (`src/credentials.ts` over the pure `src/utils/credential-policy.ts`), a capture store per root that keeps a key only from a decorated turn (OC3) and drops it after a second well-formed 401 in a row (L8), the global fetch install in `src/host/global-fetch.ts` (any disposal order ends at the fetch that was there; both `KNOWN_DEFECT P6` assertions flipped), the plane headers set per call through pi-ai's `prepareHeaders` with the host's `llm-pi-ai/request-headers` waterfall run on the planes (OC4, OC5), the seam's floor stated in the README pair with the typert peer kept as it was (OC11), and a parity pin over the four deciders landed first. Retitled from `refactor:` (P-H's and P5's precedent): the pull request's title is the release signal under squash, a `refactor` is hidden from the changelog, and the phase carries behaviour changes the README pair announces (OC3, L8, the placeholder filter at every exit, the disposal order, the per-call headers). No `!` and no BREAKING CHANGE footer (1.x minors only). The peer narrowing was decided at landing: it landed as its own commit and was reverted at landing, keeping the old range, a decision taken for the owner and recorded as such (design item 14) | -| P7 | | `refactor:` one source per table | planned | | +| 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 | | `refactor:` settings table | planned | | | P9 | | `refactor:` remote seam | planned | | | P10a | | `refactor:` pure module moves | planned | | @@ -228,7 +228,7 @@ _As built, on both cores (P-R1, from F8, F12, F14, F16 and F17's per-core text). | field | rule | | :-- | :-- | - | protocol | catalog SDK (`PROTOCOL_FOR_SDK`, with `@ai-sdk/mistral` → completions as pi's own data has it) > the user's route-level `api` (only for ids the catalog does not classify) > `openai-completions` (D16, D26) | + | protocol | catalog SDK (`PROTOCOL_FOR_SDK`, with `@ai-sdk/mistral` → completions, the plugin's own rule) > the user's route-level `api` (only for ids the catalog does not classify) > `openai-completions` (D16, D26) | | name, context, max tokens, modalities, cost | the user's row > pi-ai's route-level `modelOverrides` > catalog > pi; past that pi-ai's own defaults, which the plugin does not restate (D17, D26) | | reasoning levels | the user's `reasoningEfforts` > `reasoningFor(spec)` from the catalog (D1: a toggle model offers Off/On, in both vocabularies) > pi > none | | baseUrl | the route-level `baseURL` > the `endpoint` family table | @@ -485,7 +485,7 @@ What stays private is pinned by contract tests against the real host packages: - **The peer range (OC11).** Decided at landing (taken for the owner, recorded as such): `@deepseek-ai/dsh-typert-protocol` keeps `>=0.2.1-alpha.1 <0.3.0 || >=0.2.2-0 <0.3.0`, and the seam's floor is stated in the README pair instead. The seam first shipped in 0.2.2-alpha.3 and 0.2.2-rc.1 (installed and run: 0.2.2-alpha.3 and rc.2; read off the published bridges: present in rc.1 and rc.3, absent in 0.2.2-alpha.2 and every 0.2.1 build). A narrowing to `>=0.2.2-alpha.3 <0.3.0` landed as its own commit and was reverted, for three reasons: #163, which widened the optional cordis peer to the 4.1 line, left its clauses for the 0.2.1 hosts' core (`~4.0.4 || >=4.0.5-0 <4.1.0`) in place; D26 says host gaps are feature-detected, never compared by version; and the plane adapter detects the seam by behaviour, so on a host without it the fetch patch still writes the plugin's session, origin and project headers (no turn is marked per call) and only other plugins' `llm-pi-ai/request-headers` contributors do not run on the planes, because the host never calls `prepareHeaders`. Refusing those hosts at install would buy nothing at runtime. `test/fetch-patch.test.ts` performs that fallback. - **The per-call mark is per turn, on one activation's state (open).** `callHeadersFor` sets `perCall` on the turn state of the activation whose route claim built the adapter, for the rest of the turn. (a) A later request of that turn carrying a well-formed `x-opencode-session` is left unshaped by the fetch patch, whoever wrote the header. (b) With two live activations on one root (two entries of the plugin; cordis disposes before it re-applies), the other activation's stream hook has its own turn store with no mark, so its nested patch rewrites every plane header, a request-headers contributor's change and the minted `x-opencode-request` included; before P6 both patches rewrote them anyway, so nothing regressed. The tighter mechanism, when one is wanted, marks the request rather than the turn: the patch stands down only when the session on the wire equals the value the per-call seam wrote (`state.value`), or the mark is kept per root so every activation's patch sees it. - **L4, not decided.** P-R2's rows measured nothing about `x-opencode-request`; it is sent as before, now from the shared header table, so the decision is one line when a variants run answers. The tier-A case that asserts it on every protocol is labelled a characterization, and the decision is carried to P10a's row with the next variants run. -15. **P7 `refactor:` one source per table.** One `planeForRoute` (four copies today), `formatUsd` and `specFor`; delete the duplicate `ALL_THINKING_LEVELS` and the capitalisation copies. +15. **P7 `refactor:` one source per table.** One `planeForRoute` (four copies today), `formatUsd` and `specFor`; delete the duplicate `ALL_THINKING_LEVELS` and the capitalisation copies. **As landed:** the route-to-plane rule had eleven copies in nine files (`catalogPlaneForRoute`, `isZenProvider`'s inline rule, `tierForRequest`, `resolveDiscoveryProvider` and `servedPlane`, the route claim's two catalog and family picks, the plane adapter's auth, the purge action's table, the credential variable a plane asks for, the meter's Zen-overflow check), now `PLANE_OF_ROUTE` read through `planeOfPlaneRoute` (exact) or `planeForRoute` (relays included, case-sensitive; `isZenProvider` keeps its own case-insensitive, name-gated reading on top of it); the URL half had four copies, now `planeForUrl`; the plane-to-catalog pick had four, now `liveCatalogOn`; the spec lookup had three, now `specOn` (the meter's prospective price keeps the plane-only `findModelSpecOn`, so a Zen route never shows a Go price). `formatUsd` is one function with two named styles, `allowance` and `metered`, and every caller names its style. `ALL_THINKING_LEVELS` had already left with P-R1; the one capitalisation copy left (`"Off"` in `reasoningFor`) reads `effortName`. A source scan keeps one copy of the route rule in the spellings it names (`test/planes.test.ts`: the exact comparisons, the relay half `startsWith("opencode-go…")`, a `case` label, and a quoted route paired with a plane's name in either order and under any key name, the purge table's form and the key order its replacement builds; counted per file and exactly, so a copy inside an allowed file is seen and a removed one forces its allowance down; `go-discovery.ts`'s provider-row reads stay until P10a moves it). The scan is a tripwire for the spellings it names, not a proof: what passes it includes, for example, an unquoted key, another key between the route and the plane, and a route built from parts, each planted as a non-offender. The level names' scans likewise see any capitalised level literal (`"High"` as well as `"Off"`), not only the copy that was removed. `PLANE_OF_ROUTE` is read through `planeOfPlaneRoute` or `planeForRoute`, or indexed directly where the route is already a typed `PlaneRoute` (the route claim, the purge action, the plane model, discovery's `servedPlane`). Left in place: the relay predicate `!provider.startsWith("opencode")` (is this route a relay at all, which picks the client-generation row's relay headers) is still inline in `lifecycle.ts` and `fetch-patch.ts`; it asks a different question from route-to-plane, and is folded when a later phase touches `planeHeadersFor`'s callers. The measured window (L11) is read by the plane model and, in the catalog's place in each field order, by the discovery rows, both through a table parameter defaulting to the shipped one. 16. **P8 `refactor:` settings table.** It starts with a snapshot test of the derived `Config`. Then one field table drives the schema, resolver, types, card, copy and manifest. 17. **P9 `refactor:` remote seam.** `defineRemote`, `markRemote` and `callRemote`, with the parity test reading the contracts. 18. **P10a `refactor:` pure module moves.** @@ -533,7 +533,7 @@ How each phase changes now that it sits on `main` 1.8.0 and on both harness chan | P-R3 | **New**, after P-R2's re-measure: L2's error mapping in `prepareCall`, L7's `tool_choice` and schema check, L9's `providerRetryAfterMs`, and L10's Off through `none` if measured. Gains the console study's probe rows: OC9 (a raw, non-`ses_` session id, per plane, keyed and free), OC6 (the harness User-Agent against the CLI one, per plane, free and paid) and, beside OC9's, OC8's recorded session-only header set. Also OC10's paired README section ("With OpenCode Console installed") on what D27 ships and tests: the routes the plugin serves beside a Console-owned entry, the workspace's policies gating every turn, and an exported `OPENCODE_API_KEY` becoming the Console's credential. **As landed:** L2's codes (`FREE_TIER`, `MODEL_UNAVAILABLE`, chosen on the verified UI evidence) in `prepareCall` and `stream`, L7, the OC6, OC8 and OC9 rows with a free baseline, and OC10's two remaining bullets; L9 lands no code (run 43542273415 answered no keyed 429) and L10 none (unmeasured: the reasoning model was refused with and without the field). | | P5 | Unchanged, plus L1's warn-once when `globalThis.fetch` is no longer the patched function. **As landed:** `installRemoteService` (`src/host/remote.ts`) for the three services, with the latest live activation's options, disposal with the last activation, reports through the activation's logger after the mount settles, and no provide arm; L1's warn-once is the stream hook's, on the first decorated turn that finds `globalThis.fetch` outside the plugin's live patches (`installFetchPatch` returns the predicate, so two live activations' nested patches raise no warning). | | P6 | L8: verify before evicting a key; L4's outcome (drop `x-opencode-request`, or send it only where it is accepted). From the console study: OC3 (capture a key only from a request the plugin decorated, and close the fill path that could reuse a captured token; the marker guard, never capturing from a request carrying `x-opencode-plugin`, landed with D27), OC4 (`prepareHeaders` on the plane adapter, so the host's `llm-pi-ai/request-headers` waterfall runs on the planes), OC5 (the plane's headers set per call through that option, not the global fetch patch), OC11 (the peer range says what the header seam needs), OC2's remainder (the marker pass-through, which landed with D27 and reads the header's presence today, moves into `src/utils/request-shape.ts`; its second rule is not adopted) and OC10's last sentence (the README's coexistence section gains that the meter and headers stay off Console traffic, once OC3's discriminator lands). **As landed:** L8 adopted as its second arm (a second well-formed 401 in a row, no verification probe); L4 not decided (P-R2 measured nothing); OC3 met (capture only from a decorated turn, L8's strikes and drop lifts counted only on decorated turns too, the fill on neither plane closed to a plane's key, the meter reading the same per-root store); OC4 and OC5 met through `prepareHeaders` on `PlaneAdapter`; OC11 met by stating the seam's floor in the README pair, not by the peer (a narrowing landed and was reverted; see design item 14); OC2's remainder met (`pluginMarkerOn` in `src/utils/request-shape.ts`, still triggering on presence); OC10's last sentence met in the README pair. | -| P7 | L6's client-generation table and L11's context-window overrides table; the `planeForRoute` copies now include `main`'s `isGoPlaneUrl` and `catalogPlaneForRoute` pair; the places that justify `@ai-sdk/mistral` → completions by "the plugin follows pi" (`docs/redirect-planes.md` §2, `docs/protocol-routing-and-merge.md`'s Mistral paragraph and its SDK table row, this plan's protocol row in the P-R1 design, the SDK table row in `README.md` and `README.zh-CN.md`, `test/protocols.test.ts`'s SDK-table case title and its `piKnows` assertion, which at most stays an informational pi characterization, and `test/catalog.test.ts`'s note that pi's data files the SDK as completions) are reworded to the plugin's own routing rule, since pi's catalog no longer decides a protocol (D26). | +| 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. | | P9 | A loopback triple guard, only if a `webServer` route appears. | | P10a | L1's per-call shaping is the first move of `fetch-patch` into `request/`. 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`. | @@ -551,12 +551,12 @@ Two community plugins solve the same problem on the same host: [`FishBottle7/ope | 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 | | L5 | **`x-opencode-project` has three conflicting claims:** the folder basename (ours, which also leaks the repository's name), `global` (FB), and a 40-hex digest (SF). | FB `packages/plugin/src/adapter/ids.ts`; SF `lib/protocol.js`. | P-R2 rows for all three, then default to `global` unless another is proven | Measure; probably change the default | -| L6 | **One "client generation" table** for the User-Agent format, the header set and the session semantics. Our tree disagrees with itself about the affinity headers on plane routes, and SF ships the 2.x User-Agent format. | FB `packages/plugin/src/adapter/ids.ts`; SF `lib/protocol.js`; `src/fetch-patch.ts`; `docs/upstream-findings.md`. | P7, P-T3 | Adopt | +| 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 | | L8 | **Verify before evicting a key.** A malformed session header yields `401 Invalid API key`, and FB saw the same request refused and then accepted. Evict per plane only after one verification or a second well-formed 401. | FB `packages/plugin/src/pool/death-verify.ts`; `src/utils/session-id.ts`. | P6 | Adopted in P6 as the second arm: a captured key is dropped per plane after a second well-formed 401 in a row with no 2xx between, both on requests of decorated turns, and not recorded again until a decorated turn's request carrying it as its own is accepted; no verification probe is sent, and a turnless request (the meter's `/usage` poll among them) neither strikes a key nor lifts a drop, so the meter's 401 drops nothing | | L9 | **Honour `Retry-After`.** dsh-llm accepts `providerRetryAfterMs` and `dsh-llm-pi-ai` never fills it. pi's `onResponse` exposes the headers only after a 2xx (and Google has none), so a refusal's header is visible only at the fetch layer. | SF `lib/errors.js`. | P-R2 records whether Go's 429s carry it; P-R3 fills it | Measured: run 43542273415 answered no keyed 429 (its `Retry-After` line is in §13), so nothing to fill; when one does, at the fetch layer (P6) | | L10 | **Offer Off on plain chat-completions reasoning models** through `reasoning_effort: "none"`; ours offers Off only for a few body formats. | FB `packages/plugin/src/adapter/zen-adapter.ts`; `src/utils/model-metadata.ts`. | P-R2 keyed probe, then P-R1's metadata | Unmeasured: run 43542273415's pair was refused before the field mattered, its control as much as `"none"` (Zen account 403, Go model-gone 410, a retired id); Off stays as P-R1's metadata offers it until a served reasoning completions model answers the pair | -| L11 | **Context-window overrides with dated evidence.** FB keeps measured windows for two free models that differ from the catalog's; an understated window is the overflow trap. | FB `packages/plugin/src/adapter/catalog.ts`. | P7 | Low priority; the table pattern only | +| L11 | **Context-window overrides with dated evidence.** FB keeps measured windows for two free models that differ from the catalog's; an understated window is the overflow trap. | FB `packages/plugin/src/adapter/catalog.ts`. | P7 | Adopted in P7 as the pattern only: `MEASURED_CONTEXT_WINDOWS` (`src/utils/context-windows.ts`), each row a window, an ISO date and its evidence, read ahead of the catalog's window by the plane model and the discovery rows; it ships with no rows, since this repository has measured none (FB's two are FB's) | | L12 | **A failed or partial refresh must not replace the maps.** | SF `lib/catalog.js`; FB `packages/plugin/src/adapter/catalog.ts`. | P10b | Adopt | | L13 | **Test against the host's newer pi**, not only the pin: unit and tier A on the newest pi the host's range resolves, not just the binary e2e; the `/zen/v1/systemone` family belongs in P-R2's families. | FB's hoisted-pi test and loader hook. | P-T1a (unit and mock on each channel's newest pi), P-T1b (tiers A and B), P-R2 (the family) | Adopt | | L14 | Smaller: a triple loopback guard if a `webServer` route is ever added (the remotes seam remains the better one); the host's `volatileForm()` as an alternative to hand-written card fields; the catalog's `lastError` on the card rather than in a file. | FB `packages/plugin/src/ip-pool-settings/bridge.ts`, `packages/plugin/src/config.ts`. | P9, P8 or P11, P8 | Adopt where the phase reaches it | @@ -770,6 +770,14 @@ The vendor's own first-party DSH plugin, `@opencode/console` 0.1.10 (`anomalyco/ - **Red on the base:** `fetch-patch`'s OC3 cases (a turnless request's key is never recorded; a plane's key never fills a provider-claimed request on neither plane; a relay route's key never fills a plane request, not even after L8 drops the plane's own key), `go-discovery-keys`' OC3 case (the meter never answers a key sent to a URL on neither plane, under any policy; the base's tiered lookup admitted `unknown`), L8 (dropped at the second well-formed 401 in a row, per plane, back after an acceptance), the placeholder filter at the fill's exit (a stored `unused`, a blank exported key) and the meter's (`go-discovery-store`), OC5's per-call-shaped turn; `host-planes-foreign`'s turnless token never replayed by the meter on the real host; `host-planes-headers`' OC4 contributor on a tier-B plane turn (frozen request, the plugin's session header seen, its header on the wire, a throw failing with `REQUEST_HEADERS`) and OC5 on each protocol in tier A with the fetch patch out of the path; `architecture`'s `process.env` tripwire. - **New with the change:** `credential-policy`, `credentials`, `global-fetch`, `planeRequestHeaders`, `pluginMarkerOn`/`planeHeadersFor`, the per-call writer (`callHeadersFor`) and the route claim building its adapter with `prepareHeaders`. +**P7** + +- **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). +- **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. + ## End-to-end infrastructure ### The `e2e-host` job (`ci.yml`) diff --git a/docs/protocol-routing-and-merge.md b/docs/protocol-routing-and-merge.md index 9dd7be4..4e8b1a2 100644 --- a/docs/protocol-routing-and-merge.md +++ b/docs/protocol-routing-and-merge.md @@ -12,13 +12,13 @@ OpenCode serves its models on **four different API shapes**, and which one a mod | OpenAI **Responses** | `POST /inference/openai/v1/responses` | 32 of 89 | `@ai-sdk/openai` | | Anthropic **Messages** | `POST /inference/anthropic/v1/messages` | 18 of 89 | `@ai-sdk/anthropic` | | Google **Generative AI** | `POST /inference/google/v1beta/models/:streamGenerateContent` | 10 of 89 | `@ai-sdk/google` | -| OpenAI **Chat Completions** (as pi files it) | `POST /inference/openai/v1/chat/completions` | 1 of 89 | `@ai-sdk/mistral` | +| OpenAI **Chat Completions** (the plugin's own rule) | `POST /inference/openai/v1/chat/completions` | 1 of 89 | `@ai-sdk/mistral` | Counts are the shipped catalog. They are asserted against this table by `catalog-docs.test.ts`, because a count written into prose does not regenerate with the data it counts. Go's endpoints are the same paths under `/inference/go/…`; `endpoint: legacy` sends every protocol to `/zen/v1` (`/zen/go/v1` on Go), except Go's Google, which only the inference family serves. **"OpenAI" is two of the four served shapes.** Chat Completions and Responses are different wire formats, and a model that needs Responses does not work on the completions endpoint. The gateway does not fall back; it answers `500`. So each model has to be sent to the endpoint its own SDK names, without asking the user to configure anything. -**Mistral is completions (D16).** `@ai-sdk/mistral` was once kept unserved for want of a measured dialect. pi's own installed data files `mistral-large-4` under `openai-completions`, so the plugin follows pi, and no SDK is withheld any more. +**Mistral is completions (D16).** `@ai-sdk/mistral` was once kept unserved for want of a measured dialect. The plugin's own rule: `PROTOCOL_FOR_SDK` files the SDK as `openai-completions`, on the OpenAI root the catalog's family table places it; which dialect the gateway serves there is unmeasured. No SDK is withheld any more. ## 2. How a model is served: one route per plane (D13) diff --git a/docs/redirect-planes.md b/docs/redirect-planes.md index 5002c13..a51a813 100644 --- a/docs/redirect-planes.md +++ b/docs/redirect-planes.md @@ -39,7 +39,7 @@ That is why the servability check treats `undefined` as servable, and why `@ai-s **The two bold cells were the gap, and they are closed.** The Go plane serves 12 models on shapes other than completions; both planes now serve every shape either one carries, on the plane's own route (§3). -**`@ai-sdk/mistral` is completions (D16).** pi's own data files `mistral-large-4` under `openai-completions`, so the plugin follows it rather than keeping the SDK unserved; nothing is withheld for its protocol any more. +**`@ai-sdk/mistral` is completions (D16).** The plugin's own rule: `PROTOCOL_FOR_SDK` files the SDK as `openai-completions`, on the OpenAI root the catalog's family table places it; which dialect the gateway serves there is unmeasured. Nothing is withheld for its protocol any more. ## 3. Routes diff --git a/docs/upstream-findings.md b/docs/upstream-findings.md index a5f545a..04c4f8c 100644 --- a/docs/upstream-findings.md +++ b/docs/upstream-findings.md @@ -14,7 +14,7 @@ The payload we send is negotiated with whatever gateway the account is on, and b | :-- | :-- | :-- | | Latest at time of writing | 1.19.5 | 2.0.32 | | Session id generator | `packages/opencode/src/id/id.ts` **and** `packages/schema/src/identifier.ts` | `packages/schema/src/identifier.ts` only (`packages/opencode/` is gone) | -| Header assembly | `packages/core/src/session/runner/llm.ts` | `packages/core/src/session/model-request.ts` | +| Header assembly | `packages/opencode/src/session/llm/request.ts` at the `v1.19.5` tag, as `CLIENT_GENERATIONS["1.x"]` records it (§1.2 has an earlier, unreconciled reading) | `packages/core/src/session/model-request.ts` | | Gateway shape | `opencode.ai/zen/v1/…` | `opencode.ai/inference//v1/…` | | Free-tier gate | `allowAnonymous` on the model entry | not present in the snapshot (see §1.5) | @@ -72,7 +72,9 @@ Three facts, each of which contradicts something this plugin once assumed: ### 1.2 The header contract — 1.19.5 -`packages/core/src/session/runner/llm.ts`, the authoritative assembly: +> **Unreconciled reading.** The plugin follows the plane and relay branches of `packages/opencode/src/session/llm/request.ts` at the `v1.19.5` tag, recorded once in `CLIENT_GENERATIONS["1.x"]` (`src/utils/client-generation.ts`): on an `opencode*` route, `x-opencode-session-id` and `x-opencode-session`; the affinity pair (`x-session-affinity`, `X-Session-Id`) only on a relay. The block below is an earlier reading of `packages/core/src/session/runner/llm.ts`, most likely taken from the `dev` branch (`docs/engineering-notes.md` records three such misreadings), and has not been checked against the tag. It is kept as found, not as the contract. + +`packages/core/src/session/runner/llm.ts`, as first read: ```ts const promptCacheKey = /^ses_[0-9a-f]{64}$/.test(session.id) ? session.id.slice(4) : session.id @@ -124,7 +126,7 @@ Differences that matter to us: 2. **Three headers 1.19 does not send**: `User-Agent`, `x-opencode-project`, `x-opencode-client` (value `app.name`). 3. `x-opencode-session` exists in both lines but carries different things. -**Consequence.** Our plugin sends `session.id` in all five of 1.19's headers. That is exactly 1.19's contract and correct for a 1.19 account. For a 2.x account the gateway expects the affinity-derived value in three of them, so a 2.x account sees a session that does not group as the client intended. Whether the 2.x gateway _enforces_ this is **unverified** — it may happily accept `session.id`. +**Consequence.** Our plugin sends the session id in 1.19's headers as `CLIENT_GENERATIONS["1.x"]` records them: two session headers on a plane route (`x-opencode-session-id`, `x-opencode-session`), four on a relay (those two plus `x-session-affinity` and `X-Session-Id`), and the parent pair for a subagent. That is 1.19's contract and correct for a 1.19 account. For a 2.x account the gateway expects the affinity-derived value in three of them, so a 2.x account sees a session that does not group as the client intended. Whether the 2.x gateway _enforces_ this is **unverified** — it may happily accept `session.id`. ### 1.4 The gateway path table — identical in both lines diff --git a/scripts/check.ts b/scripts/check.ts index 993547f..3ccd3f0 100644 --- a/scripts/check.ts +++ b/scripts/check.ts @@ -343,8 +343,17 @@ try { * That is the kind of growth the last four raises were: a surface the HOST * answers, not a dependency that should have stayed external — which is the case * this tripwire exists to catch, and which the ceiling is not raised for. + * + * Raised 136 -> 140 KB when P7 gave each table one source: the client now + * carries the one dollar formatter with both styles (`src/utils/usd.ts`, + * replacing the allowance one it took from `go-limits.ts`) and the route rule + * the meter's Zen test reads (`planeForRoute`, `src/utils/planes.ts`; the + * table itself is tree-shaken out). The growth is chiefly the `metered` + * style's rationale comment, which used to live in the host-only + * `session-cost.ts`. Source and its comments, not a dependency — the client + * measured 141010 bytes against the old line, from 139148 on the base. */ -const CLIENT_BUDGET = 136 * 1024; +const CLIENT_BUDGET = 140 * 1024; const clientPath = join(ROOT, "lib/client.js"); if (existsSync(clientPath)) { const clientStat = statSync(clientPath); diff --git a/scripts/vendor-version.ts b/scripts/vendor-version.ts index 8e22481..db6b3c1 100644 --- a/scripts/vendor-version.ts +++ b/scripts/vendor-version.ts @@ -126,9 +126,10 @@ export const disagreements = ( * No constant pins that generation: `OPENCODE_CLI_VERSION` is a 1.x version * and the plugin sends the 1.x form. A 2.x literal in the tree is therefore a * claim about what the CLI sends that nothing checks, the kind of copy this - * gate exists to keep from drifting. The client-generation table that would - * pin it is P7's (L6); until then such a literal is a placeholder, never a - * value. + * gate exists to keep from drifting. The client-generation table + * (`src/utils/client-generation.ts`, L6) records the 2.x FORMAT, but pins no + * 2.x version, so a concrete literal is still a claim; such a literal is a + * placeholder, never a value. * * @param found - each 2.x-form literal, with the files that say it. * @returns the messages, one per literal. diff --git a/src/credentials.ts b/src/credentials.ts index 1236268..4065b45 100644 --- a/src/credentials.ts +++ b/src/credentials.ts @@ -46,6 +46,7 @@ import { usableKey, } from "./utils/credential-policy.ts"; import { isRecord } from "./utils/guards.ts"; +import { planeOfPlaneRoute } from "./utils/planes.ts"; /** What the gateway's answer says about the key a request carried. */ export type KeyOutcome = "accepted" | "refused"; @@ -464,9 +465,9 @@ export const createCredentials = ( // Only a known gateway plane may ask for its own variable: a configured // provider can also claim other URLs, which take the Zen one, as they // always have. + // A URL on a plane decides alone; with none, the exact route does. const declaredName = - plane === "opencode-go" || - (plane.length === 0 && provider === "opencode-go") + planeOfPlaneRoute(plane.length === 0 ? provider : plane) === "go" ? "OPENCODE_GO_API_KEY" : "OPENCODE_API_KEY"; const declared = environment(declaredName); diff --git a/src/fetch-patch.ts b/src/fetch-patch.ts index 49f8551..f15de27 100644 --- a/src/fetch-patch.ts +++ b/src/fetch-patch.ts @@ -32,9 +32,8 @@ import { extractApiKeyFromHeaders } from "./key-capture.ts"; import { type CatalogPlane, enrichModelsResponse, - findModelSpec, - findModelSpecOn, isModelsListingUrl, + specOn, } from "./models-catalog.ts"; import { isOpenCodeSessionId, @@ -51,7 +50,7 @@ import { authHeaderFor, gatewayPlaneFor, headerSourceOf, - isGoPlaneUrl, + planeForUrl, planeHeadersFor, pluginMarkerOn, projectHeaderOf, @@ -99,7 +98,7 @@ const isFreeModelBody = ( // 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 = findModelSpecOn(plane, model) ?? findModelSpec(model); + const spec = specOn(plane, model); return spec?.is_free === true; } catch { return false; @@ -345,7 +344,7 @@ export const patchFetch = ( // // 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, isGoPlaneUrl(url) ? "go" : "zen") + !isFreeModelBody(bodyToPatch, planeForUrl(url)) ) { warnedNoCredential.add(plane); const { consulted } = decision; diff --git a/src/go-limits.ts b/src/go-limits.ts index b3f7950..e96ab89 100644 --- a/src/go-limits.ts +++ b/src/go-limits.ts @@ -79,14 +79,6 @@ export const allowanceFor = ( model: string ): ModelAllowance | undefined => limits.get(model.trim().toLowerCase()); -/** Unknown allowances (including NaN serialized as null) are never dollar values. */ -export const formatUsd = (value: unknown): string => { - if (typeof value !== "number" || !Number.isFinite(value) || value < 0) { - return "—"; - } - return Number.isInteger(value) ? `$${value}` : `$${value.toFixed(2)}`; -}; - /** * Normalize a doc-table row label to a model id. * diff --git a/src/host/plane-provider.ts b/src/host/plane-provider.ts index b0d2452..3b0edcc 100644 --- a/src/host/plane-provider.ts +++ b/src/host/plane-provider.ts @@ -50,6 +50,7 @@ import { isRecord, } from "../utils/guards.ts"; import type { PlaneProviderBuilder } from "../utils/plane-profile.ts"; +import { planeOfPlaneRoute } from "../utils/planes.ts"; import { PROTOCOLS } from "../utils/protocols.ts"; /** A resolved plane profile, as far as this module reads one. */ @@ -650,7 +651,7 @@ export const buildPlaneProvider = }) ), auth: - id === "opencode-go" + planeOfPlaneRoute(id) === "go" ? libraries.opencodeGoAuth : libraries.opencodeAuth, id, diff --git a/src/host/route-claim.ts b/src/host/route-claim.ts index 259b797..7104c89 100644 --- a/src/host/route-claim.ts +++ b/src/host/route-claim.ts @@ -105,8 +105,7 @@ import { } from "../cordis-context.ts"; import { catalogGeneration, - getLiveGoCatalog, - getLiveZenCatalog, + liveCatalogOn, onCatalogChange, } from "../models-catalog.ts"; import { @@ -128,6 +127,7 @@ import { planeProfileFor, withoutPlaneProviders, } from "../utils/plane-profile.ts"; +import { PLANE_OF_ROUTE } from "../utils/planes.ts"; import { PLANE_ROUTES, type PlaneRoute } from "../utils/protocols.ts"; import { buildPlaneProvider, @@ -482,14 +482,10 @@ export const installRouteClaim = ( } const result = planeProfileFor({ buildProvider: buildPlaneProvider(libraries), - catalog: - route === "opencode-go" ? getLiveGoCatalog() : getLiveZenCatalog(), + catalog: liveCatalogOn(PLANE_OF_ROUTE[route]), endpoint: config.endpoint, entry: entries[route], - familyApi: - route === "opencode-go" - ? OPENCODE_FAMILY_API.go - : OPENCODE_FAMILY_API.zen, + familyApi: OPENCODE_FAMILY_API[PLANE_OF_ROUTE[route]], ...(interpolate === undefined ? {} : { interpolate: (value: unknown) => interpolate(pi.ctx, value) }), @@ -912,14 +908,10 @@ export const installRouteClaim = ( const { interpolate } = modules.libraries; const result = planeProfileFor({ buildProvider: buildPlaneProvider(modules.libraries), - catalog: - plane === "opencode-go" ? getLiveGoCatalog() : getLiveZenCatalog(), + catalog: liveCatalogOn(PLANE_OF_ROUTE[plane]), endpoint: config.endpoint, entry: candidate[plane], - familyApi: - plane === "opencode-go" - ? OPENCODE_FAMILY_API.go - : OPENCODE_FAMILY_API.zen, + familyApi: OPENCODE_FAMILY_API[PLANE_OF_ROUTE[plane]], ...(interpolate === undefined ? {} : { interpolate: (value: unknown) => interpolate(fiber.ctx, value) }), diff --git a/src/identity.ts b/src/identity.ts index bf261ca..f5a6ab6 100644 --- a/src/identity.ts +++ b/src/identity.ts @@ -14,6 +14,11 @@ * @module dsh-opencode-patch/identity */ +import { + CLIENT_GENERATIONS, + EMULATED_GENERATION, +} from "./utils/client-generation.ts"; + /** Component identity (log lines, service scoping). */ export const name = "dsh-opencode-patch"; @@ -59,8 +64,12 @@ export const OPENCODE_CLI_VERSION = "1.19.5"; * SDK's own User-Agent, which is what a DIFFERENT transport stamps on a request; * it is not the client's, and 2.x changed the shape again to * `opencode///` (`packages/core/src/app.ts:24`). + * Both forms are rows of `CLIENT_GENERATIONS` (`utils/client-generation.ts`), + * and this is the emulated generation's. */ -export const OPENCODE_USER_AGENT = `opencode/${OPENCODE_CLI_VERSION}`; +export const OPENCODE_USER_AGENT = CLIENT_GENERATIONS[ + EMULATED_GENERATION +].userAgent({ version: OPENCODE_CLI_VERSION }); /** The User-Agent the plugin signs its own requests with. */ -export const OPENCODE_PATCH_USER_AGENT = `opencode/${OPENCODE_CLI_VERSION} dsh-opencode-patch`; +export const OPENCODE_PATCH_USER_AGENT = `${OPENCODE_USER_AGENT} dsh-opencode-patch`; diff --git a/src/key-capture.ts b/src/key-capture.ts index 2a610e2..0a5b19f 100644 --- a/src/key-capture.ts +++ b/src/key-capture.ts @@ -18,6 +18,7 @@ import { isPlaceholderApiKey } from "./utils/credential-policy.ts"; import { isRecord } from "./utils/guards.ts"; +import { planeOfPlaneRoute } from "./utils/planes.ts"; import { gatewayPlaneFor } from "./utils/request-shape.ts"; /** Account tiers a captured credential can belong to. */ @@ -61,21 +62,14 @@ export const tierForRequest = (url?: string, provider?: string): KeyTier => { // not in `/inference/openai/v1`, so the ZEN openai family was filed under // no account at all. A key filed under the wrong account is worse than one // filed under none: it is used, and it is the wrong one. - const plane = gatewayPlaneFor(url); - if (plane === "opencode-go") { - return "go"; + const onUrl = planeOfPlaneRoute(gatewayPlaneFor(url)); + if (onUrl !== undefined) { + return onUrl; } - if (plane === "opencode") { - return "zen"; - } - } - if (provider === "opencode-go") { - return "go"; - } - if (provider === "opencode") { - return "zen"; } - return "unknown"; + // Only the two exact routes name a plane; a relay or a renamed route is a + // hint the URL above did not confirm. + return planeOfPlaneRoute(provider) ?? "unknown"; }; const readHeaderString = ( diff --git a/src/models-catalog.ts b/src/models-catalog.ts index 79b75f4..4b6e292 100644 --- a/src/models-catalog.ts +++ b/src/models-catalog.ts @@ -22,7 +22,8 @@ import { import { DEFAULT_GATEWAY_URLS } from "./config.ts"; import type { ModelCostRate } from "./session-cost.ts"; import { isRecord } from "./utils/guards.ts"; -import { isGoPlaneUrl } from "./utils/request-shape.ts"; +import { type Plane, planeForRoute } from "./utils/planes.ts"; +import { isGoPlaneUrl, planeForUrl } from "./utils/request-shape.ts"; // The catalog data is part of this module's public surface (and of the // package's, via `index.ts`), so re-export it rather than making callers @@ -33,7 +34,7 @@ export { type CatalogModelSpec, } from "./catalog-data.ts"; -export type CatalogProvider = "go" | "zen"; +export type CatalogProvider = Plane; /** * The registry this plugin actually fetches: the OpenCode catalog, served from @@ -437,20 +438,11 @@ const extractSpecs = ( return results; }; -/** Which of the two catalogs a model id should be read from. */ -export type CatalogPlane = "go" | "zen"; - /** - * The plane a route's models come from. - * - * `opencode-go` is the subscription plane, and so is an `opencode-go-*` relay - * route; everything else this plugin knows about (`opencode`) is Zen. + * Which of the two catalogs a model id should be read from: a plane. A route's + * plane is `planeForRoute`'s (`utils/planes.ts`), the one table. */ -export const catalogPlaneForRoute = (route: unknown): CatalogPlane => - route === "opencode-go" || - (typeof route === "string" && route.startsWith("opencode-go-")) - ? "go" - : "zen"; +export type CatalogPlane = Plane; /** * The spec a given PLANE declares for a model. @@ -491,11 +483,43 @@ export const findModelSpecOn = ( * ("prices a turn at the rate of the plane its route belongs to"). * * The plane has to come from the route in play; this function is the fallback - * for a model the plane's OWN row does not describe. + * for a model the plane's OWN row does not describe, and {@link specOn} reads + * the two in that order. */ export const findModelSpec = (modelId: string): CatalogModelSpec | undefined => activeGoCatalog.get(modelId) ?? activeZenCatalog.get(modelId); +/** + * The spec a plane declares for a model, and the plane-blind one for a model + * the plane's own row does not describe: the one lookup the request path, the + * core-tool fallback and the turn's price share. + * + * Not for a reading that must say "this plane has no price": the meter's + * prospective price reads {@link findModelSpecOn} alone, so a Zen route never + * shows a Go price. + * + * @param plane - the plane in play. + * @param modelId - the model id. + * @returns the plane's row, else the plane-blind row, else `undefined`. + */ +export const specOn = ( + plane: CatalogPlane, + modelId: string +): CatalogModelSpec | undefined => + findModelSpecOn(plane, modelId) ?? findModelSpec(modelId); + +/** + * {@link specOn} for the plane a ROUTE's models come from (`planeForRoute`). + * + * @param route - the route id in play. + * @param modelId - the model id. + * @returns the spec, as {@link specOn} answers it. + */ +export const specFor = ( + route: unknown, + modelId: string +): CatalogModelSpec | undefined => specOn(planeForRoute(route), modelId); + /** * Safely parse raw models.dev JSON data for both opencode-go and opencode providers. * @@ -547,7 +571,7 @@ export const parseModelsDevCatalog = (data: unknown): ParsedCatalogs => { * @param id - the model id to test. * @returns whether the registry has retired it. */ -export const isDeprecatedModelOn = (plane: "go" | "zen", id: string): boolean => +export const isDeprecatedModelOn = (plane: Plane, id: string): boolean => (plane === "go" ? deprecatedGoIds : deprecatedZenIds).has(id); /** @@ -706,6 +730,20 @@ export const getLiveZenCatalog = ( fetchFn: typeof fetch = globalThis.fetch ): readonly CatalogModelSpec[] => readLiveCatalog(activeZenCatalog, fetchFn); +/** + * The current catalog of one plane: {@link getLiveGoCatalog} or + * {@link getLiveZenCatalog}, whose revalidation it keeps. + * + * @param plane - the plane. + * @param fetchFn - fetch implementation to use for background refresh; absent, + * theirs applies. + */ +export const liveCatalogOn = ( + plane: Plane, + fetchFn?: typeof fetch +): readonly CatalogModelSpec[] => + plane === "go" ? getLiveGoCatalog(fetchFn) : getLiveZenCatalog(fetchFn); + /** Legacy alias for getLiveGoCatalog. */ export const getLiveCatalog = getLiveGoCatalog; @@ -797,8 +835,7 @@ export const enrichModelsResponse = async ( // listing, against the deployment's own gateway markers; asking // `isGoModelsListingUrl` again applied the DEFAULT markers, so a relay's // `/zen/go/v1/models` was answered with the Zen catalog. - const isGo = isGoPlaneUrl(url); - const catalog = isGo ? getLiveGoCatalog(fetchFn) : getLiveZenCatalog(fetchFn); + const catalog = liveCatalogOn(planeForUrl(url), fetchFn); const catalogById = new Map(catalog.map((m) => [m.id, m])); const merged = new Map>(); diff --git a/src/models-discovery.ts b/src/models-discovery.ts index b551069..cf0ad67 100644 --- a/src/models-discovery.ts +++ b/src/models-discovery.ts @@ -25,13 +25,18 @@ import { type CatalogProvider, DSH_SUPPORTED_MODALITIES, findModelSpecOn, - getLiveGoCatalog, - getLiveZenCatalog, isDeprecatedModelOn, + liveCatalogOn, } 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 { isGoPlaneUrl } from "./utils/request-shape.ts"; +import { planeForUrl } from "./utils/request-shape.ts"; /** * The patch sites this module installs, one id each. Two activations of the @@ -136,15 +141,22 @@ const rowFrom = ( candidate: DiscoveryCandidate | undefined, spec: CatalogModelSpec | undefined, id: string, - order: FieldOrder = "pi-first" + plane: CatalogProvider, + order: FieldOrder, + measured: MeasuredWindows ): DiscoveredRow => { const catalogFirst = order === "catalog-first"; const name = catalogFirst ? (spec?.name ?? candidate?.name) : (candidate?.name ?? spec?.name); + // A measured window takes the catalog's place in either order (L11): ahead + // of the catalog's own window, and so ahead of pi's in catalog-first, but + // still behind pi's in pi-first, where pi-ai serves the route from pi's row. + const catalogWindow = + measuredWindowFor(plane, id, measured) ?? spec?.context_window; const contextWindow = catalogFirst - ? (spec?.context_window ?? candidate?.contextWindow) - : (candidate?.contextWindow ?? spec?.context_window); + ? (catalogWindow ?? candidate?.contextWindow) + : (candidate?.contextWindow ?? catalogWindow); const maxTokens = catalogFirst ? (spec?.max_output_tokens ?? candidate?.maxTokens) : (candidate?.maxTokens ?? spec?.max_output_tokens); @@ -191,11 +203,9 @@ export const resolveDiscoveryProvider = ( marker.length > 0 && normalizedBaseURL.includes(marker.toLowerCase()) ); - if (provider === "opencode-go") { - return "go"; - } - if (provider === "opencode") { - return "zen"; + const onRoute = planeOfPlaneRoute(provider); + if (onRoute !== undefined) { + return onRoute; } if (!isGateway || baseURL === undefined) { return undefined; @@ -204,7 +214,7 @@ export const resolveDiscoveryProvider = ( // Go plane's base is the `inference` family (`…/inference/go/openai/v1`), and // a substring check that does not know that path attributes a Go discovery // request to the ZEN catalog. - return isGoPlaneUrl(baseURL) ? "go" : "zen"; + return planeForUrl(baseURL); }; /** @@ -214,7 +224,8 @@ export const resolveDiscoveryProvider = ( const adapterRows = ( discovered: unknown, provider: CatalogProvider, - order: FieldOrder + order: FieldOrder, + measured: MeasuredWindows ): DiscoveredRow[] => { const seen = new Set(); const merged: DiscoveredRow[] = []; @@ -238,7 +249,9 @@ const adapterRows = ( candidate, findModelSpecOn(provider, candidate.id), candidate.id, - order + provider, + order, + measured ) ); } @@ -267,8 +280,9 @@ const adapterRows = ( */ export const mergeDiscoveredModels = ( discovered: unknown, - provider: CatalogProvider -): DiscoveredRow[] => adapterRows(discovered, provider, "pi-first"); + provider: CatalogProvider, + measured: MeasuredWindows = MEASURED_CONTEXT_WINDOWS +): DiscoveredRow[] => adapterRows(discovered, provider, "pi-first", measured); /** * Settings' fetch on a plane the plugin serves: pi's rows first, in pi's @@ -282,15 +296,17 @@ export const mergeDiscoveredModels = ( * * @param discovered - pi-ai's answer, or `[]` when it has none. * @param plane - the catalog plane the route serves. + * @param measured - the measured windows (L11); the shipped table by default. * @returns the rows, each id once, in the Remote's shape. */ export const complementDiscoveredModels = ( discovered: unknown, - plane: CatalogProvider + plane: CatalogProvider, + measured: MeasuredWindows = MEASURED_CONTEXT_WINDOWS ): DiscoveredRow[] => { - const rows = adapterRows(discovered, plane, "catalog-first"); + const rows = adapterRows(discovered, plane, "catalog-first", measured); const seen = new Set(rows.map((row) => row.id)); - const catalog = plane === "go" ? getLiveGoCatalog() : getLiveZenCatalog(); + const catalog = liveCatalogOn(plane); for (const spec of catalog) { if ( seen.has(spec.id) || @@ -300,7 +316,9 @@ export const complementDiscoveredModels = ( continue; } seen.add(spec.id); - rows.push(rowFrom(undefined, spec, spec.id, "catalog-first")); + rows.push( + rowFrom(undefined, spec, spec.id, plane, "catalog-first", measured) + ); } return rows; }; @@ -359,7 +377,7 @@ const servedPlane = ( ) { return undefined; } - return request.provider === "opencode-go" ? "go" : "zen"; + return PLANE_OF_ROUTE[request.provider]; }; /** diff --git a/src/purge-service.ts b/src/purge-service.ts index 6b06c01..d6876ea 100644 --- a/src/purge-service.ts +++ b/src/purge-service.ts @@ -46,12 +46,13 @@ import { pluginMarkerOf, type RealmSide, } from "./utils/plane-ownership.ts"; +import { type Plane, PLANE_OF_ROUTE } from "./utils/planes.ts"; +import { PLANE_ROUTES } from "./utils/protocols.ts"; -/** A provider route the plugin knows how to read a plane from. */ -const PLANES: readonly { route: string; plane: "go" | "zen" }[] = [ - { route: "opencode", plane: "zen" }, - { route: "opencode-go", plane: "go" }, -]; +/** A provider route the plugin knows how to read a plane from, in route order. */ +const PLANES: readonly { route: string; plane: Plane }[] = PLANE_ROUTES.map( + (route) => ({ plane: PLANE_OF_ROUTE[route], route }) +); /** The configEditor surface this module uses, narrowed from `unknown`. */ interface ConfigEditorFace { diff --git a/src/session-cost.ts b/src/session-cost.ts index 082a1ad..7c24547 100644 --- a/src/session-cost.ts +++ b/src/session-cost.ts @@ -10,6 +10,7 @@ */ import type { CatalogPlane } from "./models-catalog.ts"; +import { formatUsd } from "./utils/usd.ts"; export interface ModelCostRate { cache_read?: number; @@ -87,22 +88,6 @@ interface MutableSessionUsage { const sessionStore = new Map(); -/** - * Format a USD dollar amount, always two decimals. - * - * The precision used to tier by magnitude — three decimals below a cent, four - * below a tenth of one — and the owner read `$0.006` on the trigger and called - * it too much precision in the wrong place. A meter is a gauge, not an - * invoice: `$0.01` of a real spend is an honest rounding of six tenths of a - * cent, the same rounding every wallet UI makes. Precision tiers reintroduce - * the exact thing the panel keeps paying to remove — a number whose LENGTH - * changes with its value, so the row shifts on every turn. (The allowance - * table's `formatUsd` in go-limits.ts keeps its own contract: whole dollars - * drop the cents, because a published $60 total is not the same kind of - * figure as a metered spend.) - */ -export const formatUsd = (usd: number): string => `$${usd.toFixed(2)}`; - /** Format model rate per 1M tokens. */ export const formatModelRate = ( cost?: ModelCostRate, @@ -165,7 +150,7 @@ const toSnapshot = (val: MutableSessionUsage): SessionUsageSnapshot => { cacheReadTokens: val.cacheReadTokens, /** Spend attributed to each billing plane; every turn knows its own. */ costByPlane: { go: val.costGo, zen: val.costZen }, - costFormatted: formatUsd(val.costUsd), + costFormatted: formatUsd(val.costUsd, "metered"), costUsd: val.costUsd, ...(val.activeIsFree === true ? { freeModel: true } : {}), inputTokens: val.inputTokens, @@ -217,7 +202,7 @@ export const recordTurnUsage = ( (tokens.inputTokens ?? 0) + (tokens.outputTokens ?? 0); const turnRecord: TurnRecord = { - costFormatted: formatUsd(turnCost), + costFormatted: formatUsd(turnCost, "metered"), costUsd: turnCost, inputTokens: tokens.inputTokens ?? 0, ...(isFree ? { isFree: true } : {}), diff --git a/src/settings-usage.tsx b/src/settings-usage.tsx index fa7a63f..62186c4 100644 --- a/src/settings-usage.tsx +++ b/src/settings-usage.tsx @@ -22,7 +22,6 @@ import { } from "@deepseek-ai/dsh-client-ui-primitives"; import React from "react"; -import { formatUsd } from "./go-limits.ts"; import type { Translate } from "./settings-copy.ts"; import { callUsageRead, @@ -34,6 +33,7 @@ import type { GoUsage, UsageWindow } from "./usage-contract.ts"; import { formatRelativeReset, getWindowState, resetLabel } from "./usage-ui.ts"; import { isRecord } from "./utils/guards.ts"; import { backoffOver, retryUntilAnswered } from "./utils/retry.ts"; +import { formatUsd } from "./utils/usd.ts"; /** The three windows, in the order the panel lists them. */ /** @@ -338,9 +338,7 @@ export const UsageSummaryView = ({ > {`${t("usageSummaryAllowance")} ${usage.allowance.model} · ${t( "goTier" - )} ${formatUsd(usage.allowance.go)} · ${t("goPlusTier")} ${formatUsd( - usage.allowance.goPlus - )}`} + )} ${formatUsd(usage.allowance.go, "allowance")} · ${t("goPlusTier")} ${formatUsd(usage.allowance.goPlus, "allowance")}`} )} diff --git a/src/stream-hook.ts b/src/stream-hook.ts index 6667b78..bb41f95 100644 --- a/src/stream-hook.ts +++ b/src/stream-hook.ts @@ -16,11 +16,7 @@ import type { ResolvedPluginConfig } from "./config.ts"; import { readSessionMetaResolver } from "./cordis-context.ts"; import type { DebugContext } from "./debug.ts"; import { recordDebug } from "./debug.ts"; -import { - catalogPlaneForRoute, - findModelSpec, - findModelSpecOn, -} from "./models-catalog.ts"; +import { specFor } from "./models-catalog.ts"; import { recordTurnUsage } from "./session-cost.ts"; import { fallbackSessionId, @@ -31,6 +27,7 @@ import { import type { ActiveTurnState } from "./turn-store.ts"; import { withStore } from "./turn-store.ts"; import { isAsyncIterableLike, isRecord } from "./utils/guards.ts"; +import { planeForRoute } from "./utils/planes.ts"; interface StreamOptions { messages?: unknown; @@ -259,9 +256,8 @@ export const createStreamHook = ( // The fallback is for a model the plane's own catalog does not describe, // where any price is better than none — and the turn is still attributed to // the plane it ran on. - const spec = - findModelSpecOn(catalogPlaneForRoute(providerKey), modelName) ?? - findModelSpec(modelName); + const plane = planeForRoute(providerKey); + const spec = specFor(providerKey, modelName); const wrappedStream = async function* wrappedStream() { for await (const chunk of downstream) { @@ -287,7 +283,7 @@ export const createStreamHook = ( spec?.cost, modelName, spec?.is_free, - catalogPlaneForRoute(providerKey) + plane ); } yield chunk; diff --git a/src/tool-fallback.ts b/src/tool-fallback.ts index e15219d..439222e 100644 --- a/src/tool-fallback.ts +++ b/src/tool-fallback.ts @@ -20,13 +20,9 @@ */ import { ALL_MODELS_MARKER } from "./config-values.ts"; -import { - type CatalogPlane, - findModelSpec, - findModelSpecOn, -} from "./models-catalog.ts"; +import { type CatalogPlane, findModelSpec, specOn } from "./models-catalog.ts"; import { isRecord, isUnknownArray } from "./utils/guards.ts"; -import { isGoPlaneUrl } from "./utils/request-shape.ts"; +import { planeForUrl } from "./utils/request-shape.ts"; /** Path segment that marks a Responses-API body worth inspecting. */ export const RESPONSES_PATH = "/responses"; @@ -238,8 +234,7 @@ export const isCoreToolModel = ( plane?: CatalogPlane ): boolean => { const row = - (plane === undefined ? undefined : findModelSpecOn(plane, modelId)) ?? - findModelSpec(modelId); + plane === undefined ? findModelSpec(modelId) : specOn(plane, modelId); return coreToolDecision(row, modelId, marker); }; @@ -306,7 +301,7 @@ export const maybeInjectCoreTools = ( // 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: CatalogPlane = isGoPlaneUrl(url) ? "go" : "zen"; + const plane = planeForUrl(url); if (!isCoreToolModel(modelProp, options.modelMarker, plane)) { return body; } diff --git a/src/usage-panel.tsx b/src/usage-panel.tsx index 04ad9d4..19bf12c 100644 --- a/src/usage-panel.tsx +++ b/src/usage-panel.tsx @@ -16,7 +16,6 @@ import { } from "@deepseek-ai/dsh-client-ui-primitives"; import React from "react"; -import { formatUsd } from "./go-limits.ts"; import type { GoUsage, UsageWindow } from "./usage-contract.ts"; import { BREAKDOWN_WINDOWS, @@ -29,6 +28,7 @@ import { RADIUS, type UsageFailure, } from "./usage-ui.ts"; +import { formatUsd } from "./utils/usd.ts"; /** * The refresh glyph is the HOST'S, not a hand-drawn arrow. @@ -383,8 +383,8 @@ export const UsagePanel = ({ - {t("goTier")} {formatUsd(usage.allowance.go)} · {t("goPlusTier")}{" "} - {formatUsd(usage.allowance.goPlus)} + {t("goTier")} {formatUsd(usage.allowance.go, "allowance")} ·{" "} + {t("goPlusTier")} {formatUsd(usage.allowance.goPlus, "allowance")} )} diff --git a/src/usage.ts b/src/usage.ts index ad8e9c7..92883c0 100644 --- a/src/usage.ts +++ b/src/usage.ts @@ -28,15 +28,9 @@ import { import { GO_MODEL_LIMITS } from "./go-limits-data.ts"; import { allowanceFor, type ModelAllowance } from "./go-limits.ts"; import { OPENCODE_PATCH_USER_AGENT } from "./identity.ts"; -import { - type CatalogModelSpec, - type CatalogPlane, - catalogPlaneForRoute, - findModelSpecOn, -} from "./models-catalog.ts"; +import { type CatalogPlane, findModelSpecOn } from "./models-catalog.ts"; import { describeModel, - formatUsd, getSessionUsage, type SessionUsageSnapshot, } from "./session-cost.ts"; @@ -49,7 +43,9 @@ import { type UsageWindow, } from "./usage-contract.ts"; import { isRecord } from "./utils/guards.ts"; +import { planeForRoute, planeOfPlaneRoute } from "./utils/planes.ts"; import { isZenProvider } from "./utils/request-shape.ts"; +import { formatUsd } from "./utils/usd.ts"; const USAGE_MAX_BYTES = 1024 * 1024; @@ -129,7 +125,7 @@ const attachSession = ( if (session === undefined) { return undefined; } - const plane = catalogPlaneForRoute(query?.provider ?? ""); + const plane = planeForRoute(query?.provider ?? ""); const selected = query?.model; const isProspective = selected !== undefined && @@ -149,7 +145,9 @@ const attachSession = ( if (!isProspective) { return withPlaneSpend(nameModel(session, plane), plane); } - const spec = catalogFor(plane, selected); + // The asking route's plane ONLY: a price the other plane charges is not + // this route's, and "—" is the honest answer for a plane with no row. + const spec = findModelSpecOn(plane, selected); return withPlaneSpend( nameModel( describeModel( @@ -180,16 +178,10 @@ const withPlaneSpend = ( plane: CatalogPlane ): SessionUsageSnapshot => ({ ...snapshot, - planeCostFormatted: formatUsd(snapshot.costByPlane[plane]), + planeCostFormatted: formatUsd(snapshot.costByPlane[plane], "metered"), planeSpendUsd: snapshot.costByPlane[plane], }); -/** The catalog spec for a model, or `undefined` when the catalog has none. */ -const catalogFor = ( - plane: CatalogPlane, - model: string -): CatalogModelSpec | undefined => findModelSpecOn(plane, model); - /** * Fill in the display name, which a recorded turn never carries. * @@ -211,7 +203,7 @@ const nameModel = ( ) { return snapshot; } - const spec = catalogFor(plane, model); + const spec = findModelSpecOn(plane, model); return spec === undefined ? snapshot : { ...snapshot, activeModelName: spec.name }; @@ -247,7 +239,7 @@ const attachAllowance = ( // The catalog's spelling of the model, when it knows it. A model the catalog // does not describe keeps the id the picker gave — an id is still better than // another model's name. - const name = catalogFor("go", model)?.name ?? model; + const name = findModelSpecOn("go", model)?.name ?? model; return { go: row.go, goPlus: row.goPlus, model: name }; }; @@ -322,7 +314,7 @@ export class GoUsageService extends TypertRemoteService { if (key === undefined || key.length === 0) { const zenInfo = await resolveZenCreditInfo(this.ctx); - if (zenInfo.isConfigured || targetProvider === "opencode") { + if (zenInfo.isConfigured || planeOfPlaneRoute(targetProvider) === "zen") { return zenOverflowUsage(randomUUID(), sessionId, query); } this.identity = undefined; diff --git a/src/utils/client-generation.ts b/src/utils/client-generation.ts new file mode 100644 index 0000000..d818728 --- /dev/null +++ b/src/utils/client-generation.ts @@ -0,0 +1,112 @@ +/** + * What each generation of the OpenCode client sends: its User-Agent, its + * session headers and what they carry, and its origin headers (L6). + * + * The plugin emulates one generation ({@link EMULATED_GENERATION}), and the + * headers it writes (`planeHeadersFor` in `request-shape.ts`) and the + * User-Agent it signs with (`identity.ts`) are read from that generation's + * row. The other row is RECORDED, not read: it says what the next generation + * sends, so the tree has one statement of which generation sends which header + * where, and a switch starts from a table rather than a hunt through comments. + * + * A switch is NOT a one-word change. `sessionValue` is recorded and read by + * nothing yet: `planeHeadersFor` writes the session id into every session + * header, so emulating 2.x also needs the affinity id plumbed in as an input, + * the User-Agent's channel and client parts supplied, and the writer taught + * that 2.x has no message-id header. + * + * No 2.x version is pinned (`OPENCODE_CLI_VERSION` is a 1.x version): the 2.x + * row's User-Agent is a format, not a value. A concrete 2.x literal anywhere + * in the tree is still a claim nothing checks, and `pnpm run cli:version` + * refuses one. + * + * Every value is a constant or a function of its arguments: this module is in + * `utils/` and the architecture test holds it to that. + * + * @module dsh-opencode-patch/utils/client-generation + */ + +import { + PARENT_SESSION_ALT_HEADER, + PARENT_SESSION_HEADER, + SESSION_AFFINITY_HEADER, + SESSION_HEADER, + SESSION_ID_HEADER, +} from "./session-id.ts"; + +/** The parts a User-Agent is built from; a generation reads what its form needs. */ +export interface UserAgentParts { + readonly version: string; + /** The release channel (`latest`, `dev`, ...), which only 2.x names. */ + readonly channel?: string; + /** The client app's name (`cli`, ...), which only 2.x names. */ + readonly client?: string; +} + +/** One generation's row. */ +export interface ClientGeneration { + /** The User-Agent this generation sends, from its parts. */ + readonly userAgent: (parts: UserAgentParts) => string; + /** The session headers on a request to an OpenCode plane, in write order. */ + readonly planeSessionHeaders: readonly string[]; + /** The session headers added for a relay (a route not named `opencode*`). */ + readonly relaySessionHeaders: readonly string[]; + /** The parent-session headers, for a subagent or child session. */ + readonly parentHeaders: readonly string[]; + /** The origin headers: the client app, the turn's message id, the project. */ + readonly originHeaders: { + readonly client: string; + readonly request?: string; + readonly project: string; + }; + /** + * What the session headers other than `x-opencode-session-id` carry: the + * session's own id, or its affinity id (the parent's id for a subagent). + */ + readonly sessionValue: "session" | "affinity"; + /** Where the row was read from, and how sure the reading is. */ + readonly evidence: string; +} + +/** The generations the table records. */ +export type GenerationId = "1.x" | "2.x"; + +/** The table, one row per generation. */ +export const CLIENT_GENERATIONS = { + "1.x": { + evidence: + "v1.19.5 packages/opencode/src/session/llm/request.ts: the User-Agent (line 18), the plane and relay branches, and the origin headers in the client and project branch", + originHeaders: { + client: "x-opencode-client", + project: "x-opencode-project", + request: "x-opencode-request", + }, + parentHeaders: [PARENT_SESSION_HEADER, PARENT_SESSION_ALT_HEADER], + planeSessionHeaders: ["x-opencode-session-id", SESSION_HEADER], + relaySessionHeaders: [SESSION_AFFINITY_HEADER, SESSION_ID_HEADER], + sessionValue: "session", + userAgent: ({ version }) => `opencode/${version}`, + }, + "2.x": { + evidence: + "recorded, not measured: packages/core/src/session/model-request.ts at 2.0.32 (docs/upstream-findings.md §1.3), packages/core/src/app.ts:24 for the User-Agent, a capture of 2.0.28 for the four session headers (utils/session-id.ts), and §2.1 for the dropped message id; whether the gateway enforces any of it is unverified", + originHeaders: { + client: "x-opencode-client", + project: "x-opencode-project", + }, + parentHeaders: [PARENT_SESSION_HEADER, PARENT_SESSION_ALT_HEADER], + planeSessionHeaders: [ + "x-opencode-session-id", + SESSION_AFFINITY_HEADER, + SESSION_ID_HEADER, + SESSION_HEADER, + ], + relaySessionHeaders: [], + sessionValue: "affinity", + userAgent: ({ channel, client, version }) => + `opencode/${channel ?? ""}/${version}/${client ?? ""}`, + }, +} as const satisfies Readonly>; + +/** The generation this plugin emulates: the one the registry's `latest` publishes. */ +export const EMULATED_GENERATION = "1.x" satisfies GenerationId; diff --git a/src/utils/context-windows.ts b/src/utils/context-windows.ts new file mode 100644 index 0000000..1acc181 --- /dev/null +++ b/src/utils/context-windows.ts @@ -0,0 +1,64 @@ +/** + * Context windows measured against the gateway, where they differ from the + * catalog's (L11): the table pattern, with dated evidence per row. + * + * An understated window is the overflow trap: the composer trims to the + * window it was told, the gateway serves a larger one, and nothing fails — + * the conversation is just shorter than it could be. An overstated one is + * worse: the gateway refuses a request the composer thought would fit. A + * measured window is therefore read ahead of the catalog's, and behind + * anything the user declared (`plane-model.ts`'s precedence). Settings' + * discovery rows (`models-discovery.ts`) read it in the catalog's place in + * each of their field orders: ahead of pi's window on a plane the plugin + * serves, and still behind it on a route pi-ai serves from pi's own row. + * + * The table ships EMPTY: this repository has measured no window that differs + * from the catalog's. A row is added with the measurement that justifies it — + * the date and the evidence travel with the number, so a later reader can + * tell a measurement from a guess, and a vendor fix from a stale override. + * + * Every value is a constant or a function of its arguments: this module is in + * `utils/` and the architecture test holds it to that. + * + * @module dsh-opencode-patch/utils/context-windows + */ + +import type { Plane } from "./planes.ts"; + +/** One measured window. */ +export interface MeasuredWindow { + /** The window the gateway serves, in tokens. */ + readonly window: number; + /** When it was measured, as an ISO date (`2026-11-16`). */ + readonly measured: string; + /** What was measured, and where the record is. */ + readonly evidence: string; +} + +/** A plane's measured windows, by model id. */ +export type MeasuredWindows = Readonly< + Record>> +>; + +/** The measured windows this repository ships: none yet. */ +export const MEASURED_CONTEXT_WINDOWS: MeasuredWindows = { go: {}, zen: {} }; + +/** + * The measured window for a model on a plane, or `undefined` when none was + * measured. An own row only: an id every object inherits (`toString`) is + * never a model. + * + * @param plane - the plane the model is served on. + * @param id - the model id. + * @param table - the table to read; the shipped one by default. + * @returns the window, or `undefined`. + */ +export const measuredWindowFor = ( + plane: Plane, + id: string, + table: MeasuredWindows = MEASURED_CONTEXT_WINDOWS +): number | undefined => { + const rows = table[plane]; + const row = Object.hasOwn(rows, id) ? rows[id] : undefined; + return row?.window; +}; diff --git a/src/utils/model-metadata.ts b/src/utils/model-metadata.ts index ea5b464..ee7934e 100644 --- a/src/utils/model-metadata.ts +++ b/src/utils/model-metadata.ts @@ -186,7 +186,9 @@ export const reasoningFor = ( const reasoningEfforts: Record = offEffort === undefined ? {} : { off: offEffort }; const efforts: { id: string; name: string }[] = - off || offWire !== undefined ? [{ id: "off", name: "Off" }] : []; + off || offWire !== undefined + ? [{ id: "off", name: effortName("off") }] + : []; for (const level of levels) { reasoningEfforts[level] = level; efforts.push({ id: level, name: toggle ? "On" : effortName(level) }); diff --git a/src/utils/plane-model.ts b/src/utils/plane-model.ts index 55fe7d6..3a7e837 100644 --- a/src/utils/plane-model.ts +++ b/src/utils/plane-model.ts @@ -5,7 +5,7 @@ * | field | first source that has it | * | :-- | :-- | * | protocol | the catalog SDK ({@link protocolForSdk}) > the route's `api` > completions (D16) | - * | name, context, max tokens, modalities | the user's row > pi-ai's `modelOverrides` > catalog > pi > pi-ai's own route defaults, as its `Config` filled them (D17) | + * | name, context, max tokens, modalities | the user's row > pi-ai's `modelOverrides` > catalog > pi > pi-ai's own route defaults, as its `Config` filled them (D17); the context window reads a measured window ({@link measuredWindowFor}, L11) ahead of the catalog's | * | cost | catalog > pi > zero | * | reasoning | the user's `reasoningEfforts` > the override's > the catalog ({@link reasoningFor}, D1) > pi > none | * | baseUrl | the route's `baseURL`, shaped > the endpoint family table ({@link baseUrlFor}; `auto` is {@link AUTO_ENDPOINT_FAMILY}) | @@ -27,12 +27,14 @@ * @module dsh-opencode-patch/utils/plane-model */ +import { type MeasuredWindows, measuredWindowFor } from "./context-windows.ts"; import { isRecord } from "./guards.ts"; import { piReasoningFromEfforts, reasoningFor, type ReasoningSpec, } from "./model-metadata.ts"; +import { PLANE_OF_ROUTE } from "./planes.ts"; import { compatProtocols, FAMILY_SDK_KEY, @@ -124,6 +126,8 @@ export interface PlaneModelInput { readonly maxTokens?: number; readonly input: readonly string[]; }; + /** The measured context windows; the shipped table by default (L11). */ + readonly measuredWindows?: MeasuredWindows; } /** A model {@link planeModelFor} could build. */ @@ -355,6 +359,7 @@ export const planeModelFor = (input: PlaneModelInput): PlaneModelResult => { const contextWindow = entry.contextWindow ?? override?.contextWindow ?? + measuredWindowFor(PLANE_OF_ROUTE[route], id, input.measuredWindows) ?? spec?.context_window ?? pi?.contextWindow ?? input.defaults.contextWindow; diff --git a/src/utils/planes.ts b/src/utils/planes.ts new file mode 100644 index 0000000..4fa2a33 --- /dev/null +++ b/src/utils/planes.ts @@ -0,0 +1,68 @@ +/** + * Which of the two gateway planes a route belongs to: one table, two readers. + * + * The question was answered in several places — the catalog's route rule, the + * captured key's tier, the discovery wrapper, the purge action, the plane + * adapter's auth, the credential variable a plane asks for — each with its own + * `=== "opencode-go"`. They agree today; this module is what keeps them + * agreeing, because there is now one table to disagree with. + * + * Two readers, because the callers ask two different questions: + * + * - {@link planeOfPlaneRoute}: the plane of one of the two routes the plugin + * OWNS, or `undefined` for anything else. Exact: a relay, a renamed route + * or an inherited key of every object (`constructor`) is not a plane route. + * - {@link planeForRoute}: the plane whose CATALOG a route's models are read + * from, relays included: `opencode-go` and any `opencode-go-*` relay are Go, + * and everything else is Zen. Case-sensitive, as it always was. + * + * The URL's plane is a property of its path, and lives beside the path rules + * in `request-shape.ts` (`planeForUrl`). + * + * Every value is a constant or a function of its arguments: this module is in + * `utils/` and the architecture test holds it to that. + * + * @module dsh-opencode-patch/utils/planes + */ + +import { isPlaneRoute, type PlaneRoute } from "./protocols.ts"; + +/** The two gateway planes: the Go subscription and Zen pay-as-you-go. */ +export type Plane = "go" | "zen"; + +/** + * The plane each owned route serves, keyed in `PLANE_ROUTES`' order + * (`protocols.ts`), which the purge action walks. + */ +export const PLANE_OF_ROUTE: Readonly> = { + opencode: "zen", + "opencode-go": "go", +}; + +/** + * The plane of one of the two owned routes, or `undefined` for any other + * value. Read through {@link isPlaneRoute}, so a key every object inherits + * never answers. + * + * @param route - a route id, or anything a caller holds in its place. + * @returns the route's plane, or `undefined`. + */ +export const planeOfPlaneRoute = (route: unknown): Plane | undefined => + isPlaneRoute(route) ? PLANE_OF_ROUTE[route] : undefined; + +/** + * The plane a route's models come from: `opencode-go` is the subscription + * plane, and so is an `opencode-go-*` relay route; everything else (`opencode`, + * a relay of another name, a value that is not a string) is Zen. + * + * `opencode-google` starts with `opencode-go` but not with `opencode-go-`, so + * it is Zen. + * + * @param route - the route id in play. + * @returns the plane whose catalog describes the route's models. + */ +export const planeForRoute = (route: unknown): Plane => + route === "opencode-go" || + (typeof route === "string" && route.startsWith("opencode-go-")) + ? "go" + : "zen"; diff --git a/src/utils/protocols.ts b/src/utils/protocols.ts index c837bc6..e078212 100644 --- a/src/utils/protocols.ts +++ b/src/utils/protocols.ts @@ -9,9 +9,7 @@ * plugin's own rule, consistent with the vendor catalog's family table, * which places that SDK on the OpenAI root * (`OPENCODE_FAMILY_API.zen["@ai-sdk/mistral"]` in the generated - * `catalog-data.ts`). Which dialect the gateway serves there is unmeasured, - * and rewording the docs' rationale for the row is the plan's P7 item - * (`docs/improvement-plan.md`). + * `catalog-data.ts`). Which dialect the gateway serves there is unmeasured. * * Every value is a constant or a function of its arguments: this module is in * `utils/` and the architecture test holds it to that. diff --git a/src/utils/request-shape.ts b/src/utils/request-shape.ts index c7dd859..902c020 100644 --- a/src/utils/request-shape.ts +++ b/src/utils/request-shape.ts @@ -15,16 +15,14 @@ * @module dsh-opencode-patch/request-shape */ +import { + CLIENT_GENERATIONS, + EMULATED_GENERATION, +} from "./client-generation.ts"; import { isRecord } from "./guards.ts"; import { PLUGIN_MARKER_HEADER } from "./plane-ownership.ts"; -import { - isOpenCodeMessageId, - PARENT_SESSION_ALT_HEADER, - PARENT_SESSION_HEADER, - SESSION_AFFINITY_HEADER, - SESSION_HEADER, - SESSION_ID_HEADER, -} from "./session-id.ts"; +import { type Plane, planeForRoute } from "./planes.ts"; +import { isOpenCodeMessageId } from "./session-id.ts"; /** * The PATH of a gateway URL, whether it is absolute or a bare path. @@ -85,6 +83,17 @@ const ZEN_PLANE_PATH = /\/zen(?:\/|$)|\/inference(?:\/|$)/u; export const isGoPlaneUrl = (url: string): boolean => GO_PLANE_PATH.test(pathOf(url)); +/** + * The plane a URL's path belongs to: Go by {@link isGoPlaneUrl}, otherwise + * Zen. For a caller that already knows the URL is a gateway's, so "not Go" + * is Zen rather than "neither". + * + * @param url - a request URL or a bare path. + * @returns the URL's plane. + */ +export const planeForUrl = (url: string): Plane => + isGoPlaneUrl(url) ? "go" : "zen"; + /** * Which gateway plane a URL belongs to. * @@ -268,9 +277,10 @@ export const ANTHROPIC_VERSION = "2023-06-01"; * Whether a provider route is OpenCode Zen rather than Go. * * The Go plane is `opencode-go` and any `opencode-go-*` relay route — the rule - * `catalogPlaneForRoute` encodes. Everything else in the opencode family is - * Zen pay-as-you-go, including a route named `opencode-google`, which starts - * with `opencode-go` but not with `opencode-go-`. + * `planeForRoute` encodes (`planes.ts`), read here on the lower-cased name. + * Everything else in the opencode family is Zen pay-as-you-go, including a + * route named `opencode-google`, which starts with `opencode-go` but not with + * `opencode-go-`; a name without `opencode` in it is neither. */ export const isZenProvider = (provider?: string): boolean => { if (typeof provider !== "string") { @@ -280,7 +290,7 @@ export const isZenProvider = (provider?: string): boolean => { if (!lower.includes("opencode")) { return false; } - return !(lower === "opencode-go" || lower.startsWith("opencode-go-")); + return planeForRoute(lower) === "zen"; }; /** @@ -334,32 +344,27 @@ export interface PlaneHeaderInputs { * one table both the fetch patch and the plane adapter's per-call seam (OC5) * write from. * - * 1. **Session headers, as the version this plugin emulates sends them.** Read - * from the 1.x line's last release, v1.19.5, in - * `packages/opencode/src/session/llm/request.ts`: `x-opencode-session-id` - * and `x-opencode-session` both carry `sessionID`, and the affinity pair - * belongs to relays. 2.x splits the first of those into an affinity id; the - * plugin emulates 1.19.5, so it follows 1.19.5. Which ENDPOINT the request - * goes to is the deployment's, not this table's: measured, either key - * serves a paid model on either endpoint — they are two paths into one - * gateway. - * 2. **The affinity pair belongs to the OTHER branch in 1.19.5:** for a - * provider that does not start with `opencode` — a relay a deployment - * claimed by URL — the client sends `x-session-affinity` and - * `X-Session-Id`; for an OpenCode plane it sends `x-opencode-session` - * instead and nothing else. + * Every header NAME is the emulated generation's (`CLIENT_GENERATIONS`, in + * `client-generation.ts`), which records what each generation sends, where, + * and its evidence: + * + * 1. **The plane's session headers**, both carrying the session id. Which + * ENDPOINT the request goes to is the deployment's, not this table's: + * measured, either key serves a paid model on either endpoint — they are + * two paths into one gateway. + * 2. **The relay's affinity pair**, after them, for a provider that does not + * start with `opencode` — a relay a deployment claimed by URL. * 3. The parent pair, for subagents and child sessions. * 4. **The org, when this plane's credential belongs to one.** A session token * needs the org it belongs to — measured on a paid model: `200` with it, - * `403` without — and the free tier is refused with or without one. - * 5. **The origin headers**, when enabled: the client; the message id, read - * from v1.19.5's `request.ts` (`"x-opencode-request": input.user.id`, in - * the same branch as the client and project headers), which the console - * reads for per-request metrics and rewrites to `x-opencode-request-id` - * before the request reaches the inference service (`inference-proxy.ts`); - * and the project. L4 is still open: P-R2's rows measured nothing about - * the message id, so it is sent as it always was, and this line is where a - * decision to drop or gate it lands. + * `403` without — and the free tier is refused with or without one. The + * header is the credential's, not a generation's. + * 5. **The origin headers**, when enabled: the client; the message id, which + * the console reads for per-request metrics and rewrites to + * `x-opencode-request-id` before the request reaches the inference service + * (`inference-proxy.ts`); and the project. L4 is still open: P-R2's rows + * measured nothing about the message id, so it is sent as it always was, + * and this line is where a decision to drop or gate it lands. * * @param inputs - the session, parent, relay flag, org and origin. * @returns the headers, as `[name, value]` pairs in write order. @@ -368,32 +373,28 @@ export const planeHeadersFor = ( inputs: PlaneHeaderInputs ): readonly (readonly [string, string])[] => { const { origin, org, parent, relay, session } = inputs; - const headers: (readonly [string, string])[] = [ - ["x-opencode-session-id", session], - [SESSION_HEADER, session], - ]; + const names = CLIENT_GENERATIONS[EMULATED_GENERATION]; + const headers: (readonly [string, string])[] = names.planeSessionHeaders.map( + (name) => [name, session] as const + ); if (relay) { headers.push( - [SESSION_AFFINITY_HEADER, session], - [SESSION_ID_HEADER, session] + ...names.relaySessionHeaders.map((name) => [name, session] as const) ); } if (parent !== undefined) { - headers.push( - [PARENT_SESSION_HEADER, parent], - [PARENT_SESSION_ALT_HEADER, parent] - ); + headers.push(...names.parentHeaders.map((name) => [name, parent] as const)); } if (org !== undefined && org.length > 0) { headers.push(["x-opencode-org-id", org]); } if (origin !== undefined) { - headers.push(["x-opencode-client", origin.client]); + headers.push([names.originHeaders.client, origin.client]); if (isOpenCodeMessageId(origin.request)) { - headers.push(["x-opencode-request", origin.request]); + headers.push([names.originHeaders.request, origin.request]); } if (origin.project !== undefined) { - headers.push(["x-opencode-project", origin.project]); + headers.push([names.originHeaders.project, origin.project]); } } return headers; diff --git a/src/utils/session-id.ts b/src/utils/session-id.ts index d6e46e2..8429d71 100644 --- a/src/utils/session-id.ts +++ b/src/utils/session-id.ts @@ -32,8 +32,9 @@ export const SESSION_AFFINITY_HEADER = "x-session-affinity"; * * Captured from OpenCode 2.0.28 talking to a local server: it sends * `x-opencode-session`, `x-opencode-session-id`, `x-session-affinity` AND - * `x-session-id`, all four carrying the same value on every request. This plugin - * has always sent three of them. + * `x-session-id`, all four carrying the same value on every request. Which + * generation sends which of them where — 1.x sends this pair to a relay only — + * is `CLIENT_GENERATIONS`' (`client-generation.ts`). */ export const SESSION_ID_HEADER = "x-session-id"; diff --git a/src/utils/usd.ts b/src/utils/usd.ts new file mode 100644 index 0000000..9d5ee6c --- /dev/null +++ b/src/utils/usd.ts @@ -0,0 +1,55 @@ +/** + * Dollar amounts, in the two contracts the panels show them in: one function, + * one row per contract. + * + * A metered spend and a published allowance are different kinds of figure, + * and they used to be formatted by two functions that shared a name + * (`formatUsd` in `session-cost.ts` and in `go-limits.ts`). Every caller now + * names the style it wants, so neither contract is the other's by accident. + * + * Pure and dependency-free: the client bundle imports it, and the + * architecture test holds `utils/` to that. + * + * @module dsh-opencode-patch/utils/usd + */ + +/** Which of the two dollar contracts a figure is shown in. */ +export type UsdStyle = "allowance" | "metered"; + +/** How each style renders a number. */ +const RENDER: Readonly string>> = { + /** + * A published allowance. Unknown allowances (including NaN serialized as + * null) are never dollar values, and a negative one is not a figure either; + * a whole published total drops the cents (`$60`), because it is not the + * same kind of figure as a metered spend. + */ + allowance: (usd) => { + if (!Number.isFinite(usd) || usd < 0) { + return "—"; + } + return Number.isInteger(usd) ? `$${usd}` : `$${usd.toFixed(2)}`; + }, + /** + * A metered spend, always two decimals. + * + * The precision used to tier by magnitude — three decimals below a cent, + * four below a tenth of one — and the owner read `$0.006` on the trigger + * and called it too much precision in the wrong place. A meter is a gauge, + * not an invoice: `$0.01` of a real spend is an honest rounding of six + * tenths of a cent, the same rounding every wallet UI makes. Precision tiers + * reintroduce the exact thing the panel keeps paying to remove — a number + * whose LENGTH changes with its value, so the row shifts on every turn. + */ + metered: (usd) => `$${usd.toFixed(2)}`, +}; + +/** + * Format a dollar amount in a named style. + * + * @param value - the amount; anything but a number is "—" in either style. + * @param style - `allowance` for a published total, `metered` for a spend. + * @returns the formatted amount. + */ +export const formatUsd = (value: unknown, style: UsdStyle): string => + typeof value === "number" ? RENDER[style](value) : "—"; diff --git a/test/catalog.test.ts b/test/catalog.test.ts index ac99d51..220d2c5 100644 --- a/test/catalog.test.ts +++ b/test/catalog.test.ts @@ -233,7 +233,8 @@ describe("OpenCode model catalog · the bundled shim", () => { // And each of those SDKs maps to a protocol the plane adapter serves, so no // carried model names a format with nowhere to go. `@ai-sdk/mistral` is no - // exception any more: pi's own data files it as completions (D16). + // exception any more: the plugin's own rule sends it as completions, on the + // root the catalog's family table places it (D16, D26). for (const [npm, ids] of buckets) { expect(protocolForSdk(npm), npm).toBeDefined(); expect(isServableSdk(npm), npm).toBe(true); diff --git a/test/client-generation.test.ts b/test/client-generation.test.ts new file mode 100644 index 0000000..0988159 --- /dev/null +++ b/test/client-generation.test.ts @@ -0,0 +1,119 @@ +/** + * The client-generation table (`src/utils/client-generation.ts`, L6): the + * emulated row's header names are what `planeHeadersFor` writes, and every + * row records well-formed data. + * + * `test/request-shape.test.ts` pins `planeHeadersFor`'s exact output and the + * User-Agent's literal form; this file rebuilds that output from the emulated + * row, so the writer keeps reading the row in its assembly order. The other + * cases are RECORD checks: `sessionValue` and the whole 2.x row are data + * nothing in `src` reads yet, and the titles say so. + * + * @module test/client-generation.test + */ +import { describe, expect, it } from "vitest"; + +import { + CLIENT_GENERATIONS, + EMULATED_GENERATION, + planeHeadersFor, +} from "./support/src.ts"; + +const SES = "ses_0123456789abAAAAAAAAAAAAAA"; +const PARENT = "ses_0123456789abBBBBBBBBBBBBBB"; +const MSG = "msg_0123456789abCCCCCCCCCCCCCC"; + +describe("client generations · the emulated row is what the plugin sends", () => { + const row = CLIENT_GENERATIONS[EMULATED_GENERATION]; + + it("records 1.x as the emulated generation, its session headers carrying the session's own id", () => { + expect(EMULATED_GENERATION).toBe("1.x"); + // Recorded, not read: planeHeadersFor writes the session id into every + // session header whatever this field says. + expect(row.sessionValue).toBe("session"); + }); + + it("rebuilds planeHeadersFor's plane and relay output from the row", () => { + const pairs = (names: readonly string[], value: string) => + names.map((name) => [name, value]); + expect(planeHeadersFor({ relay: false, session: SES })).toEqual( + pairs(row.planeSessionHeaders, SES) + ); + expect(planeHeadersFor({ relay: true, session: SES })).toEqual([ + ...pairs(row.planeSessionHeaders, SES), + ...pairs(row.relaySessionHeaders, SES), + ]); + expect( + planeHeadersFor({ + origin: { client: "cli", project: "p", request: MSG }, + parent: PARENT, + relay: false, + session: SES, + }) + ).toEqual([ + ...pairs(row.planeSessionHeaders, SES), + ...pairs(row.parentHeaders, PARENT), + [row.originHeaders.client, "cli"], + [row.originHeaders.request, MSG], + [row.originHeaders.project, "p"], + ]); + }); +}); + +describe("client generations · the recorded 2.x row", () => { + const row = CLIENT_GENERATIONS["2.x"]; + + it("records its User-Agent format as opencode///", () => { + // Assembled, never written out: a concrete 2.x literal in the tree is a + // claim `cli:version` refuses. + const [channel, version, client] = ["dev", "0.0.0-dev-1", "cli"]; + expect(row.userAgent({ channel, client, version })).toBe( + ["opencode", channel, version, client].join("/") + ); + // A part it was not given stays a placeholder rather than a value. + expect(row.userAgent({ version })).toBe( + ["opencode", "", version, ""].join("/") + ); + }); + + it("records all four session headers on a plane, carrying the affinity id, and no message id", () => { + expect(row.sessionValue).toBe("affinity"); + expect(row.relaySessionHeaders).toEqual([]); + expect(new Set(row.planeSessionHeaders)).toEqual( + new Set([ + ...CLIENT_GENERATIONS["1.x"].planeSessionHeaders, + ...CLIENT_GENERATIONS["1.x"].relaySessionHeaders, + ]) + ); + expect(Object.hasOwn(row.originHeaders, "request")).toBe(false); + expect(row.evidence).toMatch(/^recorded, not measured/u); + }); +}); + +describe("client generations · every row is well-formed", () => { + it("records each header name in lower case, once per list", () => { + for (const [id, row] of Object.entries(CLIENT_GENERATIONS)) { + const lists: readonly (readonly string[])[] = [ + row.planeSessionHeaders, + row.relaySessionHeaders, + row.parentHeaders, + Object.values(row.originHeaders), + ]; + for (const list of lists) { + expect(new Set(list).size, id).toBe(list.length); + for (const name of list) { + expect(name, id).toBe(name.toLowerCase()); + expect(name.length, id).toBeGreaterThan(0); + } + } + // A session header is never also a relay one in the same generation. + expect( + row.planeSessionHeaders.filter((name) => + (row.relaySessionHeaders as readonly string[]).includes(name) + ), + id + ).toEqual([]); + expect(row.evidence.length, id).toBeGreaterThan(0); + } + }); +}); diff --git a/test/context-windows.test.ts b/test/context-windows.test.ts new file mode 100644 index 0000000..a114b72 --- /dev/null +++ b/test/context-windows.test.ts @@ -0,0 +1,121 @@ +/** + * The measured context-window table (`src/utils/context-windows.ts`, L11): + * every row carries its evidence, and the reader answers own rows only. + * + * The table ships empty, so the row check is paired with a seeded table it + * must accept and a malformed one it must refuse: an empty loop proves + * nothing on its own. + * + * @module test/context-windows.test + */ +import { describe, expect, it } from "vitest"; + +import { + type CatalogModelSpec, + MEASURED_CONTEXT_WINDOWS, + type MeasuredWindows, + measuredWindowFor, + OPENCODE_GO_CATALOG, + OPENCODE_ZEN_CATALOG, + type Plane, +} from "./support/src.ts"; + +const SHIPPED: Readonly> = { + go: OPENCODE_GO_CATALOG, + zen: OPENCODE_ZEN_CATALOG, +}; + +/** Every reason a table's rows fail the evidence rule, as `plane/id: why`. */ +const problemsOf = (table: MeasuredWindows): string[] => + (["go", "zen"] as const).flatMap((plane) => + Object.entries(table[plane]).flatMap(([id, row]) => { + const at = `${plane}/${id}`; + const spec = SHIPPED[plane].find((model) => model.id === id); + return [ + ...(Number.isInteger(row.window) && row.window > 0 + ? [] + : [`${at}: window is not a positive whole number`]), + ...(/^\d{4}-\d{2}-\d{2}$/u.test(row.measured) && + !Number.isNaN(Date.parse(row.measured)) + ? [] + : [`${at}: measured is not an ISO date`]), + ...(row.evidence.trim().length > 0 ? [] : [`${at}: no evidence`]), + ...(spec === undefined + ? [`${at}: the plane's catalog has no such model`] + : []), + ...(spec !== undefined && spec.context_window === row.window + ? [`${at}: the catalog already says ${String(row.window)}`] + : []), + ]; + }) + ); + +/** A model the shipped Zen catalog carries, and a window it does not say. */ +const zenModel = (): CatalogModelSpec => { + const [spec] = OPENCODE_ZEN_CATALOG; + if (spec === undefined) { + throw new Error("the shipped Zen catalog is empty"); + } + return spec; +}; + +describe("context windows · every row carries its evidence", () => { + it("the shipped table passes, and the checker sees a row it is given", () => { + expect(problemsOf(MEASURED_CONTEXT_WINDOWS)).toEqual([]); + const spec = zenModel(); + const seeded: MeasuredWindows = { + go: {}, + zen: { + [spec.id]: { + evidence: "a probe record", + measured: "2026-11-16", + window: spec.context_window + 1, + }, + }, + }; + expect(problemsOf(seeded)).toEqual([]); + const malformed: MeasuredWindows = { + go: { + "no-such-model": { evidence: " ", measured: "yesterday", window: 0.5 }, + }, + zen: { + [spec.id]: { + evidence: "x", + measured: "2026-11-16", + window: spec.context_window, + }, + }, + }; + expect(problemsOf(malformed)).toEqual([ + "go/no-such-model: window is not a positive whole number", + "go/no-such-model: measured is not an ISO date", + "go/no-such-model: no evidence", + "go/no-such-model: the plane's catalog has no such model", + `zen/${spec.id}: the catalog already says ${String(spec.context_window)}`, + ]); + }); +}); + +describe("context windows · measuredWindowFor", () => { + const table: MeasuredWindows = { + go: { probe: { evidence: "e", measured: "2026-11-16", window: 4096 } }, + zen: {}, + }; + + it("answers a seeded row on its own plane only", () => { + expect(measuredWindowFor("go", "probe", table)).toBe(4096); + expect(measuredWindowFor("zen", "probe", table)).toBeUndefined(); + }); + + it("answers undefined for a miss and for a key every object inherits", () => { + expect(measuredWindowFor("go", "missing", table)).toBeUndefined(); + expect(measuredWindowFor("go", "toString", table)).toBeUndefined(); + expect(measuredWindowFor("go", "__proto__", table)).toBeUndefined(); + }); + + it("reads the shipped table by default, which has no rows", () => { + const spec = zenModel(); + expect(measuredWindowFor("zen", spec.id)).toBeUndefined(); + expect(MEASURED_CONTEXT_WINDOWS).toEqual({ go: {}, zen: {} }); + }); +}); diff --git a/test/credentials.test.ts b/test/credentials.test.ts index f332449..8a93416 100644 --- a/test/credentials.test.ts +++ b/test/credentials.test.ts @@ -331,6 +331,30 @@ describe("credentials · the fill's resolver", () => { expect( credentials.fillKey({ plane: "", provider: "my-relay", url: RELAY }).key ).toBe("env-zen"); + // The two edges that tell the EXACT route reader from the relay-inclusive + // one: an `opencode-go-*` relay off the planes takes the Zen variable, and + // a URL on a plane decides alone, whatever the route is named. + expect( + credentials.fillKey({ + plane: "", + provider: "opencode-go-relay", + url: RELAY, + }).key + ).toBe("env-zen"); + expect( + credentials.fillKey({ + plane: "opencode", + provider: "opencode-go", + url: ZEN, + }).key + ).toBe("env-zen"); + expect( + credentials.fillKey({ + plane: "opencode-go", + provider: "opencode", + url: GO, + }).key + ).toBe("env-go"); }); it("fill: a route named after a plane takes that plane's capture on a URL on neither plane (the name fallback)", () => { diff --git a/test/go-limits.test.ts b/test/go-limits.test.ts index c1cdade..d61a878 100644 --- a/test/go-limits.test.ts +++ b/test/go-limits.test.ts @@ -5,7 +5,6 @@ import { GO_PLAN_TIERS, WINDOW_SHARE, allowanceFor, - formatAllowanceUsd as formatUsd, normalizeModelLabel, parseGoLimitsDoc, } from "./support/src.ts"; @@ -144,18 +143,6 @@ describe("go-limits: labels and formatting", () => { expect(allowanceFor(limits, "grok-4.7")).toBeUndefined(); }); - it("writes whole dollars without cents", () => { - expect(formatUsd(0)).toBe("$0"); - expect(formatUsd(60)).toBe("$60"); - expect(formatUsd(7.5)).toBe("$7.50"); - }); - - it("does not price missing or invalid allowances as zero", () => { - for (const value of [null, undefined, Number.NaN, Infinity, -1, "60"]) { - expect(formatUsd(value)).toBe("—"); - } - }); - it("states the window shares the docs give, rather than inventing them", () => { expect(WINDOW_SHARE).toEqual({ monthly: 1, rolling: 0.2, weekly: 0.5 }); }); diff --git a/test/level-names.test.ts b/test/level-names.test.ts new file mode 100644 index 0000000..5222b77 --- /dev/null +++ b/test/level-names.test.ts @@ -0,0 +1,83 @@ +/** + * The level names' one table, inside its own file. + * + * `test/model-metadata.test.ts` pins that no OTHER file holds the level list + * or its capitalisation; a per-file scan cannot see a second copy inside + * `utils/model-metadata.ts` itself, which is where the one this phase removed + * (`reasoningFor`'s `name: "Off"`) lived. This counts the literals in that + * file's code: one capitalised level-name literal (`"Off"`) and one + * capitalisation, both inside `effortName`. + * + * @module test/level-names.test + */ +import { readFileSync } from "node:fs"; +import { join } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { blankCommentLines } from "./support/strip-comments.ts"; + +const FILE = join( + import.meta.dirname, + "..", + "src", + "utils", + "model-metadata.ts" +); + +/** A capitalised level name written as a literal; `"On"` is not a level. */ +const LEVEL_NAME = /"(?:Off|Minimal|Low|Medium|High|Xhigh|XHigh|Max)"/u; + +/** The lines of `source` that hold `pattern`, as 0-based line numbers. */ +const linesHolding = (source: string, pattern: RegExp): number[] => + source + .split("\n") + .flatMap((line, index) => (pattern.test(line) ? [index] : [])); + +/** The lines `effortName`'s definition spans, from its export to its `;`. */ +const effortNameSpan = (source: string): readonly [number, number] => { + const lines = source.split("\n"); + const start = lines.findIndex((line) => + line.startsWith("export const effortName") + ); + const end = lines.findIndex( + (line, index) => index >= start && line.trimEnd().endsWith(";") + ); + return [start, end]; +}; + +/** Every level-name literal outside `effortName`, as `pattern@line`. */ +const strays = (source: string): string[] => { + const [start, end] = effortNameSpan(source); + return [LEVEL_NAME, /charAt\(0\)\.toUpperCase\(\)/u].flatMap((pattern) => + linesHolding(source, pattern) + .filter((line) => line < start || line > end) + .map((line) => `${pattern.source}@${line + 1}`) + ); +}; + +describe("level names · one table in model-metadata.ts", () => { + it("holds one `Off` and one capitalisation, both inside effortName", () => { + const source = blankCommentLines(readFileSync(FILE, "utf8")); + // The scan read the file: effortName is found, and holds both. + const [start, end] = effortNameSpan(source); + expect(start).toBeGreaterThanOrEqual(0); + expect(end).toBeGreaterThanOrEqual(start); + expect([...source.matchAll(new RegExp(LEVEL_NAME, "gu"))]).toHaveLength(1); + expect([...source.matchAll(/"Off"/gu)]).toHaveLength(1); + expect([...source.matchAll(/charAt\(0\)\.toUpperCase\(\)/gu)]).toHaveLength( + 1 + ); + expect(strays(source)).toEqual([]); + // A second copy planted in the same file is seen, as `"Off"` and as any + // other capitalised level. + const planted = `${source}\nconst OFF = [{ id: "off", name: "Off" }];\n`; + expect(strays(planted)).toEqual([ + `${LEVEL_NAME.source}@${planted.split("\n").length - 1}`, + ]); + const high = `${source}\nconst NAMES = [{ id: "high", name: "High" }];\n`; + expect(strays(high)).toEqual([ + `${LEVEL_NAME.source}@${high.split("\n").length - 1}`, + ]); + }); +}); diff --git a/test/model-metadata.test.ts b/test/model-metadata.test.ts index 41d1ca6..7407d1d 100644 --- a/test/model-metadata.test.ts +++ b/test/model-metadata.test.ts @@ -8,6 +8,9 @@ * * @module test/model-metadata.test */ +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + import { getSupportedThinkingLevels } from "@earendil-works/pi-ai"; import { describe, expect, it } from "vitest"; @@ -22,6 +25,7 @@ import { protocolForSdk, reasoningFor, } from "./support/src.ts"; +import { blankCommentLines } from "./support/strip-comments.ts"; const zen = (id: string): CatalogModelSpec => { const spec = OPENCODE_ZEN_CATALOG.find((model) => model.id === id); @@ -261,3 +265,97 @@ describe("model-metadata · piReasoningFromEfforts (pi-ai's resolveModelReasonin ); }); }); + +describe("model-metadata · the level names live in one table (pin)", () => { + const SRC = join(import.meta.dirname, "..", "src"); + /** Generated tables hold the vendor's words, not a copy this repo keeps. */ + const GENERATED = new Set(["catalog-data.ts", "go-limits-data.ts"]); + + /** Every `src` file, relative to `src`, with its comments blanked. */ + const sources = (): ReadonlyMap => + new Map( + readdirSync(SRC, { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile() && /\.tsx?$/u.test(entry.name)) + .map((entry) => + join(entry.parentPath, entry.name).slice(SRC.length + 1) + ) + .filter((file) => !GENERATED.has(file)) + .map((file) => [ + file, + blankCommentLines(readFileSync(join(SRC, file), "utf8")), + ]) + ); + + /** + * A capitalised level name written as a literal, the form of the `"Off"` + * copy this phase removed from `reasoningFor`. `"On"` is D1's toggle label, + * not a level name, and is not matched. + */ + const LEVEL_NAME = /"(?:Off|Minimal|Low|Medium|High|Xhigh|XHigh|Max)"/u; + + /** The files whose code (comments blanked) matches `pattern`. */ + const holding = ( + files: ReadonlyMap, + pattern: RegExp + ): string[] => + [...files] + .filter(([, source]) => pattern.test(source)) + .map(([file]) => file) + .toSorted(); + + it("names every offered effort through effortName, Off included", () => { + // A bare toggle on a protocol that can disable: Off, then On. + const toggle = reasoningFor( + { reasoning: true, reasoning_options: [{ type: "toggle" }] }, + "anthropic-messages" + ); + expect(toggle?.efforts[0]).toEqual({ id: "off", name: effortName("off") }); + expect(toggle?.effortNames.off).toBe("Off"); + // An effort list with an explicit disable, on completions: every name is + // the table's. + const listed = reasoningFor( + { + reasoning: true, + reasoning_options: [ + { type: "effort", values: ["none", "low", "high"] }, + ], + }, + "openai-completions" + ); + expect(listed?.efforts.map((effort) => effort.id)).toEqual([ + "off", + "low", + "high", + ]); + for (const effort of listed?.efforts ?? []) { + expect(effort.name).toBe(effortName(effort.id)); + } + }); + + it("no second copy of the level list or of its capitalisation in src", () => { + const files = sources(); + // The scan reads the tree: the module that holds the table is in it. + expect(files.has("utils/model-metadata.ts")).toBe(true); + expect(holding(files, /"minimal"/u)).toEqual(["utils/model-metadata.ts"]); + expect(holding(files, /ALL_THINKING_LEVELS/u)).toEqual([]); + expect(holding(files, /charAt\(0\)\.toUpperCase\(\)/u)).toEqual([ + "utils/model-metadata.ts", + ]); + // A capitalised level name, as a literal: only effortName's `"Off"`. + expect(holding(files, LEVEL_NAME)).toEqual(["utils/model-metadata.ts"]); + // A planted copy is seen, so an empty answer above is not a blind scan. + const planted = new Map([ + ...files, + ["planted.ts", 'const LEVELS = ["off", "minimal"];\n'], + ["planted-names.ts", 'const NAMES = [{ id: "high", name: "High" }];\n'], + ]); + expect(holding(planted, /"minimal"/u)).toEqual([ + "planted.ts", + "utils/model-metadata.ts", + ]); + expect(holding(planted, LEVEL_NAME)).toEqual([ + "planted-names.ts", + "utils/model-metadata.ts", + ]); + }); +}); diff --git a/test/models-discovery.test.ts b/test/models-discovery.test.ts index 2ae45a5..59901b3 100644 --- a/test/models-discovery.test.ts +++ b/test/models-discovery.test.ts @@ -25,6 +25,7 @@ import { findModelSpecOn, isDeprecatedModelOn, isServableSdk, + type MeasuredWindows, mergeDiscoveredModels, OPENCODE_GO_CATALOG, OPENCODE_ZEN_CATALOG, @@ -875,6 +876,116 @@ describe("decorateModelDiscovery", () => { }); }); +describe("the discovery rows' measured window (L11)", () => { + const ID = "window-probe"; + /** A seeded table: a Zen row for the probe, and a Go row for the same id. */ + const seeded = (zen: number, go: number): MeasuredWindows => ({ + go: { [ID]: { evidence: "test", measured: "2026-11-16", window: go } }, + zen: { [ID]: { evidence: "test", measured: "2026-11-16", window: zen } }, + }); + const zenOnly = (window: number): MeasuredWindows => ({ + go: {}, + zen: { [ID]: { evidence: "test", measured: "2026-11-16", window } }, + }); + /** + * Land a live row for the probe on each plane, with a window of its own: + * 128k on Zen, 96k on Go. + */ + const seedCatalog = async (): Promise => { + await refreshCatalog( + vi.fn().mockResolvedValue( + Response.json({ + "opencode-go": { + api: "https://opencode.ai/zen/go/v1", + models: { + [ID]: { + limit: { context: 96_000 }, + name: "Window Probe", + provider: { npm: "@ai-sdk/anthropic" }, + }, + }, + }, + opencode: { + api: "https://opencode.ai/zen/v1", + models: { + [ID]: { + limit: { context: 128_000 }, + name: "Window Probe", + provider: { npm: "@ai-sdk/openai" }, + }, + }, + }, + }) + ) as unknown as typeof fetch, + true + ); + }; + const windowOf = (rows: ReturnType): unknown => + rows.find((row) => row.id === ID)?.contextWindow; + + it("catalog-first (a plane the plugin serves): the measured window beats the catalog's and pi's", async () => { + await seedCatalog(); + // The premise: the catalog and pi each answer a window of their own. + expect(findModelSpecOn("zen", ID)?.context_window).toBe(128_000); + const pi = [{ contextWindow: 200_000, id: ID }]; + expect(windowOf(complementDiscoveredModels(pi, "zen"))).toBe(128_000); + expect( + windowOf(complementDiscoveredModels(pi, "zen", zenOnly(64_000))) + ).toBe(64_000); + // A catalog row pi did not list reads it too. + expect( + windowOf(complementDiscoveredModels([], "zen", zenOnly(64_000))) + ).toBe(64_000); + }); + + it("pi-first (a route pi-ai serves): pi's window still wins, and the measured one beats the catalog's", async () => { + await seedCatalog(); + expect( + windowOf( + mergeDiscoveredModels( + [{ contextWindow: 200_000, id: ID }], + "zen", + zenOnly(64_000) + ) + ) + ).toBe(200_000); + expect( + windowOf(mergeDiscoveredModels([{ id: ID }], "zen", zenOnly(64_000))) + ).toBe(64_000); + }); + + it("reads the row of the plane asked about, never the other plane's", async () => { + await seedCatalog(); + const goOnly: MeasuredWindows = { go: seeded(1, 32_000).go, zen: {} }; + expect(windowOf(complementDiscoveredModels([], "zen", goOnly))).toBe( + 128_000 + ); + expect( + windowOf(complementDiscoveredModels([], "zen", seeded(64_000, 32_000))) + ).toBe(64_000); + expect(windowOf(mergeDiscoveredModels([{ id: ID }], "zen", goOnly))).toBe( + 128_000 + ); + // The Go arm, at both of rowFrom's call sites, so a plane fixed to either + // value turns a case red: the premise is Go's own catalog window, 96k. + expect(findModelSpecOn("go", ID)?.context_window).toBe(96_000); + expect( + windowOf(complementDiscoveredModels([], "go", seeded(64_000, 32_000))) + ).toBe(32_000); + expect( + windowOf(complementDiscoveredModels([], "go", zenOnly(64_000))) + ).toBe(96_000); + expect( + windowOf( + mergeDiscoveredModels([{ id: ID }], "go", seeded(64_000, 32_000)) + ) + ).toBe(32_000); + expect( + windowOf(mergeDiscoveredModels([{ id: ID }], "go", zenOnly(64_000))) + ).toBe(96_000); + }); +}); + describe("complementDiscoveredModels", () => { it("a catalog model the registry retired since the shim, or whose SDK nothing serves, is not offered; pi's retired row is dropped too", async () => { const retired = servableIds(OPENCODE_ZEN_CATALOG)[0] ?? ""; diff --git a/test/plane-model.test.ts b/test/plane-model.test.ts index 9068675..e39b6d6 100644 --- a/test/plane-model.test.ts +++ b/test/plane-model.test.ts @@ -407,6 +407,53 @@ describe("plane-model · base (modern, legacy, route-level)", () => { }); describe("plane-model · metadata (D17) and the model object", () => { + it("reads a measured window after the user's row and the override, and before the catalog and pi (L11)", () => { + // Seeded throughout, so no vendor row is read: the shipped table has no + // rows, and a made-up id with a catalog window and a pi window of its own + // makes "before the catalog and pi" an assertion rather than a premise. + const ID = "window-probe"; + const spec = { + context_window: 128_000, + id: ID, + name: "Window Probe", + provider_npm: "@ai-sdk/openai", + }; + const pi = { api: "openai-responses", contextWindow: 200_000, id: ID }; + const measured = { + go: {}, + zen: { + [ID]: { + evidence: "a seeded row", + measured: "2026-11-16", + window: 64_000, + }, + }, + }; + const windowOn = ( + route: "opencode" | "opencode-go", + extra: Partial = {} + ) => modelOf(inputFor(route, ID, { pi, spec, ...extra })).contextWindow; + // Without the table, the catalog's window answers, ahead of pi's. + expect(windowOn("opencode")).toBe(128_000); + expect(windowOn("opencode", { measuredWindows: measured })).toBe(64_000); + expect( + windowOn("opencode", { + measuredWindows: measured, + override: { contextWindow: 300_000, id: ID }, + }) + ).toBe(300_000); + expect( + windowOn("opencode", { + entry: { contextWindow: 400_000, id: ID }, + measuredWindows: measured, + }) + ).toBe(400_000); + // The other plane's row is not this route's measurement. + expect(windowOn("opencode-go", { measuredWindows: measured })).toBe( + 128_000 + ); + }); + it("takes the user's row, then the override, then the catalog, then pi, then the defaults", () => { const spark = modelOf( inputFor("opencode", "gpt-5.3-codex-spark", { diff --git a/test/plane-table.test.ts b/test/plane-table.test.ts new file mode 100644 index 0000000..bdeae58 --- /dev/null +++ b/test/plane-table.test.ts @@ -0,0 +1,308 @@ +/** + * The plane a route or a URL belongs to, read through every caller (P7's pin). + * + * The rule "which plane is this" was written several times over: the + * catalog's route rule, the meter's Zen test, the captured key's tier, the + * discovery wrapper's plane, the core-tool fallback's URL read. P7 folds them + * into one table without changing any answer, so this file pins each + * caller's OUTPUT, through names that exist before and after the refactor, + * and it is not edited while the refactor lands. + * + * The callers do not all agree, and that is pinned too rather than + * reconciled: the meter's `isZenProvider` is case-insensitive and needs + * "opencode" in the name, while the catalog's route rule is case-sensitive and + * answers Zen for anything that is not the Go route or a `opencode-go-*` + * relay. `OpenCode-Go` is therefore not Zen to the meter and Zen to the + * catalog, on both trees. + * + * @module test/plane-table.test + */ +import { AsyncLocalStorage } from "node:async_hooks"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { payload } from "./support/catalogs.ts"; +import { + clearSessionUsageStore, + createStreamHook, + DEFAULT_FREE_MODEL_MARKER, + getSessionUsage, + isCoreToolModel, + isZenProvider, + maybeInjectCoreTools, + recordTurnUsage, + refreshCatalog, + resolveConfig, + resolveDiscoveryProvider, + tierForRequest, +} from "./support/src.ts"; +import { okBody, serviceWithKey, stubFetch } from "./support/usage-fixture.ts"; + +afterEach(() => { + vi.unstubAllGlobals(); + clearSessionUsageStore(); +}); + +/** The relay route a deployment may add for the Go plane. */ +const GO_RELAY = "opencode-go-relay"; + +/** Every route the pin reads, with each caller's answer on both trees. */ +const ROUTES: readonly { + readonly route: string | undefined; + readonly isZen: boolean; + readonly tier: "go" | "zen" | "unknown"; +}[] = [ + { isZen: true, route: "opencode", tier: "zen" }, + { isZen: false, route: "opencode-go", tier: "go" }, + { isZen: false, route: GO_RELAY, tier: "unknown" }, + // Starts with `opencode-go` but not with `opencode-go-`: Zen's google family. + { isZen: true, route: "opencode-google", tier: "unknown" }, + { isZen: false, route: "OpenCode-Go", tier: "unknown" }, + { isZen: true, route: "OPENCODE", tier: "unknown" }, + { isZen: false, route: "my-relay", tier: "unknown" }, + { isZen: false, route: "", tier: "unknown" }, + { isZen: false, route: undefined, tier: "unknown" }, + // An inherited key of every object is never a route. + { isZen: false, route: "constructor", tier: "unknown" }, +]; + +describe("plane table · every caller reads the same plane for a route (pin)", () => { + it("the meter's Zen test and the captured key's tier, per route", () => { + for (const { isZen, route, tier } of ROUTES) { + expect(isZenProvider(route), `isZenProvider(${String(route)})`).toBe( + isZen + ); + expect( + tierForRequest(undefined, route), + `tierForRequest(undefined, ${String(route)})` + ).toBe(tier); + } + }); + + it("the discovery wrapper's plane, for the routes it claims", () => { + const config = resolveConfig({ + providers: ["opencode", "opencode-go", GO_RELAY], + }); + expect(resolveDiscoveryProvider({ provider: "opencode" }, config)).toBe( + "zen" + ); + expect(resolveDiscoveryProvider({ provider: "opencode-go" }, config)).toBe( + "go" + ); + // A claimed relay with no base URL: only the two exact routes decide by + // name, so there is nothing to read its plane from. + expect( + resolveDiscoveryProvider({ provider: GO_RELAY }, config) + ).toBeUndefined(); + expect( + resolveDiscoveryProvider({ provider: "constructor" }, config) + ).toBeUndefined(); + }); +}); + +describe("plane table · a decorated turn is billed to its route's plane, relays included (pin)", () => { + const PRICE_PROBE = "plane-table-price-probe"; + const RATES = { go: 0.15, zen: 0.3 } as const; + + /** + * One turn's usage, the way the gateway reports it: a million input tokens, + * so the cost IS the plane's input rate. + * + * @yields {unknown} one usage chunk + */ + const usageStream = async function* usageStream() { + yield { + type: "usage", + usage: { + inputTokens: 1_000_000, + outputTokens: 0, + totalTokens: 1_000_000, + }, + }; + }; + + it("bills each route to the plane the catalog's route rule names", async () => { + await refreshCatalog( + async () => + Response.json( + payload({ + go: [{ id: PRICE_PROBE, input: RATES.go }], + zen: [{ id: PRICE_PROBE, input: RATES.zen }], + }) + ), + true + ); + const hook = createStreamHook( + { logger: { info: () => {} } } as never, + resolveConfig({ + providers: [ + "opencode", + "opencode-go", + GO_RELAY, + "opencode-google", + "OpenCode-Go", + "my-relay", + ], + usageEnabled: true, + } as never), + new AsyncLocalStorage() + ); + const billed = async (provider: string): Promise => { + const sessionId = `plane-table-${provider}`; + const result = hook({ model: PRICE_PROBE, provider, sessionId }, () => + usageStream() + ); + for await (const _chunk of result as AsyncGenerator) { + void _chunk; + } + return getSessionUsage(sessionId)?.costByPlane; + }; + expect(await billed("opencode")).toEqual({ go: 0, zen: RATES.zen }); + expect(await billed("opencode-go")).toEqual({ go: RATES.go, zen: 0 }); + expect(await billed(GO_RELAY)).toEqual({ go: RATES.go, zen: 0 }); + expect(await billed("opencode-google")).toEqual({ go: 0, zen: RATES.zen }); + // Case-sensitive: not the Go route, so Zen to the catalog (the header's + // `OpenCode-Go` claim). + expect(await billed("OpenCode-Go")).toEqual({ go: 0, zen: RATES.zen }); + expect(await billed("my-relay")).toEqual({ go: 0, zen: RATES.zen }); + }); +}); + +describe("plane table · the URL decides before the route, in both endpoint families (pin)", () => { + it("files a captured key by the URL's plane first, then by the exact route", () => { + expect( + tierForRequest("https://opencode.ai/zen/v1/messages", "opencode-go") + ).toBe("zen"); + expect( + tierForRequest( + "https://opencode.ai/inference/go/openai/v1/chat/completions", + "opencode" + ) + ).toBe("go"); + expect( + tierForRequest("https://opencode.ai/inference/google/v1beta/models") + ).toBe("zen"); + expect( + tierForRequest("https://relay.example/v1/chat/completions", "opencode-go") + ).toBe("go"); + expect( + tierForRequest("https://relay.example/v1/chat/completions", "my-relay") + ).toBe("unknown"); + }); + + it("reads a gateway draft's plane from its base URL's path", () => { + const config = resolveConfig({ providers: ["opencode", "opencode-go"] }); + expect( + resolveDiscoveryProvider( + { baseURL: "https://opencode.ai/inference/go/openai/v1" }, + config + ) + ).toBe("go"); + expect( + resolveDiscoveryProvider( + { baseURL: "https://opencode.ai/inference/google/v1beta" }, + config + ) + ).toBe("zen"); + }); + + it("reads the core-tool fallback's row from the URL's plane, and with no plane the plane-blind lookup's Go row", async () => { + // Free on Zen, paid on Go: the plane's own row decides when the request + // names a plane. With none, the plane-blind lookup answers, and it reads + // Go first (pinned on its own in `test/plane-lookup.test.ts`); the + // fallback for a plane whose row is absent is `test/tool-fallback.test.ts`'s. + const ZEN_ONLY_FREE = "plane-table-tool-probe"; + await refreshCatalog( + async () => + Response.json( + payload({ + go: [{ id: ZEN_ONLY_FREE, name: "Probe" }], + zen: [{ free: true, id: ZEN_ONLY_FREE, name: "Probe" }], + }) + ), + true + ); + expect(ZEN_ONLY_FREE).not.toContain(DEFAULT_FREE_MODEL_MARKER); + expect(isCoreToolModel(ZEN_ONLY_FREE, "", "zen")).toBe(true); + expect(isCoreToolModel(ZEN_ONLY_FREE, "", "go")).toBe(false); + // No plane: the plane-blind row, which reads Go first, so paid. + expect(isCoreToolModel(ZEN_ONLY_FREE, DEFAULT_FREE_MODEL_MARKER)).toBe( + false + ); + + const body = JSON.stringify({ model: ZEN_ONLY_FREE }); + const options = { enabled: true, modelMarker: "none" }; + expect( + maybeInjectCoreTools( + "https://opencode.ai/zen/v1/chat/completions", + body, + new Headers(), + options + ) + ).not.toBe(body); + expect( + maybeInjectCoreTools( + "https://opencode.ai/zen/go/v1/chat/completions", + body, + new Headers(), + options + ) + ).toBe(body); + }); +}); + +describe("plane table · a prospective model is priced from the asking route's plane only, with no other-plane fallback (pin)", () => { + const GO_ONLY = "plane-table-go-only"; + const GO_RATE = { input: 0.4, output: 1.6 } as const; + + const seedAndRecord = async (): Promise => { + await refreshCatalog( + async () => + Response.json( + payload({ + go: [{ id: GO_ONLY, input: GO_RATE.input, output: GO_RATE.output }], + }) + ), + true + ); + // A Go turn of $0.15: a million input tokens at 0.15. + recordTurnUsage( + "plane-table-session", + { inputTokens: 1_000_000, outputTokens: 0, totalTokens: 1_000_000 }, + { input: 0.15, output: 0 }, + "plane-table-ran", + false, + "go" + ); + }; + + it("prices the picked model on the route's own plane, and says — where that plane has no row", async () => { + await seedAndRecord(); + stubFetch(() => new Response(okBody())); + const service = serviceWithKey("sk-live-key"); + const read = async (provider: string) => { + const reading = await service.read({ + model: GO_ONLY, + provider, + sessionId: "plane-table-session", + }); + return reading.session; + }; + + const zen = await read("opencode"); + expect(zen?.activeModel).toBe(GO_ONLY); + expect(zen?.activeRateFormatted).toBe("—"); + expect(zen?.planeCostFormatted).toBe("$0.00"); + + const go = await read("opencode-go"); + expect(go?.activeModel).toBe(GO_ONLY); + expect(go?.activeRateFormatted).toBe( + `$${String(GO_RATE.input)} / $${String(GO_RATE.output)} per 1M` + ); + expect(go?.planeCostFormatted).toBe("$0.15"); + + const relay = await read(GO_RELAY); + expect(relay?.activeRateFormatted).toBe(go?.activeRateFormatted); + expect(relay?.planeCostFormatted).toBe("$0.15"); + }); +}); diff --git a/test/planes.test.ts b/test/planes.test.ts new file mode 100644 index 0000000..584fba5 --- /dev/null +++ b/test/planes.test.ts @@ -0,0 +1,282 @@ +/** + * The plane table (`src/utils/planes.ts`) and its URL reader, and the guard + * against a second copy of the rule in the spellings it scans. + * + * `test/plane-table.test.ts` pins every caller's answer through names that + * existed before the table; this file tests the table's own names, and scans + * `src` for a route compared against a plane route's literal, or paired with a + * plane's name in a quoted table row (either order, any key name), anywhere + * but the table and the route list it is keyed by. A source scan is a + * tripwire for the spellings it names, not a proof: what still passes it + * includes, for example, an unquoted key (`opencode: "zen"`), a record with + * another key between the route and the plane, and a route built from parts; + * the second scan plants each of those as a non-offender, so the list is + * checked rather than only written down. + * + * @module test/planes.test + */ +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { + PLANE_OF_ROUTE, + PLANE_ROUTES, + planeForRoute, + planeForUrl, + planeOfPlaneRoute, +} from "./support/src.ts"; +import { blankCommentLines } from "./support/strip-comments.ts"; + +describe("planes · one table", () => { + it("files each owned route under its plane, keyed in the route list's order", () => { + expect(PLANE_OF_ROUTE).toEqual({ opencode: "zen", "opencode-go": "go" }); + expect(Object.keys(PLANE_OF_ROUTE)).toEqual([...PLANE_ROUTES]); + }); + + it("planeOfPlaneRoute answers the two owned routes and nothing else", () => { + expect(planeOfPlaneRoute("opencode")).toBe("zen"); + expect(planeOfPlaneRoute("opencode-go")).toBe("go"); + for (const value of [ + "opencode-go-relay", + "OpenCode-Go", + "constructor", + "__proto__", + "", + 5, + undefined, + ]) { + expect(planeOfPlaneRoute(value), String(value)).toBeUndefined(); + } + }); + + it("planeForRoute: Go for the Go route and its relays, Zen for everything else", () => { + const table: readonly (readonly [unknown, "go" | "zen"])[] = [ + ["opencode", "zen"], + ["opencode-go", "go"], + ["opencode-go-relay", "go"], + ["opencode-google", "zen"], + // Case-sensitive, as the catalog's rule always was. + ["OpenCode-Go", "zen"], + ["my-relay", "zen"], + ["", "zen"], + [undefined, "zen"], + [5, "zen"], + ]; + for (const [route, plane] of table) { + expect(planeForRoute(route), String(route)).toBe(plane); + } + }); + + it("planeForUrl reads the path, in both endpoint families and a relay's", () => { + expect(planeForUrl("https://opencode.ai/inference/go/openai/v1")).toBe( + "go" + ); + expect(planeForUrl("https://opencode.ai/zen/go/v1/chat/completions")).toBe( + "go" + ); + expect(planeForUrl("https://opencode.ai/inference/google/v1beta")).toBe( + "zen" + ); + expect(planeForUrl("https://opencode.ai/zen/v1/messages")).toBe("zen"); + expect( + planeForUrl("https://relay.example.com/go/v1/chat/completions") + ).toBe("go"); + }); +}); + +describe("planes · no second copy of the rule in src", () => { + const SRC = join(import.meta.dirname, "..", "src"); + + /** + * Files that may hold a comparison, and exactly how many: the table (its + * exact `=== "opencode-go"` and its relay half, `startsWith("opencode-go-")`), + * the route list's own guard (`isPlaneRoute`'s pair), and `go-discovery.ts`, + * whose reads of a provider row by name stay until the module moves in + * P10a. A count, not a whole-file pass, so a second copy added inside an + * allowed file is still seen; and an EXACT count, not a ceiling, so a copy + * that goes (P10a's move) forces its allowance down rather than leaving + * room for a new one. Generated files hold the vendor's data, not a copy of + * a rule. + */ + const ALLOWED: ReadonlyMap = new Map([ + ["utils/planes.ts", 2], + ["utils/protocols.ts", 2], + ["go-discovery.ts", 2], + ]); + + /** + * Files that may hold a quoted route paired with a plane's name, and exactly + * how many: `PLANE_OF_ROUTE`'s quoted row (`"opencode-go": "go"`; its + * `opencode` key is unquoted), and `go-discovery.ts`'s capture-store read + * `get("opencode", "zen")`, until P10a moves it. + */ + const PAIRS_ALLOWED: ReadonlyMap = new Map([ + ["utils/planes.ts", 1], + ["go-discovery.ts", 1], + ]); + const GENERATED = new Set(["catalog-data.ts", "go-limits-data.ts"]); + + /** + * The rule's spellings: a comparison against `"opencode"` or `"opencode-go"` + * on either side, the relay half (`startsWith("opencode-go…")`), and a + * `case` label. The relay predicate `startsWith("opencode")` (is this route + * a relay at all) is a different question and is not matched. + */ + const COMPARISON = + /[!=]==\s*"opencode(?:-go)?"|"opencode(?:-go)?"\s*[!=]==|startsWith\(\s*"opencode-go|case\s+"opencode(?:-go)?"\s*:/gu; + + /** + * The table form: a quoted route beside a plane's name, in either order, as + * an object row (`"opencode-go": "go"`, `"go": "opencode-go"`), a tuple or + * argument pair (`["opencode", "zen"]`, `["zen", "opencode"]`), or a record + * row under any key name (`{ route: "opencode", plane: "zen" }`, the form of + * the purge action's table this phase folded, and `{ plane: "zen", route: + * "opencode" }`, the key order its replacement builds). The second literal + * of a pair must not itself be a key (`(?!\s*:)`), so two neighbouring rows + * of one object (`opencode: "zen", "opencode-go": "go"`) are not read as a + * plane-first pair that would hide the real row behind it. + */ + const PAIR = + /"opencode(?:-go)?"\s*[:,]\s*(?:\w+\s*:\s*)?"(?:go|zen)"(?!\s*:)|"(?:go|zen)"\s*[:,]\s*(?:\w+\s*:\s*)?"opencode(?:-go)?"(?!\s*:)/gu; + + const count = (source: string, pattern: RegExp = COMPARISON): number => + [...source.matchAll(pattern)].length; + + /** Every file whose count of `pattern` is not exactly its allowance. */ + const offenders = ( + files: ReadonlyMap, + pattern: RegExp = COMPARISON, + allowed: ReadonlyMap = ALLOWED + ): string[] => + [...files] + .filter( + ([file, source]) => count(source, pattern) !== (allowed.get(file) ?? 0) + ) + .map(([file]) => file) + .toSorted(); + + const sources = (): ReadonlyMap => + new Map( + readdirSync(SRC, { recursive: true, withFileTypes: true }) + .filter((entry) => entry.isFile() && /\.tsx?$/u.test(entry.name)) + .map((entry) => + join(entry.parentPath, entry.name).slice(SRC.length + 1) + ) + .filter((file) => !GENERATED.has(file)) + .map((file) => [ + file, + blankCommentLines(readFileSync(join(SRC, file), "utf8")), + ]) + ); + + it("compares a route against a plane route's literal only in the table", () => { + const files = sources(); + // The scan reads the tree: the table, and a file that held a copy. + expect(files.has("utils/planes.ts")).toBe(true); + expect(files.has("key-capture.ts")).toBe(true); + expect(count(files.get("utils/planes.ts") ?? "")).toBe(2); + expect(offenders(files)).toEqual([]); + // A planted copy is seen, on either side of the operator, as the relay + // half and as a `case` label, and inside an allowed file; a longer route + // name, and the relay predicate, are not mistaken for one. + const planted = new Map([ + ...files, + ["planted.ts", 'const go = route === "opencode-go";\n'], + ["planted-left.ts", 'if ("opencode" !== provider) {}\n'], + [ + "planted-relay-half.ts", + 'const go = route.startsWith("opencode-go-");\n', + ], + ["planted-case.ts", 'switch (route) { case "opencode-go": break; }\n'], + [ + "utils/planes.ts", + `${files.get("utils/planes.ts") ?? ""}\nconst again = route === "opencode";\n`, + ], + ["relay.ts", 'const r = route === "opencode-go-relay";\n'], + ["relay-predicate.ts", 'const relay = !route.startsWith("opencode");\n'], + ]); + expect(offenders(planted)).toEqual([ + "planted-case.ts", + "planted-left.ts", + "planted-relay-half.ts", + "planted.ts", + "utils/planes.ts", + ]); + // A removed copy is seen too: the allowance is exact, not a ceiling. + const removed = new Map([...files, ["go-discovery.ts", ""]]); + expect(offenders(removed)).toEqual(["go-discovery.ts"]); + }); + + it("pairs a route with a plane's name in a table only in the table", () => { + const files = sources(); + expect(files.has("go-discovery.ts")).toBe(true); + // The table's one quoted row is the match, not a plane-first reading of + // its two neighbouring rows. + expect( + [...(files.get("utils/planes.ts") ?? "").matchAll(PAIR)].map( + (match) => match[0] + ) + ).toEqual(['"opencode-go": "go"']); + expect(offenders(files, PAIR, PAIRS_ALLOWED)).toEqual([]); + // The purge action's old table row, the same record in the key order its + // replacement builds, a record under another key name, an object row + // either way round, a Map's tuples either way round, and a second row + // inside an allowed file are each seen. + const planted = new Map([ + ...files, + [ + "planted-record.ts", + 'const PLANES = [{ route: "opencode", plane: "zen" }];\n', + ], + [ + "planted-record-plane-first.ts", + 'const PLANES = [\n { plane: "zen", route: "opencode" },\n { plane: "go", route: "opencode-go" },\n];\n', + ], + [ + "planted-record-tier.ts", + 'const T = [{ route: "opencode", tier: "zen" }];\n', + ], + ["planted-object.ts", 'const P = { "opencode": "zen" };\n'], + ["planted-object-reversed.ts", 'const P = { "go": "opencode-go" };\n'], + ["planted-map.ts", 'const P = new Map([["opencode-go", "go"]]);\n'], + [ + "planted-map-reversed.ts", + 'const P = new Map([["zen", "opencode"]]);\n', + ], + [ + "utils/planes.ts", + `${files.get("utils/planes.ts") ?? ""}\nconst again = { "opencode": "zen" };\n`, + ], + // Not seen: a relay route, a pair whose other literal is no plane's + // name, a neighbouring row that is a key, and the spellings the scan + // does not name (an unquoted key, another key between the pair, a + // route built from parts). + ["relay.ts", 'const r = { "opencode-go-relay": "go" };\n'], + ["other.ts", 'const k = get("opencode", "anthropic");\n'], + ["neighbour.ts", 'const n = { a: "zen", "opencode": 1 };\n'], + ["unquoted.ts", 'const u = { opencode: "zen" };\n'], + [ + "between.ts", + 'const b = [{ route: "opencode", label: "x", plane: "zen" }];\n', + ], + ["parts.ts", 'const p = { ["opencode" + "-go"]: "go" };\n'], + ]); + expect(offenders(planted, PAIR, PAIRS_ALLOWED)).toEqual([ + "planted-map-reversed.ts", + "planted-map.ts", + "planted-object-reversed.ts", + "planted-object.ts", + "planted-record-plane-first.ts", + "planted-record-tier.ts", + "planted-record.ts", + "utils/planes.ts", + ]); + // Exact here as well: a pair that goes forces its allowance down. + const removed = new Map([...files, ["go-discovery.ts", ""]]); + expect(offenders(removed, PAIR, PAIRS_ALLOWED)).toEqual([ + "go-discovery.ts", + ]); + }); +}); diff --git a/test/protocols.test.ts b/test/protocols.test.ts index 10ca1d1..706cadb 100644 --- a/test/protocols.test.ts +++ b/test/protocols.test.ts @@ -12,7 +12,6 @@ import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; -import { piKnows } from "./support/host.ts"; import { allOfferedCompatFields, COMPAT_GATES, @@ -37,7 +36,7 @@ import { } from "./support/src.ts"; describe("protocols · the SDK table", () => { - it("maps every catalog SDK, mistral as completions as pi's own data does, and nothing is unserved", () => { + it("maps every catalog SDK, mistral as completions by the plugin's own rule, and nothing is unserved", () => { expect(PROTOCOL_FOR_SDK).toEqual({ "@ai-sdk/anthropic": "anthropic-messages", "@ai-sdk/google": "google-generative-ai", @@ -54,7 +53,6 @@ describe("protocols · the SDK table", () => { for (const sdk of sdks) { expect(isServableSdk(sdk), `catalog SDK ${String(sdk)}`).toBe(true); } - expect(piKnows("opencode", "mistral-large-4")).toBe("openai-completions"); expect(protocolForSdk()).toBe("openai-completions"); expect(protocolForSdk("@ai-sdk/cohere")).toBeUndefined(); expect(protocolForSdk(5)).toBeUndefined(); diff --git a/test/purge-service.test.ts b/test/purge-service.test.ts index 5661a20..fff7ec9 100644 --- a/test/purge-service.test.ts +++ b/test/purge-service.test.ts @@ -117,6 +117,34 @@ describe("purge: deleting what the catalog retired", () => { { id: "mimo-v2.6-flash-free" }, ]); }); + it("judges each plane route on its own plane: an id retired on Go only stays declared on Zen", async () => { + // One id, live on Zen and retired on Go, declared on both routes. The + // route-to-plane table decides which plane's retirement applies, so a + // swapped or constant plane fails one way or the other. + const split = { + opencode: { + models: { "split-probe": { name: "Probe", limit: { context: 1000 } } }, + }, + "opencode-go": { models: { "split-probe": { status: "deprecated" } } }, + }; + parseModelsDevCatalog(split); + vi.stubGlobal("fetch", () => + Promise.resolve({ json: async () => split, ok: true }) + ); + const editor = editorWith({ + go: [{ id: "split-probe" }], + zen: [{ id: "split-probe" }], + }); + + const result = await new ModelPurgeService(ctxWith(editor)).purge(); + + expect(result.removed).toEqual([ + { id: "split-probe", provider: "opencode-go" }, + ]); + const written = editor.entry.options.config.providers; + expect(written.opencode.models).toEqual([{ id: "split-probe" }]); + expect(written["opencode-go"].models).toEqual([]); + }); }); describe("purge: the refusals it can report", () => { diff --git a/test/request-shape.test.ts b/test/request-shape.test.ts index 10c0ee2..faf4e2f 100644 --- a/test/request-shape.test.ts +++ b/test/request-shape.test.ts @@ -12,12 +12,15 @@ import { describe, expect, it } from "vitest"; import { ANTHROPIC_VERSION, authHeaderFor, - catalogPlaneForRoute, gatewayPlaneFor, headerSourceOf, isGoPlaneUrl, isZenProvider, modelIdOf, + OPENCODE_CLI_VERSION, + OPENCODE_PATCH_USER_AGENT, + OPENCODE_USER_AGENT, + planeForRoute, planeHeadersFor, pluginMarkerOn, requestUrlOf, @@ -45,7 +48,7 @@ describe("request-shape · isZenProvider", () => { expect(isZenProvider()).toBe(false); }); - it("agrees with catalogPlaneForRoute on every route the plugin serves", () => { + it("agrees with planeForRoute on every route the plugin serves", () => { // The defect was these two predicates disagreeing; a route added to or // renamed in either reader must not let them drift apart again. The // set is bounded on purpose: outside OpenCode routes the two differ by @@ -62,9 +65,7 @@ describe("request-shape · isZenProvider", () => { ]; expect(routes.length).toBeGreaterThan(2); for (const route of routes) { - expect(isZenProvider(route), route).toBe( - catalogPlaneForRoute(route) === "zen" - ); + expect(isZenProvider(route), route).toBe(planeForRoute(route) === "zen"); } }); }); @@ -353,4 +354,13 @@ describe("request-shape · planeHeadersFor, the one table of plane headers", () "x-opencode-org-id", ]); }); + + it("the User-Agent the emulated client sends, and the one the plugin signs with", () => { + // The 1.x form, `opencode/` and nothing more; the plugin's own + // requests append its name. + expect(OPENCODE_USER_AGENT).toBe(`opencode/${OPENCODE_CLI_VERSION}`); + expect(OPENCODE_PATCH_USER_AGENT).toBe( + `opencode/${OPENCODE_CLI_VERSION} dsh-opencode-patch` + ); + }); }); diff --git a/test/session-cost.test.ts b/test/session-cost.test.ts index 77e1431..0e8344d 100644 --- a/test/session-cost.test.ts +++ b/test/session-cost.test.ts @@ -16,7 +16,6 @@ import { clearSessionUsageStore, describeModel, formatModelRate, - formatUsd, getSessionUsage, recordTurnUsage, } from "./support/src.ts"; @@ -38,21 +37,6 @@ beforeEach(() => { clearSessionUsageStore(); }); -describe("formatUsd", () => { - it("always reads two decimals, whatever the magnitude", () => { - // The tiered formatter (3dp below a cent, 4dp below a tenth) printed - // $0.006 on the trigger — precision in the wrong place. A meter is a - // gauge, not an invoice, and a number whose LENGTH changes with its value - // makes the row shift on every turn. - expect(formatUsd(0)).toBe("$0.00"); - expect(formatUsd(0.00012)).toBe("$0.00"); - expect(formatUsd(0.0042)).toBe("$0.00"); - expect(formatUsd(0.006)).toBe("$0.01"); - expect(formatUsd(0.42)).toBe("$0.42"); - expect(formatUsd(12.3456)).toBe("$12.35"); - }); -}); - describe("formatModelRate", () => { it("renders both directions of a paid model's rate", () => { expect(formatModelRate(GO_FLASH)).toBe("$0.15 / $0.6 per 1M"); diff --git a/test/support/src.ts b/test/support/src.ts index 8714b90..b0e383f 100644 --- a/test/support/src.ts +++ b/test/support/src.ts @@ -26,9 +26,8 @@ * Importing this file loads the whole `src` graph, host and client, so a module * that fails to load fails every test that comes through here, not only its own. * - * Two names are defined twice under one name, so the second definition is - * aliased: the client bundle's `apply` (`applySettingsPage`) and the Go - * allowance formatter `formatUsd` (`formatAllowanceUsd`). + * One name is defined twice, so the second definition is aliased: the client + * bundle's `apply` (`applySettingsPage`). * * The file is type-checked with the rest of `test/`, so `vp check` proves that * every re-export resolves. @@ -138,7 +137,6 @@ export { GO_MODEL_LIMITS } from "../../src/go-limits-data.ts"; // go-limits.ts export { allowanceFor, - formatUsd as formatAllowanceUsd, GO_PLAN_TIERS, normalizeModelLabel, parseGoLimitsDoc, @@ -196,6 +194,7 @@ export { LEGACY_NAME, LEGACY_PKG, name, + OPENCODE_CLI_VERSION, OPENCODE_PATCH_USER_AGENT, OPENCODE_USER_AGENT, } from "../../src/identity.ts"; @@ -213,7 +212,6 @@ export { apply, callHeadersFor } from "../../src/lifecycle.ts"; export { catalogGeneration, catalogListenerCount, - catalogPlaneForRoute, enrichModelsResponse, findModelSpec, findModelSpecOn, @@ -222,12 +220,15 @@ export { isDeprecatedModelOn, isGoModelsListingUrl, isModelsListingUrl, + liveCatalogOn, MODELS_OPENCODE_URL, onCatalogChange, parseModelsDevCatalog, refreshCatalog, resetCatalogState, sanitizeModalities, + specFor, + specOn, } from "../../src/models-catalog.ts"; // models-discovery.ts @@ -282,7 +283,6 @@ export { clearSessionUsageStore, describeModel, formatModelRate, - formatUsd, getSessionUsage, recordTurnUsage, } from "../../src/session-cost.ts"; @@ -424,6 +424,12 @@ export type { RelativeReset } from "../../src/usage-ui.ts"; // usage.ts export { GoUsageService } from "../../src/usage.ts"; +// utils/client-generation.ts +export { + CLIENT_GENERATIONS, + EMULATED_GENERATION, +} from "../../src/utils/client-generation.ts"; + // utils/config-run.ts export { configRunOf, @@ -509,6 +515,14 @@ export { } from "../../src/utils/plane-profile.ts"; export type { PlaneProfileInput } from "../../src/utils/plane-profile.ts"; +// utils/planes.ts +export { + PLANE_OF_ROUTE, + planeForRoute, + planeOfPlaneRoute, +} from "../../src/utils/planes.ts"; +export type { Plane } from "../../src/utils/planes.ts"; + // utils/protocols.ts export { allOfferedCompatFields, @@ -544,6 +558,7 @@ export { isGoPlaneUrl, isZenProvider, modelIdOf, + planeForUrl, planeHeadersFor, pluginMarkerOn, projectHeaderOf, @@ -551,6 +566,13 @@ export { toolNamesOf, } from "../../src/utils/request-shape.ts"; +// utils/context-windows.ts +export { + MEASURED_CONTEXT_WINDOWS, + measuredWindowFor, +} from "../../src/utils/context-windows.ts"; +export type { MeasuredWindows } from "../../src/utils/context-windows.ts"; + // utils/credential-policy.ts export { countsAsRefusal, @@ -571,6 +593,10 @@ export type { MeterSource, } from "../../src/utils/credential-policy.ts"; +// utils/usd.ts +export { formatUsd } from "../../src/utils/usd.ts"; +export type { UsdStyle } from "../../src/utils/usd.ts"; + // utils/retry.ts export { backoffOver, retryUntilAnswered } from "../../src/utils/retry.ts"; export type { RetryOptions, RetryTimer } from "../../src/utils/retry.ts"; diff --git a/test/usage-service-readings.test.ts b/test/usage-service-readings.test.ts index d8a298d..aea297a 100644 --- a/test/usage-service-readings.test.ts +++ b/test/usage-service-readings.test.ts @@ -92,6 +92,19 @@ describe("GoUsageService readings", () => { }); }); + it.each(["opencode-google", "opencode-go", "opencode-go-relay", "my-relay"])( + "refuses with no key and no Zen credit on route %s: only the exact Zen route overflows", + async (provider) => { + // Two readers of "is this route Zen" live in this service: the no-key + // path reads the EXACT route (only `opencode` overflows), while the 401 + // path reads `isZenProvider`, which is name-gated and relay-aware. This + // pins the no-key half, so a swap to the other reader is caught. + const failure = await failureOf(serviceWithKey("").read({ provider })); + expect(failure.message).toBe("OpenCode Go API key is not configured"); + expect(failure.details).toMatchObject({ configured: false }); + } + ); + it("attaches the spend of the conversation that asked for it", async () => { // Spend is per conversation: two open sessions must not read the same total. recordTurnUsage( diff --git a/test/usd-callers.test.tsx b/test/usd-callers.test.tsx new file mode 100644 index 0000000..90c6cc1 --- /dev/null +++ b/test/usd-callers.test.tsx @@ -0,0 +1,126 @@ +/** + * The two dollar contracts, read through their callers (P7's pin). + * + * A metered spend and a published allowance are different kinds of figure, + * and they were formatted by two functions both named `formatUsd`. P7 makes + * them one function with two named styles; this file pins what each caller + * shows, through names that exist before and after, and it is not edited + * while the refactor lands. + * + * - **Metered** (the session accumulator): always two decimals, so the row's + * length does not change with its value; whole dollars keep their cents. + * - **Allowance** (the settings summary and the meter's panel): a whole + * published figure drops the cents, and an unknown one says "—". + * + * @module test/usd-callers.test + */ +import { afterEach, describe, expect, it } from "vitest"; + +import { + clearSessionUsageStore, + getSessionUsage, + type GoUsage, + recordTurnUsage, + UsagePanel, + type UsagePanelProps, + UsageSummaryView, +} from "./support/src.ts"; +import { collectText } from "./test-helpers.ts"; + +afterEach(() => { + clearSessionUsageStore(); +}); + +const t = (key: string): string => `t:${key}`; + +const usage = (overrides: Partial = {}): GoUsage => ({ + monthly: { percent: 14, resetsAt: "2026-11-07T00:55:00Z", status: "ok" }, + rolling: { percent: 0, resetsAt: "2026-10-09T06:00:00Z", status: "ok" }, + source: "opencode-go", + weekly: { percent: 28, resetsAt: "2026-10-12T00:00:00Z", status: "ok" }, + zenOverflow: false, + ...overrides, +}); + +/** Every string the tree renders, in order, joined with spaces. */ +const textOf = (tree: unknown): string => collectText(tree).join(" "); + +describe("dollars · a metered spend always shows two decimals (pin, through the session accumulator)", () => { + it("formats a session's metered spend to the cent, from the record's return and the reader", () => { + // input tokens at $1 per million: the spend is tokens / 1e6 dollars. Both + // reads are the SESSION's snapshot: the per-turn record's own string is + // written into a history nothing reads, so it is not observable here. + const cases: readonly (readonly [number, string])[] = [ + [0, "$0.00"], + [6_000, "$0.01"], + [420_000, "$0.42"], + [12_345_600, "$12.35"], + // Whole dollars keep the cents here, unlike an allowance. + [60_000_000, "$60.00"], + ]; + for (const [inputTokens, expected] of cases) { + const sessionId = `usd-callers-${String(inputTokens)}`; + const snapshot = recordTurnUsage( + sessionId, + { inputTokens }, + { input: 1, output: 0 } + ); + expect(snapshot.costFormatted, `${String(inputTokens)} tokens`).toBe( + expected + ); + expect(getSessionUsage(sessionId)?.costFormatted).toBe(expected); + } + }); +}); + +describe("dollars · a published allowance drops the cents of a whole figure and says — for an unknown one (pin, through both views)", () => { + const summary = (allowance: GoUsage["allowance"]): string => + textOf(UsageSummaryView({ locale: "zh", t, usage: usage({ allowance }) })); + + it("the settings summary", () => { + const priced = summary({ go: 60, goPlus: 7.5, model: "probe-model" }); + expect(priced).toContain("$60 ·"); + expect(priced).toContain("$7.50"); + expect(priced).not.toContain("$60.00"); + + const unknown = summary({ + go: Number.NaN, + goPlus: null as never, + model: "probe-model", + }); + expect(unknown.split("—")).toHaveLength(3); + expect(unknown).not.toContain("$"); + + expect(summary({ go: 0, goPlus: 1, model: "probe-model" })).toContain( + "$0 ·" + ); + const negative = summary({ go: -1, goPlus: 1, model: "probe-model" }); + expect(negative).toContain("—"); + expect(negative).not.toContain("$-1"); + }); + + it("the meter's panel", () => { + const props: UsagePanelProps = { + badgeText: "Go Plan", + failure: null, + isLimited: false, + isZen: false, + locale: undefined, + onMouseEnter: () => {}, + onMouseLeave: () => {}, + refreshing: false, + retry: () => {}, + t, + title: "t:goPlanTitle", + updatedAt: 1_700_000_000_000, + usage: usage({ + allowance: { go: 100, goPlus: 200, model: "probe-model" }, + }), + zenCardCredit: "t:zenPaygBadge", + }; + const text = collectText(UsagePanel(props)); + expect(text).toContain("$100"); + expect(text).toContain("$200"); + expect(text).not.toContain("$100.00"); + }); +}); diff --git a/test/usd.test.ts b/test/usd.test.ts new file mode 100644 index 0000000..d8b51d5 --- /dev/null +++ b/test/usd.test.ts @@ -0,0 +1,50 @@ +/** + * `formatUsd` (`src/utils/usd.ts`): the two dollar contracts, each a named + * style. `test/usd-callers.test.tsx` pins what each caller shows; this file + * holds the function's own table, moved here from the two modules that each + * used to define one. + * + * @module test/usd.test + */ +import { describe, expect, it } from "vitest"; + +import { formatUsd } from "./support/src.ts"; + +describe("formatUsd · allowance", () => { + it("writes whole dollars without cents", () => { + expect(formatUsd(0, "allowance")).toBe("$0"); + expect(formatUsd(60, "allowance")).toBe("$60"); + expect(formatUsd(7.5, "allowance")).toBe("$7.50"); + }); + + it("does not price missing or invalid allowances as zero", () => { + for (const value of [null, undefined, Number.NaN, Infinity, -1, "60"]) { + expect(formatUsd(value, "allowance")).toBe("—"); + } + }); +}); + +describe("formatUsd · metered", () => { + it("always reads two decimals, whatever the magnitude", () => { + // The tiered formatter (3dp below a cent, 4dp below a tenth) printed + // $0.006 on the trigger — precision in the wrong place. A meter is a + // gauge, not an invoice, and a number whose LENGTH changes with its value + // makes the row shift on every turn. + expect(formatUsd(0, "metered")).toBe("$0.00"); + expect(formatUsd(0.00012, "metered")).toBe("$0.00"); + expect(formatUsd(0.0042, "metered")).toBe("$0.00"); + expect(formatUsd(0.006, "metered")).toBe("$0.01"); + expect(formatUsd(0.42, "metered")).toBe("$0.42"); + expect(formatUsd(12.3456, "metered")).toBe("$12.35"); + }); + + it("keeps the cents of a whole dollar, and says — for a value that is not a number", () => { + expect(formatUsd(60, "metered")).toBe("$60.00"); + // A number is formatted as it is, as the metered formatter always did: + // unifying an invalid number with the allowance's "—" would be a fix. + expect(formatUsd(-1, "metered")).toBe("$-1.00"); + for (const value of [null, undefined, "60"]) { + expect(formatUsd(value, "metered")).toBe("—"); + } + }); +}); diff --git a/vite.config.ts b/vite.config.ts index b04804e..4a57c89 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -314,6 +314,34 @@ export default defineConfig({ functions: 100, lines: 100, }, + // The one route-to-plane table (P7): every branch is a route shape. + "src/utils/planes.ts": { + statements: 100, + branches: 100, + functions: 100, + lines: 100, + }, + // The one dollar formatter (P7): every branch is a style or a value. + "src/utils/usd.ts": { + statements: 100, + branches: 100, + functions: 100, + lines: 100, + }, + // The client-generation table (P7, L6): one row per generation. + "src/utils/client-generation.ts": { + statements: 100, + branches: 100, + functions: 100, + lines: 100, + }, + // The measured context-window table (P7, L11) and its reader. + "src/utils/context-windows.ts": { + statements: 100, + branches: 100, + functions: 100, + lines: 100, + }, // The plane routes' host half, measured rather than aspirational: what // is left uncovered are guards for host shapes no composition offers. "src/host/route-claim.ts": {