Skip to content

Commit 20011a1

Browse files
authored
fix(opencode-go): satisfy provider wire contract (#3405)
1 parent fc70555 commit 20011a1

7 files changed

Lines changed: 263 additions & 16 deletions

File tree

‎src/adapters/openai-responses.ts‎

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2052,25 +2052,27 @@ export function stripOpenAiOnlyWebSearchFields(body: unknown): unknown {
20522052
}
20532053

20542054
/**
2055-
* Muse Spark ids whose Responses gateway refuses `search_content_types` on a plain
2055+
* Muse Spark ids whose Responses gateway refuses provider-specific fields on a plain
20562056
* `web_search` tool. Membership, not equality: 1.3 shipped 2026-09-02 as the
20572057
* same-shaped successor to 1.2 on the same Zen wire, and an equality check would
2058-
* have let a Codex-emitted `web_search` + `search_content_types` body reach the
2058+
* have let a Codex-emitted `web_search` body reach the
20592059
* gateway and come back 400 for every request the moment 1.3 was selected.
20602060
*/
20612061
const MUSE_SPARK_WEB_SEARCH_STRICT_MODELS = new Set([
20622062
"muse-spark-1.3-contributor",
20632063
"muse-spark-1.2-contributor",
20642064
]);
20652065

2066+
const MUSE_SPARK_UNSUPPORTED_WEB_SEARCH_FIELDS = [
2067+
"search_content_types",
2068+
"indexed_web_access",
2069+
] as const;
2070+
20662071
/**
2067-
* OpenCode Zen / Go Muse Spark Responses gateway refuses `search_content_types`
2068-
* on a plain `web_search` tool (400) but accepts it on `web_search_preview`; a
2069-
* plain `web_search` is also accepted. Probed directly against the gateway on
2070-
* 2026-08-26: `web_search` + `search_content_types` -> 400, `web_search_preview`
2071-
* + `search_content_types` -> 200, plain `web_search` -> 200. Luna accepts every
2072-
* shape, so this is Muse-only. Drop only the field the gateway refuses while
2073-
* keeping the tool type and every other accepted option intact.
2072+
* OpenCode Zen / Go Muse Spark Responses gateway refuses a short list of Codex
2073+
* `web_search` fields. `web_search_preview` keeps its accepted shape, and Luna
2074+
* remains untouched. Keep the rejected names together so a newly identified field
2075+
* is a one-line compatibility update rather than another bespoke rewrite.
20742076
*/
20752077
function stripMuseSparkUnsupportedWebSearchFields(body: unknown, modelId: unknown): unknown {
20762078
if (!isPlainObject(body)) return body;
@@ -2081,8 +2083,11 @@ function stripMuseSparkUnsupportedWebSearchFields(body: unknown, modelId: unknow
20812083
let changed = false;
20822084
const rewritten = tools.map(tool => {
20832085
if (!isPlainObject(tool) || tool.type !== "web_search") return tool;
2084-
if (!Object.hasOwn(tool, "search_content_types")) return tool;
2085-
const { search_content_types: _dropped, ...rest } = tool;
2086+
if (!MUSE_SPARK_UNSUPPORTED_WEB_SEARCH_FIELDS.some(field => Object.hasOwn(tool, field))) {
2087+
return tool;
2088+
}
2089+
const rest = { ...tool };
2090+
for (const field of MUSE_SPARK_UNSUPPORTED_WEB_SEARCH_FIELDS) delete rest[field];
20862091
changed = true;
20872092
return rest;
20882093
});
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import { createHash } from "node:crypto";
2+
import type { OcxProviderConfig } from "../types";
3+
import { registryEntryForProviderDestination } from "./registry";
4+
5+
export const OPENCODE_GO_SESSION_HEADER = "x-opencode-session";
6+
7+
function hasHeaderCaseInsensitive(
8+
headers: Record<string, string> | undefined,
9+
name: string,
10+
): boolean {
11+
const target = name.toLowerCase();
12+
return Object.keys(headers ?? {}).some(key => key.toLowerCase() === target);
13+
}
14+
15+
/** Derive a provider-scoped opaque value without exposing Codex task or subagent ids. */
16+
export function deriveOpenCodeGoSessionId(sessionLane: string): string {
17+
const digest = createHash("sha256")
18+
.update("opencodex/opencode-go/session/v1\0")
19+
.update(sessionLane)
20+
.digest("hex")
21+
.slice(0, 32);
22+
return `ocx_${digest}`;
23+
}
24+
25+
/** Add per-conversation Go affinity only to the canonical fixed-key destination. */
26+
export function resolveOpenCodeGoTransport<T extends OcxProviderConfig>(
27+
provider: T,
28+
sessionLane: string | undefined,
29+
): T {
30+
if (registryEntryForProviderDestination(provider)?.id !== "opencode-go") return provider;
31+
if (!sessionLane) return provider;
32+
if (hasHeaderCaseInsensitive(provider.headers, OPENCODE_GO_SESSION_HEADER)) return provider;
33+
34+
return {
35+
...provider,
36+
headers: {
37+
...(provider.headers ?? {}),
38+
[OPENCODE_GO_SESSION_HEADER]: deriveOpenCodeGoSessionId(sessionLane),
39+
},
40+
};
41+
}

‎src/server/responses/core.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,7 @@ import {
241241
} from "../../providers/key-failover";
242242
import { shouldAttemptImageTierRetry } from "../image-retry";
243243
import { isXaiResponsesDestination, resolveProviderTransport } from "../../providers/xai-transport";
244+
import { resolveOpenCodeGoTransport } from "../../providers/opencode-go-transport";
244245
import type { WsData } from "../ws-bridge";
245246
import {
246247
codexAccountSelectionForTurn,
@@ -287,6 +288,7 @@ import {
287288
conversationIdFromResponsesRequest,
288289
normalizeLogConversationId,
289290
reasoningReplayConversationIdFromResponsesRequest,
291+
sessionLaneIdFromRequest,
290292
sessionIdHeaderFromRequest,
291293
} from "../request-log-conversation";
292294
import type { AttemptRecoveryKind } from "../../usage/log";
@@ -2059,6 +2061,7 @@ async function applyFinalRouteRequestNormalization(args: {
20592061

20602062
// Settle the wire once so logging, fast-mode, auth, and sidecars read the adapter
20612063
// this request will actually use (#404).
2064+
route.provider = resolveOpenCodeGoTransport(route.provider, sessionLaneIdFromRequest(req.headers));
20622065
route.provider = resolveWireProtocolOverride(route.providerName, route.modelId, route.provider, inboundWire);
20632066
if (preserveAnthropicResponseModel) parsed._responseModelId = responseModelId;
20642067
logCtx.model = route.modelId;

‎structure/04_transports-and-sidecars.md‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,15 @@ does not set `modelResponsesUpstreamStreaming`: client `stream: true` remains re
305305
streaming until a current-runtime reproduction justifies a separate bounded-JSON compatibility
306306
policy.
307307

308+
The canonical OpenCode Go transport also derives `x-opencode-session` from the existing hashed
309+
session lane before per-model wire selection. One conversation keeps one opaque affinity value
310+
across Responses, Chat, retries, and key rotation, while sibling subagents remain distinct. An
311+
operator-supplied header wins case-insensitively. Renamed providers are covered only when their
312+
fixed key-auth destination still matches the registry; custom and lookalike URLs receive nothing.
313+
Muse Spark's Responses sanitizer also drops the provider-rejected `search_content_types` and
314+
`indexed_web_access` fields from plain `web_search` tools while preserving preview tools and
315+
unrelated models.
316+
308317
[Decision Log]
309318
- 목적과 의도: Match OpenCode Go's model-specific Luna endpoint without changing sibling model behavior.
310319
- 기존 구현 및 제약 조건: The preset had one Chat default even though the upstream publishes a mixed Chat, Responses, and Anthropic matrix; operators must retain explicit override precedence.
@@ -313,6 +322,14 @@ policy.
313322
- 다른 대안 대신 이 방식을 선택한 이유: The endpoint mismatch is reproducible from current code and upstream documentation, whereas a current-dev live canary has not established the separate terminal-delivery policy.
314323
- 장점, 단점 및 영향: Luna reaches its documented endpoint across inbound surfaces and explicit opt-out still works; any future stream workaround remains a separately reviewed compatibility decision.
315324

325+
[Decision Log]
326+
- 목적과 의도: Give OpenCode Go the stable per-conversation header it requires for prompt-cache routing without exposing raw Codex identifiers.
327+
- 기존 구현 및 제약 조건: Codex already supplies task and subagent identity, but Go requests reached every adapter without `x-opencode-session`; one static provider header would collapse unrelated conversations.
328+
- 검토한 주요 대안: Forward a raw thread header; reuse `prompt_cache_key`; configure one global value; inject separately in Chat and Responses adapters; enrich the canonical provider before wire selection.
329+
- 선택한 방식: Hash the existing parent-qualified session lane with a provider-specific domain, attach it as runtime-only provider metadata before wire selection, and preserve an explicit operator override.
330+
- 다른 대안 대신 이 방식을 선택한 이유: The lane already separates sibling subagents, while cache keys may represent shared cohorts and adapter-local changes would drift across Go's mixed wire matrix.
331+
- 장점, 단점 및 영향: Go requests gain stable opaque affinity across normal retries and key rotation without persisted config changes; requests with no stable lane remain headerless rather than receiving a per-request value that defeats affinity.
332+
316333
### Passthrough SSE stream shapes (#314)
317334

318335
Native passthrough SSE has TWO shapes, selected per request in

‎tests/key-failover.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
rotateKeyOn429,
1111
rotateProviderTransportOn429,
1212
} from "../src/providers/key-failover";
13+
import { resolveOpenCodeGoTransport } from "../src/providers/opencode-go-transport";
1314
import { deriveXaiConvId } from "../src/providers/xai-transport";
1415
import { routeModel } from "../src/router";
1516
import type { OcxConfig, OcxParsedRequest, OcxProviderConfig } from "../src/types";
@@ -133,6 +134,36 @@ describe("rotateKeyOn429", () => {
133134
});
134135

135136
describe("rotateProviderTransportOn429", () => {
137+
test("preserves OpenCode Go session affinity across key rotation", () => {
138+
const config = makeConfig({
139+
authMode: "key",
140+
apiKey: "key-alpha-000111222333",
141+
apiKeyPool: pool3(),
142+
});
143+
config.defaultProvider = "opencode-go";
144+
config.providers["opencode-go"] = {
145+
...config.providers.p,
146+
baseUrl: "https://opencode.ai/zen/go/v1",
147+
};
148+
delete config.providers.p;
149+
150+
const initial = resolveOpenCodeGoTransport(
151+
config.providers["opencode-go"],
152+
"hashed-parent\0hashed-child",
153+
);
154+
const initialSession = initial.headers?.["x-opencode-session"];
155+
expect(initialSession).toMatch(/^ocx_[0-9a-f]{32}$/);
156+
157+
const rotated = rotateProviderTransportOn429(config, "opencode-go", initial, {
158+
now: 1_000_000,
159+
attemptedKey: "key-alpha-000111222333",
160+
});
161+
162+
expect(rotated?.apiKey).toBe("key-beta-444555666777");
163+
expect(rotated?.headers?.["x-opencode-session"]).toBe(initialSession);
164+
expect(config.providers["opencode-go"].headers?.["x-opencode-session"]).toBeUndefined();
165+
});
166+
136167
test("keeps Kimi prompt-cache forwarding after rotating a stale pre-upgrade config", () => {
137168
const promptCacheKey = "stable-kimi-conversation-429";
138169
const config = makeConfig({

‎tests/muse-spark-web-search-compat.test.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ function webSearchTool(): Record<string, unknown> {
1818
return {
1919
type: "web_search",
2020
search_content_types: ["text", "image"],
21+
indexed_web_access: true,
2122
search_context_size: "medium",
2223
};
2324
}
@@ -36,22 +37,22 @@ function build(modelId: string, rawBody: Record<string, unknown>): Record<string
3637
const toolsOf = (body: Record<string, unknown>) => body.tools as Array<Record<string, unknown>>;
3738

3839
/**
39-
* Muse Spark's Responses gateway 400s a plain `web_search` carrying
40-
* `search_content_types`, while accepting the same field on `web_search_preview` and
41-
* accepting a bare `web_search` (#2617).
40+
* Muse Spark's Responses gateway 400s a plain `web_search` carrying provider-rejected
41+
* fields, while accepting the preview shape and a bare `web_search` (#2617, #3378).
4242
*
4343
* The field is not ours: Codex emits it from `web_search_tool_type: TextAndImage`. This is
4444
* the same incompatibility class Codex itself handles for Bedrock by selecting text-only
4545
* search, so dropping exactly the refused field at the adapter boundary is a compatibility
4646
* guard rather than a symptom patch — the tool type and every other accepted option survive.
4747
*/
48-
describe("#2617 Muse Spark web_search compatibility", () => {
49-
test("drops search_content_types from a plain web_search, keeping the tool and its other fields", () => {
48+
describe("#2617/#3378 Muse Spark web_search compatibility", () => {
49+
test("drops rejected fields from a plain web_search, keeping the tool and its other fields", () => {
5050
const body = build("muse-spark-1.2-contributor", { tools: [webSearchTool()] });
5151
const tool = toolsOf(body)[0]!;
5252
expect(tool.type).toBe("web_search");
5353
expect(tool.search_context_size).toBe("medium");
5454
expect(Object.hasOwn(tool, "search_content_types")).toBe(false);
55+
expect(Object.hasOwn(tool, "indexed_web_access")).toBe(false);
5556
});
5657

5758
test("web_search_preview keeps the field, because the gateway accepts it there", () => {
@@ -61,11 +62,13 @@ describe("#2617 Muse Spark web_search compatibility", () => {
6162
const tool = toolsOf(body)[0]!;
6263
expect(tool.type).toBe("web_search_preview");
6364
expect(tool.search_content_types).toEqual(["text", "image"]);
65+
expect(tool.indexed_web_access).toBe(true);
6466
});
6567

6668
test("another model on the same provider is untouched", () => {
6769
const body = build("gpt-5.6-luna", { tools: [webSearchTool()] });
6870
expect(toolsOf(body)[0]!.search_content_types).toEqual(["text", "image"]);
71+
expect(toolsOf(body)[0]!.indexed_web_access).toBe(true);
6972
});
7073

7174
test("a nested additional_tools declaration is sanitized too", () => {
@@ -76,6 +79,7 @@ describe("#2617 Muse Spark web_search compatibility", () => {
7679
const nested = (item.tools as Array<Record<string, unknown>>)[0]!;
7780
expect(nested.type).toBe("web_search");
7881
expect(Object.hasOwn(nested, "search_content_types")).toBe(false);
82+
expect(Object.hasOwn(nested, "indexed_web_access")).toBe(false);
7983
});
8084

8185
test("the registry routes only the named exact models to Responses", () => {
@@ -98,6 +102,7 @@ describe("#2617 Muse Spark web_search compatibility", () => {
98102
expect(tool.type).toBe("web_search");
99103
expect(tool.search_context_size).toBe("medium");
100104
expect(Object.hasOwn(tool, "search_content_types")).toBe(false);
105+
expect(Object.hasOwn(tool, "indexed_web_access")).toBe(false);
101106
});
102107

103108
test("1.3 keeps the field on web_search_preview, where the gateway accepts it", () => {
@@ -107,6 +112,7 @@ describe("#2617 Muse Spark web_search compatibility", () => {
107112
const tool = toolsOf(body)[0]!;
108113
expect(tool.type).toBe("web_search_preview");
109114
expect(tool.search_content_types).toEqual(["text", "image"]);
115+
expect(tool.indexed_web_access).toBe(true);
110116
});
111117

112118
test("a nested additional_tools declaration is sanitized for 1.3 too", () => {
@@ -117,5 +123,6 @@ describe("#2617 Muse Spark web_search compatibility", () => {
117123
const nested = (item.tools as Array<Record<string, unknown>>)[0]!;
118124
expect(nested.type).toBe("web_search");
119125
expect(Object.hasOwn(nested, "search_content_types")).toBe(false);
126+
expect(Object.hasOwn(nested, "indexed_web_access")).toBe(false);
120127
});
121128
});

0 commit comments

Comments
 (0)