@hasna/switcher 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -2
- package/dist/cli/index.js +499 -14
- package/dist/domain.d.ts +1 -1
- package/dist/index.js +5 -0
- package/dist/mcp/index.js +9 -3
- package/dist/opencode.d.ts +30 -0
- package/dist/sdk.js +5 -0
- package/dist/serve/index.js +9 -3
- package/openapi.json +1 -1
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -168,7 +168,8 @@ launching the terminal CLI. `detectClaudeDesktopApp()` is available in the SDK.
|
|
|
168
168
|
The provider must implement Anthropic Messages, including streaming and tool
|
|
169
169
|
calling for the chosen model. DeepSeek and compatible gateway presets select
|
|
170
170
|
the Messages endpoint automatically. Saved provider IDs retain their explicit
|
|
171
|
-
protocol.
|
|
171
|
+
protocol. OpenCode Zen and Go additionally use the Claude translation adapter
|
|
172
|
+
described below for models served on another native wire.
|
|
172
173
|
A configured provider works in both desktop apps when it offers both required
|
|
173
174
|
APIs; a preset's existence is not proof that every model supports every feature.
|
|
174
175
|
|
|
@@ -229,7 +230,60 @@ With no Switcher API credential configured, the CLI and `switcher-mcp` exit non-
|
|
|
229
230
|
|
|
230
231
|
Remote API configuration is resolved through Contracts, including canonical credential stores and the default gateway URL. Invalid, unavailable or unauthorized remote services fail without opening local SQLite.
|
|
231
232
|
|
|
232
|
-
The registry contains DeepSeek, OpenRouter, Anthropic, OpenAI, xAI, Ollama, LM Studio, Groq, Cerebras, Mistral, Together AI, Fireworks, Moonshot/Kimi, DashScope, Z.AI, MiniMax, SiliconFlow, and generic protocol entries. `switcher providers presets ID` exposes documented routes, aliases and limitations; this is not a claim that every combination has passed live tests. Remaining adapters and acceptance gates are tracked in [TODOS.md](TODOS.md).
|
|
233
|
+
The registry contains DeepSeek, OpenCode Zen, OpenCode Go, OpenRouter, Anthropic, OpenAI, xAI, Ollama, LM Studio, Groq, Cerebras, Mistral, Together AI, Fireworks, Moonshot/Kimi, DashScope, Z.AI, MiniMax, SiliconFlow, and generic protocol entries. `switcher providers presets ID` exposes documented routes, aliases and limitations; this is not a claim that every combination has passed live tests. Remaining adapters and acceptance gates are tracked in [TODOS.md](TODOS.md).
|
|
234
|
+
|
|
235
|
+
### OpenCode and OpenRouter providers
|
|
236
|
+
|
|
237
|
+
From 0.2.1, `opencode` selects OpenCode Zen and `opencode-go` selects its Go
|
|
238
|
+
subscription. Both discover their complete live `/models` catalogs. Supply
|
|
239
|
+
`OPENCODE_API_KEY` through environment injection or bind each preset to your
|
|
240
|
+
existing vault/keychain reference. Go requires an active Go subscription.
|
|
241
|
+
`SWITCHER_PROVIDER_OPENCODE` and `SWITCHER_PROVIDER_OPENCODE_GO` can bind
|
|
242
|
+
different accounts explicitly. OpenRouter uses `OPENROUTER_API_KEY` or its
|
|
243
|
+
`SWITCHER_PROVIDER_OPENROUTER` binding.
|
|
244
|
+
|
|
245
|
+
```sh
|
|
246
|
+
switcher models opencode --limit 1000
|
|
247
|
+
switcher models opencode-go --limit 1000
|
|
248
|
+
switcher models openrouter --limit 1000
|
|
249
|
+
switcher launch claude --provider opencode --model big-pickle
|
|
250
|
+
switcher launch claude --provider opencode-go --model kimi-k3
|
|
251
|
+
switcher launch claude --provider openrouter --model deepseek/deepseek-v4-flash
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
Use the exact API model ID from the catalog. OpenCode IDs are unprefixed;
|
|
255
|
+
OpenRouter IDs include their provider prefix. `--limit` controls the displayed
|
|
256
|
+
page, and `--offset` accesses subsequent pages. The stored catalog includes all
|
|
257
|
+
pages and modalities; coding selections exclude models explicitly lacking text
|
|
258
|
+
output or tools. OpenRouter's declared reasoning efforts are retained.
|
|
259
|
+
|
|
260
|
+
Claude Code and `claude-desktop` speak Messages to Switcher. For OpenCode,
|
|
261
|
+
Switcher forwards Claude/Qwen Messages requests natively, uses Messages for
|
|
262
|
+
Go's MiniMax models, and translates the other documented model families to
|
|
263
|
+
Chat Completions, Responses, or Gemini generateContent. Translation preserves
|
|
264
|
+
streaming text, tool arguments/results, images, reasoning text, and token usage.
|
|
265
|
+
It keeps Gemini tool signatures within the current launch. Restarting a launch
|
|
266
|
+
does not restore that transient signature cache, so start a fresh conversation
|
|
267
|
+
for Gemini tool workflows. Token counting on translated routes and provider
|
|
268
|
+
server tools are rejected explicitly; model capabilities and entitlements still
|
|
269
|
+
apply. Other harnesses use the preset's selected native protocol and require a
|
|
270
|
+
model compatible with it. OpenRouter provides its own Messages translation.
|
|
271
|
+
|
|
272
|
+
OpenCode inference receives Switcher's own user agent and a stable conversation
|
|
273
|
+
identifier. Native session headers are preserved from an explicit allowlist;
|
|
274
|
+
Claude's session metadata is used when available, with a per-launch fallback.
|
|
275
|
+
Credential and session handling is scoped to the exact OpenCode service URLs.
|
|
276
|
+
|
|
277
|
+
`bun run test:native-claude-providers` uses installed Claude Code with controlled
|
|
278
|
+
upstream fixtures and verifies actual file reads through Chat Completions,
|
|
279
|
+
Responses, Gemini, Go Messages, and OpenRouter Messages. This is separate from
|
|
280
|
+
paid-provider acceptance. Development live checks discovered all three catalogs
|
|
281
|
+
and received answers from OpenCode's free Chat endpoint; the saved paid keys
|
|
282
|
+
were rejected and the free endpoint subsequently rate-limited native testing.
|
|
283
|
+
|
|
284
|
+
Sources: [OpenCode Zen](https://opencode.ai/docs/zen/),
|
|
285
|
+
[OpenCode Go](https://opencode.ai/docs/go/), and
|
|
286
|
+
[OpenRouter Claude Code integration](https://openrouter.ai/docs/cookbook/coding-agents/claude-code-integration).
|
|
233
287
|
|
|
234
288
|
## Canonical API configuration
|
|
235
289
|
|
package/dist/cli/index.js
CHANGED
|
@@ -514,7 +514,7 @@ function canonicalPolicyJSON(value) {
|
|
|
514
514
|
}
|
|
515
515
|
|
|
516
516
|
// src/domain.ts
|
|
517
|
-
var VERSION = "0.2.
|
|
517
|
+
var VERSION = "0.2.1";
|
|
518
518
|
var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
519
519
|
var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
520
520
|
var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
@@ -1080,6 +1080,11 @@ var preset = (id, name, protocols, sources, alias) => parse2(providerPresetSchem
|
|
|
1080
1080
|
verification: "documented"
|
|
1081
1081
|
});
|
|
1082
1082
|
var providerPresets = [
|
|
1083
|
+
...["opencode", "opencode-go"].map((id) => preset(id, id === "opencode" ? "OpenCode Zen" : "OpenCode Go", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, id === "opencode" ? "https://opencode.ai/zen/v1" : "https://opencode.ai/zen/go/v1", {
|
|
1084
|
+
authStyle: protocol === "anthropic-messages" ? "x-api-key" : "bearer",
|
|
1085
|
+
catalogAuthStyle: "none",
|
|
1086
|
+
notes: ["Discovers the full live catalog. Claude requests are adapted to each model's documented native endpoint. Other harnesses require models compatible with their selected protocol. Go requires an active subscription and coding-agent session headers."]
|
|
1087
|
+
})), ["https://opencode.ai/docs/zen/", "https://opencode.ai/docs/go/"], "OPENCODE_API_KEY")),
|
|
1083
1088
|
preset("deepseek", "DeepSeek", [
|
|
1084
1089
|
route("openai-chat", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
1085
1090
|
route("openai-responses", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
@@ -2020,7 +2025,7 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
2020
2025
|
return { models: provider.manualModels, source: "manual", refreshedAt };
|
|
2021
2026
|
if (provider.catalogFormat === "none")
|
|
2022
2027
|
throw new Fault(422, "catalog_unsupported", "This provider has no documented model-list contract; configure manual models or an explicit catalog URL and parser.");
|
|
2023
|
-
const headers = { accept: "application/json" };
|
|
2028
|
+
const headers = { accept: "application/json", "user-agent": `hasna-switcher/${VERSION}` };
|
|
2024
2029
|
if (provider.catalogFormat === "fireworks" && !provider.catalogBaseUrl && !provider.catalogAccountId)
|
|
2025
2030
|
throw new Fault(422, "catalog_account_required", "Fireworks model discovery requires a catalog account ID or an explicit catalog URL.");
|
|
2026
2031
|
if (provider.catalogFormat === "fireworks" && !provider.catalogBaseUrl && new URL(provider.baseUrl).origin !== "https://api.fireworks.ai")
|
|
@@ -2079,6 +2084,7 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
2079
2084
|
inputModalities: strings(row.architecture?.input_modalities ?? row.input_modalities) ?? modalities(row.inference_metadata?.request_modality),
|
|
2080
2085
|
outputModalities: strings(row.architecture?.output_modalities ?? row.output_modalities) ?? modalities(row.inference_metadata?.response_modality),
|
|
2081
2086
|
supportedParameters: strings(row.supported_parameters),
|
|
2087
|
+
reasoningEfforts: row.reasoning?.supported_efforts,
|
|
2082
2088
|
...provider.catalogFormat === "gemini" && row.supportedGenerationMethods !== undefined ? { supportedGenerationMethods: row.supportedGenerationMethods } : {}
|
|
2083
2089
|
};
|
|
2084
2090
|
if (provider.catalogFormat === "mistral") {
|
|
@@ -2374,7 +2380,7 @@ var openapi_default = {
|
|
|
2374
2380
|
openapi: "3.0.3",
|
|
2375
2381
|
info: {
|
|
2376
2382
|
title: "Switcher API",
|
|
2377
|
-
version: "0.2.
|
|
2383
|
+
version: "0.2.1",
|
|
2378
2384
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2379
2385
|
},
|
|
2380
2386
|
security: [
|
|
@@ -7160,16 +7166,477 @@ function normalizeCodexDelegation(body) {
|
|
|
7160
7166
|
}) };
|
|
7161
7167
|
}
|
|
7162
7168
|
|
|
7169
|
+
// src/opencode.ts
|
|
7170
|
+
function rememberGeminiTool(part, state) {
|
|
7171
|
+
const id2 = `call_${crypto.randomUUID()}`;
|
|
7172
|
+
if (typeof part.thoughtSignature === "string") {
|
|
7173
|
+
if (part.thoughtSignature.length > 65536 || state.size >= 2000)
|
|
7174
|
+
throw new Fault(502, "opencode_signature_limit", "Gemini tool continuation metadata exceeded the launch limit.");
|
|
7175
|
+
state.set(id2, part.thoughtSignature);
|
|
7176
|
+
}
|
|
7177
|
+
return id2;
|
|
7178
|
+
}
|
|
7179
|
+
function openCodeLane(baseUrl) {
|
|
7180
|
+
const url = new URL(baseUrl);
|
|
7181
|
+
if (url.origin !== "https://opencode.ai")
|
|
7182
|
+
return;
|
|
7183
|
+
const path = url.pathname.replace(/\/+$/, "");
|
|
7184
|
+
return path === "/zen/v1" ? "zen" : path === "/zen/go/v1" ? "go" : undefined;
|
|
7185
|
+
}
|
|
7186
|
+
function openCodeWire(model, lane) {
|
|
7187
|
+
if (/^claude-/.test(model) || /^qwen3\.(5|6|7|8)-/.test(model) || lane === "go" && /^minimax-/.test(model))
|
|
7188
|
+
return "messages";
|
|
7189
|
+
if (/^(gpt-|grok-|muse-spark-)/.test(model))
|
|
7190
|
+
return "responses";
|
|
7191
|
+
if (/^gemini-/.test(model))
|
|
7192
|
+
return "gemini";
|
|
7193
|
+
return "chat";
|
|
7194
|
+
}
|
|
7195
|
+
function openCodeHeaders(baseUrl, source, body, launchSession) {
|
|
7196
|
+
if (!openCodeLane(baseUrl))
|
|
7197
|
+
return {};
|
|
7198
|
+
const result = { "user-agent": `hasna-switcher/${VERSION}` };
|
|
7199
|
+
const names = ["x-opencode-session", "x-client-session-id", "x-session-id", "session_id", "x-codex-thread-id"];
|
|
7200
|
+
for (const name of names) {
|
|
7201
|
+
const value = source.get(name);
|
|
7202
|
+
if (value && /^[A-Za-z0-9._:-]{1,200}$/.test(value))
|
|
7203
|
+
result[name] = value;
|
|
7204
|
+
}
|
|
7205
|
+
let session = names.map((name) => result[name]).find(Boolean);
|
|
7206
|
+
if (!session && typeof body.metadata?.user_id === "string") {
|
|
7207
|
+
try {
|
|
7208
|
+
const value = JSON.parse(body.metadata.user_id)?.session_id;
|
|
7209
|
+
if (typeof value === "string" && /^[A-Za-z0-9._:-]{1,200}$/.test(value))
|
|
7210
|
+
session = value;
|
|
7211
|
+
} catch {}
|
|
7212
|
+
session ??= /_session_([a-f0-9-]{36})$/i.exec(body.metadata.user_id)?.[1];
|
|
7213
|
+
}
|
|
7214
|
+
result["x-opencode-session"] = session ?? launchSession;
|
|
7215
|
+
return result;
|
|
7216
|
+
}
|
|
7217
|
+
function unsupported2(feature) {
|
|
7218
|
+
throw new Fault(422, "opencode_translation_unsupported", `The selected OpenCode model cannot receive this Claude feature: ${feature}.`);
|
|
7219
|
+
}
|
|
7220
|
+
function blocks(value) {
|
|
7221
|
+
if (typeof value === "string")
|
|
7222
|
+
return [{ type: "text", text: value }];
|
|
7223
|
+
if (Array.isArray(value) && value.every((item) => item && typeof item === "object"))
|
|
7224
|
+
return value;
|
|
7225
|
+
return unsupported2("malformed content");
|
|
7226
|
+
}
|
|
7227
|
+
function imageUrl(block) {
|
|
7228
|
+
if (block.source?.type === "url" && typeof block.source.url === "string")
|
|
7229
|
+
return block.source.url;
|
|
7230
|
+
if (block.source?.type === "base64" && typeof block.source.data === "string" && typeof block.source.media_type === "string")
|
|
7231
|
+
return `data:${block.source.media_type};base64,${block.source.data}`;
|
|
7232
|
+
return unsupported2("image source");
|
|
7233
|
+
}
|
|
7234
|
+
function textContent(value) {
|
|
7235
|
+
return blocks(value).map((block) => block.type === "text" && typeof block.text === "string" ? block.text : unsupported2("non-text tool result")).join(`
|
|
7236
|
+
`);
|
|
7237
|
+
}
|
|
7238
|
+
function toolResult(part) {
|
|
7239
|
+
const content = blocks(part.content ?? ""), images = content.filter((block) => block.type === "image");
|
|
7240
|
+
const text = textContent(content.filter((block) => block.type !== "image"));
|
|
7241
|
+
return { text: (part.is_error ? "[Tool error] " : "") + text, images };
|
|
7242
|
+
}
|
|
7243
|
+
function chatContent(value) {
|
|
7244
|
+
return blocks(value).flatMap((block) => {
|
|
7245
|
+
if (block.type === "text" && typeof block.text === "string")
|
|
7246
|
+
return [{ type: "text", text: block.text }];
|
|
7247
|
+
if (block.type === "image")
|
|
7248
|
+
return [{ type: "image_url", image_url: { url: imageUrl(block) } }];
|
|
7249
|
+
if (block.type === "thinking" || block.type === "redacted_thinking")
|
|
7250
|
+
return [];
|
|
7251
|
+
return unsupported2(`content block ${String(block.type)}`);
|
|
7252
|
+
});
|
|
7253
|
+
}
|
|
7254
|
+
function toChat(body) {
|
|
7255
|
+
const messages = [];
|
|
7256
|
+
if (body.system)
|
|
7257
|
+
messages.push({ role: "system", content: textContent(body.system) });
|
|
7258
|
+
if (!Array.isArray(body.messages))
|
|
7259
|
+
unsupported2("missing messages");
|
|
7260
|
+
for (const message of body.messages) {
|
|
7261
|
+
if (["system", "developer"].includes(message.role)) {
|
|
7262
|
+
messages.push({ role: "system", content: textContent(message.content) });
|
|
7263
|
+
continue;
|
|
7264
|
+
}
|
|
7265
|
+
if (!["user", "assistant"].includes(message.role))
|
|
7266
|
+
unsupported2("message role");
|
|
7267
|
+
const parts = blocks(message.content);
|
|
7268
|
+
if (message.role === "assistant") {
|
|
7269
|
+
const calls = parts.filter((part) => part.type === "tool_use").map((part) => ({ id: part.id, type: "function", function: { name: part.name, arguments: JSON.stringify(part.input ?? {}) } }));
|
|
7270
|
+
const content = chatContent(parts.filter((part) => part.type !== "tool_use"));
|
|
7271
|
+
const thinking = parts.filter((part) => part.type === "thinking").map((part) => part.thinking ?? "").join("");
|
|
7272
|
+
messages.push({ role: "assistant", content: content.length ? content : null, ...calls.length ? { tool_calls: calls } : {}, ...thinking ? { reasoning_content: thinking } : {} });
|
|
7273
|
+
} else {
|
|
7274
|
+
const images = [];
|
|
7275
|
+
for (const part of parts.filter((part2) => part2.type === "tool_result")) {
|
|
7276
|
+
const result2 = toolResult(part);
|
|
7277
|
+
messages.push({ role: "tool", tool_call_id: part.tool_use_id, content: result2.text });
|
|
7278
|
+
if (result2.images.length)
|
|
7279
|
+
images.push({ type: "text", text: `Images returned by tool call ${part.tool_use_id}:` }, ...result2.images);
|
|
7280
|
+
}
|
|
7281
|
+
const content = chatContent([...images, ...parts.filter((part) => part.type !== "tool_result")]);
|
|
7282
|
+
if (content.length)
|
|
7283
|
+
messages.push({ role: "user", content });
|
|
7284
|
+
}
|
|
7285
|
+
}
|
|
7286
|
+
const tools = body.tools?.map((tool) => {
|
|
7287
|
+
if (tool.type && tool.type !== "custom")
|
|
7288
|
+
unsupported2(`server tool ${tool.type}`);
|
|
7289
|
+
if (!tool.name || !tool.input_schema)
|
|
7290
|
+
unsupported2("tool schema");
|
|
7291
|
+
return { type: "function", function: { name: tool.name, description: tool.description, parameters: tool.input_schema } };
|
|
7292
|
+
});
|
|
7293
|
+
const choice = body.tool_choice;
|
|
7294
|
+
const tool_choice = !choice ? undefined : choice.type === "tool" ? { type: "function", function: { name: choice.name } } : choice.type === "any" ? "required" : ["auto", "none"].includes(choice.type) ? choice.type : unsupported2("tool choice");
|
|
7295
|
+
const result = {
|
|
7296
|
+
model: body.model,
|
|
7297
|
+
messages,
|
|
7298
|
+
max_tokens: body.max_tokens,
|
|
7299
|
+
stream: !!body.stream,
|
|
7300
|
+
...tools?.length ? { tools, tool_choice } : {},
|
|
7301
|
+
...choice?.disable_parallel_tool_use ? { parallel_tool_calls: false } : {}
|
|
7302
|
+
};
|
|
7303
|
+
for (const key of ["temperature", "top_p"])
|
|
7304
|
+
if (body[key] !== undefined)
|
|
7305
|
+
result[key] = body[key];
|
|
7306
|
+
if (body.stop_sequences)
|
|
7307
|
+
result.stop = body.stop_sequences;
|
|
7308
|
+
const effort = body.output_config?.effort;
|
|
7309
|
+
if (effort)
|
|
7310
|
+
result.reasoning_effort = effort;
|
|
7311
|
+
if (body.thinking?.type === "disabled")
|
|
7312
|
+
result.thinking = { type: "disabled" };
|
|
7313
|
+
else if (body.thinking?.type === "enabled" || body.thinking?.type === "adaptive")
|
|
7314
|
+
result.thinking = { type: "enabled" };
|
|
7315
|
+
if (result.stream)
|
|
7316
|
+
result.stream_options = { include_usage: true };
|
|
7317
|
+
return result;
|
|
7318
|
+
}
|
|
7319
|
+
function toResponses(chat) {
|
|
7320
|
+
const input = [];
|
|
7321
|
+
let instructions = "";
|
|
7322
|
+
for (const message of chat.messages) {
|
|
7323
|
+
if (message.role === "system") {
|
|
7324
|
+
instructions += (instructions ? `
|
|
7325
|
+
|
|
7326
|
+
` : "") + message.content;
|
|
7327
|
+
continue;
|
|
7328
|
+
}
|
|
7329
|
+
if (message.role === "tool") {
|
|
7330
|
+
input.push({ type: "function_call_output", call_id: message.tool_call_id, output: message.content });
|
|
7331
|
+
continue;
|
|
7332
|
+
}
|
|
7333
|
+
if (message.content?.length)
|
|
7334
|
+
input.push({ role: message.role, content: message.content.map((part) => part.type === "image_url" ? { type: "input_image", image_url: part.image_url.url } : { type: message.role === "assistant" ? "output_text" : "input_text", text: part.text }) });
|
|
7335
|
+
for (const call of message.tool_calls ?? [])
|
|
7336
|
+
input.push({ type: "function_call", call_id: call.id, name: call.function.name, arguments: call.function.arguments });
|
|
7337
|
+
}
|
|
7338
|
+
const result = { model: chat.model, input, instructions, stream: chat.stream, max_output_tokens: chat.max_tokens, store: false };
|
|
7339
|
+
if (chat.tools)
|
|
7340
|
+
result.tools = chat.tools.map((tool) => ({ type: "function", ...tool.function }));
|
|
7341
|
+
if (chat.tool_choice)
|
|
7342
|
+
result.tool_choice = typeof chat.tool_choice === "string" ? chat.tool_choice : { type: "function", name: chat.tool_choice.function.name };
|
|
7343
|
+
for (const key of ["temperature", "top_p", "parallel_tool_calls"])
|
|
7344
|
+
if (chat[key] !== undefined)
|
|
7345
|
+
result[key] = chat[key];
|
|
7346
|
+
if (chat.reasoning_effort || chat.thinking?.type === "disabled")
|
|
7347
|
+
result.reasoning = { effort: chat.thinking?.type === "disabled" ? "none" : chat.reasoning_effort };
|
|
7348
|
+
if (chat.stop)
|
|
7349
|
+
unsupported2("stop sequences on Responses");
|
|
7350
|
+
return result;
|
|
7351
|
+
}
|
|
7352
|
+
function toGemini(chat, state) {
|
|
7353
|
+
const contents = [], names = new Map;
|
|
7354
|
+
let systemInstruction;
|
|
7355
|
+
for (const message of chat.messages) {
|
|
7356
|
+
if (message.role === "system") {
|
|
7357
|
+
systemInstruction ??= { parts: [] };
|
|
7358
|
+
systemInstruction.parts.push({ text: message.content });
|
|
7359
|
+
continue;
|
|
7360
|
+
}
|
|
7361
|
+
if (message.role === "tool") {
|
|
7362
|
+
const name = names.get(message.tool_call_id);
|
|
7363
|
+
if (!name)
|
|
7364
|
+
unsupported2("unpaired tool result");
|
|
7365
|
+
contents.push({ role: "user", parts: [{ functionResponse: { name, response: { result: message.content } } }] });
|
|
7366
|
+
continue;
|
|
7367
|
+
}
|
|
7368
|
+
const parts = (message.content ?? []).map((part) => {
|
|
7369
|
+
if (part.type === "text")
|
|
7370
|
+
return { text: part.text };
|
|
7371
|
+
const url = part.image_url.url, match = /^data:([^;]+);base64,(.+)$/s.exec(url);
|
|
7372
|
+
return match ? { inlineData: { mimeType: match[1], data: match[2] } } : { fileData: { fileUri: url } };
|
|
7373
|
+
});
|
|
7374
|
+
for (const call of message.tool_calls ?? []) {
|
|
7375
|
+
names.set(call.id, call.function.name);
|
|
7376
|
+
parts.push({ functionCall: { name: call.function.name, args: JSON.parse(call.function.arguments) }, ...state.has(call.id) ? { thoughtSignature: state.get(call.id) } : {} });
|
|
7377
|
+
}
|
|
7378
|
+
contents.push({ role: message.role === "assistant" ? "model" : "user", parts });
|
|
7379
|
+
}
|
|
7380
|
+
const generationConfig = { maxOutputTokens: chat.max_tokens };
|
|
7381
|
+
if (chat.temperature !== undefined)
|
|
7382
|
+
generationConfig.temperature = chat.temperature;
|
|
7383
|
+
if (chat.top_p !== undefined)
|
|
7384
|
+
generationConfig.topP = chat.top_p;
|
|
7385
|
+
if (chat.stop)
|
|
7386
|
+
generationConfig.stopSequences = chat.stop;
|
|
7387
|
+
if (chat.reasoning_effort)
|
|
7388
|
+
generationConfig.thinkingConfig = { thinkingLevel: chat.reasoning_effort.toUpperCase() };
|
|
7389
|
+
const result = { contents, systemInstruction, generationConfig };
|
|
7390
|
+
if (chat.tools)
|
|
7391
|
+
result.tools = [{ functionDeclarations: chat.tools.map((tool) => ({ name: tool.function.name, description: tool.function.description, parametersJsonSchema: tool.function.parameters })) }];
|
|
7392
|
+
if (chat.tool_choice)
|
|
7393
|
+
result.toolConfig = { functionCallingConfig: typeof chat.tool_choice === "object" ? { mode: "ANY", allowedFunctionNames: [chat.tool_choice.function.name] } : { mode: { auto: "AUTO", required: "ANY", none: "NONE" }[chat.tool_choice] } };
|
|
7394
|
+
return result;
|
|
7395
|
+
}
|
|
7396
|
+
var stopReason = (reason, hasTools) => hasTools ? "tool_use" : ["length", "max_tokens", "max_output_tokens", "MAX_TOKENS"].includes(reason ?? "") ? "max_tokens" : "end_turn";
|
|
7397
|
+
function usage(data, wire) {
|
|
7398
|
+
const value = wire === "gemini" ? data.usageMetadata ?? {} : data.usage ?? {};
|
|
7399
|
+
return {
|
|
7400
|
+
input_tokens: value.input_tokens ?? value.prompt_tokens ?? value.promptTokenCount ?? 0,
|
|
7401
|
+
output_tokens: value.output_tokens ?? value.completion_tokens ?? (value.candidatesTokenCount ?? 0) + (value.thoughtsTokenCount ?? 0)
|
|
7402
|
+
};
|
|
7403
|
+
}
|
|
7404
|
+
function toolInput(value) {
|
|
7405
|
+
try {
|
|
7406
|
+
return JSON.parse(value || "{}");
|
|
7407
|
+
} catch {
|
|
7408
|
+
throw new Fault(502, "invalid_provider_response", "Provider returned malformed tool arguments.");
|
|
7409
|
+
}
|
|
7410
|
+
}
|
|
7411
|
+
function fromJson(data, wire, model, state) {
|
|
7412
|
+
const content = [];
|
|
7413
|
+
let reason;
|
|
7414
|
+
if (wire === "chat") {
|
|
7415
|
+
const choice = data.choices?.[0], message = choice?.message;
|
|
7416
|
+
if (!message)
|
|
7417
|
+
throw new Fault(502, "invalid_provider_response", "Provider returned no completion.");
|
|
7418
|
+
if (message.reasoning_content ?? message.reasoning)
|
|
7419
|
+
content.push({ type: "thinking", thinking: message.reasoning_content ?? message.reasoning, signature: "" });
|
|
7420
|
+
if (message.content)
|
|
7421
|
+
content.push({ type: "text", text: message.content });
|
|
7422
|
+
for (const tool of message.tool_calls ?? [])
|
|
7423
|
+
content.push({ type: "tool_use", id: tool.id, name: tool.function.name, input: toolInput(tool.function.arguments) });
|
|
7424
|
+
reason = choice.finish_reason;
|
|
7425
|
+
} else if (wire === "responses") {
|
|
7426
|
+
if (!["completed", "incomplete"].includes(data.status))
|
|
7427
|
+
throw new Fault(502, "invalid_provider_response", "Provider response did not complete.");
|
|
7428
|
+
for (const item of data.output ?? []) {
|
|
7429
|
+
if (item.type === "message") {
|
|
7430
|
+
for (const part of item.content ?? [])
|
|
7431
|
+
if (part.type === "output_text")
|
|
7432
|
+
content.push({ type: "text", text: part.text });
|
|
7433
|
+
}
|
|
7434
|
+
if (item.type === "function_call")
|
|
7435
|
+
content.push({ type: "tool_use", id: item.call_id, name: item.name, input: toolInput(item.arguments) });
|
|
7436
|
+
if (item.type === "reasoning")
|
|
7437
|
+
for (const part of item.summary ?? [])
|
|
7438
|
+
content.push({ type: "thinking", thinking: part.text, signature: "" });
|
|
7439
|
+
}
|
|
7440
|
+
reason = data.incomplete_details?.reason;
|
|
7441
|
+
} else {
|
|
7442
|
+
const candidate = data.candidates?.[0];
|
|
7443
|
+
if (!candidate)
|
|
7444
|
+
throw new Fault(502, "invalid_provider_response", "Provider returned no candidate.");
|
|
7445
|
+
for (const part of candidate.content?.parts ?? []) {
|
|
7446
|
+
if (part.text)
|
|
7447
|
+
content.push(part.thought ? { type: "thinking", thinking: part.text, signature: "" } : { type: "text", text: part.text });
|
|
7448
|
+
if (part.functionCall)
|
|
7449
|
+
content.push({ type: "tool_use", id: rememberGeminiTool(part, state), name: part.functionCall.name, input: part.functionCall.args ?? {} });
|
|
7450
|
+
}
|
|
7451
|
+
reason = candidate.finishReason;
|
|
7452
|
+
}
|
|
7453
|
+
return {
|
|
7454
|
+
id: `msg_${crypto.randomUUID()}`,
|
|
7455
|
+
type: "message",
|
|
7456
|
+
role: "assistant",
|
|
7457
|
+
model: data.model ?? data.modelVersion ?? model,
|
|
7458
|
+
content,
|
|
7459
|
+
stop_reason: stopReason(reason, content.some((part) => part.type === "tool_use")),
|
|
7460
|
+
stop_sequence: null,
|
|
7461
|
+
usage: usage(data, wire)
|
|
7462
|
+
};
|
|
7463
|
+
}
|
|
7464
|
+
function fromStream(response, wire, model, state) {
|
|
7465
|
+
const reader = response.body.getReader(), decoder = new TextDecoder, encoder = new TextEncoder;
|
|
7466
|
+
let buffer = "", ended = false, started = false, index = 0, reason;
|
|
7467
|
+
let tokens = { input_tokens: 0, output_tokens: 0 };
|
|
7468
|
+
const active = new Map;
|
|
7469
|
+
const stream = new ReadableStream({
|
|
7470
|
+
async pull(controller) {
|
|
7471
|
+
const send = (event) => controller.enqueue(encoder.encode(`event: ${event.type}
|
|
7472
|
+
data: ${JSON.stringify(event)}
|
|
7473
|
+
|
|
7474
|
+
`));
|
|
7475
|
+
const start = () => {
|
|
7476
|
+
if (!started) {
|
|
7477
|
+
started = true;
|
|
7478
|
+
send({ type: "message_start", message: { id: `msg_${crypto.randomUUID()}`, type: "message", role: "assistant", model, content: [], stop_reason: null, stop_sequence: null, usage: tokens } });
|
|
7479
|
+
}
|
|
7480
|
+
};
|
|
7481
|
+
const part = (key, block, delta) => {
|
|
7482
|
+
start();
|
|
7483
|
+
let current = active.get(key);
|
|
7484
|
+
if (!current) {
|
|
7485
|
+
current = { index: index++, tool: block.type === "tool_use" };
|
|
7486
|
+
active.set(key, current);
|
|
7487
|
+
send({ type: "content_block_start", index: current.index, content_block: block });
|
|
7488
|
+
}
|
|
7489
|
+
if (delta)
|
|
7490
|
+
send({ type: "content_block_delta", index: current.index, delta });
|
|
7491
|
+
};
|
|
7492
|
+
const text = (value, thinking = false) => {
|
|
7493
|
+
if (value)
|
|
7494
|
+
part(thinking ? "thinking" : "text", thinking ? { type: "thinking", thinking: "", signature: "" } : { type: "text", text: "" }, thinking ? { type: "thinking_delta", thinking: value } : { type: "text_delta", text: value });
|
|
7495
|
+
};
|
|
7496
|
+
const finish = () => {
|
|
7497
|
+
start();
|
|
7498
|
+
for (const item of active.values())
|
|
7499
|
+
send({ type: "content_block_stop", index: item.index });
|
|
7500
|
+
send({ type: "message_delta", delta: { stop_reason: stopReason(reason, [...active.values()].some((item) => item.tool)), stop_sequence: null }, usage: tokens });
|
|
7501
|
+
send({ type: "message_stop" });
|
|
7502
|
+
ended = true;
|
|
7503
|
+
controller.close();
|
|
7504
|
+
reader.cancel().catch(() => {});
|
|
7505
|
+
};
|
|
7506
|
+
try {
|
|
7507
|
+
const chunk = await reader.read();
|
|
7508
|
+
if (chunk.done) {
|
|
7509
|
+
if (!ended)
|
|
7510
|
+
throw new Error("OpenCode stream ended before completion");
|
|
7511
|
+
return;
|
|
7512
|
+
}
|
|
7513
|
+
buffer = (buffer + decoder.decode(chunk.value, { stream: true })).replace(/\r\n/g, `
|
|
7514
|
+
`);
|
|
7515
|
+
if (buffer.length > 4 * 1024 * 1024)
|
|
7516
|
+
throw new Error("OpenCode SSE event too large");
|
|
7517
|
+
let end;
|
|
7518
|
+
while (!ended && (end = buffer.indexOf(`
|
|
7519
|
+
|
|
7520
|
+
`)) >= 0) {
|
|
7521
|
+
const frame = buffer.slice(0, end);
|
|
7522
|
+
buffer = buffer.slice(end + 2);
|
|
7523
|
+
const payload = frame.split(`
|
|
7524
|
+
`).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join(`
|
|
7525
|
+
`);
|
|
7526
|
+
if (!payload)
|
|
7527
|
+
continue;
|
|
7528
|
+
if (payload === "[DONE]") {
|
|
7529
|
+
if (wire !== "chat" || !reason)
|
|
7530
|
+
throw new Error("Missing completion reason");
|
|
7531
|
+
finish();
|
|
7532
|
+
break;
|
|
7533
|
+
}
|
|
7534
|
+
const data = JSON.parse(payload);
|
|
7535
|
+
if (data.error || data.type === "error" || data.type === "response.failed")
|
|
7536
|
+
throw new Error("OpenCode provider stream failed");
|
|
7537
|
+
if (wire === "chat") {
|
|
7538
|
+
if (data.usage)
|
|
7539
|
+
tokens = usage(data, wire);
|
|
7540
|
+
const choice = data.choices?.[0], delta = choice?.delta;
|
|
7541
|
+
if (choice?.finish_reason)
|
|
7542
|
+
reason = choice.finish_reason;
|
|
7543
|
+
if (!delta)
|
|
7544
|
+
continue;
|
|
7545
|
+
text(delta.reasoning_content ?? delta.reasoning ?? "", true);
|
|
7546
|
+
text(delta.content ?? "");
|
|
7547
|
+
for (const call of delta.tool_calls ?? []) {
|
|
7548
|
+
const key = `tool-${call.index}`;
|
|
7549
|
+
if (!active.has(key) && (!call.id || !call.function?.name))
|
|
7550
|
+
throw new Error("Incomplete tool start");
|
|
7551
|
+
part(key, { type: "tool_use", id: call.id, name: call.function?.name, input: {} }, call.function?.arguments ? { type: "input_json_delta", partial_json: call.function.arguments } : undefined);
|
|
7552
|
+
}
|
|
7553
|
+
} else if (wire === "responses") {
|
|
7554
|
+
if (data.type === "response.output_text.delta")
|
|
7555
|
+
text(data.delta);
|
|
7556
|
+
if (data.type === "response.reasoning_summary_text.delta")
|
|
7557
|
+
text(data.delta, true);
|
|
7558
|
+
if (data.type === "response.output_item.added" && data.item?.type === "function_call")
|
|
7559
|
+
part(`tool-${data.output_index}`, { type: "tool_use", id: data.item.call_id, name: data.item.name, input: {} });
|
|
7560
|
+
if (data.type === "response.function_call_arguments.delta") {
|
|
7561
|
+
const current = active.get(`tool-${data.output_index}`);
|
|
7562
|
+
if (!current)
|
|
7563
|
+
throw new Error("Missing tool start");
|
|
7564
|
+
send({ type: "content_block_delta", index: current.index, delta: { type: "input_json_delta", partial_json: data.delta } });
|
|
7565
|
+
}
|
|
7566
|
+
if (["response.completed", "response.incomplete"].includes(data.type)) {
|
|
7567
|
+
tokens = usage(data.response ?? {}, wire);
|
|
7568
|
+
reason = data.response?.incomplete_details?.reason;
|
|
7569
|
+
finish();
|
|
7570
|
+
}
|
|
7571
|
+
} else {
|
|
7572
|
+
if (data.usageMetadata)
|
|
7573
|
+
tokens = usage(data, wire);
|
|
7574
|
+
const candidate = data.candidates?.[0];
|
|
7575
|
+
for (const item of candidate?.content?.parts ?? []) {
|
|
7576
|
+
if (item.text)
|
|
7577
|
+
text(item.text, !!item.thought);
|
|
7578
|
+
if (item.functionCall)
|
|
7579
|
+
part(`tool-${index}`, { type: "tool_use", id: rememberGeminiTool(item, state), name: item.functionCall.name, input: {} }, { type: "input_json_delta", partial_json: JSON.stringify(item.functionCall.args ?? {}) });
|
|
7580
|
+
}
|
|
7581
|
+
if (candidate?.finishReason) {
|
|
7582
|
+
reason = candidate.finishReason;
|
|
7583
|
+
finish();
|
|
7584
|
+
}
|
|
7585
|
+
}
|
|
7586
|
+
}
|
|
7587
|
+
if (!ended)
|
|
7588
|
+
controller.enqueue(encoder.encode(`: upstream activity
|
|
7589
|
+
|
|
7590
|
+
`));
|
|
7591
|
+
} catch (error) {
|
|
7592
|
+
ended = true;
|
|
7593
|
+
controller.error(error);
|
|
7594
|
+
reader.cancel().catch(() => {});
|
|
7595
|
+
}
|
|
7596
|
+
},
|
|
7597
|
+
async cancel() {
|
|
7598
|
+
ended = true;
|
|
7599
|
+
await reader.cancel().catch(() => {});
|
|
7600
|
+
}
|
|
7601
|
+
});
|
|
7602
|
+
return new Response(stream, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } });
|
|
7603
|
+
}
|
|
7604
|
+
function prepareOpenCodeMessages(baseUrl, body, suffix, credential, state = new Map) {
|
|
7605
|
+
const lane = openCodeLane(baseUrl);
|
|
7606
|
+
if (!lane)
|
|
7607
|
+
return;
|
|
7608
|
+
const wire = openCodeWire(body.model, lane);
|
|
7609
|
+
if (wire === "messages")
|
|
7610
|
+
return;
|
|
7611
|
+
if (suffix !== "/messages")
|
|
7612
|
+
unsupported2("token counting on a translated model");
|
|
7613
|
+
const chat = toChat(body), outgoing = wire === "responses" ? toResponses(chat) : wire === "gemini" ? toGemini(chat, state) : chat;
|
|
7614
|
+
const path = wire === "responses" ? "/responses" : wire === "gemini" ? `/models/${encodeURIComponent(body.model)}:${body.stream ? "streamGenerateContent?alt=sse" : "generateContent"}` : "/chat/completions";
|
|
7615
|
+
const auth = credential ? wire === "gemini" ? { "x-goog-api-key": credential } : { authorization: `Bearer ${credential}` } : {};
|
|
7616
|
+
return { path, body: outgoing, auth, async response(response) {
|
|
7617
|
+
if (!response.ok || !response.body)
|
|
7618
|
+
return response;
|
|
7619
|
+
if (body.stream) {
|
|
7620
|
+
if (!response.headers.get("content-type")?.includes("text/event-stream"))
|
|
7621
|
+
throw new Fault(502, "invalid_provider_response", "Provider did not return an event stream.");
|
|
7622
|
+
return fromStream(response, wire, body.model, state);
|
|
7623
|
+
}
|
|
7624
|
+
return Response.json(fromJson(await boundedJson(response), wire, body.model, state));
|
|
7625
|
+
} };
|
|
7626
|
+
}
|
|
7627
|
+
|
|
7163
7628
|
// src/inference-gateway.ts
|
|
7164
7629
|
import { createHash as createHash5, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
7165
7630
|
var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
|
|
7166
7631
|
function createInferenceGateway(input, timing = {}) {
|
|
7167
7632
|
const token = crypto.randomUUID() + crypto.randomUUID();
|
|
7633
|
+
const openCodeSession = crypto.randomUUID();
|
|
7634
|
+
const openCodeState = new Map;
|
|
7168
7635
|
const digest = (value) => createHash5("sha256").update(value).digest();
|
|
7169
7636
|
const expected = digest(token), policy = input.compiledPolicy;
|
|
7170
7637
|
const known = new Set(input.models.map((m) => m.id));
|
|
7171
7638
|
const safeModel = (value) => typeof value === "string" && value !== input.credential && (known.has(value) || Object.hasOwn(policy.aliases, value)) ? value : "<unrecognized>";
|
|
7172
|
-
const fail = (status, code) => Response.json({ error: { type: "switcher_model_policy", code, message: code === "model_not_allowed" ? "This model is outside the launch policy. Select it with switcher launch --model or explicitly assign an allowed role model." : `Switcher inference gateway: ${code}.` } }, { status });
|
|
7639
|
+
const fail = (status, code, message) => Response.json({ error: { type: "switcher_model_policy", code, message: message ?? (code === "model_not_allowed" ? "This model is outside the launch policy. Select it with switcher launch --model or explicitly assign an allowed role model." : `Switcher inference gateway: ${code}.`) } }, { status });
|
|
7173
7640
|
let closing = false, stopped;
|
|
7174
7641
|
const active = new Set;
|
|
7175
7642
|
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
|
|
@@ -7256,6 +7723,7 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7256
7723
|
const signal = activity.fetchOptions.signal;
|
|
7257
7724
|
server2.timeout(request, 0);
|
|
7258
7725
|
const headers = { "content-type": "application/json" };
|
|
7726
|
+
Object.assign(headers, openCodeHeaders(input.baseUrl, request.headers, body, openCodeSession));
|
|
7259
7727
|
if (input.credential) {
|
|
7260
7728
|
const [name, value] = gemini ? ["x-goog-api-key", input.credential] : authHeader(input.authStyle ?? "bearer", input.credential);
|
|
7261
7729
|
headers[name] = value;
|
|
@@ -7290,9 +7758,18 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7290
7758
|
const guidance = renderModelGuidance({ harness: input.harness, providerId: input.providerId, baseUrl: input.baseUrl, model, compiled: policy, catalogPath: input.catalogPath });
|
|
7291
7759
|
const compatible2 = input.harness === "codex" && input.protocol === "openai-responses" && new URL(input.baseUrl).hostname !== "api.openai.com" ? normalizeCodexDelegation(payload) : payload;
|
|
7292
7760
|
const outgoing = injectModelGuidance(input.protocol, compatible2, guidance, match?.[2]);
|
|
7293
|
-
const
|
|
7761
|
+
const translated = input.protocol === "anthropic-messages" ? prepareOpenCodeMessages(input.baseUrl, outgoing, suffix, input.credential, openCodeState) : undefined;
|
|
7762
|
+
const path = translated?.path ?? (gemini ? `/models/${encodeURIComponent(model)}:${match[2]}${url.search}` : suffix + (betaQuery ? "?beta=true" : ""));
|
|
7763
|
+
const upstreamHeaders = { ...headers };
|
|
7764
|
+
if (translated) {
|
|
7765
|
+
delete upstreamHeaders["x-api-key"];
|
|
7766
|
+
delete upstreamHeaders.authorization;
|
|
7767
|
+
delete upstreamHeaders["anthropic-version"];
|
|
7768
|
+
delete upstreamHeaders["anthropic-beta"];
|
|
7769
|
+
Object.assign(upstreamHeaders, translated.auth);
|
|
7770
|
+
}
|
|
7294
7771
|
try {
|
|
7295
|
-
response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(outgoing), redirect: "manual", ...activity.fetchOptions }));
|
|
7772
|
+
response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers: upstreamHeaders, body: JSON.stringify(translated?.body ?? outgoing), redirect: "manual", ...activity.fetchOptions }));
|
|
7296
7773
|
} catch {
|
|
7297
7774
|
current.reason = activity.timedOut() ? "provider_idle_timeout" : signal.aborted ? "request_cancelled" : "network_error";
|
|
7298
7775
|
if (!signal.aborted && attempt + 1 < candidates.length)
|
|
@@ -7307,6 +7784,8 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7307
7784
|
response = undefined;
|
|
7308
7785
|
continue;
|
|
7309
7786
|
}
|
|
7787
|
+
if (translated)
|
|
7788
|
+
response = await activity.run(() => translated.response(response));
|
|
7310
7789
|
break;
|
|
7311
7790
|
}
|
|
7312
7791
|
if (!response)
|
|
@@ -7318,7 +7797,11 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7318
7797
|
release();
|
|
7319
7798
|
if (overflow)
|
|
7320
7799
|
return Response.json({ type: "error", error: { type: "invalid_request_error", code: "context_length_exceeded", message: "prompt is too long: the provider context window was exceeded. Compact the conversation or start a new session." } }, { status: 400 });
|
|
7321
|
-
|
|
7800
|
+
const rejected = fail(response.status >= 300 && response.status < 400 ? 502 : response.status, `upstream_http_${response.status}`);
|
|
7801
|
+
const retryAfter = response.headers.get("retry-after");
|
|
7802
|
+
if ((response.status === 429 || response.status === 503) && retryAfter && retryAfter.length <= 128 && (/^\d+$/.test(retryAfter) || Number.isFinite(Date.parse(retryAfter))))
|
|
7803
|
+
rejected.headers.set("retry-after", retryAfter);
|
|
7804
|
+
return rejected;
|
|
7322
7805
|
}
|
|
7323
7806
|
if (!response.body) {
|
|
7324
7807
|
release();
|
|
@@ -7369,7 +7852,7 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7369
7852
|
else if (activity.timedOut())
|
|
7370
7853
|
current.reason = "provider_idle_timeout";
|
|
7371
7854
|
release();
|
|
7372
|
-
return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : "provider_request_failed");
|
|
7855
|
+
return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : "provider_request_failed", error instanceof Fault && error.code === "opencode_translation_unsupported" ? error.message : undefined);
|
|
7373
7856
|
}
|
|
7374
7857
|
} });
|
|
7375
7858
|
return { baseUrl: new URL(input.protocol === "gemini-generate-content" ? "v1beta" : "v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
|
|
@@ -7470,9 +7953,9 @@ function compileCodexModelPolicy(input) {
|
|
|
7470
7953
|
const policy = modelPolicySchema.parse(input.policy ?? {});
|
|
7471
7954
|
const subagentModel = policy.roles?.subagent ?? input.model;
|
|
7472
7955
|
const reviewModel = policy.roles?.review ?? input.model;
|
|
7473
|
-
const
|
|
7474
|
-
if (
|
|
7475
|
-
throw new Error(`Codex does not expose role controls for: ${
|
|
7956
|
+
const unsupported3 = ["fast", "planning", "summary", "compaction", "weak", "editor"].filter((role) => policy.roles?.[role] !== undefined && policy.roles?.[role] !== input.model);
|
|
7957
|
+
if (unsupported3.length)
|
|
7958
|
+
throw new Error(`Codex does not expose role controls for: ${unsupported3.join(", ")}.`);
|
|
7476
7959
|
const agents = [];
|
|
7477
7960
|
const ignoredUntrustedAgents = [];
|
|
7478
7961
|
for (const [name, definition] of Object.entries(input.agents ?? {})) {
|
|
@@ -9728,6 +10211,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9728
10211
|
env.ANTHROPIC_MODEL = input.model;
|
|
9729
10212
|
env.ANTHROPIC_DEFAULT_MODEL = input.model;
|
|
9730
10213
|
env.CLAUDE_CODE_SUBAGENT_MODEL = input.compiledPolicy?.roles.subagent ?? input.model;
|
|
10214
|
+
env.ANTHROPIC_API_KEY = "";
|
|
10215
|
+
env.ANTHROPIC_AUTH_TOKEN = "";
|
|
9731
10216
|
env[input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"] = input.credential ?? "switcher-local-no-auth";
|
|
9732
10217
|
const file2 = await jsonFile(input.stateDir, "claude-settings.json", { modelPicker: { replaceBuiltInOptions: true, options: input.models.map((m) => ({ model: m.id, label: m.name, description: m.description?.slice(0, 300) })) } });
|
|
9733
10218
|
configPaths.push(file2);
|
|
@@ -10080,9 +10565,9 @@ async function prepareHarnessLaunch(input) {
|
|
|
10080
10565
|
input = { ...input, models: input.models.filter((model3) => !modelExpired(model3)) };
|
|
10081
10566
|
const nativePolicy = compileNativeModelPolicy({ harness: input.harness, mainModel: input.model, roles: compiledPolicy.roles, version: input.version });
|
|
10082
10567
|
const specialized = new Set(["opencode", "opencode2", "gemini", "hermes"]);
|
|
10083
|
-
const
|
|
10084
|
-
if (
|
|
10085
|
-
throw new Error(`${input.harness} does not expose native model controls for: ${
|
|
10568
|
+
const unsupported3 = specialized.has(input.harness) ? [] : nativePolicy.unsupportedRoles.filter((role) => role !== "main" && compiledPolicy.roles[role] !== input.model);
|
|
10569
|
+
if (unsupported3.length)
|
|
10570
|
+
throw new Error(`${input.harness} does not expose native model controls for: ${unsupported3.join(", ")}.`);
|
|
10086
10571
|
await mkdir10(input.stateDir, { recursive: true, mode: 448 });
|
|
10087
10572
|
const catalogPath = await jsonFile(input.stateDir, `switcher-model-policy-${randomUUID4()}.json`, { policy: compiledPolicy, models: input.models });
|
|
10088
10573
|
const bridge = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
package/dist/domain.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { type RoutingEvent } from "./model-policy-schema";
|
|
|
3
3
|
export { modelPolicySchema, routingEventSchema, routingEventsSchema } from "./model-policy-schema";
|
|
4
4
|
export type { ModelPolicy, RoutingEvent } from "./model-policy-schema";
|
|
5
5
|
export type { AuthStyle } from "./auth";
|
|
6
|
-
export declare const VERSION = "0.2.
|
|
6
|
+
export declare const VERSION = "0.2.1";
|
|
7
7
|
export declare const harnessSchema: z.ZodEnum<["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]>;
|
|
8
8
|
export declare const protocolSchema: z.ZodEnum<["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]>;
|
|
9
9
|
export declare const idSchema: z.ZodString;
|
package/dist/index.js
CHANGED
|
@@ -234,6 +234,11 @@ var preset = (id, name, protocols, sources, alias) => parse(providerPresetSchema
|
|
|
234
234
|
verification: "documented"
|
|
235
235
|
});
|
|
236
236
|
var providerPresets = [
|
|
237
|
+
...["opencode", "opencode-go"].map((id) => preset(id, id === "opencode" ? "OpenCode Zen" : "OpenCode Go", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, id === "opencode" ? "https://opencode.ai/zen/v1" : "https://opencode.ai/zen/go/v1", {
|
|
238
|
+
authStyle: protocol === "anthropic-messages" ? "x-api-key" : "bearer",
|
|
239
|
+
catalogAuthStyle: "none",
|
|
240
|
+
notes: ["Discovers the full live catalog. Claude requests are adapted to each model's documented native endpoint. Other harnesses require models compatible with their selected protocol. Go requires an active subscription and coding-agent session headers."]
|
|
241
|
+
})), ["https://opencode.ai/docs/zen/", "https://opencode.ai/docs/go/"], "OPENCODE_API_KEY")),
|
|
237
242
|
preset("deepseek", "DeepSeek", [
|
|
238
243
|
route("openai-chat", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
239
244
|
route("openai-responses", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
package/dist/mcp/index.js
CHANGED
|
@@ -69,7 +69,7 @@ function canonicalPolicyJSON(value) {
|
|
|
69
69
|
}
|
|
70
70
|
|
|
71
71
|
// src/domain.ts
|
|
72
|
-
var VERSION = "0.2.
|
|
72
|
+
var VERSION = "0.2.1";
|
|
73
73
|
var harnessSchema = z3.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
74
74
|
var protocolSchema = z3.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
75
75
|
var idSchema = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
@@ -268,6 +268,11 @@ var preset = (id, name, protocols, sources, alias) => parse(providerPresetSchema
|
|
|
268
268
|
verification: "documented"
|
|
269
269
|
});
|
|
270
270
|
var providerPresets = [
|
|
271
|
+
...["opencode", "opencode-go"].map((id) => preset(id, id === "opencode" ? "OpenCode Zen" : "OpenCode Go", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, id === "opencode" ? "https://opencode.ai/zen/v1" : "https://opencode.ai/zen/go/v1", {
|
|
272
|
+
authStyle: protocol === "anthropic-messages" ? "x-api-key" : "bearer",
|
|
273
|
+
catalogAuthStyle: "none",
|
|
274
|
+
notes: ["Discovers the full live catalog. Claude requests are adapted to each model's documented native endpoint. Other harnesses require models compatible with their selected protocol. Go requires an active subscription and coding-agent session headers."]
|
|
275
|
+
})), ["https://opencode.ai/docs/zen/", "https://opencode.ai/docs/go/"], "OPENCODE_API_KEY")),
|
|
271
276
|
preset("deepseek", "DeepSeek", [
|
|
272
277
|
route("openai-chat", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
273
278
|
route("openai-responses", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
@@ -830,7 +835,7 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
830
835
|
return { models: provider.manualModels, source: "manual", refreshedAt };
|
|
831
836
|
if (provider.catalogFormat === "none")
|
|
832
837
|
throw new Fault(422, "catalog_unsupported", "This provider has no documented model-list contract; configure manual models or an explicit catalog URL and parser.");
|
|
833
|
-
const headers = { accept: "application/json" };
|
|
838
|
+
const headers = { accept: "application/json", "user-agent": `hasna-switcher/${VERSION}` };
|
|
834
839
|
if (provider.catalogFormat === "fireworks" && !provider.catalogBaseUrl && !provider.catalogAccountId)
|
|
835
840
|
throw new Fault(422, "catalog_account_required", "Fireworks model discovery requires a catalog account ID or an explicit catalog URL.");
|
|
836
841
|
if (provider.catalogFormat === "fireworks" && !provider.catalogBaseUrl && new URL(provider.baseUrl).origin !== "https://api.fireworks.ai")
|
|
@@ -889,6 +894,7 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
889
894
|
inputModalities: strings(row.architecture?.input_modalities ?? row.input_modalities) ?? modalities(row.inference_metadata?.request_modality),
|
|
890
895
|
outputModalities: strings(row.architecture?.output_modalities ?? row.output_modalities) ?? modalities(row.inference_metadata?.response_modality),
|
|
891
896
|
supportedParameters: strings(row.supported_parameters),
|
|
897
|
+
reasoningEfforts: row.reasoning?.supported_efforts,
|
|
892
898
|
...provider.catalogFormat === "gemini" && row.supportedGenerationMethods !== undefined ? { supportedGenerationMethods: row.supportedGenerationMethods } : {}
|
|
893
899
|
};
|
|
894
900
|
if (provider.catalogFormat === "mistral") {
|
|
@@ -1089,7 +1095,7 @@ var openapi_default = {
|
|
|
1089
1095
|
openapi: "3.0.3",
|
|
1090
1096
|
info: {
|
|
1091
1097
|
title: "Switcher API",
|
|
1092
|
-
version: "0.2.
|
|
1098
|
+
version: "0.2.1",
|
|
1093
1099
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
1094
1100
|
},
|
|
1095
1101
|
security: [
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
type Wire = "messages" | "chat" | "responses" | "gemini";
|
|
2
|
+
type Json = Record<string, any>;
|
|
3
|
+
export type OpenCodeTranslationState = Map<string, string>;
|
|
4
|
+
/** OpenCode owns these two prefixes; custom URLs never inherit this adapter. */
|
|
5
|
+
export declare function openCodeLane(baseUrl: string): "zen" | "go" | undefined;
|
|
6
|
+
/** Native endpoint families documented by OpenCode, not a frozen model list.
|
|
7
|
+
* Their default OpenAI-compatible adapter serves the remaining model families.
|
|
8
|
+
* https://opencode.ai/docs/zen/ and https://opencode.ai/docs/go/
|
|
9
|
+
*/
|
|
10
|
+
export declare function openCodeWire(model: string, lane: "zen" | "go"): Wire;
|
|
11
|
+
/** Forward only conversation identifiers, never arbitrary client headers.
|
|
12
|
+
* Switcher identifies itself honestly even when a native user agent is absent.
|
|
13
|
+
*/
|
|
14
|
+
export declare function openCodeHeaders(baseUrl: string, source: Headers, body: Json, launchSession: string): Record<string, string>;
|
|
15
|
+
export declare function prepareOpenCodeMessages(baseUrl: string, body: Json, suffix: string, credential?: string, state?: OpenCodeTranslationState): {
|
|
16
|
+
path: string;
|
|
17
|
+
body: Json;
|
|
18
|
+
auth: {
|
|
19
|
+
"x-goog-api-key": string;
|
|
20
|
+
authorization?: undefined;
|
|
21
|
+
} | {
|
|
22
|
+
authorization: string;
|
|
23
|
+
"x-goog-api-key"?: undefined;
|
|
24
|
+
} | {
|
|
25
|
+
"x-goog-api-key"?: undefined;
|
|
26
|
+
authorization?: undefined;
|
|
27
|
+
};
|
|
28
|
+
response(response: Response): Promise<Response>;
|
|
29
|
+
} | undefined;
|
|
30
|
+
export {};
|
package/dist/sdk.js
CHANGED
|
@@ -234,6 +234,11 @@ var preset = (id, name, protocols, sources, alias) => parse(providerPresetSchema
|
|
|
234
234
|
verification: "documented"
|
|
235
235
|
});
|
|
236
236
|
var providerPresets = [
|
|
237
|
+
...["opencode", "opencode-go"].map((id) => preset(id, id === "opencode" ? "OpenCode Zen" : "OpenCode Go", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, id === "opencode" ? "https://opencode.ai/zen/v1" : "https://opencode.ai/zen/go/v1", {
|
|
238
|
+
authStyle: protocol === "anthropic-messages" ? "x-api-key" : "bearer",
|
|
239
|
+
catalogAuthStyle: "none",
|
|
240
|
+
notes: ["Discovers the full live catalog. Claude requests are adapted to each model's documented native endpoint. Other harnesses require models compatible with their selected protocol. Go requires an active subscription and coding-agent session headers."]
|
|
241
|
+
})), ["https://opencode.ai/docs/zen/", "https://opencode.ai/docs/go/"], "OPENCODE_API_KEY")),
|
|
237
242
|
preset("deepseek", "DeepSeek", [
|
|
238
243
|
route("openai-chat", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
239
244
|
route("openai-responses", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
package/dist/serve/index.js
CHANGED
|
@@ -67,7 +67,7 @@ function canonicalPolicyJSON(value) {
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
// src/domain.ts
|
|
70
|
-
var VERSION = "0.2.
|
|
70
|
+
var VERSION = "0.2.1";
|
|
71
71
|
var harnessSchema = z3.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
72
72
|
var protocolSchema = z3.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
73
73
|
var idSchema = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
@@ -486,7 +486,7 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
486
486
|
return { models: provider.manualModels, source: "manual", refreshedAt };
|
|
487
487
|
if (provider.catalogFormat === "none")
|
|
488
488
|
throw new Fault(422, "catalog_unsupported", "This provider has no documented model-list contract; configure manual models or an explicit catalog URL and parser.");
|
|
489
|
-
const headers = { accept: "application/json" };
|
|
489
|
+
const headers = { accept: "application/json", "user-agent": `hasna-switcher/${VERSION}` };
|
|
490
490
|
if (provider.catalogFormat === "fireworks" && !provider.catalogBaseUrl && !provider.catalogAccountId)
|
|
491
491
|
throw new Fault(422, "catalog_account_required", "Fireworks model discovery requires a catalog account ID or an explicit catalog URL.");
|
|
492
492
|
if (provider.catalogFormat === "fireworks" && !provider.catalogBaseUrl && new URL(provider.baseUrl).origin !== "https://api.fireworks.ai")
|
|
@@ -545,6 +545,7 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
545
545
|
inputModalities: strings(row.architecture?.input_modalities ?? row.input_modalities) ?? modalities(row.inference_metadata?.request_modality),
|
|
546
546
|
outputModalities: strings(row.architecture?.output_modalities ?? row.output_modalities) ?? modalities(row.inference_metadata?.response_modality),
|
|
547
547
|
supportedParameters: strings(row.supported_parameters),
|
|
548
|
+
reasoningEfforts: row.reasoning?.supported_efforts,
|
|
548
549
|
...provider.catalogFormat === "gemini" && row.supportedGenerationMethods !== undefined ? { supportedGenerationMethods: row.supportedGenerationMethods } : {}
|
|
549
550
|
};
|
|
550
551
|
if (provider.catalogFormat === "mistral") {
|
|
@@ -761,6 +762,11 @@ var preset = (id2, name, protocols, sources, alias) => parse(providerPresetSchem
|
|
|
761
762
|
verification: "documented"
|
|
762
763
|
});
|
|
763
764
|
var providerPresets = [
|
|
765
|
+
...["opencode", "opencode-go"].map((id2) => preset(id2, id2 === "opencode" ? "OpenCode Zen" : "OpenCode Go", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, id2 === "opencode" ? "https://opencode.ai/zen/v1" : "https://opencode.ai/zen/go/v1", {
|
|
766
|
+
authStyle: protocol === "anthropic-messages" ? "x-api-key" : "bearer",
|
|
767
|
+
catalogAuthStyle: "none",
|
|
768
|
+
notes: ["Discovers the full live catalog. Claude requests are adapted to each model's documented native endpoint. Other harnesses require models compatible with their selected protocol. Go requires an active subscription and coding-agent session headers."]
|
|
769
|
+
})), ["https://opencode.ai/docs/zen/", "https://opencode.ai/docs/go/"], "OPENCODE_API_KEY")),
|
|
764
770
|
preset("deepseek", "DeepSeek", [
|
|
765
771
|
route("openai-chat", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
766
772
|
route("openai-responses", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
@@ -837,7 +843,7 @@ var openapi_default = {
|
|
|
837
843
|
openapi: "3.0.3",
|
|
838
844
|
info: {
|
|
839
845
|
title: "Switcher API",
|
|
840
|
-
version: "0.2.
|
|
846
|
+
version: "0.2.1",
|
|
841
847
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
842
848
|
},
|
|
843
849
|
security: [
|
package/openapi.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hasna/switcher",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Universal provider and model switcher for coding harnesses with an API, SDK and self-hosted storage",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -61,7 +61,8 @@
|
|
|
61
61
|
"test:native-kilo": "bun scripts/test-native-kilo.ts",
|
|
62
62
|
"test:native-kilo-lifecycle": "bun scripts/test-native-kilo-lifecycle.ts",
|
|
63
63
|
"test:native-chatgpt-runtime": "bun scripts/test-native-chatgpt-runtime.ts",
|
|
64
|
-
"test:native-chatgpt-tools": "bun scripts/test-native-chatgpt-tools.ts"
|
|
64
|
+
"test:native-chatgpt-tools": "bun scripts/test-native-chatgpt-tools.ts",
|
|
65
|
+
"test:native-claude-providers": "bun scripts/test-native-claude-providers.ts"
|
|
65
66
|
},
|
|
66
67
|
"devDependencies": {
|
|
67
68
|
"@types/bun": "1.3.14",
|