diff --git a/ARCHITECTURE-MAP.md b/ARCHITECTURE-MAP.md index 4ecb88de4..3e276fd6f 100644 --- a/ARCHITECTURE-MAP.md +++ b/ARCHITECTURE-MAP.md @@ -33,19 +33,19 @@ This is a **living reference** — update it in the same session whenever a modu Total `src/` ≈ **16,310 lines** across ~109 files (excl. tests). Grouped by domain (folders) then root-level utilities. -| Domain | Folder / Files | LoC | Owns | Key contracts | -| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| **Provider** | `src/provider/` — `OpenCodeProvider.ts` (532), `chatPrep.ts` (332), `messages.ts` (446), `modelInfo.ts` (239), `historyTrim.ts` (200), `settings.ts` (260), `modelList.ts` (235), `visionProxy.ts` (345), `providerDialogs.ts` (117), `transportLog.ts` (109), `definitions.ts` (364), `tokens.ts` (106), `providerUtils.ts` (35) | ~3,017 | The `OpenCodeProvider` class implementing `LanguageModelChatProvider` (thin — delegates to siblings via deps objects), request preparation (`chatPrep`: message conversion, vision proxy, history trimming, budgets, thinking payload), model-info assembly (`modelInfo`), model-list fetch/cache (`modelList`), Manage/Test-Connection flows (`providerDialogs`), rolling transport diagnostics (`transportLog`) | `prepareChatRequest()` / `provideModelChatInformation()` / `convertMessage()` / `normalizeMessages()` / `trimOldMessagesToFitContext()` / `historyByteCapForBudget()` / `ModelListFetcher` | -| **Transports** | `src/transports/` — `engine.ts` (409), `extractors.ts` (556), `extract.ts` (225), `thinkTags.ts` (139), `streamParts.ts` (88), `sse.ts` (31), `chatCompletions.ts` (72), `responses.ts` (30), `anthropic.ts` (28), `google.ts` (31) | ~1,601 | One adapter per wire format (OpenAI chat-completions, OpenAI Responses, Anthropic Messages, Google generateContent) + the shared streaming engine, SSE parser, response extractors | `streamOpenCodeResponse()` (engine), `OpenAiResponseExtractor` / `AnthropicResponseExtractor` | -| **Core (registry/routing)** | `src/core/` — `routing.ts` (546), `registry.ts` (176), `transport.ts` (84) | ~653 | Data-driven model registry (`MODEL_REGISTRY`), transport resolution (`resolveModelRouting`), Responses/Google SSE normalization, shared `StreamRequestOptions` contract | **Pure** — no `vscode` import, no side effects | -| **Models (metadata)** | `src/models/` — `metadata.ts` (523), `modelTables.ts` (141), `metadataFetcher.ts` (102), `modelLimits.ts` (52), `modelCapabilities.ts` (41), `modelNames.ts` (29), `pricing.ts` (88) | ~976 | models.dev live metadata + bundled fallback snapshot (static data tables in `modelTables.ts`), limit/capability resolution, pricing | Live fetch may fail → bundled snapshot MUST exist | -| **Usage** | `src/usage/` — `tracker.ts` (585, thin class shell), `trackerTypes.ts` (96), `trackerWindows.ts` (140), `trackerSummary.ts` (238), `dashboard.ts` (19 barrel) + `dashboard/` (`webview.ts`, `webviewData.ts`, `webviewHtml.ts`, `state.ts`, `statusBar.ts`, `targetEditor.ts`, `tooltip.ts` ≈ 1,405), `history.ts` (378), `usage.ts` (146), `goUsageSync.ts` (128), `formatting.ts` (129), `usageProfile.ts` (74), `pricing.ts` (62) | ~3,571 | Go usage tracker (types/windows/summary split out of the old god file), per-profile tracking, CLI SQLite history reader, server-usage sync, status bar + usage webview + quick-pick (webview split into state/status/webview modules) | Server percentages/resets authoritative for Session/Weekly/Monthly; response `opencode.allowance` is the dynamic local amount; device-local for Today/Yesterday | -| **Thinking** | `src/thinking/` — `provider.ts` (84), `base.ts` (75), `resolve.ts` (119), `beam.ts` (55), `deepseek.ts` (53), `glm.ts` (93), `kimi.ts` (81), `minimax.ts` (54), `muse.ts` (71), `mimo.ts` (78), `openai.ts` (57), `qwen.ts` (103), `fallback.ts` (93), `schema.ts` (124), `payload.ts` (26), `types.ts` (61) | ~1224 | Per-family thinking strategy classes + config resolution (per-model config wins over workspace — but schema-default echoes are stripped first, `stripSchemaDefaultEcho` in `resolve.ts`, issue #226). Beam is always-reasoning and uses only `low`/`medium`/`high`/`xhigh`/`max`, normalizing stale `off` values to `low` (issue #118). `FallbackThinking` is the generic data-driven path: models.dev `reasoning` / `reasoning_options` decide whether an unknown model gets a picker and a plain `reasoning_effort`, with no per-model hardcoding (issue #252) | **Pure** — no `vscode` import; family from registry | -| **Request builders** | `src/request/` — `anthropic.ts` (233), `google.ts` (176), `types.ts` (117), `schema.ts` (163), `openai.ts` (181), `headers.ts` (110), `builders.ts` (17), `shared.ts` (41) | ~883 | Per-endpoint request-body builders + shared header builders + depth-capped tool-schema sanitizer (`MAX_TOOL_SCHEMA_DEPTH`) (`x-opencode-session` / `x-opencode-request`) | `builders.ts` is the public barrel | -| **Commands** | `src/commands/` — `agentsWindow.ts` (130), `diagnostics.ts` (41), `providers.ts` (72), `thinkingPicker.ts` (31) | ~274 | Command handlers: diagnostics, agents-window BYOK bridge, provider enable/disable (state-aware toggle, base-vendor resolved — issue #228), thinking picker | Thin — delegates to provider/usage modules | -| **Autocomplete** | `src/autocomplete/` — `index.ts` (157), `engine.ts` (143), `provider.ts` (127), `context.ts` (89), `usage.ts` (88), `throttle.ts` (79), `prompt.ts` (60), `types.ts` (32) | ~775 | Inline code suggestions (opt-in) — FIM emulation over chat-completions, debounce/throttle, usage counters | Separate subsystem; not wired into Go cost tracker yet | -| **Extension entry** | `src/extension.ts` | 415 | Thin `activate()`/`deactivate()` — wiring only (command registration, provider registration, status bar init) | Target <300 lines; keep wiring-only | -| **Root utilities** | `src/config.ts` (278), `contextWindowHook.ts` (485), `contextWindowHookBridge.ts` (122), `errors.ts` (345), `retry.ts` (463), `utils.ts` (186), `responsesRequest.ts` (271), `toolCallAccumulator.ts` (187), `imageNormalizer.ts` (118), `visionProxyCache.ts` (79), `runtimeDiagnostics.ts` (57), `chatParts.ts` (55), `reasoningHistory.ts` (43), `tokenEstimate.ts` (39), `toolLoopGuard.ts` (46), `providerTypes.ts` (23), `openCodeAuth.ts` (20), `providerEnablement.ts` (18), `apiKeyResolution.ts` (8), `thinking.ts` (30, legacy barrel) | ~2,474 | Cross-cutting utilities (plus the two proposed-API `.d.ts` module augmentations ≈ 231 LoC — `chatProvider` v6 + `languageModelThinkingPart` v1). `toolLoopGuard.ts` is a pure Beam-only circuit breaker for consecutive tool-call turns. | `config.ts` must stay **dependency-free** | +| Domain | Folder / Files | LoC | Owns | Key contracts | +| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **Provider** | `src/provider/` — `OpenCodeProvider.ts` (532), `chatPrep.ts` (332), `messages.ts` (446), `modelInfo.ts` (239), `historyTrim.ts` (200), `settings.ts` (260), `modelList.ts` (235), `visionProxy.ts` (345), `providerDialogs.ts` (117), `transportLog.ts` (109), `definitions.ts` (364), `tokens.ts` (106), `providerUtils.ts` (35) | ~3,017 | The `OpenCodeProvider` class implementing `LanguageModelChatProvider` (thin — delegates to siblings via deps objects), request preparation (`chatPrep`: message conversion, vision proxy, history trimming, budgets, thinking payload), model-info assembly (`modelInfo`), model-list fetch/cache (`modelList`), Manage/Test-Connection flows (`providerDialogs`), rolling transport diagnostics (`transportLog`) | `prepareChatRequest()` / `provideModelChatInformation()` / `convertMessage()` / `normalizeMessages()` / `trimOldMessagesToFitContext()` / `historyByteCapForBudget()` / `ModelListFetcher` | +| **Transports** | `src/transports/` — `engine.ts` (409), `extractors.ts` (556), `extract.ts` (225), `thinkTags.ts` (139), `streamParts.ts` (88), `sse.ts` (31), `chatCompletions.ts` (72), `responses.ts` (30), `anthropic.ts` (28), `google.ts` (31) | ~1,601 | One adapter per wire format (OpenAI chat-completions, OpenAI Responses, Anthropic Messages, Google generateContent) + the shared streaming engine, SSE parser, response extractors | `streamOpenCodeResponse()` (engine), `OpenAiResponseExtractor` / `AnthropicResponseExtractor` | +| **Core (registry/routing)** | `src/core/` — `routing.ts` (546), `registry.ts` (176), `transport.ts` (84) | ~653 | Data-driven model registry (`MODEL_REGISTRY`), transport resolution (`resolveModelRouting`), Responses/Google SSE normalization, shared `StreamRequestOptions` contract | **Pure** — no `vscode` import, no side effects | +| **Models (metadata)** | `src/models/` — `metadata.ts` (523), `modelTables.ts` (141), `metadataFetcher.ts` (102), `modelLimits.ts` (52), `modelCapabilities.ts` (41), `modelNames.ts` (29), `pricing.ts` (88) | ~976 | models.dev live metadata + bundled fallback snapshot (static data tables in `modelTables.ts`), limit/capability resolution, pricing | Live fetch may fail → bundled snapshot MUST exist | +| **Usage** | `src/usage/` — `tracker.ts` (585, thin class shell), `trackerTypes.ts` (96), `trackerWindows.ts` (140), `trackerSummary.ts` (238), `dashboard.ts` (19 barrel) + `dashboard/` (`webview.ts`, `webviewData.ts`, `webviewHtml.ts`, `state.ts`, `statusBar.ts`, `targetEditor.ts`, `tooltip.ts` ≈ 1,405), `history.ts` (378), `usage.ts` (146), `goUsageSync.ts` (128), `formatting.ts` (129), `usageProfile.ts` (74), `pricing.ts` (62) | ~3,571 | Go usage tracker (types/windows/summary split out of the old god file), per-profile tracking, CLI SQLite history reader, server-usage sync, status bar + usage webview + quick-pick (webview split into state/status/webview modules) | Server percentages/resets authoritative for Session/Weekly/Monthly; response `opencode.allowance` is the dynamic local amount; device-local for Today/Yesterday | +| **Thinking** | `src/thinking/` — `provider.ts` (84), `base.ts` (75), `resolve.ts` (119), `beam.ts` (55), `deepseek.ts` (53), `glm.ts` (93), `kimi.ts` (81), `minimax.ts` (54), `muse.ts` (71), `mimo.ts` (78), `openai.ts` (57), `qwen.ts` (103), `fallback.ts` (93), `schema.ts` (124), `payload.ts` (26), `types.ts` (61) | ~1224 | Per-family thinking strategy classes + config resolution (per-model config wins over workspace — but schema-default echoes are stripped first, `stripSchemaDefaultEcho` in `resolve.ts`, issue #226). Beam is always-reasoning and uses only `low`/`medium`/`high`/`xhigh`/`max`, normalizing stale `off` values to `low` (issue #118). `FallbackThinking` is the generic data-driven path: models.dev `reasoning` / `reasoning_options` decide whether an unknown model gets a picker and a plain `reasoning_effort`, with no per-model hardcoding (issue #252) | **Pure** — no `vscode` import; family from registry | +| **Request builders** | `src/request/` — `anthropic.ts` (233), `google.ts` (176), `types.ts` (117), `schema.ts` (163), `openai.ts` (181), `headers.ts` (110), `builders.ts` (17), `shared.ts` (41) | ~883 | Per-endpoint request-body builders + shared header builders + depth-capped tool-schema sanitizer (`MAX_TOOL_SCHEMA_DEPTH`) (`x-opencode-session` / `x-opencode-request`) | `builders.ts` is the public barrel | +| **Commands** | `src/commands/` — `agentsWindow.ts` (130), `consoleSignIn.ts` (60), `diagnostics.ts` (41), `providers.ts` (72), `thinkingPicker.ts` (31) | ~274 | Command handlers: diagnostics, agents-window BYOK bridge, provider enable/disable (state-aware toggle, base-vendor resolved — issue #228), thinking picker | Thin — delegates to provider/usage modules | +| **Autocomplete** | `src/autocomplete/` — `index.ts` (157), `engine.ts` (143), `provider.ts` (127), `context.ts` (89), `usage.ts` (88), `throttle.ts` (79), `prompt.ts` (60), `types.ts` (32) | ~775 | Inline code suggestions (opt-in) — FIM emulation over chat-completions, debounce/throttle, usage counters | Separate subsystem; not wired into Go cost tracker yet | +| **Extension entry** | `src/extension.ts` | 415 | Thin `activate()`/`deactivate()` — wiring only (command registration, provider registration, status bar init) | Target <300 lines; keep wiring-only | +| **Root utilities** | `src/config.ts` (278), `contextWindowHook.ts` (485), `contextWindowHookBridge.ts` (122), `errors.ts` (345), `retry.ts` (463), `utils.ts` (186), `responsesRequest.ts` (271), `toolCallAccumulator.ts` (187), `imageNormalizer.ts` (118), `visionProxyCache.ts` (79), `runtimeDiagnostics.ts` (57), `chatParts.ts` (55), `reasoningHistory.ts` (43), `tokenEstimate.ts` (39), `toolLoopGuard.ts` (46), `providerTypes.ts` (23), `openCodeAuth.ts` (20), `openCodeConsoleCredential.ts` (70), `providerEnablement.ts` (18), `apiKeyResolution.ts` (8), `thinking.ts` (30, legacy barrel) | ~2,544 | Cross-cutting utilities (plus the two proposed-API `.d.ts` module augmentations ≈ 231 LoC — `chatProvider` v6 + `languageModelThinkingPart` v1). `toolLoopGuard.ts` is a pure circuit breaker: Beam tool-call turns and Muse repeated-answer turns. `openCodeConsoleCredential.ts` reads the CLI's Go key read-only for the opt-in sign-in command. | `config.ts` must stay **dependency-free** | --- @@ -348,26 +348,28 @@ Not a plain API hook — it **monkey-patches Copilot Chat internals** to inject Reuse these before writing new logic (all under `src/` root unless noted): -| Lib | Purpose | Import from | -| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------- | -| `config.ts` | **All** tunables: URLs, timeouts, limits, storage keys, setting keys, defaults. Dependency-free. | anywhere | -| `utils.ts` | `isRecord`, `firstString`, `getErrorMessage`, `formatUsd`, `formatTokenCount`, `formatCount`, `formatRelativeTime`, `escapeHtml`, `sleep*` | anywhere | -| `errors.ts` | `OpenCodeRequestError` taxonomy + `buildOpenCodeRequestError` (rate-limit / Router.Unavailable hints) | all request paths | -| `retry.ts` | `analyzeHttp400ForRetry`, `isTransientServerError`, transient-5xx constants | engine + fetch | -| `chatParts.ts` | `createUsageDataParts`, reasoning marker parts | engine / extractors | -| `tokenEstimate.ts` | `estimateTokenCount`, `estimatePromptTokenCount` | provider | -| `imageNormalizer.ts` | normalize image data-URLs to provider-safe dims/encoding | messages + vision | -| `openCodeAuth.ts` | `buildOpenCodeGatewayAuthHeaders` (Bearer / x-api-key / x-goog-api-key) | provider | -| `apiKeyResolution.ts` | `resolveResponseApiKey` cold-start fallback | provider | -| `providerEnablement.ts` | `providerEnabledSetting()` — reads root config (never section-scoped) | extension + commands | -| `reasoningHistory.ts` | `thinkingTextFromValue`, `shouldEchoThinkingHistory` (family-gated echo), `isMiniMaxModel` + `inlineThinkingForHistory` (MiniMax replays thinking inline as `` in `content` — see `docs/features/19-20261020-minimax-interleaved-thinking-replay.md`) | messages | -| `toolCallAccumulator.ts` | `ToolCallAccumulator` (flush only on `tool_calls` finish reason; `argumentsDone` delta REPLACES pending arguments — done-event repair, #244) | extractors | -| `contextWindowHook*.ts` | context-window usage injection — **monkey-patches** Copilot's internal `$handleProgressChunk` + `Set.prototype`; bridge = lazy-load seam; silent no-op if capture fails | engine/provider | -| `visionProxyCache.ts` | SHA-256 image-hash → vision-proxy description cache (FIFO, cap 200) | provider | -| `runtimeDiagnostics.ts` | `runtimeDiagnosticsLines()` — version/host/platform/integrity lines for the Diagnostics command | provider | -| `request/headers.ts` | `buildOpenCodeRequestHeaders` (sticky session/request id) | provider | -| `request/builders.ts` | public barrel for body builders per endpoint | provider | -| `request/shared.ts` | `messagesHaveImages`, `withDeferredToolImageMessages` (tool-image defer, #233) — pure, no `vscode` import | provider | +| Lib | Purpose | Import from | +| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------- | +| `config.ts` | **All** tunables: URLs, timeouts, limits, storage keys, setting keys, defaults. Dependency-free. | anywhere | +| `utils.ts` | `isRecord`, `firstString`, `getErrorMessage`, `formatUsd`, `formatTokenCount`, `formatCount`, `formatRelativeTime`, `escapeHtml`, `sleep*` | anywhere | +| `errors.ts` | `OpenCodeRequestError` taxonomy + `buildOpenCodeRequestError` (rate-limit / Router.Unavailable hints) | all request paths | +| `retry.ts` | `analyzeHttp400ForRetry`, `isTransientServerError`, transient-5xx constants | engine + fetch | +| `chatParts.ts` | `createUsageDataParts`, reasoning marker parts | engine / extractors | +| `tokenEstimate.ts` | `estimateTokenCount`, `estimatePromptTokenCount`, `estimateMessageTokenCount` — base64 image data is stripped and charged a bounded per-image estimate (#287) | provider | +| `imageNormalizer.ts` | normalize image data-URLs to provider-safe dims/encoding | messages + vision | +| `openCodeAuth.ts` | `buildOpenCodeGatewayAuthHeaders` (Bearer / x-api-key / x-goog-api-key) | provider | +| `apiKeyResolution.ts` | `resolveResponseApiKey` cold-start fallback | provider | +| `providerEnablement.ts` | `providerEnabledSetting()` — reads root config (never section-scoped) | extension + commands | +| `reasoningHistory.ts` | `thinkingTextFromValue`, `shouldEchoThinkingHistory` (family-gated echo), `isMiniMaxModel` + `inlineThinkingForHistory` (MiniMax replays thinking inline as `` in `content` — see `docs/features/19-20261020-minimax-interleaved-thinking-replay.md`) | messages | +| `toolCallAccumulator.ts` | `ToolCallAccumulator` (flush only on `tool_calls` finish reason; `argumentsDone` delta REPLACES pending arguments — done-event repair, #244) | extractors | +| `contextWindowHook*.ts` | context-window usage injection — **monkey-patches** Copilot's internal `$handleProgressChunk` + `Set.prototype`; bridge = lazy-load seam; silent no-op if capture fails | engine/provider | +| `toolLoopGuard.ts` | pure loop breakers: `detectBeamToolLoop()` (Beam tool calls) + `detectMuseRepetitionLoop()` (Muse repeated answers, #284) — both feed the tool-free recovery turn | provider | +| `openCodeConsoleCredential.ts` | read-only CLI credential reader + `parseCredentialRows()` for the Console sign-in command (#286); never logs the key | commands | +| `visionProxyCache.ts` | SHA-256 image-hash → vision-proxy description cache (FIFO, cap 200) | provider | +| `runtimeDiagnostics.ts` | `runtimeDiagnosticsLines()` — version/host/platform/integrity lines for the Diagnostics command | provider | +| `request/headers.ts` | `buildOpenCodeRequestHeaders` (sticky session/request id) | provider | +| `request/builders.ts` | public barrel for body builders per endpoint | provider | +| `request/shared.ts` | `messagesHaveImages`, `withDeferredToolImageMessages` (#233), `stripImageData` / `countImageDataParts` shared by byte and token accounting (#287) — pure, no `vscode` import | provider | --- @@ -377,6 +379,7 @@ Reuse these before writing new logic (all under `src/` root unless noted): - **API keys only** via BYOK `options.configuration.apiKey` → SecretStorage mirror (`opencodego.apiKey` / `opencodezen.apiKey`). Never logged, never hardcoded, never in error messages. - Keys only ever sent as an auth header (`Authorization` / `x-api-key` / `x-goog-api-key`). +- Console sign-in reads the CLI credential store only after explicit user consent, stores the key in SecretStorage, and never logs its value (#286). - `reasoningContentByToolCallId` capped at 500 (per-call reasoning echo). ### Resilience @@ -476,7 +479,7 @@ On push/PR to `main`/`develop`, Node 20: `npm ci` → `compile` → `lint` (with - **Version:** `0.8.1` · **Engine:** `vscode ^1.125.0` · **Entry:** `./out/extension.js` - **Activation:** `onStartupFinished`, `onLanguageModelChatProvider:opencodego`, `onLanguageModelChatProvider:opencodezen` -- **Contribution points:** `commands` (16), `configuration` (35+ keys), `languageModelChatProviders` (4 vendors: `opencodego`, `opencodezen`, `opencodego-agent`, `opencodezen-agent`) +- **Contribution points:** `commands` (17), `configuration` (35+ keys), `languageModelChatProviders` (4 vendors: `opencodego`, `opencodezen`, `opencodego-agent`, `opencodezen-agent`) - **4 providers:** Go (paid) + Zen (free default) + agent-host variants mirroring each base vendor - **Endpoints:** `https://opencode.ai/zen/{go/,}v1/{models,chat/completions,messages,responses}` + `https://opencode.ai/inference/go/v1/models` (Go Gemini route, see `googleModelsUrl`) + `https://opencode.ai/zen/go/v1/usage` (server meters) + `https://models.dev/api.json` (metadata) diff --git a/CHANGELOG.md b/CHANGELOG.md index 72af36795..652b3fe6d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,24 @@ All notable changes to the **OpenCode Go BYOK Provider** extension are documented here. +## [Unreleased] + +### Added + +- **`[Auth]` A new "OpenCode Go: Sign In with OpenCode Console" command imports the API key the OpenCode CLI already saved, with explicit consent, or opens the Console key page and stores the pasted key in SecretStorage (issue #286).** OpenCode's `/connect` still requires an API key for Go, so no undocumented OAuth or session-cookie scraping is used. Documented in `docs/issues/127-20261125-issue286-console-sign-in.md`. + +### Fixed + +- **`[Google]` Gemini tool results use the valid `functionResponse` shape again (issue #283).** A July regression moved `content` to the top level; strict validators such as `gemini-4-argon` rejected every request after the first tool call. The text now lives in the required `response` object while multimodal `parts` stay at `functionResponse` level. Documented in `docs/issues/122-20261125-issue283-gemini-function-response-regression.md`. + +- **`[Models]` GPT Luna no longer sends a rejected `temperature` parameter (issue #285).** models.dev reports `temperature: true` for `gpt-6-luna` and `gpt-5.6-luna`, but the Go gateway rejects it. The gateway restriction now overrides live metadata, and the HTTP 400 retry classifier recognizes the `Unsupported parameter` wording. Documented in `docs/issues/123-20261125-issue285-gpt-luna-temperature.md`. + +- **`[History]` Viewing figures no longer evicts most of the conversation (issue #287).** The token estimator charged base64 image data as prose, so a few screenshots inflated the prompt estimate past the 70% budget and the trimmer dropped hundreds of text messages. Images are now stripped before token measurement and charged a bounded per-image estimate, matching the byte-cap rule from #173. Documented in `docs/issues/124-20261125-issue287-image-token-accounting.md`. + +- **`[Muse]` Repeated-answer loops in Muse Spark agent runs are stopped (issue #284).** Three consecutive identical assistant answers now trigger a tool-free final-answer recovery turn, using the same recovery path as the Beam tool-loop guard. Documented in `docs/issues/125-20261125-issue284-muse-repetition-guard.md`. + +- **`[VS Code]` The Agent picker stays visible and the Go privacy gate is explained (issue #282).** The extension pins VS Code's experimental `agentsPickerInAttachContextMenu` setting off (and restores it on cleanup), and the training opt-in 400 now names the Console privacy setting instead of showing a bare failure. Documented in `docs/issues/126-20261125-issue282-agent-mode-picker-and-privacy.md`. + ## [0.8.1] — 2026-11-10 ### Added diff --git a/docs/issues/122-20261125-issue283-gemini-function-response-regression.md b/docs/issues/122-20261125-issue283-gemini-function-response-regression.md new file mode 100644 index 000000000..7a61d156f --- /dev/null +++ b/docs/issues/122-20261125-issue283-gemini-function-response-regression.md @@ -0,0 +1,63 @@ +**Status:** ✅ Solved +**Related issue:** [#283](https://github.com/ltmoerdani/opencode-copilot-chat/issues/283) +**Introduced by:** `ec92a44` (2026-07-20, PR #79 / issue #34) + +# Gemini tool results used an invalid `functionResponse` shape + +**Topic:** provider / request / google / tool-calling +**Updated:** 2026-11-25 +**Tags:** #provider #google #tool-calling #regression + +--- + +## Problem + +`gemini-4-argon` on OpenCode Go returned HTTP 400 for every request after the +first tool call: + +```text +Unknown name "content" at 'contents[2].parts[0].function_response': Cannot find field. +``` + +The same error repeated for every tool result in the conversation, so the model +could never continue an agentic session. + +## Root cause + +`src/request/google.ts` built tool results as +`functionResponse: { name, content }`. The official Gemini +`generateContent` reference defines `FunctionResponse` as `name` plus a +**required `response` object**; there is no top-level `content` field. Older +Gemini models tolerated the unknown field, but the strict validator on +`gemini-4-argon` rejects it. + +Git history confirms a regression. Before `ec92a44` the builder emitted the +valid shape: + +```diff +- functionResponse: { name, response: { name, content } } ++ functionResponse: googleFunctionResponseContent(message.content, name) +``` + +The helper introduced by that commit moved `content` to the top level while +adding multimodal `parts`. `b8f6b45` later moved the helper into +`src/request/google.ts` without changing the shape. + +## Fix + +`googleFunctionResponseContent()` now returns: + +- `{ name, response: { content: text } }` for text-only tool results; +- `{ name, response: { content: text }, parts: [...] }` when the tool result + carries an image — `parts` stays at `functionResponse` level, as documented; +- `{ name, response: { content: JSON.stringify("") } }` for null content. + +No top-level `content` is emitted in any branch. The RULES comment above the +helper now states the wire contract explicitly. + +## Verification + +- `src/test/google-function-response.test.ts` — three cases: text-only shape, + multimodal `parts` with a valid `response`, and null content. Each asserts + that `content` is absent at `functionResponse` level. +- `npm run lint` (compile + unit tests + all strict checks) passes. diff --git a/docs/issues/123-20261125-issue285-gpt-luna-temperature.md b/docs/issues/123-20261125-issue285-gpt-luna-temperature.md new file mode 100644 index 000000000..059006bf0 --- /dev/null +++ b/docs/issues/123-20261125-issue285-gpt-luna-temperature.md @@ -0,0 +1,54 @@ +**Status:** ✅ Solved +**Related issue:** [#285](https://github.com/ltmoerdani/opencode-copilot-chat/issues/285) + +# GPT Luna rejects `temperature` despite models.dev claiming support + +**Topic:** models / metadata / request / provider +**Updated:** 2026-11-25 +**Tags:** #models #metadata #temperature #provider #go + +--- + +## Problem + +Selecting `gpt-6-luna` or `gpt-5.6-luna` on OpenCode Go (extension 0.8.1, +VS Code 1.146) failed immediately with: + +```text +OpenCode Go API request failed (HTTP 400) for gpt-6-luna: +Unsupported parameter: 'temperature' is not supported with this model. +``` + +## Root cause + +The request builders include `temperature` unless +`metadata.temperature === false` (`src/request/openai.ts:39`, +`src/request/google.ts:42`, `src/request/anthropic.ts:48`). The default is +`0.2` (`src/provider/settings.ts:136`). + +`resolveModelMetadata()` trusted live models.dev data first. The `opencode-go` +provider entry for both Luna models reports `temperature: true`, so the +parameter was always sent. `MODELS_WITHOUT_TEMPERATURE` only contained the +Kimi models, and the HTTP 400 retry classifier only recognised +`invalid temperature...` — not the gateway's `Unsupported parameter: ...` +wording, so there was no self-heal either. + +This is a data mismatch, not a regression in the request builders: the +temperature guard has existed since PR #21 (0.2.7). + +## Fix + +- `src/models/modelTables.ts` — add `gpt-6-luna` and `gpt-5.6-luna` to + `MODELS_WITHOUT_TEMPERATURE`. +- `src/models/metadata.ts` — make that set a **gateway-level override**: it now + wins over live and cached models.dev values, not just the offline fallback. +- `src/retry.ts` — add a recoverable-400 pattern for + `Unsupported parameter: 'temperature'`, which strips the field and retries. + +## Verification + +- `src/test/metadata.test.ts` — fallback metadata for both Luna models reports + `temperature: false`, and a live `temperature: true` record is overridden. +- `src/test/retry.test.ts` — the gateway wording produces a patch that removes + `temperature` while preserving the rest of the body. +- `npm run lint` (compile + unit tests + all strict checks) passes. diff --git a/docs/issues/124-20261125-issue287-image-token-accounting.md b/docs/issues/124-20261125-issue287-image-token-accounting.md new file mode 100644 index 000000000..13180b6d9 --- /dev/null +++ b/docs/issues/124-20261125-issue287-image-token-accounting.md @@ -0,0 +1,67 @@ +**Status:** ✅ Solved +**Related issue:** [#287](https://github.com/ltmoerdani/opencode-copilot-chat/issues/287) +**Related docs:** `75-20260821-issue173-vision-byte-cap.md`, `20-20261105-history-trim-context-notice.md` + +# Base64 images inflated the token budget and evicted conversation history + +**Topic:** provider / history-trim / token-estimate / vision +**Updated:** 2026-11-25 +**Tags:** #provider #history-trim #vision #token-estimate #bug + +--- + +## Problem + +In a long agentic visualization session, viewing a few figures caused the +trimmer to drop 291 messages at once (455 → 168). The model then re-read files +and redid work it had already validated. The chat transcript still showed the +full history, so the reset looked like a model failure. + +The reporter's log showed the extension estimating 538,239 tokens for a +request the provider counted at 91,033, while the byte check passed comfortably. +Their direct gateway probes also showed that DeepSeek/GLM/Qwen accepted prompts +well beyond the extension's 70% budget, so the trim was protecting against a +limit that did not bind. + +## Root cause + +`estimatePromptTokenCount()` measured `JSON.stringify(prompt)` with +`ceil(chars / 4) × 1.1`. Image parts are base64 data URLs, so a 1 MB figure was +charged roughly 393,000 "tokens" instead of the few hundred the provider +actually counts. + +Issue #173 had already fixed the **byte** side by stripping image data in +`stripImageData()` before measuring `MAX_REQUEST_PAYLOAD_BYTES`. The **token** +side kept counting base64, so the two ceilings disagreed: bytes passed, tokens +failed, and the trimmer dropped the oldest text middle in one block. The +`[Context notice]` added by #274 then told the model to re-read files, which +re-added history and made the next figure trigger the same cut again. + +A second inconsistency existed on the VS Code-facing side: +`estimateDataPartTokenCount()` reports `IMAGE_TOKEN_ESTIMATE = 1024` per image, +so Copilot Chat never saw the weight the extension was charging internally. + +## Fix + +- `src/request/shared.ts` — move `stripImageData()` out of `historyTrim.ts` and + export it together with `countImageDataParts()`, so byte and token accounting + use the same image detection. +- `src/tokenEstimate.ts` — `estimatePromptTokenCount()` now strips base64 data + URLs before the character heuristic and charges a bounded + `IMAGE_TOKEN_ESTIMATE` (1024) per stripped image. Hosted URLs remain counted + as text. `estimateMessageTokenCount()` applies the same rule to one message, + used for per-unit trim measurements. +- `src/provider/historyTrim.ts` — imports the shared helper; its contract now + states that images are excluded from both ceilings. + +Because `finalTokens` also feeds `calculateModelLimits()`, this removes the +arithmetic path where an inflated prompt estimate collapsed `max_tokens` to 1 +(the shape reported in #83 / `docs/issues/37-...`). + +## Verification + +- `src/test/tokenEstimate.test.ts` — a 400 KB base64 image yields an estimate + under 10,000 tokens instead of ~110,000. +- `src/test/messages.test.ts` — a vision-only payload no longer removes any + text history, and `finalTokens` stays near the real prompt size. +- `npm run lint` (compile + unit tests + all strict checks) passes. diff --git a/docs/issues/125-20261125-issue284-muse-repetition-guard.md b/docs/issues/125-20261125-issue284-muse-repetition-guard.md new file mode 100644 index 000000000..6b799532d --- /dev/null +++ b/docs/issues/125-20261125-issue284-muse-repetition-guard.md @@ -0,0 +1,58 @@ +**Status:** ✅ Solved +**Related issue:** [#284](https://github.com/ltmoerdani/opencode-copilot-chat/issues/284) +**Related docs:** `91-20260903-issue207-big-pickle-repetition-loop.md`, `36-20260723-mimo-thinking-infinite-loop.md` + +# Muse Spark repeated the same answer across agent turns + +**Topic:** provider / tool-calling / thinking / muse +**Updated:** 2026-11-25 +**Tags:** #provider #muse #tool-calling #repetition + +--- + +## Problem + +In Agent mode with `muse-spark-1.3-contributor`, the same Chinese sentence was +emitted hundreds of times, interleaved with tool calls (`Revert forced +Preinclud...`, `Remove port shim he...`, `Read Bootloader.ewp`, ...). The run +never converged. + +## Root cause + +This is model-level degenerate repetition, not a transport retry or a stream +duplication bug: each turn was a fresh response with the same text. + +The extension had no guard for repeated **visible content**: + +- `src/thinking/muse.ts` emits only `reasoning.effort`; unlike `big-pickle` + (#207) and MiMo (#36), Muse has no `repetition_penalty`. +- `src/transports/extractors.ts` suppresses repeated **reasoning** fragments + only; visible text is unaffected. +- `detectBeamToolLoop()` was gated to `beam-*` models. + +## Fix + +`src/toolLoopGuard.ts` gains `detectMuseRepetitionLoop()`: + +- Muse-only (`/^muse-/i`); +- looks at assistant turns after the last user message, including turns with + tool calls in between; +- normalizes visible text and compares a bounded signature (200 chars, minimum + 40 chars) across the last three turns; +- returns a warning when the same signature repeats three times consecutively. + +`src/provider/chatPrep.ts` combines the Beam and Muse warnings into the existing +`toolLoopWarning` path. That path already appends a recovery instruction and +drops `tools` from the request for that turn (`OpenCodeProvider.ts:339`), so the +model is forced to produce a tool-free final answer instead of continuing the +loop. The log tag is now the generic `[loop-guard]`. + +The guard is deliberately conservative: short answers and varying text never +fire, and non-Muse models are untouched. + +## Verification + +- `src/test/toolLoopGuard.test.ts` — three consecutive identical Muse answers + with tool calls between them trigger the guard; two repeats, varying answers, + short answers, and non-Muse models do not. +- `npm run lint` (compile + unit tests + all strict checks) passes. diff --git a/docs/issues/126-20261125-issue282-agent-mode-picker-and-privacy.md b/docs/issues/126-20261125-issue282-agent-mode-picker-and-privacy.md new file mode 100644 index 000000000..5b3d041e8 --- /dev/null +++ b/docs/issues/126-20261125-issue282-agent-mode-picker-and-privacy.md @@ -0,0 +1,65 @@ +**Status:** ✅ Solved +**Related issue:** [#282](https://github.com/ltmoerdani/opencode-copilot-chat/issues/282) +**Upstream:** [microsoft/vscode#346223](https://github.com/microsoft/vscode/issues/346223) (closed, by design) + +# Agent mode: hidden picker and a misleading 400 error + +**Topic:** vscode / agents-window / errors / provider +**Updated:** 2026-11-25 +**Tags:** #vscode #agents-window #errors #provider + +--- + +## Problem + +The reporter had three separate symptoms in one issue: + +1. Switching to Agent mode made the "Set agent" dropdown disappear. +2. No `Agent.md` file/folder existed in + `%AppData%\Code\User\globalStorage\github.copilot-chat`. +3. Sending a prompt failed with HTTP 400 for `iceman-contributor-free`: + _"This Go model trains on request data. Turn on 'Allow paid endpoints that + train on request data'..."_ + +## Analysis + +- The hidden picker is a VS Code 1.145 change: the experimental setting + `sessions.chat.experimental.agentsPickerInAttachContextMenu` moves the picker + into the `+` menu. Upstream closed #346223 as by design; the workaround is to + pin the setting to `false`. The setting and its `experiment: { mode: "auto" }` + registration are present in the local VS Code bundle, confirming why some + users get it without opting in. +- Custom agents are a VS Code/Copilot feature (`.github/agents/*.agent.md` or + the Agent Customizations editor). This extension never creates them; there is + no `Agent.md` reference anywhere in `src/`. +- The 400 is a Go workspace privacy gate, not an Agent-mode failure. The log + was from extension 0.7.11 while the report said 0.8.0. The gateway message + already contains a Console URL, but Copilot Chat renders only the short + reason, so users saw "Sorry, your request failed" with no next step. + +## Fix + +- `src/config.ts` — new setting key and globalState marker for the picker + experiment. +- `src/commands/agentsWindow.ts` — `ensureAgentsWindowSupport()` now pins + `sessions.chat.experimental.agentsPickerInAttachContextMenu` to `false` + alongside the existing `extensions.supportAgentsWindow` and + `chat.agentHost.byokModels.enabled` settings. `revertAgentsWindowSupport()` + restores it (only when the extension set it, unless `force` is used). A + window reload is still required, and the existing notification covers it. +- `src/errors.ts` — `describeTrainingOptInRestriction()` converts the Go + training opt-in rejection into an actionable message naming the exact + Console privacy setting. It is included in both the chat-visible `message` + and the toast `userMessage`; the raw gateway URL stays in the Output channel. + +## Verification + +- `src/test/errors.test.ts` — the new hint matches the gateway wording, does + not fire on unrelated errors, and reaches both error surfaces. +- `npm run lint` (compile + unit tests + all strict checks) passes. + +## User guidance + +Custom agents are created through **Chat: Open Customizations → Agents → New +Agent** or by adding `.github/agents/.agent.md` to the workspace. The +extension does not generate those files. diff --git a/docs/issues/127-20261125-issue286-console-sign-in.md b/docs/issues/127-20261125-issue286-console-sign-in.md new file mode 100644 index 000000000..74578430f --- /dev/null +++ b/docs/issues/127-20261125-issue286-console-sign-in.md @@ -0,0 +1,55 @@ +**Status:** ✅ Solved +**Related issue:** [#286](https://github.com/ltmoerdani/opencode-copilot-chat/issues/286) +**Related memory:** `opencode-auth-research.md` + +# Sign in with OpenCode Console without manually copying a key + +**Topic:** auth / byok / provider / vscode +**Updated:** 2026-11-25 +**Tags:** #auth #byok #provider #vscode + +--- + +## Problem + +The request was to sign in with OpenCode Console the way `/connect` works in +the OpenCode CLI, so users would not have to enter an API key manually. + +## Research + +Official OpenCode docs (`/console/go`, `/console/api`, `/cli/providers`) show +that `/connect` for **OpenCode Go still asks for an API key**. OAuth in +`/connect` applies to other providers (ChatGPT/Codex, GitHub Copilot, Azure). +The Console API issues personal or service keys (`oc_sk_...`); there is no +documented third-party OAuth flow for Go. + +The OpenCode CLI does save that key locally. On this machine the SQLite store +`~/.local/share/opencode/opencode.db` has a `credential` table with an +`opencode-go` row whose `value` is the API key. The extension already reads the +same database read-only for usage history (`src/usage/history.ts`), so the +credential can be imported with the user's explicit consent instead of being +scraped silently. + +## Fix + +- `src/openCodeConsoleCredential.ts` — node-only helper that reads the + `opencode-go` credential from the CLI database using `node:sqlite`, falling + back to the `sqlite3` binary. `parseCredentialRows()` accepts both row + shapes. The key is returned to the caller and never logged; read failures + degrade to `undefined`. +- `src/commands/consoleSignIn.ts` — new command + **OpenCode Go: Sign In with OpenCode Console**: + - if a CLI key exists, ask "Import?" with **Import / Open Console / Cancel**; + - otherwise open the Console personal-API-keys page and prompt for the key; + - store the key in VS Code SecretStorage under `secretKeyFor(GO_VENDOR)` and + refresh the model list. +- `src/extension.ts` / `package.json` — command registration and title. + +No Console session cookie or OAuth token is handled, and no undocumented RPC +endpoint is used. The user always confirms before a key is copied. + +## Verification + +- `src/test/openCodeConsoleCredential.test.ts` — both SQLite row shapes, empty + values, and the Console URL. +- `npm run lint` (compile + unit tests + all strict checks) passes. diff --git a/package.json b/package.json index 82f7a064b..4380e40d0 100644 --- a/package.json +++ b/package.json @@ -65,6 +65,10 @@ "command": "opencodego.manage", "title": "OpenCode Go: Manage Provider" }, + { + "command": "opencodego.signInWithConsole", + "title": "OpenCode Go: Sign In with OpenCode Console" + }, { "command": "opencodego.toggleProvider", "title": "OpenCode Go: Toggle Provider Registration in Language Models" diff --git a/src/commands/agentsWindow.ts b/src/commands/agentsWindow.ts index 5b4649821..5660cdaeb 100644 --- a/src/commands/agentsWindow.ts +++ b/src/commands/agentsWindow.ts @@ -1,6 +1,8 @@ import * as vscode from "vscode"; import { AGENTS_BYOK_BRIDGE_STATE_KEY, + AGENTS_PICKER_IN_ATTACH_CONTEXT_SETTING, + AGENTS_PICKER_STATE_KEY, AGENT_HOST_BYOK_ENABLED_SETTING, AGENT_HOST_BYOK_MINOR_VERSION, CONFIG_SECTION, @@ -42,6 +44,10 @@ function isModernAgentHostVscode(): boolean { * 2. `chat.agentHost.byokModels.enabled` (VS Code 1.129+) — the BYOK * language-model bridge that mirrors extension BYOK models into * agent-host sessions. Off by default and experimental. + * 3. `sessions.chat.experimental.agentsPickerInAttachContextMenu` — when an + * experiment turns this on, VS Code hides the Agent picker in default + * Agent mode (microsoft/vscode#346223, issue #282). We pin it off so the + * picker stays visible. * * CONTRACT: * - Only writes the settings while the user keeps `opencodego.agentsWindow` @@ -78,6 +84,13 @@ export async function ensureAgentsWindowSupport(context: vscode.ExtensionContext } } + const sessionsCfg = vscode.workspace.getConfiguration("sessions.chat.experimental"); + if (sessionsCfg.get(AGENTS_PICKER_IN_ATTACH_CONTEXT_SETTING, false)) { + await sessionsCfg.update(AGENTS_PICKER_IN_ATTACH_CONTEXT_SETTING, false, vscode.ConfigurationTarget.Global); + await context.globalState.update(AGENTS_PICKER_STATE_KEY, true); + changed = true; + } + if (changed) { const reload = await vscode.window.showInformationMessage( "OpenCode: enabled VS Code's Agents window support so OpenCode Go/Zen models can run in the Agents window. Reload the window for it to take effect.", @@ -126,6 +139,13 @@ export async function revertAgentsWindowSupport(context: vscode.ExtensionContext .update(AGENT_HOST_BYOK_ENABLED_SETTING, false, vscode.ConfigurationTarget.Global); await context.globalState.update(AGENTS_BYOK_BRIDGE_STATE_KEY, undefined); } + + if (force || context.globalState.get(AGENTS_PICKER_STATE_KEY)) { + await vscode.workspace + .getConfiguration("sessions.chat.experimental") + .update(AGENTS_PICKER_IN_ATTACH_CONTEXT_SETTING, undefined, vscode.ConfigurationTarget.Global); + await context.globalState.update(AGENTS_PICKER_STATE_KEY, undefined); + } } /** Warm the model picker metadata for every enabled vendor (incl. agent variants). */ diff --git a/src/commands/consoleSignIn.ts b/src/commands/consoleSignIn.ts new file mode 100644 index 000000000..5fa06619a --- /dev/null +++ b/src/commands/consoleSignIn.ts @@ -0,0 +1,62 @@ +/** + * "Sign in with OpenCode Console" command (#286). + * + * OpenCode's official Console flow still issues an API key — there is no + * third-party OAuth for Go. This command removes the manual steps: it imports + * the key the OpenCode CLI already saved (with explicit user consent), or + * opens the Console key page and stores the pasted key in SecretStorage. + */ +import * as vscode from "vscode"; +import { secretKeyFor } from "../config"; +import { CONSOLE_KEYS_URL, readCliGoApiKey } from "../openCodeConsoleCredential"; +import { GO_VENDOR } from "../providerTypes"; + +async function saveKey(context: vscode.ExtensionContext, key: string): Promise { + await context.secrets.store(secretKeyFor(GO_VENDOR), key); + await vscode.commands.executeCommand("opencodego.refreshModels"); + await vscode.window.showInformationMessage("OpenCode Go key saved. The model list is refreshing."); +} + +export async function signInWithConsole(context: vscode.ExtensionContext): Promise { + const cliKey = readCliGoApiKey(); + if (cliKey) { + const choice = await vscode.window.showInformationMessage( + "The OpenCode CLI already has an OpenCode Go API key. Import it into VS Code?", + "Import", + "Open Console", + "Cancel", + ); + if (choice === "Import") { + await saveKey(context, cliKey); + return; + } + if (choice !== "Open Console") { + return; + } + } else { + const choice = await vscode.window.showInformationMessage( + "No OpenCode Go key found in the OpenCode CLI. Create a personal API key in the Console, then paste it here.", + "Open Console", + "Cancel", + ); + if (choice !== "Open Console") { + return; + } + } + + await vscode.env.openExternal(vscode.Uri.parse(CONSOLE_KEYS_URL)); + const pasted = await vscode.window.showInputBox({ + password: true, + ignoreFocusOut: true, + prompt: "OpenCode Go API key (oc_sk_...)", + }); + if (pasted === undefined) { + return; + } + const key = pasted.trim(); + if (!key) { + await vscode.window.showErrorMessage("No API key entered. Nothing was saved."); + return; + } + await saveKey(context, key); +} diff --git a/src/config.ts b/src/config.ts index b2e670493..5d2a92773 100644 --- a/src/config.ts +++ b/src/config.ts @@ -405,6 +405,9 @@ export const SUPPORT_AGENTS_WINDOW_SETTING = "supportAgentsWindow"; export const AGENT_HOST_BYOK_MINOR_VERSION = 129; export const AGENTS_BYOK_BRIDGE_STATE_KEY = "opencode.agentsByokBridge.v1"; export const SUPPORT_AGENTS_WINDOW_STATE_KEY = "opencode.supportAgentsWindow.v1"; +/** VS Code experiment that hides the Agent picker in default Agent mode (#282). */ +export const AGENTS_PICKER_IN_ATTACH_CONTEXT_SETTING = "agentsPickerInAttachContextMenu"; +export const AGENTS_PICKER_STATE_KEY = "opencode.agentsPickerInAttachContextMenu.v1"; // ─── Vision proxy (issue #74) ──────────────────────────────────────────────── diff --git a/src/errors.ts b/src/errors.ts index 44cc73d4a..6507c2433 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -61,7 +61,11 @@ export function buildOpenCodeRequestError( // upstream body is still preserved in the provider output channel // (`[http-error-body]` in transports/engine.ts), so no diagnostic is lost. const hint = - describeFreeTierRestriction(apiMessage) ?? describeRouterUnavailable(apiError) ?? describeEndpointUnavailable(apiMessage) ?? apiMessage; + describeFreeTierRestriction(apiMessage) ?? + describeTrainingOptInRestriction(apiMessage) ?? + describeRouterUnavailable(apiError) ?? + describeEndpointUnavailable(apiMessage) ?? + apiMessage; const userMessage = `${providerDisplayName} API request failed (HTTP ${String(response.status)})${modelId ? ` for ${modelId}` : ""}: ${hint}${capacityHint}`; const requestMessage = `${providerDisplayName} API request failed (${String(response.status)})${modelHint}${sizeHint}${capacityHint}: ${hint}`; return new OpenCodeRequestError(requestMessage, userMessage); @@ -106,6 +110,22 @@ export function describeFreeTierRestriction(apiMessage: string): string | undefi ); } +/** + * Explain the Go privacy gate for contributor/training models (issue #282). + * The gateway already includes a Console URL; surface the exact setting name + * in the user-facing message so the failure is actionable in Copilot Chat. + */ +export function describeTrainingOptInRestriction(apiMessage: string): string | undefined { + if (!/trains on request data|allow paid endpoints that train on request data/i.test(apiMessage)) { + return undefined; + } + return ( + "This Go model requires the workspace privacy setting 'Allow paid endpoints that train on request data'. " + + "Enable it in OpenCode Console under Settings > Privacy, then retry. " + + "The exact workspace link is in the OpenCode Output channel." + ); +} + /** * Replace the raw gateway JSON detail with an actionable hint when the error * is the transient `Router.Unavailable` condition (no healthy backend for diff --git a/src/extension.ts b/src/extension.ts index f715f0188..ea82056ba 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,6 +1,7 @@ import * as vscode from "vscode"; import { registerInlineCompletions } from "./autocomplete"; import { ensureAgentsWindowSupport, revertAgentsWindowSupport, warmModelPickerMetadata } from "./commands/agentsWindow"; +import { signInWithConsole } from "./commands/consoleSignIn"; import { showModelPickerDiagnostics } from "./commands/diagnostics"; import { showThinkingEffortPicker } from "./commands/thinkingPicker"; import { configureUtilityModels, toggleProviderEnabled } from "./commands/providers"; @@ -172,6 +173,7 @@ export function activate(context: vscode.ExtensionContext) { ...(goProviderEnabled ? [vscode.lm.registerLanguageModelChatProvider(GO_VENDOR, goProvider)] : []), ...(zenProviderEnabled ? [vscode.lm.registerLanguageModelChatProvider(ZEN_VENDOR, zenProvider)] : []), vscode.commands.registerCommand("opencodego.manage", () => goProvider.manage()), + vscode.commands.registerCommand("opencodego.signInWithConsole", () => signInWithConsole(context)), vscode.commands.registerCommand("opencodego.diagnostics", () => goProvider.showDiagnostics()), vscode.commands.registerCommand("opencodego.refreshModels", () => goProvider.refreshModels()), vscode.commands.registerCommand("opencodego.toggleProvider", () => toggleProviderEnabled(GO_VENDOR, "OpenCode Go")), @@ -190,7 +192,7 @@ export function activate(context: vscode.ExtensionContext) { // markers, so it also cleans up machines in that state. await revertAgentsWindowSupport(context, { force: true }); void vscode.window.showInformationMessage( - "OpenCode: reverted the Agents window core settings (extensions.supportAgentsWindow + chat.agentHost.byokModels.enabled). Reload the window for it to take effect.", + "OpenCode: reverted the Agents window core settings (extensions.supportAgentsWindow + chat.agentHost.byokModels.enabled + agentsPickerInAttachContextMenu). Reload the window for it to take effect.", ); }), vscode.commands.registerCommand("opencodego.showUsageDetails", () => { diff --git a/src/models/metadata.ts b/src/models/metadata.ts index 410b3b1d4..479e7f213 100644 --- a/src/models/metadata.ts +++ b/src/models/metadata.ts @@ -261,10 +261,13 @@ export function resolveModelMetadata( source: liveMetadata ? "live" : cachedMetadata ? "models.dev" : fallbackMetadata ? "fallback" : "default", cost: liveMetadata?.cost ?? cachedMetadata?.cost ?? fallbackMetadata?.cost, reasoningOptions: liveMetadata?.reasoningOptions ?? cachedMetadata?.reasoningOptions, - // The bundled fallback propagates `temperature: false` (models whose API - // rejects the parameter) so the request body omits it even when the live - // models.dev fetch is unavailable. - temperature: liveMetadata?.temperature ?? cachedMetadata?.temperature ?? fallbackMetadata?.temperature, + // Gateway-specific restrictions win over models.dev: some Go models reject + // `temperature` even though models.dev reports `temperature: true` (#285). + // The bundled fallback also propagates `temperature: false` so the request + // body omits it when the live fetch is unavailable. + temperature: MODELS_WITHOUT_TEMPERATURE.has(modelId) + ? false + : (liveMetadata?.temperature ?? cachedMetadata?.temperature ?? fallbackMetadata?.temperature), }; } diff --git a/src/models/modelTables.ts b/src/models/modelTables.ts index 88da4b94b..882e3ca25 100644 --- a/src/models/modelTables.ts +++ b/src/models/modelTables.ts @@ -39,6 +39,7 @@ export const MODEL_LIMITS_BY_PROVIDER: Record SqliteDatabase; + }; + if (typeof DatabaseSync === "function") { + const db = new DatabaseSync(CLI_DB_PATH, { readOnly: true }); + try { + const key = parseCredentialRows(db.prepare(CREDENTIAL_SQL).get()); + if (key) { + return key; + } + } finally { + db.close(); + } + } + } catch { + // No built-in SQLite on this host — fall through to the binary. + } + + try { + const output = execFileSync("sqlite3", ["-readonly", "-json", CLI_DB_PATH, CREDENTIAL_SQL], { + encoding: "utf8", + timeout: 5000, + stdio: ["ignore", "pipe", "ignore"], + }); + return parseCredentialRows(JSON.parse(output) as unknown); + } catch { + return undefined; + } +} diff --git a/src/provider/chatPrep.ts b/src/provider/chatPrep.ts index b2572669e..332350a22 100644 --- a/src/provider/chatPrep.ts +++ b/src/provider/chatPrep.ts @@ -39,7 +39,7 @@ import { estimatePromptTokenCount } from "../tokenEstimate"; import { proxyVision } from "./visionProxy"; import { estimateCost } from "../usage/pricing"; import { createCacheMonitor, resolveCacheRateThreshold, type CacheRateMonitor } from "../usage/cacheMonitor"; -import { detectBeamToolLoop } from "../toolLoopGuard"; +import { detectBeamToolLoop, detectMuseRepetitionLoop } from "../toolLoopGuard"; import { activeProfileFingerprint, ensureProfileForApiKey, @@ -321,9 +321,9 @@ export async function prepareChatRequest( // expected rather than as a regression (issue #232). const historyTrimmed = historyTrim.removed > 0; - const toolLoopWarning = detectBeamToolLoop(rawModelId, apiMessages); + const toolLoopWarning = detectBeamToolLoop(rawModelId, apiMessages) ?? detectMuseRepetitionLoop(rawModelId, apiMessages); if (toolLoopWarning) { - deps.log(`[tool-loop-guard] model=${rawModelId} ${toolLoopWarning}`); + deps.log(`[loop-guard] model=${rawModelId} ${toolLoopWarning}`); apiMessages.push({ role: "user", content: diff --git a/src/provider/historyTrim.ts b/src/provider/historyTrim.ts index e4e9c7ed6..584f6c865 100644 --- a/src/provider/historyTrim.ts +++ b/src/provider/historyTrim.ts @@ -7,8 +7,9 @@ import { HISTORY_TRIM_HEADROOM_RATIO, MAX_REQUEST_PAYLOAD_BYTES, } from "../config"; -import type { ApiMessage, OpenAiContentPart } from "../request/types"; -import { estimatePromptTokenCount, estimateTokenCount } from "../tokenEstimate"; +import { stripImageData } from "../request/shared"; +import type { ApiMessage } from "../request/types"; +import { estimateMessageTokenCount, estimatePromptTokenCount, estimateTokenCount } from "../tokenEstimate"; /** * Result of trimming old conversation messages to fit the request budget. @@ -45,9 +46,10 @@ export interface HistoryTrimResult { * - Runs in O(n): the full history is estimated once, then each dropped unit's * size is subtracted incrementally (no per-candidate re-stringification of * the whole array), so it stays fast even for very long histories. - * - Base64 image data is EXCLUDED from the byte ceiling (issue #173): image - * weight is already bounded by the image-history trimmer, and counting it - * made vision payloads trigger futile text-history drops. + * - Base64 image data is EXCLUDED from the byte ceiling (issue #173) and + * charged only a bounded per-image token estimate (issue #287): image + * weight is already bounded by the image-history trimmer, and counting its + * base64 characters made vision payloads trigger futile text-history drops. * - Context notice (issue #274): when units are dropped, a single user-role * `[Context notice]` message is inserted at the cut boundary so the model * knows earlier context is missing. It is re-inserted on every trim, since @@ -107,7 +109,7 @@ export function trimOldMessagesToFitContext( // Per-unit size estimates. The running remainder keeps the JSON structure // overhead, so the estimate is slightly pessimistic — we never under-trim. - const unitTokens = units.map((u) => sumUnit(messages, u, (m) => estimateTokenCount(JSON.stringify(m)))); + const unitTokens = units.map((u) => sumUnit(messages, u, estimateMessageTokenCount)); const unitBytes = units.map((u) => sumUnit(messages, u, messageBytes)); // Low-water mark for the cache-stable cut (see HISTORY_TRIM_HEADROOM_RATIO). @@ -217,8 +219,6 @@ function noTrim(messages: ApiMessage[], tools?: readonly vscode.LanguageModelCha }; } -/** Placeholder substituted for base64 image data when measuring byte weight. */ -const IMAGE_DATA_PLACEHOLDER = "[image]"; /** * Serialized size of one message, excluding base64 image payloads (#173). * @@ -239,30 +239,6 @@ function payloadBytes(messages: ApiMessage[], tools?: readonly vscode.LanguageMo return JSON.stringify({ messages: messages.map(stripImageData), ...(tools?.length ? { tools } : {}) }).length; } -/** - * Shallow clone of `m` with base64 data-URL image payloads replaced by a short - * placeholder. Only `data:` URLs are stripped — a hosted `https://` image URL - * is plain text of trivial size and never carries the payload weight that - * caused #173, so it stays counted as-is. Returns `m` itself when there is - * nothing to strip (the common case). - */ -function stripImageData(m: ApiMessage): ApiMessage { - if (!Array.isArray(m.content)) { - return m; - } - // Copy-on-write: only clone the array when an oversized data URL is found. - let stripped: OpenAiContentPart[] | undefined; - for (let i = 0; i < m.content.length; i++) { - const part = m.content[i]; - const url = part.type === "image_url" ? part.image_url?.url : undefined; - if (typeof url === "string" && url.startsWith("data:")) { - stripped ??= [...m.content]; - stripped[i] = { ...part, image_url: { url: IMAGE_DATA_PLACEHOLDER } }; - } - } - return stripped ? { ...m, content: stripped } : m; -} - function sumUnit(messages: ApiMessage[], unit: DropUnit, measure: (m: ApiMessage) => number): number { let total = 0; for (let i = unit.start; i <= unit.end; i++) { diff --git a/src/request/google.ts b/src/request/google.ts index 76d49d7ea..a8f8afc45 100644 --- a/src/request/google.ts +++ b/src/request/google.ts @@ -148,30 +148,30 @@ function dataUrlToInlineData(url: string): { mimeType: string; data: string } | }; } -// RULES: Gemini's functionResponse.response is a flexible object. The plain -// form is `{ name, content }` where content is a JSON string (text-only tool -// results). When the tool result carries an image (e.g. MCP screenshot), we -// extend it with `parts` containing both the text and an inlineData block so -// vision-capable Gemini models can see the image. The `content` field is kept -// for backwards compatibility with providers that ignore the `parts` field. +// RULES (Gemini generateContent FunctionResponse): `name` and `response` +// are required; `response` is an arbitrary JSON object chosen by the caller. +// There is NO top-level `content` field — strict validators reject it (#283). +// Multimodal tool results put their text in `response` and their media in the +// optional top-level `parts` array (FunctionResponsePart), never inside +// `response`. This shape is what the official API reference documents. function googleFunctionResponseContent( content: ApiMessage["content"], name: string, -): { name: string; content: string; parts?: Record[] } { +): { name: string; response: Record; parts?: Record[] } { if (typeof content === "string") { - return { name, content }; + return { name, response: { content } }; } if (!Array.isArray(content)) { // ApiMessage content is `string | null | OpenAiContentPart[]`; after the // string and array checks above, this branch only sees null. - return { name, content: JSON.stringify("") }; + return { name, response: { content: JSON.stringify("") } }; } const text = joinedTextContent(content, "\n"); const hasImage = content.some((part) => part.type === "image_url" && part.image_url?.url); if (!hasImage) { - return { name, content: text }; + return { name, response: { content: text } }; } const parts: Record[] = []; @@ -187,5 +187,5 @@ function googleFunctionResponseContent( } } - return { name, content: text, parts }; + return { name, response: { content: text }, parts }; } diff --git a/src/request/shared.ts b/src/request/shared.ts index 9e72f24d5..404e702dd 100644 --- a/src/request/shared.ts +++ b/src/request/shared.ts @@ -10,6 +10,48 @@ export function messagesHaveImages(messages: readonly ApiMessage[]): boolean { return messages.some((message) => Array.isArray(message.content) && message.content.some((part) => part.type === "image_url")); } +/** Placeholder substituted for base64 image data when measuring payload weight. */ +export const IMAGE_DATA_PLACEHOLDER = "[image]"; + +/** Count base64 data-URL image parts in one message (token accounting, #287). */ +export function countImageDataParts(message: ApiMessage): number { + if (!Array.isArray(message.content)) { + return 0; + } + let count = 0; + for (const part of message.content) { + const url = part.type === "image_url" ? part.image_url?.url : undefined; + if (typeof url === "string" && url.startsWith("data:")) { + count += 1; + } + } + return count; +} + +/** + * Shallow clone of `m` with base64 data-URL image payloads replaced by a short + * placeholder. Only `data:` URLs are stripped — a hosted `https://` image URL + * is plain text of trivial size and never carries the payload weight that + * caused #173/#287, so it stays counted as-is. Returns `m` itself when there + * is nothing to strip (the common case). + */ +export function stripImageData(m: ApiMessage): ApiMessage { + if (!Array.isArray(m.content)) { + return m; + } + // Copy-on-write: only clone the array when a data URL is found. + let stripped: OpenAiContentPart[] | undefined; + for (let i = 0; i < m.content.length; i++) { + const part = m.content[i]; + const url = part.type === "image_url" ? part.image_url?.url : undefined; + if (typeof url === "string" && url.startsWith("data:")) { + stripped ??= [...m.content]; + stripped[i] = { ...part, image_url: { url: IMAGE_DATA_PLACEHOLDER } }; + } + } + return stripped ? { ...m, content: stripped } : m; +} + /** Leading note on deferred tool-image messages (see below). */ export const DEFERRED_TOOL_IMAGES_NOTE = "Images returned by a tool result (the upstream provider does not accept images inside tool messages):"; diff --git a/src/retry.ts b/src/retry.ts index 5c6f964c5..d4f9c4ca7 100644 --- a/src/retry.ts +++ b/src/retry.ts @@ -152,6 +152,18 @@ const RECOVERABLE_ERROR_PATTERNS: { }, // --- Temperature errors --- + // "Unsupported parameter: 'temperature' is not supported with this model" + // OpenCode Go gateway for GPT Luna (issue #285). models.dev still claims + // temperature is supported, so the request must be patched on retry too. + { + pattern: /unsupported parameter:\s*['"]temperature['"]/i, + patch: (body) => { + const next = { ...body }; + delete next.temperature; + return next; + }, + describe: () => "removed temperature (unsupported parameter)", + }, // "invalid temperature: only 1 is allowed for this model" { pattern: /invalid temperature[:\s]+only \d+(\.\d+)? is allowed/i, diff --git a/src/test/errors.test.ts b/src/test/errors.test.ts index f67fc7efb..1c54e15b2 100644 --- a/src/test/errors.test.ts +++ b/src/test/errors.test.ts @@ -1,6 +1,12 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; -import { describeEndpointUnavailable, describeFreeTierRestriction, buildOpenCodeRequestError, OpenCodeRequestError } from "../errors.js"; +import { + describeEndpointUnavailable, + describeFreeTierRestriction, + describeTrainingOptInRestriction, + buildOpenCodeRequestError, + OpenCodeRequestError, +} from "../errors.js"; import { MODEL_METADATA_CACHE_KEY, MODEL_METADATA_REVISION } from "../config.js"; describe("describeFreeTierRestriction (issues #235/#240)", () => { @@ -38,6 +44,35 @@ describe("describeFreeTierRestriction (issues #235/#240)", () => { }); }); +describe("describeTrainingOptInRestriction (issue #282)", () => { + it("turns the Go training opt-in rejection into an actionable hint", () => { + const hint = describeTrainingOptInRestriction( + "This Go model trains on request data. Turn on 'Allow paid endpoints that train on request data' at https://opencode.ai/console/...", + ); + assert.ok(hint, "should produce a hint"); + assert.match(hint, /Allow paid endpoints that train on request data/); + assert.match(hint, /Settings > Privacy/); + }); + + it("returns undefined for unrelated messages", () => { + assert.equal(describeTrainingOptInRestriction("Model is unavailable"), undefined); + }); + + it("surfaces the hint through buildOpenCodeRequestError", () => { + const response = new Response(null, { status: 400 }); + const error = buildOpenCodeRequestError( + "OpenCode Go", + response, + JSON.stringify({ error: { message: "This Go model trains on request data." } }), + "iceman-contributor-free", + 49097, + "", + ); + assert.match(error.userMessage, /workspace privacy setting/); + assert.match(error.message, /workspace privacy setting/); + }); +}); + describe("describeEndpointUnavailable (longcat-2.5-preview-free 402)", () => { it("matches the upstream endpoint-unavailable message", () => { const hint = describeEndpointUnavailable("Upstream request failed: Endpoint is unavailable."); diff --git a/src/test/google-function-response.test.ts b/src/test/google-function-response.test.ts new file mode 100644 index 000000000..1d786ecd9 --- /dev/null +++ b/src/test/google-function-response.test.ts @@ -0,0 +1,93 @@ +import { describe, it, before } from "node:test"; +import assert from "node:assert/strict"; +import Module from "node:module"; +import path from "node:path"; +import fs from "node:fs"; +import os from "node:os"; + +/* + * Regression for #283: Gemini's FunctionResponse requires `name` + `response`. + * Commit ec92a44 (2026-07-20) replaced the valid `{ name, response: {...} }` + * shape with `{ name, content }`, which strict validators (gemini-4-argon) + * reject with `Unknown name "content" at function_response`. + */ + +const vscodeMockPath = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "vscode-mock-google-")), "index.js"); +fs.writeFileSync( + vscodeMockPath, + `"use strict";\nclass LanguageModelChatToolMode { static Required = "required"; }\nmodule.exports = { LanguageModelChatToolMode };\n`, + "utf-8", +); + +type ResolveFilename = (request: string, parent: unknown, ...args: unknown[]) => string; +const moduleResolver = Module as unknown as { _resolveFilename: ResolveFilename }; +const originalResolveFilename = moduleResolver._resolveFilename; +moduleResolver._resolveFilename = function (request: string, parent: unknown, ...args: unknown[]): string { + if (request === "vscode") { + return vscodeMockPath; + } + return originalResolveFilename.call(this, request, parent, ...args); +}; + +let buildGoogleGenerateContentBody: typeof import("../request/google.js").buildGoogleGenerateContentBody; + +const settings = { + temperature: 0.2, + thinking: {}, + maxOutputTokensOverride: 0, + maxInputTokensOverride: 0, + debugReasoning: false, + requestTimeoutMs: 0, + streamIdleTimeoutMs: 0, + stripThinkTags: "auto", +} as unknown as import("../request/types.js").ApiSettings; +const metadata = {} as unknown as import("../models/metadata.js").ResolvedModelMetadata; +const limits = { maxOutputTokens: 4096 } as unknown as import("../models/modelLimits.js").ModelLimits; +const options = {} as unknown as import("vscode").ProvideLanguageModelChatResponseOptions; + +interface FunctionResponsePart { + functionResponse?: Record; +} + +function functionResponseFor(content: import("../request/types.js").ApiMessage["content"]): Record { + const messages = [ + { + role: "assistant", + content: null, + tool_calls: [{ id: "call_1", type: "function", function: { name: "read_file", arguments: "{}" } }], + }, + { role: "tool", content, tool_call_id: "call_1" }, + ] as import("../request/types.js").ApiMessage[]; + const body = buildGoogleGenerateContentBody("gemini-4-argon", messages, options, settings, metadata, limits); + const contents = body.contents as Array<{ parts: FunctionResponsePart[] }>; + const part = contents.flatMap((entry) => entry.parts).find((candidate) => candidate.functionResponse !== undefined); + assert.ok(part?.functionResponse, "expected a functionResponse part"); + return part.functionResponse; +} + +before(async () => { + ({ buildGoogleGenerateContentBody } = await import("../request/google.js")); +}); + +describe("Gemini functionResponse wire shape (#283)", () => { + it("sends text tool results inside response, never as a top-level content field", () => { + const response = functionResponseFor("file contents"); + assert.deepEqual(response, { name: "read_file", response: { content: "file contents" } }); + assert.equal("content" in response, false); + }); + + it("keeps multimodal parts at functionResponse level with a valid response object", () => { + const response = functionResponseFor([ + { type: "text", text: "screenshot" }, + { type: "image_url", image_url: { url: "data:image/png;base64,AAAA" } }, + ]); + assert.deepEqual(response.response, { content: "screenshot" }); + assert.deepEqual(response.parts, [{ text: "screenshot" }, { inlineData: { mimeType: "image/png", data: "AAAA" } }]); + assert.equal("content" in response, false); + }); + + it("still emits a response object for null tool content", () => { + const response = functionResponseFor(null); + assert.deepEqual(response, { name: "read_file", response: { content: '""' } }); + }); +}); diff --git a/src/test/messages.test.ts b/src/test/messages.test.ts index c09a3a86e..21e9d9b3d 100644 --- a/src/test/messages.test.ts +++ b/src/test/messages.test.ts @@ -219,6 +219,23 @@ describe("trimOldMessagesToFitContext — image data excluded from byte cap (#17 }); }); +describe("trimOldMessagesToFitContext — image data excluded from token budget (#287)", () => { + it("keeps text history when only a large image would inflate the token estimate", () => { + const messages: ApiMessage[] = [ + textMessage("user", "anchor"), + { + role: "user", + content: [{ type: "image_url", image_url: { url: `data:image/png;base64,${"A".repeat(400_000)}` } }], + }, + textMessage("assistant", "work already done"), + textMessage("user", "current prompt"), + ]; + const result = trimOldMessagesToFitContext(messages, 5_000, 512 * 1024); + assert.equal(result.removed, 0, "text history must survive a vision-only payload"); + assert.ok(result.finalTokens < 5_000, `finalTokens ${String(result.finalTokens)} must stay near the real prompt size`); + }); +}); + describe("trimOldMessagesToFitContext — cache-stable headroom", () => { /** * Budget used across these tests: 100K tokens. The headroom resolves to diff --git a/src/test/metadata.test.ts b/src/test/metadata.test.ts index 95f02dd87..d3a55ba16 100644 --- a/src/test/metadata.test.ts +++ b/src/test/metadata.test.ts @@ -99,6 +99,20 @@ describe("fallbackModelMetadata — non-kimi models unaffected", () => { }); }); +describe("fallbackModelMetadata — GPT Luna temperature (issue #285)", () => { + it("gpt-6-luna reports temperature: false despite models.dev claiming support", () => { + const meta = fallbackModelMetadata("gpt-6-luna", GO_VENDOR); + assert.ok(meta, "expected fallback metadata to be defined"); + assert.equal(meta.temperature, false); + }); + + it("gpt-5.6-luna reports temperature: false", () => { + const meta = fallbackModelMetadata("gpt-5.6-luna", GO_VENDOR); + assert.ok(meta, "expected fallback metadata to be defined"); + assert.equal(meta.temperature, false); + }); +}); + describe("VISION_CAPABLE_MODELS", () => { it("includes known vision models (minimax-m2.7, kimi-k2.6, mimo-v2.5)", () => { assert.ok(VISION_CAPABLE_MODELS.has("minimax-m2.7")); @@ -180,6 +194,12 @@ describe("resolveModelMetadata — cold-start temperature chain", () => { const resolved = resolveModelMetadata("glm-5", GO_VENDOR, emptySnapshot, new Map()); assert.notEqual(resolved.temperature, false); }); + + it("overrides a live models.dev temperature:true for GPT Luna (issue #285)", () => { + const live = new Map([["gpt-6-luna", { temperature: true }]]); + const resolved = resolveModelMetadata("gpt-6-luna", GO_VENDOR, emptySnapshot, live); + assert.equal(resolved.temperature, false, "the Go gateway rejects temperature regardless of models.dev"); + }); }); describe("normalizeLiveModelMetadata — modality-based vision detection", () => { diff --git a/src/test/openCodeConsoleCredential.test.ts b/src/test/openCodeConsoleCredential.test.ts new file mode 100644 index 000000000..3a645a1f4 --- /dev/null +++ b/src/test/openCodeConsoleCredential.test.ts @@ -0,0 +1,24 @@ +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { CONSOLE_KEYS_URL, parseCredentialRows } from "../openCodeConsoleCredential.js"; + +describe("OpenCode Console credential import (#286)", () => { + it("reads the sqlite3 -json array shape", () => { + assert.equal(parseCredentialRows([{ value: "oc_sk_placeholder" }]), "oc_sk_placeholder"); + }); + + it("reads the node:sqlite single-row shape and trims whitespace", () => { + assert.equal(parseCredentialRows({ value: " oc_sk_placeholder " }), "oc_sk_placeholder"); + }); + + it("returns undefined for missing or empty values", () => { + assert.equal(parseCredentialRows([]), undefined); + assert.equal(parseCredentialRows([{ value: " " }]), undefined); + assert.equal(parseCredentialRows(null), undefined); + assert.equal(parseCredentialRows([{ other: "x" }]), undefined); + }); + + it("points at the Console personal API keys page", () => { + assert.match(CONSOLE_KEYS_URL, /opencode\.ai\/console\/api/); + }); +}); diff --git a/src/test/retry.test.ts b/src/test/retry.test.ts index 0d99b4e79..985097361 100644 --- a/src/test/retry.test.ts +++ b/src/test/retry.test.ts @@ -50,6 +50,14 @@ describe("analyzeHttp400ForRetry — temperature errors", () => { assert.ok(result, "should be recoverable"); assert.deepEqual(result.body, { model: "kimi-k2.7-code" }); }); + + it("patches GPT Luna's 'Unsupported parameter: temperature' (issue #285)", () => { + const body = { model: "gpt-6-luna", temperature: 0.2, stream: true }; + const result = analyzeHttp400ForRetry("Unsupported parameter: 'temperature' is not supported with this model.", body); + assert.ok(result, "should be recoverable"); + assert.deepEqual(result.body, { model: "gpt-6-luna", stream: true }); + assert.match(result.reason, /temperature/i); + }); }); describe("analyzeHttp400ForRetry — enable_thinking errors", () => { diff --git a/src/test/tokenEstimate.test.ts b/src/test/tokenEstimate.test.ts index 0f01668d5..69b667187 100644 --- a/src/test/tokenEstimate.test.ts +++ b/src/test/tokenEstimate.test.ts @@ -8,8 +8,20 @@ describe("token estimates", () => { assert.equal(estimateTokenCount(" \n\t"), 0); }); + it("charges base64 image data as a bounded per-image estimate, not as prose (#287)", () => { + const messages: import("../request/types.js").ApiMessage[] = [ + { + role: "user", + content: [{ type: "image_url", image_url: { url: `data:image/png;base64,${"A".repeat(400_000)}` } }], + }, + ]; + const estimate = estimatePromptTokenCount(messages); + assert.ok(estimate < 10_000, `image estimate ${String(estimate)} must not scale with base64 length`); + assert.ok(estimate >= 1024); + }); + it("includes tool schemas in the prompt estimate", () => { - const messages = [{ role: "user", content: "inspect the workspace" }]; + const messages: import("../request/types.js").ApiMessage[] = [{ role: "user", content: "inspect the workspace" }]; const withoutTools = estimatePromptTokenCount(messages); const withTools = estimatePromptTokenCount(messages, [ { diff --git a/src/test/toolLoopGuard.test.ts b/src/test/toolLoopGuard.test.ts index ec434253e..1b724798c 100644 --- a/src/test/toolLoopGuard.test.ts +++ b/src/test/toolLoopGuard.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { describe, it } from "node:test"; -import { BEAM_TOOL_LOOP_TURN_LIMIT, detectBeamToolLoop } from "../toolLoopGuard.js"; +import { BEAM_TOOL_LOOP_TURN_LIMIT, detectBeamToolLoop, detectMuseRepetitionLoop, MUSE_REPETITION_TURN_LIMIT } from "../toolLoopGuard.js"; import type { ApiMessage } from "../request/types.js"; function loopMessages(turns: number, repeated = false): ApiMessage[] { @@ -35,3 +35,42 @@ describe("detectBeamToolLoop", () => { assert.equal(detectBeamToolLoop("beam-free", loopMessages(BEAM_TOOL_LOOP_TURN_LIMIT - 1)), undefined); }); }); + +const repeatedAnswer = "第三方源码不动是对的——我换一种做法:上游文件一个字节都不碰,只动我们自己的 port 层和工程配置。"; + +function museLoopMessages(turns: number, texts: readonly string[] = []): ApiMessage[] { + const messages: ApiMessage[] = [{ role: "user", content: "finish the port migration" }]; + for (let i = 0; i < turns; i++) { + const id = `call_${String(i)}`; + messages.push({ + role: "assistant", + content: texts[i] ?? repeatedAnswer, + tool_calls: [{ id, type: "function", function: { name: "read_file", arguments: JSON.stringify({ path: `/file-${String(i)}.ts` }) } }], + }); + messages.push({ role: "tool", tool_call_id: id, content: "file content" }); + } + return messages; +} + +describe("detectMuseRepetitionLoop (#284)", () => { + it("stops three consecutive identical Muse answers even with tool calls between them", () => { + const warning = detectMuseRepetitionLoop("muse-spark-1.3-contributor", museLoopMessages(MUSE_REPETITION_TURN_LIMIT)); + assert.match(warning ?? "", /tool-free final-answer recovery/); + }); + + it("does not fire for two repeats or for varying answers", () => { + assert.equal(detectMuseRepetitionLoop("muse-spark-1.3-contributor", museLoopMessages(2)), undefined); + const varying = museLoopMessages(3, [ + "first distinct answer that is long enough to count", + "second distinct answer that is long enough to count", + "third distinct answer that is long enough to count", + ]); + assert.equal(detectMuseRepetitionLoop("muse-spark-1.3-contributor", varying), undefined); + }); + + it("ignores short answers and non-Muse models", () => { + const short = museLoopMessages(3, ["ok", "ok", "ok"]); + assert.equal(detectMuseRepetitionLoop("muse-spark-1.3-contributor", short), undefined); + assert.equal(detectMuseRepetitionLoop("deepseek-v4.1-flash", museLoopMessages(10)), undefined); + }); +}); diff --git a/src/tokenEstimate.ts b/src/tokenEstimate.ts index 0b8b2dbd7..00ea9ae3d 100644 --- a/src/tokenEstimate.ts +++ b/src/tokenEstimate.ts @@ -1,13 +1,29 @@ +import { IMAGE_TOKEN_ESTIMATE } from "./config"; +import { countImageDataParts, stripImageData } from "./request/shared"; +import type { ApiMessage } from "./request/types"; + export interface PromptToolDefinition { name: string; description?: string; inputSchema?: unknown; } -/** Estimate the complete prompt surface that the provider will tokenize. */ -export function estimatePromptTokenCount(messages: unknown, tools?: readonly PromptToolDefinition[]): number { +/** + * Estimate the complete prompt surface that the provider will tokenize. + * + * CONTRACT: base64 image data is replaced with a short placeholder before the + * character heuristic runs; each stripped image is charged a bounded + * `IMAGE_TOKEN_ESTIMATE` instead of its base64 length (#287). Hosted image + * URLs stay counted as ordinary text. Tool schemas are included as before. + */ +export function estimatePromptTokenCount(messages: readonly ApiMessage[], tools?: readonly PromptToolDefinition[]): number { + let imageTokens = 0; + const strippedMessages = messages.map((message) => { + imageTokens += countImageDataParts(message) * IMAGE_TOKEN_ESTIMATE; + return stripImageData(message); + }); const prompt = { - messages, + messages: strippedMessages, ...(tools?.length ? { tools: tools.map((tool) => ({ @@ -19,7 +35,12 @@ export function estimatePromptTokenCount(messages: unknown, tools?: readonly Pro : {}), }; - return estimateTokenCount(JSON.stringify(prompt)); + return estimateTokenCount(JSON.stringify(prompt)) + imageTokens; +} + +/** Estimate one message with the same image accounting as the full prompt. */ +export function estimateMessageTokenCount(message: ApiMessage): number { + return estimateTokenCount(JSON.stringify(stripImageData(message))) + countImageDataParts(message) * IMAGE_TOKEN_ESTIMATE; } export function estimateTokenCount(value: string): number { diff --git a/src/toolLoopGuard.ts b/src/toolLoopGuard.ts index ac931ac7f..8a64f1c4c 100644 --- a/src/toolLoopGuard.ts +++ b/src/toolLoopGuard.ts @@ -6,12 +6,18 @@ * many consecutive tool-call turns; it does not try to judge whether an * individual tool call is correct. */ +import { joinedTextContent } from "./responsesRequest"; import type { ApiMessage, OpenAiToolCall } from "./request/types"; /** Number of consecutive Beam tool-call turns tolerated before stopping. */ export const BEAM_TOOL_LOOP_TURN_LIMIT = 8; const BEAM_REPEATED_TOOL_CALL_TURN_LIMIT = 3; +/** Consecutive identical assistant answers that trigger the Muse guard (#284). */ +export const MUSE_REPETITION_TURN_LIMIT = 3; +const MUSE_REPETITION_MIN_CHARS = 40; +const MUSE_REPETITION_SIGNATURE_CHARS = 200; + /** Return a recovery instruction when Beam is stuck in a tool loop. */ export function detectBeamToolLoop(modelId: string, messages: readonly ApiMessage[]): string | undefined { if (!/^beam-/i.test(modelId)) return undefined; @@ -40,6 +46,51 @@ export function detectBeamToolLoop(modelId: string, messages: readonly ApiMessag return `[Beam tool-call loop detected after ${String(turns.length)} consecutive tool-calling turns. Switching to a tool-free final-answer recovery turn.]`; } +/** + * Detect a Muse Spark answer-repetition loop: the same visible assistant text + * reappears in consecutive turns, typically with tool calls in between (#284). + * + * CONTRACT: pure, Muse-only. Short answers are ignored, and only a run of + * identical normalized signatures at the tail of the current user turn fires. + * The caller turns the warning into a tool-free recovery turn. + */ +export function detectMuseRepetitionLoop(modelId: string, messages: readonly ApiMessage[]): string | undefined { + if (!/^muse-/i.test(modelId)) { + return undefined; + } + + let lastUserIndex = -1; + for (let index = messages.length - 1; index >= 0; index--) { + if (messages[index]?.role === "user") { + lastUserIndex = index; + break; + } + } + + const signatures = messages + .slice(lastUserIndex + 1) + .filter((message) => message.role === "assistant") + .map((message) => repetitionSignature(joinedTextContent(message.content))) + .filter((signature): signature is string => signature !== undefined); + if (signatures.length < MUSE_REPETITION_TURN_LIMIT) { + return undefined; + } + + const tail = signatures.slice(-MUSE_REPETITION_TURN_LIMIT); + if (tail.every((signature) => signature === tail[0])) { + return `[Muse repetition loop detected: the same answer text repeated in ${String(tail.length)} consecutive turns. Switching to a tool-free final-answer recovery turn.]`; + } + return undefined; +} + +function repetitionSignature(text: string): string | undefined { + const normalized = text.replace(/\s+/g, " ").trim(); + if (normalized.length < MUSE_REPETITION_MIN_CHARS) { + return undefined; + } + return normalized.slice(0, MUSE_REPETITION_SIGNATURE_CHARS); +} + function toolCallTurnSignature(toolCalls: readonly OpenAiToolCall[]): string { return toolCalls.map((call) => `${call.function.name}:${canonicalArguments(call.function.arguments)}`).join("|"); }