@hasna/switcher 0.1.9 → 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/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.1.9";
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" }),
@@ -1566,6 +1571,7 @@ function proxyProviderStream(input) {
1566
1571
  if (ended)
1567
1572
  return;
1568
1573
  ended = true;
1574
+ input.activity?.finish();
1569
1575
  try {
1570
1576
  if (error)
1571
1577
  output.error(error);
@@ -1576,9 +1582,9 @@ function proxyProviderStream(input) {
1576
1582
  };
1577
1583
  const cancelReader = async () => {
1578
1584
  input.abort.abort();
1579
- try {
1580
- await reader.cancel();
1581
- } catch {}
1585
+ reader.cancel().catch(() => {
1586
+ return;
1587
+ });
1582
1588
  };
1583
1589
  const stream = new ReadableStream({
1584
1590
  start(controller) {
@@ -1586,7 +1592,7 @@ function proxyProviderStream(input) {
1586
1592
  },
1587
1593
  async pull(controller) {
1588
1594
  try {
1589
- const chunk = await reader.read();
1595
+ const chunk = await (input.activity ? input.activity.run(() => reader.read()) : reader.read());
1590
1596
  if (ended)
1591
1597
  return;
1592
1598
  if (chunk.done) {
@@ -1604,17 +1610,22 @@ function proxyProviderStream(input) {
1604
1610
  } catch {
1605
1611
  if (ended)
1606
1612
  return;
1607
- if (input.requestSignal.aborted || input.abort.signal.aborted || input.closing())
1613
+ if (input.activity?.timedOut()) {
1614
+ input.interrupted?.("provider_idle_timeout");
1615
+ end(new Error("Provider stream timed out waiting for activity"));
1616
+ } else if (input.requestSignal.aborted || input.abort.signal.aborted || input.closing())
1608
1617
  end();
1609
1618
  else {
1610
- input.interrupted?.();
1619
+ input.interrupted?.("stream_interrupted");
1611
1620
  end(new Error("Provider stream ended unexpectedly"));
1612
1621
  }
1622
+ await cancelReader();
1613
1623
  }
1614
1624
  },
1615
1625
  async cancel() {
1616
1626
  if (!ended) {
1617
1627
  ended = true;
1628
+ input.activity?.finish();
1618
1629
  input.release();
1619
1630
  }
1620
1631
  await cancelReader();
@@ -1626,6 +1637,58 @@ function proxyProviderStream(input) {
1626
1637
  } };
1627
1638
  }
1628
1639
 
1640
+ // src/provider-request.ts
1641
+ function createProviderRequest(requestSignal, abortSignal, timing = {}) {
1642
+ const idleTimeoutMs = timing.idleTimeoutMs ?? 240000;
1643
+ if (!Number.isFinite(idleTimeoutMs) || idleTimeoutMs <= 0)
1644
+ throw new Error("Invalid provider idle timeout.");
1645
+ const idle = new AbortController;
1646
+ const signal = AbortSignal.any([requestSignal, abortSignal, idle.signal]);
1647
+ let timer, finished = false, timedOut = false;
1648
+ const received = () => {
1649
+ clearTimeout(timer);
1650
+ timer = undefined;
1651
+ };
1652
+ const finish = () => {
1653
+ finished = true;
1654
+ received();
1655
+ signal.removeEventListener("abort", finish);
1656
+ };
1657
+ const waiting = () => {
1658
+ if (finished || signal.aborted || timer !== undefined)
1659
+ return;
1660
+ timer = setTimeout(() => {
1661
+ timedOut = true;
1662
+ idle.abort(new DOMException("Provider response idle timeout", "TimeoutError"));
1663
+ }, idleTimeoutMs);
1664
+ };
1665
+ signal.addEventListener("abort", finish, { once: true });
1666
+ waiting();
1667
+ const run = async (operation) => {
1668
+ waiting();
1669
+ let onAbort;
1670
+ try {
1671
+ if (signal.aborted)
1672
+ throw signal.reason;
1673
+ const aborted = new Promise((_, reject) => {
1674
+ onAbort = () => reject(signal.reason);
1675
+ signal.addEventListener("abort", onAbort, { once: true });
1676
+ });
1677
+ return await Promise.race([operation(), aborted]);
1678
+ } finally {
1679
+ if (onAbort)
1680
+ signal.removeEventListener("abort", onAbort);
1681
+ received();
1682
+ }
1683
+ };
1684
+ return {
1685
+ fetchOptions: { signal, timeout: false },
1686
+ run,
1687
+ finish,
1688
+ timedOut: () => timedOut
1689
+ };
1690
+ }
1691
+
1629
1692
  // src/claude-context.ts
1630
1693
  function claudeContextEnvironment(providerBaseUrl, environment = process.env) {
1631
1694
  const explicit = environment.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
@@ -1962,7 +2025,7 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
1962
2025
  return { models: provider.manualModels, source: "manual", refreshedAt };
1963
2026
  if (provider.catalogFormat === "none")
1964
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.");
1965
- const headers = { accept: "application/json" };
2028
+ const headers = { accept: "application/json", "user-agent": `hasna-switcher/${VERSION}` };
1966
2029
  if (provider.catalogFormat === "fireworks" && !provider.catalogBaseUrl && !provider.catalogAccountId)
1967
2030
  throw new Fault(422, "catalog_account_required", "Fireworks model discovery requires a catalog account ID or an explicit catalog URL.");
1968
2031
  if (provider.catalogFormat === "fireworks" && !provider.catalogBaseUrl && new URL(provider.baseUrl).origin !== "https://api.fireworks.ai")
@@ -2021,6 +2084,7 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
2021
2084
  inputModalities: strings(row.architecture?.input_modalities ?? row.input_modalities) ?? modalities(row.inference_metadata?.request_modality),
2022
2085
  outputModalities: strings(row.architecture?.output_modalities ?? row.output_modalities) ?? modalities(row.inference_metadata?.response_modality),
2023
2086
  supportedParameters: strings(row.supported_parameters),
2087
+ reasoningEfforts: row.reasoning?.supported_efforts,
2024
2088
  ...provider.catalogFormat === "gemini" && row.supportedGenerationMethods !== undefined ? { supportedGenerationMethods: row.supportedGenerationMethods } : {}
2025
2089
  };
2026
2090
  if (provider.catalogFormat === "mistral") {
@@ -2316,7 +2380,7 @@ var openapi_default = {
2316
2380
  openapi: "3.0.3",
2317
2381
  info: {
2318
2382
  title: "Switcher API",
2319
- version: "0.1.9",
2383
+ version: "0.2.1",
2320
2384
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2321
2385
  },
2322
2386
  security: [
@@ -6498,7 +6562,59 @@ async function startServer(options) {
6498
6562
  }
6499
6563
 
6500
6564
  // src/runtime.ts
6501
- import { resolveCredential as resolveClientCredential, clientTransportEnvKeys, appConfigDiskValue, keychainConfigValue } from "@hasna/contracts/client";
6565
+ import { resolveCredential as resolveClientCredential, clientTransportEnvKeys as clientTransportEnvKeys2, appConfigDiskValue, keychainConfigValue } from "@hasna/contracts/client";
6566
+
6567
+ // src/lib/local-opt-in.ts
6568
+ import {
6569
+ clientTransportEnvKeys,
6570
+ credentialDiskSources,
6571
+ credentialOverrideEnvKey,
6572
+ credentialPointerEnvKey,
6573
+ CREDENTIAL_PROFILE_ENV_KEY
6574
+ } from "@hasna/contracts/client";
6575
+ var SWITCHER_LOCAL_OPT_IN_ENV_KEYS = ["HASNA_SWITCHER_LOCAL", "SWITCHER_LOCAL"];
6576
+ var SWITCHER_KEYCHAIN_ITEM = "hasna.credentials.switcher.api-key";
6577
+ var SWITCHER_CREDENTIALS_FILE = "~/.hasna/switcher/config/credentials";
6578
+ function isSwitcherLocalOptIn(env = process.env) {
6579
+ return SWITCHER_LOCAL_OPT_IN_ENV_KEYS.some((key) => (env[key] ?? "").trim() !== "");
6580
+ }
6581
+ function switcherAuthorityEnvKeys() {
6582
+ const keys = clientTransportEnvKeys("switcher");
6583
+ return [
6584
+ ...keys.apiUrlKeys,
6585
+ ...keys.apiKeyKeys,
6586
+ credentialOverrideEnvKey("switcher"),
6587
+ credentialPointerEnvKey("switcher"),
6588
+ CREDENTIAL_PROFILE_ENV_KEY
6589
+ ];
6590
+ }
6591
+ function hasSwitcherEnvAuthorityIntent(env = process.env) {
6592
+ return switcherAuthorityEnvKeys().some((key) => env[key] !== undefined);
6593
+ }
6594
+ function switcherCredentialSources(env = process.env) {
6595
+ const disk = credentialDiskSources("switcher", env)[0];
6596
+ return [
6597
+ `Keychain item ${SWITCHER_KEYCHAIN_ITEM}`,
6598
+ disk ? `${SWITCHER_CREDENTIALS_FILE} (${disk})` : SWITCHER_CREDENTIALS_FILE,
6599
+ `${clientTransportEnvKeys("switcher").apiKeyKeys[0] ?? "HASNA_SWITCHER_API_KEY"} in the environment`
6600
+ ];
6601
+ }
6602
+ function remoteConfigMissingMessage(env = process.env) {
6603
+ return `No Switcher API credential is configured; consulted ${switcherCredentialSources(env).join(", ")}. ` + `Configure one of them, or set ${SWITCHER_LOCAL_OPT_IN_ENV_KEYS[0]}=1 (alias ${SWITCHER_LOCAL_OPT_IN_ENV_KEYS[1]}=1) to deliberately use the on-box local store. Nothing was read or created locally.`;
6604
+ }
6605
+ var announced = false;
6606
+ function announceSwitcherLocalMode(home, write = (line) => {
6607
+ process.stderr.write(line);
6608
+ }) {
6609
+ if (announced)
6610
+ return;
6611
+ announced = true;
6612
+ write(`switcher: LOCAL mode \u2014 using the on-box store under ${home} behind an owned per-process loopback API, not a hosted Switcher API (${SWITCHER_LOCAL_OPT_IN_ENV_KEYS[0]} is set; a configured API URL or key would outrank it).
6613
+ `);
6614
+ }
6615
+
6616
+ // src/runtime.ts
6617
+ var REMOTE_API_CONFIG_MISSING = "remote_api_config_missing";
6502
6618
  function switcherHome(env = process.env) {
6503
6619
  const override = env.HASNA_HOME?.trim();
6504
6620
  const root = override && isAbsolute4(override) ? override : join4(env.HOME?.trim() || homedir3(), ".hasna");
@@ -6514,13 +6630,18 @@ async function privateDirectory(path) {
6514
6630
  }
6515
6631
  async function openCliRuntime(env = process.env, resolveCredential) {
6516
6632
  const providerEnv = Object.fromEntries(Object.entries(env).filter(([name]) => name.startsWith("SWITCHER_PROVIDER_")));
6517
- const keys = clientTransportEnvKeys("switcher");
6518
- const credential = resolveClientCredential("switcher", env);
6519
- const configured = credential || keys.apiUrlKeys.some((name) => env[name] !== undefined) || keychainConfigValue("switcher", env) || appConfigDiskValue("switcher", env, keys.apiUrlKeys);
6520
- if (configured) {
6521
- return { client: clientFromEnv(env), mode: "remote", providerEnv, close: async () => {} };
6633
+ const remote = () => ({ client: clientFromEnv(env), mode: "remote", providerEnv, close: async () => {} });
6634
+ if (hasSwitcherEnvAuthorityIntent(env))
6635
+ return remote();
6636
+ if (!isSwitcherLocalOptIn(env)) {
6637
+ const keys = clientTransportEnvKeys2("switcher");
6638
+ const configured = resolveClientCredential("switcher", env) || keychainConfigValue("switcher", env) || appConfigDiskValue("switcher", env, keys.apiUrlKeys);
6639
+ if (configured)
6640
+ return remote();
6641
+ throw new Fault(401, REMOTE_API_CONFIG_MISSING, remoteConfigMissingMessage(env));
6522
6642
  }
6523
6643
  const home = switcherHome(env);
6644
+ announceSwitcherLocalMode(home);
6524
6645
  if (!env.HASNA_SWITCHER_DATABASE_URL && !env.HASNA_SWITCHER_SQLITE_PATH)
6525
6646
  await privateDirectory(home);
6526
6647
  const apiKey = randomBytes(32).toString("base64url");
@@ -6816,12 +6937,12 @@ async function prepareGemini(input) {
6816
6937
 
6817
6938
  // src/gemini-bridge.ts
6818
6939
  import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "crypto";
6819
- function geminiBridge(input) {
6940
+ function geminiBridge(input, timing = {}) {
6820
6941
  const token = crypto.randomUUID() + crypto.randomUUID(), digest = (value) => createHash4("sha256").update(value).digest(), expected = digest(token);
6821
6942
  const models = new Set(input.models.map((model) => model.id));
6822
6943
  let closing = false, stopped;
6823
6944
  const active = new Set;
6824
- const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request) {
6945
+ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
6825
6946
  const fail = (status, message) => Response.json({ error: { code: status, message } }, { status });
6826
6947
  if (closing)
6827
6948
  return fail(503, "Bridge is closing");
@@ -6861,15 +6982,20 @@ function geminiBridge(input) {
6861
6982
  const record2 = { abort: new AbortController, done: new Promise((resolve5) => {
6862
6983
  complete = resolve5;
6863
6984
  }) };
6985
+ const activity = createProviderRequest(request.signal, record2.abort.signal, timing);
6864
6986
  const release = () => {
6987
+ activity.finish();
6865
6988
  active.delete(record2);
6866
6989
  complete();
6867
6990
  };
6868
6991
  active.add(record2);
6992
+ server2.timeout(request, 0);
6869
6993
  try {
6870
- const response = await fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", signal: AbortSignal.any([request.signal, record2.abort.signal, AbortSignal.timeout(240000)]) });
6994
+ const response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
6871
6995
  if (!response.ok) {
6872
- await response.body?.cancel();
6996
+ response.body?.cancel().catch(() => {
6997
+ return;
6998
+ });
6873
6999
  release();
6874
7000
  return fail(response.status >= 300 && response.status < 400 ? 502 : response.status, `Provider returned HTTP ${response.status}`);
6875
7001
  }
@@ -6877,12 +7003,12 @@ function geminiBridge(input) {
6877
7003
  release();
6878
7004
  return new Response(null, { status: response.status });
6879
7005
  }
6880
- const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record2.abort, closing: () => closing, release });
7006
+ const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record2.abort, closing: () => closing, release, activity });
6881
7007
  record2.cancel = cancel;
6882
7008
  return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
6883
7009
  } catch {
6884
7010
  release();
6885
- return fail(502, "Provider request failed");
7011
+ return fail(activity.timedOut() ? 504 : 502, activity.timedOut() ? "Provider request timed out waiting for activity" : "Provider request failed");
6886
7012
  }
6887
7013
  } });
6888
7014
  return { baseUrl: new URL("v1beta", server.url).href, token, cleanup: () => stopped ??= (async () => {
@@ -7040,19 +7166,480 @@ function normalizeCodexDelegation(body) {
7040
7166
  }) };
7041
7167
  }
7042
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
+
7043
7628
  // src/inference-gateway.ts
7044
7629
  import { createHash as createHash5, timingSafeEqual as timingSafeEqual3 } from "crypto";
7045
7630
  var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
7046
- function createInferenceGateway(input) {
7631
+ function createInferenceGateway(input, timing = {}) {
7047
7632
  const token = crypto.randomUUID() + crypto.randomUUID();
7633
+ const openCodeSession = crypto.randomUUID();
7634
+ const openCodeState = new Map;
7048
7635
  const digest = (value) => createHash5("sha256").update(value).digest();
7049
7636
  const expected = digest(token), policy = input.compiledPolicy;
7050
7637
  const known = new Set(input.models.map((m) => m.id));
7051
7638
  const safeModel = (value) => typeof value === "string" && value !== input.credential && (known.has(value) || Object.hasOwn(policy.aliases, value)) ? value : "<unrecognized>";
7052
- 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 });
7053
7640
  let closing = false, stopped;
7054
7641
  const active = new Set;
7055
- const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request) {
7642
+ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
7056
7643
  if (closing)
7057
7644
  return fail(503, "closing");
7058
7645
  const credential = request.headers.get("x-goog-api-key") ?? request.headers.get("x-api-key") ?? request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
@@ -7125,14 +7712,18 @@ function createInferenceGateway(input) {
7125
7712
  const abort = new AbortController;
7126
7713
  let complete;
7127
7714
  const record2 = { abort, done: new Promise((r) => complete = r) };
7715
+ const activity = createProviderRequest(request.signal, abort.signal, timing);
7128
7716
  const release = () => {
7717
+ activity.finish();
7129
7718
  flush();
7130
7719
  active.delete(record2);
7131
7720
  complete();
7132
7721
  };
7133
7722
  active.add(record2);
7134
- const signal = AbortSignal.any([request.signal, abort.signal, AbortSignal.timeout(240000)]);
7723
+ const signal = activity.fetchOptions.signal;
7724
+ server2.timeout(request, 0);
7135
7725
  const headers = { "content-type": "application/json" };
7726
+ Object.assign(headers, openCodeHeaders(input.baseUrl, request.headers, body, openCodeSession));
7136
7727
  if (input.credential) {
7137
7728
  const [name, value] = gemini ? ["x-goog-api-key", input.credential] : authHeader(input.authStyle ?? "bearer", input.credential);
7138
7729
  headers[name] = value;
@@ -7167,21 +7758,34 @@ function createInferenceGateway(input) {
7167
7758
  const guidance = renderModelGuidance({ harness: input.harness, providerId: input.providerId, baseUrl: input.baseUrl, model, compiled: policy, catalogPath: input.catalogPath });
7168
7759
  const compatible2 = input.harness === "codex" && input.protocol === "openai-responses" && new URL(input.baseUrl).hostname !== "api.openai.com" ? normalizeCodexDelegation(payload) : payload;
7169
7760
  const outgoing = injectModelGuidance(input.protocol, compatible2, guidance, match?.[2]);
7170
- const path = gemini ? `/models/${encodeURIComponent(model)}:${match[2]}${url.search}` : suffix + (betaQuery ? "?beta=true" : "");
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
+ }
7171
7771
  try {
7172
- response = await fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(outgoing), redirect: "manual", signal });
7772
+ response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers: upstreamHeaders, body: JSON.stringify(translated?.body ?? outgoing), redirect: "manual", ...activity.fetchOptions }));
7173
7773
  } catch {
7174
- current.reason = signal.aborted ? "request_cancelled" : "network_error";
7774
+ current.reason = activity.timedOut() ? "provider_idle_timeout" : signal.aborted ? "request_cancelled" : "network_error";
7175
7775
  if (!signal.aborted && attempt + 1 < candidates.length)
7176
7776
  continue;
7177
7777
  throw new Error("provider_request_failed");
7178
7778
  }
7179
7779
  current.upstreamStatus = response.status;
7180
7780
  if ((response.status === 429 || response.status >= 500) && attempt + 1 < candidates.length) {
7181
- await response.body?.cancel();
7781
+ response.body?.cancel().catch(() => {
7782
+ return;
7783
+ });
7182
7784
  response = undefined;
7183
7785
  continue;
7184
7786
  }
7787
+ if (translated)
7788
+ response = await activity.run(() => translated.response(response));
7185
7789
  break;
7186
7790
  }
7187
7791
  if (!response)
@@ -7193,7 +7797,11 @@ function createInferenceGateway(input) {
7193
7797
  release();
7194
7798
  if (overflow)
7195
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 });
7196
- return fail(response.status >= 300 && response.status < 400 ? 502 : response.status, `upstream_http_${response.status}`);
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;
7197
7805
  }
7198
7806
  if (!response.body) {
7199
7807
  release();
@@ -7233,16 +7841,18 @@ function createInferenceGateway(input) {
7233
7841
  if (done && buffer)
7234
7842
  observe(buffer);
7235
7843
  };
7236
- const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort, closing: () => closing, release, inspect, interrupted: () => {
7237
- current.reason = "stream_interrupted";
7844
+ const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort, closing: () => closing, release, activity, inspect, interrupted: (reason) => {
7845
+ current.reason = reason;
7238
7846
  } });
7239
7847
  record2.cancel = cancel;
7240
7848
  return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
7241
7849
  } catch (error) {
7242
7850
  if (error instanceof Fault)
7243
7851
  current.reason = error.code;
7852
+ else if (activity.timedOut())
7853
+ current.reason = "provider_idle_timeout";
7244
7854
  release();
7245
- return fail(error instanceof Fault ? error.status : 502, error instanceof Fault ? error.code : "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);
7246
7856
  }
7247
7857
  } });
