diff --git a/AGENTS.md b/AGENTS.md index f0a79292..9113b05f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,7 +57,7 @@ Host bundle (`lib/index.mjs`), a thin `apply` barrel over small modules: - `scripts/propose-host-bump.ts` · `scripts/host-bump.ts` — the nightly bump proposal (the same job, schedule only): plans each channel from the report's own reading (`bumpPlan`: `current`; `blocked` on any unread answer; `waiting` while the new `dsh` or pi is inside pnpm's one-day release-age window, which it never lifts; `range` for a cut that opens a prerelease tuple the peer ranges do not admit, moves the bridge's pi range or sits under a dist-tag the record type does not admit; else `data`; a dist-tag moves only with `dsh`, so a plan is `current` exactly when the report has no line for it) and, with `--write`, moves CONTRIBUTING's release-step-3 data and nothing else — the record (`withRecord`), alpha's pins (`channelManifest`), the README pair's "today" sentences (`withReadmePolicy`, a value both channels share left for review unless both records move it to the same value), the root lockfile and the rc relock — for CI to push as `chore/host-bump`, dispatching the floor cells (with the keyed e2e tier off) when `piFloor` or a family field moved. Both lockfiles hold one pi, so a proposed pi move carries every record (`coupleSharedPi`: a channel waiting only on its own young cut takes a pi-only move when its recorded pi range admits it; one that cannot, a dsh-only proposal included, holds the pi move as `blocked`). It never edits a measured table, and runs no test: the proposed pull request's CI is the run. CI writes the plan in a step with no token in its environment (which holds because nothing approves a dependency build script, so the install runs none of the cut's code; `test/host-drift.test.ts` names an approval in every source the pinned pnpm reads, which are `pnpm-workspace.yaml`, a `PNPM_CONFIG_*` variable and a CLI flag in the step, the proposer or the rc relock, and a pnpmfile at the root or named by any of them, and in the older spellings pnpm 12 ignores), and a second step pushes it; **an open proposal is the reviewer's**: one with the same target (the marker line its body ends with, `bumpTarget`: every proposed record in full, never the title) is left alone, and a newer target rebuilds the branch only while every commit on it is the nightly's own, as author and as committer (only this repository's own branch is the proposal). `host-bump.ts` is pure (`test/host-bump.test.ts`), the text half of `--write` included (`applyBumpTexts`: every edit, each README plan checked against the other channel's record now and as proposed; the CLI only writes what it returns and runs the installs); the CLI runs against a loopback registry in `test/mock/host-drift-cli.mock.ts` (its `--out` files, the pi coupling, and on a scratch copy through `--root` a successful `--write`'s `files` list and a failed one's put-back); the two CI steps are executed with stub tools in `test/host-drift.test.ts`. - `scripts/use-channel.ts` — switches the dev install: `rc` or `alpha` installs that channel's committed lockfile (unpatched pi at the newest version the bridge's range admits, what an npm user runs), and `--floor` the same cluster with pi at the range's floor, never committed. It restores every tracked file it touched, so a switch leaves no diff. Its pure half is `scripts/channel-manifest.ts` (`channelManifest`, `pinFor`, `workspaceWithPi`, and `withoutHostPackages`, the lockfile `rc --relock` starts from), held by `test/use-channel.test.ts`. A relock keeps the cordis family at the record's floors because `package.json` pins every member the install resolves (include, group and cosmokit too, which arrive transitively and would otherwise resolve to the newest patch inside their `~` ranges) and `pinFor` moves each with the channel. `rc --relock` belongs in the same commit as ANY change to `package.json`'s dependencies or `pnpm-workspace.yaml`'s catalog or overrides, not only a channel bump: the rc lockfile carries every specifier the root one does and CI installs it frozen, and `test/harness-channel.test.ts` fails, naming the command, when they disagree. Dependabot ignores the cluster and pi, which move only as a channel bump. **This repository carries no pi patch** (D14''): an npm install runs pi unpatched, the harness's patch reaches users only through the desktop app and touches nothing the plugin reads, and a version-keyed patch would break every pi bump. `test/architecture.test.ts` keeps it that way by failing if `src` ever reads a streamed tool-call delta, partial arguments or a thought signature. - `src/settings-table.ts` — the one field table: a row per setting (its kind, default, choice values, volatile flag and card group), from which `config.ts` derives the schema, the resolver, the config types, the defaults and the config-only list (`CONFIG_ONLY_FIELDS`), `settings-fields.ts` derives the card's field specs, `settings-copy.ts` checks the copy keys a card row implies, and `test/manifest.test.ts` holds `cordis.patch.yml`'s header to it (order, type labels, defaults, choice values). **Adding a setting is one row there plus its copy when the card shows it**, and a card row without its label, hint, option or group copy fails to compile. The schema descriptions and the config-only reasons are a second export, `SETTING_PROSE`, which only the host-side `config.ts` imports, so the bundler drops it from the page (`test/client-bundle.test.ts` pins that). -- `src/config.ts` · `src/config-values.ts` · `src/utils/guards.ts` — the schema, the resolver and their defaults, read off the table; dependency-free readers and type guards. `config.ts` is host-side: it imports schemastery, so the client imports the table and never the schema (`test/architecture.test.ts` checks the client graph never reaches it). The client bundle may import the other two, and it does — along with the contract and presentation modules (`usage-contract.ts`, `settings-copy.ts`, `settings-fields.ts`, `settings-table.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/config.ts` · `src/config-values.ts` · `src/utils/guards.ts` — the schema, the resolver and their defaults, read off the table; dependency-free readers and type guards. `config.ts` is host-side: it imports schemastery, so the client imports the table and never the schema (`test/architecture.test.ts` checks the client graph never reaches it). The client bundle may import the other two, and it does — along with the contract and presentation modules (`contracts/*`, `settings-copy.ts`, `settings-fields.ts`, `settings-table.ts`, `usage-ui.ts`, `utils/usd.ts`, `utils/planes.ts` through `utils/request-shape.ts`). The rule is not a list of names: **the client may import a module that reaches nothing host-only** — no cordis context, no credential seam, no node built-in — and `test/architecture.test.ts`'s client-bundle block ("the client bundle reaches nothing host-only") is what enforces it: it walks the entry's import graph, and the unit suite fails the build rather than anyone having to remember. An earlier version of this line named two files as the only ones allowed, which the tree had already outgrown. ## `src/utils/` — pure by construction, enforced by test @@ -106,7 +106,7 @@ It is the same trick `test/architecture.test.ts` already uses for the client bun - `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 (`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/key-capture.ts` · `src/go-discovery.ts` · `src/usage.ts` · `src/contracts/usage.ts` — credential extraction and its tier, quota discovery, the usage service, and the shared shape (with `USAGE_NAMESPACE`, and `parseUsageReading`, the client's reading parser: the vendor whitelist `parseGoUsage` plus the fields the Host attaches, the allowance, `quotaUnavailable` and the plane spend). - `src/utils/credential-policy.ts` · `src/credentials.ts` — the credential rules every decider shares (P6), and their effects. The pure half holds the one placeholder filter (`usableKey`), the fill's and the meter's orders per policy, the capture gate (OC3: only a request of a turn the plugin decorated, never a foreign turn or a marked request) and L8's strike count (a captured key is dropped after a second well-formed 401 in a row on its plane, counted only on requests of decorated turns: the meter's own `/usage` poll and any other turnless request neither strike a key nor lift a drop). The effect half is the capture store, one per ROOT (`captureStoreFor(ctx)`, so a test's fresh `Context` is a fresh store and nothing process-wide needs clearing), the fetch patch's one resolver for an empty or placeholder wire key (`createCredentials`: observe, fill, settle, and the one read of the process environment the fill makes), and the installation's store read. The plane adapter never asks it: its key is pi-ai's rule (D20). `test/credential-parity.test.ts` pins all four deciders side by side and was written before the move. - `src/catalog-data.ts` · `src/models-catalog.ts` · `src/models-discovery.ts` — the generated static shim, the OpenCode-catalog parser with SWR refresh (with the one spec lookup, `specOn`/`specFor`, a plane's row then the plane-blind one, and `liveCatalogOn`), and the Settings discovery wrapper (behind `enrichModels`; off, Fetch is pi's list and `NO_DISCOVERY` passes through): on a plane the plugin serves, Settings → Models → Fetch answers pi's list plus the catalog's servable, non-deprecated models pi lacks (D3, P3), and the catalog alone while pi-ai restarts. `catalog-data.ts` is **generated**; never hand-edit it. - A note on the sweep that found the two entries around here, because it nearly produced a false one: grepping for a symbol's callers while EXCLUDING the file that defines it makes every same-file call look like no call at all. `resolveGoKeyForRef` reads as unreferenced that way and is not — `resolveGoApiKey` calls it, and the usage service calls that. (An earlier version of this line said that is "how the Go endpoint keeps Zen keys away from itself"; there is no such exclusion, and the note below records why.) Check the defining file too before believing an export is dead. @@ -119,8 +119,9 @@ It is the same trick `test/architecture.test.ts` already uses for the client bun - `scripts/session-band.ts` — `verify-session-band.ts`'s pure half: the vendor's id construction, ported, the four band facts with the answer each must have (`bandMismatches`), and the verdict the script prints (`bandVerdict`): "CONFIRMED" only when there is no mismatch, otherwise one `MISMATCH:` line each and exit 1. The unit run makes the verdict fail on a planted derivation, spawns the script in its passing state, and spawns a scratch copy of it beside a `src/session.ts` whose derivation leaves the band, which prints the `MISMATCH:` line and exits 1. - `scripts/freshness-scope.ts` — which of CI's three freshness checks (`catalog:shim`, `limits:shim`, `cli:version`) a pull request is GATED on: the ones whose inputs (the check's script and the local modules it loads, walked from the source as Node loads it — types erased by Node's own stripper, specifiers read by `es-module-lexer` — plus `src/identity.ts` for the CLI version; never the generated files) its own diff touches. The rest only warn, because vendor drift is not the pull request's regression: for the two generated tables the nightly run regenerates them and proposes the refresh, and for the CLI version it warns and the bump is a human pull request, which then gates. The gates fail closed: each runs unless the scope step answered `report`. The CLI version's offline half — every copy in the tree agrees with the pin, `cli:version -- --copies` — gates every pull request, since it skips the generated tables and only the repository can break it. `test/freshness-scope.test.ts` walks the real generators, runs the scope step's own shell and the CLI it calls, and evaluates the workflow's step conditions. - `src/host/route-claim.ts` · `src/host/plane-provider.ts` · `src/host/describe-graft.ts` · `src/host/host-modules.ts` — the plugin owns the plane routes (D13). The route claim appends ONE `internal/config` listener that reads either cordis core's call shape (`src/utils/config-run.ts`: `function (this: Fiber, raw, next)` on the OLD core, `(fiber, next)` with `this` null on the NEW one), calls `next()` exactly once, re-appends itself whenever pi-ai reaches `internal/status` ACTIVE so it stays inner to pi-ai's own checking listener (the new registration first, the old one released only once the host accepted it, so a refusal while the plugin's fiber is going away throws nothing into pi-ai's emit), and hands `llm-pi-ai`'s fiber a copy of what `next()` answered without the `opencode`/`opencode-go` entries it TAKES — an entry another plugin owns (D27: pi-ai's row resolving `credentials` in a realm the plugin's context does not, compared by the key each context reads off cordis's realm map so a group's `isolate` counts, or an entry carrying the `x-opencode-plugin` header, `src/utils/plane-ownership.ts`) stays pi-ai's, is logged once, and is never counted by a restart, a handback or the reconcile; a commit run releases at once a plane the plugin registered that its candidate no longer lets it take, so pi-ai's registration of it meets no duplicate; and the claim's read-only `steppedAside()` accessor makes the stream hook run such a turn undecorated under a `foreign` turn state (`turn-store.ts`), which the fetch patch passes through before its URL claim, as it does any marked request, and keeps the 1.x discovery wrapper off its Fetch; a commit run (the fiber's raw config, the loader's stored row config, or any run while the fiber is not ACTIVE) never throws, and every fiber config is read through the feature-detected accessors, validates a Settings edit to a plane with pi-ai's own checks, and registers the plane adapter for exactly the declared planes through `registerAdapter`/`handle.replace`; on dispose it hands the planes back by restarting pi-ai (never on a reload). `plane-provider.ts` is `PlaneAdapter`, a subclass of the host's `PiAiAdapter` over pi's own `createProvider` and four protocol implementations, with the credential seams that mirror pi-ai's (D20), and pi-ai's `prepareHeaders` option, as pi-ai's own adapter has it (`planeRequestHeaders`): per call, the plane headers of the turn the stream hook decorated (OC5, written by `lifecycle.ts` from `planeHeadersFor`), then the host's `llm-pi-ai/request-headers` waterfall, so another plugin's contributor runs on the planes the plugin serves (OC4), detected by behaviour; its `prepareCall` stream and `stream` finish the gateway's typed refusals as `FREE_TIER` or `MODEL_UNAVAILABLE` with the gateway's words, and its status except on Google-protocol models, whose failure text carries none (`src/utils/gateway-refusal.ts`), because the conversation replaces an AUTH failure's message with "API key is invalid". Its stand-in (`test/support/route-claim-stand-in.ts`, driving `test/route-claim*.test.ts`; the new core's call-shape cases are in `test/route-claim-listener.test.ts`) builds fibers of both cores — `piFiber` (the OLD core's `_config` and resolved `config`, driven through `oldRun`) and `newPiFiber` (the NEW core's raw `config`, `rawConfig` and `effectiveConfig`, no `_config`, driven through the stand-in's `waterfall`, whose per-listener `next` throws on a second call, and its `internal/status` emit) — and `test/host-planes.test.ts` runs the claim on the installed host, whichever core it is. `describe-graft.ts` is the one read-only `settings.describe` wrapper that keeps Settings showing the planes (D18). `host-modules.ts` is where the host's own modules are found — pi-ai's on its loader entry, pi, dsh-llm and the loader from the wrapper's own tree — behind the replaceable seam in `src/cordis-context.ts` (`replaceHostModuleSource`), which is how tier A runs the claim. What a protocol sends, Google's thinking control included, is the host's pi's own (D26): where a host's pi lacks something the gateway needs, the suite records a `[HOST_LIMITATION]` row and skips the cases that would exercise it by pi's own exported predicate, never a version compare. -- `src/host/remote.ts` — `installRemoteService`, the one installer for the usage, purge and store-inspection services. One service per root, alive while a live activation holds it, reading the latest live activation's options and disposed with the last; checked against the client contract's namespace after the mount settles and reported through the activation's logger; no `ctx.provide` fallback, because a provided value is invisible to the Gateway's discovery. -- `src/purge-service.ts` · `src/purge-contract.ts` — the card's "purge deprecated models" action, and the shape it answers with. It **rewrites the profile**, deleting the declared model entries the live catalog has retired, through `configEditor` (the same service the settings UI writes with). That is deliberate: a read-time filter would leave the declaration in place, and then the only way to explain a missing row is to find the filter. One source of truth, and it is the configuration. It never rewrites a plane entry another plugin owns (D27: the `x-opencode-plugin` marker, or a row whose credentials resolve in a realm the service's context does not), nor a reference to a route only such entries declare. +- `src/contracts/remote.ts` · `src/contracts/all.ts` · `src/settings-remote.ts` — one remote seam (P9). `defineRemote(namespace, methods)` builds a contract from each method's parameters and result parser and DERIVES the descriptors the client mounts; `REMOTE_CONTRACTS` is the one list the client's `patchRemote` is built from. A new remote is one `defineRemote`, one entry in `all.ts`, one `markRemote` on its service and one `installRemoteService` in `lifecycle.ts`. On the client, `callRemote` finds the call (through `ctx.get` first, see `remoteNamespaceOf`), calls it with no argument unless one is given (the gateway checks arity), and `unwrapRemote` is the one unwrap of the `{ ok, value | error }` envelope, parsing the payload with the contract's own result parser. The two usage callers (the settings summary and the meter) do not use `callRemote`: they go `findRemoteCall`, then `callUsageRead` (the arity retry that tolerates the sibling `dsh-opencode-go`'s zero-parameter registration of the same `read`), then `unwrapRemote`; and the meter passes an `invalid` payload through to the pill unchanged until P11. Client-safe, so the bundle loads them. +- `src/host/remote.ts` — `markRemote`, which writes a service's Remote marker from its contract (the decorator is rejected by the build transform; the type makes a contract method the class lacks a compile error), and `installRemoteService`, the one installer for the usage, purge and store-inspection services. One service per root, alive while a live activation holds it, reading the latest live activation's options and disposed with the last; checked against the client contract's namespace after the mount settles and reported through the activation's logger; no `ctx.provide` fallback, because a provided value is invisible to the Gateway's discovery. +- `src/purge-service.ts` · `src/contracts/purge.ts` — the card's "purge deprecated models" action, and the shape it answers with. It **rewrites the profile**, deleting the declared model entries the live catalog has retired, through `configEditor` (the same service the settings UI writes with). That is deliberate: a read-time filter would leave the declaration in place, and then the only way to explain a missing row is to find the filter. One source of truth, and it is the configuration. It never rewrites a plane entry another plugin owns (D27: the `x-opencode-plugin` marker, or a row whose credentials resolve in a realm the service's context does not), nor a reference to a route only such entries declare. - `src/session-cost.ts` · `src/cordis-context.ts` · `src/debug.ts` — per-turn accounting, the typed host interfaces, and stream debug logging. - `src/host/global-fetch.ts` — `installGlobalFetch`, the plugin's one write to `globalThis.fetch` (P6). It reads the fetch it wraps inside the effect, keeps a chain of its links, turns a link disposed under another into a pass-through, and on a restore unwinds through disposed links, so apply A, apply B, dispose A, dispose B ends at the fetch that was there, in either order, and a function the plugin did not install is never replaced. It is the one named exemption of the host-write tripwire below, which stays while the patch keeps relays, listing enrichment, the credential fill, the body fallback and the User-Agent. - `src/host/patch-method.ts` — `patchMethod`, the one way to wrap a method on a host object. A dispose restores only while its wrapper is still the current value (otherwise it becomes a pass-through under whatever wrapped on top), and deletes the own property when the original was inherited rather than assigning it back; a second install of the same site wraps the unpatched method instead of the first install. Identity is read from own descriptors, never from a property read, because cordis's traceable proxy answers a fresh proxy for every method read (`docs/engineering-notes.md`). `rewrapOnAdaptersUpdated` reinstalls a site on `llm/adapters-updated`, for a site that must follow the registry; none uses it yet. Every instance patch in `src/` goes through this module — today two sites: model discovery (`models-discovery.ts`) and the `settings.describe` graft (`host/describe-graft.ts`) — and `test/reload.test.ts` runs apply A, apply B, dispose A, dispose B on each. Two tripwires hold the rule. `test/architecture.test.ts` is textual: anywhere `apply()` reaches but the helper, it fails on a `Reflect.set`/`defineProperty`/`deleteProperty`/`setPrototypeOf`, an `Object.assign`/`defineProperty`/`defineProperties`/`setPrototypeOf` onto `llm`, an adapter, `settings` or `globalThis` (bare or through a property path such as `registration?.adapter`; a prototype swap shadows a method without leaving an own property), a dotted or bracketed assignment (through `?.` or `!` too) onto the first three, and `globalThis.x =` (the global `fetch` installer, `host/global-fetch.ts`, is the one named exemption); a write through a local alias or a cast receiver escapes it. The `apply()`-twice reload case is behavioural: it requires the helper's record on every own function `apply()` leaves on the stand-in's `llm` and `settings`. @@ -131,12 +132,12 @@ It is the same trick `test/architecture.test.ts` already uses for the client bun - `src/opencode-paths.ts` — where an OpenCode installation keeps its files, ported from `~/dev/opencode`'s `global-roots.ts` (the directory) and `database-path.ts` (the filename). It takes `home`, `env` and `channel` as parameters and reads neither the environment nor the filesystem, which is what makes the Windows and Linux layouts testable from here. Two facts it encodes that are easy to get wrong: the directory is XDG on EVERY platform — macOS and Windows use `~/.local/share` too, and `os.homedir()` is the only platform-dependent call — and the FILENAME is not constant, being `$OPENCODE_DB`, else `opencode.db` on a stable channel, else `opencode-.db`. The database sits under `data` while the config sits under `config`, so one root cannot serve both. It is the foundation of the opt-in reader: `credentials.ts`'s `resolveOpencodeStoreKey` imports it, and so does `opencode-store-service.ts` (the inspection's path); nothing else does. - `src/opencode-store.ts` — reading the credentials an OpenCode installation already holds, through `node:sqlite`. Two rules shape it: nothing throws (a missing file, a foreign schema and `:memory:` all answer `undefined`), and a value never leaves the return value — no log line, no error message, no client bundle. `node:sqlite` is host-only, which is what keeps the module on the host side of the bundle rule. It is reached only through `resolveOpencodeStoreKey`, which is the last step of every key-source policy and is off unless `readOpencodeStore` is on. Its second reader, `inspectOpencodeStore`, answers the _other_ question — "is there a credential here, and whose is it?" — with a sanitized summary (email, org, kind, expiry) and never the token, which is what lets the settings card show the evidence beside the permission. - **What the plugin page shows is `docs/detail.md`, not the README.** The page renders one document: the Markdown `meta.detail` in `locale/.json` names, else the whole `README.md`. This package declared nothing for years, so its page carried 461 lines of engineering notes above the settings card. It now declares a page per language that is **one image and nothing else** — a UI preview of the card and the meter (`docs/media/preview.svg`, `.zh.svg`) — which is the shape the upstream plugins use, because the header above the card already carries the title and the one-sentence description. The image is served from the package, so `files` has to ship it (the detail-image route reads package-relative paths). `test/plugin-detail.test.ts` holds the contract: a declared detail in every locale, a path that exists AND is shipped, an image that does the same, and a page that is the picture and nothing else. -- `src/opencode-store-contract.ts` · `src/opencode-store-service.ts` — the inspection seam: the sanitized summary type both sides share, and the host service that produces it. The contract is pure data (no `node:`, no context), so the client bundle may import it; the service is the half that touches `node:sqlite` and the filesystem, and it rewrites the store path to `~`-relative before answering — a home directory is a fact about the machine, not about the plugin. `inspect` is declared through the `Object.defineProperty` marker rather than `@Remote`, for the reason `usage.ts` documents. +- `src/contracts/store.ts` · `src/opencode-store-service.ts` — the inspection seam: the sanitized summary type both sides share, and the host service that produces it. The contract is pure data (no `node:`, no context), so the client bundle may import it; the service is the half that touches `node:sqlite` and the filesystem, and it rewrites the store path to `~`-relative before answering — a home directory is a fact about the machine, not about the plugin. `inspect` is declared through `markRemote` rather than `@Remote`, for the reason `src/host/remote.ts` documents. - **The login stack is not in this tree.** It lives on the `v2` bookmark, and the map used to describe it here for years after it left — nine modules a reader could not find. What this tree carries is the API-key path only; a login grant is the other half, and reviving it is a days-scale port rather than a rebase (`v2` is 163 commits behind, and its `src/index.ts` exports a module the tree no longer has). `credentialOrg` is the one remnant with behaviour: a configured org is sent as `x-opencode-org-id`. -- A timing dependency every remote shares, worth knowing before debugging a row that will not appear: the mount is an async `$mount` started in an effect, and the card reads `ctx.remote.` SYNCHRONOUSLY when its injector builds the props. If the injector runs before the mount resolves, the service is not there yet and the surface renders nothing. More often the cause is a namespace with no client descriptor at all — the purge row and the store-inspection row each shipped that way — which `test/remote-contract.test.ts` now catches per method. Each caller reports an empty lookup (`no opencodeStore service on the remote`, `no opencodeGoUsage service on the remote`, with the keys the remote does expose), so the symptom is a console line rather than a blank. And since P5 the host services go with the plugin's last activation: a reload unloads before it applies again, which leaves a short window in which a call finds no active Remote method (the meter's poll retries; a purge click there reports the host's refusal), and disabling the plugin withdraws all three, including the `opencodeGoUsage` instance the sibling `dsh-opencode-go` account page reads. +- A timing dependency every remote shares, worth knowing before debugging a row that will not appear: the mount is an async `$mount` started in an effect, and the card reads `ctx.remote.` SYNCHRONOUSLY when its injector builds the props. If the injector runs before the mount resolves, the service is not there yet and the surface renders nothing. More often the cause is a namespace with no client descriptor at all — the purge row and the store-inspection row each shipped that way — which `test/remote-contract.test.ts` now catches per method: it reads `REMOTE_CONTRACTS`, the client's descriptors and the services the plugin mounts on a real cordis `Context`. Each caller reports an empty lookup (`no opencodeStore service on the remote`, `no opencodeGoUsage service on the remote`, with the keys the remote does expose), so the symptom is a console line rather than a blank. And since P5 the host services go with the plugin's last activation: a reload unloads before it applies again, which leaves a short window in which a call finds no active Remote method (the meter's poll retries; a purge click there reports the host's refusal), and disabling the plugin withdraws all three, including the `opencodeGoUsage` instance the sibling `dsh-opencode-go` account page reads. -Web client bundle (`lib/client.js`): `src/settings-page.tsx` (entry, wiring only), the `settings-*` card and its controls — including the store-inspection row, `src/settings-store-inspect.tsx` — and the meter — `src/usage-pill.tsx` (state), `src/usage-panel.tsx` (pure views), `src/usage-ui.ts` (logic and stylesheet). `test/architecture.test.ts` walks this graph from the entry and fails on a node built-in, the cordis runtime, pi, or `process.env`. +Web client bundle (`lib/client.js`): `src/settings-page.tsx` (entry, wiring only), the remote contracts (`src/contracts/*`), the `settings-*` card and its controls — including the store-inspection row, `src/settings-store-inspect.tsx` — and the meter — `src/usage-pill.tsx` (state), `src/usage-panel.tsx` (pure views), `src/usage-ui.ts` (logic and stylesheet). `test/architecture.test.ts` walks this graph from the entry and fails on a node built-in, the cordis runtime, pi, or `process.env`. ## Commands diff --git a/docs/improvement-plan.md b/docs/improvement-plan.md index 1b028a1c..43f50922 100644 --- a/docs/improvement-plan.md +++ b/docs/improvement-plan.md @@ -38,7 +38,7 @@ Phases land as **stacked pull requests**. The open ones are rebased, each onto i | 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 | in review | **on P6**; one route-to-plane table (`src/utils/planes.ts`: `PLANE_OF_ROUTE`, the exact `planeOfPlaneRoute` and the relay-inclusive `planeForRoute`) with `planeForUrl` beside `isGoPlaneUrl`, one `formatUsd` with two named styles (`src/utils/usd.ts`), one spec lookup (`specOn`/`specFor` in `src/models-catalog.ts`) and `liveCatalogOn`, the last capitalised level name read from `effortName`; L6's client-generation table (`src/utils/client-generation.ts`, 1.x emulated, 2.x recorded and unread) and L11's measured-window table (`src/utils/context-windows.ts`, shipped empty); the Mistral rationale reworded to the plugin's own rule. No behaviour change: the caller pins (`test/plane-table.test.ts`, `test/usd-callers.test.tsx`, the level-name and User-Agent cases, a per-plane purge case, the credential variable's exact-route edges and the meter's no-key refusal per route) were green on the base and land unchanged | | P8 | | `fix:` the card says when its settings apply, over one settings table | in review | **on P7**; one field table (`src/settings-table.ts`: `SETTINGS`, a row per key, and `SETTING_PROSE`, its host-only prose) from which `config.ts` derives the schema, resolver, types, defaults and config-only list, `settings-fields.ts` the card specs, and `settings-copy.ts` checks the copy keys; `cordis.patch.yml`'s header held to it by order, type label, stated default and choice values; fifteen dead copy keys and the meter's `modelMarkers` prop deleted, the zh README's stale name for the card replaced by the package's `meta.title`, and the card says its settings apply on re-apply (performed on the real host in both channels: a volatile edit of the plugin's row commits in place and the plugin follows it only once re-applied). No setting changed: the schema, resolver and card pins (`test/settings-snapshot.test.ts`) were green on the base and land unchanged but for the named edits (the copy keys, `CONFIG_DEFAULTS`' `credentialOrg: undefined`, the resolved type's modifiers). Retitled from `refactor:` (P-H's, P5's and P6's precedent): under squash the pull request's title is the release signal and a `refactor` is hidden from the changelog, while the phase ships a visible card line and the README pair's re-apply sentence. No `!` and no BREAKING CHANGE footer (1.x minors only); the owner may keep `refactor:` at landing, and the card line then ships without a changelog entry | -| P9 | | `refactor:` remote seam | planned | | +| P9 | | `refactor:` remote seam | in review | **on P8**; one builder (`defineRemote`, `src/contracts/remote.ts`) derives every descriptor and codec of the three contracts, which move into `src/contracts/` with `REMOTE_CONTRACTS` the one list the client mounts; `markRemote` writes each service's marker from its contract; `callRemote`/`unwrapRemote` are the one unwrap of the four client callers; `isGoUsage` deleted, `USAGE_NAMESPACE` and `parseUsageReading` added; `remote-contract` reads the contracts and the mounted services | | P10a | | `refactor:` pure module moves | planned | | | P10b | | `fix:` catalog state | planned | | | P11 | | `refactor:` UI on the primitives | planned | | @@ -491,6 +491,11 @@ What stays private is pinned by contract tests against the real host packages: - **The dead copy keys were fifteen**, counted by scanning the code of every `src` file, comment lines blanked, for each of `en`'s 119 keys (the scan is now a case of `settings-copy`, which reports each of the fifteen as unread): `storeInspectFound`, the eleven `login*` keys the removed sign-in used (`loginAction`, `loginAgain`, `loginExpired`, `loginFailed`, `loginSignedIn`, `loginSignedOut`, `loginPlane`, `loginPlaneGo`, `loginPlaneZen`, `loginTitle`, `loginWaiting`), `zenFallbackNotice`, `zenOverflowActive` and `title`. The first count, fourteen, read comments as code and missed `title`, which only a comment in `src/usage-ui.ts` quoted: nothing has read it since the card moved to `plugins.bundle.config`, whose heading the host takes from the package's `meta.title`. Also gone: the meter's `modelMarkers` prop (read by nothing; the meter's gate is the provider list) and a stale `usageModelMarkers` fixture key. The zh dictionary's `title` said "OpenCode 补丁设置" while `meta.title` says "OpenCode 补丁", so the card on screen already said "OpenCode 补丁"; `README.zh-CN.md`, which named it the old way, now names it as `meta.title` does. - **The choice fields stay `z.string()`.** `z.union([z.const(…)]).default("auto").loose().volatile()` composes, measured on both channels' schemastery (3.18.6-alpha.2 on alpha, 3.19.0 on rc), in either call order: a valid value is kept, and a typo, a number, `null` and an absent value all answer the default. It is not adopted here, because it would change the snapshot this phase holds (the node's `type`, a `loose` flag in its `meta`, the schema JSON `settings.describe` serves) and turn a non-string value from a load failure into the default. The table carries the values, so the switch is one line in the schema's builder when it is wanted. 17. **P9 `refactor:` remote seam.** `defineRemote`, `markRemote` and `callRemote`, with the parity test reading the contracts. + - **As landed.** `src/contracts/remote.ts` holds `remoteValue(type, parse)` (one codec, the same parser behind `schema.parse` and `create().parse`) and `defineRemote(namespace, methods)`, which derives each descriptor key for key as the hand-written literals had it (the id under `dsh-opencode-patch`, `invocation: { kind: "direct" }`, `service` equal to the namespace, one wire name per parameter, `acceptsUndefined` only on an optional one, and no key at all on a required one). The three contract modules moved, as plain moves with no shim, to `src/contracts/{usage,purge,store}.ts`, and `src/contracts/all.ts` exports `REMOTE_CONTRACTS`, from which `patchRemote` is built. `markRemote(Service, contract)` in `src/host/remote.ts` is the one copy of the marker key and writes the method list from the contract; its type makes a contract method the class lacks a compile error. `src/settings-remote.ts` gains `findRemoteCall`, `unwrapRemote` and `callRemote` (a zero-argument call when no argument is given: the client face checks arity), and the four callers (purge, store, the settings summary, the meter) read through them with their outcome types unchanged. `isGoUsage` is deleted and `USAGE_NAMESPACE` added. **`parseGoUsage` could not replace `isGoUsage`:** it is the whitelist for the VENDOR payload and drops `allowance`, `quotaUnavailable` and the session's `planeCostFormatted`/`planeSpendUsd`, which the service attaches after parsing and the panel renders; wired as the client parser it would have removed the allowance row and drawn the overflow floor's three 0% windows. The client's parser is `parseUsageReading`, the vendor whitelist plus those fields, of which every reading the service sends is a fixed point (`test/remote-seam.test.ts` round-trips the real service's answers). + - **Five unifications, each stated by a new case.** D1, D2 and D5 are on shapes the gateway cannot send (its client face answers `RemoteResult`, `{ ok: true, value } | { ok: false, error: RemoteError }`). D3 and D4 are a fixed point for every reading THIS plugin's service sends (`test/remote-seam.test.ts`), but not only for shapes the gateway cannot send: the sibling `dsh-opencode-go` serves the same `opencodeGoUsage` namespace, and a reading it answers (when `usageEnabled` is off here) now reaches the summary and the meter as the whitelisted copy. A `source` over 128 characters is dropped, a session without a string `costFormatted` or a numeric `totalTokens` is dropped whole (a partial one gets zero defaults), and the summary hides a window the old check accepted. No sibling install was available, so that case is unmeasured. (D1) the store inspection shows an envelope-level `message` or a string `error` instead of its default sentence; (D2) the purge no longer reads a refusal nested inside `value`; (D3) the settings summary's reading is the whitelisted copy and its windows are checked as `parseGoUsage` checks them (a finite non-negative percent, a parseable `resetsAt`), an enveloped invalid payload now logs the "not a usage shape" line, a refusal whose `error` is `null` or absent rejects with `Error("usage call failed")` (the base threw the `null`), and the vendor's `{ usage: { rolling, weekly, monthly } }` wrapped form, which `isGoUsage` rejected, now reads as the reading it wraps; (D4) the meter's valid reading is the whitelisted copy, and a bare `{ value }` is unwrapped, valid or not (an invalid payload passes through as the payload, no longer inside its `{ value }`); (D5) the usage result codec's parser is `parseUsageReading`, for both `read` and `readAccount`. D5 is wire-inert: read in both published installs (`@deepseek-ai/dsh-api-gateway` 0.2.2-alpha.3 and 0.2.2-rc.2), the host encodes a result with `codec.encode?.(…) ?? value` and the client decodes with `descriptor.result.decode` when present, neither of which these codecs have, and `codec.create().parse` runs in `validateArguments` only; the client face's `prepareInvocation` still refuses a call whose argument count differs (`client api: … expected N argument(s), got M`). + - **The meter keeps its pass-through.** A reading the reading parser rejects reaches the pill as it came, as before (`test/settings-page.test.tsx` pins it with `{ test: 123 }` and a non-envelope answer); rejecting it changes a pinned answer, so it is a `fix:` carried to P11, with the meter's move onto the primitives. + - **Measured:** `lib/client.js` 146,953 bytes, from 143,074 on the base; `CLIENT_BUDGET` raised 140 -> 146 KB with its history paragraph (source and comments, no dependency: the bundle still requires only react and the UI primitives), which leaves about 2.5 KB of room, close to the ~3 KB the line is meant to keep. + - **The client keeps the lookup order it had.** `findRemoteCall` reads `ctx.get('remote.')` first and reads `scope.remote` only when that misses, inside a guard, so a scope whose `remote` getter throws still finds a namespace `ctx.get` resolves, as the base's `remoteNamespaceOf(…) ?? remoteNamespace(scope.remote, …)` did. When `ctx.get` misses it is not the base's answer: there the base read `scope.remote` unguarded on the right of `??`, so a throwing getter rejected the purge and the store inspection (whose docs say they never throw) and threw out of the meter's injector; now it reads as no remote, so purge and store resolve `unavailable` with their console line and the meter returns its "no usage service" reason (`settings-purge`, `settings-store` and `settings-page`'s meter each pin it with a scope whose `get` misses and whose `remote` getter throws, and each fails with the guard dropped; the meter's case also fails with any unguarded `meterScope.remote` read planted beside the call). The settings summary is unchanged: `readGoUsage` still reads `scope.remote` first and unguarded, and rejects on that input as it did; guarding it would be a further change, carried to P11 with the meter's fix. The input is unreachable on the host, since every caller's scope declares `remote` in `inject`. 18. **P10a `refactor:` pure module moves.** - `models-discovery` → `host/*`; - `go-discovery` → `credentials.ts`; @@ -538,7 +543,7 @@ How each phase changes now that it sits on `main` 1.8.0 and on both harness chan | 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). **As landed:** all of them, with the `piKnows` assertion dropped: no other row uses that pi premise, and a hard assertion on pi's data would gate every channel's run on a fact the plugin no longer reads, while `PROTOCOL_FOR_SDK` in `test/protocols.test.ts` pins the plugin's own rule; L6 and L11 as their rows below say. | | P8 | The health snapshot shows the catalog's `lastError` on the card. From P5's review: every field of the row is `.volatile()`, and a Settings edit takes the loader's volatile-only path (`entry.update` → `_commitVolatile`, no remount), while `resolveConfig` unwraps each node once at apply; so no part of the plugin (the usage options, the fetch patch, the stream hook) follows a Settings edit until the plugin is applied again. P8 decides whether the settings table reads those values per call or says in the card that they apply on re-apply. **As landed:** they apply on re-apply, and the card says so once above its controls (`appliesOnReapply`), as both READMEs do; `host-planes` performs it on the real host in both channels (a volatile edit of the plugin's own row, then a re-apply). Reading per call is not a refactor: `lifecycle.ts` mounts the usage service at apply only when `usageEnabled` is on, copies `keySource` and `readOpencodeStore` into the services it builds, and the route claim reads `endpoint` once. The catalog's `lastError` on the card is carried to P10b: no health snapshot exists, `refreshCatalog` swallows its error, and the carrier would be a remote contract that P9 reshapes over catalog state that P10b rewrites. | -| P9 | A loopback triple guard, only if a `webServer` route appears. | +| P9 | A loopback triple guard, only if a `webServer` route appears. **As landed:** no `webServer` route appeared; nothing built (L14). | | P10a | L1's per-call shaping is the first move of `fetch-patch` into `request/`. L4, carried from P6 (P-R2 measured nothing): with the next keyed variants run, drop `x-opencode-request` or send it only where it is accepted, which is one line in `planeHeadersFor` and one expectation in `test/host-planes-headers.test.ts`. | | P10b | L12's test; optionally emit `llm/models-updated` on refresh, a new host event. The catalog's `lastError` on the card (L14), carried from P8: the refresh keeps its last error with the state it rewrites, and the card shows it beside the purge row. | | P11, P12 | Unchanged. | @@ -789,6 +794,14 @@ The vendor's own first-party DSH plugin, `@opencode/console` 0.1.10 (`anomalyco/ - **New with the change:** `settings-table` (one row per schema key in the schema's order, a choice's default among its values, card rows first with each group adjacent, a reason exactly on the rows the card does not show, a card control only on a boolean or a choice, a `routes` row's default equal to `PLANE_ROUTES`, the floor its reader builds on); `architecture`'s client graph reaches `settings-table.ts`; `settings-copy`'s READMEs name the card by `meta.title` and no zh page keeps the old name, and every `en` key has a reader in `src` (a quoted literal in code, with comment lines, JSX `{/* … */}` spans and `//` tails after code blanked, or a key the card derives from the table; the fifteen deleted keys, a planted orphan, and planted keys only a comment line, a JSX comment or a `//` tail quotes are reported); `host-planes`' re-apply case, tier B on both channels (a volatile edit of the plugin's own row, made through Settings' `mutate` as the card's save makes it, commits one `loader/volatile-update` naming the key on the same fiber, a turn still carries `x-opencode-project`, and after `fiber.restart()` it does not, while every turn carries `x-opencode-client`, so the absence is the row read and not an undecorated turn), which performs the behaviour the card line states; a 100% coverage floor on `src/settings-table.ts`. - **Test edits that are not pins:** `usage-pill`'s two gate cases drop the deleted `modelMarkers` prop and are retitled to the provider list; `settings-page` drops the stale `usageModelMarkers` fixture key; the door re-exports `SETTINGS` and `SETTING_PROSE`, and `CONFIG_ONLY_FIELDS` from `config.ts`. +**P9** + +- **Pin first, green on the base (`d1f7bf4`) with no expectation changed:** `remote-contract`'s field-for-field descriptor table (every key of the four descriptors, codecs read as their type symbols, exact key sets so a present `acceptsUndefined: undefined` fails, the shared usage result codec and each other parser's identity) and the Remote marker each of the three services carries (non-enumerable, read-only, frozen, version 1, its methods in order); `remote-seam` (a real `OpencodeStoreService` over a fixture database and a missing one, a real `GoUsageService` reading with an allowance and the session's plane spend, the 403 overflow floor with `quotaUnavailable`, the unconfigured `RemoteError` and what `parseFailure` makes of it, and a real `ModelPurgeService`'s result, over a config editor whose profile references one retired id as a provider declaration, a subagent and the summariser, and its own refusal with no config editor: each carried to its client caller through the envelope and asserted against the service's own answer); and the callers' envelope shapes: `settings-usage` (a `Required` reading enveloped and bare, each empty lookup's console line with the keys exposed, an error-less refusal, an empty ok envelope), `settings-page` (the meter hands the pill the complete reading, and an empty envelope as nothing), `settings-purge` and `settings-store` (a string error, an empty ok envelope, a value without `ok`, the missing service's console line, and a zero-argument call). 21 cases in six files (with each file's existing cases, 88 green on the base), unedited after but for the edits below. The pins land with the change in one commit, as P5's and P-R2's did. +- **The pin-file edits:** `settings-usage`'s type import of the moved `src/contracts/usage.ts`; and `remote-seam`'s two purge cases, first written over a hand-built result (with a `site` on a provider row, which the service never sends) and a hand-built refusal (in words the service does not use), rewritten to run the real service as the usage and store cases do. The rewritten file was run on the base (`d1f7bf4`, exported to a scratch tree with the working tree's `node_modules`) and passed, 7 of 7, with a control that drops `site` in the base's `parsePurgeResult` failing the result case there. +- **Test edits that are not pins:** `usage-pill-mount`'s type import of the moved `src/contracts/usage.ts`, and the header comments of `usage-contract` and `opencode-store-contract`, which name the moved modules. +- **Rewritten:** `remote-contract`'s grep half (the services found by regex over `src/*.ts`) now reads `REMOTE_CONTRACTS`: the client registers exactly their descriptors (the contracts' own objects), and the plugin mounted on a real cordis `Context` resolves a service per contract whose `typertRemote` namespace is the contract's and whose `remoteMethods()` are exactly its methods, with one "is reachable" report per contract (a tripwire on the installer's own line). Its unique-ids, `readAccount` and one-parser-per-codec cases are kept. +- **New with the change:** `remote-define` (the builder at 100%), `settings-remote`'s `findRemoteCall`, `unwrapRemote` (a table over every envelope shape, including a parser that answers `undefined`, `null` or throws) and `callRemote` (a zero-argument call, one argument passed as one, a rejection rejected), `remote-service`'s `markRemote` (the host's reader, the descriptor flags, a re-mark made twice inside one case, and a `@ts-expect-error` for a contract method the class lacks; each case on a class of its own), `remote-contract`'s D5 identity case and a per-method `typeof … === "function"` check in its mount loop (the marker is written from the contract, so the method list is equal by construction), `settings-remote`'s two cases for a throwing `remote` getter (never read when `ctx.get` resolves; read as no remote when it misses) and the miss case at the caller level in `settings-purge` and `settings-store` (`unavailable` where the base rejected) and in `settings-page`'s meter (its "no usage service" reason where the base threw out of the dock injector), `usage-contract`'s `parseUsageReading`, the D1–D4 cases in the four caller files (with D3's `null` error and wrapped form, and D4's invalid bare `{ value }`), and `architecture`'s client graph reaching `contracts/*` and three one-seam scans (the marker key in `host/remote.ts` only, the envelope reads in `settings-remote.ts` only, the `"opencodeGoUsage"` literal in `contracts/usage.ts` only), each with planted spellings. `src/contracts/remote.ts` carries a 100% per-file floor. + ## End-to-end infrastructure ### The `e2e-host` job (`ci.yml`) diff --git a/docs/opencode-parity-plan.md b/docs/opencode-parity-plan.md index 3a0f6e3e..5ff036ef 100644 --- a/docs/opencode-parity-plan.md +++ b/docs/opencode-parity-plan.md @@ -46,7 +46,7 @@ To maintain long-term stability and prevent regressions, the codebase enforces s ┌────────────────────────────────────────────────────────────────────────┐ │ 1. Domain Models (Pure Types & Constants) │ │ • src/config-values.ts: Pure coercion readers & constants │ -│ • src/usage-contract.ts: Quota reading envelopes & status enums │ +│ • src/contracts/usage.ts: Quota reading envelopes & status enums │ │ • src/login-contract.ts: OAuth grant records & service codecs │ │ • src/catalog-data.ts: Static catalog schema definitions │ │ (Zero dependencies, shared safely across Host and Web Client) │ diff --git a/docs/protocol-routing-and-merge.md b/docs/protocol-routing-and-merge.md index 4e8b1a2b..380a7af8 100644 --- a/docs/protocol-routing-and-merge.md +++ b/docs/protocol-routing-and-merge.md @@ -140,6 +140,6 @@ What belongs here is only the part that is a routing consequence: the meter is a | Catalog merge | `models-catalog.ts`, `models-discovery.ts`, `catalog-data.ts` | | Allowance table | `go-limits-data.ts` (generated) | | Credentials and the `/usage` endpoint | `go-discovery.ts`, `key-capture.ts` | -| The usage Host service | `usage.ts`, `usage-contract.ts` | +| The usage Host service | `usage.ts`, `contracts/usage.ts` | | Meter state / views / logic | `usage-pill.tsx`, `usage-panel.tsx`, `usage-ui.ts` | | Settings card and its summary | `settings-card.tsx`, `settings-usage.tsx` | diff --git a/scripts/check.ts b/scripts/check.ts index 3ccd3f03..f66c9466 100644 --- a/scripts/check.ts +++ b/scripts/check.ts @@ -352,8 +352,19 @@ try { * 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. + * + * Raised 140 -> 146 KB when P9 gave the remotes one seam: the client now + * carries the contract builder (`src/contracts/remote.ts`, which derives every + * descriptor and codec), the one unwrap with its lookup and call + * (`findRemoteCall`, `unwrapRemote`, `callRemote` in `src/settings-remote.ts`) + * and the usage reading parser, replacing four hand-written unwraps and three + * descriptor literals. Source and its comments, not a dependency (the bundle + * still requires only react and the UI primitives) — the client measured + * 146953 bytes against the old line, from 143074 on the base. 146 rather + * than 144 keeps the ~3 KB of room this line is meant to have; at 144 the + * bundle sat under a kilobyte below it. */ -const CLIENT_BUDGET = 140 * 1024; +const CLIENT_BUDGET = 146 * 1024; const clientPath = join(ROOT, "lib/client.js"); if (existsSync(clientPath)) { const clientStat = statSync(clientPath); diff --git a/src/contracts/all.ts b/src/contracts/all.ts new file mode 100644 index 00000000..93e80134 --- /dev/null +++ b/src/contracts/all.ts @@ -0,0 +1,23 @@ +/** + * Every remote contract this plugin defines, in one list. + * + * The client mounts them as ONE contribution (`patchRemote` in + * `src/settings-page.tsx`): Typert enforces a unique package name per + * contribution. A new remote is one `defineRemote`, one entry here, one + * `markRemote` on its service and one `installRemoteService` in + * `src/lifecycle.ts`. Kept apart from `remote.ts` so the builder imports none + * of the contracts it builds. + * + * @module dsh-opencode-patch/contracts/all + */ + +import { purgeRemote } from "./purge.ts"; +import { storeRemote } from "./store.ts"; +import { usageRemote } from "./usage.ts"; + +/** Usage, purge, store: the order the client's descriptors have always had. */ +export const REMOTE_CONTRACTS = [ + usageRemote, + purgeRemote, + storeRemote, +] as const; diff --git a/src/purge-contract.ts b/src/contracts/purge.ts similarity index 82% rename from src/purge-contract.ts rename to src/contracts/purge.ts index dae8ef8f..a84791d0 100644 --- a/src/purge-contract.ts +++ b/src/contracts/purge.ts @@ -5,13 +5,12 @@ * rather than in either side means the two cannot drift, and the bundle rule * (a client module reaches nothing host-only) is satisfied by construction. * - * @module dsh-opencode-patch/purge-contract + * @module dsh-opencode-patch/contracts/purge */ -import type { - RemoteResult, - TypertRemoteContribution, -} from "@deepseek-ai/dsh-typert-protocol"; +import type { RemoteResult } from "@deepseek-ai/dsh-typert-protocol"; + +import { defineRemote, remoteValue } from "./remote.ts"; /** * Where a retired model id was found. @@ -93,14 +92,6 @@ export const parsePurgeResult = (value: unknown): PurgeResult | undefined => { return { catalogRead, removed: rows }; }; -/** The wire codec for one purge result, in the shape `usageCodec` uses. */ -const purgeResultCodec = { - create: () => ({ parse: parsePurgeResult }), - mode: "strict" as const, - schema: { parse: parsePurgeResult }, - typeSymbol: "dsh-opencode-patch#PurgeResult", -}; - /** * The purge namespace, as a contribution the client mounts. * @@ -108,23 +99,12 @@ const purgeResultCodec = { * mounts the Service and the card asks `remote.opencodeModelPurge.purge`; a * Remote is only reachable when a contribution carrying its descriptor was * mounted on the client, so the row reported "unavailable" for a host that had - * the service all along. Same shape as `usageRemote`, and the card mounts both - * under one package name. + * the service all along. Same builder as `usageRemote`, and the card mounts + * every contract under one package name (`REMOTE_CONTRACTS`). */ -export const purgeRemote: TypertRemoteContribution = { - descriptors: [ - { - id: "dsh-opencode-patch#opencodeModelPurge/purge", - invocation: { kind: "direct" }, - method: "purge", - namespace: PURGE_NAMESPACE, - parameters: [], - result: purgeResultCodec, - service: PURGE_NAMESPACE, - }, - ], - package: "dsh-opencode-patch", -}; +export const purgeRemote = defineRemote(PURGE_NAMESPACE, { + purge: { result: remoteValue("PurgeResult", parsePurgeResult) }, +}); /** The one failure a purge reports: the profile cannot be rewritten here. */ export const PURGE_UNAVAILABLE = "opencode/purge-unavailable"; diff --git a/src/contracts/remote.ts b/src/contracts/remote.ts new file mode 100644 index 00000000..ac18d611 --- /dev/null +++ b/src/contracts/remote.ts @@ -0,0 +1,130 @@ +/** + * The one builder for this plugin's remote contracts, in a module both bundles + * may import. + * + * A contract is a namespace and its methods: each method's parameters and the + * value it answers, each value a parser. Everything the Typert gateway reads is + * DERIVED from that: the descriptors the client mounts (ids, the one wire name + * per parameter, `acceptsUndefined` on an optional one only), the codecs, and + * the method list the host's Remote marker carries (`markRemote` in + * `src/host/remote.ts`). They were three hand-written literals per remote, and + * a remote whose descriptor was missing reached the browser as "unavailable". + * + * Type-only imports from the protocol package, and nothing host-only, so the + * client bundle may load it. + * + * @module dsh-opencode-patch/contracts/remote + */ + +import type { + InvocationDescriptor, + InvocationParameterDescriptor, + TypertRemoteContribution, +} from "@deepseek-ai/dsh-typert-protocol"; + +/** The npm package every descriptor id and codec type symbol is under. */ +export const REMOTE_PACKAGE = "dsh-opencode-patch"; + +/** + * Parse one boundary value. A throw and an `undefined` answer both mean "not + * one": the purge and store parsers answer `undefined`, the usage parsers throw. + */ +export type RemoteParse = (value: unknown) => Value | undefined; + +/** One wire codec, in the shape the gateway reads: one parser behind both doors. */ +export interface RemoteValue { + readonly create: () => { readonly parse: RemoteParse }; + readonly mode: "strict"; + readonly schema: { readonly parse: RemoteParse }; + readonly typeSymbol: string; +} + +/** + * The codec for one value type. + * + * @param type - the type's name, under {@link REMOTE_PACKAGE}. + * @param parse - the contract's parser, behind both doors. + * @returns a fresh codec. + */ +export const remoteValue = ( + type: string, + parse: RemoteParse +): RemoteValue => ({ + create: () => ({ parse }), + mode: "strict", + schema: { parse }, + typeSymbol: `${REMOTE_PACKAGE}#${type}`, +}); + +/** One parameter: its name (also its wire name) and its value. */ +export interface RemoteParameter { + readonly name: string; + readonly value: RemoteValue; + /** The whole argument may be absent on the wire. */ + readonly optional?: true; +} + +/** One method: its parameters, in order, and the value it answers. */ +export interface RemoteMethod { + readonly parameters?: readonly RemoteParameter[]; + readonly result: RemoteValue; +} + +/** What a contract is, to a reader of its methods. */ +export interface RemoteContractOf< + Methods extends Readonly>>, +> { + readonly namespace: string; + readonly methods: Methods; +} + +/** A contract, and the contribution the client mounts for it. */ +export interface DefinedRemote< + Methods extends Readonly>>, +> + extends RemoteContractOf, TypertRemoteContribution { + readonly descriptors: readonly InvocationDescriptor[]; + readonly package: typeof REMOTE_PACKAGE; +} + +/** One parameter's descriptor; no `acceptsUndefined` key on a required one. */ +const parameterDescriptor = ({ + name, + optional, + value, +}: RemoteParameter): InvocationParameterDescriptor => ({ + ...(optional === true ? { acceptsUndefined: true } : {}), + codec: value, + name, + source: "json", + wire: name, +}); + +/** + * Define a remote: the namespace, and its methods in the order they are listed. + * + * @param namespace - the wire namespace, which is also the service key. + * @param methods - each method's parameters and result. + * @returns the contract, carrying its derived descriptors. + */ +export const defineRemote = < + const Methods extends Readonly>>, +>( + namespace: string, + methods: Methods +): DefinedRemote => ({ + descriptors: Object.entries>(methods).map( + ([method, { parameters = [], result }]): InvocationDescriptor => ({ + id: `${REMOTE_PACKAGE}#${namespace}/${method}`, + invocation: { kind: "direct" }, + method, + namespace, + parameters: parameters.map(parameterDescriptor), + result, + service: namespace, + }) + ), + methods, + namespace, + package: REMOTE_PACKAGE, +}); diff --git a/src/opencode-store-contract.ts b/src/contracts/store.ts similarity index 81% rename from src/opencode-store-contract.ts rename to src/contracts/store.ts index 556bdcb3..232fb489 100644 --- a/src/opencode-store-contract.ts +++ b/src/contracts/store.ts @@ -3,12 +3,11 @@ * * Pure data types, no I/O, no context, safely imported by host and client. * - * @module dsh-opencode-patch/opencode-store-contract + * @module dsh-opencode-patch/contracts/store */ -import type { TypertRemoteContribution } from "@deepseek-ai/dsh-typert-protocol"; - -import { isRecord } from "./utils/guards.ts"; +import { isRecord } from "../utils/guards.ts"; +import { defineRemote, remoteValue } from "./remote.ts"; export const STORE_NAMESPACE = "opencodeStore"; @@ -110,14 +109,6 @@ export const parseStoreInspection = ( }; }; -/** The wire codec for one inspection, in the shape `usageCodec` uses. */ -const storeInspectionCodec = { - create: () => ({ parse: parseStoreInspection }), - mode: "strict" as const, - schema: { parse: parseStoreInspection }, - typeSymbol: "dsh-opencode-patch#OpencodeStoreInspection", -}; - /** * The store-inspection namespace, as a contribution the client mounts. * @@ -126,17 +117,8 @@ const storeInspectionCodec = { * mounted on the client — the same finding `purgeRemote` records — and this one * was not: the host mounted the service, and the row reported "unavailable". */ -export const storeRemote: TypertRemoteContribution = { - descriptors: [ - { - id: "dsh-opencode-patch#opencodeStore/inspect", - invocation: { kind: "direct" }, - method: "inspect", - namespace: STORE_NAMESPACE, - parameters: [], - result: storeInspectionCodec, - service: STORE_NAMESPACE, - }, - ], - package: "dsh-opencode-patch", -}; +export const storeRemote = defineRemote(STORE_NAMESPACE, { + inspect: { + result: remoteValue("OpencodeStoreInspection", parseStoreInspection), + }, +}); diff --git a/src/usage-contract.ts b/src/contracts/usage.ts similarity index 77% rename from src/usage-contract.ts rename to src/contracts/usage.ts index 4ba52d57..1e015486 100644 --- a/src/usage-contract.ts +++ b/src/contracts/usage.ts @@ -2,16 +2,17 @@ * Remote contract and validation for OpenCode Go account usage. A Typert remote, * so the host fetches with server-side credentials and never exposes the key. * - * @module dsh-opencode-patch/usage-contract + * @module dsh-opencode-patch/contracts/usage */ -import type { - RemoteResult, - TypertRemoteContribution, -} from "@deepseek-ai/dsh-typert-protocol"; +import type { RemoteResult } from "@deepseek-ai/dsh-typert-protocol"; -import type { SessionUsageSnapshot } from "./session-cost.ts"; -import { isRecord } from "./utils/guards.ts"; +import type { SessionUsageSnapshot } from "../session-cost.ts"; +import { isRecord } from "../utils/guards.ts"; +import { defineRemote, remoteValue } from "./remote.ts"; + +/** The remote namespace the host mounts the usage service under. */ +export const USAGE_NAMESPACE = "opencodeGoUsage"; /** The active model's published monthly allowance, resolved on the Host. */ export interface ModelAllowanceSnapshot { @@ -229,13 +230,62 @@ declare module "@deepseek-ai/dsh-typert-protocol" { } } -const usageCodec = { - create: () => ({ parse: parseGoUsage }), - mode: "strict" as const, - schema: { parse: parseGoUsage }, - typeSymbol: "dsh-opencode-patch#GoUsage", +/** The allowance the Host attached, kept only as the three fields it names. */ +const parseAllowance = (raw: unknown): ModelAllowanceSnapshot | undefined => { + if (!isRecord(raw)) { + return undefined; + } + const { go, goPlus, model } = raw; + return typeof go === "number" && + Number.isFinite(go) && + typeof goPlus === "number" && + Number.isFinite(goPlus) && + typeof model === "string" + ? { go, goPlus, model } + : undefined; +}; + +/** + * Validate a reading the HOST answered, for the client that renders it. + * + * {@link parseGoUsage} is the whitelist for the VENDOR's payload, and the Host + * adds to what it parsed: the allowance, the overflow floor's + * `quotaUnavailable`, and this route's plane spend on the session. All of them + * are rendered, so the client's parser is a superset: the vendor whitelist, + * plus those fields, each kept only in the shape the Host sends it. + * + * @param value - the reading, as the remote answered it. + * @returns the reading; throws `parseGoUsage`'s TypeError when it is not one. + */ +export const parseUsageReading = (value: unknown): GoUsage => { + if (!isRecord(value)) { + return parseGoUsage(value); + } + const usage = parseGoUsage(value); + const allowance = parseAllowance(value.allowance); + const raw = isRecord(value.session) ? value.session : {}; + const { planeCostFormatted, planeSpendUsd } = raw; + return { + ...usage, + ...(allowance === undefined ? {} : { allowance }), + ...(value.quotaUnavailable === true ? { quotaUnavailable: true } : {}), + ...(usage.session === undefined + ? {} + : { + session: { + ...usage.session, + ...(typeof planeCostFormatted === "string" + ? { planeCostFormatted } + : {}), + ...(typeof planeSpendUsd === "number" ? { planeSpendUsd } : {}), + }, + }), + }; }; +/** One codec for both reads: the reading parser, which the client unwraps with. */ +const usageReading = remoteValue("GoUsage", parseUsageReading); + /** * What the caller may tell the Host about the meter it is rendering. * @@ -288,12 +338,7 @@ export const parseUsageQuery = (value?: unknown): UsageQuery => { }; }; -const usageQueryCodec = { - create: () => ({ parse: parseUsageQuery }), - mode: "strict" as const, - schema: { parse: parseUsageQuery }, - typeSymbol: "dsh-opencode-patch#UsageQuery", -}; +const usageQuery = remoteValue("UsageQuery", parseUsageQuery); /** * An account reference, as the sibling `dsh-opencode-go` account manager spells @@ -312,52 +357,19 @@ export const parseAccountRef = (value: unknown): string => { return value; }; -const accountRefCodec = { - create: () => ({ parse: parseAccountRef }), - mode: "strict" as const, - schema: { parse: parseAccountRef }, - typeSymbol: "dsh-opencode-patch#AccountRef", -}; +const accountRef = remoteValue("AccountRef", parseAccountRef); -export const usageRemote: TypertRemoteContribution = { - descriptors: [ - { - id: "dsh-opencode-patch#opencodeGoUsage/read", - invocation: { kind: "direct" }, - method: "read", - namespace: "opencodeGoUsage", - parameters: [ - { - // The query is optional: a caller that knows nothing still gets the - // default route and the latest session. - acceptsUndefined: true, - codec: usageQueryCodec, - name: "query", - source: "json", - wire: "query", - }, - ], - result: usageCodec, - service: "opencodeGoUsage", - }, - { - // The sibling `dsh-opencode-go` account page reads through this spelling; - // the reading is the one for the account this plugin's route selects. - id: "dsh-opencode-patch#opencodeGoUsage/readAccount", - invocation: { kind: "direct" }, - method: "readAccount", - namespace: "opencodeGoUsage", - parameters: [ - { - codec: accountRefCodec, - name: "ref", - source: "json", - wire: "ref", - }, - ], - result: usageCodec, - service: "opencodeGoUsage", - }, - ], - package: "dsh-opencode-patch", -}; +export const usageRemote = defineRemote(USAGE_NAMESPACE, { + read: { + // The query is optional: a caller that knows nothing still gets the + // default route and the latest session. + parameters: [{ name: "query", optional: true, value: usageQuery }], + result: usageReading, + }, + // The sibling `dsh-opencode-go` account page reads through this spelling; + // the reading is the one for the account this plugin's route selects. + readAccount: { + parameters: [{ name: "ref", value: accountRef }], + result: usageReading, + }, +}); diff --git a/src/host/remote.ts b/src/host/remote.ts index f73e5008..bf166800 100644 --- a/src/host/remote.ts +++ b/src/host/remote.ts @@ -1,7 +1,8 @@ /** - * The one installer for the plugin's remote services: the usage meter's - * `opencodeGoUsage`, the card's `opencodeModelPurge` and its `opencodeStore` - * inspection. + * The host half of the plugin's remote services: `markRemote`, which declares + * a service's Remote methods from its contract, and `installRemoteService`, + * the one installer for the usage meter's `opencodeGoUsage`, the card's + * `opencodeModelPurge` and its `opencodeStore` inspection. * * Three rules shape it, and each replaced a copy that got one of them wrong. * @@ -66,6 +67,54 @@ export interface RemoteContract { }[]; } +/** + * Prototype key `remoteMethods()` reads Remote markers from. A plain string + * constant in the protocol package (index.ts:140); not re-exported, so this is + * the one copy of it. + */ +const REMOTE_METHOD_DESCRIPTOR_KEY = + "@deepseek-ai/dsh-typert-protocol/remote-methods"; + +/** + * Declare a service's Remote methods, one per contract method, in the + * contract's order: exactly what `@Remote()` does. + * + * The decorator cannot be used: this build transform is oxc/rolldown based and + * rejects TC39 decorator syntax outright ("SyntaxError: Invalid or unexpected + * token"), and `esbuild: { target: "esnext" }` is ignored by it. The decorator + * has no magic — it registers an instance initializer calling + * `mark(prototype, method, invocation)`, and `mark` only writes this one + * property. `remoteMethods()` reads it straight off the prototype, so writing + * it directly is equivalent. Swap for the decorator once the transform accepts + * one. + * + * The type makes a contract method the class does not implement a compile + * error, so the marker cannot declare a method the gateway would then find + * missing. + * + * @param Service - the service class; its prototype carries the marker. + * @param contract - the contract whose methods the service answers. + */ +export const markRemote = ( + Service: abstract new ( + ...args: never[] + ) => Record, (...args: never[]) => Promise>, + contract: RemoteContract & { readonly methods: Record } +): void => { + Object.defineProperty(Service.prototype, REMOTE_METHOD_DESCRIPTOR_KEY, { + configurable: true, + value: Object.freeze({ + version: 1, + methods: Object.freeze( + contract.descriptors.map(({ method }) => ({ + method, + invocation: { kind: "direct" }, + })) + ), + }), + }); +}; + /** The one service and namespace a contract's descriptors all name. */ interface Target { readonly service: string; diff --git a/src/lifecycle.ts b/src/lifecycle.ts index 4059b5af..a21eb4cf 100644 --- a/src/lifecycle.ts +++ b/src/lifecycle.ts @@ -26,6 +26,9 @@ import { type ResolvedPluginConfig, resolveConfig, } from "./config.ts"; +import { purgeRemote } from "./contracts/purge.ts"; +import { storeRemote } from "./contracts/store.ts"; +import { usageRemote } from "./contracts/usage.ts"; import { type CordisContext, readEntryOptions } from "./cordis-context.ts"; import { captureStoreFor, createCredentials } from "./credentials.ts"; import { recordDebug } from "./debug.ts"; @@ -40,13 +43,10 @@ import { decorateModelDiscovery, type DiscoveryClaim, } from "./models-discovery.ts"; -import { storeRemote } from "./opencode-store-contract.ts"; import { OpencodeStoreService } from "./opencode-store-service.ts"; -import { purgeRemote } from "./purge-contract.ts"; import { ModelPurgeService } from "./purge-service.ts"; import { createStreamHook } from "./stream-hook.ts"; import type { ActiveTurnState } from "./turn-store.ts"; -import { usageRemote } from "./usage-contract.ts"; import { GoUsageService } from "./usage.ts"; import { isFunctionLike, isRecord } from "./utils/guards.ts"; import { planeHeadersFor, projectHeaderOf } from "./utils/request-shape.ts"; diff --git a/src/opencode-store-service.ts b/src/opencode-store-service.ts index 1acf0caa..0f7d8e52 100644 --- a/src/opencode-store-service.ts +++ b/src/opencode-store-service.ts @@ -21,11 +21,13 @@ import os from "node:os"; import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol"; -import { opencodeDatabasePath } from "./opencode-paths.ts"; import { STORE_NAMESPACE, + storeRemote, type OpencodeStoreInspection, -} from "./opencode-store-contract.ts"; +} from "./contracts/store.ts"; +import { markRemote } from "./host/remote.ts"; +import { opencodeDatabasePath } from "./opencode-paths.ts"; import { inspectOpencodeStore } from "./opencode-store.ts"; import { isRecord } from "./utils/guards.ts"; @@ -94,29 +96,4 @@ const defaultStorePath = (): string => os.tmpdir() ); -/** - * Prototype key `remoteMethods()` reads Remote markers from — the same constant - * `usage.ts` and `purge-service.ts` spell out, because the protocol package does - * not re-export it. - */ -const REMOTE_METHOD_DESCRIPTOR_KEY = - "@deepseek-ai/dsh-typert-protocol/remote-methods"; - -/** - * Declare `inspect` as a Remote method. See `usage.ts` for why the decorator - * cannot be used in this build: the oxc/rolldown transform rejects TC39 decorator - * syntax outright, and the marker it would write is a plain property. - */ -Object.defineProperty( - OpencodeStoreService.prototype, - REMOTE_METHOD_DESCRIPTOR_KEY, - { - configurable: true, - value: Object.freeze({ - version: 1, - methods: Object.freeze([ - { method: "inspect", invocation: { kind: "direct" } }, - ]), - }), - } -); +markRemote(OpencodeStoreService, storeRemote); diff --git a/src/opencode-store.ts b/src/opencode-store.ts index 0028fc0f..bb664b38 100644 --- a/src/opencode-store.ts +++ b/src/opencode-store.ts @@ -25,7 +25,7 @@ import { existsSync } from "node:fs"; import { DatabaseSync } from "node:sqlite"; -import type { OpencodeStoreInspection } from "./opencode-store-contract.ts"; +import type { OpencodeStoreInspection } from "./contracts/store.ts"; import { isRecord } from "./utils/guards.ts"; /** A credential as the installation stores it, minus everything unused. */ diff --git a/src/purge-service.ts b/src/purge-service.ts index d6876ea8..f6b43095 100644 --- a/src/purge-service.ts +++ b/src/purge-service.ts @@ -30,16 +30,19 @@ import { TypertRemoteService, } from "@deepseek-ai/dsh-typert-protocol"; +import { + PURGE_NAMESPACE, + PURGE_UNAVAILABLE, + purgeRemote, + type PurgeResult, + type PurgedModel, +} from "./contracts/purge.ts"; +import { markRemote } from "./host/remote.ts"; import { didCatalogRefreshSucceed, isDeprecatedModelOn, refreshCatalog, } from "./models-catalog.ts"; -import { - PURGE_UNAVAILABLE, - type PurgeResult, - type PurgedModel, -} from "./purge-contract.ts"; import { isRecord } from "./utils/guards.ts"; import { foreignCredentialsRealm, @@ -239,7 +242,7 @@ export class ModelPurgeService extends TypertRemoteService { throw new TypeError("ModelPurgeService requires a Cordis context object"); } // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `TypertRemoteService` takes cordis `Context`, whose types ship only from the Harness installation; the guard above is the runtime check. - super(ctx as never, "opencodeModelPurge"); + super(ctx as never, PURGE_NAMESPACE); } /** @@ -376,28 +379,4 @@ export class ModelPurgeService extends TypertRemoteService { } } -/** - * Prototype key `remoteMethods()` reads Remote markers from — the same constant - * `usage.ts` uses, spelled here rather than imported because the protocol - * package does not re-export it. - */ -const REMOTE_METHOD_DESCRIPTOR_KEY = - "@deepseek-ai/dsh-typert-protocol/remote-methods"; - -/** - * Declare `purge` as a Remote method. See `usage.ts` for why the decorator - * cannot be used in this build. - */ -Object.defineProperty( - ModelPurgeService.prototype, - REMOTE_METHOD_DESCRIPTOR_KEY, - { - configurable: true, - value: Object.freeze({ - version: 1, - methods: Object.freeze([ - { method: "purge", invocation: { kind: "direct" } }, - ]), - }), - } -); +markRemote(ModelPurgeService, purgeRemote); diff --git a/src/settings-card.tsx b/src/settings-card.tsx index 25928a30..83b674cd 100644 --- a/src/settings-card.tsx +++ b/src/settings-card.tsx @@ -16,6 +16,7 @@ import { } from "@deepseek-ai/dsh-client-ui-primitives"; import React from "react"; +import type { GoUsage } from "./contracts/usage.ts"; import { SettingsBooleanField } from "./settings-boolean-field.tsx"; import { SettingsChoiceField } from "./settings-choice-field.tsx"; import { withBundleCopy, type Translate } from "./settings-copy.ts"; @@ -24,7 +25,6 @@ import type { PurgeOutcome } from "./settings-purge.ts"; import { StoreInspectRow } from "./settings-store-inspect.tsx"; import type { StoreInspectOutcome } from "./settings-store.ts"; import { UsageSummary } from "./settings-usage.tsx"; -import type { GoUsage } from "./usage-contract.ts"; interface CardField { invalid: boolean; diff --git a/src/settings-page.tsx b/src/settings-page.tsx index 49ada410..3fb35443 100644 --- a/src/settings-page.tsx +++ b/src/settings-page.tsx @@ -15,20 +15,20 @@ import { } from "@deepseek-ai/dsh-client-ui-primitives"; import { DEFAULT_PROVIDERS, readStringList } from "./config-values.ts"; -import { storeRemote } from "./opencode-store-contract.ts"; -import { purgeRemote } from "./purge-contract.ts"; +import { REMOTE_CONTRACTS } from "./contracts/all.ts"; +import { USAGE_NAMESPACE, usageRemote } from "./contracts/usage.ts"; import { OpencodeCard } from "./settings-card.tsx"; import { en, withBundleCopy, zh, type CopyKey } from "./settings-copy.ts"; import { SPECS } from "./settings-fields.ts"; import { purgeDeprecatedModels } from "./settings-purge.ts"; import { callUsageRead, - remoteNamespace, + findRemoteCall, remoteNamespaceOf, + unwrapRemote, } from "./settings-remote.ts"; import { inspectStore } from "./settings-store.ts"; import { readGoUsage } from "./settings-usage.tsx"; -import { usageRemote } from "./usage-contract.ts"; import { UsagePill } from "./usage-pill.tsx"; import { isRecord } from "./utils/guards.ts"; @@ -62,11 +62,7 @@ export const patchRemote = { // Typert enforces a unique package name per // contribution, so mounting them separately with the same package throws // "already registered" and drops the remote entirely. - descriptors: [ - ...usageRemote.descriptors, - ...purgeRemote.descriptors, - ...storeRemote.descriptors, - ], + descriptors: REMOTE_CONTRACTS.flatMap((contract) => contract.descriptors), package: PKG, }; @@ -147,11 +143,11 @@ const mountRemote = ( // indistinguishable from a working mount: the surface reads // `remote.`, finds nothing, and reports "no usage service" — // the same sentence a host with no service at all produces. - if (remoteNamespaceOf(ctx, "opencodeGoUsage") === undefined) { + if (remoteNamespaceOf(ctx, USAGE_NAMESPACE) === undefined) { const face = isRecord(ctx.remote) ? Object.keys(ctx.remote) : []; console.warn( `[dsh-opencode-patch] ${what}: the mount settled but ` + - `remote.opencodeGoUsage is still unreachable; the remote exposes ` + + `remote.${USAGE_NAMESPACE} is still unreachable; the remote exposes ` + `[${face.join(", ")}]` ); } @@ -436,17 +432,15 @@ export const apply = (ctx: ClientContext): void => { // is refused for a namespace this bundle mounts itself, and the refusal is // indistinguishable from "no service". Measured: `property read: false; // ctx.get('remote.opencodeGoUsage'): object`. - const usage = - remoteNamespaceOf(meterScope, "opencodeGoUsage") ?? - remoteNamespace(meterScope.remote, "opencodeGoUsage"); - if (typeof usage?.read !== "function") { + const found = findRemoteCall(meterScope, usageRemote, "read"); + if (found.call === undefined) { return { - reason: "no usage service: remote.opencodeGoUsage.read is missing", + reason: `no usage service: remote.${USAGE_NAMESPACE}.read is missing`, }; } // Captured once, narrowed by the guard above: the read stays reachable // from the meter closure without re-testing the namespace per call. - const { read } = usage; + const { call: read } = found; const markers = usageMarkers(); // The id the Host must price; the pill also names the active provider, // which is how the Host knows which account is on screen. @@ -458,24 +452,29 @@ export const apply = (ctx: ClientContext): void => { provider?: string, model?: string ): Promise => { - const res: unknown = await callUsageRead(read, { - ...(provider === undefined || provider.length === 0 - ? {} - : { provider }), - ...(model === undefined || model.length === 0 ? {} : { model }), - ...(meterSessionId.length === 0 - ? {} - : { sessionId: meterSessionId }), - }); - // Narrow `ok` to a boolean so the branch reads as truthiness; the lint - // config rejects coercing an `unknown` in the condition. - if (isRecord(res) && typeof res.ok === "boolean") { - if (res.ok) { - return "value" in res ? res.value : undefined; - } - throw "error" in res ? res.error : undefined; + const answer = unwrapRemote( + usageRemote, + "read", + await callUsageRead(read, { + ...(provider === undefined || provider.length === 0 + ? {} + : { provider }), + ...(model === undefined || model.length === 0 ? {} : { model }), + ...(meterSessionId.length === 0 + ? {} + : { sessionId: meterSessionId }), + }) + ); + if (answer.kind === "refused") { + // `undefined` when the envelope carried no error: the pill's + // `parseFailure` renders that as the generic unavailable state. + throw answer.error; } - return res; + // An answer the reading parser rejects passes through as it came: + // the meter never validated, and test/settings-page.test.tsx pins + // the pass-through. Rejecting it changes a pinned answer, so it is a + // `fix:` for a later phase, not this refactor. + return answer.value; }, // The dictionary and every `Intl` formatter must agree on the // language: `t` selects the words, `getLocale` feeds the dates and diff --git a/src/settings-purge.ts b/src/settings-purge.ts index cb37bbc1..c7dcd581 100644 --- a/src/settings-purge.ts +++ b/src/settings-purge.ts @@ -10,13 +10,8 @@ * @module dsh-opencode-patch/settings-purge */ -import { - parsePurgeResult, - PURGE_NAMESPACE, - type PurgeResult, -} from "./purge-contract.ts"; -import { remoteNamespace, remoteNamespaceOf } from "./settings-remote.ts"; -import { isRecord } from "./utils/guards.ts"; +import { purgeRemote, type PurgeResult } from "./contracts/purge.ts"; +import { callRemote, type RemoteOutcome } from "./settings-remote.ts"; /** What one click produced, in a shape the card can render without guessing. */ export type PurgeOutcome = @@ -24,66 +19,45 @@ export type PurgeOutcome = | { readonly kind: "unavailable" } | { readonly kind: "failed"; readonly message: string }; -/** The Remote's namespace, read through the shared guard (see settings-remote). */ -const namespaceOf = (scope: unknown) => - remoteNamespaceOf(scope, PURGE_NAMESPACE) ?? - remoteNamespace(isRecord(scope) ? scope.remote : undefined, PURGE_NAMESPACE); - /** * Ask the host to purge, once. * + * Through the one unwrap (`callRemote`): the host's own failure comes first, + * in its own words, and the result is PARSED by the contract's whitelist, + * never cast. + * * @param scope - the settings scope the card was rendered with. * @returns the outcome; never throws. */ export const purgeDeprecatedModels = async ( scope: unknown ): Promise => { - const namespace = namespaceOf(scope); - const call = namespace?.purge; - if (typeof call !== "function") { + let outcome: RemoteOutcome; + try { + outcome = await callRemote(scope, purgeRemote, "purge"); + } catch (error: unknown) { + return { + kind: "failed", + message: error instanceof Error ? error.message : String(error), + }; + } + if (outcome.kind === "unavailable") { console.warn( "[dsh-opencode-patch] purge: no opencodeModelPurge service on the remote" ); return { kind: "unavailable" }; } - try { - const answer: unknown = await call(); - const value = isRecord(answer) && "value" in answer ? answer.value : answer; - // **The host's own failure comes first.** The host answers a failure as - // `{ ok: false, … }`, and reading that as "not a purge result" replaced the - // message that says WHY with a sentence about shape — which tells the reader - // nothing they can act on. The remote protocol sends `{ ok: false, error }` - // with `error` a serialized `RemoteError`, so its `message` is read too. - if (isRecord(value) && value.ok === false) { - const { error, message: said } = value; - let message = "the host refused the purge"; - if (typeof said === "string") { - message = said; - } else if (typeof error === "string") { - message = error; - } else if (isRecord(error)) { - const { message: reason } = error; - if (typeof reason === "string") { - message = reason; - } - } - return { kind: "failed", message }; - } - // And the result is PARSED, not cast: the contract's whitelist is the - // client's only statement about what it is told, and a cast is no statement - // at all. - const result = parsePurgeResult(value); - if (result === undefined) { - return { - kind: "failed", - message: "the host answered something that is not a purge result", - }; - } - return { kind: "purged", result }; - } catch (error: unknown) { + if (outcome.kind === "refused") { return { kind: "failed", - message: error instanceof Error ? error.message : String(error), + message: outcome.reason ?? "the host refused the purge", + }; + } + if (outcome.kind === "invalid") { + return { + kind: "failed", + message: "the host answered something that is not a purge result", }; } + return { kind: "purged", result: outcome.value }; }; diff --git a/src/settings-remote.ts b/src/settings-remote.ts index 91b49e91..e9a3a093 100644 --- a/src/settings-remote.ts +++ b/src/settings-remote.ts @@ -16,9 +16,15 @@ * that holds the whole plugin until it exists, which is what took the meter out * once with "web boot: 1 entry did not activate". * + * It is also where every Remote answer is unwrapped, once, for every caller: + * {@link callRemote} finds the call, makes it, and parses the answer with the + * contract's own parser ({@link unwrapRemote}). + * * @module dsh-opencode-patch/settings-remote */ +import type { RemoteMethod } from "./contracts/remote.ts"; + /** One call on a remote namespace, as the seam exposes it. */ export type RemoteCall = (query?: unknown) => Promise; @@ -158,3 +164,145 @@ export const remoteNamespaceOf = ( return undefined; } }; + +/** A contract, as the unwrap reads it: its namespace and each result parser. */ +interface Contract { + readonly namespace: string; + readonly methods: Readonly>>; +} + +/** The call a contract's method resolves to, or the keys found instead. */ +export type FoundCall = + | { readonly call: RemoteCall } + | { readonly call: undefined; readonly exposed: readonly string[] }; + +/** The scope's `remote` face, or `undefined` when it is absent or the read throws. */ +const remoteFaceOf = (scope: unknown): unknown => { + try { + return isObject(scope) ? scope.remote : undefined; + } catch { + return undefined; + } +}; + +/** + * Find one method of a contract on the scope: through `ctx.get` first, then + * the guarded property (see {@link remoteNamespaceOf}). + * + * @param scope - the scope the caller was rendered with. + * @param contract - the contract; only its namespace is read. + * @param method - the method to find. + * @returns the call, or the keys the namespace (else the remote) exposes. + */ +export const findRemoteCall = ( + scope: unknown, + contract: { readonly namespace: string }, + method: string +): FoundCall => { + const viaGet = remoteNamespaceOf(scope, contract.namespace); + // `scope.remote` is read only when `ctx.get` found nothing, and guarded: a + // getter that throws (`cannot get property "remote" without inject`) reads + // as no remote, never as a throw out of a slot injector. + const remote = viaGet === undefined ? remoteFaceOf(scope) : undefined; + const namespace = viaGet ?? remoteNamespace(remote, contract.namespace); + const call = namespace?.[method]; + if (isRemoteCall(call)) { + return { call }; + } + return { + call: undefined, + exposed: Object.keys(namespace ?? (isObject(remote) ? remote : {})), + }; +}; + +/** One answer, unwrapped: the parsed value, the host's refusal, or neither. */ +export type RemoteAnswer = + | { readonly kind: "ok"; readonly value: Value } + | { + readonly kind: "refused"; + readonly error: unknown; + readonly reason: string | undefined; + } + | { readonly kind: "invalid"; readonly value: unknown }; + +/** A refusal's reason: the envelope's `message`, else the error's own words. */ +const reasonOf = ({ + error, + message, +}: Record): string | undefined => { + if (typeof message === "string") { + return message; + } + if (typeof error === "string") { + return error; + } + return isObject(error) && typeof error.message === "string" + ? error.message + : undefined; +}; + +/** + * THE one unwrap of a Remote answer. The gateway answers `{ ok, value | error }`; + * a bare value, or `{ value }`, is read as the payload. The payload is parsed + * with the contract's own result parser: a throw or `undefined` is `invalid`. + * + * @param contract - the contract the call was made through. + * @param method - the method that answered. + * @param answer - what the call resolved to. + * @returns the answer, unwrapped. + */ +export const unwrapRemote = ( + contract: Contract, + method: Method, + answer: unknown +): RemoteAnswer> => { + let payload = answer; + if (isObject(answer) && typeof answer.ok === "boolean") { + if (!answer.ok) { + return { error: answer.error, kind: "refused", reason: reasonOf(answer) }; + } + payload = answer.value; + } else if (isObject(answer) && "value" in answer) { + payload = answer.value; + } + let value: Value | undefined; + try { + value = contract.methods[method].result.schema.parse(payload); + } catch { + value = undefined; + } + return value === undefined || value === null + ? { kind: "invalid", value: payload } + : { kind: "ok", value }; +}; + +/** A call's outcome: its answer, or no call to make. */ +export type RemoteOutcome = + | RemoteAnswer + | { readonly kind: "unavailable"; readonly exposed: readonly string[] }; + +/** + * Find, call and unwrap one method. With no `argument` the call takes NONE: + * the client gateway refuses a call whose count differs from the descriptor's. + * A rejected call rejects. + * + * @param scope - the scope the caller was rendered with. + * @param contract - the contract to call through. + * @param method - the method to call. + * @param argument - the one argument, for a method that takes one. + * @returns the outcome. + */ +export const callRemote = async ( + scope: unknown, + contract: Contract, + method: Method, + argument?: unknown +): Promise>> => { + const found = findRemoteCall(scope, contract, method); + if (found.call === undefined) { + return { exposed: found.exposed, kind: "unavailable" }; + } + const answer = + argument === undefined ? await found.call() : await found.call(argument); + return unwrapRemote(contract, method, answer); +}; diff --git a/src/settings-store-inspect.tsx b/src/settings-store-inspect.tsx index 2e529c44..852b1328 100644 --- a/src/settings-store-inspect.tsx +++ b/src/settings-store-inspect.tsx @@ -24,7 +24,7 @@ import { Button } from "@deepseek-ai/dsh-client-ui-primitives"; import React from "react"; -import type { OpencodeStoreInspection } from "./opencode-store-contract.ts"; +import type { OpencodeStoreInspection } from "./contracts/store.ts"; import type { Translate } from "./settings-copy.ts"; import type { StoreInspectOutcome } from "./settings-store.ts"; diff --git a/src/settings-store.ts b/src/settings-store.ts index e9df08e9..03e770bf 100644 --- a/src/settings-store.ts +++ b/src/settings-store.ts @@ -8,22 +8,16 @@ */ import { - parseStoreInspection, - STORE_NAMESPACE, + storeRemote, type OpencodeStoreInspection, -} from "./opencode-store-contract.ts"; -import { remoteNamespace, remoteNamespaceOf } from "./settings-remote.ts"; -import { isRecord } from "./utils/guards.ts"; +} from "./contracts/store.ts"; +import { callRemote, type RemoteOutcome } from "./settings-remote.ts"; export type StoreInspectOutcome = | { readonly kind: "inspected"; readonly inspection: OpencodeStoreInspection } | { readonly kind: "unavailable" } | { readonly kind: "failed"; readonly message: string }; -const namespaceOf = (scope: unknown) => - remoteNamespaceOf(scope, STORE_NAMESPACE) ?? - remoteNamespace(isRecord(scope) ? scope.remote : undefined, STORE_NAMESPACE); - /** * Ask the host to inspect the local OpenCode installation. * @@ -33,42 +27,34 @@ const namespaceOf = (scope: unknown) => export const inspectStore = async ( scope: unknown ): Promise => { - const namespace = namespaceOf(scope); - const call = namespace?.inspect; - if (typeof call !== "function") { + let outcome: RemoteOutcome; + try { + outcome = await callRemote(scope, storeRemote, "inspect"); + } catch (error: unknown) { + return { + kind: "failed", + message: error instanceof Error ? error.message : String(error), + }; + } + if (outcome.kind === "unavailable") { console.warn( "[dsh-opencode-patch] store inspection: no opencodeStore service on the remote" ); return { kind: "unavailable" }; } - try { - const answer: unknown = await call(); - if (isRecord(answer) && answer.ok === false) { - // The remote's own failure, said in its own words rather than as a shape - // error about the envelope it arrived in. - const { error } = answer; - return { - kind: "failed", - message: - isRecord(error) && typeof error.message === "string" - ? error.message - : "the host could not inspect the installation", - }; - } - const value = isRecord(answer) && "value" in answer ? answer.value : answer; - const inspection: OpencodeStoreInspection | undefined = - parseStoreInspection(value); - if (inspection === undefined) { - return { - kind: "failed", - message: "host returned an invalid inspection shape", - }; - } - return { inspection, kind: "inspected" }; - } catch (error: unknown) { + if (outcome.kind === "refused") { + // The remote's own failure, said in its own words rather than as a + // shape error about the envelope it arrived in. return { kind: "failed", - message: error instanceof Error ? error.message : String(error), + message: outcome.reason ?? "the host could not inspect the installation", + }; + } + if (outcome.kind === "invalid") { + return { + kind: "failed", + message: "host returned an invalid inspection shape", }; } + return { inspection: outcome.value, kind: "inspected" }; }; diff --git a/src/settings-usage.tsx b/src/settings-usage.tsx index 62186c41..50fadba9 100644 --- a/src/settings-usage.tsx +++ b/src/settings-usage.tsx @@ -22,14 +22,17 @@ import { } from "@deepseek-ai/dsh-client-ui-primitives"; import React from "react"; +import { + USAGE_NAMESPACE, + usageRemote, + type GoUsage, +} from "./contracts/usage.ts"; import type { Translate } from "./settings-copy.ts"; import { callUsageRead, - isRemoteCall, - remoteNamespace, - remoteNamespaceOf, + findRemoteCall, + unwrapRemote, } from "./settings-remote.ts"; -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"; @@ -54,20 +57,6 @@ const WINDOWS = [ { copy: "usage_monthly", key: "monthly" }, ] as const; -/** Whether a value is one window, as the Host's contract defines it. */ -const isWindow = (value: unknown): value is UsageWindow => - isRecord(value) && - typeof value.percent === "number" && - typeof value.resetsAt === "string" && - (value.status === "ok" || value.status === "rate-limited"); - -/** Whether a value is a quota reading. The windows are what this page renders. */ -export const isGoUsage = (value: unknown): value is GoUsage => - isRecord(value) && - isWindow(value.rolling) && - isWindow(value.weekly) && - isWindow(value.monthly); - /** * Read the Go plane's quota through the Host service. * @@ -98,50 +87,37 @@ export const readGoUsage = async ( ); return undefined; } - // Through the context first: `remote.` is a service property, so an - // undeclared read THROWS and the guard answers `undefined` — the same answer as - // "no service". `ctx.get` does not consult `inject`, which is what makes a - // namespace this bundle mounts itself readable at all. - const namespace = - remoteNamespaceOf(scope, "opencodeGoUsage") ?? - remoteNamespace(remote, "opencodeGoUsage"); - if (namespace === undefined) { + // Through the context first (`findRemoteCall`): `remote.` is a service + // property, so an undeclared read THROWS and the guard answers `undefined` — + // the same answer as "no service". `ctx.get` does not consult `inject`, + // which is what makes a namespace this bundle mounts itself readable at all. + const found = findRemoteCall(scope, usageRemote, "read"); + if (found.call === undefined) { console.warn( - "[dsh-opencode-patch] usage read: no opencodeGoUsage service on the remote", - Object.keys(isRecord(remote) ? remote : {}) + `[dsh-opencode-patch] usage read: no ${USAGE_NAMESPACE} service on the remote`, + found.exposed ); return undefined; } - const call = namespace.read; - if (!isRemoteCall(call)) { - console.warn( - "[dsh-opencode-patch] usage read: no opencodeGoUsage service on the remote", - Object.keys(namespace) - ); - return undefined; - } - const result: unknown = await callUsageRead(call, { - provider: "opencode-go", - }); - if (isRecord(result) && typeof result.ok === "boolean") { - if (!result.ok) { - throw "error" in result ? result.error : new Error("usage call failed"); - } - const value = "value" in result ? result.value : undefined; - if (!isGoUsage(value)) { - return undefined; - } - return value; + // Parsed by the contract's reading parser, so the windows are checked as + // the Host checks them and only the fields it sends are kept. + const answer = unwrapRemote( + usageRemote, + "read", + await callUsageRead(found.call, { provider: "opencode-go" }) + ); + if (answer.kind === "refused") { + const failure: unknown = answer.error ?? new Error("usage call failed"); + throw failure; } - const value = isRecord(result) && "value" in result ? result.value : result; - if (!isGoUsage(value)) { + if (answer.kind === "invalid") { console.warn( "[dsh-opencode-patch] usage read: the answer is not a usage shape", - result + answer.value ); return undefined; } - return value; + return answer.value; }; /** The status word: which of the three states this reading is in. */ diff --git a/src/usage-panel.tsx b/src/usage-panel.tsx index 19bf12c8..9b5f0758 100644 --- a/src/usage-panel.tsx +++ b/src/usage-panel.tsx @@ -16,7 +16,7 @@ import { } from "@deepseek-ai/dsh-client-ui-primitives"; import React from "react"; -import type { GoUsage, UsageWindow } from "./usage-contract.ts"; +import type { GoUsage, UsageWindow } from "./contracts/usage.ts"; import { BREAKDOWN_WINDOWS, CONSOLE_URL, diff --git a/src/usage-pill.tsx b/src/usage-pill.tsx index 267bbfcd..cb2bebe5 100644 --- a/src/usage-pill.tsx +++ b/src/usage-pill.tsx @@ -15,7 +15,7 @@ import React, { } from "react"; import { DEFAULT_PROVIDERS } from "./config-values.ts"; -import type { GoUsage } from "./usage-contract.ts"; +import type { GoUsage } from "./contracts/usage.ts"; import { goQuotaTooltip, UsagePanel, UsageTrigger } from "./usage-panel.tsx"; import { CIRCUMFERENCE, diff --git a/src/usage-ui.ts b/src/usage-ui.ts index b51358fe..f5cac014 100644 --- a/src/usage-ui.ts +++ b/src/usage-ui.ts @@ -6,7 +6,7 @@ * @module dsh-opencode-patch/usage-ui */ -import type { GoUsage, UsageWindow } from "./usage-contract.ts"; +import type { GoUsage, UsageWindow } from "./contracts/usage.ts"; import { isRecord } from "./utils/guards.ts"; import { isZenProvider } from "./utils/request-shape.ts"; diff --git a/src/usage.ts b/src/usage.ts index 92883c02..8894cd10 100644 --- a/src/usage.ts +++ b/src/usage.ts @@ -18,6 +18,16 @@ import { import type { KeySourcePolicy } from "./config-values.ts"; import { DEFAULT_USAGE_BASE_URL } from "./config.ts"; +import { + parseAccountRef, + parseGoUsage, + USAGE_NAMESPACE, + usageRemote, + type GoUsage, + type ModelAllowanceSnapshot, + type UsageQuery, + type UsageWindow, +} from "./contracts/usage.ts"; import { discoverGoConfig, effectiveGoKeyRef, @@ -27,6 +37,7 @@ import { } from "./go-discovery.ts"; import { GO_MODEL_LIMITS } from "./go-limits-data.ts"; import { allowanceFor, type ModelAllowance } from "./go-limits.ts"; +import { markRemote } from "./host/remote.ts"; import { OPENCODE_PATCH_USER_AGENT } from "./identity.ts"; import { type CatalogPlane, findModelSpecOn } from "./models-catalog.ts"; import { @@ -34,14 +45,6 @@ import { getSessionUsage, type SessionUsageSnapshot, } from "./session-cost.ts"; -import { - parseAccountRef, - parseGoUsage, - type GoUsage, - type ModelAllowanceSnapshot, - type UsageQuery, - 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"; @@ -91,7 +94,7 @@ const zenOverflowUsage = ( query?: UsageQuery ): GoUsage => { // The three windows are a TYPE FLOOR, not a reading — see `quotaUnavailable` - // in usage-contract.ts for why the panel must not render them. Filling them + // in contracts/usage.ts for why the panel must not render them. Filling them // with 0% and a reset time of "now" is the only way to satisfy the shape // without inventing a number, and the flag is what stops them being drawn. const resetsAt = new Date().toISOString(); @@ -266,7 +269,7 @@ export class GoUsageService extends TypertRemoteService { throw new TypeError("GoUsageService requires a Cordis context object"); } // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- `TypertRemoteService` takes cordis `Context`, whose types ship only from the Harness installation and are not nameable from this package; the object guard above is the runtime check this cast stands in for. - super(ctx as never, "opencodeGoUsage"); + super(ctx as never, USAGE_NAMESPACE); this.options = options; } @@ -475,34 +478,6 @@ export class GoUsageService extends TypertRemoteService { } } -/** - * Prototype key `remoteMethods()` reads Remote markers from. A plain string - * constant in the protocol package (index.ts:140); not re-exported. - */ -const REMOTE_METHOD_DESCRIPTOR_KEY = - "@deepseek-ai/dsh-typert-protocol/remote-methods"; - -/** - * Declare `read` and `readAccount` as Remote methods — exactly what - * `@Remote()` does. - * - * The decorator cannot be used: this build transform is oxc/rolldown based and - * rejects TC39 decorator syntax outright ("SyntaxError: Invalid or unexpected - * token"), and `esbuild: { target: "esnext" }` is ignored by it. The decorator has - * no magic — it registers an instance initializer calling - * `mark(prototype, method, invocation)`, and `mark` only writes this one property. - * `remoteMethods()` reads it straight off the prototype, so writing it directly - * is equivalent. Swap for the decorator once the transform accepts one. - */ -Object.defineProperty(GoUsageService.prototype, REMOTE_METHOD_DESCRIPTOR_KEY, { - configurable: true, - value: Object.freeze({ - version: 1, - methods: Object.freeze([ - { method: "read", invocation: { kind: "direct" } }, - // A sibling plugin's account page reads through this spelling, and this - // root-mounted instance is the one the gateway resolves for the namespace. - { method: "readAccount", invocation: { kind: "direct" } }, - ]), - }), -}); +// `read`, and the `readAccount` a sibling plugin's account page reads +// through: this root-mounted instance is the one the gateway resolves. +markRemote(GoUsageService, usageRemote); diff --git a/test/architecture.test.ts b/test/architecture.test.ts index 7ec9313b..769809e9 100644 --- a/test/architecture.test.ts +++ b/test/architecture.test.ts @@ -533,6 +533,23 @@ describe("architecture · the client bundle reaches nothing host-only", () => { expect(graph.has("config.ts")).toBe(false); }); + it("walks into the remote contracts, so the rules below cover them (P9)", () => { + // The contracts are client-safe by construction, and the bundle loads + // every one of them: the walker must resolve a nested folder for the + // HOST_ONLY and process.env rules to be seen to apply. + const graph = clientGraph(); + for (const file of [ + "contracts/all.ts", + "contracts/purge.ts", + "contracts/remote.ts", + "contracts/store.ts", + "contracts/usage.ts", + ]) { + expect(graph.has(file), file).toBe(true); + } + expect(graph.has("utils/guards.ts")).toBe(true); + }); + it("imports no node built-in, no cordis runtime and no pi", () => { const violations: string[] = []; for (const [file, source] of clientGraph()) { @@ -565,6 +582,70 @@ describe("architecture · the client bundle reaches nothing host-only", () => { }); }); +describe("architecture · one remote seam (P9)", () => { + /** + * Each spelling the seam owns lives in one module: the Remote marker's key + * in `host/remote.ts` (`markRemote`), the envelope reads in + * `settings-remote.ts` (the one unwrap), and the usage namespace's literal + * in `contracts/usage.ts` (`USAGE_NAMESPACE`). Tripwires for the spellings + * they name, as P7's scans are: comments are stripped first, and a read + * spelled another way (a destructured `ok`, a computed key) escapes them. + */ + const RULES: readonly { + readonly name: string; + readonly owner: string; + readonly matches: (source: string) => boolean; + }[] = [ + { + matches: (source) => + source.includes("@deepseek-ai/dsh-typert-protocol/remote-methods"), + name: "the Remote marker key", + owner: "host/remote.ts", + }, + { + matches: (source) => + /"value"\s+in\b|\.ok\s*===\s*false|typeof\s+[\w.]+\.ok\s*===\s*"boolean"/u.test( + source + ), + name: "an envelope read", + owner: "settings-remote.ts", + }, + { + matches: (source) => source.includes('"opencodeGoUsage"'), + name: "the usage namespace literal", + owner: "contracts/usage.ts", + }, + ]; + + it("flags a planted spelling of each, so a pass means something", () => { + const [marker, envelope, namespace] = RULES; + expect( + marker?.matches( + 'const KEY = "@deepseek-ai/dsh-typert-protocol/remote-methods";' + ) + ).toBe(true); + expect(envelope?.matches('if ("value" in answer) {}')).toBe(true); + expect(envelope?.matches("if (res.ok === false) {}")).toBe(true); + expect(envelope?.matches('if (typeof res.ok === "boolean") {}')).toBe(true); + expect(envelope?.matches("const { ok } = res;")).toBe(false); + expect( + namespace?.matches('remoteNamespaceOf(ctx, "opencodeGoUsage")') + ).toBe(true); + expect(namespace?.matches("remote.opencodeGoUsage.read")).toBe(false); + // And a comment is not code. + expect( + namespace?.matches(stripComments('// "opencodeGoUsage"\nconst a = 1;')) + ).toBe(false); + }); + + it.each(RULES)("$name occurs in $owner only", ({ matches, owner }) => { + const holders = filesUnder(SRC_DIR).filter((file) => + matches(stripComments(readFileSync(join(SRC_DIR, file), "utf8"))) + ); + expect(holders).toEqual([owner]); + }); +}); + describe("architecture · the host bundle mutates no registry it does not own", () => { /** The host half's composition root: everything `apply()` can run. */ const ENTRY = "lifecycle.ts"; diff --git a/test/opencode-store-contract.test.ts b/test/opencode-store-contract.test.ts index 31dcfc9a..f902b137 100644 --- a/test/opencode-store-contract.test.ts +++ b/test/opencode-store-contract.test.ts @@ -1,5 +1,5 @@ /** - * `opencode-store-contract.ts` · the inspection's whitelist and its Remote. + * `contracts/store.ts` · the inspection's whitelist and its Remote. * * The contract is the one place a field the host did not mean to send — a * token, say — is dropped before it can reach the card, so the whitelist is diff --git a/test/remote-contract.test.ts b/test/remote-contract.test.ts index d5bc14be..cdd67815 100644 --- a/test/remote-contract.test.ts +++ b/test/remote-contract.test.ts @@ -10,142 +10,125 @@ * Neither half's own test could see it. `lifecycle.test.ts` asserted the SERVICE * mounted; `settings-page.test.tsx` asserted the contribution listed what it * listed. Both passed. The bug lived in the gap, so the assertion has to be about - * the gap: every namespace a service is mounted under must appear in the - * descriptors the client mounts, and nothing else may. + * the gap. Since P9 both halves are built from one list, `REMOTE_CONTRACTS`: the + * client's descriptors are its descriptors, and the plugin, mounted on a real + * cordis `Context`, must answer every contract with a service carrying exactly + * its methods, and mount nothing else. It used to grep `src/` for the services; + * it reads the contracts and the mounted services now. * * @module test/remote-contract.test */ -import { readdirSync, readFileSync } from "node:fs"; -import { join } from "node:path"; +import { remoteMethods } from "@deepseek-ai/dsh-typert-protocol"; +import { afterEach, describe, expect, it } from "vitest"; -import { describe, expect, it } from "vitest"; +import { disposeMounted, mountPlugin, until } from "./support/composition.ts"; +import { + GoUsageService, + ModelPurgeService, + OpencodeStoreService, + parseAccountRef, + parsePurgeResult, + parseStoreInspection, + parseUsageQuery, + parseUsageReading, + patchRemote, + REMOTE_CONTRACTS, + usageRemote, +} from "./support/src.ts"; -import { patchRemote } from "./support/src.ts"; +/** The prototype key `remoteMethods()` reads, as the services spell it. */ +const REMOTE_METHOD_DESCRIPTOR_KEY = + "@deepseek-ai/dsh-typert-protocol/remote-methods"; -const SRC = join(import.meta.dirname, "..", "src"); +afterEach(async () => { + await disposeMounted(); +}); -/** Every `export const NAME = "value"` in `src/`, so a constant resolves. */ -const exportedStrings = (): Map => { - const constants = new Map(); - for (const file of readdirSync(SRC).filter((name) => name.endsWith(".ts"))) { - const source = readFileSync(join(SRC, file), "utf8"); - for (const match of source.matchAll( - /export const ([A-Z_][A-Z0-9_]*)\s*=\s*"([^"]+)"/gu - )) { - if (match[1] !== undefined && match[2] !== undefined) { - constants.set(match[1], match[2]); - } - } - } - return constants; +/** The service the composition resolves for a namespace, if any. */ +const serviceOn = ( + ctx: { get: (name: never) => unknown }, + namespace: string +): Record | undefined => { + const service: unknown = ctx.get(namespace as never); + return typeof service === "object" && service !== null + ? (service as Record) + : undefined; }; -/** One remote service the host mounts: its file, class and namespace. */ -interface HostService { - readonly file: string; - readonly className: string; - readonly namespace: string; -} +describe("remote contract · host and client agree", () => { + it("lists the three contracts, so the checks below are not vacuous", () => { + expect(REMOTE_CONTRACTS.map((contract) => contract.namespace)).toEqual([ + "opencodeGoUsage", + "opencodeModelPurge", + "opencodeStore", + ]); + }); -/** - * Every remote service the host mounts, with the namespace it mounts under. - * - * Read from the source rather than imported: the services publish their - * namespace through `super(ctx, name)`, and instantiating them needs a cordis - * context. The name may be a literal or an exported constant, and both resolve: - * matching only the literal let `opencodeStore` — passed as `STORE_NAMESPACE` — - * through with no client descriptor, and the card's inspection row could never - * answer. - */ -const hostServices = (): HostService[] => { - const constants = exportedStrings(); - const services: HostService[] = []; - for (const file of readdirSync(SRC).filter((name) => name.endsWith(".ts"))) { - const source = readFileSync(join(SRC, file), "utf8"); - const className = /export class (\w+) extends TypertRemoteService/u.exec( - source - )?.[1]; - const argument = - /super\(\s*ctx\s+as\s+never\s*,\s*("([^"]+)"|[A-Z_][A-Z0-9_]*)\s*\)/u.exec( - source - ); - if (className === undefined || argument === null) { - continue; + it("registers exactly the contracts' descriptors on the client", () => { + const expected = REMOTE_CONTRACTS.flatMap( + (contract) => contract.descriptors + ); + expect(patchRemote.descriptors).toEqual(expected); + for (const [index, descriptor] of patchRemote.descriptors.entries()) { + // The contract's own object, not a copy that could drift from it. + expect(descriptor).toBe(expected[index]); } - const namespace = - argument[2] ?? - constants.get(argument[1] ?? "") ?? - `unresolved:${argument[1]}`; - services.push({ className, file, namespace }); - } - return services.toSorted((a, b) => a.namespace.localeCompare(b.namespace)); -}; - -const hostNamespaces = (): string[] => - hostServices().map((service) => service.namespace); - -/** The prototype key `remoteMethods()` reads, as the services spell it. */ -const REMOTE_METHOD_DESCRIPTOR_KEY = - "@deepseek-ai/dsh-typert-protocol/remote-methods"; - -describe("remote contract · host and client agree", () => { - it("finds the host namespaces, so the check is not vacuous", () => { - // A grep that matches nothing is indistinguishable from a clean result; - // these two are the services this plugin mounts today. - expect(hostNamespaces()).toContain("opencodeGoUsage"); - expect(hostNamespaces()).toContain("opencodeModelPurge"); - expect(hostNamespaces()).toContain("opencodeStore"); - expect( - hostNamespaces().filter((name) => name.startsWith("unresolved:")) - ).toEqual([]); + expect(patchRemote.package).toBe("dsh-opencode-patch"); }); - it("registers a descriptor for every Remote METHOD each service declares", async () => { + it("mounts a service for every contract, carrying exactly its methods, each one it can answer", async () => { // Per method, not per namespace: a namespace with one descriptor and a - // second declared method would pass the namespace check and still leave - // the second unreachable. - const declared = new Set( - patchRemote.descriptors.map((d) => `${d.service}.${d.method}`) - ); - const missing: string[] = []; - let methods = 0; - for (const service of hostServices()) { - const module = (await import(join(SRC, service.file))) as Record< - string, - { prototype: Record } - >; - const marker = module[service.className]?.prototype[ - REMOTE_METHOD_DESCRIPTOR_KEY - ] as { methods?: readonly { method: string }[] } | undefined; - for (const { method } of marker?.methods ?? []) { - methods += 1; - if (!declared.has(`${service.namespace}.${method}`)) { - missing.push(`${service.namespace}.${method}`); - } + // second declared method would pass a namespace check and still leave the + // second unreachable. Read through the host's own `remoteMethods()`. + const { ctx } = await mountPlugin({ config: { usageEnabled: true } }); + for (const contract of REMOTE_CONTRACTS) { + await until( + () => serviceOn(ctx, contract.namespace) !== undefined, + `ctx.get('${contract.namespace}')` + ); + const service = serviceOn(ctx, contract.namespace); + expect( + (service?.typertRemote as { namespace?: unknown } | undefined) + ?.namespace, + contract.namespace + ).toBe(contract.namespace); + expect( + remoteMethods(service as never).map(({ method }) => method), + contract.namespace + ).toEqual(Object.keys(contract.methods)); + // The marker is written FROM the contract, so the list above is equal by + // construction; this is what says the service can answer each method, + // should a cast defeat `markRemote`'s compile-time check. + for (const method of Object.keys(contract.methods)) { + expect( + typeof service?.[method], + `${contract.namespace}.${method}` + ).toBe("function"); } } - // Every service declares at least one method, so a marker read that found - // nothing would show here rather than as a clean pass. - expect(methods).toBeGreaterThanOrEqual(hostServices().length); - expect(missing).toEqual([]); }); - it("registers a descriptor for every namespace the host mounts", () => { - const mounted = new Set( - patchRemote.descriptors.map((descriptor) => descriptor.service) + it("mounts no remote service outside the contracts", async () => { + // A tripwire on the installer's own report, not a proof: every service + // `installRemoteService` mounts says it "is reachable with a typertRemote + // binding", once, and there must be exactly one such line per contract. A + // reworded report fails this loudly; a service mounted some other way + // would not be seen. + const { lines } = await mountPlugin({ config: { usageEnabled: true } }); + const reachable = (): string[] => + lines().filter((line) => + /is reachable with a typertRemote binding/u.test(line) + ); + await until( + () => reachable().length >= REMOTE_CONTRACTS.length, + "every remote service's report" ); - const missing = hostNamespaces().filter((name) => !mounted.has(name)); - expect(missing).toEqual([]); - }); - - it("registers nothing the host does not mount", () => { - // The other direction: a descriptor for an unmounted service is a namespace - // the browser can address and the host cannot answer. - const host = new Set(hostNamespaces()); - const orphaned = [ - ...new Set(patchRemote.descriptors.map((d) => d.service)), - ].filter((name) => !host.has(name)); - expect(orphaned).toEqual([]); + expect(reachable()).toHaveLength(REMOTE_CONTRACTS.length); + for (const contract of REMOTE_CONTRACTS) { + expect( + reachable().filter((line) => line.includes(`${contract.namespace} is`)) + ).toHaveLength(1); + } }); it("namespaces every descriptor uniquely and under one package", () => { @@ -163,6 +146,17 @@ describe("remote contract · host and client agree", () => { expect(ids).toContain("dsh-opencode-patch#opencodeGoUsage/readAccount"); }); + it("parses both usage reads' answers with the reading parser (D5), not the vendor whitelist", () => { + // `parseGoUsage` drops `allowance`, `quotaUnavailable` and the session's + // plane spend, which the service attaches and the panel renders. + expect(usageRemote.methods.read.result.schema.parse).toBe( + parseUsageReading + ); + expect(usageRemote.methods.readAccount.result.schema.parse).toBe( + parseUsageReading + ); + }); + it("gives every wire codec one parser, whichever door the runtime takes", () => { // A codec answers its parser twice: as `schema.parse`, and from `create()`. // A runtime that builds a fresh codec per call takes the second door, so a @@ -193,3 +187,181 @@ describe("remote contract · host and client agree", () => { } }); }); + +/** One wire codec, as a descriptor carries it. */ +interface WireCodec { + readonly create: () => { readonly parse: unknown }; + readonly mode: string; + readonly schema: { readonly parse: unknown }; + readonly typeSymbol: string; +} + +/** One descriptor, read as plain data: the fields the pin below names. */ +interface WireDescriptor { + readonly id: string; + readonly invocation: unknown; + readonly method: string; + readonly namespace: string; + readonly parameters: readonly (Record & { + readonly codec: WireCodec; + })[]; + readonly result: WireCodec; + readonly service: string; +} + +/** The client's descriptors, typed as the wire data they are. */ +const wireDescriptors = (): readonly WireDescriptor[] => + // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- the protocol types a descriptor's codecs opaquely; the pin reads them as the plain objects they are + patchRemote.descriptors as unknown as readonly WireDescriptor[]; + +/** A descriptor as plain data, each codec replaced by its `typeSymbol`. */ +const plain = (descriptor: WireDescriptor): Record => ({ + ...descriptor, + parameters: descriptor.parameters.map((parameter) => ({ + ...parameter, + codec: parameter.codec.typeSymbol, + })), + result: descriptor.result.typeSymbol, +}); + +describe("remote contract · the wire, pinned field for field", () => { + it("pins every descriptor field for field, so a rebuilt contract cannot drift", () => { + // The descriptors are what the client's gateway mounts and validates + // arity against, so a builder that derives them has to answer exactly + // these: the same ids, the same one optional parameter, and no + // `acceptsUndefined` key on a required one. + const descriptors = wireDescriptors(); + expect(descriptors.map((descriptor) => plain(descriptor))).toEqual([ + { + id: "dsh-opencode-patch#opencodeGoUsage/read", + invocation: { kind: "direct" }, + method: "read", + namespace: "opencodeGoUsage", + parameters: [ + { + acceptsUndefined: true, + codec: "dsh-opencode-patch#UsageQuery", + name: "query", + source: "json", + wire: "query", + }, + ], + result: "dsh-opencode-patch#GoUsage", + service: "opencodeGoUsage", + }, + { + id: "dsh-opencode-patch#opencodeGoUsage/readAccount", + invocation: { kind: "direct" }, + method: "readAccount", + namespace: "opencodeGoUsage", + parameters: [ + { + codec: "dsh-opencode-patch#AccountRef", + name: "ref", + source: "json", + wire: "ref", + }, + ], + result: "dsh-opencode-patch#GoUsage", + service: "opencodeGoUsage", + }, + { + id: "dsh-opencode-patch#opencodeModelPurge/purge", + invocation: { kind: "direct" }, + method: "purge", + namespace: "opencodeModelPurge", + parameters: [], + result: "dsh-opencode-patch#PurgeResult", + service: "opencodeModelPurge", + }, + { + id: "dsh-opencode-patch#opencodeStore/inspect", + invocation: { kind: "direct" }, + method: "inspect", + namespace: "opencodeStore", + parameters: [], + result: "dsh-opencode-patch#OpencodeStoreInspection", + service: "opencodeStore", + }, + ]); + + // Exact key sets: `toEqual` ignores an `undefined`-valued key, and a + // present `acceptsUndefined: undefined` is not the absent key. + for (const descriptor of descriptors) { + expect(Object.keys(descriptor).toSorted()).toEqual([ + "id", + "invocation", + "method", + "namespace", + "parameters", + "result", + "service", + ]); + const codecs = [ + descriptor.result, + ...descriptor.parameters.map((parameter) => parameter.codec), + ]; + for (const codec of codecs) { + expect(Object.keys(codec).toSorted()).toEqual([ + "create", + "mode", + "schema", + "typeSymbol", + ]); + expect(codec.mode).toBe("strict"); + } + } + const [read, readAccount, purge, inspect] = descriptors; + expect(Object.keys(readAccount?.parameters[0] ?? {}).toSorted()).toEqual([ + "codec", + "name", + "source", + "wire", + ]); + + // One result codec for both usage reads, and each other parser is the + // contract's own. (The usage RESULT parser's identity is not pinned: P9 + // swaps it for the reading parser, which the wire never runs.) + expect(read?.result).toBe(readAccount?.result); + expect(read?.parameters[0]?.codec.schema.parse).toBe(parseUsageQuery); + expect(readAccount?.parameters[0]?.codec.schema.parse).toBe( + parseAccountRef + ); + expect(purge?.result.schema.parse).toBe(parsePurgeResult); + expect(inspect?.result.schema.parse).toBe(parseStoreInspection); + }); + + it.each([ + { methods: ["read", "readAccount"], Service: GoUsageService }, + { methods: ["purge"], Service: ModelPurgeService }, + { methods: ["inspect"], Service: OpencodeStoreService }, + ])( + "pins the Remote marker $Service.name carries, as the host's reader sees it", + ({ methods, Service }) => { + // The marker `remoteMethods()` reads off the prototype, as `@Remote()` + // would write it: non-enumerable, read-only, frozen, version 1. + const descriptor = Reflect.getOwnPropertyDescriptor( + Service.prototype, + REMOTE_METHOD_DESCRIPTOR_KEY + ); + expect(descriptor).toMatchObject({ + configurable: true, + enumerable: false, + writable: false, + }); + const value: unknown = descriptor?.value; + expect(value).toEqual({ + version: 1, + methods: methods.map((method) => ({ + method, + invocation: { kind: "direct" }, + })), + }); + expect(Object.keys(value as object)).toEqual(["version", "methods"]); + expect(Object.isFrozen(value)).toBe(true); + expect(Object.isFrozen((value as { methods: unknown }).methods)).toBe( + true + ); + } + ); +}); diff --git a/test/remote-define.test.ts b/test/remote-define.test.ts new file mode 100644 index 00000000..743803e6 --- /dev/null +++ b/test/remote-define.test.ts @@ -0,0 +1,107 @@ +/** + * The contract builder: what `defineRemote` and `remoteValue` derive from a + * namespace and its methods. + * + * `test/remote-contract.test.ts` pins the plugin's own three contracts field + * for field; this file holds the builder to its rules on a probe contract, so + * every branch it has is driven here. + * + * @module test/remote-define.test + */ +import { describe, expect, it } from "vitest"; + +import { defineRemote, REMOTE_PACKAGE, remoteValue } from "./support/src.ts"; + +const parseText = (value: unknown): string | undefined => + typeof value === "string" ? value : undefined; +const parseCount = (value: unknown): number => { + if (typeof value !== "number") { + throw new TypeError("not a count"); + } + return value; +}; + +const text = remoteValue("Text", parseText); +const count = remoteValue("Count", parseCount); + +const probe = defineRemote("probeNamespace", { + first: { + parameters: [ + { name: "query", optional: true, value: text }, + { name: "limit", value: count }, + ], + result: count, + }, + second: { result: text }, +}); + +describe("remoteValue", () => { + it("names the type under the package and puts one parser behind both doors", () => { + expect(text.typeSymbol).toBe("dsh-opencode-patch#Text"); + expect(text.mode).toBe("strict"); + expect(text.schema.parse).toBe(parseText); + expect(text.create().parse).toBe(parseText); + expect(Object.keys(text).toSorted()).toEqual([ + "create", + "mode", + "schema", + "typeSymbol", + ]); + }); + + it("answers a fresh codec per call", () => { + expect(remoteValue("Text", parseText)).not.toBe(text); + }); +}); + +describe("defineRemote", () => { + it("derives one descriptor per method, in the order the methods are listed", () => { + expect(probe.descriptors.map((descriptor) => descriptor.method)).toEqual([ + "first", + "second", + ]); + for (const descriptor of probe.descriptors) { + expect(descriptor.id).toBe( + `dsh-opencode-patch#probeNamespace/${descriptor.method}` + ); + expect(descriptor.namespace).toBe("probeNamespace"); + expect(descriptor.service).toBe("probeNamespace"); + expect(descriptor.invocation).toEqual({ kind: "direct" }); + } + }); + + it("marks only an optional parameter as accepting undefined, and wires each by its name", () => { + const [first] = probe.descriptors; + const [query, limit] = first?.parameters ?? []; + expect(query).toEqual({ + acceptsUndefined: true, + codec: text, + name: "query", + source: "json", + wire: "query", + }); + // No key at all, not `acceptsUndefined: undefined`. + expect(Object.keys(limit ?? {}).toSorted()).toEqual([ + "codec", + "name", + "source", + "wire", + ]); + expect(limit?.codec).toBe(count); + expect(first?.result).toBe(count); + }); + + it("gives a method with no parameters an empty list", () => { + const [, second] = probe.descriptors; + expect(second?.parameters).toEqual([]); + expect(second?.result).toBe(text); + }); + + it("keeps the namespace, the methods and the package beside the descriptors", () => { + expect(probe.namespace).toBe("probeNamespace"); + expect(Object.keys(probe.methods)).toEqual(["first", "second"]); + expect(probe.methods.second.result).toBe(text); + expect(probe.package).toBe(REMOTE_PACKAGE); + expect(REMOTE_PACKAGE).toBe("dsh-opencode-patch"); + }); +}); diff --git a/test/remote-seam.test.ts b/test/remote-seam.test.ts new file mode 100644 index 00000000..4bd83b7a --- /dev/null +++ b/test/remote-seam.test.ts @@ -0,0 +1,321 @@ +/** + * Each remote's answer, carried to its client caller whole. + * + * The host services and the card's callers are tested apart, each against + * shapes its own file builds; this file joins them. A real service answers, + * the answer crosses the seam as the gateway's `{ ok, value | error }` + * envelope (through a JSON round trip, or a structured clone, as the wire + * would carry it), and the caller's outcome is asserted against the service's + * own answer. So a client-side parser that drops a field the service sends + * (the usage reading's `allowance`, its plane spend, the overflow floor's + * `quotaUnavailable`) fails here, whichever side moved. + * + * The store and usage cases were written on the base of P9 (the remote seam), + * before the seam was rebuilt, and green there. The two purge cases were + * rewritten afterwards to run the real `ModelPurgeService`, and the whole file + * was then run green on the base, with a control that fails there + * (docs/improvement-plan.md, P9). The file is the pin the refactor is held to. + * + * @module test/remote-seam.test + */ +import { Context } from "@deepseek-ai/cordis"; +import { RemoteError } from "@deepseek-ai/dsh-typert-protocol"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { + createOpencodeStore, + type FixtureStore, +} from "./support/opencode-store-fixture.ts"; +import { + clearSessionUsageStore, + findModelSpecOn, + GO_MODEL_LIMITS, + inspectStore, + OpencodeStoreService, + ModelPurgeService, + parseFailure, + parseModelsDevCatalog, + purgeDeprecatedModels, + readGoUsage, + recordTurnUsage, +} from "./support/src.ts"; +import { + okBody, + serviceWithKey, + serviceWithoutKey, + stubFetch, +} from "./support/usage-fixture.ts"; + +const stores: FixtureStore[] = []; + +afterEach(() => { + vi.unstubAllGlobals(); + delete process.env.OPENCODE_API_KEY; + delete process.env.OPENCODE_GO_API_KEY; + clearSessionUsageStore(); + for (const store of stores.splice(0)) { + store.cleanup(); + } +}); + +/** The database path inside a fixture's data root. */ +const databaseOf = (store: FixtureStore): string => + `${store.root}/opencode/opencode.db`; + +/** + * What the wire does to a value: a JSON round trip, which (unlike a + * structured clone) drops an `undefined`-valued key, as the gateway's + * transport does. + */ +const overTheWire = (value: Value): Value => + // oxlint-disable-next-line unicorn/prefer-structured-clone -- the JSON round trip IS the wire being modelled + JSON.parse(JSON.stringify(value)) as Value; + +/** + * A Go model the generated limits table prices, picked by shape so a refresh + * of the table cannot fail a case: the one an attached allowance names. + */ +const pricedGoModel = (): string => { + for (const [id, row] of Object.entries(GO_MODEL_LIMITS)) { + if (Number.isFinite(row.go) && findModelSpecOn("go", id) !== undefined) { + return id; + } + } + throw new Error("no priced limits row the Go catalog lists"); +}; + +describe("remote seam · store: the service's inspection reaches the card whole", () => { + it("carries an account with every summary field", async () => { + const expires = Date.now() + 86_400_000; + const store = createOpencodeStore( + [ + { + integrationId: "opencode", + label: "Default", + value: JSON.stringify({ + access: "st_fixture_access", + expires, + metadata: { email: "someone@example.com", orgName: "Fixture Org" }, + refresh: "rt_fixture_refresh", + type: "oauth", + }), + }, + ], + { + accessToken: "st_fixture_access", + email: "someone@example.com", + refreshToken: "rt_fixture_refresh", + tokenExpiry: expires, + } + ); + stores.push(store); + const service = new OpencodeStoreService(new Context(), { + resolveStorePath: () => databaseOf(store), + }); + const answer = await service.inspect(); + // Non-vacuous: the fixture fills every field the summary can carry. + expect(answer.account).toMatchObject({ + accountId: expect.any(String), + email: "someone@example.com", + expired: false, + expiresAt: expect.any(String), + label: "Default", + orgName: "Fixture Org", + refreshable: true, + type: "oauth", + }); + await expect( + inspectStore({ + remote: { + opencodeStore: { + inspect: async () => ({ ok: true, value: structuredClone(answer) }), + }, + }, + }) + ).resolves.toEqual({ inspection: answer, kind: "inspected" }); + }); + + it("carries a missing installation with its message and shown path", async () => { + const store = createOpencodeStore([]); + stores.push(store); + const service = new OpencodeStoreService(new Context(), { + resolveStorePath: () => `${store.root}/absent/opencode.db`, + }); + const answer = await service.inspect(); + expect(answer).toMatchObject({ found: false, message: "not_found" }); + await expect( + inspectStore({ + remote: { + opencodeStore: { + inspect: async () => ({ ok: true, value: structuredClone(answer) }), + }, + }, + }) + ).resolves.toEqual({ inspection: answer, kind: "inspected" }); + }); +}); + +describe("remote seam · usage: the service's reading reaches the settings summary whole", () => { + /** A scope whose `opencodeGoUsage.read` answers with `answer`. */ + const scopeWith = (answer: () => Promise): unknown => ({ + remote: { opencodeGoUsage: { read: answer } }, + }); + + it("keeps the allowance and the session's plane spend", async () => { + const model = pricedGoModel(); + recordTurnUsage( + "s-seam", + { inputTokens: 10, outputTokens: 20, totalTokens: 30 }, + { input: 1, output: 2 }, + model, + false, + "go" + ); + stubFetch(() => new Response(okBody())); + const answer = await serviceWithKey("sk-live-key").read({ + model, + provider: "opencode-go", + sessionId: "s-seam", + }); + // Non-vacuous: the fields a vendor-payload whitelist would drop are here. + expect(answer.allowance).toBeDefined(); + expect(answer.session?.planeCostFormatted).toBeDefined(); + expect(answer.session?.planeSpendUsd).toBeDefined(); + await expect( + readGoUsage( + scopeWith(async () => ({ ok: true, value: overTheWire(answer) })) + ) + ).resolves.toEqual(answer); + }); + + it("keeps the overflow floor's quotaUnavailable flag", async () => { + process.env.OPENCODE_API_KEY = "oc_sk_zen-key"; + stubFetch( + () => + new Response( + '{"error":{"code":"EntitlementError","message":"no Go subscription"}}', + { status: 403 } + ) + ); + const answer = await serviceWithKey("sk-live-key").read(); + expect(answer.quotaUnavailable).toBe(true); + expect(answer.zenOverflow).toBe(true); + await expect( + readGoUsage( + scopeWith(async () => ({ ok: true, value: overTheWire(answer) })) + ) + ).resolves.toEqual(answer); + }); + + it("rejects with the service's own RemoteError, which the pill reads as unconfigured", async () => { + const error: unknown = await serviceWithoutKey() + .read() + .catch((error_: unknown) => error_); + expect(error).toBeInstanceOf(RemoteError); + await expect( + readGoUsage(scopeWith(async () => ({ error, ok: false }))) + ).rejects.toBe(error); + expect(parseFailure(error)).toEqual({ + configured: false, + message: "OpenCode Go API key is not configured", + reason: undefined, + retainPrevious: false, + source: undefined, + }); + }); +}); + +describe("remote seam · purge: a result and the host's refusal reach the card as the same outcome", () => { + const scopeWith = (purge: () => Promise): unknown => ({ + remote: { opencodeModelPurge: { purge } }, + }); + + /** One retired id, referenced at every site the purge strips. */ + const registry = { + opencode: { + models: { + "live-free": { limit: { context: 1000 }, name: "Live" }, + "retired-free": { status: "deprecated" }, + }, + }, + }; + + /** A config editor that applies each change to the entry it was handed. */ + const editorOver = ( + entries: readonly { options: { config: unknown } }[] + ) => ({ + edit: async ( + entry: unknown, + change: (current: Record) => Record + ) => { + const holder = entry as { options: { config: Record } }; + holder.options.config = change(holder.options.config); + }, + entries: () => entries, + }); + + it("carries the service's result, with every site it reports", async () => { + parseModelsDevCatalog(registry); + vi.stubGlobal("fetch", async () => ({ + json: async () => registry, + ok: true, + })); + const ctx = new Context(); + ctx.provide( + "configEditor" as never, + editorOver([ + { + options: { + config: { + providers: { + opencode: { + models: [{ id: "retired-free" }, { id: "live-free" }], + }, + }, + }, + }, + }, + { + options: { + config: { + allowedModels: [{ model: "retired-free", provider: "opencode" }], + }, + }, + }, + { + options: { + config: { + summarizationModel: "retired-free", + summarizationProvider: "opencode", + }, + }, + }, + ]) as never + ); + const result = await new ModelPurgeService(ctx).purge(); + // The fixture reaches every site, so the case is not vacuous. + expect(result.removed.map((row) => row.site)).toEqual([ + undefined, + "subagent", + "summarizer", + ]); + await expect( + purgeDeprecatedModels( + scopeWith(async () => ({ ok: true, value: overTheWire(result) })) + ) + ).resolves.toEqual({ kind: "purged", result: overTheWire(result) }); + }); + + it("carries the service's own refusal in its own words", async () => { + const error: unknown = await new ModelPurgeService(new Context()) + .purge() + .catch((error_: unknown) => error_); + expect(error).toBeInstanceOf(RemoteError); + await expect( + purgeDeprecatedModels(scopeWith(async () => ({ error, ok: false }))) + ).resolves.toEqual({ + kind: "failed", + message: (error as Error).message, + }); + }); +}); diff --git a/test/remote-service.test.ts b/test/remote-service.test.ts index 76fe742d..0270a8f7 100644 --- a/test/remote-service.test.ts +++ b/test/remote-service.test.ts @@ -15,14 +15,20 @@ * @module test/remote-service.test */ import { Context, type Fiber } from "@deepseek-ai/cordis"; -import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol"; +import { + remoteMethods, + TypertRemoteService, +} from "@deepseek-ai/dsh-typert-protocol"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { logLines } from "./support/cordis-wait.ts"; import { type CordisContext, + defineRemote, installRemoteService, + markRemote, type RemoteContract, + remoteValue, } from "./support/src.ts"; interface ProbeOptions { @@ -600,3 +606,86 @@ describe("installRemoteService · stand-in compositions", () => { expect({ ...view }).toEqual({ value: "a" }); }); }); + +describe("markRemote", () => { + const KEY = "@deepseek-ai/dsh-typert-protocol/remote-methods"; + const text = remoteValue("Text", (value: unknown) => + typeof value === "string" ? value : undefined + ); + + /** + * A fresh service class answering two methods, one per case, so no case + * reads a marker another case wrote. + */ + const markedClass = () => + class Marked extends TypertRemoteService { + constructor(ctx: unknown) { + super(ctx as never, "markedRemote"); + } + + second(): Promise { + return Promise.resolve("second"); + } + + first(): Promise { + return Promise.resolve("first"); + } + }; + + it("declares the contract's methods, in the contract's order, as the host's reader sees them", () => { + const Marked = markedClass(); + markRemote( + Marked, + defineRemote("markedRemote", { + first: { result: text }, + second: { result: text }, + }) + ); + expect(remoteMethods(new Marked(new Context()))).toEqual([ + { invocation: { kind: "direct" }, method: "first" }, + { invocation: { kind: "direct" }, method: "second" }, + ]); + const descriptor = Reflect.getOwnPropertyDescriptor(Marked.prototype, KEY); + expect(descriptor).toMatchObject({ + configurable: true, + enumerable: false, + writable: false, + }); + const value = descriptor?.value as { + methods: unknown; + version: unknown; + }; + expect(value.version).toBe(1); + expect(Object.isFrozen(value)).toBe(true); + expect(Object.isFrozen(value.methods)).toBe(true); + }); + + it("replaces the list when marked again with another contract", () => { + const Marked = markedClass(); + const methodsOf = () => + remoteMethods(new Marked(new Context())).map(({ method }) => method); + markRemote( + Marked, + defineRemote("markedRemote", { + first: { result: text }, + second: { result: text }, + }) + ); + expect(methodsOf()).toEqual(["first", "second"]); + markRemote( + Marked, + defineRemote("markedRemote", { second: { result: text } }) + ); + expect(methodsOf()).toEqual(["second"]); + }); + + it("refuses, at compile time, a contract method the class does not implement", () => { + const Marked = markedClass(); + const missing = defineRemote("markedRemote", { third: { result: text } }); + // @ts-expect-error -- `Marked` has no `third`: the marker would declare a method the gateway cannot call + markRemote(Marked, missing); + expect( + remoteMethods(new Marked(new Context())).map(({ method }) => method) + ).toEqual(["third"]); + }); +}); diff --git a/test/settings-page.test.tsx b/test/settings-page.test.tsx index d170ed98..089269d0 100644 --- a/test/settings-page.test.tsx +++ b/test/settings-page.test.tsx @@ -11,10 +11,12 @@ import { describe, expect, it, vi } from "vitest"; import { applySettingsPage as apply, + type GoUsage, LEGACY_NS, NS, PKG, SCOPED_PKG, + type SessionUsageSnapshot, } from "./support/src.ts"; describe("settings-page: apply & slots", () => { @@ -432,6 +434,57 @@ describe("settings-page: apply & slots", () => { }); }); + it("reads a meter scope whose `get` misses and whose `remote` getter throws as no usage service", () => { + // The caller-level half of `findRemoteCall`'s guard. The base read + // `remoteNamespaceOf(meterScope, …) ?? remoteNamespace(meterScope.remote, …)` + // with the right side unguarded, so this scope threw out of the dock + // injector. The meter scope is its own object: the root context keeps a + // plain `remote`, so the mount's own read is not what is under test. + let dockInjector: ((sessionId: unknown) => unknown) | undefined; + let remoteReads = 0; + const slots = { + inject: (_name: string, fn: () => void) => fn(), + register: (entry: Record) => { + if (entry.name === "conversation.input.right") { + dockInjector = entry.inject as (s: unknown) => unknown; + } + }, + }; + const meterScope = { + get: () => {}, + modelDirectories: { directoryFor: () => ({ store: {} }) }, + slots, + get remote(): never { + remoteReads += 1; + throw new TypeError('cannot get property "remote" without inject'); + }, + }; + const ctx = { + effect: (fn: () => unknown) => fn(), + inject: (_deps: string[], callback: (scope: unknown) => unknown) => + callback(meterScope), + remote: {}, + slots, + }; + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + expect(() => apply(ctx as never)).not.toThrow(); + expect(dockInjector).toBeTypeOf("function"); + let answer: unknown; + expect(() => { + answer = dockInjector?.("session"); + }).not.toThrow(); + expect(answer).toMatchObject({ + reason: expect.stringContaining("no usage service"), + }); + // The getter was actually reached: the case exercises the guard, not a + // path that never read `remote`. + expect(remoteReads).toBeGreaterThan(0); + } finally { + warn.mockRestore(); + } + }); + it("registers the meter once per slot registry, so a second activation cannot throw", () => { // The host may run a plugin's client entry more than once in a page's life. // The slot registry THROWS on a duplicate id @@ -808,3 +861,122 @@ describe("settings-page: apply & slots", () => { expect(() => apply(ctx as never)).not.toThrow(); }); }); + +describe("settings-page: the meter's read, pinned before the remote seam", () => { + /** The meter's `readUsage`, over a remote whose `read` is `read`. */ + const meterOver = ( + read: () => Promise + ): ((provider?: string, model?: string) => Promise) => { + let dockInjector: ((sessionId: unknown) => unknown) | undefined; + const ctx = { + effect: (fn: () => unknown) => fn(), + modelDirectories: { directoryFor: () => ({ store: {} }) }, + remote: { opencodeGoUsage: { read } }, + slots: { + inject: (_name: string, fn: () => void) => fn(), + register: (entry: Record) => { + if (entry.name === "conversation.input.right") { + dockInjector = entry.inject as (s: unknown) => unknown; + } + }, + }, + }; + apply(ctx as never); + const injected = dockInjector?.("valid") as { + readUsage: (provider?: string, model?: string) => Promise; + }; + expect(injected.readUsage).toBeTypeOf("function"); + return injected.readUsage; + }; + + /** Every field of a session snapshot, `Required` so a new one must appear. */ + const session: Required = { + activeModel: "go-model-x", + activeModelName: "Go Model X", + activeRateFormatted: "$1 / $2 per 1M", + cacheReadTokens: 5, + costByPlane: { go: 0.25, zen: 0.5 }, + costFormatted: "$0.75", + costUsd: 0.75, + freeModel: true, + inputTokens: 100, + modelsUsed: ["go-model-x"], + outputTokens: 200, + planeCostFormatted: "$0.25", + planeSpendUsd: 0.25, + totalTokens: 305, + turns: 2, + }; + + /** Every field of a reading, `Required` for the same reason. */ + const full: Required = { + allowance: { go: 12, goPlus: 48, model: "Go Model X" }, + monthly: { percent: 14, resetsAt: "2026-11-07T00:55:00Z", status: "ok" }, + quotaUnavailable: true, + rolling: { percent: 0, resetsAt: "2026-10-09T06:00:00Z", status: "ok" }, + session, + source: "opencode-go", + weekly: { + percent: 100, + resetsAt: "2026-10-12T00:00:00Z", + status: "rate-limited", + }, + zenOverflow: true, + }; + + it("hands the pill a complete reading whole, and an empty envelope as nothing", async () => { + const readUsage = meterOver(async () => ({ ok: true, value: full })); + await expect(readUsage("opencode-go", "m")).resolves.toEqual(full); + const empty = meterOver(async () => ({ ok: true })); + await expect(empty()).resolves.toBeUndefined(); + }); +}); + +describe("settings-page: the meter's read through the one unwrap (P9), on readings the Host does not send", () => { + const reading = { + monthly: { percent: 14, resetsAt: "2026-11-07T00:55:00Z", status: "ok" }, + rolling: { percent: 0, resetsAt: "2026-10-09T06:00:00Z", status: "ok" }, + weekly: { percent: 28, resetsAt: "2026-10-12T00:00:00Z", status: "ok" }, + }; + + /** The meter's `readUsage`, over a remote whose `read` answers `answer`. */ + const readUsageOver = (answer: unknown): (() => Promise) => { + let dockInjector: ((sessionId: unknown) => unknown) | undefined; + const ctx = { + effect: (fn: () => unknown) => fn(), + modelDirectories: { directoryFor: () => ({ store: {} }) }, + remote: { opencodeGoUsage: { read: async () => answer } }, + slots: { + inject: (_name: string, fn: () => void) => fn(), + register: (entry: Record) => { + if (entry.name === "conversation.input.right") { + dockInjector = entry.inject as (s: unknown) => unknown; + } + }, + }, + }; + apply(ctx as never); + const injected = dockInjector?.("valid") as { + readUsage: () => Promise; + }; + return injected.readUsage; + }; + + it("unifies a valid reading into the whitelisted copy", async () => { + await expect( + readUsageOver({ ok: true, value: { ...reading, extra: 1 } })() + ).resolves.toEqual(reading); + }); + + it("unifies a bare { value } into its value", async () => { + await expect(readUsageOver({ value: reading })()).resolves.toEqual(reading); + }); + + it("unwraps an invalid bare { value } too, and passes its payload through", async () => { + // The pass-through stays until P11; what reaches the pill is the payload, + // no longer the `{ value }` that carried it. + await expect(readUsageOver({ value: { rolling: {} } })()).resolves.toEqual({ + rolling: {}, + }); + }); +}); diff --git a/test/settings-purge.test.ts b/test/settings-purge.test.ts index 0be6a2a5..3dc95fc9 100644 --- a/test/settings-purge.test.ts +++ b/test/settings-purge.test.ts @@ -171,3 +171,97 @@ describe("purgeDeprecatedModels: the paths a scope can take", () => { } }); }); + +describe("purgeDeprecatedModels: the envelope shapes, pinned before the remote seam", () => { + it("reads a string error as the message, an empty ok envelope as not a result, and a value without ok as the result", async () => { + await expect( + purgeDeprecatedModels( + scopeWith(async () => ({ + error: "the profile is read-only", + ok: false, + })) + ) + ).resolves.toEqual({ kind: "failed", message: "the profile is read-only" }); + await expect( + purgeDeprecatedModels(scopeWith(async () => ({ ok: true }))) + ).resolves.toEqual({ + kind: "failed", + message: "the host answered something that is not a purge result", + }); + await expect( + purgeDeprecatedModels( + scopeWith(async () => ({ value: { catalogRead: true, removed: [] } })) + ) + ).resolves.toEqual({ + kind: "purged", + result: { catalogRead: true, removed: [] }, + }); + }); + + it("names the missing service on the console, once", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + await expect(purgeDeprecatedModels({ remote: {} })).resolves.toEqual({ + kind: "unavailable", + }); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith( + "[dsh-opencode-patch] purge: no opencodeModelPurge service on the remote" + ); + } finally { + warn.mockRestore(); + } + }); + + it("calls the purge with no argument, as its descriptor declares none", async () => { + // The client gateway validates arity: one argument to a zero-parameter + // method is refused before it leaves the browser. + const purge = vi.fn(async () => ({ + ok: true, + value: { catalogRead: true, removed: [] }, + })); + await purgeDeprecatedModels(scopeWith(purge)); + expect(purge).toHaveBeenCalledTimes(1); + expect(purge.mock.calls[0]).toHaveLength(0); + }); +}); + +describe("purgeDeprecatedModels: the one unwrap (P9), on shapes the host does not send", () => { + // A refusal nested INSIDE `value` is not a refusal the gateway can send: its + // `value` is the method's own result. The one unwrap reads the envelope + // once, so the nested shape is a payload, and not a purge result. + it("unifies a refusal nested inside value into not a purge result", async () => { + await expect( + purgeDeprecatedModels( + scopeWith(async () => ({ value: { message: "x", ok: false } })) + ) + ).resolves.toEqual({ + kind: "failed", + message: "the host answered something that is not a purge result", + }); + }); + + // On the base, `scope.remote` was read unguarded when `ctx.get` missed, so a + // getter that throws there rejected the purge. The seam reads it inside a + // guard: no remote, so "unavailable" with its console line. The host never + // builds this scope (every caller's scope declares `remote` in `inject`). + it("reads a throwing remote getter as no service when ctx.get misses", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const scope = { + get: () => {}, + get remote(): never { + throw new Error('cannot get property "remote" without inject'); + }, + }; + await expect(purgeDeprecatedModels(scope)).resolves.toEqual({ + kind: "unavailable", + }); + expect(warn).toHaveBeenCalledWith( + "[dsh-opencode-patch] purge: no opencodeModelPurge service on the remote" + ); + } finally { + warn.mockRestore(); + } + }); +}); diff --git a/test/settings-remote.test.ts b/test/settings-remote.test.ts index b63ce116..92e928b3 100644 --- a/test/settings-remote.test.ts +++ b/test/settings-remote.test.ts @@ -12,12 +12,17 @@ * * @module test/settings-remote.test */ -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { + callRemote, callUsageRead, + defineRemote, + findRemoteCall, remoteNamespace, remoteNamespaceOf, + remoteValue, + unwrapRemote, } from "./support/src.ts"; describe("settings-remote · remoteNamespaceOf", () => { @@ -142,3 +147,243 @@ describe("settings-remote · callUsageRead", () => { expect(seen).toHaveLength(1); }); }); + +/** + * A probe contract for the one unwrap: its parser answers `undefined` for a + * string, `null` for `null`, THROWS for `false`, and keeps a record's `n`. + */ +const parseProbe = (value: unknown): { n: number } | null | undefined => { + if (value === false) { + throw new TypeError("not a probe"); + } + if (value === null) { + return null; + } + return typeof value === "object" && + "n" in value && + typeof value.n === "number" + ? { n: value.n } + : undefined; +}; +const probe = defineRemote("probeRemote", { + read: { result: remoteValue("Probe", parseProbe) }, +}); + +describe("settings-remote · findRemoteCall", () => { + it("reads through ctx.get first, ahead of the property", () => { + const viaGet = async () => "get"; + const viaProperty = async () => "property"; + const scope = { + get: (name: string) => + name === "remote.probeRemote" ? { read: viaGet } : undefined, + remote: { probeRemote: { read: viaProperty } }, + }; + expect(findRemoteCall(scope, probe, "read")).toEqual({ call: viaGet }); + }); + + it("never reads the remote face when ctx.get resolves, so a throwing getter costs nothing", () => { + const read = async () => "get"; + let faceReads = 0; + const scope = { + get: (name: string) => + name === "remote.probeRemote" ? { read } : undefined, + get remote(): unknown { + faceReads += 1; + throw new Error('cannot get property "remote" without inject'); + }, + }; + expect(findRemoteCall(scope, probe, "read")).toEqual({ call: read }); + expect(faceReads).toBe(0); + }); + + it("reads a throwing remote getter as no remote when ctx.get misses", () => { + const scope = { + get: (): unknown => null, + get remote(): unknown { + throw new Error('cannot get property "remote" without inject'); + }, + }; + expect(findRemoteCall(scope, probe, "read")).toEqual({ + call: undefined, + exposed: [], + }); + }); + + it("falls back to the guarded property", () => { + const read = async () => "property"; + expect( + findRemoteCall({ remote: { probeRemote: { read } } }, probe, "read") + ).toEqual({ call: read }); + }); + + it("answers no call for a guarded read that throws", () => { + const remote = new Proxy( + {}, + { + get: (_target, property) => { + if (property === "probeRemote") { + throw new TypeError( + 'cannot get property "remote.probeRemote" without inject' + ); + } + }, + } + ); + expect(findRemoteCall({ remote }, probe, "read")).toEqual({ + call: undefined, + exposed: [], + }); + }); + + it("names the namespace's keys when the method is missing, and the remote's when the namespace is", () => { + expect( + findRemoteCall({ remote: { probeRemote: { peek: 1 } } }, probe, "read") + ).toEqual({ call: undefined, exposed: ["peek"] }); + expect( + findRemoteCall({ remote: { other: {}, more: {} } }, probe, "read") + ).toEqual({ call: undefined, exposed: ["other", "more"] }); + expect(findRemoteCall({ remote: "face" }, probe, "read")).toEqual({ + call: undefined, + exposed: [], + }); + }); + + it("answers no call and no keys for a scope that is not an object", () => { + for (const scope of [undefined, null, "scope", 42]) { + expect(findRemoteCall(scope, probe, "read")).toEqual({ + call: undefined, + exposed: [], + }); + } + }); +}); + +describe("settings-remote · unwrapRemote, the one unwrap", () => { + const failure = new Error("m"); + const blank = {}; + it.each<{ name: string; answer: unknown; expected: unknown }>([ + { + answer: { ok: true, value: { n: 1 } }, + expected: { kind: "ok", value: { n: 1 } }, + name: "an ok envelope is its parsed value", + }, + { + answer: { ok: true }, + expected: { kind: "invalid", value: undefined }, + name: "an ok envelope with no value is not one", + }, + { + answer: { error: failure, ok: false }, + expected: { error: failure, kind: "refused", reason: "m" }, + name: "a refusal carries its error and the error's message", + }, + { + answer: { error: "s", ok: false }, + expected: { error: "s", kind: "refused", reason: "s" }, + name: "a string error is its own reason", + }, + { + answer: { message: "e", ok: false }, + expected: { error: undefined, kind: "refused", reason: "e" }, + name: "an envelope message is the reason", + }, + { + answer: { error: failure, message: "e", ok: false }, + expected: { error: failure, kind: "refused", reason: "e" }, + name: "the envelope's message comes first", + }, + { + answer: { ok: false }, + expected: { error: undefined, kind: "refused", reason: undefined }, + name: "a bare refusal has no reason", + }, + { + answer: { error: blank, ok: false }, + expected: { error: blank, kind: "refused", reason: undefined }, + name: "an error with no message has no reason", + }, + { + answer: { n: 2 }, + expected: { kind: "ok", value: { n: 2 } }, + name: "a bare value is the payload", + }, + { + answer: { value: { n: 3 } }, + expected: { kind: "ok", value: { n: 3 } }, + name: "a value without ok is the payload", + }, + { + answer: 42, + expected: { kind: "invalid", value: 42 }, + name: "a payload the parser answers undefined for is invalid", + }, + { + answer: null, + expected: { kind: "invalid", value: null }, + name: "a payload the parser answers null for is invalid", + }, + { + answer: { value: { message: "x", ok: false } }, + expected: { kind: "invalid", value: { message: "x", ok: false } }, + name: "a refusal nested inside value is not read as one", + }, + { + answer: { ok: true, value: false }, + expected: { kind: "invalid", value: false }, + name: "a parser that throws makes the payload invalid", + }, + { + answer: { n: 4, ok: "yes" }, + expected: { kind: "ok", value: { n: 4 } }, + name: "an ok that is not a boolean is no envelope", + }, + ])("$name", ({ answer, expected }) => { + const unwrapped = unwrapRemote(probe, "read", answer); + expect(unwrapped).toEqual(expected); + if (unwrapped.kind === "refused" && isErrorCase(answer)) { + // The same object, not a copy: the caller rethrows it. + expect(unwrapped.error).toBe(answer.error); + } + }); +}); + +/** Whether an answer carries an `error` key to compare by identity. */ +const isErrorCase = (answer: unknown): answer is { error: unknown } => + typeof answer === "object" && answer !== null && "error" in answer; + +describe("settings-remote · callRemote", () => { + it("answers unavailable, with the exposed keys, when there is no call", async () => { + await expect( + callRemote({ remote: { other: {} } }, probe, "read") + ).resolves.toEqual({ exposed: ["other"], kind: "unavailable" }); + }); + + it("calls with NO argument when none is given, as the arity check requires", async () => { + const read = vi.fn(async () => ({ ok: true, value: { n: 5 } })); + await expect( + callRemote({ remote: { probeRemote: { read } } }, probe, "read") + ).resolves.toEqual({ kind: "ok", value: { n: 5 } }); + expect(read.mock.calls[0]).toHaveLength(0); + }); + + it("passes an argument as the one argument", async () => { + const read = vi.fn(async (_query?: unknown) => ({ n: 6 })); + await callRemote({ remote: { probeRemote: { read } } }, probe, "read", { + q: 1, + }); + expect(read.mock.calls[0]).toEqual([{ q: 1 }]); + }); + + it("rejects with the call's own rejection", async () => { + const error = new Error("the gateway said no"); + await expect( + callRemote( + { + remote: { probeRemote: { read: () => Promise.reject(error) } }, + }, + probe, + "read" + ) + ).rejects.toBe(error); + }); +}); diff --git a/test/settings-store.test.ts b/test/settings-store.test.ts index ab9517c2..6d039bc4 100644 --- a/test/settings-store.test.ts +++ b/test/settings-store.test.ts @@ -132,3 +132,86 @@ describe("inspectStore", () => { }); }); }); + +describe("inspectStore: the envelope shapes, pinned before the remote seam", () => { + it("names a refusal with no reason, an empty ok envelope, and accepts a value without ok", async () => { + for (const refusal of [{ ok: false }, { error: {}, ok: false }]) { + await expect( + inspectStore(scopeWith(async () => refusal)) + ).resolves.toEqual({ + kind: "failed", + message: "the host could not inspect the installation", + }); + } + await expect( + inspectStore(scopeWith(async () => ({ ok: true }))) + ).resolves.toEqual({ + kind: "failed", + message: "host returned an invalid inspection shape", + }); + await expect( + inspectStore(scopeWith(async () => ({ value: { found: false } }))) + ).resolves.toEqual({ inspection: { found: false }, kind: "inspected" }); + }); + + it("names the missing service on the console, once", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + await expect(inspectStore({ remote: {} })).resolves.toEqual({ + kind: "unavailable", + }); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith( + "[dsh-opencode-patch] store inspection: no opencodeStore service on the remote" + ); + } finally { + warn.mockRestore(); + } + }); + + it("calls the inspection with no argument, as its descriptor declares none", async () => { + const inspect = vi.fn(async () => ({ ok: true, value: { found: false } })); + await inspectStore(scopeWith(inspect)); + expect(inspect).toHaveBeenCalledTimes(1); + expect(inspect.mock.calls[0]).toHaveLength(0); + }); +}); + +describe("inspectStore: the one unwrap (P9), on shapes the host does not send", () => { + // The gateway answers a refusal as `{ ok: false, error: RemoteError }`; an + // envelope-level `message` or a string `error` is a shape only a test + // builds. The one unwrap reads every caller's refusal the same way, so the + // store now shows those words rather than its default sentence. + it("unifies an envelope message and a string error into the refusal's reason", async () => { + await expect( + inspectStore(scopeWith(async () => ({ message: "read-only", ok: false }))) + ).resolves.toEqual({ kind: "failed", message: "read-only" }); + await expect( + inspectStore(scopeWith(async () => ({ error: "no sqlite", ok: false }))) + ).resolves.toEqual({ kind: "failed", message: "no sqlite" }); + }); + + // On the base, `scope.remote` was read unguarded when `ctx.get` missed, so a + // getter that throws there rejected the inspection. The seam reads it inside + // a guard: no remote, so "unavailable" with its console line. The host never + // builds this scope (every caller's scope declares `remote` in `inject`). + it("reads a throwing remote getter as no service when ctx.get misses", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + const scope = { + get: () => {}, + get remote(): never { + throw new Error('cannot get property "remote" without inject'); + }, + }; + await expect(inspectStore(scope)).resolves.toEqual({ + kind: "unavailable", + }); + expect(warn).toHaveBeenCalledWith( + "[dsh-opencode-patch] store inspection: no opencodeStore service on the remote" + ); + } finally { + warn.mockRestore(); + } + }); +}); diff --git a/test/settings-usage.test.tsx b/test/settings-usage.test.tsx index e6d3fb3b..aaf8f9e0 100644 --- a/test/settings-usage.test.tsx +++ b/test/settings-usage.test.tsx @@ -10,6 +10,8 @@ import type { ReactNode } from "react"; import React from "react"; import { describe, expect, it, vi } from "vitest"; +import type { GoUsage } from "../src/contracts/usage.ts"; +import type { SessionUsageSnapshot } from "../src/session-cost.ts"; import { zh } from "../src/settings-copy.ts"; // @vitest-environment jsdom import { @@ -18,7 +20,6 @@ import { UsageSummaryView, readUntilAnswered, } from "../src/settings-usage.tsx"; -import type { GoUsage } from "../src/usage-contract.ts"; import { findAll, findAllOf } from "./test-helpers.ts"; const t = (key: string): string => zh[key as keyof typeof zh] ?? key; @@ -395,3 +396,177 @@ describe("settings-usage: reading until the remote answers", () => { } }); }); + +describe("settings: every reading the Host can send, pinned before the remote seam", () => { + const scopeWith = (read: unknown): unknown => ({ + remote: { opencodeGoUsage: { read } }, + }); + + /** + * Every field of a session snapshot, typed `Required` so a field added to + * the snapshot without a value here fails to compile. + */ + const session: Required = { + activeModel: "go-model-x", + activeModelName: "Go Model X", + activeRateFormatted: "$1 / $2 per 1M", + cacheReadTokens: 5, + costByPlane: { go: 0.25, zen: 0.5 }, + costFormatted: "$0.75", + costUsd: 0.75, + freeModel: true, + inputTokens: 100, + modelsUsed: ["go-model-x"], + outputTokens: 200, + planeCostFormatted: "$0.25", + planeSpendUsd: 0.25, + totalTokens: 305, + turns: 2, + }; + + /** Every field of a reading, typed `Required` for the same reason. */ + const full: Required = { + allowance: { go: 12, goPlus: 48, model: "Go Model X" }, + monthly: { percent: 14, resetsAt: "2026-11-07T00:55:00Z", status: "ok" }, + quotaUnavailable: true, + rolling: { percent: 0, resetsAt: "2026-10-09T06:00:00Z", status: "ok" }, + session, + source: "opencode-go", + weekly: { + percent: 100, + resetsAt: "2026-10-12T00:00:00Z", + status: "rate-limited", + }, + zenOverflow: true, + }; + + it("keeps every field of a complete reading, enveloped or bare", async () => { + await expect( + readGoUsage(scopeWith(async () => ({ ok: true, value: full }))) + ).resolves.toEqual(full); + await expect(readGoUsage(scopeWith(async () => full))).resolves.toEqual( + full + ); + }); + + it("names each empty lookup on the console, with the keys the remote does expose", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + await expect(readGoUsage({})).resolves.toBeUndefined(); + expect(warn).toHaveBeenLastCalledWith( + "[dsh-opencode-patch] usage read: the settings scope exposes no remote" + ); + await expect( + readGoUsage({ remote: { other: {} } }) + ).resolves.toBeUndefined(); + expect(warn).toHaveBeenLastCalledWith( + "[dsh-opencode-patch] usage read: no opencodeGoUsage service on the remote", + ["other"] + ); + await expect( + readGoUsage({ remote: { opencodeGoUsage: { peek: 1 } } }) + ).resolves.toBeUndefined(); + expect(warn).toHaveBeenLastCalledWith( + "[dsh-opencode-patch] usage read: no opencodeGoUsage service on the remote", + ["peek"] + ); + await expect( + readGoUsage(scopeWith(async () => 42)) + ).resolves.toBeUndefined(); + expect(warn).toHaveBeenLastCalledWith( + "[dsh-opencode-patch] usage read: the answer is not a usage shape", + 42 + ); + expect(warn).toHaveBeenCalledTimes(4); + } finally { + warn.mockRestore(); + } + }); + + it("rejects an error-less refusal with its own sentence, and reads an empty ok envelope as nothing", async () => { + const refused: unknown = await readGoUsage( + scopeWith(async () => ({ ok: false })) + ).catch((error: unknown) => error); + expect(refused).toBeInstanceOf(Error); + expect((refused as Error).message).toBe("usage call failed"); + await expect( + readGoUsage(scopeWith(async () => ({ ok: true }))) + ).resolves.toBeUndefined(); + }); +}); + +describe("settings: the one unwrap (P9), on readings the Host does not send", () => { + // The Host's own reading is a fixed point of the contract's reading parser + // (test/remote-seam.test.ts); these are the shapes it cannot produce, which + // the summary now reads as the parser reads them. + const scopeWith = (read: unknown): unknown => ({ + remote: { opencodeGoUsage: { read } }, + }); + + it("unifies a window the Host would reject into no reading", async () => { + for (const window of [ + { percent: Number.NaN, resetsAt: "2026-10-09T06:00:00Z", status: "ok" }, + { percent: 10, resetsAt: "soon", status: "ok" }, + ]) { + await expect( + readGoUsage( + scopeWith(async () => ({ + ok: true, + value: { ...usage(), rolling: window }, + })) + ) + ).resolves.toBeUndefined(); + } + }); + + it("names an enveloped payload that is not a reading on the console, once", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + try { + await expect( + readGoUsage( + scopeWith(async () => ({ ok: true, value: { rolling: {} } })) + ) + ).resolves.toBeUndefined(); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith( + "[dsh-opencode-patch] usage read: the answer is not a usage shape", + { rolling: {} } + ); + } finally { + warn.mockRestore(); + } + }); + + it("rejects a refusal whose error is null with its own sentence", async () => { + const refused: unknown = await readGoUsage( + scopeWith(async () => ({ error: null, ok: false })) + ).catch((error: unknown) => error); + expect(refused).toBeInstanceOf(Error); + expect((refused as Error).message).toBe("usage call failed"); + }); + + it("reads the vendor's { usage } wrapped form as the reading it wraps", async () => { + const { monthly, rolling, weekly } = usage(); + await expect( + readGoUsage( + scopeWith(async () => ({ + ok: true, + value: { usage: { monthly, rolling, weekly } }, + })) + ) + ).resolves.toEqual({ monthly, rolling, weekly }); + }); + + it("drops a field the contract does not name from a valid reading", async () => { + const reading = usage(); + await expect( + readGoUsage( + scopeWith(async () => ({ ok: true, value: { ...reading, extra: 1 } })) + ) + ).resolves.toEqual(reading); + const read = await readGoUsage( + scopeWith(async () => ({ ok: true, value: { ...reading, extra: 1 } })) + ); + expect(Object.hasOwn(read ?? {}, "extra")).toBe(false); + }); +}); diff --git a/test/support/src.ts b/test/support/src.ts index 44d3a791..8f09bcd2 100644 --- a/test/support/src.ts +++ b/test/support/src.ts @@ -75,6 +75,49 @@ export { } from "../../src/config.ts"; export type { PluginConfig, ResolvedPluginConfig } from "../../src/config.ts"; +// contracts/all.ts +export { REMOTE_CONTRACTS } from "../../src/contracts/all.ts"; + +// contracts/purge.ts +export { + parsePurgeResult, + PURGE_NAMESPACE, + purgeRemote, +} from "../../src/contracts/purge.ts"; + +// contracts/remote.ts +export { + defineRemote, + REMOTE_PACKAGE, + remoteValue, +} from "../../src/contracts/remote.ts"; + +// contracts/store.ts +export { + parseStoreInspection, + STORE_NAMESPACE, + storeRemote, +} from "../../src/contracts/store.ts"; +export type { + OpencodeStoreAccount, + OpencodeStoreInspection, +} from "../../src/contracts/store.ts"; + +// contracts/usage.ts +export { + parseAccountRef, + parseGoUsage, + parseUsageQuery, + parseUsageReading, + USAGE_NAMESPACE, + usageRemote, +} from "../../src/contracts/usage.ts"; +export type { + GoUsage, + ModelAllowanceSnapshot, + UsageWindow, +} from "../../src/contracts/usage.ts"; + // cordis-context.ts export { loadHostModules, @@ -186,7 +229,7 @@ export { } from "../../src/host/patch-method.ts"; // host/remote.ts -export { installRemoteService } from "../../src/host/remote.ts"; +export { installRemoteService, markRemote } from "../../src/host/remote.ts"; export type { RemoteContract } from "../../src/host/remote.ts"; // identity.ts @@ -248,17 +291,6 @@ export { opencodeRoots, } from "../../src/opencode-paths.ts"; -// opencode-store-contract.ts -export { - parseStoreInspection, - STORE_NAMESPACE, - storeRemote, -} from "../../src/opencode-store-contract.ts"; -export type { - OpencodeStoreAccount, - OpencodeStoreInspection, -} from "../../src/opencode-store-contract.ts"; - // opencode-store-service.ts export { OpencodeStoreService } from "../../src/opencode-store-service.ts"; @@ -269,9 +301,6 @@ export { summarizeCredential, } from "../../src/opencode-store.ts"; -// purge-contract.ts -export { parsePurgeResult } from "../../src/purge-contract.ts"; - // purge-service.ts export { ModelPurgeService, @@ -337,9 +366,12 @@ export { purgeDeprecatedModels } from "../../src/settings-purge.ts"; // settings-remote.ts export { + callRemote, callUsageRead, + findRemoteCall, remoteNamespace, remoteNamespaceOf, + unwrapRemote, } from "../../src/settings-remote.ts"; // settings-store-inspect.tsx @@ -382,14 +414,6 @@ export { export { withStore } from "../../src/turn-store.ts"; export type { ActiveTurnState } from "../../src/turn-store.ts"; -// usage-contract.ts -export { - parseAccountRef, - parseGoUsage, - parseUsageQuery, -} from "../../src/usage-contract.ts"; -export type { GoUsage } from "../../src/usage-contract.ts"; - // usage-panel.tsx export { UsagePanel, UsageTrigger } from "../../src/usage-panel.tsx"; export type { diff --git a/test/usage-contract.test.ts b/test/usage-contract.test.ts index 57117b56..93b33af2 100644 --- a/test/usage-contract.test.ts +++ b/test/usage-contract.test.ts @@ -1,5 +1,5 @@ /** - * `usage-contract.ts` — the Go usage wire shape and the Typert descriptor. + * `contracts/usage.ts` — the Go usage wire shape and the Typert descriptor. * * `usage.test.ts` pins the happy path through this module; this file pins what * it *rejects* and what it *drops*. That is the half that decides whether a @@ -13,9 +13,12 @@ import { describe, expect, it } from "vitest"; import { + type GoUsage, parseAccountRef, parseGoUsage, parseUsageQuery, + parseUsageReading, + type SessionUsageSnapshot, } from "./support/src.ts"; /** One well-formed quota window, with a single field overridden. */ @@ -348,3 +351,143 @@ describe("parseAccountRef", () => { } }); }); + +describe("parseUsageReading, the client's reading parser", () => { + it("keeps a well-formed allowance as exactly its three fields", () => { + const reading = parseUsageReading( + threeWindows({ + allowance: { extra: "dropped", go: 12, goPlus: 48, model: "Go X" }, + }) + ); + expect(reading.allowance).toEqual({ go: 12, goPlus: 48, model: "Go X" }); + expect(Object.keys(reading.allowance ?? {}).toSorted()).toEqual([ + "go", + "goPlus", + "model", + ]); + }); + + it.each([ + { go: 12, goPlus: 48 }, + { go: 12, model: "Go X" }, + { goPlus: 48, model: "Go X" }, + { go: Number.NaN, goPlus: 48, model: "Go X" }, + { go: 12, goPlus: Number.POSITIVE_INFINITY, model: "Go X" }, + { go: "12", goPlus: 48, model: "Go X" }, + { go: 12, goPlus: 48, model: 7 }, + "Go X", + ])("drops an allowance that is not one: %j", (allowance) => { + expect( + Object.hasOwn(parseUsageReading(threeWindows({ allowance })), "allowance") + ).toBe(false); + }); + + it("keeps quotaUnavailable only when it is true", () => { + expect( + parseUsageReading(threeWindows({ quotaUnavailable: true })) + .quotaUnavailable + ).toBe(true); + for (const quotaUnavailable of [false, "true", 1]) { + expect( + Object.hasOwn( + parseUsageReading(threeWindows({ quotaUnavailable })), + "quotaUnavailable" + ) + ).toBe(false); + } + }); + + it("keeps the session's plane spend, only with a kept session and only in its own type", () => { + const kept = parseUsageReading( + threeWindows({ + session: { + ...fullSession(), + planeCostFormatted: "$1.25", + planeSpendUsd: 1.25, + }, + }) + ); + expect(kept.session?.planeCostFormatted).toBe("$1.25"); + expect(kept.session?.planeSpendUsd).toBe(1.25); + + const mistyped = parseUsageReading( + threeWindows({ + session: { + ...fullSession(), + planeCostFormatted: 1, + planeSpendUsd: "1", + }, + }) + ); + expect(Object.hasOwn(mistyped.session ?? {}, "planeCostFormatted")).toBe( + false + ); + expect(Object.hasOwn(mistyped.session ?? {}, "planeSpendUsd")).toBe(false); + + // A session the vendor whitelist drops (no `costFormatted`) is not + // rebuilt from its plane spend alone. + const dropped = parseUsageReading( + threeWindows({ session: { planeCostFormatted: "$1", totalTokens: 1 } }) + ); + expect(Object.hasOwn(dropped, "session")).toBe(false); + }); + + it("throws the vendor parser's own TypeError for what is not a reading", () => { + for (const bad of [ + 42, + undefined, + threeWindows({ rolling: windowRow({ percent: -1 }) }), + threeWindows({ weekly: windowRow({ resetsAt: "soon" }) }), + threeWindows({ monthly: undefined }), + ]) { + let expected: unknown; + try { + parseGoUsage(bad); + } catch (error) { + expected = error; + } + expect(expected).toBeInstanceOf(TypeError); + expect(() => parseUsageReading(bad)).toThrow( + (expected as TypeError).message + ); + } + }); + + it("answers every complete reading the Host sends as itself", () => { + // `Required` so a field added to either type without a reading rule fails + // to compile here, or reads back different. + const session: Required = { + activeModel: "go-model-x", + activeModelName: "Go Model X", + activeRateFormatted: "$1 / $2 per 1M", + cacheReadTokens: 5, + costByPlane: { go: 0.25, zen: 0.5 }, + costFormatted: "$0.75", + costUsd: 0.75, + freeModel: true, + inputTokens: 100, + modelsUsed: ["go-model-x"], + outputTokens: 200, + planeCostFormatted: "$0.25", + planeSpendUsd: 0.25, + totalTokens: 305, + turns: 2, + }; + const full: Required = { + allowance: { go: 12, goPlus: 48, model: "Go Model X" }, + monthly: { percent: 14, resetsAt: "2026-11-07T00:55:00Z", status: "ok" }, + quotaUnavailable: true, + rolling: { percent: 0, resetsAt: "2026-10-09T06:00:00Z", status: "ok" }, + session, + source: "opencode-go", + weekly: { + percent: 100, + resetsAt: "2026-10-12T00:00:00Z", + status: "rate-limited", + }, + zenOverflow: true, + }; + expect(parseUsageReading(full)).toEqual(full); + expect(parseUsageReading(parseUsageReading(full))).toEqual(full); + }); +}); diff --git a/test/usage-pill-mount.test.tsx b/test/usage-pill-mount.test.tsx index 9c8f71a9..2c91bd05 100644 --- a/test/usage-pill-mount.test.tsx +++ b/test/usage-pill-mount.test.tsx @@ -27,7 +27,7 @@ import { } from "@testing-library/react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { GoUsage } from "../src/usage-contract.ts"; +import type { GoUsage } from "../src/contracts/usage.ts"; import { MIN_FEEDBACK_MS, UsagePill, diff --git a/vite.config.ts b/vite.config.ts index d4d6dd61..c95d56c7 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -395,6 +395,14 @@ export default defineConfig({ functions: 100, lines: 100, }, + // The contract builder (P9): every branch driven by + // test/remote-define.test.ts, so 100. + "src/contracts/remote.ts": { + statements: 100, + branches: 100, + functions: 100, + lines: 100, + }, "src/host/describe-graft.ts": { statements: 100, branches: 94,