From 157c3c3a3610420c4c30fbf9bf1bc3846823e8f1 Mon Sep 17 00:00:00 2001 From: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:37:30 -0300 Subject: [PATCH 01/18] fix(providers): remove OpenCode Free provider and free-tier client contract Preventive removal of the keyless "OpenCode Free" provider (id `opencode`, alias `oc`) and of the free-tier request contract that shaped requests to look like the OpenCode client (placeholder/borrowed tools, forced stream and JSON rebuild, shape replay, observed-tool retry, keyless premium gate), honoring the OpenCode operator's public removal request. - registry entry, no-auth catalog entry, executor alias, free-apikey and no-auth proxy allowlists, auto-combo no-auth allowlist, fingerprint expansion member, egress-lock default, search pair, usage fetcher ids - free-model catalog rows for `opencode` and the opencode-zen free rows, ToS verdict entry, models.dev mapping and synced-capability fallback - opencode-zen / opencode-go no longer offer the keyless anonymous fallback or hydrate from the removed sibling id - combo `opencode/` -> `oc/` target rewrite (#11912) removed - migration 206 cleans stored `opencode` / `oc` provider state - REMOVED_PROVIDERS.md entry + blocklist guard (declaration-shaped needles, so opencode-zen / opencode-go and the OpenCode client integrations stay untouched) The paid opencode-zen / opencode-go providers keep the OpencodeExecutor; a free model requested through opencode-zen is sent without the contract. --- .env.example | 18 +- .../0000-remove-opencode-free-provider.md | 1 + docs/reference/ENVIRONMENT.md | 6 +- docs/reference/REMOVED_PROVIDERS.md | 15 +- open-sse/config/codexIdentity.ts | 2 +- open-sse/config/freeModelCatalog.data.ts | 13 - open-sse/config/freeTierCatalog.ts | 1 - open-sse/config/providerErrorRules.ts | 3 +- open-sse/config/providerModels.ts | 14 +- open-sse/config/providers/index.ts | 2 - .../providers/registry/opencode/index.ts | 93 -- open-sse/executors/base/reasoningEffort.ts | 7 +- open-sse/executors/index.ts | 1 - open-sse/executors/opencode.ts | 279 +---- .../executors/opencodeFreeTierContract.ts | 531 ---------- open-sse/executors/opencodeFreeTierRetry.ts | 178 ---- open-sse/executors/opencodeGeoBlock.ts | 19 - open-sse/executors/opencodeRequestContext.ts | 7 +- open-sse/executors/opencodeRequestShape.ts | 242 ----- open-sse/executors/opencodeToolObservation.ts | 181 ---- open-sse/handlers/chatCore.ts | 2 +- open-sse/services/autoCombo/virtualFactory.ts | 10 +- open-sse/services/combo/comboStructure.ts | 10 +- .../services/combo/fingerprintExpansion.ts | 9 +- .../services/combo/opencodeTargetAlias.ts | 43 - open-sse/services/model.ts | 16 +- open-sse/services/opencodeQuotaFetcher.ts | 4 +- .../services/opencodeReasoningSanitizer.ts | 1 - open-sse/services/providerAlias.ts | 9 +- open-sse/services/providerConnectionPool.ts | 2 - open-sse/services/usage.ts | 1 - open-sse/services/usage/fetcherProviders.ts | 1 - open-sse/utils/opencodeHeaders.ts | 28 +- open-sse/utils/opencodeSessionIdentity.ts | 2 +- open-sse/utils/reasoningContentInjector.ts | 2 +- open-sse/utils/reasoningPlaceholder.ts | 2 +- scripts/ad-hoc/dry-run-strict-zero-cost.ts | 6 +- .../components/HermesAgentToolCard.tsx | 3 - src/app/(dashboard)/dashboard/combos/page.tsx | 8 +- .../components/LlmChatCard.tsx | 4 +- .../components/AnonymousFallbackToggle.tsx | 2 +- .../components/NoAuthProviderControls.tsx | 1 - .../models/discovery/providerModelsConfig.ts | 3 +- src/app/api/v1/models/catalogOrder.ts | 2 +- src/app/api/v1/models/catalogProviderMaps.ts | 6 +- src/lib/combos/builderDraft.ts | 16 +- src/lib/combos/builderOptions.ts | 16 +- src/lib/combos/controlCenter.ts | 13 +- .../206_remove_opencode_free_provider.sql | 24 + src/lib/db/settings.ts | 2 +- src/lib/db/settings/noAuthProxyFallback.ts | 2 +- src/lib/guardrails/visionBridgeCredentials.ts | 4 +- src/lib/modelsDevSync.ts | 11 +- src/lib/modelsDevSync/transform.ts | 17 +- .../hardcodedModelsConfigIds.ts | 1 - src/shared/constants/providers.ts | 1 - .../constants/providers/apikey/gateways.ts | 2 - src/shared/constants/providers/noauth.ts | 21 +- src/shared/reasoning/effortStandardization.ts | 2 +- src/sse/services/auth.ts | 12 +- src/sse/services/model.ts | 6 +- src/sse/services/noAuthProviderSiblings.ts | 22 +- src/sse/services/noAuthProxyResolution.ts | 3 +- tests/unit/7993-noauth-proxy-routing.test.ts | 154 --- .../auth-opencode-zen-noauth-fallback.test.ts | 77 -- .../combo-builder-opencode-prefix.test.ts | 83 -- ...11912-opencode-roundrobin-collapse.test.ts | 70 -- ...-206-remove-opencode-free-provider.test.ts | 167 +++ .../noauth-autocombo-exclude-7622.test.ts | 100 -- .../unit/noauth-autocombo-hidden-7620.test.ts | 80 -- .../noauth-autocombo-lockout-7623.test.ts | 107 -- ...te.test.ts => noauth-models-route.test.ts} | 0 ...oauth-sibling-compat-override-7620.test.ts | 98 -- .../opencode-autocombo-search-pair.test.ts | 29 - ...ncode-free-tier-catalog-stale-6998.test.ts | 40 - ...pencode-free-tier-refusal-rotation.test.ts | 396 -------- ...pencode-free-tier-request-contract.test.ts | 959 ------------------ ...pencode-noauth-copy-freetier-14313.test.ts | 38 - ...opencode-premium-keyless-gate-8681.test.ts | 168 --- .../opencode-quota-retry-own-tools.test.ts | 184 ---- .../unit/opencode-request-shape-retry.test.ts | 707 ------------- ...de-shape-replay-insufficient-quota.test.ts | 181 ---- ...encode-shape-replay-verdict-reread.test.ts | 150 --- .../unit/removed-providers-blocklist.test.ts | 65 +- ...-noauth-connection-disable-ignored.test.ts | 102 -- .../ui/hermes-agent-opencode-free.test.tsx | 76 -- 86 files changed, 405 insertions(+), 5591 deletions(-) create mode 100644 changelog.d/fixes/0000-remove-opencode-free-provider.md delete mode 100644 open-sse/config/providers/registry/opencode/index.ts delete mode 100644 open-sse/executors/opencodeFreeTierContract.ts delete mode 100644 open-sse/executors/opencodeFreeTierRetry.ts delete mode 100644 open-sse/executors/opencodeRequestShape.ts delete mode 100644 open-sse/executors/opencodeToolObservation.ts delete mode 100644 open-sse/services/combo/opencodeTargetAlias.ts create mode 100644 src/lib/db/migrations/206_remove_opencode_free_provider.sql delete mode 100644 tests/unit/7993-noauth-proxy-routing.test.ts delete mode 100644 tests/unit/auth-opencode-zen-noauth-fallback.test.ts delete mode 100644 tests/unit/combo-builder-opencode-prefix.test.ts delete mode 100644 tests/unit/issue-11912-opencode-roundrobin-collapse.test.ts create mode 100644 tests/unit/migration-206-remove-opencode-free-provider.test.ts delete mode 100644 tests/unit/noauth-autocombo-exclude-7622.test.ts delete mode 100644 tests/unit/noauth-autocombo-hidden-7620.test.ts delete mode 100644 tests/unit/noauth-autocombo-lockout-7623.test.ts rename tests/unit/{opencode-noauth-models-route.test.ts => noauth-models-route.test.ts} (100%) delete mode 100644 tests/unit/noauth-sibling-compat-override-7620.test.ts delete mode 100644 tests/unit/opencode-autocombo-search-pair.test.ts delete mode 100644 tests/unit/opencode-free-tier-catalog-stale-6998.test.ts delete mode 100644 tests/unit/opencode-free-tier-refusal-rotation.test.ts delete mode 100644 tests/unit/opencode-free-tier-request-contract.test.ts delete mode 100644 tests/unit/opencode-noauth-copy-freetier-14313.test.ts delete mode 100644 tests/unit/opencode-premium-keyless-gate-8681.test.ts delete mode 100644 tests/unit/opencode-quota-retry-own-tools.test.ts delete mode 100644 tests/unit/opencode-request-shape-retry.test.ts delete mode 100644 tests/unit/opencode-shape-replay-insufficient-quota.test.ts delete mode 100644 tests/unit/opencode-shape-replay-verdict-reread.test.ts delete mode 100644 tests/unit/repro-6557-noauth-connection-disable-ignored.test.ts delete mode 100644 tests/unit/ui/hermes-agent-opencode-free.test.tsx diff --git a/.env.example b/.env.example index 7ba51c5a92bd..2d2eb787eb3b 100644 --- a/.env.example +++ b/.env.example @@ -885,24 +885,12 @@ NEXT_PUBLIC_CLOUD_URL= #OPENCODE_CLIENT=desktop #OPENCODE_PROJECT=global -# Keyless OpenCode models are answered only when the request declares a non-empty tool -# list, and the upstream inspects which names it carries. OmniRoute reuses the list a -# request of the same conversation was last seen getting through, so a request that -# carries none — a title or a summary — goes out with the list its own client already -# declared. Set to off to stop adjusting request bodies entirely; headers are unaffected. -#OPENCODE_FREE_TIER_REQUEST_CONTRACT=off - -# Tool names to declare when nothing has been observed yet for a model, comma-separated. -# Empty falls back to a single placeholder the model is told not to call. Only useful on -# an install where no client sends tools, since there is then nothing to learn from. -#OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS=glob,grep,read - -# Egress-IP lockout scope (#9611). By default the free-tier opencode family -# (opencode, opencode-go, opencode-cli) is bucketed by egress IP: one upstream +# Egress-IP lockout scope (#9611). By default the opencode family +# (opencode-go, opencode-cli) is bucketed by egress IP: one upstream # 429 parks every sibling connection sharing that IP. PAID plans are # account-bucketed upstream, so operators on paid subscriptions can disable the # cascade or narrow it to the providers that actually need it. -# unset → default free-tier set (opencode, opencode-go, opencode-cli) +# unset → default set (opencode-go, opencode-cli) # none / off / false / 0 → egress-IP lockout disabled entirely # "a,b,c" → exact replacement set (comma-separated provider IDs) # Used by: open-sse/config/providerErrorRules.ts (isEgressBucketedLockScope) diff --git a/changelog.d/fixes/0000-remove-opencode-free-provider.md b/changelog.d/fixes/0000-remove-opencode-free-provider.md new file mode 100644 index 000000000000..428272e22ec3 --- /dev/null +++ b/changelog.d/fixes/0000-remove-opencode-free-provider.md @@ -0,0 +1 @@ +- **fix(providers):** remove the keyless "OpenCode Free" provider (`opencode`, alias `oc`) and the free-tier request contract that shaped requests like the OpenCode client (synthetic tools, forced stream, shape replay, free-tier retry), as a preventive measure honoring the OpenCode operator's public removal request. The paid `opencode-zen` / `opencode-go` providers and the OpenCode client integrations are unaffected; migration `206` cleans stored `opencode` config. See `docs/reference/REMOVED_PROVIDERS.md`. diff --git a/docs/reference/ENVIRONMENT.md b/docs/reference/ENVIRONMENT.md index 2f859d37999d..b040cadc8260 100644 --- a/docs/reference/ENVIRONMENT.md +++ b/docs/reference/ENVIRONMENT.md @@ -360,12 +360,10 @@ OmniRoute provides a two-layer defense: request-side injection scanning and resp | `OMNIROUTE_CLINEPASS_USAGE_URL` | `https://api.cline.bot/api/v1/users/me/plan/usage-limits` | `open-sse/services/usage/clinepass.ts` | ClinePass 5-hour / weekly / monthly quota endpoint used by the Usage page. Override for relays / test fixtures. | | `OMNIROUTE_OPENCODE_QUOTA_URL` | `https://opencode.ai/zen/go/v1/usage` | `open-sse/services/opencodeQuotaFetcher.ts` | Official API-key-authenticated OpenCode Go usage endpoint used by the Usage page. Override for relays / test fixtures. | | `OPENCODE_SYNTHESIZE_CLI_HEADERS` | `true` | `open-sse/executors/opencode.ts` | Synthesize OpenCode CLI identity headers (User-Agent, x-opencode-client/project, request/session UUIDs) on opencode-go/zen upstream requests the client didn't send, so Cloudflare on VPS egress accepts them (#6210/#5997). On by default since #10571; opt out with `false`/`0`/`no`/`off`. | -| `OPENCODE_USER_AGENT` | `opencode/1.18.31` | `open-sse/utils/opencodeHeaders.ts` | Default User-Agent used when `OPENCODE_SYNTHESIZE_CLI_HEADERS` is on and no per-provider `_USER_AGENT` override is set. Only applied to opencode executors. On a keyless request the upstream gates, a configured value that does not carry `opencode/= 1.17>` is replaced by this default rather than refused. | +| `OPENCODE_USER_AGENT` | `opencode/1.18.31` | `open-sse/utils/opencodeHeaders.ts` | Default User-Agent used when `OPENCODE_SYNTHESIZE_CLI_HEADERS` is on and no per-provider `_USER_AGENT` override is set. Only applied to opencode executors. | | `OPENCODE_CLIENT` | `desktop` | `open-sse/executors/opencode.ts` | Value for the synthesized `x-opencode-client` header when `OPENCODE_SYNTHESIZE_CLI_HEADERS` is on. | | `OPENCODE_PROJECT` | `global` | `open-sse/executors/opencode.ts` | Value for the synthesized `x-opencode-project` header when `OPENCODE_SYNTHESIZE_CLI_HEADERS` is on. | -| `OMNIROUTE_EGRESS_IP_LOCK_PROVIDERS` | _(unset)_ | `open-sse/config/providerErrorRules.ts` | Effective set of providers whose upstream failures are bucketed by egress IP (one 429 parks every sibling connection sharing that IP). Unset uses the free-tier default `opencode,opencode-go,opencode-cli`; `none`/`off`/`false`/`0` disables the cascade entirely; a comma-separated list replaces the set. Paid plans are account-bucketed upstream and can safely disable it (#9611). | -| `OPENCODE_FREE_TIER_REQUEST_CONTRACT` | _(unset)_ | `open-sse/executors/opencodeFreeTierContract.ts` | Set to `off` to stop adjusting the body of keyless OpenCode requests (streaming flag and tool list). Headers are still applied. Read per request, so a change takes effect immediately. | -| `OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS` | _(unset)_ | `open-sse/executors/opencodeFreeTierContract.ts` | Comma-separated tool names to declare on a keyless OpenCode request that carries none, when nothing has been observed yet for that model. Empty falls back to a single placeholder the model is told not to call. At most 32 entries, `[A-Za-z_][A-Za-z0-9_-]{0,63}`; invalid entries are ignored. | +| `OMNIROUTE_EGRESS_IP_LOCK_PROVIDERS` | _(unset)_ | `open-sse/config/providerErrorRules.ts` | Effective set of providers whose upstream failures are bucketed by egress IP (one 429 parks every sibling connection sharing that IP). Unset uses the default `opencode-go,opencode-cli`; `none`/`off`/`false`/`0` disables the cascade entirely; a comma-separated list replaces the set. Paid plans are account-bucketed upstream and can safely disable it (#9611). | | `OMNIROUTE_OLLAMA_CLOUD_USAGE_URL` | `https://ollama.com/settings` | `open-sse/services/usage.ts` | Ollama Cloud settings URL used for quota scraping. Override for relays / test fixtures. | | `OLLAMA_USAGE_COOKIE` | _(unset)_ | `open-sse/services/usage.ts` | Ollama Cloud `__Secure-session` cookie used for settings-page quota scraping. Sensitive; prefer the per-connection Dashboard field when multiple accounts are configured. | | `OLLAMA_CLOUD_USAGE_COOKIE` | _(unset)_ | `open-sse/services/usage.ts` | Alternate Ollama Cloud `__Secure-session` cookie env var. Sensitive; prefer the per-connection Dashboard field when multiple accounts are configured. | diff --git a/docs/reference/REMOVED_PROVIDERS.md b/docs/reference/REMOVED_PROVIDERS.md index 1dcecff07348..dd47d49f9cab 100644 --- a/docs/reference/REMOVED_PROVIDERS.md +++ b/docs/reference/REMOVED_PROVIDERS.md @@ -1,7 +1,7 @@ --- title: "Removed Providers" version: 3.8.51 -lastUpdated: 2026-09-03 +lastUpdated: 2026-10-10 --- # Providers removed at their operator's request @@ -45,12 +45,13 @@ the request, and that permission must be linked from the entry. ## Register -| Removed on | Provider id | Alias | Domains | Requested by | Removal PR | Notes | -| ---------- | ----------------- | -------- | ------------------------------------------------ | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| 2026-08-12 | `puter` | `pu` | `puter.com` | Puter's owner (Nariman Jelveh) | [#10210](https://github.com/diegosouzapw/OmniRoute/pull/10210) | API-key provider. Migration `152_remove_puter_provider.sql` cleans stored config. | -| 2026-09-02 | `theoldllm` | `tllm` | `theoldllm.com`, `theoldllm.vercel.app` | The service operator (support email) | [#12440](https://github.com/diegosouzapw/OmniRoute/pull/12440) | Keyless provider. Written request received 2026-08-30. Dedicated issues and discussion deleted, PRs retitled. | -| 2026-09-21 | `gemini-business` | `gembiz` | `business.gemini.google` | Project owner decision (issue [#14217](https://github.com/diegosouzapw/OmniRoute/issues/14217)) | [#14467](https://github.com/diegosouzapw/OmniRoute/pull/14467) | Cookie-based web provider. Google retired the `BardFrontendService/StreamGenerate` endpoint the executor targeted; the replacement (`biz-discoveryengine.googleapis.com` `widgetStreamAssist`, Bearer JWT bootstrapped from `__Secure-C_SES`/`csesidx`) cannot be built or validated without a live Gemini Enterprise/Workspace account, which the project does not have. Retired rather than rewritten unverified. | -| 2026-09-21 | `suno` | `suno` | `studio-api.suno.ai`, `studio-api-prod.suno.com` | Project owner decision (`#14224`) | [#14468](https://github.com/diegosouzapw/OmniRoute/pull/14468) | Cookie-auth provider, not an operator takedown. `studio-api.suno.ai` was suspended (503); the live host requires a Clerk JWT exchange plus a paid hCaptcha-solving dependency that OmniRoute chose not to add for one music provider. `kie/suno-v4.0` and `kie/suno-v3.5` (kie.ai-hosted) are unaffected and remain supported. | +| Removed on | Provider id | Alias | Domains | Requested by | Removal PR | Notes | +| ---------- | ----------------- | -------- | ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| 2026-08-12 | `puter` | `pu` | `puter.com` | Puter's owner (Nariman Jelveh) | [#10210](https://github.com/diegosouzapw/OmniRoute/pull/10210) | API-key provider. Migration `152_remove_puter_provider.sql` cleans stored config. | +| 2026-09-02 | `theoldllm` | `tllm` | `theoldllm.com`, `theoldllm.vercel.app` | The service operator (support email) | [#12440](https://github.com/diegosouzapw/OmniRoute/pull/12440) | Keyless provider. Written request received 2026-08-30. Dedicated issues and discussion deleted, PRs retitled. | +| 2026-09-21 | `gemini-business` | `gembiz` | `business.gemini.google` | Project owner decision (issue [#14217](https://github.com/diegosouzapw/OmniRoute/issues/14217)) | [#14467](https://github.com/diegosouzapw/OmniRoute/pull/14467) | Cookie-based web provider. Google retired the `BardFrontendService/StreamGenerate` endpoint the executor targeted; the replacement (`biz-discoveryengine.googleapis.com` `widgetStreamAssist`, Bearer JWT bootstrapped from `__Secure-C_SES`/`csesidx`) cannot be built or validated without a live Gemini Enterprise/Workspace account, which the project does not have. Retired rather than rewritten unverified. | +| 2026-09-21 | `suno` | `suno` | `studio-api.suno.ai`, `studio-api-prod.suno.com` | Project owner decision (`#14224`) | [#14468](https://github.com/diegosouzapw/OmniRoute/pull/14468) | Cookie-auth provider, not an operator takedown. `studio-api.suno.ai` was suspended (503); the live host requires a Clerk JWT exchange plus a paid hCaptcha-solving dependency that OmniRoute chose not to add for one music provider. `kie/suno-v4.0` and `kie/suno-v3.5` (kie.ai-hosted) are unaffected and remain supported. | +| 2026-10-10 | `opencode` | `oc` | `opencode.ai/zen/v1` (free tier; host shared with `opencode-zen`) | Preventive removal (project owner decision), honoring the OpenCode operator's public removal request to the upstream 9router project (2026-09-19) | PR: | Keyless "OpenCode Free" provider plus the free-tier request contract that made requests look like the OpenCode client. The free models are provisioned for use from inside the OpenCode client only. The paid `opencode-zen` and `opencode-go` providers, the OpenCode client integrations and `@omniroute/opencode-plugin*` are unaffected; a free model requested through `opencode-zen` is sent without the contract. Migration `206_remove_opencode_free_provider.sql` cleans stored config. | ## Adding an entry diff --git a/open-sse/config/codexIdentity.ts b/open-sse/config/codexIdentity.ts index 856807eaf255..d133927408ac 100644 --- a/open-sse/config/codexIdentity.ts +++ b/open-sse/config/codexIdentity.ts @@ -666,7 +666,7 @@ export function isVerifiedNativeCodexRequest( /** * Detect the Claude Code CLI as the request *client* from request headers. * Used to auto-enable model echo so session restores work when the resolved - * upstream model (e.g. `oc/nemotron-3-ultra-free`) is not recognized by the + * upstream model (e.g. `opencode-zen/nemotron-3-ultra-free`) is not recognized by the * Claude Code client on `--resume`. */ export function isClaudeCodeOriginatedHeaders( diff --git a/open-sse/config/freeModelCatalog.data.ts b/open-sse/config/freeModelCatalog.data.ts index 5b58c600ebcc..44840bb8ab04 100644 --- a/open-sse/config/freeModelCatalog.data.ts +++ b/open-sse/config/freeModelCatalog.data.ts @@ -326,19 +326,6 @@ export const FREE_MODEL_BUDGETS: FreeModelBudget[] = [ { provider: "ollama-cloud", modelId: "gemma4:31b", displayName: "Gemma 4 31B", monthlyTokens: 0, creditTokens: 0, freeType: "recurring-uncapped", poolKey: "ollama-cloud", tos: "ambiguous" }, { provider: "ollama-cloud", modelId: "nemotron-3-super", displayName: "NVIDIA Nemotron 3 Super", monthlyTokens: 0, creditTokens: 0, freeType: "recurring-uncapped", poolKey: "ollama-cloud", tos: "ambiguous" }, { provider: "ollama-cloud", modelId: "qwen3.5:397b", displayName: "Qwen 3.5 397B", monthlyTokens: 0, creditTokens: 0, freeType: "recurring-uncapped", poolKey: "ollama-cloud", tos: "ambiguous" }, - { provider: "opencode", modelId: "big-pickle", displayName: "Big Pickle", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "opencode", tos: "avoid" }, - { provider: "opencode", modelId: "deepseek-v4-flash-free", displayName: "DeepSeek V4 Flash Free", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "opencode", tos: "avoid" }, - { provider: "opencode", modelId: "minimax-m2.5-free", displayName: "MiniMax M2.5 Free", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "opencode", tos: "avoid" }, - { provider: "opencode", modelId: "ling-2.6-1t-free", displayName: "Ling 2.6 Free", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "opencode", tos: "avoid" }, - { provider: "opencode", modelId: "trinity-large-preview-free", displayName: "Trinity Large Preview Free", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "opencode", tos: "avoid" }, - { provider: "opencode", modelId: "nemotron-3-super-free", displayName: "Nemotron 3 Super Free", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "opencode", tos: "avoid" }, - { provider: "opencode", modelId: "qwen3.6-plus-free", displayName: "Qwen3.6 Plus Free", monthlyTokens: 0, creditTokens: 0, freeType: "keyless", poolKey: "opencode", tos: "avoid" }, - { provider: "opencode-zen", modelId: "opencode/big-pickle", displayName: "Big Pickle (stealth)", monthlyTokens: 0, creditTokens: 0, freeType: "recurring-uncapped", poolKey: "opencode-zen-free", tos: "caution" }, - { provider: "opencode-zen", modelId: "opencode/deepseek-v4-flash-free", displayName: "DeepSeek V4 Flash (free)", monthlyTokens: 0, creditTokens: 0, freeType: "recurring-uncapped", poolKey: "opencode-zen-free", tos: "caution" }, - { provider: "opencode-zen", modelId: "opencode/nemotron-3-super-free", displayName: "Nemotron 3 Super (free)", monthlyTokens: 0, creditTokens: 0, freeType: "recurring-uncapped", poolKey: "opencode-zen-free", tos: "caution" }, - { provider: "opencode-zen", modelId: "opencode/mimo-v2.5-free", displayName: "MiMo V2.5 (free)", monthlyTokens: 0, creditTokens: 0, freeType: "recurring-uncapped", poolKey: "opencode-zen-free", tos: "caution" }, - { provider: "opencode-zen", modelId: "opencode/north-mini-code-free", displayName: "North Mini Code (free)", monthlyTokens: 0, creditTokens: 0, freeType: "recurring-uncapped", poolKey: "opencode-zen-free", tos: "caution" }, - { provider: "opencode-zen", modelId: "opencode/nemotron-3-ultra-free", displayName: "Nemotron 3 Ultra (free)", monthlyTokens: 0, creditTokens: 0, freeType: "recurring-uncapped", poolKey: "opencode-zen-free", tos: "caution" }, { provider: "openrouter", modelId: "auto", displayName: "Auto (Best Available)", monthlyTokens: 1200000, creditTokens: 0, freeType: "recurring-daily", poolKey: "openrouter-free", tos: "caution" }, { provider: "openrouter", modelId: "stealth/ox-alpha", displayName: "Stealth Ox Alpha (free)", monthlyTokens: 0, creditTokens: 0, freeType: "recurring-daily", poolKey: "openrouter-free", tos: "caution" }, { provider: "openrouter", modelId: "liquid/lfm-2.5-2.6b:free", displayName: "LiquidAI: LFM2.5-2.6B (free)", monthlyTokens: 0, creditTokens: 0, freeType: "recurring-daily", poolKey: "openrouter-free", tos: "caution" }, diff --git a/open-sse/config/freeTierCatalog.ts b/open-sse/config/freeTierCatalog.ts index b099438cad5d..beed3bc4d243 100644 --- a/open-sse/config/freeTierCatalog.ts +++ b/open-sse/config/freeTierCatalog.ts @@ -38,7 +38,6 @@ export const FREE_TIER_BUDGETS: Record = { * non-personal use. Source: ToS attention table in docs/reference/FREE_TIERS.md. */ export const FREE_TIER_TOS: Record = { - opencode: "avoid", "duckduckgo-web": "avoid", agy: "avoid", antigravity: "avoid", // Both registered IDs use the same Antigravity integration. diff --git a/open-sse/config/providerErrorRules.ts b/open-sse/config/providerErrorRules.ts index 9ede02bea9b9..e6c70433e801 100644 --- a/open-sse/config/providerErrorRules.ts +++ b/open-sse/config/providerErrorRules.ts @@ -321,7 +321,7 @@ function buildAgentrouterRules(): ProviderErrorRule[] { } /** Providers sharing the opencode upstream envelope, hence the opencode catalog rules. */ -const OPENCODE_RULE_FAMILY = ["opencode", "opencode-zen", "opencode-go", "opencode-cli"]; +const OPENCODE_RULE_FAMILY = ["opencode-zen", "opencode-go", "opencode-cli"]; /** * Global registry. Provider name → ordered list of rules (first match wins). @@ -383,7 +383,6 @@ export function honorsRuleLockScope(provider: string | null | undefined): boolea // Static default as a plain lookup table; the runtime set is env-derived // (dynamic membership), so a Set is the right structure there. const EGRESS_BUCKETED_LOCK_PROVIDERS_DEFAULT: Record = { - opencode: true, "opencode-go": true, "opencode-cli": true, }; diff --git a/open-sse/config/providerModels.ts b/open-sse/config/providerModels.ts index 1dd32a5b0d0b..b3c5c1dcd11e 100644 --- a/open-sse/config/providerModels.ts +++ b/open-sse/config/providerModels.ts @@ -80,8 +80,8 @@ export function getProviderModels(aliasOrId: string): RegistryModel[] { // provider id (e.g. "github") and resolve id→alias before reading the namespace // map — so callers don't need to know which form they hold. We resolve here rather // than mirroring raw-id keys into PROVIDER_MODELS, whose keys ARE the public - // prefixes (a raw id like "opencode" would collide with the opencode-zen route — - // see #2798/#3870). + // prefixes (a raw id could collide with another provider's route — see + // #2798/#3870). const alias = PROVIDER_ID_TO_ALIAS[aliasOrId] || aliasOrId; return PROVIDER_MODELS[alias] || PROVIDER_MODELS[aliasOrId] || []; } @@ -215,10 +215,10 @@ export function findModelName(aliasOrId: string, modelId: string): string { // OpenCode's Muse Spark family is Responses-only. Keep this rule provider-scoped // and version-agnostic so a newly published Muse Spark model is routed correctly // before the static catalog is refreshed. -const OPENCODE_MUSE_SPARK_ALIASES = new Set(["oc", "opencode-zen", "opencode-go"]); +const OPENCODE_MUSE_SPARK_ALIASES = new Set(["opencode-zen", "opencode-go"]); const MUSE_SPARK_MODEL_PATTERN = /^muse-spark(?:-|$)/i; -const OPENCODE_MODEL_PREFIXES = ["opencode/", "oc/", "opencode-zen/", "opencode-go/"] as const; +const OPENCODE_MODEL_PREFIXES = ["opencode/", "opencode-zen/", "opencode-go/"] as const; /** * OpenCode Zen's Responses endpoint accepts the upstream model id only. The @@ -243,9 +243,9 @@ export function getModelTargetFormat(aliasOrId: string, modelId: string): string const bareModelId = prefix ? modelId.slice(prefix.length) : modelId; const found = PROVIDER_MODELS[alias]?.find((m) => m.id === bareModelId); if (found?.targetFormat) return found.targetFormat; - // Resolved models can still carry the raw provider id (for example - // "opencode/muse-spark-1.3-contributor-free") even when the public alias is - // "oc". Match the family against the final model segment so both forms work. + // Resolved models can still carry an extra provider segment (for example + // "opencode/muse-spark-1.3-contributor-free" under opencode-zen). Match the + // family against the final model segment so both forms work. const modelFamilyId = bareModelId.split("/").pop() || bareModelId; if (OPENCODE_MUSE_SPARK_ALIASES.has(alias) && MUSE_SPARK_MODEL_PATTERN.test(modelFamilyId)) { return "openai-responses"; diff --git a/open-sse/config/providers/index.ts b/open-sse/config/providers/index.ts index bedcf9346e4c..df98b08d2d7a 100644 --- a/open-sse/config/providers/index.ts +++ b/open-sse/config/providers/index.ts @@ -201,7 +201,6 @@ import { vercel_ai_gatewayProvider } from "./registry/vercel-ai-gateway/index.ts import { v0_vercelProvider } from "./registry/v0-vercel/index.ts"; import { opencode_zenProvider } from "./registry/opencode/zen/index.ts"; import { opencode_goProvider } from "./registry/opencode/go/index.ts"; -import { opencodeProvider } from "./registry/opencode/index.ts"; import { dahlProvider } from "./registry/dahl/index.ts"; import { maritalkProvider } from "./registry/maritalk/index.ts"; import { basetenProvider } from "./registry/baseten/index.ts"; @@ -489,7 +488,6 @@ export const REGISTRY: Record = { "v0-vercel": v0_vercelProvider, "opencode-zen": opencode_zenProvider, "opencode-go": opencode_goProvider, - opencode: opencodeProvider, dahl: dahlProvider, maritalk: maritalkProvider, baseten: basetenProvider, diff --git a/open-sse/config/providers/registry/opencode/index.ts b/open-sse/config/providers/registry/opencode/index.ts deleted file mode 100644 index 0a255836e3ce..000000000000 --- a/open-sse/config/providers/registry/opencode/index.ts +++ /dev/null @@ -1,93 +0,0 @@ -import type { RegistryEntry } from "../../shared.ts"; - -export const opencodeProvider: RegistryEntry = { - id: "opencode", - alias: "oc", - format: "openai", - executor: "opencode", - baseUrl: "https://opencode.ai/zen/v1", - modelsUrl: "https://opencode.ai/zen/v1/models", - authType: "apikey", - authHeader: "Authorization", - authPrefix: "Bearer", - passthroughModels: true, - defaultContextLength: 200000, - models: [ - // #2900: big-pickle's upstream runs DeepSeek thinking mode — declare the - // interleaved reasoning_content contract so follow-up/tool-use turns replay - // it (otherwise DeepSeek returns 400 "reasoning_content ... must be passed back"). - { - id: "big-pickle", - name: "Big Pickle", - supportsReasoning: true, - interleavedField: "reasoning_content", - }, - // #MUSE_SPARK: Muse Spark is served by OpenCode Zen ONLY on the OpenAI - // Responses API (https://opencode.ai/zen/v1/responses), not /chat/completions - // (confirmed in the official OpenCode Zen docs: https://opencode.ai/docs/zen/). - // Without targetFormat:"openai-responses" these models fall through to the - // default chat/completions pass-through and the upstream returns null/empty - // content (see issue #10867). The opencode provider is passthrough, so - // declaring them here only sets the wire format / capability flags — the - // live upstream model list already advertises both ids. - // #12681: real window confirmed against the opencode-go registry's own - // muse-spark-1.2-contributor entries (contextLength: 1048576, maxOutputTokens: - // 131072) — without an explicit value here resolution fell back to the - // provider-wide defaultContextLength (200000), understating the real window. - { - id: "muse-spark-1.2", - name: "Muse Spark 1.2", - supportsReasoning: true, - targetFormat: "openai-responses", - contextLength: 1048576, - maxOutputTokens: 131072, - }, - { - id: "muse-spark-1.2-contributor-free", - name: "Muse Spark 1.2 Contributor Free", - supportsReasoning: true, - targetFormat: "openai-responses", - contextLength: 1048576, - maxOutputTokens: 131072, - }, - // Muse Spark 1.3 is served only on the Responses API, same as 1.2 above. - // Its window matches the published OpenCode catalog instead of the - // 200000 provider default. - { - id: "muse-spark-1.3", - name: "Muse Spark 1.3", - supportsReasoning: true, - targetFormat: "openai-responses", - contextLength: 1048576, - maxOutputTokens: 131072, - }, - { - id: "muse-spark-1.3-contributor-free", - name: "Muse Spark 1.3 Contributor Free", - supportsReasoning: true, - targetFormat: "openai-responses", - contextLength: 1048576, - maxOutputTokens: 131072, - }, - { id: "deepseek-v4-flash-free", name: "DeepSeek V4 Flash Free", supportsReasoning: true }, - // #6998: 2026-07-14 refresh — the upstream free tier rotated its lineup; - // minimax-m3-free, minimax-m2.5-free, ling-2.6-1t-free, - // trinity-large-preview-free, nemotron-3-super-free and qwen3.6-plus-free - // were delisted (401 "Model X is not supported") and replaced by the 4 - // entries below, confirmed live against - // https://opencode.ai/zen/v1/chat/completions. - { id: "mimo-v2.5-free", name: "MiMo V2.5 Free", contextLength: 1048576 }, - // MiMo V2.6 Flash Free ships a 1M window upstream (same as V2.5); without - // this row it falls through to the 200000 provider default and clients - // compact far too early. - { - id: "mimo-v2.6-flash-free", - name: "MiMo V2.6 Flash Free", - contextLength: 1048576, - maxOutputTokens: 131072, - }, - { id: "hy3-free", name: "HY3 Free", contextLength: 131000 }, - { id: "nemotron-3-ultra-free", name: "Nemotron 3 Ultra Free", contextLength: 1000000 }, - { id: "north-mini-code-free", name: "North Mini Code Free", contextLength: 131000 }, - ], -}; diff --git a/open-sse/executors/base/reasoningEffort.ts b/open-sse/executors/base/reasoningEffort.ts index 020daff11c46..7e54e5b20300 100644 --- a/open-sse/executors/base/reasoningEffort.ts +++ b/open-sse/executors/base/reasoningEffort.ts @@ -84,12 +84,7 @@ export function isOllamaCloudProvider(provider: string): boolean { } export function isOpencodeGoProvider(provider: string): boolean { - return ( - provider === "opencode-go" || - provider === "opencode-zen" || - provider === "opencode" || - provider === "opencode_go" - ); + return provider === "opencode-go" || provider === "opencode-zen" || provider === "opencode_go"; } export function isSenseNovaDeepSeekV4Flash(provider: string, model: string | undefined): boolean { diff --git a/open-sse/executors/index.ts b/open-sse/executors/index.ts index 43496d0e5e01..ec107eed1557 100644 --- a/open-sse/executors/index.ts +++ b/open-sse/executors/index.ts @@ -75,7 +75,6 @@ const lazyExecutors: Record Promise> = { fb: () => import("./freebuff.ts").then((m) => new m.FreebuffExecutor()), // Alias "opencode-zen": () => import("./opencode.ts").then((m) => new m.OpencodeExecutor("opencode-zen")), "opencode-go": () => import("./opencode.ts").then((m) => new m.OpencodeExecutor("opencode-go")), - opencode: () => import("./opencode.ts").then((m) => new m.OpencodeExecutor("opencode-zen")), // Alias for opencode-zen vertex: () => import("./vertex.ts").then((m) => new m.VertexExecutor()), "vertex-partner": () => import("./vertex.ts").then((m) => new m.VertexExecutor()), cliproxyapi: () => import("./cliproxyapi.ts").then((m) => new m.CliproxyapiExecutor()), diff --git a/open-sse/executors/opencode.ts b/open-sse/executors/opencode.ts index c9630ef3c240..53047277e20b 100644 --- a/open-sse/executors/opencode.ts +++ b/open-sse/executors/opencode.ts @@ -27,7 +27,6 @@ import { noteStoredFallback, } from "./opencodeResilienceNotes.ts"; import { - clientSuppliedOpencodeSession, forwardOpencodeClientHeaders, resolveOpencodeCliDefaults, } from "../utils/opencodeHeaders.ts"; @@ -45,27 +44,13 @@ import { extractChatcmplId, recordRotationSnapshot, } from "./accountRotation.ts"; -import { - markCooldown, - markOutcome, - markSuccess, - noteResponseServed, -} from "./opencodeAccountHealth.ts"; +import { markCooldown, markOutcome, markSuccess } from "./opencodeAccountHealth.ts"; import { isOpencodeGeoBlocked, proxyKeyOf, poolReselectKeyOf, isOpencodeUserBlocked, } from "./opencodeGeoBlock.ts"; -import { - attemptFor, - isGatedFreeTierRequest, - isPremiumOpencodeModel, - noteFreeTierOutcome, - prepareFreeTierRequest, - rebuildJsonFromForcedStream, - surfaceFromBaseUrl, -} from "./opencodeFreeTierContract.ts"; import { applyMuseSparkMinOutputTokens, createMuseSparkStreamFinishNormalizer, @@ -73,17 +58,7 @@ import { normalizeMuseSparkFinishReason, } from "./opencodeMuseSpark.ts"; import { currentRequestContext, runInRequestContext } from "./opencodeRequestContext.ts"; -import { - handleLoopFreeTierRefusal, - isOwnToolsRetryableRefusal, - retryFreeTierRefusalWithObservedTools, -} from "./opencodeFreeTierRetry.ts"; -import { withRequestShapeRetry } from "./opencodeRequestShape.ts"; import { trimOversizedToolEnums } from "./opencodeEnumTrim.ts"; - -// Re-exported: the free-model catalog moved to the contract module (it decides whether the -// contract applies), and existing importers keep resolving it from the executor. -export { isPremiumOpencodeModel }; import { isResponsesFirstByteTimeout, makeStallGuardedCall, @@ -118,12 +93,14 @@ import { } from "./opencodeParkResume.ts"; /** - * The main OpenCode Zen host, shared by the `opencode` and `opencode-zen` - * registry entries. Used to scope the `x-api-key` auth override (#12633) away + * The main OpenCode Zen host (the `opencode-zen` registry entry). Used to scope the `x-api-key` auth override (#12633) away * from `opencode-go`, which serves a different upstream (`.../zen/go/v1`). */ const ZEN_BASE_URL = "https://opencode.ai/zen/v1"; +/** The OpenCode Go host (`opencode-go`), which keeps an agent's own User-Agent (#15311). */ +const GO_BASE_URL = "https://opencode.ai/zen/go/v1"; + /** * Per-account proxy configuration, persisted by NoAuthAccountCard under * `providerSpecificData.accountProxies` (keyed by the account id, which the UI @@ -189,8 +166,8 @@ export function parseEffortLevel(model: string): { baseModel: string; effort: st /** * Resolves the registry `targetFormat` for a model, aliasing `provider` first. * - * `PROVIDER_MODELS` is keyed by the provider's public ALIAS (e.g. `"oc"`), not its - * raw registry id (e.g. `"opencode"`) — mirrors `resolveChatCoreTargetFormat()` + * `PROVIDER_MODELS` is keyed by the provider's public ALIAS, not its raw registry + * id — mirrors `resolveChatCoreTargetFormat()` * (`handlers/chatCore/targetFormat.ts`), which already aliases before calling * `getModelTargetFormat()`. Calling it with the raw id here made every entry miss * silently (fell through to `"openai"`), while chatCore's own request-body @@ -211,35 +188,13 @@ export { } from "./opencodeMuseSpark.ts"; export class OpencodeExecutor extends BaseExecutor { - /** Delegates to `isPremiumOpencodeModel`. Exported for testability. */ - static isPremiumModel(model: string, provider: string): boolean { - return isPremiumOpencodeModel(model, provider); - } - /** - * Note the outcome of a forced-stream response without reading its body: a success - * confirms the borrowed shape, anything else carries no verdict (the paths that hold - * the verdict note it explicitly where they already read it). - */ - private noteForcedStreamOutcome(input: ExecuteInput, result: ExecutorExecuteResult): void { - const attempt = attemptFor(input.body); - const response = - result instanceof Response ? result : "response" in result ? result.response : null; - noteFreeTierOutcome(attempt, { - ok: !!response?.ok, - status: response?.ok ? (response.status ?? null) : null, - bodyText: null, - }); - } - - /** - * The target format and the client session of the request being served. While `execute()` - * runs they live in that request's own context (this instance is shared and requests - * overlap); outside it they fall back to plain fields, which is how `buildHeaders`, - * `buildUrl` and `transformRequest` are exercised on their own. + * The target format of the request being served. While `execute()` runs it lives in that + * request's own context (this instance is shared and requests overlap); outside it it + * falls back to a plain field, which is how `buildHeaders`, `buildUrl` and + * `transformRequest` are exercised on their own. */ private _formatFallback: string | null = null; - private _sessionFallback: string | undefined; get _requestFormat(): string | null { return currentRequestContext()?.format ?? this._formatFallback; } @@ -248,31 +203,7 @@ export class OpencodeExecutor extends BaseExecutor { if (context) context.format = value; else this._formatFallback = value; } - private get _clientSession(): string | undefined { - const context = currentRequestContext(); - return context ? context.session : this._sessionFallback; - } - private set _clientSession(value: string | undefined) { - const context = currentRequestContext(); - if (context) context.session = value; - else this._sessionFallback = value; - } - private _surface = () => surfaceFromBaseUrl(this.config?.baseUrl); - - /** Free-tier retry context: the request-scoped contract state the retry helper needs. */ - private freeTierRetryCtx(input: ExecuteInput) { - // #14148 moved the contract attempt off the executor: it is keyed by the - // request body, so read it back from there instead of a shared field. - const attempt = attemptFor(input.body); - return { - surface: this._surface(), - provider: this.provider, - requestFormat: this._requestFormat, - clientSession: this._clientSession, - borrowed: attempt?.borrowed, - clientToolNames: attempt?.clientToolNames ?? [], - }; - } + private _isGoSurface = () => this.config?.baseUrl === GO_BASE_URL; // Not `private`: passed as the shared pick cursor to // pickRotatableAccount(), which needs a plain `{ nextAccountIdx }` shape — @@ -360,52 +291,6 @@ export class OpencodeExecutor extends BaseExecutor { * non-streaming success responses. Non-muse-spark models pass through * untouched. */ - /** - * Hand a JSON caller a JSON body even though the free-tier contract forced the upstream - * request to stream. A streaming caller, a refusal and an already-JSON body pass through. - */ - private finalizeForcedStream( - input: ExecuteInput, - result: ExecutorExecuteResult - ): ExecutorExecuteResult { - this.noteForcedStreamOutcome(input, result); - if (input.stream) return result; - if (!(result instanceof Response)) { - if (!("response" in result) || !result.response) return result; - } - // Non-null exactly when the contract applied: stands in for the old surface/model guard. - const model = attemptFor(input.body)?.model; - if (!model) return result; - if (result instanceof Response) { - const rebuilt = rebuildJsonFromForcedStream(result, this._requestFormat, model); - return rebuilt === result ? result : rebuilt; - } - const rebuilt = rebuildJsonFromForcedStream(result.response, this._requestFormat, model); - return rebuilt === result.response ? result : { ...result, response: rebuilt }; - } - - /** - * Count a refusal that says something about the borrowed tools, on a path - * that already holds the verdict. Only 403/451 carry that verdict, so only - * they pay for a body read — anything else leaves the store alone. - */ - private async noteFreeTierRefusal( - input: ExecuteInput, - response: Response, - log: ExecuteInput["log"] - ): Promise { - const attempt = attemptFor(input.body); - if (!attempt || !attempt.borrowed || attempt.probe) return; - if (response.status !== 403 && response.status !== 451) return; - let bodyText: string | null = null; - try { - bodyText = await response.clone().text(); - } catch { - log?.debug?.("OPENCODE", "body read failed on borrowed-shape check"); - } - noteFreeTierOutcome(attempt, { ok: false, status: response.status, bodyText }); - } - private normalizeMuseSparkResponse( input: ExecuteInput, result: ExecutorExecuteResult @@ -527,7 +412,7 @@ export class OpencodeExecutor extends BaseExecutor { const reselect = currentAppliedProxySink()?.reselectPoolMember; const ctx = currentRequestContext(); if (ctx && typeof reselect === "function") ctx.reselectPoolMember = reselect; - return withRequestShapeRetry(input, (i) => this.executeOnce(i)); + return this.executeOnce(input); }); } finally { releaseRequestList(input.body, this.accountHealth); @@ -537,32 +422,6 @@ export class OpencodeExecutor extends BaseExecutor { private async executeOnce(input: ExecuteInput) { this._requestFormat = resolveOpencodeTargetFormat(this.provider, input.model); - // #8681: Gate premium opencode models behind a usable API key. - // When the connection is keyless (no apiKey, no accessToken) and the model - // is a premium model (not on the free tier), return a clear 402 error - // instead of proxying the raw upstream 401 "Missing API key" response. - const creds = input.credentials; - const isKeyless = - !creds?.apiKey && !creds?.accessToken && !creds?.providerSpecificData?.extraApiKeys; - if (isKeyless && isPremiumOpencodeModel(input.model, this.provider)) { - const bodyJson = JSON.stringify({ - error: { - message: "This model requires an opencode API key — add one in Settings → Providers.", - type: "invalid_request_error", - code: "premium_model_requires_key", - }, - }); - return { - response: new Response(bodyJson, { - status: 402, - headers: { "Content-Type": "application/json" }, - }), - url: "", - headers: {} as Record, - transformedBody: null, - }; - } - try { // muse-spark reasoning models consume the entire output budget on hidden // server-side reasoning; small caller budgets come back as empty-message @@ -636,29 +495,6 @@ export class OpencodeExecutor extends BaseExecutor { const single = (await guardStall( await (hasAmbientProxyContext() ? dispatch() : runWithDirectFetchContext(dispatch)) )) as HttpExecuteResult; - const retryAfterRefusal = await retryFreeTierRefusalWithObservedTools( - this.freeTierRetryCtx(input), - input, - single, - log, - cid, - (retryInput) => - guardStall( - hasAmbientProxyContext() - ? super.execute(retryInput) - : runWithDirectFetchContext(() => super.execute(retryInput)) - ) as unknown as Promise - ); - if (retryAfterRefusal) { - await this.noteFreeTierRefusal(input, retryAfterRefusal.response, log); - return this.finalizeForcedStream( - input, - this.normalizeMuseSparkResponse(input, retryAfterRefusal) - ); - } - if (single.response.status === 403 || single.response.status === 451) { - await this.noteFreeTierRefusal(input, single.response, log); - } if (single.response.status === 400) { let bodyText: string | null = null; try { @@ -673,9 +509,9 @@ export class OpencodeExecutor extends BaseExecutor { "OPENCODE", `${cid}upstream empty rejection on direct account (${chatcmplId}), retrying once…` ); - return this.finalizeForcedStream( + return this.normalizeMuseSparkResponse( input, - this.normalizeMuseSparkResponse(input, await guardStall(await super.execute(input))) + await guardStall(await super.execute(input)) ); } log?.debug?.( @@ -684,7 +520,7 @@ export class OpencodeExecutor extends BaseExecutor { ); } } - return this.finalizeForcedStream(input, this.normalizeMuseSparkResponse(input, single)); + return this.normalizeMuseSparkResponse(input, single); } // This loop only ever dispatches through super.execute() (the HTTP request @@ -1166,36 +1002,6 @@ export class OpencodeExecutor extends BaseExecutor { abandonedResponse = result.response; continue; } - // Free-tier refusal: upstream rejected the REQUEST (client identity or - // request shape), not this account. Handled in opencodeFreeTierRetry.ts - // (one bounded retry with observed tools appended, then unchanged return). - if (bodyText !== null && isOwnToolsRetryableRefusal(status, bodyText)) { - noteFreeTierOutcome(attemptFor(input.body), { - ok: false, - status, - bodyText, - }); - if (attributionOn && skippedCooldown.size > 0) { - this.logSkippedCooldownAccounts(log, cid, skippedCooldown); - } - return await handleLoopFreeTierRefusal( - (retried) => - this.finalizeForcedStream(input, this.normalizeMuseSparkResponse(input, retried)), - input, - result, - this.freeTierRetryCtx(input), - { account, masked, proxyKey: proxyKeyOf(account.proxy) ?? "direct" }, - log, - cid, - { - dispatch: (retryInput) => - runWithProxyContext(account.proxy, () => - super.execute({ ...retryInput, skipUpstreamRetry: true }) - ) as Promise, - noteServed: (a) => noteResponseServed(a as typeof account), - } - ); - } } // Empty upstream rejection (malformed 400: no error field, no real @@ -1235,10 +1041,10 @@ export class OpencodeExecutor extends BaseExecutor { if (attributionOn && skippedCooldown.size > 0) { this.logSkippedCooldownAccounts(log, cid, skippedCooldown); } - return this.finalizeForcedStream(input, this.normalizeMuseSparkResponse(input, result)); + return this.normalizeMuseSparkResponse(input, result); } finally { // Single release point for every post-dispatch arm (5xx, 403/451, - // free-tier, 429, 400, success): the released-guard makes the 429 + // 429, 400, success): the released-guard makes the 429 // internal release a harmless no-op. egressPacing.releasePacingSlot(egressRelease); } @@ -1258,12 +1064,9 @@ export class OpencodeExecutor extends BaseExecutor { if (attributionOn && skippedCooldown.size > 0) { this.logSkippedCooldownAccounts(log, cid, skippedCooldown); } - return this.finalizeForcedStream( + return this.normalizeMuseSparkResponse( input, - this.normalizeMuseSparkResponse( - input, - lastResult ?? (await guardStall(await super.execute(input))) - ) + lastResult ?? (await guardStall(await super.execute(input))) ); } finally { this._requestFormat = null; @@ -1298,7 +1101,7 @@ export class OpencodeExecutor extends BaseExecutor { * models) requires `x-api-key`, not `Authorization: Bearer` — unlike the * default `/chat/completions` endpoint on the same host, which accepts * Bearer. Scoped by baseUrl (not provider id/alias) so this only applies to - * the main Zen host (`opencode` / `opencode-zen`, both `https://opencode.ai/zen/v1`) + * the main Zen host (`opencode-zen`, `https://opencode.ai/zen/v1`) * and never to opencode-go, which serves Responses-format models from a * different upstream (`https://opencode.ai/zen/go/v1`) that expects Bearer. */ @@ -1333,14 +1136,7 @@ export class OpencodeExecutor extends BaseExecutor { headers["anthropic-version"] = "2023-06-01"; } - // The free tier only answers streamed requests (measured 2026-09-17: a non-streamed - // body answers 403 FreeTierError), so a JSON client is served by streaming upstream and - // rebuilding the JSON body from the event stream — the path chatCore already takes for - // any buffered event-stream response. Announcing the stream here keeps that buffering an - // expected outcome rather than a warning. - const gatedScope = - Boolean(model) && isGatedFreeTierRequest(this._surface(), this.provider, model); - if (stream || gatedScope) { + if (stream) { headers["Accept"] = "text/event-stream"; } @@ -1349,17 +1145,13 @@ export class OpencodeExecutor extends BaseExecutor { // OPENCODE_SYNTHESIZE_CLI_HEADERS=false. Client-supplied headers always win; // User-Agent is replaced with the CLI UA unless the client already sends one that // looks like the OpenCode CLI. Default values match 9router's proven defaults. - const cliDefaults = resolveOpencodeCliDefaults( - this.config?.id || this.provider || "opencode", - gatedScope - ); + const cliDefaults = resolveOpencodeCliDefaults(this.config?.id || this.provider); - this._clientSession = clientSuppliedOpencodeSession(clientHeaders, body); if (clientHeaders || cliDefaults) { forwardOpencodeClientHeaders(headers, clientHeaders ?? {}, { synthesizeRequestId: true, cliDefaults, - keepAgentUserAgent: this._surface() === "go" && !gatedScope, // #15311 + keepAgentUserAgent: this._isGoSurface(), // #15311 sessionBody: projectOpencodeSessionBody(body), }); } @@ -1375,16 +1167,13 @@ export class OpencodeExecutor extends BaseExecutor { } /** - * OpenCode's free DeepSeek V4 Flash endpoint accepts json_object but + * OpenCode Zen's DeepSeek V4 Flash Free endpoint accepts json_object but * rejects json_schema response_format with HTTP 400. Preserve the schema * as an instruction and downgrade only this proven-incompatible route to * json_object so callers still receive structured JSON. */ private applyDeepSeekJsonSchemaFallback(model: string, body: T): T { - if ( - model !== "deepseek-v4-flash-free" || - (this.provider !== "opencode" && this.provider !== "opencode-zen") - ) { + if (model !== "deepseek-v4-flash-free" || this.provider !== "opencode-zen") { return body; } @@ -1453,23 +1242,9 @@ export class OpencodeExecutor extends BaseExecutor { ): any { let modifiedBody = super.transformRequest(model, body, stream, credentials); modifiedBody = this.applyDeepSeekJsonSchemaFallback(model, modifiedBody); - // Free-tier request contract (see opencodeFreeTierContract.ts): streaming plus a - // non-empty tools array, in the shape of the surface this model is served on. Paid - // models on the same host are not gated and stay untouched. - const prepared = prepareFreeTierRequest( - modifiedBody, - this._requestFormat ?? resolveOpencodeTargetFormat(this.provider, model), - this._surface(), - this.provider, - model, - this._clientSession, - body - ); - modifiedBody = prepared.body; // OpenCode's upstream 400s a request when a single enum property carries // more than 250 values or 15000 combined characters (VSCode-shaped caller - // tools hit this). Cap oversized enums on every surface before dispatch — - // covers caller tools and contract-borrowed declarations alike. + // tools hit this). Cap oversized enums on every surface before dispatch. if ( modifiedBody && typeof modifiedBody === "object" && diff --git a/open-sse/executors/opencodeFreeTierContract.ts b/open-sse/executors/opencodeFreeTierContract.ts deleted file mode 100644 index 328333a59b74..000000000000 --- a/open-sse/executors/opencodeFreeTierContract.ts +++ /dev/null @@ -1,531 +0,0 @@ -/** - * opencodeFreeTierContract.ts — the request contract OpenCode Zen's free tier enforces. - * - * Measured against the live endpoint on 2026-09-17, on three models and both the Chat - * Completions and Responses surfaces: the upstream answers 403 FreeTierError unless the - * request carries all four of - * - * 1. `stream: true` in the body, - * 2. a non-empty `tools` array (the content is not inspected), - * 3. a session header shaped `ses_` + 12 hex + 14 base62 (the shape is checked, the - * value is not — 12 arbitrary hex digits pass), - * 4. a `User-Agent` carrying `opencode/` with version >= 1.17 (an older - * version answers 426 UpgradeRequired rather than 403). - * - * Removing any single one of the four turns a 200 into a 403. Paid models on the same - * host are not gated (a paid model without tools answers 401 CreditsError), which is why - * `requiresFreeTierRequestContract` narrows the contract to free-tier models. - * - * The module also owns the free-model catalog — the catalog is what decides whether the - * contract applies, so the two belong together and the executor imports them from here — - * and the way back: the forced stream is rebuilt into a JSON body for a caller that asked - * for JSON, reusing the shared event-stream parsers. - */ -import { parseSSEToOpenAIResponse, parseSSEToResponsesOutput } from "../handlers/sseParser.ts"; -import { - confirmBorrowedToolNames, - getObservedToolNames, - noteRefusedBorrowedToolNames, - recordAcceptedToolNames, - resolvePlaceholderNames, -} from "./opencodeToolObservation.ts"; -import { isOpencodeFreeTierRefusal } from "./opencodeGeoBlock.ts"; -import { - forgetAttempt, - planShape, - recallAttempt, - recordInjection, - rememberAttempt, - shapeKeyOf, -} from "./opencodeRequestShape.ts"; - -/** - * What one gated request declared, kept until its outcome is known. - * - * `borrowed` means the placeholder came from the observation store rather than from the - * caller or the configuration, which is the only case where a refusal says anything about - * that store. - */ -export interface FreeTierContractAttempt { - readonly provider: string; - readonly model: string; - readonly session: string | undefined; - readonly borrowed: boolean; - readonly clientToolNames: readonly string[]; - /** A refusal may still be replayed in the other shape: its outcome is noted afterwards. */ - readonly probe?: boolean; - /** - * True when this attempt injected placeholder tools the caller had not sent. Kept as a - * separate flag from `borrowed`: a placeholder this layer added is ours to attribute, while - * `borrowed` means it came from the observation store. - */ - readonly injectedPlaceholders?: boolean; -} - -/** - * Models that work WITHOUT any API key on the free/noauth opencode tier. - * - * The upstream free tier rotates frequently — when a `-free` suffix model is - * delisted upstream, the upstream returns "Model X is not supported" (a separate - * issue from this gate). The set is defined by two data sources: - * - * 1. **Known free models** — models explicitly listed in the noauth - * `opencode` provider registry (`open-sse/config/providers/registry/opencode/index.ts`). - * These are the canonical free models. `deepseek-v4-flash-free` appears in both - * the noauth AND the zen registry (it is free on both tiers). - * 2. **`-free` suffix** — any model whose id ends in `-free`. This automatically - * covers upstream free-tier additions without a code deploy. - * - * For `opencode-go`, there is no free tier — ALL models require an API key. - */ -const OPENCODE_FREE_MODELS = new Set([ - "big-pickle", - "deepseek-v4-flash-free", - "mimo-v2.5-free", - "hy3-free", - "nemotron-3-ultra-free", - "north-mini-code-free", -]); - -/** - * Determine whether a model requires an API key on the given opencode provider. - * - * - `opencode-go`: ALL models require a key (no free tier). - * - `opencode` / `opencode-zen`: premium = any model NOT in the free set (known - * free models OR ending in `-free`). - * - Unknown models are assumed premium (fail-safe). - */ -export function isPremiumOpencodeModel(model: string, provider: string): boolean { - // opencode-go has no free tier — every model requires a key. - if (provider === "opencode-go") return true; - - // Models ending in `-free` are always free on the noauth/zen tier. - if (model.endsWith("-free")) return false; - - // Check the known free model catalog. - return !OPENCODE_FREE_MODELS.has(model); -} - -/** - * The upstream surface a request is served on, as told apart by the registry `baseUrl`. - * - * The gate is a property of the surface, not of billing: `/zen/v1` refuses a request that - * carries no tools, while `/zen/go/v1` refuses one that carries any (upstream - * anomalyco/opencode#44300 and #44382, "Endpoint is unavailable" for any request - * containing tools). Passing the surface in keeps this module free of registry imports and - * covers every entry of the family — including the `oc` alias, which resolves to - * `opencode` before an executor is ever picked. - */ -export type OpencodeSurface = "zen" | "go" | "other"; - -const ZEN_SURFACE_BASE_URL = "https://opencode.ai/zen/v1"; -const GO_SURFACE_BASE_URL = "https://opencode.ai/zen/go/v1"; - -/** Tell the surfaces apart by registry `baseUrl`, so provider ids and aliases stay out. */ -export function surfaceFromBaseUrl(baseUrl: string | null | undefined): OpencodeSurface { - if (baseUrl === ZEN_SURFACE_BASE_URL) return "zen"; - if (baseUrl === GO_SURFACE_BASE_URL) return "go"; - return "other"; -} - -/** - * Operator opt-out for the body half of the contract. - * - * The headers stay in place either way: they are what the upstream validates by shape, and - * they cost nothing. The body half is the half built on an observation of someone else's - * service, so it is the half worth being able to switch off without waiting for a release. - * Read per call, so a change takes effect immediately. - */ -function isBodyContractEnabled(): boolean { - return (process.env.OPENCODE_FREE_TIER_REQUEST_CONTRACT || "").trim().toLowerCase() !== "off"; -} - -/** - * Whether the upstream gates this request at all. - * - * Scope only — it ignores the opt-out on purpose, because the headers are applied either - * way: they are what the upstream validates by shape, they cost nothing, and switching - * them off with the body half would turn an opt-out into a second failure mode. - */ -export function isGatedFreeTierRequest( - surface: OpencodeSurface, - provider: string, - model: string -): boolean { - if (surface !== "zen") return false; - return !isPremiumOpencodeModel(model, provider); -} - -/** Whether the body half of the contract applies: gated, and not switched off. */ -export function requiresFreeTierRequestContract( - surface: OpencodeSurface, - provider: string, - model: string -): boolean { - return isGatedFreeTierRequest(surface, provider, model) && isBodyContractEnabled(); -} - -/** The placeholder tool name the official client uses for the same purpose. */ -const PLACEHOLDER_TOOL_NAME = "_noop"; -export const DEFAULT_PLACEHOLDER_TOOL_NAME = PLACEHOLDER_TOOL_NAME; - -/** - * Operator-supplied placeholder tool names, comma-separated. - * - * The upstream inspects which names a request declares, and what it accepts differs by - * model and moves over time (measured 2026-09-18: one made-up name is accepted on - * `big-pickle` and refused on two other free models that had accepted it the day before). - * That is an observation about someone else's service, not a fact about this project, so - * it belongs in configuration rather than in a constant that needs a release to change. - * - * Empty or unset falls back to the built-in name, so an install that sets nothing keeps - * the previous behaviour. Read per call, so a change takes effect immediately. - */ -export function configuredPlaceholderToolNames(): string[] { - const raw = process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS || ""; - const kept: string[] = []; - for (const part of raw.split(",")) { - const name = part.trim(); - if (kept.length >= 32) break; - if (!/^[A-Za-z_][A-Za-z0-9_-]{0,63}$/.test(name)) continue; - if (!kept.includes(name)) kept.push(name); - } - return kept; -} -const PLACEHOLDER_TOOL_DESCRIPTION = - "Do not call this tool. It exists only for API compatibility and must never be invoked."; -const PLACEHOLDER_TOOL_PARAMETERS = { type: "object", properties: {} } as const; - -/** - * Bring a free-tier request up to the upstream contract, without overriding anything the - * caller already decided: client tools are kept as they are, and the placeholder tool is - * only added when the caller sent none or when client-supplied tools do not yet carry the - * required placeholder tool. Idempotent. - * - * The placeholder differs per surface: Chat Completions takes the nested function shape, - * the Responses surface takes the flat one. Neither carries a `tool_choice` — the upstream - * rejects any value but "auto" (measured 2026-09-18: 400 invalid_request_error, `only - * "auto" is supported for tool_choice`), so a `tool_choice` the caller did not send is - * never added, and one the caller did send travels unchanged. Any other body format only - * gets the streaming flag: injecting a tool shape blind would be a guess. - * - * Which names go in is resolved by `resolvePlaceholderNames`, because the upstream does - * inspect them. - */ -export function applyFreeTierRequestContract( - body: T, - requestFormat: string | null, - placeholderNames: readonly string[] = [PLACEHOLDER_TOOL_NAME] -): T { - if (!body || typeof body !== "object" || Array.isArray(body)) return body; - const record = body as Record; - const next: Record = { ...record, stream: true }; - - const existingNames = new Set(clientToolNamesOf(next)); - const baseNames = placeholderNames.length > 0 ? placeholderNames : [PLACEHOLDER_TOOL_NAME]; - const namesToAdd = baseNames.filter((name) => !existingNames.has(name)); - - if (namesToAdd.length === 0) return next as T; - - const existingTools = Array.isArray(next.tools) ? [...next.tools] : []; - - if (requestFormat === "openai-responses") { - next.tools = [ - ...existingTools, - ...namesToAdd.map((name) => ({ - type: "function", - name, - description: PLACEHOLDER_TOOL_DESCRIPTION, - parameters: PLACEHOLDER_TOOL_PARAMETERS, - })), - ]; - return next as T; - } - - if (requestFormat === "openai" || requestFormat === null) { - next.tools = [ - ...existingTools, - ...namesToAdd.map((name) => ({ - type: "function", - function: { - name, - description: PLACEHOLDER_TOOL_DESCRIPTION, - parameters: PLACEHOLDER_TOOL_PARAMETERS, - }, - })), - ]; - return next as T; - } - - return next as T; -} - -/** - * Merge a gated request's own tools with the names the store last saw accepted. - * - * A client that declares tools is left alone by `applyFreeTierRequestContract` — but the - * upstream inspects WHICH names are declared, and a subset it never saw pass (measured - * 2026-09-21: the 5 explore-agent tools `[glob, grep, read, webfetch, websearch]` on - * `muse-spark-1.3-contributor-free`, 11 refusals, zero passes) is answered 403 - * FreeTierError. When such a refusal comes back, this rebuilds the same body with the - * observed names appended after the client's own entries: the client tools keep their - * full shape (description, parameters) so the model can still call them, while the - * appended names are list entries with an empty parameter object — the same shape the - * placeholder path uses, never a callable tool. - * - * Pure: returns the input body unchanged when no observed names are missing, so the - * caller can skip the retry on identity alone. Resolution order is the store's own: - * this conversation first, then any conversation on the model, then the operator's - * configured names. - */ -export function mergeClientToolsWithObserved( - body: T, - requestFormat: string | null, - provider: string, - model: string, - session: string | undefined, - configured: readonly string[] -): T { - if (!body || typeof body !== "object" || Array.isArray(body)) return body; - const record = body as Record; - if (!Array.isArray(record.tools) || record.tools.length === 0) return body; - const own = session ? getObservedToolNames(provider, model, session) : null; - const observed = own ?? getObservedToolNames(provider, model) ?? configured; - const have = new Set(clientToolNamesOf(body)); - const missing = observed.filter((name) => !have.has(name)); - if (missing.length === 0) return body; - const next: Record = { ...(record as Record) }; - if (requestFormat === "openai-responses") { - next.tools = [ - ...(record.tools as unknown[]), - ...missing.map((name) => ({ - type: "function", - name, - description: PLACEHOLDER_TOOL_DESCRIPTION, - parameters: PLACEHOLDER_TOOL_PARAMETERS, - })), - ]; - return next as T; - } - if (requestFormat === "openai" || requestFormat === null) { - next.tools = [ - ...(record.tools as unknown[]), - ...missing.map((name) => ({ - type: "function", - function: { - name, - description: PLACEHOLDER_TOOL_DESCRIPTION, - parameters: PLACEHOLDER_TOOL_PARAMETERS, - }, - })), - ]; - return next as T; - } - return body; -} - -function clientToolNamesOf(body: unknown): string[] { - if (!body || typeof body !== "object" || Array.isArray(body)) return []; - const tools = (body as Record).tools; - if (!Array.isArray(tools)) return []; - const names: string[] = []; - for (const tool of tools) { - if (!tool || typeof tool !== "object") continue; - const entry = tool as { name?: unknown; function?: { name?: unknown } }; - const name = typeof entry.name === "string" ? entry.name : entry.function?.name; - if (typeof name === "string") names.push(name); - } - return names; -} - -/** - * Bring one request up to the contract and report what it ended up declaring. - * - * Single entry point for the executor: it decides whether the contract applies to this - * surface and model, resolves the placeholder names, applies the body changes, and hands - * back the attempt so the outcome can be fed to `noteFreeTierOutcome`. - */ -/** - * The attempt of the request being served, found by the identity of the body the executor was - * handed. It cannot live on the executor: that instance is shared, and two requests in flight - * would read each other's attempt when they finish. It is released when the request is over. - */ -export function attemptFor(origin: unknown): FreeTierContractAttempt | null { - return recallAttempt(origin); -} - -function isTrackable(value: unknown): value is object { - return typeof value === "object" && value !== null; -} - -export function prepareFreeTierRequest( - body: T, - requestFormat: string | null, - surface: OpencodeSurface, - provider: string, - model: string, - session?: string, - origin?: object -): { body: T; attempt: FreeTierContractAttempt | null } { - const clientToolNames = clientToolNamesOf(body); - if (!requiresFreeTierRequestContract(surface, provider, model)) { - if (isTrackable(origin)) forgetAttempt(origin); - return { body, attempt: null }; - } - const eligible = isTrackable(origin) && clientToolNames.length === 0; - const key = eligible ? shapeKeyOf(provider, model, body) : ""; - const plan = - isTrackable(origin) && eligible - ? planShape(origin, key) - : { shape: "tools" as const, probe: false }; - const chosen = plan.shape; - const names = resolvePlaceholderNames(provider, model, session, configuredPlaceholderToolNames()); - const borrowed = clientToolNames.length === 0 && names.length > 0 && chosen === "tools"; - const attempt: FreeTierContractAttempt = { - provider, - model, - session, - borrowed, - clientToolNames, - probe: plan.probe, - }; - if (isTrackable(origin)) rememberAttempt(origin, attempt); - if (isTrackable(origin) && eligible) { - recordInjection(origin, { - shape: chosen, - key, - probe: plan.probe, - replayNote: (verdict) => noteFreeTierOutcome({ ...attempt, probe: false }, verdict), - }); - } - return { - body: - chosen === "bare" - ? withStreaming(body) - : applyFreeTierRequestContract(body, requestFormat, names), - attempt, - }; -} - -function withStreaming(body: T): T { - if (!body || typeof body !== "object" || Array.isArray(body)) return body; - return { ...(body as Record), stream: true } as T; -} - -/** - * What the upstream answered, with enough detail to tell a refusal about the - * tools apart from any other failure. A bare boolean keeps the legacy callers - * compiling: `true` counts as an acceptance, `false` carries no verdict and is - * never counted. - */ -export interface FreeTierOutcome { - readonly ok: boolean; - readonly status: number | null; - readonly bodyText: string | null; -} - -/** - * Feed a gated request's outcome back, so the next one borrows a shape that still works. - * - * An accepted request teaches which names the upstream takes right now; a refused one only - * teaches something when the names it carried came from the store AND the refusal says - * something about the tools (a 403/451 carrying the refusal signals — a 429, a 5xx or a - * refusal about something else leaves the store alone). - */ -export function noteFreeTierOutcome( - attempt: FreeTierContractAttempt | null, - outcome: boolean | FreeTierOutcome -): void { - if (!attempt) return; - const decided: FreeTierOutcome = - typeof outcome === "boolean" ? { ok: outcome, status: null, bodyText: null } : outcome; - if (decided.ok) { - if (attempt.clientToolNames.length > 0) { - recordAcceptedToolNames( - attempt.provider, - attempt.model, - attempt.session, - attempt.clientToolNames - ); - } else if (attempt.borrowed && !attempt.probe) { - confirmBorrowedToolNames(attempt.provider, attempt.model, attempt.session); - } - return; - } - if (attempt.probe) return; - if (!attempt.borrowed) return; - if (decided.status === null) return; - if (isOpencodeFreeTierRefusal(decided.status, decided.bodyText)) { - noteRefusedBorrowedToolNames(attempt.provider, attempt.model, attempt.session); - } -} - -/** - * Rebuild a JSON body from the event stream the contract forced. - * - * The contract makes the upstream request streamed even when the caller asked for JSON, so - * the conversion back has to happen here rather than in one caller: `handleChatCore` knows - * how to buffer an event stream, but the other executor consumers (the compression judge, - * token counting) call `execute()` and then read `response.json()`. Handing them the raw - * event stream would throw on a request they explicitly asked not to stream. - * - * The conversion is LAZY: the returned body drains and parses the upstream only when the - * caller reads it, so the executor never blocks on a stream that has not arrived yet — the - * caller's own read timeout governs, and a caller that cancels pays nothing. Only a - * successful event-stream response is converted; a streaming caller, a refusal and an - * already-JSON body pass through untouched. - */ -export function rebuildJsonFromForcedStream( - response: Response, - requestFormat: string | null, - model: string -): Response { - if (!response.ok || !response.body) return response; - if (!(response.headers.get("content-type") || "").includes("text/event-stream")) { - return response; - } - const upstream = response; - let drained = false; - const body = new ReadableStream( - { - async pull(controller) { - if (drained) { - controller.close(); - return; - } - drained = true; - try { - const rawSse = await upstream.text(); - const parsed = - requestFormat === "openai-responses" - ? parseSSEToResponsesOutput(rawSse, model) - : parseSSEToOpenAIResponse(rawSse, model); - const out = parsed && typeof parsed === "object" ? JSON.stringify(parsed) : rawSse; - controller.enqueue(new TextEncoder().encode(out)); - } catch (err) { - controller.error(err); - return; - } - controller.close(); - }, - cancel(reason) { - // Only when nothing started draining: once `text()` holds the reader, cancelling the - // upstream body directly throws "ReadableStream is locked". - if (!drained && !upstream.bodyUsed && upstream.body && !upstream.body.locked) { - void upstream.body.cancel(reason); - } - }, - }, - // No pull before the caller reads: a caller that never reads (or cancels) must not make - // the executor wait on an upstream stream that may never arrive. - { highWaterMark: 0 } - ); - const headers = new Headers(response.headers); - headers.set("content-type", "application/json"); - headers.delete("content-length"); - return new Response(body, { - status: response.status, - statusText: response.statusText, - headers, - }); -} diff --git a/open-sse/executors/opencodeFreeTierRetry.ts b/open-sse/executors/opencodeFreeTierRetry.ts deleted file mode 100644 index 7c6cecea05d6..000000000000 --- a/open-sse/executors/opencodeFreeTierRetry.ts +++ /dev/null @@ -1,178 +0,0 @@ -import type { default as BaseExecutorType } from "./base.ts"; -import { - configuredPlaceholderToolNames, - isGatedFreeTierRequest, - mergeClientToolsWithObserved, - type OpencodeSurface, -} from "./opencodeFreeTierContract.ts"; -import { resolvePlaceholderNames } from "./opencodeToolObservation.ts"; -import { isOpencodeFreeTierRefusal, isOpencodeQuotaShapeRefusal } from "./opencodeGeoBlock.ts"; -import { resolveOpencodeTargetFormat } from "./opencode.ts"; - -type ExecutorInput = Parameters[0]; -type ExecutorLog = ExecutorInput["log"]; -type DispatchFn = (retryInput: ExecutorInput) => Promise<{ response: Response }>; - -/** - * One bounded retry after a free-tier refusal on a gated request that carried - * the caller's own tools (not borrowed): rebuild the upstream body with the - * observed tool names appended and dispatch once more. Returns the retry - * result, or null when no retry applies (not a refusal, not gated, borrowed - * tools, or nothing observed to add). A retry that also fails returns the - * ORIGINAL refusal — and never touches the observation store, since the names - * under test came from the client, not from the store (see - * `noteRefusedBorrowedToolNames`, which deliberately ignores own-tools - * refusals for the same reason). - */ -type RetryCtx = { - surface: OpencodeSurface; - provider: string; - requestFormat: string | null; - clientSession: string | undefined; - borrowed: boolean | undefined; - clientToolNames: readonly string[]; -}; - -/** Scope guards: refusal status, gated surface+model, own (non-borrowed) tools, object body. */ -function retryScopeApplies(ctx: RetryCtx, input: ExecutorInput, status: number): boolean { - if (status !== 403 && status !== 451) return false; - if (!isGatedFreeTierRequest(ctx.surface, ctx.provider, String(input.model ?? ""))) return false; - // Borrowed tools are the store's own names coming back: the retry would add - // nothing, and the refusal is already counted by noteFreeTierOutcome below. - // Only a refusal naming the model clears borrowed tools (#15475); other - // failures leave the streak untouched. - if (ctx.borrowed) return false; - return !!input.body && typeof input.body === "object" && !Array.isArray(input.body); -} - -/** - * Whether a refusal on a request carrying its own tools may be retried once - * with the observed names appended: a free-tier refusal or a quota-shape - * refusal. The quota predicate's own exclusions win, so a refusal carrying a - * fingerprint, geo or user_blocked marker stays excluded here too. - */ -export function isOwnToolsRetryableRefusal(status: number, bodyText: string | null): boolean { - return ( - isOpencodeFreeTierRefusal(status, bodyText) || isOpencodeQuotaShapeRefusal(status, bodyText) - ); -} - -/** Read the refusal body; null when unreadable or not a retryable refusal. */ -async function readRefusalBody( - first: { response: Response }, - status: number, - log: ExecutorLog -): Promise { - try { - const text = await first.response.clone().text(); - return isOwnToolsRetryableRefusal(status, text) ? text : null; - } catch { - log?.debug?.("OPENCODE", "body read failed on free-tier retry check"); - return null; - } -} - -function toolNamesOf(body: unknown): string[] { - const tools = (body as { tools?: unknown } | null)?.tools; - if (!Array.isArray(tools)) return []; - const names: string[] = []; - for (const tool of tools) { - const entry = (tool ?? {}) as { name?: unknown; function?: { name?: unknown } }; - const name = typeof entry.name === "string" ? entry.name : entry.function?.name; - if (typeof name === "string") names.push(name); - } - return names; -} - -/** - * Since #14156 the contract appends the resolved placeholder names to a client's own - * tools on the FIRST dispatch too. When the merged retry body declares no name beyond - * what that first dispatch already carried (client names + resolved placeholders), the - * retry would re-send the exact shape the upstream just refused — skip it. - */ -function addsNothingBeyondFirstDispatch( - ctx: RetryCtx, - model: string, - configured: readonly string[], - merged: unknown -): boolean { - const sent = new Set([ - ...ctx.clientToolNames, - ...resolvePlaceholderNames(ctx.provider, model, ctx.clientSession, configured), - ]); - return toolNamesOf(merged).every((name) => sent.has(name)); -} - -export async function retryFreeTierRefusalWithObservedTools( - ctx: RetryCtx, - input: ExecutorInput, - first: { response: Response }, - log: ExecutorLog, - cid: string, - dispatch: DispatchFn -): Promise<{ response: Response } | null> { - const status = first.response.status; - if (!retryScopeApplies(ctx, input, status)) return null; - const model = String(input.model ?? ""); - const configured = configuredPlaceholderToolNames(); - const merged = mergeClientToolsWithObserved( - input.body, - ctx.requestFormat ?? resolveOpencodeTargetFormat(ctx.provider, model), - ctx.provider, - model, - ctx.clientSession, - configured - ); - if (merged === input.body) return null; - if (addsNothingBeyondFirstDispatch(ctx, model, configured, merged)) return null; - if ((await readRefusalBody(first, status, log)) === null) return null; - log?.warn?.( - "OPENCODE", - `${cid}free-tier refusal on own tools [${ctx.clientToolNames.join(",")}], retrying once with observed names appended…` - ); - const retry = await dispatch({ ...input, body: merged }); - if (!retry.response.ok) return { response: first.response }; - return retry; -} - -/** - * Serve the rotation loop's free-tier arm: try the observed-tools retry on the - * same account proxy, else return the refusal untouched with account health - * unchanged (no cooldown, no success — the request, not the account, was - * rejected; rotating would only add latency since every sibling gets the same - * verdict). The executor callback reuses the loop's own finalize path so the - * retry result is shaped exactly like a first-dispatch result. - */ -type ShapedResult = { response: Response } | Response; - -export async function handleLoopFreeTierRefusal( - shape: (retried: { response: Response }) => ShapedResult, - input: ExecutorInput, - result: { response: Response }, - ctx: RetryCtx, - account: { account: unknown; masked: string; proxyKey: string }, - log: ExecutorLog, - cid: string, - hooks: { - dispatch: (retryInput: ExecutorInput) => Promise<{ response: Response }>; - noteServed: (account: unknown) => void; - } -): Promise { - const retried = await retryFreeTierRefusalWithObservedTools( - ctx, - input, - result, - log, - cid, - hooks.dispatch - ); - if (retried) { - return shape(retried); - } - log?.warn?.( - "OPENCODE", - `${cid}free-tier refusal ${result.response.status} on account ${account.masked} (proxy ${account.proxyKey}), returning it unchanged (request-scoped, no rotation)` - ); - hooks.noteServed(account.account); - return result; -} diff --git a/open-sse/executors/opencodeGeoBlock.ts b/open-sse/executors/opencodeGeoBlock.ts index c81dbe55a60c..32ec130d7b9c 100644 --- a/open-sse/executors/opencodeGeoBlock.ts +++ b/open-sse/executors/opencodeGeoBlock.ts @@ -92,25 +92,6 @@ export function isOpencodeFreeTierRefusal(status: number, bodyText: string | nul return FREE_TIER_SIGNALS.some((signal) => lower.includes(signal)); } -// Exact upstream token seen on title-shaped refusals: a 403 or 451 carrying -// `insufficient_quota` may refuse the request shape rather than the account. -// The shape replay probes the other shape once; more specific refusals -// (fingerprint, geo, user_blocked) win; anything else is not a shape refusal. -const QUOTA_SHAPE_SIGNAL = "insufficient_quota"; - -export function isOpencodeQuotaShapeRefusal(status: number, bodyText: string | null): boolean { - if (status !== 403 && status !== 451) return false; - const text = String(bodyText || ""); - if ( - isFingerprintRejection(text) || - isOpencodeGeoBlocked(status, text) || - isOpencodeUserBlocked(status, text) - ) { - return false; - } - return text.toLowerCase().includes(QUOTA_SHAPE_SIGNAL); -} - export function proxyKeyOf(proxy: { host: string; port: number } | null): string | null { if (!proxy) return null; return `${proxy.host}:${proxy.port}`; diff --git a/open-sse/executors/opencodeRequestContext.ts b/open-sse/executors/opencodeRequestContext.ts index 10cc12c7b976..32112cc4a409 100644 --- a/open-sse/executors/opencodeRequestContext.ts +++ b/open-sse/executors/opencodeRequestContext.ts @@ -3,15 +3,14 @@ * * The executor is one shared instance per provider alias and its requests overlap: a field * written when one request starts is read by the other one after an `await`. The target format - * and the client session therefore live in a context that belongs to one `execute()` call and - * follows its async continuations. Outside `execute()` there is no context, and the executor + * therefore lives in a context that belongs to one `execute()` call and follows its async + * continuations. Outside `execute()` there is no context, and the executor * falls back to plain fields (direct calls to `buildHeaders`, `buildUrl`, `transformRequest`). */ import { AsyncLocalStorage } from "node:async_hooks"; export interface RequestContext { format: string | null; - session: string | undefined; /** * Pool-member resolver published by the chat layer for one request (see the * applied-proxy capture sink). Absent unless a connection pool was resolved @@ -26,7 +25,7 @@ const store = new AsyncLocalStorage(); /** Run one request in a context of its own. */ export function runInRequestContext(fn: () => T): T { - return store.run({ format: null, session: undefined, reselectPoolMember: undefined }, fn); + return store.run({ format: null, reselectPoolMember: undefined }, fn); } export function currentRequestContext(): RequestContext | undefined { diff --git a/open-sse/executors/opencodeRequestShape.ts b/open-sse/executors/opencodeRequestShape.ts deleted file mode 100644 index 96456e1a3718..000000000000 --- a/open-sse/executors/opencodeRequestShape.ts +++ /dev/null @@ -1,242 +0,0 @@ -/** - * Which tool shape a gated request must carry, learned from the upstream's refusals. - * - * The upstream accepts a request whose instructions say "Never use tools" only with no tools, - * and any other request only with tools (measured 2026-09-18, both surfaces). The request - * contract used to fill an empty `tools` array unconditionally, so the first kind was refused. - * Rather than match a prompt, the executor replays a refused request once in the other shape - * and remembers which one worked (see `withRequestShapeRetry`). - * - * State lives here, keyed by the identity of the request body the executor was handed - * (`WeakMap`), never on the executor: it is a shared instance and requests overlap. - */ -import { createHash } from "node:crypto"; -import { isOpencodeFreeTierRefusal, isOpencodeQuotaShapeRefusal } from "./opencodeGeoBlock.ts"; -import type { ExecuteInput, ExecutorExecuteResult } from "./base.ts"; -import type { FreeTierOutcome } from "./opencodeFreeTierContract.ts"; - -export type RequestShape = "tools" | "bare"; - -/** What `prepareFreeTierRequest` decided for one request, kept until its outcome is known. */ -export interface InjectionContext { - readonly shape: RequestShape; - /** The prompt class this request belongs to (see `shapeKeyOf`). */ - readonly key: string; - /** False when a refusal is final for this request: its outcome is noted as it happens. */ - readonly probe: boolean; - /** - * Replays the outcome note that was deferred while a replay was still possible. The - * verdict travels with the note, so a refusal that says something about the borrowed - * tools still counts once no replay can rescue it. - */ - readonly replayNote: (verdict: FreeTierOutcome) => void; -} - -/** Prompt classes that the upstream accepts bare. Bounded; least recently confirmed goes first. */ -const MAX_CLASSES = 64; -const bareClasses = new Set(); - -/** Both shapes were refused: no replay for this class until the stamp passes. */ -const PAUSE_MS = 60_000; -const pausedUntil = new Map(); -let now: () => number = () => Date.now(); - -const forced = new WeakMap(); -const contexts = new WeakMap(); -/** What the contract decided for a request, kept until the request is over (see `forget`). */ -const attempts = new WeakMap(); - -const isObject = (value: unknown): value is object => typeof value === "object" && value !== null; - -function textOf(content: unknown): string { - if (typeof content === "string") return content; - if (content === null || content === undefined) return ""; - if (Array.isArray(content)) { - const text = content - .map((part) => (part as { text?: unknown } | null)?.text) - .filter((t): t is string => typeof t === "string") - .join(""); - if (text) return text; - } - // Not plain text: hash its structure, so it is a class of its own rather than "no prompt". - try { - return JSON.stringify(content); - } catch { - return String(content); - } -} - -/** - * The class a request belongs to: provider, model and a digest of its prompt. - * - * Responses bodies carry the prompt as `instructions`, Chat Completions bodies as the first - * system or developer message. A request with no prompt hashes the empty string: it is a class - * like any other, so a remembered shape and the replay bookkeeping apply to it too. - */ -export function shapeKeyOf(provider: string, model: string, body: unknown): string { - const record = isObject(body) ? (body as Record) : {}; - let prompt = typeof record.instructions === "string" ? record.instructions : ""; - if (!prompt && Array.isArray(record.messages)) { - const first = (record.messages as Array>).find( - (m) => m && (m.role === "system" || m.role === "developer") - ); - prompt = textOf(first?.content); - } - const digest = createHash("sha1").update(prompt).digest("hex"); - return `${provider}|${model}|${digest}`; -} - -/** Which shape this request goes out in, and whether a refusal may still be replayed. */ -export function planShape(origin: object, key: string): { shape: RequestShape; probe: boolean } { - const imposed = forced.get(origin); - if (imposed) return { shape: imposed, probe: false }; - return { shape: bareClasses.has(key) ? "bare" : "tools", probe: !isPaused(key) }; -} - -function isPaused(key: string): boolean { - const until = pausedUntil.get(key); - if (until === undefined) return false; - if (until > now()) return true; - pausedUntil.delete(key); - return false; -} - -function pause(key: string): void { - pausedUntil.delete(key); - pausedUntil.set(key, now() + PAUSE_MS); - while (pausedUntil.size > MAX_CLASSES) { - const oldest = pausedUntil.keys().next(); - if (oldest.done) break; - pausedUntil.delete(oldest.value); - } -} - -function rememberBare(key: string): void { - bareClasses.delete(key); - bareClasses.add(key); - while (bareClasses.size > MAX_CLASSES) { - const oldest = bareClasses.values().next(); - if (oldest.done) break; - bareClasses.delete(oldest.value); - } -} - -export function rememberAttempt(origin: object, attempt: object): void { - attempts.set(origin, attempt); -} - -export function recallAttempt(origin: unknown): T | null { - return isObject(origin) ? ((attempts.get(origin) as T | undefined) ?? null) : null; -} - -export function forgetAttempt(origin: object): void { - attempts.delete(origin); -} - -export function recordInjection(origin: object, ctx: InjectionContext): void { - contexts.set(origin, ctx); -} - -function responseOf(result: ExecutorExecuteResult): Response | null { - if (result instanceof Response) return result; - return result && "response" in result && result.response ? result.response : null; -} - -async function readVerdict(response: Response, log: ExecuteInput["log"]): Promise { - const status = response.status; - if (status !== 403 && status !== 451) return { ok: false, status, bodyText: null }; - try { - return { ok: false, status, bodyText: await response.clone().text() }; - } catch { - // Unreadable body: treated as "not a shape refusal", so the response is returned as-is. - log?.debug?.("OPENCODE", "refusal body unreadable, no replay"); - return { ok: false, status, bodyText: null }; - } -} - -async function isShapeRefusal(verdict: FreeTierOutcome): Promise { - if (verdict.status !== 403 && verdict.status !== 451) return false; - if (verdict.bodyText === null) return false; - return ( - isOpencodeFreeTierRefusal(verdict.status, verdict.bodyText) || - isOpencodeQuotaShapeRefusal(verdict.status, verdict.bodyText) - ); -} - -/** - * Run one execution and, when the upstream refuses a request whose tool shape we chose, - * replay it once in the other shape. - * - * Only a refusal of the request itself counts: a 429, a 5xx or a network error says nothing about the - * shape. A request whose tools the client declared is never touched (no context recorded). - */ -/** What a replay taught: the shape that worked is remembered, two refusals pause the class. */ -function learnFromReplay(ctx: InjectionContext, accepted: boolean, verdict: FreeTierOutcome): void { - if (!accepted) { - pause(ctx.key); - ctx.replayNote(verdict); - } else if (ctx.shape === "tools") { - rememberBare(ctx.key); - } else { - bareClasses.delete(ctx.key); - } -} - -/** Release the refused response, send the request again in the other shape, learn from it. */ -async function replayInOtherShape( - input: ExecuteInput, - run: (i: ExecuteInput) => Promise, - ctx: InjectionContext, - refused: Response, - origin: object, - verdict: FreeTierOutcome -): Promise { - await refused.body?.cancel().catch(() => undefined); - forced.set(origin, ctx.shape === "bare" ? "tools" : "bare"); - let second: ExecutorExecuteResult; - try { - second = await run(input); - } catch (error) { - ctx.replayNote(verdict); - throw error; - } - learnFromReplay(ctx, responseOf(second)?.ok === true, verdict); - return second; -} - -function forget(origin: unknown): void { - if (!isObject(origin)) return; - forced.delete(origin); - contexts.delete(origin); - attempts.delete(origin); -} - -export async function withRequestShapeRetry( - input: ExecuteInput, - run: (i: ExecuteInput) => Promise -): Promise { - const origin = input.body; - try { - const first = await run(input); - const ctx = isObject(origin) ? contexts.get(origin) : undefined; - const response = responseOf(first); - if (!ctx || !isObject(origin) || !response || response.ok || !ctx.probe) return first; - const verdict = await readVerdict(response, input.log); - if (input.signal?.aborted || !(await isShapeRefusal(verdict))) { - ctx.replayNote(verdict); - return first; - } - return await replayInOtherShape(input, run, ctx, response, origin, verdict); - } finally { - forget(origin); - } -} - -export function _resetShapeMemoForTests(): void { - bareClasses.clear(); - pausedUntil.clear(); -} - -export function _setShapeClockForTests(clock: () => number): void { - now = clock; -} diff --git a/open-sse/executors/opencodeToolObservation.ts b/open-sse/executors/opencodeToolObservation.ts deleted file mode 100644 index 07964c1d7554..000000000000 --- a/open-sse/executors/opencodeToolObservation.ts +++ /dev/null @@ -1,181 +0,0 @@ -/** - * opencodeToolObservation.ts — which tool names the gated upstream accepts right now. - * - * The free tier inspects the `tools` array, and what it accepts moves. Measured on - * 2026-09-18: one made-up tool was accepted on `big-pickle` and refused on - * `nemotron-3.5-lightning-free` and `muse-spark-1.3-contributor-free` — the same body that - * the first of those had accepted a day earlier. No published artifact carries that rule; - * the upstream npm package is a 3 KB platform dispatcher. A pinned placeholder is - * therefore a guess that goes stale between releases. - * - * The relayed traffic already carries the answer. A client request that goes out with - * tools and comes back OK proves which names the upstream accepts, for that surface and - * that model, at that moment. This module remembers those names so a later request - * carrying none can borrow them, and forgets them when a borrowed set is refused. - * - * Only names are kept — never a schema, a description, or any conversation content — and - * the placeholder rebuilt from them declares an empty parameter object, so a borrowed name - * is an entry in a list rather than a callable tool. - * - * Leaf module: no internal imports, so the executor and the contract can both use it. - */ - -/** - * Bounds are arbitrary and revisable: they cap memory, they are not a measured property of - * the upstream. Entries are small (short strings), so the ceiling is generous on purpose. - */ -const MAX_NAMES_PER_ENTRY = 32; -const MAX_ENTRIES = 64; -const NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/; - -/** - * How many refusals in a row a borrowed set takes before it is dropped. - * - * One refusal is not proof: the same body was refused and then accepted on - * `muse-spark-1.3-contributor-free` minutes apart (measured 2026-09-18), so the verdict - * carries a share of noise. Dropping on the first refusal would make the store oscillate - * and fall back to a placeholder already known to be refused. Arbitrary and revisable. - */ -const REFUSALS_BEFORE_FORGETTING = 3; - -/** Insertion-ordered, so the first key `Map` yields is the least recently confirmed one. */ -const observed = new Map(); -const consecutiveRefusals = new Map(); - -/** - * Surfaces and models do not share a gate, so neither do their entries. A session id - * narrows it further: within one conversation the tools a request declares belong to the - * very client whose service request is being repaired. - */ -function keyOf(provider: string, model: string, session?: string): string { - return [provider, model, session ?? ""].join("|"); -} - -/** - * Keep the names usable as a placeholder: well-formed, unique, order preserved. The - * upstream may care about which names are present; nothing suggests it cares how many - * follow a given one, so the original order is the safest thing to replay. - */ -function sanitize(names: readonly unknown[]): string[] { - const kept: string[] = []; - for (const raw of names) { - if (kept.length >= MAX_NAMES_PER_ENTRY) break; - if (typeof raw !== "string" || !NAME_PATTERN.test(raw)) continue; - if (!kept.includes(raw)) kept.push(raw); - } - return kept; -} - -/** - * Record the tool names an accepted gated request carried. - * - * Called only for a response the upstream answered OK, so an entry is always a shape that - * worked rather than one that merely looked plausible. - */ -export function recordAcceptedToolNames( - provider: string, - model: string, - session: string | undefined, - names: readonly unknown[] -): void { - const kept = sanitize(names); - if (kept.length === 0) return; - const frozen = Object.freeze(kept); - // Both scopes are written: the session entry serves the conversation it came from, the - // model entry serves a conversation that has not yet sent a request carrying tools. - for (const key of session - ? [keyOf(provider, model, session), keyOf(provider, model)] - : [keyOf(provider, model)]) { - // Re-insert so a confirmed entry becomes the most recent one for eviction. - observed.delete(key); - observed.set(key, frozen); - consecutiveRefusals.delete(key); - } - while (observed.size > MAX_ENTRIES) { - const oldest = observed.keys().next(); - if (oldest.done) break; - observed.delete(oldest.value); - consecutiveRefusals.delete(oldest.value); - } -} - -/** - * Count one refusal against a borrowed entry, and drop it once the streak is long enough. - * - * Called only when a request that BORROWED this entry was refused. A refusal on a request - * carrying the client's own tools says nothing about the entry, and a refusal caused by - * the session or the user-agent says nothing about tools at all — counting either would - * drop a sound entry and fall back to a placeholder that is already known to be refused. - */ -export function noteRefusedBorrowedToolNames( - provider: string, - model: string, - session?: string -): void { - const key = observed.has(keyOf(provider, model, session)) - ? keyOf(provider, model, session) - : keyOf(provider, model); - if (!observed.has(key)) return; - const streak = (consecutiveRefusals.get(key) ?? 0) + 1; - if (streak < REFUSALS_BEFORE_FORGETTING) { - consecutiveRefusals.set(key, streak); - return; - } - observed.delete(key); - consecutiveRefusals.delete(key); -} - -/** - * Confirm a borrowed shape that just worked: the streak of refusals is dropped, - * the entry itself is left alone (no rewrite, so its eviction rank is kept). - * - * Called only when a request that BORROWED this entry was answered OK. A 200 on - * borrowed names proves the shape still works, which cancels the noise the - * refusal threshold exists to absorb. - */ -export function confirmBorrowedToolNames(provider: string, model: string, session?: string): void { - const key = observed.has(keyOf(provider, model, session)) - ? keyOf(provider, model, session) - : keyOf(provider, model); - if (!observed.has(key)) return; - consecutiveRefusals.delete(key); -} - -/** The names last seen accepted for this surface, model and — when known — session. */ -export function getObservedToolNames( - provider: string, - model: string, - session?: string -): readonly string[] | null { - return observed.get(keyOf(provider, model, session)) ?? null; -} - -/** - * The names to declare on a gated request the caller sent without tools. - * - * Order of resolution: what this very conversation was last seen declaring, then what any - * conversation on this surface and model was, then what the operator configured, then - * nothing — which leaves the caller on the built-in placeholder. - * - * The first step is the one that matters. The official client sends its service requests — - * title generation, compaction — without tools while the build requests of the same - * session carry a full list (upstream anomalyco/opencode#49433), so replaying that - * session\'s own list gives a request back the contract its own client just declared. - */ -export function resolvePlaceholderNames( - provider: string, - model: string, - session: string | undefined, - configured: readonly string[] -): readonly string[] { - const own = session ? getObservedToolNames(provider, model, session) : null; - if (own && own.length > 0) return own; - if (configured && configured.length > 0) return configured; - return getObservedToolNames(provider, model) ?? configured; -} - -/** Reserved for tests. */ -export function _resetToolObservationForTests(): void { - observed.clear(); - consecutiveRefusals.clear(); -} diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.ts index df54cacbfd0b..9bff940bb68b 100644 --- a/open-sse/handlers/chatCore.ts +++ b/open-sse/handlers/chatCore.ts @@ -929,7 +929,7 @@ async function handleChatCoreInner({ // Detect Claude Code CLI so we can auto-enable model echo — this prevents // session restore failures when the resolved upstream model (e.g. - // `oc/nemotron-3-ultra-free`) is not recognized by the client on `--resume`. + // `opencode-zen/nemotron-3-ultra-free`) is not recognized by the client on `--resume`. const isClaudeCodeClient = isClaudeCodeOriginatedHeaders(clientRawRequest?.headers); let echoModel = diff --git a/open-sse/services/autoCombo/virtualFactory.ts b/open-sse/services/autoCombo/virtualFactory.ts index a61389aaa88d..edc692674902 100644 --- a/open-sse/services/autoCombo/virtualFactory.ts +++ b/open-sse/services/autoCombo/virtualFactory.ts @@ -348,10 +348,10 @@ const SYNTHETIC_NOAUTH_CONNECTION_ID = RESILIENCE_NOAUTH_CONNECTION_ID; // Allowlist of no-auth (keyless) providers permitted to enter the `auto`/`auto-*` // candidate pool. Narrowed to the backends verified to answer without any -// configuration on our reference egress (VPS .15): `opencode` returns 200 -// there, while duckduckgo-web (429/VQD rate limit), -// aihorde (401, anon key rejected) -// and the others are unreliable. The excluded providers stay fully usable via +// configuration on our reference egress (VPS .15). Currently empty: the only +// verified member, the keyless OpenCode provider, was removed (see +// docs/reference/REMOVED_PROVIDERS.md), while duckduckgo-web (429/VQD rate +// limit), aihorde (401, anon key rejected) and the others are unreliable. The excluded providers stay fully usable via // direct `/` calls — they are just kept OUT of auto-routing until // re-verified. Re-add an id here to bring it back into every auto/* pool. // @@ -363,7 +363,7 @@ const SYNTHETIC_NOAUTH_CONNECTION_ID = RESILIENCE_NOAUTH_CONNECTION_ID; // pool, so it admits any no-auth backend that genuinely serves the family (e.g. // auggie, a local CLI subprocess with zero HTTP egress, belongs in auto/glm // regardless of this list). See the `bypassAllowlist` param below. -const AUTO_COMBO_NOAUTH_ALLOWLIST = new Set(["opencode"]); +const AUTO_COMBO_NOAUTH_ALLOWLIST = new Set(); function isChatAutoComboNoAuthProvider( providerDef: NoAuthProviderDefinition, diff --git a/open-sse/services/combo/comboStructure.ts b/open-sse/services/combo/comboStructure.ts index 080608b8e959..b3ee531a2e0c 100644 --- a/open-sse/services/combo/comboStructure.ts +++ b/open-sse/services/combo/comboStructure.ts @@ -26,7 +26,6 @@ import { containsMediaKind } from "../../utils/mediaParts.ts"; import { getResolvedModelCapabilities } from "../modelCapabilities.ts"; import { parseModel, stripContextWindowSuffix } from "../model.ts"; import { dedupeTargetsByExecutionKey, isRecord } from "./comboData.ts"; -import { resolveComboTargetModelStr } from "./opencodeTargetAlias.ts"; import { isComboModelVisible } from "./comboVisibility.ts"; import { getTargetProvider, MAX_COMBO_DEPTH } from "./comboPredicates.ts"; import { evaluateContextLimit, getModelContextOverrideValue } from "./contextOverrideGate.ts"; @@ -123,13 +122,8 @@ function normalizeRuntimeStep( }; } - const declaredModelStr = getComboModelString(step); - if (!declaredModelStr) return null; - // #11912: rewrite an ambiguous "opencode/" target to the "oc/" alias - // so it stays distinct from an explicit "opencode-zen/" sibling - // instead of both collapsing onto the same provider — see - // opencodeTargetAlias.ts for the full rationale. - const modelStr = resolveComboTargetModelStr(declaredModelStr); + const modelStr = getComboModelString(step); + if (!modelStr) return null; const connectionId = toTrimmedString(step.connectionId); const allowedConnectionIds = implicitPinAllowlist(connectionId, step.allowedConnectionIds); diff --git a/open-sse/services/combo/fingerprintExpansion.ts b/open-sse/services/combo/fingerprintExpansion.ts index e9b8419cb1b6..ca58dfd2973b 100644 --- a/open-sse/services/combo/fingerprintExpansion.ts +++ b/open-sse/services/combo/fingerprintExpansion.ts @@ -1,7 +1,7 @@ /** * Fingerprint-based target expansion for combo routing. * - * Some providers (MiMoCode, MiCode, OpenCode) store multiple device + * Some no-auth providers can store multiple device * fingerprints inside a single connection's `providerSpecificData.fingerprints`. * Without expansion the combo system treats the connection as one account, * so only one fingerprint is used per request. This module splits such @@ -14,8 +14,11 @@ import type { ResolvedComboTarget } from "./types.ts"; -/** Providers whose `providerSpecificData.fingerprints` array should be expanded. */ -const FINGERPRINT_PROVIDERS: ReadonlySet = new Set(["opencode"]); +/** + * Providers whose `providerSpecificData.fingerprints` array should be expanded. + * Empty since the keyless OpenCode provider (its last member) was removed. + */ +const FINGERPRINT_PROVIDERS: ReadonlySet = new Set(); /** Separator the combo builder UI uses to encode an account pin (#6087). */ const FP_PIN_SEPARATOR = "|fp|"; diff --git a/open-sse/services/combo/opencodeTargetAlias.ts b/open-sse/services/combo/opencodeTargetAlias.ts deleted file mode 100644 index b3cfa5e26e49..000000000000 --- a/open-sse/services/combo/opencodeTargetAlias.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Issue #11912 — a combo step declared with the raw "opencode/" prefix - * is ambiguous: open-sse/services/model.ts's manual ALIAS_TO_PROVIDER_ID - * override canonicalizes ANY "opencode/" string to provider - * "opencode-zen" (the api-key gateway) before dispatch. A round-robin combo - * mixing declared "opencode/" targets (intended as the free/dynamic - * no-auth pool) with an explicit "opencode-zen/" target therefore - * collapses every rotation slot onto the SAME provider + connection identity - * — every request executes against the single opencode-zen connection - * instead of rotating across the free pool, and the account eventually - * 429s. - * - * The combo BUILDER already avoids this for freshly-generated model strings - * by emitting the "oc/" alias for the no-auth provider (#2901, - * src/lib/combos/builderOptions.ts's rewriteQualifiedModelPrefix). This - * mirrors that same substitution at combo TARGET RESOLUTION time so a step - * saved — or hand-typed — with the raw "opencode/" prefix still reaches the - * true no-auth provider and stays a distinct rotation identity from an - * explicit "opencode-zen/" target. - * - * Deliberately scoped to combo target resolution only — this never touches - * open-sse/services/model.ts's general alias-resolution path, so a raw - * client request to "opencode/" outside a combo keeps routing to - * opencode-zen unchanged (#2798/#3870), and the #7993 sibling credential - * lookup (tests/unit/opencode-autocombo-search-pair.test.ts) is unaffected. - */ - -const AMBIGUOUS_OPENCODE_PREFIX = "opencode"; -const OPENCODE_NOAUTH_ALIAS = "oc"; - -/** - * Rewrite a combo-declared model string's "opencode/" prefix to the "oc/" - * no-auth alias. Every other prefix (including "opencode-zen/" and - * "opencode-go/") passes through untouched. - */ -export function resolveComboTargetModelStr(modelStr: string): string { - if (typeof modelStr !== "string" || modelStr.length === 0) return modelStr; - const slashIndex = modelStr.indexOf("/"); - if (slashIndex <= 0) return modelStr; - const prefix = modelStr.slice(0, slashIndex); - if (prefix !== AMBIGUOUS_OPENCODE_PREFIX) return modelStr; - return `${OPENCODE_NOAUTH_ALIAS}${modelStr.slice(slashIndex)}`; -} diff --git a/open-sse/services/model.ts b/open-sse/services/model.ts index f7c192d8c97f..95b3a33944ea 100644 --- a/open-sse/services/model.ts +++ b/open-sse/services/model.ts @@ -547,21 +547,13 @@ async function resolveModelByProviderInference(modelId: string, extendedContext: } } - // Opencode free-tier models always route to opencode when active — prevents - // prefix inference from misrouting -free names to other providers when the - // live catalog is temporarily unreachable. - // - // A literal `activeProviders?.has("opencode")` check is unreachable in - // practice: `getActiveProviderSet()` canonicalizes every connection's - // provider id through `resolveProviderAlias()`, and the manual override - // above (`ALIAS_TO_PROVIDER_ID["opencode"] = "opencode-zen"`) rewrites any - // "opencode" id to "opencode-zen" before it ever reaches the active set — - // so an active no-auth opencode connection never appears as "opencode". - // Check both opencode-family canonical ids that catalog this model id. + // OpenCode Zen catalog ids (`big-pickle`, `*-free`) route to opencode-zen + // when it is active — prevents prefix inference from misrouting -free names + // to other providers when the live catalog is temporarily unreachable. if (modelId === "big-pickle" || modelId.endsWith("-free")) { const candidates = MODEL_TO_PROVIDERS.get(modelId) || []; const activeOpencodeCandidate = candidates.find( - (p) => (p === "opencode" || p === "opencode-zen") && activeProviders?.has(p) + (p) => p === "opencode-zen" && activeProviders?.has(p) ); if (activeOpencodeCandidate) { return { provider: activeOpencodeCandidate, model: modelId, extendedContext }; diff --git a/open-sse/services/opencodeQuotaFetcher.ts b/open-sse/services/opencodeQuotaFetcher.ts index f49a14cd8ccd..3643519ed06f 100644 --- a/open-sse/services/opencodeQuotaFetcher.ts +++ b/open-sse/services/opencodeQuotaFetcher.ts @@ -233,12 +233,12 @@ export function invalidateOpencodeQuotaCache(connectionId: string): void { /** * Register the OpenCode quota fetcher with the preflight and monitor systems - * for all three provider variants: opencode-go, opencode, opencode-zen. + * for both provider variants: opencode-go, opencode-zen. * * Call this once at server startup (in chat.ts, before registerGenericQuotaFetchers). */ export function registerOpencodeQuotaFetcher(): void { - for (const provider of ["opencode-go", "opencode", "opencode-zen"] as const) { + for (const provider of ["opencode-go", "opencode-zen"] as const) { registerQuotaFetcher(provider, fetchOpencodeQuota); registerMonitorFetcher(provider, fetchOpencodeQuota); registerQuotaWindows(provider, [ diff --git a/open-sse/services/opencodeReasoningSanitizer.ts b/open-sse/services/opencodeReasoningSanitizer.ts index 30a94ee450d6..93f8d9ca3993 100644 --- a/open-sse/services/opencodeReasoningSanitizer.ts +++ b/open-sse/services/opencodeReasoningSanitizer.ts @@ -27,7 +27,6 @@ const OPENCODE_GO_PROVIDERS = new Set([ "ollama_cloud", "opencode-go", "opencode_go", - "opencode", "opencode-zen", ]); diff --git a/open-sse/services/providerAlias.ts b/open-sse/services/providerAlias.ts index a5941b22e0a5..4f52cc55bd1f 100644 --- a/open-sse/services/providerAlias.ts +++ b/open-sse/services/providerAlias.ts @@ -14,7 +14,7 @@ for (const [id, alias] of Object.entries(PROVIDER_ID_TO_ALIAS)) { // Manual alias overrides — maps slug-style prefixes to canonical provider IDs. // These live outside the registry because they represent multiple providers // or backward-compatible slug changes, not a single provider's display name. -// opencode/ → opencode-zen (the main free/open tier; opencode-go is a separate paid tier) +// opencode/ → opencode-zen (OpenCode Zen; opencode-go is a separate tier) ALIAS_TO_PROVIDER_ID["opencode"] = "opencode-zen"; // xiaomi/ is the user-visible prefix for MiMo models; register it so // parseModel("xiaomi/mimo-v2-flash") resolves provider = "xiaomi-mimo" instead @@ -39,10 +39,9 @@ export function resolveProviderAlias(aliasOrId: string | null | undefined): stri if (typeof aliasOrId !== "string") return null; // Follow the alias chain transitively so intermediate alias-only hops resolve // to the final target, but STOP as soon as a hop lands on a registered - // provider id (#2901): "oc" must resolve to the no-auth "opencode" provider, - // NOT continue through the manual "opencode" → "opencode-zen" slug override — - // that override is for user-typed `opencode/` prefixes only. Without this - // boundary the no-auth provider becomes unreachable by any prefix. + // provider id (#2901): an alias that names a registered provider must not + // continue through a manual slug override meant for user-typed prefixes only. + // Without this boundary such a provider becomes unreachable by any prefix. // Guarded against infinite loops with both a depth limit and a seen-set. let current = aliasOrId; const seen = new Set(); diff --git a/open-sse/services/providerConnectionPool.ts b/open-sse/services/providerConnectionPool.ts index 963095a70d28..7fdfe8891ed5 100644 --- a/open-sse/services/providerConnectionPool.ts +++ b/open-sse/services/providerConnectionPool.ts @@ -15,8 +15,6 @@ const PROVIDER_SEARCH_PAIRS: string[][] = [ // The model layer canonicalizes `agy/` to `antigravity`, but the Antigravity // CLI card stores its connection under `agy`. Same account, either id serves. ["antigravity", "agy"], - // OpenCode connection card stores under `opencode`, but model alias resolves to `opencode-zen`. - ["opencode", "opencode-zen"], // One Jina token works on api.jina.ai, r.jina.ai, and s.jina.ai. // Requested id stays first so embed/rerank do not silently pick a // Reader-only row when both cards are filled. jina-search has no diff --git a/open-sse/services/usage.ts b/open-sse/services/usage.ts index 1aeea84c2052..7d0f19a8e402 100644 --- a/open-sse/services/usage.ts +++ b/open-sse/services/usage.ts @@ -222,7 +222,6 @@ export async function getUsageForProvider( return await getLlmgatewayUsage(id || "", apiKey || ""); case "lyceum": return await getLyceumUsage(id || "", apiKey || ""); - case "opencode": case "opencode-zen": return await getOpencodeUsage(id || "", apiKey || ""); case "xiaomi-mimo": diff --git a/open-sse/services/usage/fetcherProviders.ts b/open-sse/services/usage/fetcherProviders.ts index 709e129358a5..7ff89ab2a17d 100644 --- a/open-sse/services/usage/fetcherProviders.ts +++ b/open-sse/services/usage/fetcherProviders.ts @@ -51,7 +51,6 @@ export const USAGE_FETCHER_PROVIDERS = [ "deepseek", "moonshot", "kimi", - "opencode", "opencode-zen", "xiaomi-mimo", "xiaomi-mimo-token-plan", diff --git a/open-sse/utils/opencodeHeaders.ts b/open-sse/utils/opencodeHeaders.ts index 6939db14c882..fa3bcb61517e 100644 --- a/open-sse/utils/opencodeHeaders.ts +++ b/open-sse/utils/opencodeHeaders.ts @@ -61,15 +61,11 @@ export function clientSuppliedOpencodeSession( * The CLI identity defaults the upstream expects, or `undefined` when synthesis is off. * * Lives here rather than in the executor because this module already owns the default - * user-agent and the contract that validates one. `gated` says the free tier will inspect - * this request: outside the gate a configured user-agent is honoured as-is (the #5997 - * contract, which `opencode-go` and paid models rely on), while on a gated request one - * that does not satisfy the version rule is replaced — an operator still carrying the - * previous unversioned default would otherwise be refused. + * user-agent. A configured user-agent is honoured as-is (the #5997 contract, which + * `opencode-zen` and `opencode-go` rely on). */ export function resolveOpencodeCliDefaults( - providerId: string, - gated: boolean + providerId: string ): { userAgent: string; client: string; project: string } | undefined { if (/^(0|false|no|off)$/i.test(process.env.OPENCODE_SYNTHESIZE_CLI_HEADERS?.trim() ?? "")) { return undefined; @@ -84,10 +80,7 @@ export function resolveOpencodeCliDefaults( void refreshOpencodeCliVersion(); } return { - userAgent: - configuredUA && (!gated || satisfiesOpencodeUserAgentContract(configuredUA)) - ? configuredUA - : `opencode/${getCachedOpencodeCliVersion()}`, + userAgent: configuredUA || `opencode/${getCachedOpencodeCliVersion()}`, client: process.env.OPENCODE_CLIENT?.trim() || "desktop", project: process.env.OPENCODE_PROJECT?.trim() || "global", }; @@ -162,8 +155,8 @@ function findHeader(headers: Record, name: string): string | und * UUIDs, but ONLY for keys the client did not already supply. Client values always * win; these defaults only fill gaps. User-Agent is the one exception: a client UA * that is not already the OpenCode CLI (e.g. curl/8.5.0) is REPLACED with the - * synthesized CLI UA, because opencode.ai's free tier rejects generic client UAs - * from datacenter IPs with FreeUsageLimitError 429. (#5997, follow-up #10229) + * synthesized CLI UA, because opencode.ai rejects generic client UAs from + * datacenter IPs with a 429. (#5997, follow-up #10229) * @param options.keepAgentUserAgent - OpenCode Go (#15311): keep a client User-Agent that * names the agent itself, as Go's client requirements ask. A generic SDK / HTTP-library * UA is still replaced, and a missing one is still filled. @@ -245,15 +238,14 @@ function applySessionFallback( * Fill the OpenCode CLI identity headers Cloudflare requires on VPS egress. For * x-opencode-* headers, client values always win (defaults only fill gaps). The * User-Agent is the exception: a non-CLI client UA (curl, python, SDKs) is replaced - * with the synthesized CLI UA, because opencode.ai's free tier flags generic client - * UAs from datacenter IPs (FreeUsageLimitError 429). A client UA that already looks + * with the synthesized CLI UA, because opencode.ai flags generic client UAs from + * datacenter IPs (429). A client UA that already looks * like the OpenCode CLI (opencode-cli/...) is preserved so the real CLI's versioned * identity stays intact. (#5997, follow-up) */ /** - * Whether the client's User-Agent survives CLI synthesis. A UA that satisfies the upstream - * contract is always kept; the previous rule kept anything starting with `opencode-cli/`, - * which carries no parsable version and is refused by the free tier. With + * Whether the client's User-Agent survives CLI synthesis. A versioned OpenCode CLI UA + * (`opencode/.`, >= 1.17) is always kept. With * `keepAgentUserAgent` (OpenCode Go, #15311) an agent's own UA is kept too, because Go asks * third-party agents to identify themselves — but never a generic SDK / HTTP-library UA. */ diff --git a/open-sse/utils/opencodeSessionIdentity.ts b/open-sse/utils/opencodeSessionIdentity.ts index 758bb250f5c8..858832ca7f5d 100644 --- a/open-sse/utils/opencodeSessionIdentity.ts +++ b/open-sse/utils/opencodeSessionIdentity.ts @@ -72,7 +72,7 @@ export function preserveOpencodeSessionIdentity( headers: Record, request?: { provider?: string; body?: unknown } ): void { - if (request?.provider !== "opencode" && request?.provider !== "opencode-go") return; + if (request?.provider !== "opencode-go") return; const sessionId = resolveOpencodeSessionIdentity(headers, request.body); if (sessionId) headers["x-opencode-session"] = sessionId; } diff --git a/open-sse/utils/reasoningContentInjector.ts b/open-sse/utils/reasoningContentInjector.ts index 7d3f48a9e79f..8fc7add727a3 100644 --- a/open-sse/utils/reasoningContentInjector.ts +++ b/open-sse/utils/reasoningContentInjector.ts @@ -20,7 +20,7 @@ type JsonRecord = Record; /** * Model-id predicates for thinking-mode families that need the echo. * Matched case-insensitively against the resolved model id (post upstream - * routing, e.g. `oc/deepseek-v4-flash-free` for the OpenCode meta-provider). + * routing, e.g. `opencode-zen/deepseek-v4-flash-free` for OpenCode Zen). */ const THINKING_MODEL_PATTERNS: RegExp[] = [ /deepseek/i, diff --git a/open-sse/utils/reasoningPlaceholder.ts b/open-sse/utils/reasoningPlaceholder.ts index 438cc1894f97..c046b925f6c8 100644 --- a/open-sse/utils/reasoningPlaceholder.ts +++ b/open-sse/utils/reasoningPlaceholder.ts @@ -54,6 +54,6 @@ export function requiresReasoningContentPresence(provider: unknown, model: unkno return ( normalizedProvider === "xiaomi-mimo" || /(^|\/)mimo/i.test(normalizedModel) || - ["opencode", "opencode-go", "opencode-zen"].includes(normalizedProvider) + ["opencode-go", "opencode-zen"].includes(normalizedProvider) ); } diff --git a/scripts/ad-hoc/dry-run-strict-zero-cost.ts b/scripts/ad-hoc/dry-run-strict-zero-cost.ts index 54ea41f4d396..e90c8dba2569 100644 --- a/scripts/ad-hoc/dry-run-strict-zero-cost.ts +++ b/scripts/ad-hoc/dry-run-strict-zero-cost.ts @@ -38,11 +38,11 @@ function loadCandidates(path: string): Candidate[] { const list = Array.isArray(raw) ? raw : raw.candidates; // The candidates endpoint's `model` field is the FULL "/" // string (`modelStr` — the leading segment is sometimes the provider id, - // e.g. "groq/...", sometimes its short alias, e.g. "oc/..." for opencode); + // e.g. "groq/...", sometimes its short alias, e.g. "agy/..." for antigravity); // FREE_MODEL_BUDGETS.modelId is always bare. Strip exactly the first "/" // segment (whichever form it is) so e.g. "groq/meta-llama/llama-4-scout..." - // becomes "meta-llama/llama-4-scout..." and "oc/big-pickle" becomes - // "big-pickle", matching the catalog's modelId either way. + // becomes "meta-llama/llama-4-scout..." and "agy/gemini-3-flash" becomes + // "gemini-3-flash", matching the catalog's modelId either way. return list.map((c: { provider: string; model: string; connectionId?: string }) => { const slash = c.model.indexOf("/"); return { diff --git a/src/app/(dashboard)/dashboard/cli-code/components/HermesAgentToolCard.tsx b/src/app/(dashboard)/dashboard/cli-code/components/HermesAgentToolCard.tsx index 669d90b5f96f..145ed159dcf0 100644 --- a/src/app/(dashboard)/dashboard/cli-code/components/HermesAgentToolCard.tsx +++ b/src/app/(dashboard)/dashboard/cli-code/components/HermesAgentToolCard.tsx @@ -85,8 +85,6 @@ const HERMES_ROLES: Role[] = [ }, ]; -const HERMES_AGENT_ZERO_CONFIG_PROVIDERS = ["opencode"]; - export default function HermesAgentToolCard({ tool, isExpanded = false, @@ -617,7 +615,6 @@ export default function HermesAgentToolCard({ }} showCombos={true} activeProviders={activeProviders} - alwaysIncludeProviders={HERMES_AGENT_ZERO_CONFIG_PROVIDERS} modelAliases={modelAliases} /> diff --git a/src/app/(dashboard)/dashboard/combos/page.tsx b/src/app/(dashboard)/dashboard/combos/page.tsx index 30a00b4d9b36..80bbc6b116c6 100644 --- a/src/app/(dashboard)/dashboard/combos/page.tsx +++ b/src/app/(dashboard)/dashboard/combos/page.tsx @@ -2374,8 +2374,8 @@ function ComboFormModal({ builderConnectionId !== COMBO_BUILDER_AUTO_CONNECTION ? builderConnectionId : null, connectionLabel: selectedBuilderConnection?.label || null, allowedConnectionIds: builderEffectiveAllowedConnectionIds, - // #11433: use the already-corrected routing prefix (e.g. "oc" for - // OpenCode Free) instead of letting it default to the raw providerId. + // #11433: use the already-corrected routing prefix (e.g. a no-auth + // provider's alias) instead of letting it default to the raw providerId. modelPrefix: parseQualifiedModel(selectedBuilderModel.qualifiedModel)?.providerId, }) : null; @@ -2714,8 +2714,8 @@ function ComboFormModal({ builderConnectionId !== COMBO_BUILDER_AUTO_CONNECTION ? builderConnectionId : null, connectionLabel: selectedBuilderConnection?.label || null, allowedConnectionIds: builderEffectiveAllowedConnectionIds, - // #11433: use the already-corrected routing prefix (e.g. "oc" for - // OpenCode Free) instead of letting it default to the raw providerId. + // #11433: use the already-corrected routing prefix (e.g. a no-auth + // provider's alias) instead of letting it default to the raw providerId. modelPrefix: parseQualifiedModel(selectedBuilderModel.qualifiedModel)?.providerId, }); diff --git a/src/app/(dashboard)/dashboard/media-providers/components/LlmChatCard.tsx b/src/app/(dashboard)/dashboard/media-providers/components/LlmChatCard.tsx index 9f3b09411151..04c752f15cde 100644 --- a/src/app/(dashboard)/dashboard/media-providers/components/LlmChatCard.tsx +++ b/src/app/(dashboard)/dashboard/media-providers/components/LlmChatCard.tsx @@ -58,8 +58,8 @@ const NO_THINKING_PREFIX = "no-think/"; * contain a slash, so they were sent bare and rejected with * "Ambiguous model ... Use provider/model prefix" when the same id exists under * several providers (#3050). The routing prefix is normally the provider alias, - * which can intentionally differ from the provider id (for example `oc` routes - * OpenCode Free while `opencode` is reserved by the Zen executor). + * which can intentionally differ from the provider id (for example `unc` routes + * uncloseai). */ export function qualifyPlaygroundModel( model: string | null | undefined, diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/AnonymousFallbackToggle.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/AnonymousFallbackToggle.tsx index 4ae64dde7fae..bf5de9d1eee4 100644 --- a/src/app/(dashboard)/dashboard/providers/[id]/components/AnonymousFallbackToggle.tsx +++ b/src/app/(dashboard)/dashboard/providers/[id]/components/AnonymousFallbackToggle.tsx @@ -2,7 +2,7 @@ // Issue #8935 — per-provider opt-out for the synthetic anonymous (no-auth) // credential fallback on API-key providers whose static definition declares -// anonymousFallback: true (opencode-go, opencode-zen, pollinations, kilocode). +// anonymousFallback: true (pollinations, kilocode). // Default ON (fallback enabled) when the setting is absent, so existing // behavior is preserved for everyone who does not opt out. True no-auth // providers (NOAUTH_PROVIDERS / WEB_COOKIE_PROVIDERS) never see this control — diff --git a/src/app/(dashboard)/dashboard/providers/[id]/components/NoAuthProviderControls.tsx b/src/app/(dashboard)/dashboard/providers/[id]/components/NoAuthProviderControls.tsx index 0ebb4d5c0f6f..ad54e4851785 100644 --- a/src/app/(dashboard)/dashboard/providers/[id]/components/NoAuthProviderControls.tsx +++ b/src/app/(dashboard)/dashboard/providers/[id]/components/NoAuthProviderControls.tsx @@ -8,7 +8,6 @@ import { useNotificationStore } from "@/store/notificationStore"; import { providerText } from "../providerPageHelpers"; const ACCOUNT_PROVIDER_NAMES: Record = { - opencode: "OpenCode", dahl: "Dahl", }; diff --git a/src/app/api/providers/[id]/models/discovery/providerModelsConfig.ts b/src/app/api/providers/[id]/models/discovery/providerModelsConfig.ts index e38ebbc4afc9..da8016fb98ee 100644 --- a/src/app/api/providers/[id]/models/discovery/providerModelsConfig.ts +++ b/src/app/api/providers/[id]/models/discovery/providerModelsConfig.ts @@ -902,10 +902,9 @@ export const PROVIDER_MODELS_CONFIG: Record = authPrefix: "Bearer ", parseResponse: (data) => data.data || data.models || [], }, - // OpenCode CLI identity headers on all three opencode-family entries (see + // OpenCode CLI identity headers on both opencode-family entries (see // buildOpencodeModelsDiscoveryEntry above for why — bare "Bun fetch" calls // without x-opencode-session are what OpenCode's operator warning names). - opencode: buildOpencodeModelsDiscoveryEntry("https://opencode.ai/zen/v1/models"), "opencode-zen": buildOpencodeModelsDiscoveryEntry("https://opencode.ai/zen/v1/models"), "opencode-go": buildOpencodeModelsDiscoveryEntry("https://opencode.ai/zen/go/v1/models"), "glm-cn": { diff --git a/src/app/api/v1/models/catalogOrder.ts b/src/app/api/v1/models/catalogOrder.ts index 7e0bfce672f1..3338b77b0e57 100644 --- a/src/app/api/v1/models/catalogOrder.ts +++ b/src/app/api/v1/models/catalogOrder.ts @@ -10,7 +10,7 @@ * Group key = owned_by (the public owner identity), NOT the model-id prefix. * Built-in providers use their canonical id as owned_by; compatible nodes use the * configured node prefix. A single routable public prefix can differ from its owner: - * no-auth OpenCode publishes `oc/` while retaining owned_by "opencode". + * a no-auth provider publishes `/` while retaining its id as owned_by. * Grouping by the prefix would split one provider's models; grouping by owned_by * keeps them contiguous. * diff --git a/src/app/api/v1/models/catalogProviderMaps.ts b/src/app/api/v1/models/catalogProviderMaps.ts index 33350d968512..86115578a62b 100644 --- a/src/app/api/v1/models/catalogProviderMaps.ts +++ b/src/app/api/v1/models/catalogProviderMaps.ts @@ -105,9 +105,9 @@ export function resolveCanonicalProviderId( * providerId EXACTLY. Kept strict on purpose: this is the anti-collision * guard (catalog.ts, #11433/7db430a3) that stops the catalog from publishing * a provider-prefixed model id that would actually route to a DIFFERENT - * provider at request time — loosening it here would let a self-aliased - * no-auth provider (e.g. "opencode" -> "opencode-zen") pass a check that was - * specifically built to fail for it (#13994). + * provider at request time — loosening it here would let a provider whose id + * collides with a manual alias override pass a check that was specifically + * built to fail for it (#13994). */ export function prefixRoutesToProvider(prefix: string, providerId: string): boolean { const parsed = parseModel(`${prefix}/__omniroute_probe__`); diff --git a/src/lib/combos/builderDraft.ts b/src/lib/combos/builderDraft.ts index 3e4c7d76064f..e86e3df8bb3c 100644 --- a/src/lib/combos/builderDraft.ts +++ b/src/lib/combos/builderDraft.ts @@ -93,9 +93,9 @@ export function buildPrecisionComboModelStep({ allowedConnectionIds?: string[] | null; weight?: number; /** - * #11433: the routing-prefix segment to serialize into `model` (e.g. "oc" - * for the no-auth OpenCode Free provider), when it differs from the - * canonical `providerId`. Some canonical provider ids collide with an + * #11433: the routing-prefix segment to serialize into `model` (e.g. a + * no-auth provider's alias), when it differs from the canonical + * `providerId`. Some canonical provider ids collide with an * unrelated manual `ALIAS_TO_PROVIDER_ID` routing override (`opencode` → * `opencode-zen`), so reconstructing `model` from the raw `providerId` * alone can round-trip to the wrong provider on request routing. Falls @@ -174,10 +174,10 @@ export function buildManualComboModelStep({ const providerId = resolveComboBuilderProviderId(parsed.providerId, providers); if (!providerId) return null; - // #11433: preserve the user-typed prefix (e.g. "oc") as the routing prefix - // instead of letting buildPrecisionComboModelStep rebuild `model` from the - // resolved canonical providerId, which can collide with an unrelated - // manual alias override (e.g. "opencode" -> "opencode-zen"). + // #11433: preserve the user-typed prefix as the routing prefix instead of + // letting buildPrecisionComboModelStep rebuild `model` from the resolved + // canonical providerId, which can collide with an unrelated manual alias + // override (e.g. "opencode" -> "opencode-zen"). return buildPrecisionComboModelStep({ providerId, modelId: parsed.modelId, @@ -272,7 +272,7 @@ export function buildGlobalModelList( if (!modelId) return; const modelName = toTrimmedString(model?.name) || modelId; // #11433: derive the routing prefix from the model's already-corrected - // `qualifiedModel` (e.g. "oc/" for the OpenCode Free provider) + // `qualifiedModel` (e.g. "/" for a no-auth provider) // instead of defaulting to the raw providerId, which can collide with // an unrelated manual alias override. const modelPrefix = parseQualifiedModel(model?.qualifiedModel)?.providerId || providerId; diff --git a/src/lib/combos/builderOptions.ts b/src/lib/combos/builderOptions.ts index 06b0810cd7c9..8eb3f1e9e60e 100644 --- a/src/lib/combos/builderOptions.ts +++ b/src/lib/combos/builderOptions.ts @@ -704,18 +704,13 @@ export async function getComboBuilderOptions(): Promise/model"). const routingPrefix = - providerId === "opencode" + providerVisual.source === "provider-node" && providerVisual.alias ? providerVisual.alias - : providerVisual.source === "provider-node" && providerVisual.alias - ? providerVisual.alias - : providerId; + : providerId; rewriteQualifiedModelPrefix(modelMap, providerId, routingPrefix); const normalizedConnections = @@ -778,10 +773,9 @@ export async function getComboBuilderOptions(): Promise" misroutes to the opencode-zen api-key tier - // (manual ALIAS_TO_PROVIDER_ID override), while "oc/" resolves to the - // no-auth "opencode" provider. Rewrite qualifiedModel to the alias prefix. + // #2901: no-auth providers must route under their alias, not their id — a + // raw id can collide with a manual ALIAS_TO_PROVIDER_ID override that points + // at another provider. Rewrite qualifiedModel to the alias prefix. const routingPrefix = noAuthProvider.alias || providerId; rewriteQualifiedModelPrefix(modelMap, providerId, routingPrefix); diff --git a/src/lib/combos/controlCenter.ts b/src/lib/combos/controlCenter.ts index 3c16a03e8ab3..09d0374cb486 100644 --- a/src/lib/combos/controlCenter.ts +++ b/src/lib/combos/controlCenter.ts @@ -1,5 +1,4 @@ import { normalizeComboModels, type ComboStep } from "./steps"; -import { resolveComboTargetModelStr } from "../../../open-sse/services/combo/opencodeTargetAlias.ts"; import { resolveProviderAlias } from "../../../open-sse/services/providerAlias.ts"; type JsonRecord = Record; @@ -110,14 +109,12 @@ function toString(value: unknown): string | null { function providerFromModel(model: string | null | undefined): string | null { if (!model) return null; - // #11912: resolve through the same "opencode" -> "oc" combo-target alias - // treatment (and then the general alias table) that target resolution - // applies before dispatch, so this label matches what actually executed - // upstream instead of a raw, un-aliased prefix slice. - const normalized = resolveComboTargetModelStr(model); - const slashIndex = normalized.indexOf("/"); + // Resolve through the general alias table that target resolution applies + // before dispatch, so this label matches what actually executed upstream + // instead of a raw, un-aliased prefix slice. + const slashIndex = model.indexOf("/"); if (slashIndex <= 0) return null; - const prefix = normalized.slice(0, slashIndex); + const prefix = model.slice(0, slashIndex); return resolveProviderAlias(prefix) || prefix; } diff --git a/src/lib/db/migrations/206_remove_opencode_free_provider.sql b/src/lib/db/migrations/206_remove_opencode_free_provider.sql new file mode 100644 index 000000000000..e52ad73747ac --- /dev/null +++ b/src/lib/db/migrations/206_remove_opencode_free_provider.sql @@ -0,0 +1,24 @@ +-- 206_remove_opencode_free_provider.sql +-- The keyless "OpenCode Free" provider (id `opencode`, alias `oc`) was removed +-- from OmniRoute (see docs/reference/REMOVED_PROVIDERS.md). Clean up any +-- locally stored configuration for it. The paid `opencode-zen` and +-- `opencode-go` providers are separate ids and are not touched. +-- +-- Historical request, usage, and call-log records are intentionally preserved +-- (same principle as 152_remove_puter_provider.sql). + +DELETE FROM provider_connections +WHERE provider IN ('opencode', 'oc'); + +DELETE FROM registered_keys +WHERE provider IN ('opencode', 'oc'); + +DELETE FROM provider_key_limits +WHERE provider IN ('opencode', 'oc'); + +DELETE FROM discovery_results +WHERE provider_id IN ('opencode', 'oc'); + +DELETE FROM key_value +WHERE namespace = 'customModels' + AND key IN ('opencode', 'oc'); diff --git a/src/lib/db/settings.ts b/src/lib/db/settings.ts index 1ae1c56baae3..7f8fe06b3536 100644 --- a/src/lib/db/settings.ts +++ b/src/lib/db/settings.ts @@ -796,7 +796,7 @@ export async function resolveProxyForConnection( } } - // Step 8.5 (#6272): no-auth providers (mimocode, opencode, ...) share a single + // Step 8.5 (#6272): no-auth providers share a single // synthetic connectionId that never matches a `provider_connections` row, so // `connectionRecord` above is null and Steps 5-8 (which require it) never run for // them — a provider-level proxy assigned to a no-auth provider was silently diff --git a/src/lib/db/settings/noAuthProxyFallback.ts b/src/lib/db/settings/noAuthProxyFallback.ts index c682f292d308..6f413a4a186a 100644 --- a/src/lib/db/settings/noAuthProxyFallback.ts +++ b/src/lib/db/settings/noAuthProxyFallback.ts @@ -1,7 +1,7 @@ /** * db/settings/noAuthProxyFallback.ts * - * #6272 — no-auth providers (mimocode, opencode, ...) are dispatched with a single + * #6272 — no-auth providers are dispatched with a single * hardcoded, provider-agnostic connectionId ("noauth" — SYNTHETIC_NOAUTH_CONNECTION_ID * in src/sse/services/auth.ts). No `provider_connections` row ever has id="noauth", so * `resolveProxyForConnection()` in ../settings.ts can never populate `connectionRecord` diff --git a/src/lib/guardrails/visionBridgeCredentials.ts b/src/lib/guardrails/visionBridgeCredentials.ts index 75d1919aba2b..d00aaf1172b4 100644 --- a/src/lib/guardrails/visionBridgeCredentials.ts +++ b/src/lib/guardrails/visionBridgeCredentials.ts @@ -134,8 +134,8 @@ async function getPrefixToNode(): Promise | null> { * Returns `null` when the credential store is unavailable (unit tests / early boot). * * Two-step resolve before querying `provider_connections`: - * 1. alias→canonical id (#10702: the column stores the id, e.g. "opencode" - * for the "oc" alias — an alias-keyed query returned zero rows); + * 1. alias→canonical id (#10702: the column stores the id, not the alias — + * an alias-keyed query returned zero rows); * 2. public prefix→node id via the provider-prefix index (#re-land 932002580: * a compatible node's rows are stored under its generated * `openai-compatible-chat-` id while the operator-facing model id diff --git a/src/lib/modelsDevSync.ts b/src/lib/modelsDevSync.ts index 7b7392851a42..055058682674 100644 --- a/src/lib/modelsDevSync.ts +++ b/src/lib/modelsDevSync.ts @@ -447,15 +447,12 @@ export function getSyncedCapabilities(provider?: string, modelId?: string): Capa /** * Resolved providers/aliases to also try when looking up a synced capability. - * Required because models.dev has historically stored capability rows under the - * alias side of an alias pair (e.g. "opencode-zen") while the catalog & combo - * targets reference the canonical id (e.g. "opencode"). Without this fallback, - * combos whose targets use the canonical id (e.g. "Opencode FREE Omni" → all - * `opencode/...` models) end up with `context_length: null` in the catalog. + * Required because models.dev has historically stored capability rows under one + * side of an alias pair while the catalog & combo targets reference the other. + * Without this fallback such combos end up with `context_length: null` in the + * catalog. */ const SYNCED_CAPABILITY_FALLBACK_ALIASES: Record = { - opencode: ["opencode-zen"], - "opencode-zen": ["opencode"], "opencode-go": ["opencode-zen"], }; diff --git a/src/lib/modelsDevSync/transform.ts b/src/lib/modelsDevSync/transform.ts index 1457dd7f1b10..63efd38ff721 100644 --- a/src/lib/modelsDevSync/transform.ts +++ b/src/lib/modelsDevSync/transform.ts @@ -147,17 +147,8 @@ export const MODELS_DEV_PROVIDER_MAP: Record = { kilo: ["kilocode", "kc", "kilo-gateway"], kilocode: ["kilocode", "kc", "kilo-gateway"], "kimi-for-coding": ["kimi-coding", "kmc", "kimi-coding-apikey", "kmca"], - // The `opencode` models.dev entry used to map only to "opencode-zen" because - // that is the historical alias pair. But OmniRoute's catalog & combo targets - // reference models under BOTH provider IDs: - // - `opencode-zen/big-pickle` (alias form) - // - `opencode/big-pickle` (canonical id form, used by live API catalog - // and by combos like "Opencode FREE Omni") - // If we only store synced capabilities under "opencode-zen", the canonical - // `opencode/` lookup in getCanonicalModelMetadata returns null and - // any combo that targets `opencode/...` ends up with no computed context. - // Symmetric mapping keeps both lookup paths populated. - opencode: ["opencode", "opencode-zen"], + // The `opencode` models.dev entry is OpenCode Zen. + opencode: ["opencode-zen"], "opencode-go": ["opencode-go", "opencode-zen"], // Additional providers that may overlap with OmniRoute alibaba: ["ali", "alibaba"], @@ -240,9 +231,7 @@ export function transformModelsDevToPricing(raw: ModelsDevData): PricingByProvid // models.dev lists tiers as reasoning_options: [{ type: "effort", values }]. // Only the effort option is a reasoning tier; anything else is unrelated. -function modelsDevEffortValues( - options: ModelsDevReasoningOption[] | undefined -): string[] | null { +function modelsDevEffortValues(options: ModelsDevReasoningOption[] | undefined): string[] | null { if (!Array.isArray(options)) return null; const values = options.flatMap((option) => option?.type === "effort" && Array.isArray(option.values) ? option.values : [] diff --git a/src/lib/providerModels/hardcodedModelsConfigIds.ts b/src/lib/providerModels/hardcodedModelsConfigIds.ts index 2fa7c07773e5..5c248bb509b1 100644 --- a/src/lib/providerModels/hardcodedModelsConfigIds.ts +++ b/src/lib/providerModels/hardcodedModelsConfigIds.ts @@ -38,7 +38,6 @@ export const HARDCODED_MODELS_CONFIG_IDS: ReadonlySet = new Set([ "nvidia", "ollama-cloud", "openai", - "opencode", "opencode-go", "opencode-zen", "openference", diff --git a/src/shared/constants/providers.ts b/src/shared/constants/providers.ts index 9fed0ab2645a..7f110614dfb8 100644 --- a/src/shared/constants/providers.ts +++ b/src/shared/constants/providers.ts @@ -23,7 +23,6 @@ export const FREE_PROVIDERS = {}; export const FREE_APIKEY_PROVIDER_IDS = new Set([ "qoder", - "opencode", "dahl", // auggie is a fully local, credential-less CLI passthrough (auth handled by // `auggie login` outside OmniRoute). Admitted here purely so POST /api/providers diff --git a/src/shared/constants/providers/apikey/gateways.ts b/src/shared/constants/providers/apikey/gateways.ts index 27126ecc4523..e26c4727d064 100644 --- a/src/shared/constants/providers/apikey/gateways.ts +++ b/src/shared/constants/providers/apikey/gateways.ts @@ -766,7 +766,6 @@ export const APIKEY_PROVIDERS_GATEWAYS = { icon: "opencode", color: "#6366f1", website: "https://opencode.ai/zen", - anonymousFallback: true, // One credential fronts many upstream models (deepseek, glm, qwen, grok, // minimax, ...). A 402 means "this MODEL is not in the plan", not "the // account is out of credit", so it must reach the per-model lockout branch @@ -781,7 +780,6 @@ export const APIKEY_PROVIDERS_GATEWAYS = { icon: "opencode", color: "#6366f1", website: "https://opencode.ai/go", - anonymousFallback: true, // One credential fronts many upstream models (deepseek, glm, qwen, grok, // minimax, ...). A 402 means "this MODEL is not in the plan", not "the // account is out of credit", so it must reach the per-model lockout branch diff --git a/src/shared/constants/providers/noauth.ts b/src/shared/constants/providers/noauth.ts index 37a73b4306b2..e37ea52242e5 100644 --- a/src/shared/constants/providers/noauth.ts +++ b/src/shared/constants/providers/noauth.ts @@ -21,25 +21,6 @@ export const NOAUTH_PROVIDERS = { text: "This provider accepts only the official Devin CLI over local ACP stdio and never falls back to another provider.", }, }, - opencode: { - id: "opencode", - alias: "oc", - name: "OpenCode Free", - icon: "terminal", - color: "#E87040", - textIcon: "OC", - website: "https://opencode.ai", - noAuth: true, - hasFree: true, - serviceKinds: ["llm"], - authHint: - "No API key required — OpenCode's free tier can only be used from within OpenCode (client-contract requests).", - freeNote: - "No API key required — public OpenCode endpoint with Kimi, GLM, Qwen, MiMo, MiniMax models. Free tier only works from within OpenCode.", - notice: { - text: "OpenCode Free uses the public OpenCode endpoint (https://opencode.ai/zen/v1). No signup or API key needed. Rate limits apply. OpenCode's free tier can only be used from within OpenCode — requests that do not match the OpenCode client contract are refused with 403 FreeTierError.", - }, - }, "duckduckgo-web": { id: "duckduckgo-web", alias: "ddgw", @@ -196,7 +177,7 @@ export const NOAUTH_PROVIDERS = { // upstream path runs through OmniRoute's proxy-aware global fetch. Providers // with browser, WebSocket, direct dispatcher, media, or local CLI paths stay // hidden until those paths can guarantee the configured provider proxy. -export const NOAUTH_PROVIDER_PROXY_SUPPORTED = new Set(["opencode"]); +export const NOAUTH_PROVIDER_PROXY_SUPPORTED = new Set(); export function supportsNoAuthProviderProxy(providerId: string): boolean { return NOAUTH_PROVIDER_PROXY_SUPPORTED.has(providerId); diff --git a/src/shared/reasoning/effortStandardization.ts b/src/shared/reasoning/effortStandardization.ts index a8210e5a363b..641c2c4596f0 100644 --- a/src/shared/reasoning/effortStandardization.ts +++ b/src/shared/reasoning/effortStandardization.ts @@ -91,7 +91,7 @@ export function extendDeepSeekEffortValues( * DeepSeek provider (registry id `deepseek`, alias `ds`). * * Deliberately scoped to the native provider: routed namespaces such as - * `openrouter/deepseek/...` or `oc/deepseek-v4-flash-free` terminate at a different + * `openrouter/deepseek/...` or `opencode-zen/deepseek-v4-flash-free` terminate at a different * upstream whose accepted effort vocabulary we do not control. */ export function isDeepSeekNativeMaxModel( diff --git a/src/sse/services/auth.ts b/src/sse/services/auth.ts index a3bb0660dfc7..70e5e9cb17ea 100644 --- a/src/sse/services/auth.ts +++ b/src/sse/services/auth.ts @@ -700,9 +700,9 @@ function mergeNoAuthProviderSpecificData( * and resolve by-id Proxy Pool references to live records (./noAuthProxyResolution) * so the executor gets a resolved inline `proxy`. Best-effort: failures → empty. * - * #7993: also checks sibling ids (e.g. "opencode-zen" -> "opencode") so a - * proxy/fingerprint row saved under the no-auth id is still found when - * credentials are hydrated for the apikey-gateway id that shares its public + * #7993: also checks sibling ids (see noAuthProviderSiblings.ts) so a + * proxy/fingerprint row saved under a no-auth id is still found when + * credentials are hydrated for an apikey-gateway id that shares its public * endpoint. */ async function loadNoAuthProviderSpecificData(providerId: string): Promise { @@ -771,7 +771,7 @@ async function maybeSyntheticNoAuthFallback( requestedModelForPause?: string | null ) { if (!providerCanUseSyntheticNoAuthFallback(providerId)) return null; - // #9057: a restricted key must NOT reach free providers (OpenCode Free, etc.) through the + // #9057: a restricted key must NOT reach free no-auth providers through the // synthetic "noauth" connection unless its allowedConnections names it. if (!allowlistPermitsSyntheticNoAuth(allowedConnections)) return null; if (excludedConnectionIds.has(SYNTHETIC_NOAUTH_CONNECTION_ID)) return null; @@ -794,7 +794,7 @@ async function maybeSyntheticNoAuthFallback( return null; } // #4954: hydrate per-account proxy/rotation config off the connection row so - // no-auth executors (opencode, mimocode) actually honor configured proxies. + // no-auth executors actually honor configured proxies. const providerSpecificData = await loadNoAuthProviderSpecificData(providerId); return buildSyntheticNoAuthCredentials(providerSpecificData); } @@ -1079,7 +1079,7 @@ export async function getProviderCredentials( try { await selectionLock?.wait; - // No-auth providers (e.g. opencode) need no DB connection — return synthetic credentials + // No-auth providers need no DB connection — return synthetic credentials // so the executor receives a valid credentials object without auth headers being added. const resolvedId = resolveProviderId(provider); const providerMaps: Record[] = [ diff --git a/src/sse/services/model.ts b/src/sse/services/model.ts index 966463f310de..23d036a5ddbb 100644 --- a/src/sse/services/model.ts +++ b/src/sse/services/model.ts @@ -385,9 +385,9 @@ async function lookupModelMeta( getActiveSyncedCatalog(providerId), // #10898 / #7620: model-compat overrides (apiFormat/targetFormat/ // supportsVision, isHidden, ...) are stored keyed on the id the operator - // wrote them under. For a no-auth alias the model prefix resolves to the - // APIKEY gateway id (e.g. "opencode/x" -> providerId "opencode-zen") but - // the override was written on the sibling "opencode" row. Merge overrides + // wrote them under. For a no-auth alias the model prefix can resolve to an + // APIKEY gateway id while the override was written on the sibling no-auth + // row (see noAuthProviderSiblings.ts). Merge overrides // across the provider AND its no-auth sibling ids (requested id first) // instead of canonicalizing the low-level compat key, which would break // paths that legitimately key on the raw id (e.g. getHiddenModelsByProvider). diff --git a/src/sse/services/noAuthProviderSiblings.ts b/src/sse/services/noAuthProviderSiblings.ts index 5b36a99494b5..3ad3e26c5276 100644 --- a/src/sse/services/noAuthProviderSiblings.ts +++ b/src/sse/services/noAuthProviderSiblings.ts @@ -1,22 +1,12 @@ /** - * #7993 — "OpenCode Free" is served by TWO distinct provider identities that - * are never unified: the no-auth "opencode" provider (NOAUTH_PROVIDERS, - * alias "oc" — the id the NoAuthAccountCard UI writes fingerprints + - * accountProxies onto via a `provider_connections` row) and the - * "opencode-zen" / "opencode-go" APIKEY_PROVIDERS gateways (which carry - * `anonymousFallback: true` for the same public endpoint). + * #7993 — sibling provider ids whose no-auth `providerSpecificData` + * (fingerprints + accountProxies) must also be consulted when hydrating + * credentials for a provider that shares the same public endpoint. * - * A model string resolved to the canonical/full prefix ("opencode/") - * routes to "opencode-zen", not "opencode" (see the #2901 guard in - * open-sse/services/model.ts). When that happens, credential hydration for - * "opencode-zen" must still be able to find the user's proxy/fingerprint - * config, which physically lives on the "opencode" connection row — this - * sibling map lets `loadNoAuthProviderSpecificData()` look there too. + * Empty since the keyless OpenCode provider was removed (see + * docs/reference/REMOVED_PROVIDERS.md): it was the only sibling pair. */ -const NOAUTH_SIBLING_PROVIDER_IDS: Record = { - "opencode-zen": ["opencode"], - "opencode-go": ["opencode"], -}; +const NOAUTH_SIBLING_PROVIDER_IDS: Record = {}; /** Provider ids to query when hydrating no-auth `providerSpecificData` for `providerId`. */ export function getNoAuthHydrationProviderIds(providerId: string): string[] { diff --git a/src/sse/services/noAuthProxyResolution.ts b/src/sse/services/noAuthProxyResolution.ts index dde96bb1f5d3..a1ba88419f74 100644 --- a/src/sse/services/noAuthProxyResolution.ts +++ b/src/sse/services/noAuthProxyResolution.ts @@ -3,8 +3,7 @@ import { isProxyRegistryStatusAlive } from "@/lib/db/proxies/guards"; import { isRelayProxyType, extractRelayAuth } from "@/lib/db/proxies/mappers"; /** - * #5217 (Gap 1) — Per-account proxy resolution for no-auth providers - * ("OpenCode Free", MiMoCode, …). + * #5217 (Gap 1) — Per-account proxy resolution for no-auth providers. * * The NoAuthAccountCard now stores a proxy *reference* (by id) per account so a * single edit to a Proxy Pool entry applies to every account that references it, diff --git a/tests/unit/7993-noauth-proxy-routing.test.ts b/tests/unit/7993-noauth-proxy-routing.test.ts deleted file mode 100644 index dec0ac47a85c..000000000000 --- a/tests/unit/7993-noauth-proxy-routing.test.ts +++ /dev/null @@ -1,154 +0,0 @@ -/** - * #7993 — "OpenCode Free" is served by TWO distinct provider identities that - * are never unified: the no-auth "opencode" provider (NOAUTH_PROVIDERS — - * the id the NoAuthAccountCard UI writes fingerprints + accountProxies onto - * via a `provider_connections` row) and the "opencode-zen" APIKEY_PROVIDERS - * gateway (anonymousFallback: true, resolved from the canonical - * "opencode/" prefix via the #2901 alias override in - * open-sse/services/model.ts). - * - * Before the fix, `getProviderCredentials("opencode-zen")` fell through to - * `maybeSyntheticNoAuthFallback("opencode-zen", ...)`, which hydrated - * `providerSpecificData` by querying `provider_connections` filtered by - * `provider === "opencode-zen"` — a DIFFERENT id than the one the user's - * connection row is saved under ("opencode") — so the assigned proxy was - * silently dropped and the request egressed direct. - */ -import test from "node:test"; -import assert from "node:assert/strict"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -import net from "node:net"; - -const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-7993-noauth-proxy-")); -process.env.DATA_DIR = TEST_DATA_DIR; - -const core = await import("../../src/lib/db/core.ts"); -const { getProviderCredentials } = await import("../../src/sse/services/auth.ts"); -const { createProviderConnection } = await import("../../src/lib/db/providers.ts"); -const { createProxy } = await import("../../src/lib/db/proxies.ts"); -const { OpencodeExecutor } = await import("../../open-sse/executors/opencode.ts"); -const { resolveProxyForRequest } = await import("../../open-sse/utils/proxyFetch.ts"); - -const log = { debug() {}, info() {}, warn() {}, error() {} }; -const FINGERPRINT = "cccccccccccccccccccccccccccccccc"; - -let proxyServer: net.Server; -let proxyPort = 0; - -function listen(server: net.Server): Promise { - return new Promise((resolve) => { - server.listen(0, "127.0.0.1", () => { - resolve((server.address() as net.AddressInfo).port); - }); - }); -} - -test.before(async () => { - proxyServer = net.createServer((s) => s.destroy()); - proxyPort = await listen(proxyServer); - const proxy = await createProxy({ - name: "opencode-noauth-test-proxy", - type: "http", - host: "127.0.0.1", - port: proxyPort, - }); - assert.ok(proxy?.id, "test proxy must be persisted in the registry"); - - // Mirror exactly what the NoAuthAccountCard UI writes: a `provider_connections` - // row filed under the no-auth id "opencode" (NOT "opencode-zen"), carrying the - // configured account proxy as a Proxy Pool reference. - await createProviderConnection({ - provider: "opencode", - authType: "no-auth", - name: "opencode-noauth-account", - isActive: true, - providerSpecificData: { - fingerprints: [FINGERPRINT], - accountProxies: [ - { - fingerprint: FINGERPRINT, - proxyId: proxy.id, - }, - ], - }, - }); -}); - -test.after(() => { - proxyServer?.close(); - core.resetDbInstance(); - fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); -}); - -test("#7993 getProviderCredentials('opencode-zen') hydrates the proxy saved under the sibling 'opencode' connection", async () => { - const creds = (await getProviderCredentials("opencode-zen")) as { - connectionId?: string; - providerSpecificData?: { fingerprints?: unknown; accountProxies?: unknown }; - } | null; - - assert.ok(creds, "opencode-zen must resolve to credentials"); - assert.ok( - creds!.connectionId === "noauth" || - (typeof creds!.connectionId === "string" && creds!.connectionId.length > 0), - `expected synthetic noauth or the sibling opencode connection id, got ${creds!.connectionId}` - ); - const psd = creds!.providerSpecificData || {}; - assert.ok( - Array.isArray(psd.fingerprints) && psd.fingerprints.length === 1, - `expected the sibling opencode connection's fingerprints to be hydrated, got ${JSON.stringify(psd)}` - ); - assert.ok( - Array.isArray(psd.accountProxies) && psd.accountProxies.length === 1, - `expected the sibling opencode connection's accountProxies to be hydrated, got ${JSON.stringify(psd)}` - ); - const accountProxy = (psd.accountProxies as Array>)[0]; - assert.equal( - accountProxy.proxyId, - undefined, - "request credentials must not retain a raw proxyId" - ); - assert.deepEqual(accountProxy.proxy, { - type: "http", - host: "127.0.0.1", - port: proxyPort, - }); -}); - -test("#7993 a canonical 'opencode/' resolved combo/catalog target egresses through the assigned proxy, not direct", async () => { - const creds = await getProviderCredentials("opencode-zen"); - - const exec = new OpencodeExecutor("opencode-zen"); - let observedSource: string | null = null; - const originalFetch = globalThis.fetch; - globalThis.fetch = (async (input: unknown) => { - const url = - typeof input === "string" ? input : (input as { url?: string })?.url || String(input); - observedSource = resolveProxyForRequest(url).source; - return new Response(JSON.stringify({ ok: true }), { - status: 200, - headers: { "Content-Type": "application/json" }, - }); - }) as typeof globalThis.fetch; - - try { - const result = await exec.execute({ - model: "deepseek-v4-flash-free", - body: { messages: [{ role: "user", content: "hi" }], stream: false }, - stream: false, - signal: null, - credentials: creds as never, - log, - }); - assert.strictEqual((result as { response: Response }).response.status, 200); - } finally { - globalThis.fetch = originalFetch; - } - - assert.strictEqual( - observedSource, - "context", - `combo/catalog-path ('opencode-zen') must ALSO egress through the assigned proxy — got source=${observedSource}, expected 'context'` - ); -}); diff --git a/tests/unit/auth-opencode-zen-noauth-fallback.test.ts b/tests/unit/auth-opencode-zen-noauth-fallback.test.ts deleted file mode 100644 index 8d747949f39b..000000000000 --- a/tests/unit/auth-opencode-zen-noauth-fallback.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -/** - * Issue #2962 — Playground cannot use the OpenCode free model: - * "No credentials for the provider: opencode-zen". - * - * opencode-zen serves the public, signup-free OpenCode Zen endpoint - * (https://opencode.ai/zen/v1). When no API-key connection is configured, - * getProviderCredentials returned null → the chat handler surfaced - * "No credentials for provider: opencode-zen". It must instead fall back to - * anonymous (no-auth) credentials so the free tier works. - */ -import test from "node:test"; -import assert from "node:assert/strict"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-opencode-zen-noauth-")); -process.env.DATA_DIR = TEST_DATA_DIR; - -const core = await import("../../src/lib/db/core.ts"); -const { getProviderCredentials } = await import("../../src/sse/services/auth.ts"); -const { createProviderConnection } = await import("../../src/lib/db/providers.ts"); - -test.after(() => { - core.resetDbInstance(); - fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); -}); - -test("#2962 opencode-zen with no connection falls back to anonymous no-auth credentials", async () => { - const creds = await getProviderCredentials("opencode-zen"); - assert.ok(creds, "opencode-zen must resolve to credentials, not null (no-auth free tier)"); - assert.equal( - (creds as { connectionId?: string }).connectionId, - "noauth", - "should be synthetic no-auth credentials" - ); - assert.equal((creds as { apiKey?: unknown }).apiKey, null, "anonymous access carries no api key"); -}); - -test("apikey providers with anonymous fallback use no-auth when saved rows are terminal", async () => { - await createProviderConnection({ - provider: "pollinations", - authType: "apikey", - name: "expired-pollinations-key", - apiKey: "pollinations-expired", - isActive: true, - testStatus: "expired", - }); - - const creds = await getProviderCredentials("pollinations"); - assert.ok(creds, "pollinations should fall back to anonymous credentials"); - assert.equal((creds as { connectionId?: string }).connectionId, "noauth"); - assert.equal((creds as { apiKey?: unknown }).apiKey, null); -}); - -test("#2962 a normal api-key provider with no connection still returns null (no over-broadening)", async () => { - const creds = await getProviderCredentials("openai"); - // Must NOT synthesize no-auth creds for a real api-key provider. - const connectionId = (creds as { connectionId?: string } | null)?.connectionId; - assert.notEqual(connectionId, "noauth", "openai must not get anonymous no-auth credentials"); -}); - -test("#2962 opencode-zen falls back to no-auth when saved key rows are unusable", async () => { - await createProviderConnection({ - provider: "opencode-zen", - authType: "apikey", - name: "expired-test-key", - apiKey: "oa_test_expired", - isActive: true, - testStatus: "expired", - }); - - const creds = await getProviderCredentials("opencode-zen"); - assert.ok(creds, "opencode-zen should still resolve to anonymous no-auth credentials"); - assert.equal((creds as { connectionId?: string }).connectionId, "noauth"); - assert.equal((creds as { apiKey?: unknown }).apiKey, null); -}); diff --git a/tests/unit/combo-builder-opencode-prefix.test.ts b/tests/unit/combo-builder-opencode-prefix.test.ts deleted file mode 100644 index 24cfe8762d2e..000000000000 --- a/tests/unit/combo-builder-opencode-prefix.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Issue #2901 — OpenCode Free combo entries use the `opencode/` prefix instead - * of `oc/`. - * - * The no-auth OpenCode provider has id "opencode" and alias "oc". The combo - * builder built `qualifiedModel` from the provider *id* (`opencode/big-pickle`), - * but `parseModel("opencode/...")` resolves to the **opencode-zen** provider - * (an api-key tier) via a manual ALIAS_TO_PROVIDER_ID override — not the no-auth - * "opencode" provider. The user-facing routing alias `oc/` resolves correctly - * (`oc/big-pickle` → provider "opencode"). - * - * This test drives the real builder against a fresh DB and asserts that no-auth - * OpenCode models carry the `oc/` prefix. - */ -import test from "node:test"; -import assert from "node:assert/strict"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-combo-prefix-")); -process.env.DATA_DIR = TEST_DATA_DIR; - -const core = await import("../../src/lib/db/core.ts"); -const providersDb = await import("../../src/lib/db/providers.ts"); -const { getComboBuilderOptions } = await import("../../src/lib/combos/builderOptions.ts"); -const { parseModel } = await import("../../open-sse/services/model.ts"); - -test.after(() => { - core.resetDbInstance(); - fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); -}); - -test("#2901 no-auth OpenCode combo models use the oc/ prefix (not opencode/)", async () => { - const payload = await getComboBuilderOptions(); - const opencode = payload.providers.find((p) => p.providerId === "opencode"); - assert.ok(opencode, "no-auth 'opencode' provider must appear in the combo builder"); - - const bigPickle = opencode.models.find((m) => m.id === "big-pickle"); - assert.ok(bigPickle, "big-pickle must be listed under the no-auth opencode provider"); - assert.equal( - bigPickle.qualifiedModel, - "oc/big-pickle", - "no-auth opencode/big-pickle combo entry must use the 'oc/' routing alias" - ); - - // Every model under the no-auth provider must use the alias prefix. - for (const m of opencode.models) { - assert.ok( - m.qualifiedModel.startsWith("oc/"), - `qualifiedModel '${m.qualifiedModel}' must start with 'oc/' (got id-prefix instead)` - ); - } -}); - -test("#2901 configured OpenCode connections also use the oc/ prefix", async () => { - await providersDb.createProviderConnection({ - provider: "opencode", - authType: "apikey", - name: "OpenCode Free test connection", - apiKey: "test-key", - }); - - const payload = await getComboBuilderOptions(); - const opencode = payload.providers.find( - (provider) => provider.providerId === "opencode" && provider.connectionCount > 0 - ); - assert.ok(opencode, "configured OpenCode provider must appear in the combo builder"); - - const bigPickle = opencode.models.find((model) => model.id === "big-pickle"); - assert.ok(bigPickle, "big-pickle must be listed under the configured opencode provider"); - assert.equal( - bigPickle.qualifiedModel, - "oc/big-pickle", - "configured opencode combo entries must use the 'oc/' routing alias" - ); -}); - -test("#2901 the oc/ prefix actually resolves back to the no-auth opencode provider", () => { - // Guards the premise: opencode/ misroutes to opencode-zen, oc/ is correct. - assert.equal(parseModel("oc/big-pickle").provider, "opencode"); - assert.equal(parseModel("opencode/big-pickle").provider, "opencode-zen"); -}); diff --git a/tests/unit/issue-11912-opencode-roundrobin-collapse.test.ts b/tests/unit/issue-11912-opencode-roundrobin-collapse.test.ts deleted file mode 100644 index 7522e9d9a6ed..000000000000 --- a/tests/unit/issue-11912-opencode-roundrobin-collapse.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; - -import { resolveComboTargets } from "../../open-sse/services/combo/comboStructure.ts"; -import { resolveComboTargetModelStr } from "../../open-sse/services/combo/opencodeTargetAlias.ts"; -import { parseModel } from "../../open-sse/services/model.ts"; - -// Issue #11912: a round-robin combo built from several "opencode" (free / -// dynamic no-auth) targets plus one "opencode-zen" (authenticated api-key) -// target routed 100% of upstream traffic to the opencode-zen connection. -// -// Root cause: open-sse/services/model.ts's manual ALIAS_TO_PROVIDER_ID -// override canonicalizes ANY "opencode/" string to provider -// "opencode-zen" before dispatch, so every declared "opencode/" -// combo target and the explicit "opencode-zen/" target resolved to -// the identical provider identity — round-robin's "7 targets" were never 7 -// distinct upstream accounts. -// -// Fix: combo target resolution (comboStructure.ts's normalizeRuntimeStep) -// now rewrites an ambiguous "opencode/" combo target to the "oc/" -// no-auth alias, mirroring the combo builder's existing #2901 guard, before -// the model string reaches dispatch — so it resolves to the true no-auth -// "opencode" provider and stays distinct from an "opencode-zen/" -// sibling target. - -test("issue #11912: round-robin combo keeps opencode and opencode-zen targets on distinct providers", () => { - const targets = resolveComboTargets( - { - name: "opencode-round-robin", - strategy: "round-robin", - models: [ - { kind: "model", model: "opencode/mimo-v2.5-free" }, - { kind: "model", model: "opencode/mimo-v2.5-free" }, - { kind: "model", model: "opencode-zen/mimo-v2.5-free" }, - ], - }, - null - ); - - assert.equal(targets.length, 3); - const [dynamicA, dynamicB, authenticated] = targets; - - assert.notEqual( - dynamicA.provider, - authenticated.provider, - `combo target "opencode/" resolved to provider "${dynamicA.provider}" — it collapsed ` + - `onto the same identity as the explicit "opencode-zen/" target instead of routing ` + - `to the free/dynamic no-auth pool` - ); - assert.equal(dynamicA.provider, dynamicB.provider); - assert.equal(authenticated.provider, "opencode-zen"); - - // The rewritten model string must still resolve to the genuine no-auth - // provider identity when it later reaches dispatch (parseModel is exactly - // what open-sse/services/combo/roundRobinCombo.ts and - // resolveModelOrError() call on the resolved target's modelStr). - assert.equal(parseModel(dynamicA.modelStr).provider, "opencode"); - assert.equal(parseModel(authenticated.modelStr).provider, "opencode-zen"); -}); - -test("resolveComboTargetModelStr rewrites the ambiguous opencode/ prefix to oc/", () => { - assert.equal(resolveComboTargetModelStr("opencode/mimo-v2.5-free"), "oc/mimo-v2.5-free"); - // Siblings and the explicit api-key gateway must pass through untouched. - assert.equal(resolveComboTargetModelStr("opencode-zen/mimo-v2.5-free"), "opencode-zen/mimo-v2.5-free"); - assert.equal(resolveComboTargetModelStr("opencode-go/mimo-v2.5-free"), "opencode-go/mimo-v2.5-free"); - assert.equal(resolveComboTargetModelStr("oc/mimo-v2.5-free"), "oc/mimo-v2.5-free"); - // Non-slashed / non-opencode strings are untouched. - assert.equal(resolveComboTargetModelStr("bare-model"), "bare-model"); - assert.equal(resolveComboTargetModelStr("anthropic/claude"), "anthropic/claude"); -}); diff --git a/tests/unit/migration-206-remove-opencode-free-provider.test.ts b/tests/unit/migration-206-remove-opencode-free-provider.test.ts new file mode 100644 index 000000000000..ea3547f9fed1 --- /dev/null +++ b/tests/unit/migration-206-remove-opencode-free-provider.test.ts @@ -0,0 +1,167 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-opencode-free-retirement-")); +process.env.DATA_DIR = TEST_DATA_DIR; + +const core = await import("../../src/lib/db/core.ts"); + +test.after(() => { + core.resetDbInstance(); + fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); +}); + +test("migration 206 removes stale OpenCode Free provider state, keeps opencode-zen, and is idempotent", () => { + const db = core.getDbInstance(); + + const applied = db + .prepare("SELECT version FROM _omniroute_migrations WHERE version = 206") + .get() as { version: number } | undefined; + + assert.ok(applied, "migration 206 must be recorded as applied"); + + for (const provider of ["opencode", "oc"]) { + db.prepare( + "INSERT INTO provider_connections " + + "(id, provider, auth_type, name, is_active, created_at, updated_at) " + + "VALUES (?, ?, ?, ?, 1, datetime('now'), datetime('now'))" + ).run(`${provider}-connection`, provider, "apikey", `${provider}-legacy`); + + db.prepare( + "INSERT INTO registered_keys " + + "(id, key, key_prefix, name, provider, account_id) " + + "VALUES (?, ?, ?, ?, ?, ?)" + ).run( + `${provider}-key-id`, + `${provider}-key-hash`, + `${provider.slice(0, 8)}`, + `${provider}-key`, + provider, + `${provider}-account` + ); + + db.prepare("INSERT INTO provider_key_limits (provider) VALUES (?)").run(provider); + + db.prepare( + "INSERT INTO discovery_results " + + "(provider_id, method, endpoint, auth_type) " + + "VALUES (?, 'public_api', ?, 'api_key')" + ).run(provider, `https://${provider}.example.invalid/v1`); + + db.prepare( + "INSERT INTO key_value (namespace, key, value) " + "VALUES ('customModels', ?, '[]')" + ).run(provider); + + db.prepare( + "INSERT INTO usage_history (provider, model, timestamp) " + + "VALUES (?, 'legacy-model', datetime('now'))" + ).run(provider); + + db.prepare( + "INSERT INTO call_logs (id, timestamp, provider, model, status) " + + "VALUES (?, datetime('now'), ?, 'legacy-model', 200)" + ).run(`${provider}-historical-call`, provider); + } + + db.prepare( + "INSERT INTO provider_connections " + + "(id, provider, auth_type, name, is_active, created_at, updated_at) " + + "VALUES ('opencode-zen-control', 'opencode-zen', 'apikey', 'control', 1, datetime('now'), datetime('now'))" + ).run(); + + db.prepare( + "INSERT INTO registered_keys " + + "(id, key, key_prefix, name, provider, account_id) " + + "VALUES ('opencode-zen-key-id', 'opencode-zen-key-hash', 'opencode-', 'control', 'opencode-zen', 'control-account')" + ).run(); + + db.prepare("INSERT INTO provider_key_limits (provider) VALUES ('opencode-zen')").run(); + + db.prepare( + "INSERT INTO discovery_results " + + "(provider_id, method, endpoint, auth_type) " + + "VALUES ('opencode-zen', 'public_api', 'https://opencode-zen.example.invalid/v1', 'api_key')" + ).run(); + + db.prepare( + "INSERT INTO key_value (namespace, key, value) " + + "VALUES ('customModels', 'opencode-zen', '[]')" + ).run(); + + const sql = fs.readFileSync( + path.join(process.cwd(), "src/lib/db/migrations/206_remove_opencode_free_provider.sql"), + "utf8" + ); + + db.exec(sql); + db.exec(sql); + + for (const provider of ["opencode", "oc"]) { + assert.equal( + db.prepare("SELECT id FROM provider_connections WHERE provider = ?").get(provider), + undefined, + `${provider} provider_connections rows must be deleted` + ); + + assert.equal( + db.prepare("SELECT id FROM registered_keys WHERE provider = ?").get(provider), + undefined, + `${provider} registered_keys rows must be deleted` + ); + + assert.equal( + db.prepare("SELECT provider FROM provider_key_limits WHERE provider = ?").get(provider), + undefined, + `${provider} provider_key_limits rows must be deleted` + ); + + assert.equal( + db.prepare("SELECT id FROM discovery_results WHERE provider_id = ?").get(provider), + undefined, + `${provider} discovery_results rows must be deleted` + ); + + assert.equal( + db + .prepare("SELECT key FROM key_value WHERE namespace = 'customModels' AND key = ?") + .get(provider), + undefined, + `${provider} custom models must be deleted` + ); + + assert.ok( + db.prepare("SELECT id FROM usage_history WHERE provider = ?").get(provider), + `${provider} historical usage must be preserved` + ); + + assert.ok( + db.prepare("SELECT id FROM call_logs WHERE provider = ?").get(provider), + `${provider} historical call logs must be preserved` + ); + } + + assert.ok( + db.prepare("SELECT id FROM provider_connections WHERE provider = 'opencode-zen'").get() + ); + + assert.ok(db.prepare("SELECT id FROM registered_keys WHERE provider = 'opencode-zen'").get()); + + assert.ok( + db.prepare("SELECT provider FROM provider_key_limits WHERE provider = 'opencode-zen'").get() + ); + + assert.ok( + db.prepare("SELECT id FROM discovery_results WHERE provider_id = 'opencode-zen'").get() + ); + + assert.ok( + db + .prepare( + "SELECT key FROM key_value WHERE namespace = 'customModels' AND key = 'opencode-zen'" + ) + .get() + ); +}); diff --git a/tests/unit/noauth-autocombo-exclude-7622.test.ts b/tests/unit/noauth-autocombo-exclude-7622.test.ts deleted file mode 100644 index 4f1ccfef4fce..000000000000 --- a/tests/unit/noauth-autocombo-exclude-7622.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -/** - * #7622 — no-auth provider "Excluded Models" field is stored + enforced at - * dispatch time (src/sse/services/auth.ts) but IGNORED by the auto-combo/fusion - * candidate pool builder (`getNoAuthCandidates()` in - * open-sse/services/autoCombo/virtualFactory.ts). An excluded no-auth model must - * never be advertised/selected in `auto/*` combos in the first place — it should - * only fail over after being picked instead. - */ -import test from "node:test"; -import assert from "node:assert/strict"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-7622-noauth-exclude-")); -const ORIGINAL_DATA_DIR = process.env.DATA_DIR; - -process.env.DATA_DIR = TEST_DATA_DIR; - -const core = await import("../../src/lib/db/core.ts"); -const providersDb = await import("../../src/lib/db/providers.ts"); -const settingsDb = await import("../../src/lib/db/settings.ts"); -const virtualFactory = await import("../../open-sse/services/autoCombo/virtualFactory.ts"); - -async function resetStorage() { - core.resetDbInstance(); - fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); - fs.mkdirSync(TEST_DATA_DIR, { recursive: true }); -} - -test.beforeEach(async () => { - await resetStorage(); - // #15059: excludeTosAvoid defaults to true and every opencode model is tos:avoid; - // these tests exercise the no-auth pool builder, so opt out of the ToS filter. - await settingsDb.updateSettings({ excludeTosAvoid: false }); -}); - -test.after(async () => { - await resetStorage(); - fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); - - if (ORIGINAL_DATA_DIR === undefined) { - delete process.env.DATA_DIR; - } else { - process.env.DATA_DIR = ORIGINAL_DATA_DIR; - } -}); - -test("#7622: a no-auth model excluded via providerSpecificData.excludedModels is ABSENT from the auto-combo candidate pool", async () => { - const conn = await providersDb.createProviderConnection({ - provider: "opencode", - authType: "no-auth", - name: "OpenCode Free Account 1", - providerSpecificData: { excludedModels: "mimo-v2.5-free" }, - }); - assert.ok(conn.id, "connection must be created"); - - const combo = await virtualFactory.createVirtualAutoCombo(undefined); - - const modelStrings = combo.models.map((m: { model: string }) => m.model); - assert.ok( - !modelStrings.some((model: string) => model.endsWith("/mimo-v2.5-free")), - "BUG #7622: the excluded model 'mimo-v2.5-free' must not appear in the auto-combo " + - `candidate pool, but it did. Pool: ${JSON.stringify(modelStrings)}` - ); -}); - -test("#7622: a non-excluded no-auth model from the same connection remains in the auto-combo candidate pool", async () => { - await providersDb.createProviderConnection({ - provider: "opencode", - authType: "no-auth", - name: "OpenCode Free Account 1", - providerSpecificData: { excludedModels: "mimo-v2.5-free" }, - }); - - const combo = await virtualFactory.createVirtualAutoCombo(undefined); - - const modelStrings = combo.models.map((m: { model: string }) => m.model); - assert.ok( - modelStrings.some((model: string) => model.endsWith("/big-pickle")), - `a non-excluded model ("big-pickle") must remain in the pool. Pool: ${JSON.stringify(modelStrings)}` - ); -}); - -test("#7622 regression guard: with no excludedModels set, all opencode models remain in the pool (baseline unchanged)", async () => { - await providersDb.createProviderConnection({ - provider: "opencode", - authType: "no-auth", - name: "OpenCode Free Account 1", - providerSpecificData: { fingerprints: ["11111111111111111111111111111111"] }, - }); - - const combo = await virtualFactory.createVirtualAutoCombo(undefined); - - const modelStrings = combo.models.map((m: { model: string }) => m.model); - assert.ok( - modelStrings.some((model: string) => model.endsWith("/mimo-v2.5-free")), - `baseline: no exclusion set, mimo-v2.5-free must still be present. Pool: ${JSON.stringify(modelStrings)}` - ); -}); diff --git a/tests/unit/noauth-autocombo-hidden-7620.test.ts b/tests/unit/noauth-autocombo-hidden-7620.test.ts deleted file mode 100644 index c491dd22b499..000000000000 --- a/tests/unit/noauth-autocombo-hidden-7620.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -/** - * #7620 — hiding a no-auth-provider model with the EYE icon (Dashboard → Models, - * `isHidden: true` written via setModelIsHidden()/mergeModelCompatOverride()) does - * remove it from `/v1/models`, but `getNoAuthCandidates()` in - * `open-sse/services/autoCombo/virtualFactory.ts` never consults - * `getHiddenModelsByProvider()` at all (unlike the credentialed-connection loop a - * few lines above it, which does). A hidden no-auth model therefore stays in the - * `auto/*` candidate pool and can still be selected, causing a 401 when the - * upstream account for that hidden model is no longer valid/allowed. - */ -import test from "node:test"; -import assert from "node:assert/strict"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-7620-noauth-hidden-")); -const ORIGINAL_DATA_DIR = process.env.DATA_DIR; - -process.env.DATA_DIR = TEST_DATA_DIR; - -const core = await import("../../src/lib/db/core.ts"); -const modelsDb = await import("../../src/lib/db/models.ts"); -const settingsDb = await import("../../src/lib/db/settings.ts"); -const virtualFactory = await import("../../open-sse/services/autoCombo/virtualFactory.ts"); - -async function resetStorage() { - core.resetDbInstance(); - fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); - fs.mkdirSync(TEST_DATA_DIR, { recursive: true }); -} - -test.beforeEach(async () => { - await resetStorage(); - // contract changed by #15979 (on top of #15839): `excludeTosAvoid` defaults to on and - // uncataloged models inherit the provider's curated `tos: "avoid"` verdict, so every opencode - // model is ToS-filtered out of auto/*. Opt out so this file keeps guarding the #7620 - // hidden-model behaviour; the ToS default is covered by issue-15059-tos-avoid-auto-default. - await settingsDb.updateSettings({ excludeTosAvoid: false }); -}); - -test.after(async () => { - await resetStorage(); - fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); - if (ORIGINAL_DATA_DIR === undefined) { - delete process.env.DATA_DIR; - } else { - process.env.DATA_DIR = ORIGINAL_DATA_DIR; - } -}); - -test("#7620: a no-auth model hidden via the eye icon (isHidden:true) must be ABSENT from the auto-combo candidate pool", async () => { - modelsDb.setModelIsHidden("opencode", "mimo-v2.5-free", true); - - const hiddenMap = modelsDb.getHiddenModelsByProvider(); - const hidden = [...hiddenMap.values()].some((ids) => ids.has("mimo-v2.5-free")); - assert.equal( - hidden, - true, - "sanity: getHiddenModelsByProvider() must report mimo-v2.5-free as hidden" - ); - - const combo = await virtualFactory.createVirtualAutoCombo(undefined); - - const modelStrings = combo.models.map((m: { model: string }) => m.model); - assert.ok( - !modelStrings.some((model: string) => model.endsWith("/mimo-v2.5-free")), - "BUG #7620: the eye-hidden model 'mimo-v2.5-free' must not appear in the auto-combo " + - `candidate pool, but it did. Pool: ${JSON.stringify(modelStrings)}` - ); -}); - -test("#7620 baseline: with nothing hidden, opencode/mimo-v2.5-free is present in the pool", async () => { - const combo = await virtualFactory.createVirtualAutoCombo(undefined); - const modelStrings = combo.models.map((m: { model: string }) => m.model); - assert.ok( - modelStrings.some((model: string) => model.endsWith("/mimo-v2.5-free")), - `baseline: with nothing hidden, mimo-v2.5-free must be present. Pool: ${JSON.stringify(modelStrings)}` - ); -}); diff --git a/tests/unit/noauth-autocombo-lockout-7623.test.ts b/tests/unit/noauth-autocombo-lockout-7623.test.ts deleted file mode 100644 index 4d06deff6cc2..000000000000 --- a/tests/unit/noauth-autocombo-lockout-7623.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -/** - * #7623 — auto-combo candidate pool must honor existing model lockouts so - * repeatedly failing no-auth models (e.g. opencode 401) are not re-advertised. - */ -import test from "node:test"; -import assert from "node:assert/strict"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-7623-noauth-lockout-")); -const ORIGINAL_DATA_DIR = process.env.DATA_DIR; - -process.env.DATA_DIR = TEST_DATA_DIR; - -const core = await import("../../src/lib/db/core.ts"); -const providersDb = await import("../../src/lib/db/providers.ts"); -const settingsDb = await import("../../src/lib/db/settings.ts"); -const virtualFactory = await import("../../open-sse/services/autoCombo/virtualFactory.ts"); -const accountFallback = await import("../../open-sse/services/accountFallback.ts"); - -async function resetStorage() { - core.resetDbInstance(); - accountFallback.clearAllModelLockouts(); - fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); - fs.mkdirSync(TEST_DATA_DIR, { recursive: true }); -} - -test.beforeEach(async () => { - await resetStorage(); - // #15059: excludeTosAvoid defaults to true and every opencode model is tos:avoid; - // these tests exercise the no-auth pool builder, so opt out of the ToS filter. - await settingsDb.updateSettings({ excludeTosAvoid: false }); -}); - -test.after(async () => { - await resetStorage(); - fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); - - if (ORIGINAL_DATA_DIR === undefined) { - delete process.env.DATA_DIR; - } else { - process.env.DATA_DIR = ORIGINAL_DATA_DIR; - } -}); - -test("#7623: a model-locked no-auth opencode model is ABSENT from the auto-combo candidate pool", async () => { - accountFallback.lockModel("opencode", "noauth", "mimo-v2.5-free", "model_not_found", 60_000); - - const combo = await virtualFactory.createVirtualAutoCombo(undefined); - const modelStrings = combo.models.map((m: { model: string }) => m.model); - - assert.ok( - !modelStrings.some((model: string) => model.endsWith("/mimo-v2.5-free")), - "BUG #7623: locked no-auth model must not appear in auto-combo pool. Pool: " + - JSON.stringify(modelStrings) - ); -}); - -test("#7623: sibling no-auth models stay in the pool when only one model is locked", async () => { - accountFallback.lockModel("opencode", "noauth", "mimo-v2.5-free", "model_not_found", 60_000); - - const combo = await virtualFactory.createVirtualAutoCombo(undefined); - const modelStrings = combo.models.map((m: { model: string }) => m.model); - - assert.ok( - modelStrings.some((model: string) => model.endsWith("/big-pickle")), - `healthy sibling model must remain in pool. Pool: ${JSON.stringify(modelStrings)}` - ); -}); - -test("#7623: credentialed provider drops a connection from allowedConnectionIds when that model is locked", async () => { - const tokenExpiresAt = new Date(Date.now() + 60_000).toISOString(); - const locked = await providersDb.createProviderConnection({ - provider: "antigravity", - authType: "oauth", - email: "locked@example.com", - accessToken: "fake-token-locked", - tokenExpiresAt, - }); - const healthy = await providersDb.createProviderConnection({ - provider: "antigravity", - authType: "oauth", - email: "healthy@example.com", - accessToken: "fake-token-healthy", - tokenExpiresAt, - }); - - const lockedModel = "claude-sonnet-4-6"; - accountFallback.lockModel("antigravity", locked.id, lockedModel, "rate_limited", 60_000); - - const combo = await virtualFactory.createVirtualAutoCombo(undefined); - const candidate = combo.models.find( - (m: { model: string }) => m.model === `antigravity/${lockedModel}` - ) as { allowedConnectionIds?: string[] } | undefined; - - assert.ok(candidate, `expected antigravity/${lockedModel} logical candidate`); - assert.deepEqual( - [...(candidate.allowedConnectionIds ?? [])].sort(), - [healthy.id].sort(), - "locked connection must be removed from allowedConnectionIds" - ); - assert.ok( - !(candidate.allowedConnectionIds ?? []).includes(locked.id), - "locked connection must not remain eligible" - ); -}); diff --git a/tests/unit/opencode-noauth-models-route.test.ts b/tests/unit/noauth-models-route.test.ts similarity index 100% rename from tests/unit/opencode-noauth-models-route.test.ts rename to tests/unit/noauth-models-route.test.ts diff --git a/tests/unit/noauth-sibling-compat-override-7620.test.ts b/tests/unit/noauth-sibling-compat-override-7620.test.ts deleted file mode 100644 index 751eaab9e7c1..000000000000 --- a/tests/unit/noauth-sibling-compat-override-7620.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Regression: #7620 hidden-model persistence must survive the #10898 compat - * canonicalization (fixed in this PR by keying the low-level compat store on the - * RAW providerId and merging overrides across no-auth siblings at resolution). - * - * The bug: #10898 canonicalized the compat key via resolveProviderAlias inside - * readCompatList/writeCompatList. setModelIsHidden / mergeModelCompatOverride - * writes the isHidden override under the raw no-auth id "opencode", but #10898 - * relocated the write to the canonical APIKEY gateway id "opencode-zen". The - * hidden-model reader (getHiddenModelsByProvider) still keyed on "opencode", so - * it read an empty row and a hidden no-auth model reappeared in the auto-combo - * pool. - * - * The fix has two halves, both pinned here: - * (1) the low-level compat store keys on the RAW providerId again, so an - * override written under "opencode" lands on the "opencode" key and is - * NOT visible under the sibling "opencode-zen" key; and - * (2) resolution (getNoAuthHydrationProviderIds) merges overrides across the - * provider AND its no-auth siblings (requested id first), so a lookup that - * resolves the model prefix to "opencode-zen" still finds the override the - * operator wrote under "opencode". - */ - -import test from "node:test"; -import assert from "node:assert/strict"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-7620-sibling-compat-")); -process.env.DATA_DIR = TEST_DATA_DIR; -process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "compat-sibling-test-secret"; - -const { mergeModelCompatOverride, getModelCompatOverrides } = await import( - "../../src/lib/db/models/compat.ts" -); -const { getNoAuthHydrationProviderIds } = await import( - "../../src/sse/services/noAuthProviderSiblings.ts" -); -const { getModelInfo } = await import("../../src/sse/services/model.ts"); - -test("#7620: isHidden override written under raw 'opencode' stays on the raw key, not the 'opencode-zen' sibling", () => { - mergeModelCompatOverride("opencode", "grok-code-fast-1", { isHidden: true }); - - const rawOverrides = getModelCompatOverrides("opencode"); - const rawEntry = rawOverrides.find((m) => m.id === "grok-code-fast-1"); - assert.ok(rawEntry, "override must be stored on the raw 'opencode' key"); - assert.equal(rawEntry.isHidden, true); - - // #10898 regression guard: the write must NOT have been canonicalized onto the - // APIKEY gateway id. If it had, the raw-keyed hidden reader would miss it. - const siblingOverrides = getModelCompatOverrides("opencode-zen"); - const leaked = siblingOverrides.find((m) => m.id === "grok-code-fast-1"); - assert.equal( - leaked, - undefined, - "override must NOT leak onto the 'opencode-zen' key (that was the #10898 regression)" - ); -}); - -test("getNoAuthHydrationProviderIds merges the no-auth sibling so 'opencode-zen' resolution reaches 'opencode' overrides", () => { - // Sibling map contract: opencode-zen (and opencode-go) hydrate from opencode. - assert.deepEqual(getNoAuthHydrationProviderIds("opencode-zen"), ["opencode-zen", "opencode"]); - assert.deepEqual(getNoAuthHydrationProviderIds("opencode-go"), ["opencode-go", "opencode"]); - // A provider with no siblings resolves to just itself (requested id first). - assert.deepEqual(getNoAuthHydrationProviderIds("opencode"), ["opencode"]); - - // End-to-end: an override written under "opencode" is found when the merged - // sibling set for the resolved gateway id "opencode-zen" is walked. - mergeModelCompatOverride("opencode", "claude-sonnet-5", { - apiFormat: "responses", - targetFormat: "claude", - isHidden: true, - }); - const merged = getNoAuthHydrationProviderIds("opencode-zen").flatMap((id) => - getModelCompatOverrides(id) - ); - const resolved = merged.find((m) => m.id === "claude-sonnet-5"); - assert.ok(resolved, "sibling-merged overrides must include the 'opencode' row"); - assert.equal(resolved.isHidden, true); - assert.equal(resolved.apiFormat, "responses"); - assert.equal(resolved.targetFormat, "claude"); -}); - -test("#10898 stays fixed: getModelInfo('opencode/') resolves to opencode-zen and reads the sibling override", async () => { - mergeModelCompatOverride("opencode", "claude-opus-5", { - apiFormat: "responses", - targetFormat: "claude", - supportsVision: true, - }); - - const info = await getModelInfo("opencode/claude-opus-5"); - - assert.equal(info.provider, "opencode-zen"); - assert.equal(info.apiFormat, "responses"); - assert.equal(info.targetFormat, "claude"); - assert.equal(info.supportsVision, true); -}); diff --git a/tests/unit/opencode-autocombo-search-pair.test.ts b/tests/unit/opencode-autocombo-search-pair.test.ts deleted file mode 100644 index 34fa7d24c2fb..000000000000 --- a/tests/unit/opencode-autocombo-search-pair.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - -const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-opencode-pair-test-")); -process.env.DATA_DIR = TEST_DATA_DIR; -process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "opencode-pair-test-secret"; - -const core = await import("../../src/lib/db/core.ts"); -const { getProviderCredentials } = await import("../../src/sse/services/auth.ts"); - -test("getProviderCredentials('opencode-zen') finds active connection stored under 'opencode'", async () => { - const db = core.getDbInstance(); - const now = new Date().toISOString(); - - // Seed an active connection under provider='opencode' - db.prepare( - `INSERT OR REPLACE INTO provider_connections - (id, provider, is_active, api_key, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?)` - ).run("opencode-conn-1", "opencode", 1, "test-opencode-key", now, now); - - const creds = (await getProviderCredentials("opencode-zen")) as { apiKey?: string } | null; - - assert.ok(creds, "Credentials should be returned for opencode-zen lookup"); - assert.equal(creds!.apiKey, "test-opencode-key"); -}); diff --git a/tests/unit/opencode-free-tier-catalog-stale-6998.test.ts b/tests/unit/opencode-free-tier-catalog-stale-6998.test.ts deleted file mode 100644 index c1d3eeae090a..000000000000 --- a/tests/unit/opencode-free-tier-catalog-stale-6998.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import test from "node:test"; -import assert from "node:assert/strict"; - -const { opencodeProvider } = await import( - "../../open-sse/config/providers/registry/opencode/index.ts" -); - -function modelIds(): string[] { - return (opencodeProvider.models ?? []).map((m) => m.id); -} - -const DELISTED_FREE_MODELS = [ - "minimax-m3-free", - "minimax-m2.5-free", - "ling-2.6-1t-free", - "trinity-large-preview-free", - "nemotron-3-super-free", - "qwen3.6-plus-free", -]; - -const LIVE_FREE_MODELS_MISSING_FROM_CATALOG = [ - "mimo-v2.5-free", - "hy3-free", - "nemotron-3-ultra-free", - "north-mini-code-free", -]; - -test("issue #6998: oc registry does not advertise delisted free-tier models", () => { - const ids = modelIds(); - for (const delisted of DELISTED_FREE_MODELS) { - assert.ok(!ids.includes(delisted), `oc registry still advertises delisted upstream model "${delisted}"`); - } -}); - -test("issue #6998: oc registry advertises the current live free-tier models", () => { - const ids = modelIds(); - for (const live of LIVE_FREE_MODELS_MISSING_FROM_CATALOG) { - assert.ok(ids.includes(live), `oc registry is missing live upstream free-tier model "${live}"`); - } -}); diff --git a/tests/unit/opencode-free-tier-refusal-rotation.test.ts b/tests/unit/opencode-free-tier-refusal-rotation.test.ts deleted file mode 100644 index 3be93880abb8..000000000000 --- a/tests/unit/opencode-free-tier-refusal-rotation.test.ts +++ /dev/null @@ -1,396 +0,0 @@ -import { describe, it, beforeEach, afterEach, before, after } from "node:test"; -import assert from "node:assert"; -import net from "node:net"; -import { OpencodeExecutor } from "../../open-sse/executors/opencode.ts"; -import type { ExecutorLog, ProviderCredentials } from "../../open-sse/executors/base.ts"; -import { resolveProxyForRequest } from "../../open-sse/utils/proxyFetch.ts"; -import { resetDbInstance } from "../../src/lib/db/core.ts"; -import { - _resetToolObservationForTests, - getObservedToolNames, - recordAcceptedToolNames, -} from "../../open-sse/executors/opencodeToolObservation.ts"; - -// Upstream free-tier refusal: the request identity/shape is rejected, the account -// is not. Rotating cannot help (every account gets the same verdict from the same -// request), and the refusal must never improve the account's rotation health — -// markSuccess resets the failure history that drives the cooldown backoff. -const REFUSAL_BODY = JSON.stringify({ - type: "error", - error: { - type: "FreeTierError", - message: - "Error from provider (Console): OpenCode's free tier can only be used from within OpenCode", - }, -}); -const REAL_400_BODY = JSON.stringify({ - error: { type: "invalid_request_error", message: "max_tokens is too large" }, -}); - -const log: ExecutorLog = { debug() {}, info() {}, warn() {}, error() {} }; -const FPS = ["a", "b", "c"].map((c) => c.repeat(32)); -const servers: net.Server[] = []; -const ports: number[] = []; - -function listen(server: net.Server): Promise { - return new Promise((resolve) => { - server.listen(0, "127.0.0.1", () => resolve((server.address() as net.AddressInfo).port)); - }); -} - -before(async () => { - for (let i = 0; i < FPS.length; i++) { - const server = net.createServer((s) => s.destroy()); - servers.push(server); - ports.push(await listen(server)); - } -}); - -after(() => { - servers.forEach((s) => s.close()); - resetDbInstance(); -}); - -function credentialsFor(count: number): ProviderCredentials { - const fingerprints = FPS.slice(0, count); - return { - apiKey: null, - accessToken: null, - connectionId: "noauth", - providerSpecificData: { - fingerprints, - accountProxies: fingerprints.map((fp, i) => ({ - fingerprint: fp, - proxy: { type: "http", host: "127.0.0.1", port: ports[i] }, - })), - }, - }; -} - -type AccountsProbe = Array<{ - fingerprint: string; - cooldownUntil: number; - consecutiveFails: number; -}>; - -function accountsOf(exec: OpencodeExecutor): AccountsProbe { - return (exec as unknown as { accounts: AccountsProbe }).accounts; -} - -describe("OpencodeExecutor free-tier refusal", () => { - let originalFetch: typeof globalThis.fetch; - let observed: string[]; - - beforeEach(() => { - originalFetch = globalThis.fetch; - observed = []; - }); - - afterEach(() => { - globalThis.fetch = originalFetch; - }); - - function installFetch(plan: Array<{ status: number; body?: string }>) { - let call = 0; - globalThis.fetch = (async (input: RequestInfo | URL) => { - const url = - typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; - const resolved = resolveProxyForRequest(url); - observed.push(resolved.proxyUrl ? new URL(resolved.proxyUrl).port : "direct"); - const step = plan[Math.min(call, plan.length - 1)]; - call++; - return new Response(step.body ?? JSON.stringify({ ok: true }), { - status: step.status, - headers: { "Content-Type": "application/json" }, - }); - }) as typeof globalThis.fetch; - } - - async function run(exec: OpencodeExecutor, creds: ProviderCredentials) { - const result = (await exec.execute({ - model: "muse-spark-1.3-contributor-free", - // The client declares its own tool list: the request contract adds nothing, so a refusal - // is returned as-is. (When the contract injects the tools itself, the executor replays - // the request once in the other shape first: see opencode-request-shape-retry.test.ts.) - body: { - messages: [{ role: "user", content: "hi" }], - tools: [{ type: "function", function: { name: "read", parameters: { type: "object" } } }], - stream: false, - }, - stream: false, - signal: null, - credentials: creds, - log, - })) as { response: Response }; - return result.response; - } - - // Materialize the account list, then set the health the refusal must not touch. - async function warmUp(exec: OpencodeExecutor, creds: ProviderCredentials) { - installFetch([{ status: 200 }]); - const warm = await run(exec, creds); - await warm.body?.cancel(); - observed = []; - for (const account of accountsOf(exec)) account.consecutiveFails = 2; - } - - for (const status of [403, 451]) { - it(`${status}: returned as-is, no rotation, account health untouched`, async () => { - const exec = new OpencodeExecutor("opencode-zen"); - const creds = credentialsFor(3); - await warmUp(exec, creds); - installFetch([{ status, body: REFUSAL_BODY }, { status: 200 }]); - - const response = await run(exec, creds); - - assert.strictEqual(response.status, status); - assert.strictEqual(await response.text(), REFUSAL_BODY, "upstream body preserved"); - assert.strictEqual(observed.length, 1, "no rotation: every account gets the same verdict"); - for (const account of accountsOf(exec)) { - assert.strictEqual(account.consecutiveFails, 2, "never marked success"); - assert.strictEqual(account.cooldownUntil, 0, "no cooldown: the account is not at fault"); - } - }); - } - - it("a single account behaves the same (no special case)", async () => { - const exec = new OpencodeExecutor("opencode-zen"); - const creds = credentialsFor(1); - await warmUp(exec, creds); - installFetch([{ status: 403, body: REFUSAL_BODY }, { status: 200 }]); - - const response = await run(exec, creds); - - assert.strictEqual(response.status, 403); - assert.strictEqual(observed.length, 1); - assert.strictEqual(accountsOf(exec)[0].consecutiveFails, 2); - }); - - it("a 400 carrying a real upstream error no longer marks the account successful", async () => { - const exec = new OpencodeExecutor("opencode-zen"); - const creds = credentialsFor(2); - await warmUp(exec, creds); - installFetch([{ status: 400, body: REAL_400_BODY }]); - - const response = await run(exec, creds); - - assert.strictEqual(response.status, 400); - assert.strictEqual(await response.text(), REAL_400_BODY); - for (const account of accountsOf(exec)) { - assert.strictEqual(account.consecutiveFails, 2, "a rejected request is not a success"); - } - }); - - it("an unmatched refusal status no longer marks the account successful", async () => { - const exec = new OpencodeExecutor("opencode-zen"); - const creds = credentialsFor(2); - await warmUp(exec, creds); - installFetch([ - { status: 401, body: JSON.stringify({ error: { message: "invalid api key" } }) }, - ]); - - const response = await run(exec, creds); - - assert.strictEqual(response.status, 401); - await response.body?.cancel(); - for (const account of accountsOf(exec)) { - assert.strictEqual(account.consecutiveFails, 2); - } - }); - - it("a successful response still clears the account's failure history", async () => { - const exec = new OpencodeExecutor("opencode-zen"); - const creds = credentialsFor(2); - await warmUp(exec, creds); - installFetch([{ status: 200 }]); - - const response = await run(exec, creds); - - assert.strictEqual(response.status, 200); - await response.body?.cancel(); - - const served = accountsOf(exec).filter((a) => a.consecutiveFails === 0); - assert.strictEqual(served.length, 1, "the account that served is reset"); - }); -}); - -describe("OpencodeExecutor free-tier refusal retry with observed tools", () => { - let originalFetch: typeof globalThis.fetch; - let seenTools: Array; - - beforeEach(() => { - originalFetch = globalThis.fetch; - seenTools = []; - _resetToolObservationForTests(); - }); - - afterEach(() => { - globalThis.fetch = originalFetch; - }); - - function toolNameOf(entry: unknown): string | null { - if (!entry || typeof entry !== "object" || Array.isArray(entry)) return null; - const rec = entry as { name?: unknown; function?: { name?: unknown } }; - const name = typeof rec.name === "string" ? rec.name : rec.function?.name; - return typeof name === "string" ? name : null; - } - - async function runWithBody(exec: OpencodeExecutor, body: unknown) { - return (await exec.execute({ - model: "muse-spark-1.3-contributor-free", - body, - stream: true, - signal: null, - credentials: { - apiKey: null, - accessToken: null, - connectionId: "noauth", - providerSpecificData: {}, - }, - log, - })) as { response: Response }; - } - - // Single direct account (fast path): first dispatch 403 FreeTier, retry carries - // the union and succeeds — one extra fetch, original tools intact first. - // - // Since #14156 the contract appends the RESOLVED placeholder names to client tools on - // the first dispatch too, and resolution prefers the operator's configured names over - // the un-scoped observed ones. The retry therefore only adds something when the - // observed names differ from the configured ones — so this scenario configures `bash`. - it("retries once with observed names appended and returns the retry success", async () => { - const prevConfigured = process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS; - process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS = "bash"; - after(() => { - if (prevConfigured === undefined) delete process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS; - else process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS = prevConfigured; - }); - const exec = new OpencodeExecutor("opencode"); - recordAcceptedToolNames("opencode", "muse-spark-1.3-contributor-free", undefined, [ - "edit", - "write", - ]); - const calls: Array<{ status: number; body?: string }> = [ - { status: 403, body: REFUSAL_BODY }, - { status: 200, body: JSON.stringify({ ok: true }) }, - ]; - let call = 0; - globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { - const parsed = JSON.parse(String((init as Record)?.body ?? "{}")) as { - tools?: unknown[]; - }; - seenTools.push(Array.isArray(parsed.tools) ? parsed.tools.map(toolNameOf) : null); - const step = calls[Math.min(call, calls.length - 1)]; - call++; - return new Response(step.body ?? "{}", { - status: step.status, - headers: { "Content-Type": "application/json" }, - }); - }) as typeof globalThis.fetch; - - const clientBody = { - model: "muse-spark-1.3-contributor-free", - messages: [{ role: "user", content: "hi" }], - stream: true, - tools: [ - { type: "function", function: { name: "glob", parameters: { type: "object" } } }, - { type: "function", function: { name: "read", parameters: { type: "object" } } }, - ], - }; - const result = await runWithBody(exec, clientBody); - - assert.strictEqual(result.response.status, 200); - assert.strictEqual(seenTools.length, 2, "exactly one retry dispatch"); - assert.deepEqual( - seenTools[0], - ["glob", "read", "bash"], - "first dispatch keeps client tools first, then the configured placeholders (#14156)" - ); - assert.deepEqual( - seenTools[1], - ["glob", "read", "edit", "write", "bash"], - "retry appends observed names after client tools" - ); - await result.response.body?.cancel(); - }); - - // #14156 + #14464 interaction: without configured names the first dispatch already - // carries the observed names, so the merged retry body would be byte-for-byte the shape - // the upstream just refused. It must not be re-sent. - it("does not re-send the refused shape when the first dispatch already carried the observed names", async () => { - const exec = new OpencodeExecutor("opencode"); - recordAcceptedToolNames("opencode", "muse-spark-1.3-contributor-free", undefined, [ - "edit", - "write", - ]); - globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { - const parsed = JSON.parse(String((init as Record)?.body ?? "{}")) as { - tools?: unknown[]; - }; - seenTools.push(Array.isArray(parsed.tools) ? parsed.tools.map(toolNameOf) : null); - return new Response(REFUSAL_BODY, { - status: 403, - headers: { "Content-Type": "application/json" }, - }); - }) as typeof globalThis.fetch; - - const result = await runWithBody(exec, { - model: "muse-spark-1.3-contributor-free", - messages: [{ role: "user", content: "hi" }], - stream: true, - tools: [ - { type: "function", function: { name: "glob", parameters: { type: "object" } } }, - { type: "function", function: { name: "read", parameters: { type: "object" } } }, - ], - }); - - assert.strictEqual(result.response.status, 403); - assert.deepEqual(seenTools, [["glob", "read", "edit", "write"]], "one dispatch, no duplicate"); - }); - - // Retry refusal: the ORIGINAL 403 is propagated and the store is untouched. - it("propagates the original refusal when the retry is refused, store untouched", async () => { - const exec = new OpencodeExecutor("opencode"); - recordAcceptedToolNames("opencode", "muse-spark-1.3-contributor-free", undefined, ["edit"]); - globalThis.fetch = (async () => { - return new Response(REFUSAL_BODY, { - status: 403, - headers: { "Content-Type": "application/json" }, - }); - }) as typeof globalThis.fetch; - - const result = await runWithBody(exec, { - model: "muse-spark-1.3-contributor-free", - messages: [{ role: "user", content: "hi" }], - stream: true, - tools: [{ type: "function", function: { name: "glob", parameters: { type: "object" } } }], - }); - - assert.strictEqual(result.response.status, 403); - assert.strictEqual(await result.response.text(), REFUSAL_BODY); - assert.deepEqual(getObservedToolNames("opencode", "muse-spark-1.3-contributor-free"), ["edit"]); - }); - - // Nothing observed to add: no second fetch. - it("skips the retry when the store holds nothing new", async () => { - const exec = new OpencodeExecutor("opencode"); - let fetches = 0; - globalThis.fetch = (async () => { - fetches++; - return new Response(REFUSAL_BODY, { - status: 403, - headers: { "Content-Type": "application/json" }, - }); - }) as typeof globalThis.fetch; - - const result = await runWithBody(exec, { - model: "muse-spark-1.3-contributor-free", - messages: [{ role: "user", content: "hi" }], - stream: true, - tools: [{ type: "function", function: { name: "glob", parameters: { type: "object" } } }], - }); - - assert.strictEqual(result.response.status, 403); - assert.strictEqual(fetches, 1, "no retry without observed names"); - }); -}); diff --git a/tests/unit/opencode-free-tier-request-contract.test.ts b/tests/unit/opencode-free-tier-request-contract.test.ts deleted file mode 100644 index 020adbdc6390..000000000000 --- a/tests/unit/opencode-free-tier-request-contract.test.ts +++ /dev/null @@ -1,959 +0,0 @@ -/** - * OpenCode Zen free-tier request contract. - * - * Since 2026-09-17 the free tier answers 403 FreeTierError unless the request carries - * all four of: `stream: true`, a non-empty `tools` array, an `x-opencode-session` (or - * `x-session-id`) shaped `ses_` + 12 hex + 14 base62, and a `User-Agent` containing - * `opencode/= 1.17>`. Removing any one of the four turns a 200 into a 403, and - * a version below 1.17 answers 426 instead. - * - * Measured again on 2026-09-18, and the tools condition is narrower than it first looked: - * the upstream inspects which names are declared. One made-up name, twelve made-up names - * and twelve plausible names borrowed from another vocabulary are all refused, while six, - * nine and twelve names from the official client pass; three of those same names are - * refused. What the upstream takes also differs by model and moves between days, which is - * why the placeholder is resolved at runtime rather than pinned here. - * - * `tool_choice` is never imposed on any surface: the upstream rejects every value but - * "auto" with a 400 invalid_request_error (`only "auto" is supported for tool_choice`). - * - * Paid models on the same host are not gated (one without tools answers 401), so the - * request contract applies to free-tier models only. - */ -import { test } from "node:test"; -import assert from "node:assert/strict"; -import { - applyFreeTierRequestContract, - configuredPlaceholderToolNames, - mergeClientToolsWithObserved, - noteFreeTierOutcome, - prepareFreeTierRequest, - isGatedFreeTierRequest, - requiresFreeTierRequestContract, - surfaceFromBaseUrl, -} from "../../open-sse/executors/opencodeFreeTierContract.ts"; -import { - _resetToolObservationForTests, - getObservedToolNames, - recordAcceptedToolNames, - resolvePlaceholderNames, -} from "../../open-sse/executors/opencodeToolObservation.ts"; -import { - DEFAULT_OPENCODE_USER_AGENT, - OPENCODE_SESSION_PATTERN, - clientSuppliedOpencodeSession, - forwardOpencodeClientHeaders, - satisfiesOpencodeUserAgentContract, -} from "../../open-sse/utils/opencodeHeaders.ts"; -import { OpencodeExecutor } from "../../open-sse/executors/opencode.ts"; - -const CHAT_BODY = () => ({ - model: "nemotron-3.5-lightning-free", - messages: [{ role: "user", content: "hi" }], -}); -const RESPONSES_BODY = () => ({ - model: "muse-spark-1.3-contributor-free", - input: [{ role: "user", content: "hi" }], -}); - -test("the contract applies to free-tier models on the gated surface only", () => { - assert.equal( - requiresFreeTierRequestContract("zen", "opencode", "nemotron-3.5-lightning-free"), - true - ); - assert.equal(requiresFreeTierRequestContract("zen", "opencode-zen", "big-pickle"), true); - assert.equal( - requiresFreeTierRequestContract("zen", "opencode-zen", "muse-spark-1.3-contributor-free"), - true - ); - assert.equal(requiresFreeTierRequestContract("zen", "opencode-zen", "gpt-5.6-luna"), false); - // The other surface refuses a request that carries tools rather than one that does not - // (upstream anomalyco/opencode#44300 and #44382), so it is never brought up to this - // contract — including for the free model its registry declares. - assert.equal(requiresFreeTierRequestContract("go", "opencode-go", "big-pickle"), false); - assert.equal(requiresFreeTierRequestContract("go", "opencode-go", "ox-alpha-free"), false); - assert.equal(requiresFreeTierRequestContract("other", "groq", "big-pickle"), false); -}); - -test("the surface is told apart by base url, so the `oc` alias needs no special case", () => { - assert.equal(surfaceFromBaseUrl("https://opencode.ai/zen/v1"), "zen"); - assert.equal(surfaceFromBaseUrl("https://opencode.ai/zen/go/v1"), "go"); - assert.equal(surfaceFromBaseUrl("https://api.groq.com/openai/v1"), "other"); - assert.equal(surfaceFromBaseUrl(undefined), "other"); -}); - -test("chat completions: the contract adds streaming and a placeholder tool, and no tool_choice", () => { - const body = applyFreeTierRequestContract(CHAT_BODY(), "openai") as Record; - assert.equal(body.stream, true); - const tools = body.tools as Array<{ type: string; function: { name: string } }>; - assert.equal(tools.length, 1); - assert.equal(tools[0].type, "function"); - assert.equal(tools[0].function.name, "_noop"); - // The upstream answers 400 `only "auto" is supported for tool_choice` (measured - // 2026-09-18 on the Chat Completions surface), so none is imposed here either. - assert.equal("tool_choice" in body, false); -}); - -test("the placeholder carries the names it is given, one entry each", () => { - const body = applyFreeTierRequestContract(CHAT_BODY(), "openai", [ - "glob", - "grep", - "read", - ]) as Record; - const tools = body.tools as Array<{ function: { name: string; parameters: object } }>; - assert.deepEqual( - tools.map((t) => t.function.name), - ["glob", "grep", "read"] - ); - // Names only: an empty parameter object, so a borrowed name is a list entry rather than - // a tool the model could usefully call. - assert.deepEqual(tools[0].function.parameters, { type: "object", properties: {} }); -}); - -test("responses: several placeholder names keep the flat shape and no tool_choice", () => { - const body = applyFreeTierRequestContract(RESPONSES_BODY(), "openai-responses", [ - "glob", - "grep", - ]) as Record; - const tools = body.tools as Array<{ type: string; name: string }>; - assert.deepEqual( - tools.map((t) => t.name), - ["glob", "grep"] - ); - assert.equal("tool_choice" in body, false); -}); - -test("an empty tools array counts as no tools", () => { - // It is the exact shape the upstream refuses — the official client sends it on its own - // compaction path (upstream anomalyco/opencode#49433). - const body = applyFreeTierRequestContract({ ...CHAT_BODY(), tools: [] }, "openai") as Record< - string, - unknown - >; - assert.equal((body.tools as unknown[]).length, 1); -}); - -test("responses: the placeholder tool is flat and tool_choice stays absent", () => { - // The upstream Responses surface rejects tool_choice with a 400 invalid_request_error - // (measured on both "none" and {type:"none"}), so the contract must not send it there. - const body = applyFreeTierRequestContract(RESPONSES_BODY(), "openai-responses") as Record< - string, - unknown - >; - assert.equal(body.stream, true); - const tools = body.tools as Array<{ type: string; name: string }>; - assert.equal(tools.length, 1); - assert.equal(tools[0].type, "function"); - assert.equal(tools[0].name, "_noop"); - assert.equal("tool_choice" in body, false); -}); - -test("client-supplied tools are never replaced, required placeholders are appended, and no tool_choice is imposed", () => { - const clientTools = [ - { type: "function", function: { name: "search", parameters: { type: "object" } } }, - ]; - const body = applyFreeTierRequestContract( - { ...CHAT_BODY(), tools: clientTools }, - "openai" - ) as Record; - const tools = body.tools as Array<{ type: string; function?: { name: string } }>; - assert.equal(tools.length, 2); - assert.equal(tools[0].function?.name, "search"); - assert.equal(tools[1].function?.name, "_noop"); - assert.equal("tool_choice" in body, false); - assert.equal(body.stream, true); -}); - -test("when client-supplied tools already include placeholder tools, nothing extra is added", () => { - const clientTools = [ - { type: "function", function: { name: "search", parameters: { type: "object" } } }, - { type: "function", function: { name: "_noop", parameters: { type: "object" } } }, - ]; - const body = applyFreeTierRequestContract( - { ...CHAT_BODY(), tools: clientTools }, - "openai" - ) as Record; - assert.deepEqual(body.tools, clientTools); -}); - -test("when client-supplied tools are present, multiple configured placeholders are appended", () => { - const clientTools = [ - { type: "function", function: { name: "run_code", parameters: { type: "object" } } }, - ]; - const body = applyFreeTierRequestContract({ ...CHAT_BODY(), tools: clientTools }, "openai", [ - "glob", - "grep", - "read", - "edit", - "write", - "bash", - ]) as Record; - const tools = body.tools as Array<{ type: string; function?: { name: string } }>; - assert.equal(tools.length, 7); - assert.equal(tools[0].function?.name, "run_code"); - assert.deepEqual( - tools.slice(1).map((t) => t.function?.name), - ["glob", "grep", "read", "edit", "write", "bash"] - ); -}); - -test("a client tool_choice is preserved", () => { - const body = applyFreeTierRequestContract( - { ...CHAT_BODY(), tool_choice: "auto" }, - "openai" - ) as Record; - assert.equal(body.tool_choice, "auto"); -}); - -test("applying the contract twice does not duplicate the placeholder tool", () => { - const once = applyFreeTierRequestContract(CHAT_BODY(), "openai"); - const twice = applyFreeTierRequestContract(once, "openai") as Record; - assert.equal((twice.tools as unknown[]).length, 1); -}); - -test("an unknown body format only gets the streaming flag", () => { - const body = applyFreeTierRequestContract(CHAT_BODY(), "claude") as Record; - assert.equal(body.stream, true); - assert.equal("tools" in body, false); - assert.equal("tool_choice" in body, false); -}); - -test("the user-agent contract accepts a versioned opencode client and rejects the rest", () => { - assert.equal(satisfiesOpencodeUserAgentContract(DEFAULT_OPENCODE_USER_AGENT), true); - assert.equal(satisfiesOpencodeUserAgentContract("opencode/1.17.0"), true); - assert.equal(satisfiesOpencodeUserAgentContract("opencode/beta/1.18.31/cli"), true); - assert.equal( - satisfiesOpencodeUserAgentContract("opencode/1.18.14 ai-sdk/provider-utils/4.0.23"), - true - ); - // Measured: 1.16.0 answers 426 UpgradeRequired, so it does not satisfy the contract. - assert.equal(satisfiesOpencodeUserAgentContract("opencode/1.16.0"), false); - assert.equal(satisfiesOpencodeUserAgentContract("opencode-cli/1.0.0"), false); - assert.equal(satisfiesOpencodeUserAgentContract("opencode"), false); - assert.equal(satisfiesOpencodeUserAgentContract("curl/8.5.0"), false); - assert.equal(satisfiesOpencodeUserAgentContract(undefined), false); -}); - -test("synthesized identity headers carry a canonical session and request id", () => { - const headers: Record = {}; - forwardOpencodeClientHeaders( - headers, - {}, - { - cliDefaults: { - userAgent: DEFAULT_OPENCODE_USER_AGENT, - client: "desktop", - project: "global", - }, - sessionBody: CHAT_BODY(), - } - ); - assert.equal(headers["User-Agent"], DEFAULT_OPENCODE_USER_AGENT); - assert.match(headers["x-opencode-session"] ?? "", OPENCODE_SESSION_PATTERN); - assert.match(headers["x-opencode-request"] ?? "", /^msg_[0-9a-f]{12}[0-9A-Za-z]{14}$/); -}); - -test("the same conversation keeps the same session id, a different one does not", () => { - const sessionFor = (body: Record) => { - const headers: Record = {}; - forwardOpencodeClientHeaders( - headers, - {}, - { - cliDefaults: { - userAgent: DEFAULT_OPENCODE_USER_AGENT, - client: "desktop", - project: "global", - }, - sessionBody: body, - } - ); - return headers["x-opencode-session"]; - }; - const first = sessionFor(CHAT_BODY()); - assert.equal(sessionFor(CHAT_BODY()), first, "conversation-stable, so upstream caching hits"); - assert.notEqual( - sessionFor({ ...CHAT_BODY(), messages: [{ role: "user", content: "other" }] }), - first - ); -}); - -test("a client session already in the canonical shape is preserved", () => { - const canonical = "ses_0123456789abABCDEFGHIJKLMN"; - const headers: Record = {}; - forwardOpencodeClientHeaders( - headers, - { "x-opencode-session": canonical }, - { - cliDefaults: { - userAgent: DEFAULT_OPENCODE_USER_AGENT, - client: "desktop", - project: "global", - }, - } - ); - assert.equal(headers["x-opencode-session"], canonical); -}); - -test("a foreign client session is translated into the canonical shape, deterministically", () => { - const translate = () => { - const headers: Record = {}; - forwardOpencodeClientHeaders( - headers, - { "x-opencode-session": "conv-42" }, - { - cliDefaults: { - userAgent: DEFAULT_OPENCODE_USER_AGENT, - client: "desktop", - project: "global", - }, - } - ); - return headers["x-opencode-session"]; - }; - const translated = translate(); - assert.match(translated ?? "", OPENCODE_SESSION_PATTERN); - assert.equal(translate(), translated, "same client session, same upstream session"); -}); - -test("buildHeaders: a free-tier request accepts an event stream even when the client wants JSON", () => { - const executor = new OpencodeExecutor("opencode-zen"); - const headers = executor.buildHeaders(null, false, null, "nemotron-3.5-lightning-free"); - assert.equal(headers["Accept"], "text/event-stream"); - assert.equal(headers["User-Agent"], DEFAULT_OPENCODE_USER_AGENT); - assert.match(headers["x-opencode-session"] ?? "", OPENCODE_SESSION_PATTERN); -}); - -test("buildHeaders: a paid model keeps the client's non-streaming expectation", () => { - const executor = new OpencodeExecutor("opencode-zen"); - const headers = executor.buildHeaders(null, false, null, "gpt-5.6-luna"); - assert.equal(headers["Accept"], undefined); -}); - -test("transformRequest: the contract is applied for a free model and skipped for a paid one", () => { - const executor = new OpencodeExecutor("opencode-zen"); - const free = executor.transformRequest( - "nemotron-3.5-lightning-free", - CHAT_BODY(), - false, - null as never - ) as Record; - assert.equal(free.stream, true); - assert.equal((free.tools as unknown[]).length, 1); - - const paid = executor.transformRequest( - "gpt-5.6-luna", - { model: "gpt-5.6-luna", messages: [{ role: "user", content: "hi" }] }, - false, - null as never - ) as Record; - assert.equal("tools" in paid, false); - assert.equal(paid.stream, undefined); -}); - -test("a JSON caller gets a JSON body back even though the upstream request was streamed", async () => { - // The contract forces streaming, so the executor owes every caller that asked for JSON a - // JSON body — handleChatCore can buffer an event stream, but the other consumers - // (compression judge, token counting) call execute() and read response.json() directly. - const executor = new OpencodeExecutor("opencode-zen"); - const originalFetch = globalThis.fetch; - const seen: Array> = []; - globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { - seen.push(JSON.parse(String(init?.body ?? "{}"))); - const sse = - 'data: {"id":"gen-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":null}]}\n\n' + - 'data: {"id":"gen-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n' + - "data: [DONE]\n\n"; - return new Response(sse, { - status: 200, - headers: { "Content-Type": "text/event-stream" }, - }); - }) as typeof globalThis.fetch; - - try { - const result = (await executor.execute({ - model: "nemotron-3.5-lightning-free", - body: { model: "nemotron-3.5-lightning-free", messages: [{ role: "user", content: "hi" }] }, - stream: false, - signal: null, - credentials: { apiKey: "k", accessToken: null, connectionId: "c" }, - log: { debug() {}, info() {}, warn() {}, error() {} }, - })) as { response: Response }; - - assert.equal(seen[0]?.stream, true, "the upstream request was streamed"); - assert.equal((seen[0]?.tools as unknown[]).length, 1, "and carried the placeholder tool"); - assert.match(result.response.headers.get("content-type") ?? "", /application\/json/); - const json = (await result.response.json()) as { - choices?: Array<{ message?: { content?: string } }>; - }; - assert.equal(json.choices?.[0]?.message?.content, "hi"); - } finally { - globalThis.fetch = originalFetch; - } -}); - -test("a streaming caller still receives the event stream untouched", async () => { - const executor = new OpencodeExecutor("opencode-zen"); - const originalFetch = globalThis.fetch; - globalThis.fetch = (async () => - new Response('data: {"choices":[{"delta":{"content":"hi"}}]}\n\n', { - status: 200, - headers: { "Content-Type": "text/event-stream" }, - })) as typeof globalThis.fetch; - try { - const result = (await executor.execute({ - model: "nemotron-3.5-lightning-free", - body: { - model: "nemotron-3.5-lightning-free", - messages: [{ role: "user", content: "hi" }], - stream: true, - }, - stream: true, - signal: null, - credentials: { apiKey: "k", accessToken: null, connectionId: "c" }, - log: { debug() {}, info() {}, warn() {}, error() {} }, - })) as { response: Response }; - assert.match(result.response.headers.get("content-type") ?? "", /text\/event-stream/); - await result.response.body?.cancel(); - } finally { - globalThis.fetch = originalFetch; - } -}); - -test("a gated request repairs a stale configured user-agent, a non-gated one keeps it", () => { - // An operator still carrying the previous default in OPENCODE_USER_AGENT would otherwise - // keep sending `opencode`, which the free tier refuses. Outside the gate the configured - // value is still honoured verbatim (#5997). - const saved = process.env.OPENCODE_USER_AGENT; - process.env.OPENCODE_USER_AGENT = "opencode"; - try { - const executor = new OpencodeExecutor("opencode-zen"); - const gated = executor.buildHeaders(null, true, null, "nemotron-3.5-lightning-free"); - assert.equal(gated["User-Agent"], DEFAULT_OPENCODE_USER_AGENT); - assert.ok(satisfiesOpencodeUserAgentContract(gated["User-Agent"])); - - const paid = executor.buildHeaders(null, true, null, "gpt-5.6-luna"); - assert.equal(paid["User-Agent"], "opencode"); - } finally { - if (saved === undefined) delete process.env.OPENCODE_USER_AGENT; - else process.env.OPENCODE_USER_AGENT = saved; - } -}); - -test("responses: two conversations on the same model get different session ids", () => { - const executor = new OpencodeExecutor("opencode"); - executor._requestFormat = "openai-responses"; - const sessionFor = (text: string) => - executor.buildHeaders(null, true, null, "muse-spark-1.3-contributor-free", undefined, { - model: "muse-spark-1.3-contributor-free", - input: [{ role: "user", content: text }], - })["x-opencode-session"]; - - const first = sessionFor("first conversation"); - assert.match(first ?? "", OPENCODE_SESSION_PATTERN); - assert.equal(sessionFor("first conversation"), first, "same conversation, same session"); - assert.notEqual( - sessionFor("a completely different opening message"), - first, - "the Responses surface carries the conversation under input, not messages" - ); -}); - -// ── The placeholder is resolved from what the upstream is currently accepting ────────── - -test("the opt-out switches the body half off and leaves the scope predicate alone", () => { - const previous = process.env.OPENCODE_FREE_TIER_REQUEST_CONTRACT; - try { - process.env.OPENCODE_FREE_TIER_REQUEST_CONTRACT = "off"; - assert.equal( - requiresFreeTierRequestContract("zen", "opencode", "nemotron-3.5-lightning-free"), - false - ); - assert.equal(isGatedFreeTierRequest("zen", "opencode", "nemotron-3.5-lightning-free"), true); - const { body, attempt } = prepareFreeTierRequest( - CHAT_BODY(), - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free" - ); - assert.equal(attempt, null); - assert.equal("tools" in (body as Record), false); - assert.equal("stream" in (body as Record), false); - } finally { - if (previous === undefined) delete process.env.OPENCODE_FREE_TIER_REQUEST_CONTRACT; - else process.env.OPENCODE_FREE_TIER_REQUEST_CONTRACT = previous; - } -}); - -test("configured placeholder names are parsed, bad entries dropped, unset stays empty", () => { - const previous = process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS; - try { - delete process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS; - assert.deepEqual(configuredPlaceholderToolNames(), []); - process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS = " glob , grep ,,9bad, glob ,ok-name"; - assert.deepEqual(configuredPlaceholderToolNames(), ["glob", "grep", "ok-name"]); - } finally { - if (previous === undefined) delete process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS; - else process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS = previous; - } -}); - -test("with nothing observed and nothing configured, the built-in placeholder is used", () => { - _resetToolObservationForTests(); - const { body, attempt } = prepareFreeTierRequest( - CHAT_BODY(), - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free" - ); - const tools = (body as Record).tools as Array<{ function: { name: string } }>; - assert.deepEqual( - tools.map((t) => t.function.name), - ["_noop"] - ); - // Nothing was borrowed, so a refusal here must not be charged against the store. - assert.equal(attempt?.borrowed, false); -}); - -test("an accepted request teaches the names it carried, and a later bare request borrows them", () => { - _resetToolObservationForTests(); - const withTools = { - ...CHAT_BODY(), - tools: [ - { type: "function", function: { name: "glob" } }, - { type: "function", function: { name: "grep" } }, - ], - }; - const first = prepareFreeTierRequest( - withTools, - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free" - ); - assert.deepEqual(first.attempt?.clientToolNames, ["glob", "grep"]); - noteFreeTierOutcome(first.attempt, true); - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), [ - "glob", - "grep", - ]); - - const second = prepareFreeTierRequest( - CHAT_BODY(), - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free" - ); - const tools = (second.body as Record).tools as Array<{ - function: { name: string }; - }>; - assert.deepEqual( - tools.map((t) => t.function.name), - ["glob", "grep"] - ); - assert.equal(second.attempt?.borrowed, true); -}); - -test("configured placeholder names take precedence over un-scoped observed tools for generic clients", () => { - _resetToolObservationForTests(); - recordAcceptedToolNames("opencode", "big-pickle", undefined, ["run_code"]); - const resolved = resolvePlaceholderNames("opencode", "big-pickle", undefined, ["glob", "grep"]); - assert.deepEqual(resolved, ["glob", "grep"]); -}); - -test("what one model learns stays with that model", () => { - // Asserts an absence, so it stays green if the store is removed entirely — it guards - // against cross-model leakage, not against the mechanism disappearing. - _resetToolObservationForTests(); - const learned = prepareFreeTierRequest( - { ...CHAT_BODY(), tools: [{ type: "function", function: { name: "glob" } }] }, - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free" - ); - noteFreeTierOutcome(learned.attempt, true); - assert.equal(getObservedToolNames("opencode", "big-pickle"), null); - assert.equal(getObservedToolNames("opencode-zen", "nemotron-3.5-lightning-free"), null); -}); - -test("a borrowed set is dropped after three refusals in a row, not after one", () => { - _resetToolObservationForTests(); - const learned = prepareFreeTierRequest( - { ...CHAT_BODY(), tools: [{ type: "function", function: { name: "glob" } }] }, - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free" - ); - noteFreeTierOutcome(learned.attempt, true); - - const borrow = () => - prepareFreeTierRequest(CHAT_BODY(), "openai", "zen", "opencode", "nemotron-3.5-lightning-free") - .attempt; - // One refusal is not proof: the same body was refused and then accepted minutes apart on - // a free model (measured 2026-09-18), so a single verdict must not clear the entry. - // Only a refusal that says something about the tools counts: a bare verdict or a - // 429 leaves the entry alone. - const refused = () => - noteFreeTierOutcome(borrow(), { ok: false, status: 403, bodyText: REFUSAL_BODY }); - refused(); - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), ["glob"]); - refused(); - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), ["glob"]); - refused(); - assert.equal(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), null); -}); - -test("an acceptance resets the refusal streak", () => { - _resetToolObservationForTests(); - const withTools = { - ...CHAT_BODY(), - tools: [{ type: "function", function: { name: "glob" } }], - }; - const learned = prepareFreeTierRequest( - withTools, - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free" - ); - noteFreeTierOutcome(learned.attempt, true); - const borrow = () => - prepareFreeTierRequest(CHAT_BODY(), "openai", "zen", "opencode", "nemotron-3.5-lightning-free") - .attempt; - const refused = () => - noteFreeTierOutcome(borrow(), { ok: false, status: 403, bodyText: REFUSAL_BODY }); - refused(); - refused(); - noteFreeTierOutcome( - prepareFreeTierRequest(withTools, "openai", "zen", "opencode", "nemotron-3.5-lightning-free") - .attempt, - true - ); - noteFreeTierOutcome(borrow(), { ok: false, status: 403, bodyText: REFUSAL_BODY }); - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), ["glob"]); -}); - -test("a refusal on the caller's own tools never touches the store", () => { - _resetToolObservationForTests(); - const withTools = { - ...CHAT_BODY(), - tools: [{ type: "function", function: { name: "glob" } }], - }; - noteFreeTierOutcome( - prepareFreeTierRequest(withTools, "openai", "zen", "opencode", "nemotron-3.5-lightning-free") - .attempt, - true - ); - for (let i = 0; i < 5; i++) { - const own = prepareFreeTierRequest( - withTools, - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free" - ); - assert.equal(own.attempt?.borrowed, false); - noteFreeTierOutcome(own.attempt, false); - } - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), ["glob"]); -}); - -test("the other surface is left alone entirely", () => { - // Scope guard only. That `/zen/go/v1` refuses a request carrying tools comes from - // upstream anomalyco/opencode#44300 and #44382, not from a measurement here: this - // installation exposes no model on that surface. - _resetToolObservationForTests(); - const { body, attempt } = prepareFreeTierRequest( - CHAT_BODY(), - "openai", - "go", - "opencode-go", - "ox-alpha-free" - ); - assert.equal(attempt, null); - assert.equal("tools" in (body as Record), false); - assert.equal("stream" in (body as Record), false); -}); - -// ── A conversation repairs its own service requests ─────────────────────────────────── - -const SES_A = "ses_0123456789abABCDEFGHIJKLMN"; -const SES_B = "ses_fedcba987654ZYXWVUTSRQPONM"; - -test("a session's service request borrows the list its own build request declared", () => { - _resetToolObservationForTests(); - // The official client sends its build requests with a full tool list and its title and - // compaction requests with none, on the same session (upstream - // anomalyco/opencode#49433). The second gets back what the first declared. - const build = prepareFreeTierRequest( - { - ...CHAT_BODY(), - tools: [ - { type: "function", function: { name: "glob" } }, - { type: "function", function: { name: "grep" } }, - ], - }, - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free", - SES_A - ); - noteFreeTierOutcome(build.attempt, true); - - const title = prepareFreeTierRequest( - CHAT_BODY(), - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free", - SES_A - ); - const tools = (title.body as Record).tools as Array<{ - function: { name: string }; - }>; - assert.deepEqual( - tools.map((t) => t.function.name), - ["glob", "grep"] - ); - assert.equal(title.attempt?.borrowed, true); -}); - -test("a session's own list wins over the shared one", () => { - _resetToolObservationForTests(); - // Order matters: the session entry is recorded FIRST and the shared entry overwritten - // afterwards by another conversation, so a store keyed by model alone would answer - // "shared" here and this case would fail. - const own = prepareFreeTierRequest( - { ...CHAT_BODY(), tools: [{ type: "function", function: { name: "own" } }] }, - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free", - SES_A - ); - noteFreeTierOutcome(own.attempt, true); - const shared = prepareFreeTierRequest( - { ...CHAT_BODY(), tools: [{ type: "function", function: { name: "shared" } }] }, - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free", - SES_B - ); - noteFreeTierOutcome(shared.attempt, true); - - const borrowed = prepareFreeTierRequest( - CHAT_BODY(), - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free", - SES_A - ); - const tools = (borrowed.body as Record).tools as Array<{ - function: { name: string }; - }>; - assert.deepEqual( - tools.map((t) => t.function.name), - ["own"] - ); -}); - -test("a session that has declared nothing yet falls back to the shared entry", () => { - _resetToolObservationForTests(); - noteFreeTierOutcome( - prepareFreeTierRequest( - { ...CHAT_BODY(), tools: [{ type: "function", function: { name: "shared" } }] }, - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free", - SES_A - ).attempt, - true - ); - const fresh = prepareFreeTierRequest( - CHAT_BODY(), - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free", - SES_B - ); - const tools = (fresh.body as Record).tools as Array<{ - function: { name: string }; - }>; - assert.deepEqual( - tools.map((t) => t.function.name), - ["shared"] - ); -}); - -test("a client session id is read case-insensitively, a synthesized one is not borrowed from", () => { - assert.equal(clientSuppliedOpencodeSession({ "X-OpenCode-Session": SES_A }), SES_A); - assert.equal(clientSuppliedOpencodeSession({ "x-session-id": SES_B }), SES_B); - assert.equal(clientSuppliedOpencodeSession({ "x-opencode-session": " " }), undefined); - assert.equal(clientSuppliedOpencodeSession({}), undefined); - assert.equal(clientSuppliedOpencodeSession(undefined), undefined); -}); - -test("mergeClientToolsWithObserved: keeps client tools first and appends missing observed names with empty schemas [free-tier-observed-tools]", () => { - _resetToolObservationForTests(); - const body = { - ...CHAT_BODY(), - tools: [ - { type: "function", function: { name: "glob", parameters: { type: "object" } } }, - { type: "function", function: { name: "read", parameters: { type: "object" } } }, - ], - }; - const merged = mergeClientToolsWithObserved(body, "openai", "opencode", "big-pickle", undefined, [ - "read", - "edit", - ]); - const tools = (merged as Record).tools as Array<{ - function: { name: string; parameters: object }; - }>; - assert.deepEqual( - tools.map((t) => t.function.name), - ["glob", "read", "edit"] - ); - // Appended entries are list entries, not callable tools. - assert.deepEqual(tools[2].function.parameters, { type: "object", properties: {} }); -}); - -test("mergeClientToolsWithObserved: leaves the body untouched when nothing observed [free-tier-observed-tools]", () => { - _resetToolObservationForTests(); - const body = { - ...CHAT_BODY(), - tools: [{ type: "function", function: { name: "glob", parameters: { type: "object" } } }], - }; - assert.equal( - mergeClientToolsWithObserved(body, "openai", "opencode", "big-pickle", undefined, []), - body - ); -}); - -// ── Only a refusal that says something about the tools counts ────────────────── - -const REFUSAL_BODY = JSON.stringify({ - error: { - type: "FreeTierError", - message: - "Error from provider (Console): OpenCode's free tier can only be used from within OpenCode", - }, -}); - -function learnBorrowedNames(): void { - _resetToolObservationForTests(); - const learned = prepareFreeTierRequest( - { ...CHAT_BODY(), tools: [{ type: "function", function: { name: "glob" } }] }, - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free" - ); - noteFreeTierOutcome(learned.attempt, true); -} - -function borrowedAttempt() { - return prepareFreeTierRequest( - CHAT_BODY(), - "openai", - "zen", - "opencode", - "nemotron-3.5-lightning-free" - ).attempt; -} - -test("three 429 answers on a borrowed request keep the observed names", () => { - learnBorrowedNames(); - for (let i = 0; i < 3; i++) { - noteFreeTierOutcome(borrowedAttempt(), { - ok: false, - status: 429, - bodyText: "Too many requests", - }); - } - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), ["glob"]); -}); - -test("three 503 answers on a borrowed request keep the observed names", () => { - learnBorrowedNames(); - for (let i = 0; i < 3; i++) { - noteFreeTierOutcome(borrowedAttempt(), { - ok: false, - status: 503, - bodyText: "Service unavailable", - }); - } - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), ["glob"]); -}); - -test("three 403 answers carrying the refusal keep dropping the observed names", () => { - learnBorrowedNames(); - const refused = () => - noteFreeTierOutcome(borrowedAttempt(), { ok: false, status: 403, bodyText: REFUSAL_BODY }); - refused(); - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), ["glob"]); - refused(); - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), ["glob"]); - refused(); - assert.equal(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), null); -}); - -test("a 200 on a borrowed shape clears the streak without rewriting the entry", () => { - learnBorrowedNames(); - const refused = () => - noteFreeTierOutcome(borrowedAttempt(), { ok: false, status: 403, bodyText: REFUSAL_BODY }); - refused(); - refused(); - noteFreeTierOutcome(borrowedAttempt(), { ok: true, status: 200, bodyText: null }); - noteFreeTierOutcome(borrowedAttempt(), { ok: false, status: 403, bodyText: REFUSAL_BODY }); - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), ["glob"]); -}); - -test("refusals that say nothing about the tools never touch the observed names", () => { - learnBorrowedNames(); - const bodies = [ - JSON.stringify({ error: { type: "FreeTierError", message: "not available in your country" } }), - JSON.stringify({ - error: { type: "FreeTierError", message: "[user_blocked] egress refused" }, - }), - JSON.stringify({ error_code: 1010, error: { type: "FreeTierError" } }), - ]; - for (const bodyText of bodies) { - for (let i = 0; i < 3; i++) { - noteFreeTierOutcome(borrowedAttempt(), { ok: false, status: 403, bodyText }); - } - } - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), ["glob"]); -}); - -test("a deferred note without a verdict never touches the observed names", () => { - learnBorrowedNames(); - for (let i = 0; i < 3; i++) { - noteFreeTierOutcome(borrowedAttempt(), false); - } - assert.deepEqual(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), ["glob"]); -}); - -test("a deferred 403 verdict still counts against the borrowed names", () => { - learnBorrowedNames(); - const first = borrowedAttempt(); - assert.equal(first?.borrowed, true); - for (let i = 0; i < 3; i++) { - const attempt = borrowedAttempt(); - noteFreeTierOutcome({ ...(attempt as object), probe: false } as typeof attempt, { - ok: false, - status: 403, - bodyText: REFUSAL_BODY, - }); - } - assert.equal(getObservedToolNames("opencode", "nemotron-3.5-lightning-free"), null); -}); diff --git a/tests/unit/opencode-noauth-copy-freetier-14313.test.ts b/tests/unit/opencode-noauth-copy-freetier-14313.test.ts deleted file mode 100644 index 467858b34e1e..000000000000 --- a/tests/unit/opencode-noauth-copy-freetier-14313.test.ts +++ /dev/null @@ -1,38 +0,0 @@ -/** - * #14313: the shipped OpenCode Free catalog copy must disclose that the public - * free tier only answers requests that match the OpenCode client contract — - * otherwise the dashboard promises keyless access that upstream will refuse. - */ -import test from "node:test"; -import assert from "node:assert/strict"; -import fs from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); -const { NOAUTH_PROVIDERS } = await import("../../src/shared/constants/providers/noauth.ts"); - -test("opencode freeNote / authHint / notice mention the OpenCode-only free-tier gate", () => { - const opencode = NOAUTH_PROVIDERS.opencode as { - authHint: string; - freeNote: string; - notice: { text: string }; - }; - const haystack = - `${opencode.authHint}\n${opencode.freeNote}\n${opencode.notice.text}`.toLowerCase(); - assert.match( - haystack, - /free tier can only be used from within opencode|only.*within opencode|opencode client/, - "copy must state that the free tier only works from within OpenCode" - ); - assert.match(haystack, /rate limit|rate-limit/, "copy must keep the rate-limit caveat"); -}); - -test("FREE_TIERS.md documents the OpenCode free-tier client-contract restriction", () => { - const doc = fs.readFileSync(path.join(root, "docs/reference/FREE_TIERS.md"), "utf8"); - assert.match( - doc, - /free tier can only be used from within OpenCode|only.*within OpenCode|OpenCode client contract/i, - "FREE_TIERS.md must document #14313's refusal so operators are not surprised" - ); -}); diff --git a/tests/unit/opencode-premium-keyless-gate-8681.test.ts b/tests/unit/opencode-premium-keyless-gate-8681.test.ts deleted file mode 100644 index b1aaf4768a8d..000000000000 --- a/tests/unit/opencode-premium-keyless-gate-8681.test.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { after, before, describe, it } from "node:test"; -import assert from "node:assert/strict"; - -const { OpencodeExecutor } = await import("../../open-sse/executors/opencode.ts"); -const { PROVIDER_MODELS } = await import("../../open-sse/config/providerModels.ts"); - -function createInput(model, stream = true, credentials = null) { - return { - model, - stream, - credentials, - body: { - model, - stream, - messages: [{ role: "user", content: "hello" }], - }, - }; -} - -function createMockResponse() { - return new Response(JSON.stringify({ ok: true }), { - status: 200, - headers: { "Content-Type": "application/json" }, - }); -} - -describe("OpencodeExecutor — premium model keyless gate (#8681)", () => { - let originalFetch: typeof globalThis.fetch; - - before(() => { - originalFetch = globalThis.fetch; - globalThis.fetch = (async (_url: string, _options?: RequestInit) => { - return createMockResponse(); - }) as typeof globalThis.fetch; - }); - - after(() => { - globalThis.fetch = originalFetch; - }); - - describe("isPremiumModel", () => { - it("returns false for known free models on opencode-zen", () => { - // Free models from the opencode (noauth) registry - assert.equal(OpencodeExecutor.isPremiumModel("big-pickle", "opencode-zen"), false); - assert.equal(OpencodeExecutor.isPremiumModel("deepseek-v4-flash-free", "opencode-zen"), false); - }); - - it("returns false for models ending in -free on opencode-zen", () => { - assert.equal(OpencodeExecutor.isPremiumModel("mimo-v2.5-free", "opencode-zen"), false); - assert.equal(OpencodeExecutor.isPremiumModel("nemotron-3-ultra-free", "opencode-zen"), false); - assert.equal(OpencodeExecutor.isPremiumModel("north-mini-code-free", "opencode-zen"), false); - assert.equal(OpencodeExecutor.isPremiumModel("hy3-free", "opencode-zen"), false); - }); - - it("returns true for premium models on opencode-zen", () => { - assert.equal(OpencodeExecutor.isPremiumModel("gpt-5", "opencode-zen"), true); - assert.equal(OpencodeExecutor.isPremiumModel("gpt-5-nano", "opencode-zen"), true); - assert.equal(OpencodeExecutor.isPremiumModel("claude-sonnet-4-5", "opencode-zen"), true); - assert.equal(OpencodeExecutor.isPremiumModel("gemini-3-flash", "opencode-zen"), true); - assert.equal(OpencodeExecutor.isPremiumModel("kimi-k2.6", "opencode-zen"), true); - assert.equal(OpencodeExecutor.isPremiumModel("glm-5", "opencode-zen"), true); - }); - - it("returns true for ALL models on opencode-go (no free tier)", () => { - assert.equal(OpencodeExecutor.isPremiumModel("deepseek-v4-pro", "opencode-go"), true); - assert.equal(OpencodeExecutor.isPremiumModel("kimi-k2.7-code", "opencode-go"), true); - assert.equal(OpencodeExecutor.isPremiumModel("glm-5.2", "opencode-go"), true); - assert.equal(OpencodeExecutor.isPremiumModel("deepseek-v4-flash-free", "opencode-go"), true); - assert.equal(OpencodeExecutor.isPremiumModel("big-pickle", "opencode-go"), true); - assert.equal(OpencodeExecutor.isPremiumModel("mimo-v2.5-free", "opencode-go"), true); - }); - - it("returns false for free models on the opencode (noauth) provider", () => { - assert.equal(OpencodeExecutor.isPremiumModel("deepseek-v4-flash-free", "opencode"), false); - assert.equal(OpencodeExecutor.isPremiumModel("big-pickle", "opencode"), false); - assert.equal(OpencodeExecutor.isPremiumModel("hy3-free", "opencode"), false); - }); - - it("returns true for premium models on the opencode (noauth) provider", () => { - assert.equal(OpencodeExecutor.isPremiumModel("gpt-5", "opencode"), true); - assert.equal(OpencodeExecutor.isPremiumModel("claude-sonnet-4-5", "opencode"), true); - }); - - it("returns true for unknown models on any opencode provider", () => { - assert.equal(OpencodeExecutor.isPremiumModel("unknown-random-model", "opencode-zen"), true); - }); - }); - - describe("execute with keyless credentials", () => { - const zenExecutor = new OpencodeExecutor("opencode-zen"); - - it("returns 402 for premium model gpt-5 with keyless credentials", async () => { - const result = await zenExecutor.execute(createInput("gpt-5", true, null)); - const response = result instanceof Response ? result : result.response; - const body = await response.json() as { error: { message: string } }; - assert.equal(response.status, 402); - assert.ok( - body.error.message.includes("API key"), - `Expected message to mention "API key" — got: ${body.error.message}` - ); - assert.ok( - !body.error.message.includes("Missing API key"), - "Should NOT be the raw upstream 'Missing API key' message" - ); - }); - - it("returns 402 for premium model claude-sonnet-4-5 with keyless credentials", async () => { - const result = await zenExecutor.execute(createInput("claude-sonnet-4-5", true, null)); - const response = result instanceof Response ? result : result.response; - assert.equal(response.status, 402); - }); - - it("allows free model deepseek-v4-flash-free with keyless credentials", async () => { - // Should reach the upstream fetch (mock returns 200) - const result = await zenExecutor.execute(createInput("deepseek-v4-flash-free", true, null)); - const response = result instanceof Response ? result : result.response; - // Should NOT be 402 (the premium gate); should reach the mock fetch - assert.notEqual(response.status, 402); - }); - - it("allows free model big-pickle with keyless credentials", async () => { - const result = await zenExecutor.execute(createInput("big-pickle", true, null)); - const response = result instanceof Response ? result : result.response; - assert.notEqual(response.status, 402); - }); - }); - - describe("execute with valid key credentials", () => { - const zenExecutor = new OpencodeExecutor("opencode-zen"); - - it("allows premium model gpt-5 with a valid API key", async () => { - // Should reach the upstream fetch (mock returns 200) - const result = await zenExecutor.execute(createInput("gpt-5", true, { apiKey: "valid-key" })); - const response = result instanceof Response ? result : result.response; - assert.notEqual(response.status, 402); - }); - - it("allows premium model claude-sonnet-4-5 with a valid API key", async () => { - const result = await zenExecutor.execute( - createInput("claude-sonnet-4-5", true, { apiKey: "valid-key" }) - ); - const response = result instanceof Response ? result : result.response; - assert.notEqual(response.status, 402); - }); - }); - - describe("execute with keyless credentials on opencode-go", () => { - const goExecutor = new OpencodeExecutor("opencode-go"); - - it("returns 402 for ANY model with keyless credentials (opencode-go has no free tier)", async () => { - const result = await goExecutor.execute(createInput("deepseek-v4-pro", true, null)); - const response = result instanceof Response ? result : result.response; - assert.equal(response.status, 402); - }); - }); - - describe("execute with valid key on opencode-go", () => { - const goExecutor = new OpencodeExecutor("opencode-go"); - - it("allows deepseek-v4-pro with a valid API key", async () => { - const result = await goExecutor.execute( - createInput("deepseek-v4-pro", true, { apiKey: "valid-key" }) - ); - const response = result instanceof Response ? result : result.response; - assert.notEqual(response.status, 402); - }); - }); -}); diff --git a/tests/unit/opencode-quota-retry-own-tools.test.ts b/tests/unit/opencode-quota-retry-own-tools.test.ts deleted file mode 100644 index f45f32917856..000000000000 --- a/tests/unit/opencode-quota-retry-own-tools.test.ts +++ /dev/null @@ -1,184 +0,0 @@ -/** - * A 403 or 451 carrying `insufficient_quota` on a request that declares its - * own tools is retried once with the observed names appended; the retry - * answer is served when it passes, otherwise the original refusal stands. - */ -import { test, beforeEach, afterEach } from "node:test"; -import assert from "node:assert/strict"; -import { OpencodeExecutor } from "../../open-sse/executors/opencode.ts"; -import type { ProviderCredentials } from "../../open-sse/executors/base.ts"; -import { resetDbInstance } from "../../src/lib/db/core.ts"; -import { - classifyProviderError, - PROVIDER_ERROR_TYPES, -} from "../../open-sse/services/errorClassifier.ts"; -import { - _resetShapeMemoForTests, - _setShapeClockForTests, -} from "../../open-sse/executors/opencodeRequestShape.ts"; -import { - _resetToolObservationForTests, - getObservedToolNames, - recordAcceptedToolNames, -} from "../../open-sse/executors/opencodeToolObservation.ts"; - -const MODEL = "muse-spark-1.3-contributor-free"; -const QUOTA_BODY = JSON.stringify({ - error: { type: "insufficient_quota", message: "insufficient_quota" }, -}); -const ANSWER_OK = JSON.stringify({ ok: true }); - -type Body = Record; - -function toolNamesOf(body: Body): Array { - if (!Array.isArray(body.tools)) return []; - return (body.tools as Array).map((entry) => { - if (!entry || typeof entry !== "object" || Array.isArray(entry)) return null; - const rec = entry as { name?: unknown; function?: { name?: unknown } }; - const name = typeof rec.name === "string" ? rec.name : rec.function?.name; - return typeof name === "string" ? name : null; - }); -} - -const originalFetch = globalThis.fetch; -let bodies: Body[] = []; - -function quotaRefusal(status: number, body: string = QUOTA_BODY): Response { - return new Response(body, { - status, - headers: { "Content-Type": "application/json" }, - }); -} - -function answerOk(): Response { - return new Response(ANSWER_OK, { - status: 200, - headers: { "Content-Type": "application/json" }, - }); -} - -function installFirstRefusedThen(status: number, second: () => Response): void { - bodies = []; - globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { - bodies.push(JSON.parse(String(init?.body ?? "{}")) as Body); - if (bodies.length === 1) return quotaRefusal(status); - return second(); - }) as typeof globalThis.fetch; -} - -function installAlwaysRefused(status: number, body: string = QUOTA_BODY): void { - bodies = []; - globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { - bodies.push(JSON.parse(String(init?.body ?? "{}")) as Body); - return quotaRefusal(status, body); - }) as typeof globalThis.fetch; -} - -const directCredentials: ProviderCredentials = { - apiKey: "k", - accessToken: null, - connectionId: "c", -}; - -const loopCredentials: ProviderCredentials = { - apiKey: "k", - accessToken: null, - connectionId: "c", - providerSpecificData: { - fingerprints: ["loop-account-a", "loop-account-b"], - }, -}; - -function ownToolsBody(): Body { - return { - model: MODEL, - messages: [{ role: "user", content: "hi" }], - stream: false, - tools: [{ type: "function", function: { name: "read", parameters: { type: "object" } } }], - }; -} - -async function run(executor: OpencodeExecutor, body: Body, credentials: ProviderCredentials) { - const result = (await executor.execute({ - model: MODEL, - body, - stream: false, - signal: null, - credentials, - log: { debug() {}, info() {}, warn() {}, error() {} }, - })) as { response: Response }; - return result.response; -} - -beforeEach(() => { - _resetShapeMemoForTests(); - _resetToolObservationForTests(); - _setShapeClockForTests(() => Date.now()); - process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS = "bash"; - recordAcceptedToolNames("opencode-zen", MODEL, undefined, ["edit", "write"]); -}); - -afterEach(() => { - delete process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS; - globalThis.fetch = originalFetch; - _setShapeClockForTests(() => Date.now()); - _resetToolObservationForTests(); - resetDbInstance(); -}); - -for (const status of [403, 451]) { - for (const path of ["direct", "loop"] as const) { - test(`a ${status} carrying the quota token on own tools is retried once and served (${path} path)`, async () => { - installFirstRefusedThen(status, answerOk); - const executor = new OpencodeExecutor("opencode-zen"); - const response = await run( - executor, - ownToolsBody(), - path === "direct" ? directCredentials : loopCredentials - ); - assert.equal(response.status, 200); - assert.equal(bodies.length, 2); - assert.deepEqual(toolNamesOf(bodies[0]), ["read", "bash"]); - assert.ok(toolNamesOf(bodies[1]).includes("read")); - assert.ok(toolNamesOf(bodies[1]).includes("edit")); - await response.body?.cancel(); - }); - } -} - -test("when both attempts are refused the original refusal is served and the store is untouched", async () => { - installAlwaysRefused(403); - const executor = new OpencodeExecutor("opencode-zen"); - const response = await run(executor, ownToolsBody(), directCredentials); - assert.equal(response.status, 403); - assert.equal(bodies.length, 2); - assert.equal(await response.text(), QUOTA_BODY); - assert.equal( - classifyProviderError(403, QUOTA_BODY, "opencode-zen"), - PROVIDER_ERROR_TYPES.QUOTA_EXHAUSTED - ); - assert.deepEqual(getObservedToolNames("opencode-zen", MODEL), ["edit", "write"]); -}); - -test("a quota refusal carrying a user_blocked marker is not retried", async () => { - installAlwaysRefused( - 403, - JSON.stringify({ error: { message: "insufficient_quota [user_blocked] egress refused" } }) - ); - const executor = new OpencodeExecutor("opencode-zen"); - const response = await run(executor, ownToolsBody(), directCredentials); - assert.equal(response.status, 403); - assert.equal(bodies.length, 1); - await response.body?.cancel(); -}); - -test("no retry when there is nothing observed to add", async () => { - _resetToolObservationForTests(); - delete process.env.OPENCODE_FREE_TIER_PLACEHOLDER_TOOLS; - installAlwaysRefused(403); - const executor = new OpencodeExecutor("opencode-zen"); - const response = await run(executor, ownToolsBody(), directCredentials); - assert.equal(response.status, 403); - assert.equal(bodies.length, 1); - await response.body?.cancel(); -}); diff --git a/tests/unit/opencode-request-shape-retry.test.ts b/tests/unit/opencode-request-shape-retry.test.ts deleted file mode 100644 index f3ea285079dc..000000000000 --- a/tests/unit/opencode-request-shape-retry.test.ts +++ /dev/null @@ -1,707 +0,0 @@ -/** - * OpenCode Zen: which tool shape a request must carry depends on what it is. - * - * Measured on 2026-09-18 against the live gateway, on both the Responses and the Chat - * Completions surface. A request whose instructions say "Never use tools" (the official - * client's title agent) is accepted with NO tools and refused with any; every other request - * is accepted with at least the canonical tool names and refused without. The request - * contract used to fill an empty `tools` array unconditionally, which turned exactly the - * title requests into refusals. - * - * The executor therefore learns the accepted shape from the refusal: a refused request that - * received an injection is replayed once without it, and the shape that worked is - * remembered per prompt so the next identical request goes out in that shape at once. - * The fake upstream below applies the rule as measured. - */ -import { test, beforeEach, afterEach, before, after } from "node:test"; -import net from "node:net"; -import assert from "node:assert/strict"; -import { OpencodeExecutor } from "../../open-sse/executors/opencode.ts"; -import type { ProviderCredentials } from "../../open-sse/executors/base.ts"; -import { resolveProxyForRequest } from "../../open-sse/utils/proxyFetch.ts"; -import { resetDbInstance } from "../../src/lib/db/core.ts"; -import { - attemptFor, - noteFreeTierOutcome, - prepareFreeTierRequest, -} from "../../open-sse/executors/opencodeFreeTierContract.ts"; -import { - _resetShapeMemoForTests, - _setShapeClockForTests, - shapeKeyOf, -} from "../../open-sse/executors/opencodeRequestShape.ts"; -import { - _resetToolObservationForTests, - getObservedToolNames, -} from "../../open-sse/executors/opencodeToolObservation.ts"; - -const MODEL = "nemotron-3.5-lightning-free"; -const TITLE_PROMPT = - "You are a title generator. You output ONLY a thread title.\n- Never use tools\n- Keep it short"; -const REFUSAL_BODY = JSON.stringify({ - type: "error", - error: { - type: "FreeTierError", - message: - "Error from provider (Console): OpenCode's free tier can only be used from within OpenCode", - }, -}); -const SSE_OK = - 'data: {"id":"gen-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":null}]}\n\n' + - 'data: {"id":"gen-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n' + - "data: [DONE]\n\n"; - -type Body = Record; -type Verdict = number | "network"; -type Rule = (body: Body, call: number) => Verdict; - -function toolCount(body: Body): number { - return Array.isArray(body.tools) ? body.tools.length : 0; -} - -function promptOf(body: Body): string { - if (typeof body.instructions === "string") return body.instructions; - const messages = Array.isArray(body.messages) ? (body.messages as Array) : []; - const system = messages.find((m) => m.role === "system" || m.role === "developer"); - return typeof system?.content === "string" ? system.content : ""; -} - -/** The rule as measured: a "Never use tools" prompt wants no tools, anything else wants some. */ -const measuredRule: Rule = (body) => { - const wantsNone = promptOf(body).includes("Never use tools"); - const has = toolCount(body) > 0; - return wantsNone !== has ? 200 : 403; -}; - -/** The same gateway after it flips: every prompt now wants tools. */ -const invertedRule: Rule = (body) => (toolCount(body) > 0 ? 200 : 403); - -const originalFetch = globalThis.fetch; -let bodies: Body[] = []; -/** Which proxy port (or "direct") each upstream call went through. */ -let seen: string[] = []; -/** The responses handed back by the fake upstream, in call order. */ -let answers: Response[] = []; - -function installUpstream(rule: Rule): void { - bodies = []; - seen = []; - answers = []; - globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { - const url = - typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; - const via = resolveProxyForRequest(url); - seen.push(via.proxyUrl ? new URL(via.proxyUrl).port : "direct"); - const body = JSON.parse(String(init?.body ?? "{}")) as Body; - bodies.push(body); - const verdict = rule(body, bodies.length); - if (verdict === "network") throw new TypeError("fetch failed"); - const answer = (response: Response): Response => { - answers.push(response); - return response; - }; - if (verdict === 200) { - return answer( - new Response(SSE_OK, { - status: 200, - headers: { "Content-Type": "text/event-stream" }, - }) - ); - } - if (verdict === 403) { - return answer( - new Response(REFUSAL_BODY, { - status: 403, - headers: { "Content-Type": "application/json" }, - }) - ); - } - return answer( - new Response(JSON.stringify({ error: { message: "upstream said no" } }), { - status: verdict, - headers: { "Content-Type": "application/json" }, - }) - ); - }) as typeof globalThis.fetch; -} - -beforeEach(() => { - _resetShapeMemoForTests(); - _resetToolObservationForTests(); - _setShapeClockForTests(() => Date.now()); -}); - -afterEach(() => { - globalThis.fetch = originalFetch; - _setShapeClockForTests(() => Date.now()); -}); - -const titleBody = (prompt = TITLE_PROMPT, model = MODEL): Body => ({ - model, - messages: [ - { role: "system", content: prompt }, - { role: "user", content: "hello" }, - ], -}); - -type RunOptions = { - signal?: AbortSignal | null; - skipUpstreamRetry?: boolean; - provider?: string; - stream?: boolean; - executor?: OpencodeExecutor; - credentials?: ProviderCredentials; -}; - -async function run(body: Body, extra: RunOptions = {}): Promise { - const executor = extra.executor ?? new OpencodeExecutor(extra.provider ?? "opencode-zen"); - const result = (await executor.execute({ - model: String(body.model), - body, - stream: extra.stream ?? true, - signal: extra.signal ?? null, - skipUpstreamRetry: extra.skipUpstreamRetry, - credentials: extra.credentials ?? { apiKey: "k", accessToken: null, connectionId: "c" }, - log: { debug() {}, info() {}, warn() {}, error() {} }, - })) as { response: Response }; - return result.response; -} - -test("a refused title request is replayed once without the injected tools and then accepted", async () => { - installUpstream(measuredRule); - const response = await run(titleBody()); - assert.equal(response.status, 200); - assert.equal(bodies.length, 2, "one refusal, one replay"); - assert.ok(toolCount(bodies[0]) > 0, "the first attempt carried the injection"); - assert.equal(toolCount(bodies[1]), 0, "the replay carried no tools"); - assert.equal(bodies[1].stream, true, "the replay is still streamed"); -}); - -for (const [label, verdict] of [ - ["429", 429], - ["500", 500], - ["a network error", "network"], -] as Array<[string, Verdict]>) { - test(`${label} on the first attempt is not a shape refusal: no replay`, async () => { - installUpstream(() => verdict); - await run(titleBody(), { skipUpstreamRetry: true }).catch(() => undefined); - assert.ok(bodies.length >= 1); - assert.ok( - bodies.every((b) => toolCount(b) > 0), - "every attempt kept the injection: nothing was replayed bare" - ); - }); -} - -test("a refusal that does not name the request contract is not replayed", async () => { - globalThis.fetch = (async (_i: RequestInfo | URL, init?: RequestInit) => { - bodies.push(JSON.parse(String(init?.body ?? "{}")) as Body); - return new Response(JSON.stringify({ error: { message: "forbidden for another reason" } }), { - status: 403, - headers: { "Content-Type": "application/json" }, - }); - }) as typeof globalThis.fetch; - bodies = []; - const response = await run(titleBody()); - assert.equal(response.status, 403); - assert.equal(bodies.length, 1); -}); - -test("tools declared by the client are never removed, even for a title prompt", async () => { - installUpstream(measuredRule); - const body = titleBody(); - body.tools = [{ type: "function", function: { name: "read", parameters: { type: "object" } } }]; - const response = await run(body); - assert.equal( - response.status, - 403, - "the upstream refuses this shape and we do not second-guess it" - ); - assert.equal(bodies.length, 1, "no replay: the injection was not ours"); - // Since #14156 the contract appends the required placeholder names AFTER the client's - // own tools (it no longer sends a client tool list verbatim), but it never removes or - // reshapes what the client declared: the client's tool is still first and intact. - const sent = bodies[0].tools as Array>; - assert.ok(toolCount(bodies[0]) >= 1); - assert.deepEqual( - sent[0], - (body.tools as unknown[])[0], - "the client's own tool went out first, untouched" - ); -}); - -const shapesOf = (from: number): string[] => - bodies.slice(from).map((b) => (toolCount(b) > 0 ? "tools" : "bare")); - -test("the shape that worked is remembered: the next identical request goes out bare at once", async () => { - installUpstream(measuredRule); - assert.equal((await run(titleBody())).status, 200); - assert.deepEqual(shapesOf(0), ["tools", "bare"]); - assert.equal((await run(titleBody())).status, 200); - assert.deepEqual(shapesOf(2), ["bare"], "no refusal to pay for the second time"); -}); - -test("a remembered bare shape that the upstream stops accepting is replayed with tools and forgotten", async () => { - installUpstream(measuredRule); - await run(titleBody()); - installUpstream(invertedRule); - assert.equal((await run(titleBody())).status, 200); - assert.deepEqual(shapesOf(0), ["bare", "tools"], "bare refused, replayed with tools"); - assert.equal((await run(titleBody())).status, 200); - assert.deepEqual(shapesOf(2), ["tools"], "the memory was dropped: tools go out first again"); -}); - -test("an empty prompt is an ordinary class: it is remembered like any other", async () => { - installUpstream((body) => (toolCount(body) === 0 ? 200 : 403)); - const empty = (): Body => ({ model: MODEL, messages: [{ role: "user", content: "hello" }] }); - assert.equal((await run(empty())).status, 200); - assert.deepEqual(shapesOf(0), ["tools", "bare"]); - assert.equal((await run(empty())).status, 200); - assert.deepEqual(shapesOf(2), ["bare"]); -}); - -test("the Responses surface takes the same path: the prompt travels as `instructions`", async () => { - installUpstream(measuredRule); - const body = (): Body => ({ - model: "muse-spark-1.3-contributor-free", - input: [{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] }], - instructions: TITLE_PROMPT, - }); - assert.equal((await run(body())).status, 200); - assert.deepEqual(shapesOf(0), ["tools", "bare"]); - assert.equal((await run(body())).status, 200); - assert.deepEqual(shapesOf(2), ["bare"]); -}); - -test("a distinct prompt is a distinct class: the memory does not leak across prompts", async () => { - installUpstream(measuredRule); - await run(titleBody(TITLE_PROMPT)); - const from = bodies.length; - await run(titleBody(`${TITLE_PROMPT}\n- Another wording`)); - assert.deepEqual(shapesOf(from), ["tools", "bare"], "a new prompt starts from the default"); -}); - -test("the memory is bounded: the oldest class is forgotten after 64 others", async () => { - installUpstream(measuredRule); - const prompt = (i: number) => `${TITLE_PROMPT}\n- Variant ${i}`; - for (let i = 1; i <= 65; i++) await run(titleBody(prompt(i))); - let from = bodies.length; - await run(titleBody(prompt(65))); - assert.deepEqual(shapesOf(from), ["bare"], "the newest is still remembered"); - from = bodies.length; - await run(titleBody(prompt(1))); - assert.deepEqual(shapesOf(from), ["tools", "bare"], "the oldest was evicted"); -}); - -test("two identical requests in flight both succeed and leave one shared memory", async () => { - installUpstream(measuredRule); - const [a, b] = await Promise.all([run(titleBody()), run(titleBody())]); - assert.equal(a.status, 200); - assert.equal(b.status, 200); - const from = bodies.length; - await run(titleBody()); - assert.deepEqual(shapesOf(from), ["bare"]); -}); - -test("when both shapes are refused the refusal is returned and further replays pause for a minute", async () => { - let now = 1_000_000; - _setShapeClockForTests(() => now); - installUpstream(() => 403); - const first = await run(titleBody()); - assert.equal(first.status, 403); - assert.match(await first.text(), /FreeTierError/, "the upstream verdict is returned as it came"); - assert.equal(bodies.length, 2, "one injection, one bare replay"); - - now += 59_000; - let from = bodies.length; - await run(titleBody()); - assert.equal(bodies.length - from, 1, "inside the pause: no replay"); - - now += 2_000; - from = bodies.length; - await run(titleBody()); - assert.equal(bodies.length - from, 2, "after the pause: replay allowed again"); -}); - -test("a refusal that is rescued by the replay does not count against the learned tool names", async () => { - installUpstream(measuredRule); - const tools = ["read", "edit", "glob", "grep", "shell", "write"].map((name) => ({ - type: "function", - function: { name, parameters: { type: "object" } }, - })); - const main: Body = { - model: MODEL, - messages: [ - { role: "system", content: "You are a coding agent." }, - { role: "user", content: "go" }, - ], - tools, - }; - assert.equal((await run(main)).status, 200); - assert.ok(getObservedToolNames("opencode-zen", MODEL), "the accepted list was learned"); - - // Three different prompts: a repeated one would be sent bare from the second time on and - // never reach the refusal path this test is about. - for (let i = 1; i <= 3; i++) { - const from = bodies.length; - assert.equal((await run(titleBody(`${TITLE_PROMPT}\n- Variant ${i}`))).status, 200); - assert.deepEqual(shapesOf(from), ["tools", "bare"], `title ${i}: refused once, then rescued`); - } - assert.ok( - getObservedToolNames("opencode-zen", MODEL), - "three rescued refusals in a row did not make the store forget a list that works" - ); -}); - -test("with the contract switched off nothing is injected and nothing is replayed", async () => { - const previous = process.env.OPENCODE_FREE_TIER_REQUEST_CONTRACT; - process.env.OPENCODE_FREE_TIER_REQUEST_CONTRACT = "off"; - try { - installUpstream(measuredRule); - assert.equal((await run(titleBody())).status, 200, "the bare title is what the upstream wants"); - assert.equal(bodies.length, 1); - assert.equal(toolCount(bodies[0]), 0); - const from = bodies.length; - const plain = await run(titleBody("You are a coding agent.")); - assert.equal(plain.status, 403, "no injection: the refusal stands"); - assert.equal(bodies.length - from, 1, "and no replay"); - } finally { - if (previous === undefined) delete process.env.OPENCODE_FREE_TIER_REQUEST_CONTRACT; - else process.env.OPENCODE_FREE_TIER_REQUEST_CONTRACT = previous; - } -}); - -test("a paid model and the other surface are out of scope: one send, no injection, no replay", async () => { - installUpstream(() => 403); - const paid = await run(titleBody(TITLE_PROMPT, "gpt-5.6-luna")); - assert.equal(paid.status, 403); - assert.equal(bodies.length, 1); - assert.equal(toolCount(bodies[0]), 0); - - // Integration guard only: the surface rule itself is pinned by - // opencode-free-tier-request-contract.test.ts (removing it fails there, not here, because - // the go provider is also excluded as a keyed-only provider). - const from = bodies.length; - const go = await run(titleBody(TITLE_PROMPT, "ox-alpha-free"), { provider: "opencode-go" }); - assert.equal(go.status, 403); - assert.equal(bodies.length - from, 1); - assert.equal(toolCount(bodies[from]), 0); -}); - -// --- several accounts, each behind its own proxy ----------------------------- - -const FPS = ["a", "b", "c"].map((c) => c.repeat(32)); -const proxyServers: net.Server[] = []; -const proxyPorts: number[] = []; - -before(async () => { - for (let i = 0; i < FPS.length; i++) { - const server = net.createServer((socket) => socket.destroy()); - proxyServers.push(server); - await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve())); - proxyPorts.push((server.address() as net.AddressInfo).port); - } -}); - -after(() => { - proxyServers.forEach((server) => server.close()); - resetDbInstance(); -}); - -function multiAccountCredentials(): ProviderCredentials { - return { - apiKey: null, - accessToken: null, - connectionId: "noauth", - providerSpecificData: { - fingerprints: FPS, - accountProxies: FPS.map((fingerprint, i) => ({ - fingerprint, - proxy: { type: "http", host: "127.0.0.1", port: proxyPorts[i] }, - })), - }, - }; -} - -type Health = Array<{ cooldownUntil: number; consecutiveFails: number }>; -const healthOf = (executor: OpencodeExecutor): Health => - (executor as unknown as { accounts: Health }).accounts; - -/** Materialise the account list, then give every account a failure history to protect. */ -async function warmedAccounts(): Promise<{ - executor: OpencodeExecutor; - credentials: ProviderCredentials; -}> { - const executor = new OpencodeExecutor("opencode-zen"); - const credentials = multiAccountCredentials(); - installUpstream(() => 200); - const warm = await run( - { - model: MODEL, - messages: [{ role: "user", content: "hi" }], - tools: [{ type: "function", function: { name: "read", parameters: { type: "object" } } }], - }, - { executor, credentials } - ); - await warm.body?.cancel(); - for (const account of healthOf(executor)) account.consecutiveFails = 2; - return { executor, credentials }; -} - -test("several accounts: a refused title is replayed bare and no account is put on cooldown", async () => { - const { executor, credentials } = await warmedAccounts(); - installUpstream(measuredRule); - const response = await run(titleBody(), { executor, credentials }); - assert.equal(response.status, 200); - assert.deepEqual(shapesOf(0), ["tools", "bare"]); - assert.equal(seen.length, 2, "one refusal and one replay, not one send per account"); - for (const account of healthOf(executor)) { - assert.equal(account.cooldownUntil, 0, "a refused request does not cool an account down"); - } - assert.ok( - healthOf(executor).filter((a) => a.consecutiveFails === 2).length >= 2, - "at most the account that served the replay had its failure history reset" - ); -}); - -test("several accounts: when both shapes are refused the verdict is returned without touching account health", async () => { - const { executor, credentials } = await warmedAccounts(); - installUpstream(() => 403); - const response = await run(titleBody(), { executor, credentials }); - assert.equal(response.status, 403); - assert.equal(seen.length, 2, "two sends in total: no walk across the three accounts"); - for (const account of healthOf(executor)) { - assert.equal(account.consecutiveFails, 2, "a refusal is never counted as a success"); - assert.equal(account.cooldownUntil, 0); - } -}); - -// --- abort, JSON callers, prepare without an origin, no stray rejections ------------------- - -test("a caller that already gave up gets no replay", async () => { - const controller = new AbortController(); - installUpstream((_body, call) => { - if (call === 1) controller.abort(); - return 403; - }); - await run(titleBody(), { signal: controller.signal }).catch(() => undefined); - assert.equal(bodies.length, 1, "the abandoned request was not sent a second time"); -}); - -test("a JSON caller gets a JSON body from the replayed request", async () => { - installUpstream(measuredRule); - const response = await run(titleBody(), { stream: false }); - assert.equal(response.status, 200); - assert.ok( - bodies.every((b) => b.stream === true), - "both attempts were streamed upstream" - ); - const json = (await response.json()) as { choices?: Array<{ message?: { content?: string } }> }; - assert.equal(json.choices?.[0]?.message?.content, "ok"); -}); - -test("without an origin, preparing a request behaves exactly as before", () => { - const body = { model: MODEL, messages: [{ role: "user", content: "hi" }] }; - const { attempt, body: out } = prepareFreeTierRequest(body, null, "zen", "opencode", MODEL); - assert.ok(attempt); - assert.equal(attempt.probe, false, "no replay can happen without an origin to key it on"); - assert.equal(((out as Body).tools as unknown[]).length, 1); - noteFreeTierOutcome(attempt, false); -}); - -test("the first refusal is released before the replay is sent", async () => { - const stray: unknown[] = []; - const onStray = (reason: unknown) => stray.push(reason); - process.on("unhandledRejection", onStray); - try { - installUpstream(measuredRule); - await run(titleBody()); - await new Promise((resolve) => setImmediate(resolve)); - assert.equal(answers.length, 2); - assert.equal(answers[0].status, 403); - assert.equal(answers[0].bodyUsed, true, "its body was cancelled, not left hanging"); - assert.deepEqual(stray, [], "and cancelling it raised nothing"); - } finally { - process.off("unhandledRejection", onStray); - } -}); - -test("a body that is not an object is passed through: nothing to key a replay on, nothing thrown", () => { - const { attempt, body } = prepareFreeTierRequest( - "not an object" as never, - null, - "zen", - "opencode", - MODEL, - undefined, - "not an object" as never - ); - assert.ok(attempt); - assert.equal(attempt.probe, false, "no replay is possible without an object to key it on"); - assert.equal(body, "not an object"); -}); - -test("a system prompt that is not text still gets its own class", () => { - const withObject = { messages: [{ role: "system", content: { rules: ["a"] } }] }; - const otherObject = { messages: [{ role: "system", content: { rules: ["b"] } }] }; - const none = { messages: [{ role: "user", content: "hi" }] }; - const key = (b: unknown) => shapeKeyOf("opencode-zen", MODEL, b); - assert.notEqual(key(withObject), key(none), "not the same class as no prompt at all"); - assert.notEqual(key(withObject), key(otherObject), "and not the same as another such prompt"); -}); - -test("two requests in flight on one executor each keep their own outcome", async () => { - installUpstream(measuredRule); - const inner = globalThis.fetch; - let release!: () => void; - const gate = new Promise((resolve) => { - release = resolve; - }); - globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { - const sent = JSON.parse(String(init?.body ?? "{}")) as Body; - if (promptOf(sent).includes("coding agent")) await gate; - return inner(input, init); - }) as typeof globalThis.fetch; - - const executor = new OpencodeExecutor("opencode-zen"); - const tools = ["read", "edit", "glob", "grep", "shell", "write"].map((name) => ({ - type: "function", - function: { name, parameters: { type: "object" } }, - })); - const slow = run( - { - model: MODEL, - messages: [ - { role: "system", content: "You are a coding agent." }, - { role: "user", content: "go" }, - ], - tools, - }, - { executor } - ); - await new Promise((resolve) => setImmediate(resolve)); - assert.equal( - (await run(titleBody(), { executor })).status, - 200, - "the quick request finishes first" - ); - release(); - assert.equal((await slow).status, 200); - assert.ok( - getObservedToolNames("opencode-zen", MODEL), - "the slow request was accepted with its own tools: they were learned, not lost to the other request" - ); -}); - -test("the attempt of a finished request is released with it", async () => { - installUpstream(measuredRule); - const body = titleBody(); - assert.equal((await run(body)).status, 200); - assert.equal( - attemptFor(body), - null, - "a body reused later must not inherit this request's attempt" - ); -}); - -test("a system prompt with a circular structure does not break the request", () => { - const circular: Record = { rules: [] }; - circular.self = circular; - const body = { messages: [{ role: "system", content: circular }] }; - assert.doesNotThrow(() => shapeKeyOf("opencode-zen", MODEL, body)); -}); - -test("an empty successful answer is not a shape refusal: no replay", async () => { - bodies = []; - globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { - bodies.push(JSON.parse(String(init?.body ?? "{}")) as Body); - return new Response(null, { status: 200, headers: { "Content-Type": "text/event-stream" } }); - }) as typeof globalThis.fetch; - const response = await run(titleBody()); - assert.equal(response.status, 200); - assert.equal(bodies.length, 1); -}); - -test("a refusal whose body cannot be read is returned as it came, without a replay", async () => { - bodies = []; - globalThis.fetch = (async (_input: RequestInfo | URL, init?: RequestInit) => { - bodies.push(JSON.parse(String(init?.body ?? "{}")) as Body); - const refusal = new Response(REFUSAL_BODY, { status: 403 }); - refusal.clone = () => { - throw new Error("body already consumed"); - }; - return refusal; - }) as typeof globalThis.fetch; - const response = await run(titleBody()); - assert.equal(response.status, 403, "the verdict reaches the caller"); - assert.equal(bodies.length, 1, "and nothing was replayed on a body we could not read"); -}); - -test("when the replay itself fails, the error surfaces and the first refusal still counts against the borrowed names", async () => { - const tools = ["read", "edit", "glob", "grep", "shell", "write"].map((name) => ({ - type: "function", - function: { name, parameters: { type: "object" } }, - })); - installUpstream(measuredRule); - await run({ - model: MODEL, - messages: [ - { role: "system", content: "You are a coding agent." }, - { role: "user", content: "go" }, - ], - tools, - }); - assert.ok(getObservedToolNames("opencode-zen", MODEL), "a list was learned"); - - // The replay of every title fails on the network, so the only verdict on the borrowed names - // is the first refusal. Three different prompts, as three refusals in a row forget the list. - installUpstream((body) => - promptOf(body).includes("Never use tools") ? (toolCount(body) > 0 ? 403 : "network") : 200 - ); - for (let i = 1; i <= 3; i++) { - await assert.rejects( - run(titleBody(`${TITLE_PROMPT}\n- Variant ${i}`), { skipUpstreamRetry: true }) - ); - } - assert.equal( - getObservedToolNames("opencode-zen", MODEL), - null, - "three refusals in a row, none rescued: the borrowed list is forgotten" - ); -}); - -// The compaction request of the official client: no system prompt, no tools, and the whole -// instruction plus the serialized conversation in one user message (3 to 52 thousand characters -// were seen). By the measured rule it is a plain request, so it needs tools like any other. -const compactionBody = (size: number): Body => ({ - model: MODEL, - messages: [ - { - role: "user", - content: `Create a new anchored summary from the conversation history.\n\nOutput exactly the Markdown structure shown inside