7248
7858
  return { baseUrl: new URL(input.protocol === "gemini-generate-content" ? "v1beta" : "v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
@@ -7343,9 +7953,9 @@ function compileCodexModelPolicy(input) {
7343
7953
  const policy = modelPolicySchema.parse(input.policy ?? {});
7344
7954
  const subagentModel = policy.roles?.subagent ?? input.model;
7345
7955
  const reviewModel = policy.roles?.review ?? input.model;
7346
- const unsupported2 = ["fast", "planning", "summary", "compaction", "weak", "editor"].filter((role) => policy.roles?.[role] !== undefined && policy.roles?.[role] !== input.model);
7347
- if (unsupported2.length)
7348
- throw new Error(`Codex does not expose role controls for: ${unsupported2.join(", ")}.`);
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(", ")}.`);
7349
7959
  const agents = [];
7350
7960
  const ignoredUntrustedAgents = [];
7351
7961
  for (const [name, definition] of Object.entries(input.agents ?? {})) {
@@ -8531,7 +9141,7 @@ var routePath = {
8531
9141
  "openai-chat": "/v1/chat/completions"
8532
9142
  };
8533
9143
  var apiMode = hermesApiMode;
8534
- function createHermesBridge(input) {
9144
+ function createHermesBridge(input, timing = {}) {
8535
9145
  const protocol = input.protocol;
8536
9146
  const token = crypto.randomUUID() + crypto.randomUUID();
8537
9147
  const modelIds = new Set(input.models.map((model3) => model3.id));
@@ -8544,7 +9154,7 @@ function createHermesBridge(input) {
8544
9154
  port: 0,
8545
9155
  maxRequestBodySize: 4 * 1024 * 1024,
8546
9156
  idleTimeout: 255,
8547
- async fetch(request) {
9157
+ async fetch(request, server2) {
8548
9158
  if (closing)
8549
9159
  return Response.json({ error: { message: "Hermes bridge is closing" } }, { status: 503 });
8550
9160
  const nativeHeader = protocol === "anthropic-messages" ? "x-api-key" : "authorization";
@@ -8589,7 +9199,9 @@ function createHermesBridge(input) {
8589
9199
  complete = resolve8;
8590
9200
  })
8591
9201
  };
9202
+ const activity = createProviderRequest(request.signal, abortController.signal, timing);
8592
9203
  const release = () => {
9204
+ activity.finish();
8593
9205
  active.delete(record3);
8594
9206
  complete();
8595
9207
  };
@@ -8609,16 +9221,19 @@ function createHermesBridge(input) {
8609
9221
  if (beta)
8610
9222
  headers["anthropic-beta"] = beta;
8611
9223
  }
9224
+ server2.timeout(request, 0);
8612
9225
  try {
8613
- const upstream = await fetch(`${input.baseUrl}${routePath[protocol].replace(/^\/v1/, "")}`, {
9226
+ const upstream = await activity.run(() => fetch(`${input.baseUrl}${routePath[protocol].replace(/^\/v1/, "")}`, {
8614
9227
  method: "POST",
8615
9228
  headers,
8616
9229
  body: JSON.stringify(body),
8617
9230
  redirect: "manual",
8618
- signal: AbortSignal.any([abortController.signal, request.signal, AbortSignal.timeout(240000)])
8619
- });
9231
+ ...activity.fetchOptions
9232
+ }));
8620
9233
  if (!upstream.ok) {
8621
- await upstream.body?.cancel();
9234
+ upstream.body?.cancel().catch(() => {
9235
+ return;
9236
+ });
8622
9237
  release();
8623
9238
  return Response.json({ error: { message: `Provider returned HTTP ${upstream.status}` } }, { status: upstream.status });
8624
9239
  }
@@ -8626,7 +9241,7 @@ function createHermesBridge(input) {
8626
9241
  release();
8627
9242
  return new Response(null, { status: upstream.status });
8628
9243
  }
8629
- const { stream, cancel } = proxyProviderStream({ response: upstream, protocol: input.protocol, requestSignal: request.signal, abort: abortController, closing: () => closing, release });
9244
+ const { stream, cancel } = proxyProviderStream({ response: upstream, protocol: input.protocol, requestSignal: request.signal, abort: abortController, closing: () => closing, release, activity });
8630
9245
  record3.cancel = cancel;
8631
9246
  return new Response(stream, {
8632
9247
  status: upstream.status,
@@ -8637,7 +9252,7 @@ function createHermesBridge(input) {
8637
9252
  });
8638
9253
  } catch {
8639
9254
  release();
8640
- return Response.json({ error: { message: "Provider request failed" } }, { status: 502 });
9255
+ return Response.json({ error: { message: activity.timedOut() ? "Provider request timed out waiting for activity" : "Provider request failed" } }, { status: activity.timedOut() ? 504 : 502 });
8641
9256
  }
8642
9257
  }
8643
9258
  });
@@ -9230,7 +9845,7 @@ function codexModel(model3, priority, baseUrl = "https://provider.invalid", sele
9230
9845
  model_messages: { instructions_template: "You are Codex, a coding assistant. Help the user with their requested work. Follow the user and developer instructions, use the available tools when appropriate, preserve unrelated changes, and report actual results and remaining limitations.", instructions_variables: null }
9231
9846
  };
9232
9847
  }
9233
- function grokBridge(input) {
9848
+ function grokBridge(input, timing = {}) {
9234
9849
  const token = crypto.randomUUID() + crypto.randomUUID();
9235
9850
  const expected = createHash8("sha256").update(`Bearer ${token}`).digest();
9236
9851
  const models = new Map(input.models.flatMap((m) => [[m.id, m.id], [grokAlias(input, m.id), m.id]]));
@@ -9240,7 +9855,7 @@ function grokBridge(input) {
9240
9855
  const active = new Set;
9241
9856
  const apiBackend = { "anthropic-messages": "messages", "openai-responses": "responses", "openai-chat": "chat_completions", "gemini-generate-content": "generate_content" }[input.protocol];
9242
9857
  const apiPath = { "anthropic-messages": "/messages", "openai-responses": "/responses", "openai-chat": "/chat/completions", "gemini-generate-content": "/generateContent" }[input.protocol];
9243
- server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request) {
9858
+ server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
9244
9859
  if (closing)
9245
9860
  return Response.json({ error: { message: "Bridge is closing" } }, { status: 503 });
9246
9861
  const auth = request.headers.get("authorization") ?? (request.headers.has("x-api-key") ? `Bearer ${request.headers.get("x-api-key")}` : "");
@@ -9255,7 +9870,7 @@ function grokBridge(input) {
9255
9870
  model: m.id,
9256
9871
  name: m.name,
9257
9872
  description: m.description,
9258
- base_url: new URL("v1", server.url).href,
9873
+ base_url: new URL("v1", server2.url).href,
9259
9874
  context_window: m.contextWindow,
9260
9875
  max_completion_tokens: m.maxOutputTokens,
9261
9876
  api_backend: apiBackend,
@@ -9288,15 +9903,20 @@ function grokBridge(input) {
9288
9903
  const record3 = { abort: new AbortController, done: new Promise((resolve9) => {
9289
9904
  complete = resolve9;
9290
9905
  }) };
9906
+ const activity = createProviderRequest(request.signal, record3.abort.signal, timing);
9291
9907
  const release = () => {
9908
+ activity.finish();
9292
9909
  active.delete(record3);
9293
9910
  complete();
9294
9911
  };
9295
9912
  active.add(record3);
9913
+ server2.timeout(request, 0);
9296
9914
  try {
9297
- const response = await fetch(`${input.baseUrl}${apiPath}`, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", signal: AbortSignal.any([record3.abort.signal, request.signal, AbortSignal.timeout(240000)]) });
9915
+ const response = await activity.run(() => fetch(`${input.baseUrl}${apiPath}`, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
9298
9916
  if (!response.ok) {
9299
- await response.body?.cancel();
9917
+ response.body?.cancel().catch(() => {
9918
+ return;
9919
+ });
9300
9920
  release();
9301
9921
  return Response.json({ error: { message: `Provider returned HTTP ${response.status}` } }, { status: response.status >= 300 && response.status < 400 ? 502 : response.status });
9302
9922
  }
@@ -9304,12 +9924,12 @@ function grokBridge(input) {
9304
9924
  release();
9305
9925
  return new Response(null, { status: response.status });
9306
9926
  }
9307
- const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record3.abort, closing: () => closing, release });
9927
+ const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record3.abort, closing: () => closing, release, activity });
9308
9928
  record3.cancel = cancel;
9309
9929
  return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
9310
9930
  } catch {
9311
9931
  release();
9312
- return Response.json({ error: { message: "Provider request failed" } }, { status: 502 });
9932
+ return Response.json({ error: { message: activity.timedOut() ? "Provider request timed out waiting for activity" : "Provider request failed" } }, { status: activity.timedOut() ? 504 : 502 });
9313
9933
  }
9314
9934
  } });
9315
9935
  return { baseUrl: new URL("v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
@@ -9591,6 +10211,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
9591
10211
  env.ANTHROPIC_MODEL = input.model;
9592
10212
  env.ANTHROPIC_DEFAULT_MODEL = input.model;
9593
10213
  env.CLAUDE_CODE_SUBAGENT_MODEL = input.compiledPolicy?.roles.subagent ?? input.model;
10214
+ env.ANTHROPIC_API_KEY = "";
10215
+ env.ANTHROPIC_AUTH_TOKEN = "";
9594
10216
  env[input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"] = input.credential ?? "switcher-local-no-auth";
9595
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) })) } });
9596
10218
  configPaths.push(file2);
@@ -9943,9 +10565,9 @@ async function prepareHarnessLaunch(input) {
9943
10565
  input = { ...input, models: input.models.filter((model3) => !modelExpired(model3)) };
9944
10566
  const nativePolicy = compileNativeModelPolicy({ harness: input.harness, mainModel: input.model, roles: compiledPolicy.roles, version: input.version });
9945
10567
  const specialized = new Set(["opencode", "opencode2", "gemini", "hermes"]);
9946
- const unsupported2 = specialized.has(input.harness) ? [] : nativePolicy.unsupportedRoles.filter((role) => role !== "main" && compiledPolicy.roles[role] !== input.model);
9947
- if (unsupported2.length)
9948
- throw new Error(`${input.harness} does not expose native model controls for: ${unsupported2.join(", ")}.`);
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(", ")}.`);
9949
10571
  await mkdir10(input.stateDir, { recursive: true, mode: 448 });
9950
10572
  const catalogPath = await jsonFile(input.stateDir, `switcher-model-policy-${randomUUID4()}.json`, { policy: compiledPolicy, models: input.models });
9951
10573
  const bridge = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
@@ -10646,6 +11268,9 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
10646
11268
  set -eu
10647
11269
  unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
10648
11270
  export CODEX_HOME=${quote2(home)}
11271
+ if [ "\${1-}" = sandbox ]; then
11272
+ exec ${quote2(app.codexExecutable)} "$@"
11273
+ fi
10649
11274
  exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
10650
11275
  `, { mode: 448, flag: "wx" });
10651
11276
  return {
@@ -11252,7 +11877,7 @@ import { join as join16, isAbsolute as isAbsolute13, dirname as dirname8, parse
11252
11877
  import { createHash as createHash12, randomUUID as randomUUID5 } from "crypto";
11253
11878
  import { execFile as execFile5, spawn as spawn2 } from "child_process";
11254
11879
  import { promisify as promisify5 } from "util";
11255
- import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys2, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
11880
+ import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
11256
11881
  var execute4 = promisify5(execFile5);
11257
11882
  var reference = z7.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
11258
11883
  var item = z7.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
@@ -11546,15 +12171,19 @@ function bindingTarget(selector, override, allowedOrigins) {
11546
12171
  async function readKeychain(source) {
11547
12172
  if (process.platform !== "darwin")
11548
12173
  throw new Fault(422, "keychain_unavailable", "This binding requires macOS Keychain. Use a supported vault binding or runtime environment on this station.");
12174
+ let stdout;
11549
12175
  try {
11550
- const { stdout } = await execute4("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 });
11551
- const value = stdout.replace(/\r?\n$/, "");
11552
- if (!value || /[\x00-\x1f\x7f]/.test(value))
11553
- throw new Error("Invalid credential");
11554
- return value;
11555
- } catch {
11556
- throw new Fault(422, "keychain_unavailable", "The configured Keychain item is missing, locked, or inaccessible; no alternate credential was selected.");
11557
- }
12176
+ ({ stdout } = await execute4("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 }));
12177
+ } catch (error) {
12178
+ const status = error.code;
12179
+ if (status === 44)
12180
+ throw new Fault(422, "keychain_item_missing", "The configured Keychain item does not exist for that service and account; no alternate credential was selected.");
12181
+ throw new Fault(422, "keychain_unavailable", `The configured Keychain item could not be read (security exited ${typeof status === "number" ? status : "without a status"}); it is locked or inaccessible. No alternate credential was selected.`);
12182
+ }
12183
+ const value = stdout.replace(/\r?\n$/, "");
12184
+ if (!value || /[\x00-\x1f\x7f]/.test(value))
12185
+ throw new Fault(422, "keychain_item_invalid", "The configured Keychain item holds an unusable value; no alternate credential was selected.");
12186
+ return value;
11558
12187
  }
11559
12188
 
11560
12189
  class CredentialResolver {
@@ -11610,7 +12239,7 @@ async function vaultEnvironment(binding, env, options = {}) {
11610
12239
  try {
11611
12240
  if (source.operator.kind === "contracts") {
11612
12241
  const pair = () => {
11613
- const keys = clientTransportEnvKeys2("secrets");
12242
+ const keys = clientTransportEnvKeys3("secrets");
11614
12243
  const configuredUrl = keys.apiUrlKeys.map((name) => env[name]).find((value) => value !== undefined) ?? keychainConfigValue2("secrets", env, options.keychain)?.value ?? appConfigDiskValue2("secrets", env, keys.apiUrlKeys)?.value;
11615
12244
  const resolution = resolveClientTransport("secrets", env, { credentials: options });
11616
12245
  const key = resolveCredential("secrets", env, options);
@@ -11815,11 +12444,14 @@ Keep Switcher running while using the app; quit that app instance to end the lau
11815
12444
  --reasoning: none, minimal, low, medium, high, xhigh, max, ultra (provider support required).
11816
12445
  --dangerously-bypass-approvals-and-sandbox: full access without prompts or command sandboxing.
11817
12446
  PROTOCOL: anthropic-messages, openai-responses, openai-chat, gemini-generate-content
11818
- Without remote API configuration, the CLI owns a local authenticated API and
11819
- stores data in ~/.hasna/switcher (override HASNA_SWITCHER_HOME).
11820
- Remote API URL/key resolve through @hasna/contracts: overrides, Keychain,
11821
- ~/.hasna/switcher/config/credentials, then environment. A key alone uses the gateway.
11822
- A configured remote API never falls back to local data.
12447
+ Data access is HTTP against the configured Switcher API. Its URL/key resolve
12448
+ through @hasna/contracts: overrides, Keychain (hasna.credentials.switcher.api-key),
12449
+ ~/.hasna/switcher/config/credentials, then environment (HASNA_SWITCHER_API_KEY).
12450
+ A key alone uses the gateway. With nothing configured the command exits 1 and
12451
+ names those sources; it never falls back to local data.
12452
+ HASNA_SWITCHER_LOCAL=1 (alias SWITCHER_LOCAL=1) deliberately selects the on-box
12453
+ store in ~/.hasna/switcher (override HASNA_SWITCHER_HOME) behind an owned
12454
+ per-command loopback API; a configured remote API outranks the flag.
11823
12455
  Provider credential references must start SWITCHER_PROVIDER_.
11824
12456
  --models-file accepts a JSON array of model metadata; --model adds one starter.
11825
12457
  Use --catalog-format none for a manual catalog; otherwise discovery stays active.