@hasna/switcher 0.2.23 → 0.2.25

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
  return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
515
515
  }
516
516
  // package.json
517
- var version = "0.2.23";
517
+ var version = "0.2.25";
518
518
 
519
519
  // src/version.ts
520
520
  var VERSION = version;
@@ -1467,16 +1467,38 @@ function apiError(status, data, apiKey) {
1467
1467
  const message = typeof error.message === "string" && error.message.length <= 4096 ? redact(error.message).replace(/[\x00-\x1f\x7f-\x9f]/g, " ").trim().slice(0, 2048) || fallback : fallback;
1468
1468
  return new SwitcherError(status, code, message, requestId);
1469
1469
  }
1470
+ var DEFAULT_RETRIES = 3;
1471
+ var DEFAULT_RETRY_BASE_MS = 200;
1472
+ var DEFAULT_RETRY_MAX_MS = 2000;
1473
+ var RETRIES_LIMIT = 5;
1474
+ var RETRY_DELAY_LIMIT_MS = 1e4;
1475
+ function retryPolicy(options) {
1476
+ if (options === false)
1477
+ return;
1478
+ const whole = (value, fallback, minimum) => value !== undefined && Number.isFinite(value) ? Math.max(minimum, Math.floor(value)) : fallback;
1479
+ return {
1480
+ retries: Math.min(whole(options?.retries, DEFAULT_RETRIES, 0), RETRIES_LIMIT),
1481
+ baseDelayMs: Math.min(whole(options?.baseDelayMs, DEFAULT_RETRY_BASE_MS, 0), RETRY_DELAY_LIMIT_MS),
1482
+ maxDelayMs: Math.min(whole(options?.maxDelayMs, DEFAULT_RETRY_MAX_MS, 0), RETRY_DELAY_LIMIT_MS),
1483
+ sleep: options?.sleep ?? ((milliseconds) => new Promise((resolve2) => setTimeout(resolve2, milliseconds)))
1484
+ };
1485
+ }
1486
+ function edgeFailure(error) {
1487
+ return error instanceof SwitcherError && (error.status === 503 || error.status >= 500 && error.code === "invalid_response");
1488
+ }
1489
+ var operationKey = (supplied) => supplied ?? crypto.randomUUID();
1470
1490
 
1471
1491
  class SwitcherClient {
1472
1492
  options;
1473
1493
  transport;
1494
+ retry;
1474
1495
  baseUrl;
1475
1496
  constructor(options) {
1476
1497
  this.baseUrl = endpoint(options.baseUrl).replace(/\/v1$/, "");
1477
1498
  if (typeof options.apiKey === "string" && (!options.apiKey || /[\r\n]/.test(options.apiKey)))
1478
1499
  throw new Error("Switcher API key is required.");
1479
1500
  this.options = { ...options };
1501
+ this.retry = retryPolicy(options.retry);
1480
1502
  }
1481
1503
  static fromEnvironment(env = process.env, options = {}) {
1482
1504
  const shared = createClientTransport("switcher", env, {
@@ -1511,15 +1533,30 @@ class SwitcherClient {
1511
1533
  throw new Error("Shared credential transport was not invoked.");
1512
1534
  } });
1513
1535
  client.transport = shared.client;
1536
+ client.retry = retryPolicy(options.retry);
1514
1537
  return client;
1515
1538
  }
1516
1539
  async request(method, path, body, options = {}) {
1517
1540
  if (!/^\/v1\/[a-zA-Z0-9/?&=._%+-]+$/.test(path) && !["/health", "/ready", "/version"].includes(path) || path.includes(".."))
1518
1541
  throw new Error("Invalid API path.");
1542
+ const key = method === "GET" ? undefined : options.idempotencyKey ?? crypto.randomUUID();
1543
+ const policy = method === "GET" || options.idempotencyKey !== undefined ? this.retry : undefined;
1544
+ for (let attempt = 0;; attempt++) {
1545
+ try {
1546
+ return await this.send(method, path, body, options.version, key);
1547
+ } catch (error) {
1548
+ if (!policy || attempt >= policy.retries || !edgeFailure(error))
1549
+ throw error;
1550
+ const delay = policy.baseDelayMs * 2 ** attempt;
1551
+ await policy.sleep(Math.min(policy.maxDelayMs, delay + Math.floor(Math.random() * (delay / 2 + 1))));
1552
+ }
1553
+ }
1554
+ }
1555
+ async send(method, path, body, version2, idempotencyKey) {
1519
1556
  if (this.transport)
1520
1557
  return this.transport.request(method, path.startsWith("/v1/") ? path.slice(3) : path, body, {
1521
- idempotencyKey: method === "GET" ? undefined : options.idempotencyKey ?? crypto.randomUUID(),
1522
- headers: options.version === undefined ? undefined : { "if-match": String(options.version) },
1558
+ idempotencyKey,
1559
+ headers: version2 === undefined ? undefined : { "if-match": String(version2) },
1523
1560
  retry: false
1524
1561
  });
1525
1562
  const apiKey = typeof this.options.apiKey === "function" ? this.options.apiKey() : this.options.apiKey;
@@ -1528,10 +1565,10 @@ class SwitcherClient {
1528
1565
  const headers = { authorization: `Bearer ${apiKey}`, accept: "application/json" };
1529
1566
  if (body !== undefined)
1530
1567
  headers["content-type"] = "application/json";
1531
- if (method !== "GET")
1532
- headers["idempotency-key"] = options.idempotencyKey ?? crypto.randomUUID();
1533
- if (options.version !== undefined)
1534
- headers["if-match"] = String(options.version);
1568
+ if (idempotencyKey !== undefined)
1569
+ headers["idempotency-key"] = idempotencyKey;
1570
+ if (version2 !== undefined)
1571
+ headers["if-match"] = String(version2);
1535
1572
  let response;
1536
1573
  try {
1537
1574
  response = await (this.options.fetch ?? fetch)(`${this.baseUrl}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: "manual", signal: AbortSignal.timeout(this.options.timeoutMs ?? 120000) });
@@ -1573,13 +1610,13 @@ class SwitcherClient {
1573
1610
  return this.request("GET", `/v1/providers/${encodeURIComponent(id)}`);
1574
1611
  }
1575
1612
  createProvider(input, idempotencyKey) {
1576
- return this.request("POST", "/v1/providers", input, { idempotencyKey });
1613
+ return this.request("POST", "/v1/providers", input, { idempotencyKey: operationKey(idempotencyKey) });
1577
1614
  }
1578
1615
  updateProvider(input, version2, idempotencyKey) {
1579
- return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
1616
+ return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey: operationKey(idempotencyKey) });
1580
1617
  }
1581
1618
  deleteProvider(id, version2, idempotencyKey) {
1582
- return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
1619
+ return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey: operationKey(idempotencyKey) });
1583
1620
  }
1584
1621
  async editModel(providerId, operation, value) {
1585
1622
  const model = typeof value === "string" ? undefined : parse2(modelSchema, value);
@@ -1609,10 +1646,10 @@ class SwitcherClient {
1609
1646
  return this.editModel(providerId, "remove", modelId);
1610
1647
  }
1611
1648
  refreshModels(id, idempotencyKey) {
1612
- return this.request("POST", `/v1/providers/${encodeURIComponent(id)}/refresh`, {}, { idempotencyKey });
1649
+ return this.request("POST", `/v1/providers/${encodeURIComponent(id)}/refresh`, {}, { idempotencyKey: operationKey(idempotencyKey) });
1613
1650
  }
1614
1651
  saveCatalog(id, providerVersion, catalog, idempotencyKey) {
1615
- return this.request("PUT", `/v1/providers/${encodeURIComponent(id)}/catalog`, catalog, { version: providerVersion, idempotencyKey });
1652
+ return this.request("PUT", `/v1/providers/${encodeURIComponent(id)}/catalog`, catalog, { version: providerVersion, idempotencyKey: operationKey(idempotencyKey) });
1616
1653
  }
1617
1654
  listModels(id, options = {}) {
1618
1655
  return this.request("GET", `/v1/providers/${encodeURIComponent(id)}/models?${this.query(options)}`);
@@ -1624,16 +1661,16 @@ class SwitcherClient {
1624
1661
  return this.request("GET", `/v1/profiles/${encodeURIComponent(id)}`);
1625
1662
  }
1626
1663
  createProfile(input, idempotencyKey) {
1627
- return this.request("POST", "/v1/profiles", input, { idempotencyKey });
1664
+ return this.request("POST", "/v1/profiles", input, { idempotencyKey: operationKey(idempotencyKey) });
1628
1665
  }
1629
1666
  updateProfile(input, version2, idempotencyKey) {
1630
- return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
1667
+ return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey: operationKey(idempotencyKey) });
1631
1668
  }
1632
1669
  deleteProfile(id, version2, idempotencyKey) {
1633
- return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
1670
+ return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey: operationKey(idempotencyKey) });
1634
1671
  }
1635
1672
  launchPlan(profileId, idempotencyKey) {
1636
- return this.request("POST", "/v1/launch-plans", { profileId }, { idempotencyKey });
1673
+ return this.request("POST", "/v1/launch-plans", { profileId }, { idempotencyKey: operationKey(idempotencyKey) });
1637
1674
  }
1638
1675
  listRuns(options = {}) {
1639
1676
  return this.request("GET", `/v1/runs?${this.query(options)}`);
@@ -1642,10 +1679,10 @@ class SwitcherClient {
1642
1679
  return this.request("GET", `/v1/runs/${encodeURIComponent(id)}`);
1643
1680
  }
1644
1681
  createRun(input, idempotencyKey) {
1645
- return this.request("POST", "/v1/runs", { ...input, modelPolicyVersion: 1 }, { idempotencyKey });
1682
+ return this.request("POST", "/v1/runs", { ...input, modelPolicyVersion: 1 }, { idempotencyKey: operationKey(idempotencyKey) });
1646
1683
  }
1647
1684
  finishRun(id, version2, input, idempotencyKey) {
1648
- return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version: version2, idempotencyKey });
1685
+ return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version: version2, idempotencyKey: operationKey(idempotencyKey) });
1649
1686
  }
1650
1687
  }
1651
1688
  function clientFromEnv(env = process.env, options = {}) {
@@ -1827,15 +1864,26 @@ function createProviderRequest(requestSignal, abortSignal, timing = {}) {
1827
1864
  }
1828
1865
 
1829
1866
  // src/claude-context.ts
1830
- function claudeContextEnvironment(providerBaseUrl, environment = process.env) {
1867
+ function claudeContextEnvironment(providerBaseUrl, environment = process.env, contextWindow) {
1868
+ const result = {};
1869
+ const window = contextWindow !== undefined && Number.isFinite(contextWindow) && contextWindow > 0 ? Math.floor(contextWindow) : undefined;
1870
+ const explicitMaximum = environment.CLAUDE_CODE_MAX_CONTEXT_TOKENS;
1871
+ if (explicitMaximum !== undefined)
1872
+ result.CLAUDE_CODE_MAX_CONTEXT_TOKENS = explicitMaximum;
1873
+ else if (window !== undefined && window < CLAUDE_ONE_MILLION_CONTEXT)
1874
+ result.CLAUDE_CODE_MAX_CONTEXT_TOKENS = String(window);
1831
1875
  const explicit = environment.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
1832
- if (explicit !== undefined)
1833
- return { CLAUDE_CODE_AUTO_COMPACT_WINDOW: explicit };
1834
1876
  const provider = new URL(providerBaseUrl);
1835
- if (provider.origin === "https://api.deepseek.com" && /^\/anthropic(?:\/v1)?\/?$/.test(provider.pathname))
1836
- return { CLAUDE_CODE_AUTO_COMPACT_WINDOW: "786432" };
1837
- return {};
1877
+ if (explicit !== undefined)
1878
+ result.CLAUDE_CODE_AUTO_COMPACT_WINDOW = explicit;
1879
+ else if (provider.origin === "https://api.deepseek.com" && /^\/anthropic(?:\/v1)?\/?$/.test(provider.pathname))
1880
+ result.CLAUDE_CODE_AUTO_COMPACT_WINDOW = "786432";
1881
+ else if (window !== undefined)
1882
+ result.CLAUDE_CODE_AUTO_COMPACT_WINDOW = String(Math.min(CLAUDE_AUTO_COMPACT_WINDOW_MAXIMUM, Math.max(CLAUDE_AUTO_COMPACT_WINDOW_MINIMUM, Math.floor(window * 0.75))));
1883
+ return result;
1838
1884
  }
1885
+ var CLAUDE_AUTO_COMPACT_WINDOW_MINIMUM = 1e5;
1886
+ var CLAUDE_AUTO_COMPACT_WINDOW_MAXIMUM = 1e6;
1839
1887
  var CLAUDE_ONE_MILLION_CONTEXT = 1e6;
1840
1888
  function claudeNativeModelId(id, models) {
1841
1889
  if (/\[1m\]$/i.test(id))
@@ -2481,8 +2529,11 @@ function compileModelPolicy(model, catalog, policy) {
2481
2529
  const result = { version: 1, model: selected, roles: compiledRoles, allowedModels, aliases, fallbacks };
2482
2530
  return { ...result, digest: createHash3("sha256").update(stable(result)).digest("hex") };
2483
2531
  }
2532
+ var CLAUDE_CONTEXT_SUFFIX = /\[1m\]$/i;
2484
2533
  function resolvePolicyModel(compiled, requested) {
2485
- const value = id(requested, "requested model");
2534
+ const value = id(requested, "requested model").replace(CLAUDE_CONTEXT_SUFFIX, "");
2535
+ if (!value)
2536
+ throw new Fault(400, "invalid_model_policy", "requested model is invalid.");
2486
2537
  const canonical = Object.hasOwn(compiled.aliases, value) ? compiled.aliases[value] : value;
2487
2538
  if (!compiled.allowedModels.includes(canonical))
2488
2539
  throw new Fault(403, "model_not_allowed", "Requested model is outside the launch model policy.");
@@ -2581,7 +2632,7 @@ var openapi_default = {
2581
2632
  openapi: "3.0.3",
2582
2633
  info: {
2583
2634
  title: "Switcher API",
2584
- version: "0.2.23",
2635
+ version: "0.2.25",
2585
2636
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2586
2637
  },
2587
2638
  security: [
@@ -7879,16 +7930,15 @@ function compileNativeModelPolicy(input) {
7879
7930
  }
7880
7931
 
7881
7932
  // src/provider-error.ts
7882
- var MAX_ERROR_BYTES = 16 * 1024;
7933
+ var MAX_CLASSIFIED_ERROR_BYTES = 16 * 1024;
7934
+ var MAX_UPSTREAM_ERROR_BYTES = 64 * 1024;
7935
+ var MAX_UPSTREAM_ERROR_MESSAGE = 300;
7883
7936
  var ERROR_READ_TIMEOUT_MS = 1000;
7884
7937
  var contextCodes = new Set(["context_length_exceeded", "context_window_exceeded", "prompt_too_long"]);
7885
- async function isContextOverflow(response) {
7886
- if (![400, 413, 422].includes(response.status) || !response.body) {
7887
- response.body?.cancel().catch(() => {
7888
- return;
7889
- });
7890
- return false;
7891
- }
7938
+ var REDACTED = "[redacted]";
7939
+ async function readBounded(response, limit) {
7940
+ if (!response.body)
7941
+ return;
7892
7942
  const reader = response.body.getReader();
7893
7943
  let timer;
7894
7944
  try {
@@ -7901,20 +7951,17 @@ async function isContextOverflow(response) {
7901
7951
  const { done, value } = await Promise.race([reader.read(), timeout]);
7902
7952
  if (done)
7903
7953
  break;
7954
+ if (bytes + value.byteLength > limit) {
7955
+ text += new TextDecoder("utf-8").decode(value.subarray(0, limit - bytes)).replace(/\uFFFD$/, "");
7956
+ return { text, bytes: limit, truncated: true };
7957
+ }
7904
7958
  bytes += value.byteLength;
7905
- if (bytes > MAX_ERROR_BYTES)
7906
- return false;
7907
7959
  text += decoder.decode(value, { stream: true });
7908
7960
  }
7909
7961
  text += decoder.decode();
7910
- const error = JSON.parse(text)?.error;
7911
- if (!error || typeof error !== "object" || Array.isArray(error))
7912
- return false;
7913
- if ([error.code, error.type].some((code) => typeof code === "string" && contextCodes.has(code)))
7914
- return true;
7915
- return typeof error.message === "string" && /^(?:prompt is too long\b|(?:this model['\u2019]s )?maximum context length (?:is|has been exceeded)\b|(?:input|prompt) tokens? (?:exceed|exceeds|exceeded) (?:the )?(?:maximum|model['\u2019]s) context (?:length|window)\b)/i.test(error.message.trim());
7962
+ return { text, bytes, truncated: false };
7916
7963
  } catch {
7917
- return false;
7964
+ return;
7918
7965
  } finally {
7919
7966
  clearTimeout(timer);
7920
7967
  reader.cancel().catch(() => {
@@ -7922,6 +7969,234 @@ async function isContextOverflow(response) {
7922
7969
  });
7923
7970
  }
7924
7971
  }
7972
+ var record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
7973
+ function classifiesAsOverflow(error) {
7974
+ if (!error)
7975
+ return false;
7976
+ if ([error.code, error.type].some((code) => typeof code === "string" && contextCodes.has(code)))
7977
+ return true;
7978
+ return typeof error.message === "string" && /^(?:prompt is too long\b|(?:this model['\u2019]s )?maximum context length (?:is|has been exceeded)\b|(?:input|prompt) tokens? (?:exceed|exceeds|exceeded) (?:the )?(?:maximum|model['\u2019]s) context (?:length|window)\b)/i.test(error.message.trim());
7979
+ }
7980
+ function redactCredentials(text, known = []) {
7981
+ let out = text;
7982
+ for (const value of known)
7983
+ if (typeof value === "string" && value.length > 0)
7984
+ out = out.split(value).join(REDACTED);
7985
+ out = out.replace(/\b(https?):\/\/(?:[^\s/@"'<>]*@)?([^\s/?#"'<>]+)([^\s?#"'<>]*)(?:[?#][^\s"'<>]*)?/gi, (_, scheme, host2, path) => `${scheme}://${host2}${path}`).replace(/\b(bearer)\s+[A-Za-z0-9._~+/=-]{4,}/gi, `$1 ${REDACTED}`).replace(/\b(basic)\s+([A-Za-z0-9+/]{8,}={0,2})/gi, (match, word, value) => /[0-9+/=]|[a-z][A-Z]/.test(value) ? `${word} ${REDACTED}` : match).replace(/\b((?:x-)?api[_-]?key|access[_-]?token|refresh[_-]?token|auth[_-]?token|token|secret|password|passwd|authorization|credential)(["']?\s*[:=]\s*["']?)[^\s"',;&}]+/gi, `$1$2${REDACTED}`).replace(/\b(?:sk|pk|rk)-(?:[a-z]+-)*[A-Za-z0-9_-]{8,}/g, REDACTED).replace(/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, REDACTED).replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}|\bgithub_pat_[A-Za-z0-9_]{20,}/g, REDACTED).replace(/\bxox[abposr]-[A-Za-z0-9-]{10,}/g, REDACTED).replace(/\bAIza[0-9A-Za-z_-]{30,}/g, REDACTED).replace(/\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}/g, REDACTED).replace(/\b[0-9a-fA-F]{32,}\b/g, REDACTED).replace(/[A-Za-z0-9+/_=-]{24,}/g, (run) => /[0-9]/.test(run) && /[A-Za-z]/.test(run) && run.length >= 32 ? REDACTED : run);
7986
+ return out;
7987
+ }
7988
+ function cleanMessage(value, known) {
7989
+ const line = redactCredentials(value.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]+/g, " "), known).replace(/\s+/g, " ").trim();
7990
+ if (!line)
7991
+ return;
7992
+ return line.length <= MAX_UPSTREAM_ERROR_MESSAGE ? line : `${line.slice(0, MAX_UPSTREAM_ERROR_MESSAGE - 1).trimEnd()}\u2026`;
7993
+ }
7994
+ var REDACTED_ERROR_TYPE = "provider_error";
7995
+ var cleanType = (value, known) => {
7996
+ if (typeof value !== "string" || !/^[A-Za-z0-9_.:-]{1,64}$/.test(value))
7997
+ return;
7998
+ return redactCredentials(value, known) === value ? value : REDACTED_ERROR_TYPE;
7999
+ };
8000
+ function fieldFromPrefix(text, name) {
8001
+ const match = new RegExp(`"${name}"\\s*:\\s*("(?:[^"\\\\]|\\\\.){0,4096}")`).exec(text);
8002
+ if (!match)
8003
+ return;
8004
+ try {
8005
+ const value = JSON.parse(match[1]);
8006
+ return typeof value === "string" ? value : undefined;
8007
+ } catch {
8008
+ return;
8009
+ }
8010
+ }
8011
+ async function readUpstreamError(response, known = []) {
8012
+ const body = await readBounded(response, MAX_UPSTREAM_ERROR_BYTES);
8013
+ if (!body)
8014
+ return { overflow: false };
8015
+ let parsed, structured = false;
8016
+ if (!body.truncated)
8017
+ try {
8018
+ parsed = JSON.parse(body.text);
8019
+ structured = true;
8020
+ } catch {}
8021
+ const top = record2(parsed);
8022
+ const error = record2(top?.error);
8023
+ const overflow = [400, 413, 422].includes(response.status) && !body.truncated && body.bytes <= MAX_CLASSIFIED_ERROR_BYTES && classifiesAsOverflow(error);
8024
+ let type, message;
8025
+ if (structured) {
8026
+ type = error?.type ?? error?.status ?? error?.code ?? (typeof top?.type === "string" && top.type !== "error" ? top.type : undefined);
8027
+ message = error?.message ?? (typeof top?.error === "string" ? top.error : undefined) ?? top?.message ?? top?.detail;
8028
+ if (message !== undefined && typeof message !== "string")
8029
+ message = JSON.stringify(message);
8030
+ } else if (/^\s*[[{]/.test(body.text)) {
8031
+ type = fieldFromPrefix(body.text, "type");
8032
+ message = fieldFromPrefix(body.text, "message");
8033
+ } else
8034
+ message = body.text;
8035
+ return { overflow, type: cleanType(type, known), message: typeof message === "string" ? cleanMessage(message, known) : undefined };
8036
+ }
8037
+
8038
+ // src/deepseek-messages.ts
8039
+ function deepSeekMessagesRoute(baseUrl) {
8040
+ try {
8041
+ const url = new URL(baseUrl);
8042
+ return url.origin === "https://api.deepseek.com" && /^\/anthropic(?:\/|$)/.test(url.pathname);
8043
+ } catch {
8044
+ return false;
8045
+ }
8046
+ }
8047
+ var KEPT_TOOL_TYPES = new Set(["web_search_20250305", "web_search_20260209"]);
8048
+ var KEPT_BLOCKS = new Set(["text", "image", "document", "thinking", "server_tool_use", "tool_use", "tool_result", "web_search_tool_result", "tool_addition"]);
8049
+ var KEPT_TOOL_RESULT_BLOCKS = new Set(["text", "image", "document", "tool_reference"]);
8050
+ var EMPTY_MESSAGE_TEXT = "[content removed: not supported by this provider]";
8051
+ var isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
8052
+ var typeName = (value) => typeof value === "string" && /^[A-Za-z0-9_.-]{1,64}$/.test(value) ? value : "unknown";
8053
+ var counter = () => Object.create(null);
8054
+ var bump = (counts, key) => {
8055
+ counts[key] = (Object.hasOwn(counts, key) ? counts[key] : 0) + 1;
8056
+ };
8057
+ function contentText(value) {
8058
+ if (typeof value === "string")
8059
+ return value;
8060
+ if (!Array.isArray(value))
8061
+ return "";
8062
+ return value.map((part) => isRecord(part) && part.type === "text" && typeof part.text === "string" ? part.text : "").filter(Boolean).join(`
8063
+
8064
+ `);
8065
+ }
8066
+ function textBlock(text, original) {
8067
+ return isRecord(original.cache_control) ? { type: "text", text, cache_control: original.cache_control } : { type: "text", text };
8068
+ }
8069
+ function rewriteBlock(block, change) {
8070
+ const type = typeName(block.type);
8071
+ if (type === "redacted_thinking") {
8072
+ bump(change.droppedBlocks, type);
8073
+ return;
8074
+ }
8075
+ if (type === "compaction") {
8076
+ const summary = contentText(block.content) || (typeof block.summary === "string" ? block.summary : "") || (typeof block.text === "string" ? block.text : "");
8077
+ if (summary) {
8078
+ bump(change.convertedBlocks, type);
8079
+ return textBlock(summary, block);
8080
+ }
8081
+ }
8082
+ if (type === "search_result") {
8083
+ const text = [block.title, block.source, contentText(block.content)].filter((part) => typeof part === "string" && part !== "").join(`
8084
+ `);
8085
+ if (text) {
8086
+ bump(change.convertedBlocks, type);
8087
+ return textBlock(text, block);
8088
+ }
8089
+ }
8090
+ change.placeholderBlocks++;
8091
+ bump(change.convertedBlocks, type);
8092
+ return textBlock(`[${type} content removed: not supported by this provider]`, block);
8093
+ }
8094
+ function rewriteList(list, kept, change, nested) {
8095
+ let changed = false;
8096
+ const out = [];
8097
+ for (const block of list) {
8098
+ if (!isRecord(block)) {
8099
+ out.push(block);
8100
+ continue;
8101
+ }
8102
+ if (kept.has(block.type)) {
8103
+ if (!nested && block.type === "tool_result" && Array.isArray(block.content)) {
8104
+ const inner = rewriteList(block.content, KEPT_TOOL_RESULT_BLOCKS, change, true);
8105
+ if (inner !== block.content) {
8106
+ changed = true;
8107
+ out.push({ ...block, content: inner });
8108
+ continue;
8109
+ }
8110
+ }
8111
+ out.push(block);
8112
+ continue;
8113
+ }
8114
+ changed = true;
8115
+ const replacement = rewriteBlock(block, change);
8116
+ if (replacement)
8117
+ out.push(replacement);
8118
+ }
8119
+ if (!changed)
8120
+ return list;
8121
+ if (!out.length && list.length) {
8122
+ change.placeholderBlocks++;
8123
+ out.push({ type: "text", text: EMPTY_MESSAGE_TEXT });
8124
+ }
8125
+ return out;
8126
+ }
8127
+ function rewriteDeepSeekMessages(body) {
8128
+ const change = { droppedTools: counter(), customTypesRemoved: 0, deferLoadingRemoved: 0, convertedBlocks: counter(), droppedBlocks: counter(), placeholderBlocks: 0 };
8129
+ let out = body, changed = false;
8130
+ if (Array.isArray(body.tools)) {
8131
+ let droppedSearch = false, toolsChanged = false;
8132
+ const droppedNames = new Set;
8133
+ let tools = [];
8134
+ for (const tool of body.tools) {
8135
+ if (!isRecord(tool) || tool.type === undefined || KEPT_TOOL_TYPES.has(tool.type)) {
8136
+ tools.push(tool);
8137
+ continue;
8138
+ }
8139
+ toolsChanged = true;
8140
+ if (tool.type === "custom") {
8141
+ const { type: _type, ...rest } = tool;
8142
+ tools.push(rest);
8143
+ change.customTypesRemoved++;
8144
+ continue;
8145
+ }
8146
+ const type = typeName(tool.type);
8147
+ bump(change.droppedTools, type);
8148
+ if (type.startsWith("tool_search_tool_"))
8149
+ droppedSearch = true;
8150
+ if (typeof tool.name === "string")
8151
+ droppedNames.add(tool.name);
8152
+ }
8153
+ const deferred = tools.filter((tool) => isRecord(tool) && tool.defer_loading !== undefined);
8154
+ const allDeferred = tools.length > 0 && tools.every((tool) => isRecord(tool) && tool.defer_loading === true);
8155
+ if (deferred.length && (droppedSearch || allDeferred)) {
8156
+ toolsChanged = true;
8157
+ tools = tools.map((tool) => {
8158
+ if (!isRecord(tool) || tool.defer_loading === undefined)
8159
+ return tool;
8160
+ const { defer_loading: _deferLoading, ...rest } = tool;
8161
+ change.deferLoadingRemoved++;
8162
+ return rest;
8163
+ });
8164
+ }
8165
+ if (toolsChanged) {
8166
+ changed = true;
8167
+ out = { ...out };
8168
+ if (tools.length)
8169
+ out.tools = tools;
8170
+ else {
8171
+ delete out.tools;
8172
+ delete out.tool_choice;
8173
+ }
8174
+ if (isRecord(out.tool_choice) && out.tool_choice.type === "tool" && droppedNames.has(out.tool_choice.name))
8175
+ delete out.tool_choice;
8176
+ }
8177
+ }
8178
+ if (Array.isArray(body.messages)) {
8179
+ let messagesChanged = false;
8180
+ const messages = body.messages.map((message) => {
8181
+ if (!isRecord(message) || !Array.isArray(message.content))
8182
+ return message;
8183
+ const content = rewriteList(message.content, KEPT_BLOCKS, change, false);
8184
+ if (content === message.content)
8185
+ return message;
8186
+ messagesChanged = true;
8187
+ return { ...message, content };
8188
+ });
8189
+ if (messagesChanged) {
8190
+ changed = true;
8191
+ out = { ...out, messages };
8192
+ }
8193
+ }
8194
+ return changed ? { body: out, change } : { body };
8195
+ }
8196
+ function deepSeekRewriteLogLine(providerId, change) {
8197
+ const counts = (value) => Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, count]) => `${key}:${count}`).join(",") || "none";
8198
+ return `upstream request rewritten provider=${providerId} dropped_tools=${counts(change.droppedTools)} custom_types_removed=${change.customTypesRemoved} defer_loading_removed=${change.deferLoadingRemoved} converted_blocks=${counts(change.convertedBlocks)} dropped_blocks=${counts(change.droppedBlocks)} placeholder_blocks=${change.placeholderBlocks}`;
8199
+ }
7925
8200
 
7926
8201
  // src/codex-delegation.ts
7927
8202
  function normalizeCodexDelegation(body) {
@@ -8404,30 +8679,34 @@ var MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024;
8404
8679
  var REQUEST_BYTES_PER_CONTEXT_TOKEN = 16;
8405
8680
  var CLOSING_MESSAGE = "Switcher gateway: this launch is shutting down. Start a new session with `switcher launch`.";
8406
8681
  var PROVIDER_FIX = "Check the provider's status and your network, then retry.";
8407
- var EXPLAINED_UPSTREAM_STATUSES = new Set([400, 413, 422]);
8408
- var LARGE_TOOL_COUNT = 128;
8409
- var LARGE_REQUEST_BYTES = 256 * 1024;
8410
8682
  function toolDefinitionCount(body) {
8411
- const record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
8683
+ const record3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
8412
8684
  const count = (value) => {
8413
8685
  if (!value)
8414
8686
  return 0;
8415
8687
  let total = Array.isArray(value.functions) ? value.functions.length : 0;
8416
8688
  for (const tool of Array.isArray(value.tools) ? value.tools : []) {
8417
- const declarations = record2(tool)?.functionDeclarations ?? record2(tool)?.function_declarations;
8689
+ const declarations = record3(tool)?.functionDeclarations ?? record3(tool)?.function_declarations;
8418
8690
  total += Array.isArray(declarations) ? declarations.length : 1;
8419
8691
  }
8420
8692
  return total;
8421
8693
  };
8422
- const top = record2(body);
8423
- return count(top) + count(record2(top?.generateContentRequest));
8694
+ const top = record3(body);
8695
+ return count(top) + count(record3(top?.generateContentRequest));
8424
8696
  }
8425
- function upstreamRejectionMessage(status, providerId, sent) {
8426
- const provider = idSchema.safeParse(providerId).success ? `the provider ${providerId}` : "the provider";
8427
- const message = `Switcher inference gateway: ${provider} rejected the request with HTTP ${status} (upstream_http_${status}). Switcher sent ${sent.tools} tool definition${sent.tools === 1 ? "" : "s"} in a ${Math.ceil(sent.bytes / 1024)} KB request.`;
8428
- if (sent.tools <= LARGE_TOOL_COUNT && sent.bytes <= LARGE_REQUEST_BYTES)
8429
- return message;
8430
- return `${message} Some providers reject large tool sets or large requests. Start a new session instead of resuming this one, or reduce the MCP servers enabled for this harness.`;
8697
+ var safeProviderId = (providerId) => idSchema.safeParse(providerId).success ? providerId : undefined;
8698
+ var sentText = (sent) => `Switcher sent ${sent.tools} tool definition${sent.tools === 1 ? "" : "s"} in a ${Math.ceil(sent.bytes / 1024)} KB request.`;
8699
+ function providerSaid(detail) {
8700
+ if (!detail.message)
8701
+ return `The provider gave no readable error message${detail.type ? ` (error type ${detail.type})` : ""}.`;
8702
+ return `The provider said${detail.type ? ` (${detail.type})` : ""}: ${detail.message}${/[.!?\u2026]$/.test(detail.message) ? "" : "."}`;
8703
+ }
8704
+ function upstreamRejectionMessage(status, providerId, sent, detail) {
8705
+ const id2 = safeProviderId(providerId), provider = id2 ? `the provider ${id2}` : "the provider";
8706
+ return `Switcher inference gateway: ${provider} rejected the request with HTTP ${status} (upstream_http_${status}). ${providerSaid(detail)} ${sentText(sent)}${[400, 413, 422].includes(status) ? " The provider refuses the request as sent, so retrying it unchanged fails the same way." : ""}`;
8707
+ }
8708
+ function rejectionLogLine(status, providerId, sent, detail) {
8709
+ return `upstream rejection provider=${safeProviderId(providerId) ?? "unknown"} status=${status} request_bytes=${sent.bytes} tools=${sent.tools} error_type=${detail.type ?? "none"} message=${JSON.stringify(detail.message ?? "")}`;
8431
8710
  }
8432
8711
  function requestBodyLimit(models, policy) {
8433
8712
  const allowed = new Set(policy.allowedModels);
@@ -8469,6 +8748,7 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8469
8748
  const bodyLimit = requestBodyLimit(input.models, input.compiledPolicy);
8470
8749
  const safeModelFor = (credential) => (value) => typeof value === "string" && value !== credential && (known.has(value) || Object.hasOwn(policy.aliases, value) || input.harness === "antigravity" && value === antigravityHelperModel) ? value : "<unrecognized>";
8471
8750
  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." : code === "closing" ? CLOSING_MESSAGE : `Switcher inference gateway: ${code}.`) } }, { status });
8751
+ const upstreamFail = (status, code, message) => Response.json({ ...input.protocol === "anthropic-messages" ? { type: "error" } : {}, error: { type: "switcher_model_policy", code, message } }, { status });
8472
8752
  let closing = false, stopped;
8473
8753
  const active = new Set;
8474
8754
  const handle = async (request, server) => {
@@ -8540,6 +8820,15 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8540
8820
  }
8541
8821
  event.resolvedModel = resolved;
8542
8822
  event.decision = resolved === requested ? "allow" : "alias";
8823
+ let forwarded = body;
8824
+ if (input.protocol === "anthropic-messages" && deepSeekMessagesRoute(input.baseUrl)) {
8825
+ const rewritten = rewriteDeepSeekMessages(body);
8826
+ forwarded = rewritten.body;
8827
+ if (rewritten.change)
8828
+ try {
8829
+ options.log?.(deepSeekRewriteLogLine(safeProviderId(input.providerId) ?? "unknown", rewritten.change));
8830
+ } catch {}
8831
+ }
8543
8832
  let current = event, response;
8544
8833
  const emitted = new Set;
8545
8834
  const flush = () => {
@@ -8550,15 +8839,15 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8550
8839
  };
8551
8840
  const abort = new AbortController;
8552
8841
  let complete;
8553
- const record2 = { abort, done: new Promise((r) => complete = r) };
8842
+ const record3 = { abort, done: new Promise((r) => complete = r) };
8554
8843
  const activity = createProviderRequest(request.signal, abort.signal, timing);
8555
8844
  const release = () => {
8556
8845
  activity.finish();
8557
8846
  flush();
8558
- active.delete(record2);
8847
+ active.delete(record3);
8559
8848
  complete();
8560
8849
  };
8561
- active.add(record2);
8850
+ active.add(record3);
8562
8851
  const signal = activity.fetchOptions.signal;
8563
8852
  server.timeout(request, 0);
8564
8853
  const headers = { "content-type": "application/json" };
@@ -8587,7 +8876,7 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8587
8876
  flush();
8588
8877
  current = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), resolvedModel: model, decision: "fallback", reason: "explicit_transient_fallback", ...effort.success ? { reasoningEffort: effort.data } : {} };
8589
8878
  }
8590
- const payload = structuredClone(body);
8879
+ const payload = structuredClone(forwarded);
8591
8880
  if (gemini) {
8592
8881
  if (payload.model !== undefined)
8593
8882
  payload.model = `models/${model}`;
@@ -8631,18 +8920,22 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8631
8920
  if (!response)
8632
8921
  throw new Error("provider_request_failed");
8633
8922
  if (!response.ok) {
8634
- const overflow = await isContextOverflow(response);
8923
+ const detail = await readUpstreamError(response, [credential]);
8924
+ const overflow = detail.overflow;
8635
8925
  const paymentRequired = response.status === 402;
8636
8926
  if (overflow)
8637
8927
  current.reason = "context_length_exceeded";
8638
8928
  else if (paymentRequired)
8639
8929
  current.reason = "provider_payment_required";
8640
8930
  release();
8931
+ try {
8932
+ options.log?.(rejectionLogLine(response.status, input.providerId, sent, detail));
8933
+ } catch {}
8641
8934
  if (overflow)
8642
8935
  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 });
8643
8936
  if (paymentRequired)
8644
- return fail(402, "provider_payment_required", "The selected provider rejected this request for billing or credit limits (HTTP 402). Check the account balance, API-key spending limit, and requested output-token budget before retrying.");
8645
- const rejected = fail(response.status >= 300 && response.status < 400 ? 502 : response.status, `upstream_http_${response.status}`, EXPLAINED_UPSTREAM_STATUSES.has(response.status) ? upstreamRejectionMessage(response.status, input.providerId, sent) : undefined);
8937
+ return upstreamFail(402, "provider_payment_required", `The selected provider rejected this request for billing or credit limits (HTTP 402). Check the account balance, API-key spending limit, and requested output-token budget before retrying. ${providerSaid(detail)}`);
8938
+ const rejected = upstreamFail(response.status >= 300 && response.status < 400 ? 502 : response.status, `upstream_http_${response.status}`, upstreamRejectionMessage(response.status, input.providerId, sent, detail));
8646
8939
  const retryAfter = response.headers.get("retry-after");
8647
8940
  if ((response.status === 429 || response.status === 503) && retryAfter && retryAfter.length <= 128 && (/^\d+$/.test(retryAfter) || Number.isFinite(Date.parse(retryAfter))))
8648
8941
  rejected.headers.set("retry-after", retryAfter);
@@ -8689,7 +8982,7 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8689
8982
  const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort, closing: () => closing, release, activity, inspect, interrupted: (reason) => {
8690
8983
  current.reason = reason;
8691
8984
  } });
8692
- record2.cancel = cancel;
8985
+ record3.cancel = cancel;
8693
8986
  return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
8694
8987
  } catch (error) {
8695
8988
  if (error instanceof Fault)
@@ -8722,11 +9015,11 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8722
9015
  })()
8723
9016
  };
8724
9017
  }
8725
- function createInferenceGateway(input, timing = {}) {
9018
+ function createInferenceGateway(input, timing = {}, options = {}) {
8726
9019
  const token = crypto.randomUUID() + crypto.randomUUID();
8727
9020
  const digest = (value) => createHash6("sha256").update(value).digest();
8728
9021
  const expected = digest(token);
8729
- const handler = createInferenceHandler(input, timing);
9022
+ const handler = createInferenceHandler(input, timing, options);
8730
9023
  let stopped;
8731
9024
  const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: handler.bodyLimit, idleTimeout: 255, async fetch(request, server2) {
8732
9025
  if (handler.closing())
@@ -9466,7 +9759,7 @@ var action = (value) => ({ bash: "shell", task: "subagent", write: "edit", patch
9466
9759
  function invalid2(path, field) {
9467
9760
  throw new Error(`OpenCode 2 cannot preserve ${field} in ${path}; use a supported explicit permission or agent declaration.`);
9468
9761
  }
9469
- function record2(value, path, field) {
9762
+ function record3(value, path, field) {
9470
9763
  if (!object4(value))
9471
9764
  invalid2(path, field);
9472
9765
  return value;
@@ -9484,15 +9777,15 @@ function literal2(value, path, field) {
9484
9777
  function permissions(value, path, home) {
9485
9778
  const result = [];
9486
9779
  if (own2(value, "tools"))
9487
- for (const [name, enabled] of Object.entries(record2(value.tools, path, "tools permission"))) {
9780
+ for (const [name, enabled] of Object.entries(record3(value.tools, path, "tools permission"))) {
9488
9781
  if (typeof enabled !== "boolean")
9489
9782
  invalid2(path, "tools permission");
9490
9783
  result.push({ action: action(name), resource: "*", effect: enabled ? "allow" : "deny" });
9491
9784
  }
9492
9785
  if (own2(value, "permission")) {
9493
- const legacy = typeof value.permission === "string" ? { "*": value.permission } : record2(value.permission, path, "permission");
9786
+ const legacy = typeof value.permission === "string" ? { "*": value.permission } : record3(value.permission, path, "permission");
9494
9787
  for (const [name, permission2] of Object.entries(legacy)) {
9495
- const entries = typeof permission2 === "string" ? { "*": permission2 } : record2(permission2, path, "permission");
9788
+ const entries = typeof permission2 === "string" ? { "*": permission2 } : record3(permission2, path, "permission");
9496
9789
  for (const [resource, item] of Object.entries(entries)) {
9497
9790
  const parsed = effect.safeParse(item);
9498
9791
  if (!parsed.success)
@@ -9537,7 +9830,7 @@ function jsonc2(text, path) {
9537
9830
  if (errors.length)
9538
9831
  invalid2(path, "JSON/JSONC configuration");
9539
9832
  rejectDuplicateKeys2(parseTree3(text), path);
9540
- return record2(value, path, "configuration object");
9833
+ return record3(value, path, "configuration object");
9541
9834
  }
9542
9835
  async function checkRemoteConfiguration(dataHome) {
9543
9836
  const path = join12(dataHome, "opencode", "opencode.db");
@@ -9690,7 +9983,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9690
9983
  if (parsed.errors.length)
9691
9984
  invalid2(path, "agent YAML frontmatter");
9692
9985
  try {
9693
- data2 = record2(parsed.toJS({ maxAliasCount: 0 }), path, "agent YAML frontmatter");
9986
+ data2 = record3(parsed.toJS({ maxAliasCount: 0 }), path, "agent YAML frontmatter");
9694
9987
  } catch {
9695
9988
  invalid2(path, "agent YAML frontmatter");
9696
9989
  }
@@ -9765,9 +10058,9 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9765
10058
  policies.push(...parsed.data);
9766
10059
  }
9767
10060
  providerPolicies.push(policies);
9768
- const legacy = own2(value, "agent") ? record2(value.agent, path, "agent") : {};
9769
- const modes = own2(value, "mode") ? record2(value.mode, path, "mode") : {};
9770
- const native = own2(value, "agents") ? record2(value.agents, path, "agents") : {};
10061
+ const legacy = own2(value, "agent") ? record3(value.agent, path, "agent") : {};
10062
+ const modes = own2(value, "mode") ? record3(value.mode, path, "mode") : {};
10063
+ const native = own2(value, "agents") ? record3(value.agents, path, "agents") : {};
9771
10064
  const selected = new Map(Object.entries(legacy).map(([name, item]) => [name, { item, legacy: true, primary: false }]));
9772
10065
  for (const [name, item] of Object.entries(modes))
9773
10066
  selected.set(name, { item, legacy: true, primary: true });
@@ -9775,7 +10068,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9775
10068
  selected.set(name, { item, legacy: false, primary: false });
9776
10069
  for (const [name, entry] of selected) {
9777
10070
  literal2(name, path, "agent name");
9778
- const item = record2(entry.item, path, "agent");
10071
+ const item = record3(entry.item, path, "agent");
9779
10072
  const target = agents[name] ??= {};
9780
10073
  const system = entry.legacy ? item.prompt : item.system;
9781
10074
  if (system !== undefined)
@@ -10067,7 +10360,7 @@ function createHermesBridge(input, timing = {}) {
10067
10360
  return Response.json({ error: { message: "Model is outside the Switcher launch catalog" } }, { status: 403 });
10068
10361
  const abortController = new AbortController;
10069
10362
  let complete;
10070
- const record3 = {
10363
+ const record4 = {
10071
10364
  abort: abortController,
10072
10365
  done: new Promise((resolve8) => {
10073
10366
  complete = resolve8;
@@ -10076,11 +10369,11 @@ function createHermesBridge(input, timing = {}) {
10076
10369
  const activity = createProviderRequest(request.signal, abortController.signal, timing);
10077
10370
  const release = () => {
10078
10371
  activity.finish();
10079
- active.delete(record3);
10372
+ active.delete(record4);
10080
10373
  complete();
10081
10374
  };
10082
- active.add(record3);
10083
- record3.cancel = async () => {
10375
+ active.add(record4);
10376
+ record4.cancel = async () => {
10084
10377
  abortController.abort();
10085
10378
  release();
10086
10379
  };
@@ -10116,7 +10409,7 @@ function createHermesBridge(input, timing = {}) {
10116
10409
  return new Response(null, { status: upstream.status });
10117
10410
  }
10118
10411
  const { stream, cancel } = proxyProviderStream({ response: upstream, protocol: input.protocol, requestSignal: request.signal, abort: abortController, closing: () => closing, release, activity });
10119
- record3.cancel = cancel;
10412
+ record4.cancel = cancel;
10120
10413
  return new Response(stream, {
10121
10414
  status: upstream.status,
10122
10415
  headers: {
@@ -10136,11 +10429,11 @@ function createHermesBridge(input, timing = {}) {
10136
10429
  cleanup: () => stopped ??= (async () => {
10137
10430
  closing = true;
10138
10431
  const pending = [...active];
10139
- for (const record3 of pending)
10140
- record3.abort.abort();
10141
- await Promise.allSettled(pending.map(async (record3) => {
10142
- await record3.cancel?.();
10143
- await record3.done;
10432
+ for (const record4 of pending)
10433
+ record4.abort.abort();
10434
+ await Promise.allSettled(pending.map(async (record4) => {
10435
+ await record4.cancel?.();
10436
+ await record4.done;
10144
10437
  }));
10145
10438
  await server.stop(true);
10146
10439
  })()
@@ -10585,9 +10878,9 @@ function toolsPermission(value, path) {
10585
10878
  function expandHomePattern(value) {
10586
10879
  if (typeof value !== "object" || value === null || Array.isArray(value))
10587
10880
  return value;
10588
- const record3 = value;
10881
+ const record4 = value;
10589
10882
  const output = {};
10590
- for (const [key, item] of Object.entries(record3)) {
10883
+ for (const [key, item] of Object.entries(record4)) {
10591
10884
  const expanded = key === "~" ? homedir8() : key.startsWith("~/") ? join15(homedir8(), key.slice(2)) : key;
10592
10885
  output[expanded] = expandHomePattern(item);
10593
10886
  }
@@ -10596,9 +10889,9 @@ function expandHomePattern(value) {
10596
10889
  function policyWithExpandedPatterns(value) {
10597
10890
  if (typeof value !== "object" || value === null || Array.isArray(value))
10598
10891
  return value;
10599
- const record3 = value;
10892
+ const record4 = value;
10600
10893
  const output = {};
10601
- for (const [key, item] of Object.entries(record3))
10894
+ for (const [key, item] of Object.entries(record4))
10602
10895
  output[key] = typeof item === "object" && item !== null && !Array.isArray(item) ? expandHomePattern(item) : item;
10603
10896
  return output;
10604
10897
  }
@@ -10863,16 +11156,16 @@ function grokBridge(input, timing = {}) {
10863
11156
  if (closing)
10864
11157
  return Response.json({ error: { message: "Bridge is closing" } }, { status: 503 });
10865
11158
  let complete;
10866
- const record3 = { abort: new AbortController, done: new Promise((resolve9) => {
11159
+ const record4 = { abort: new AbortController, done: new Promise((resolve9) => {
10867
11160
  complete = resolve9;
10868
11161
  }) };
10869
- const activity = createProviderRequest(request.signal, record3.abort.signal, timing);
11162
+ const activity = createProviderRequest(request.signal, record4.abort.signal, timing);
10870
11163
  const release = () => {
10871
11164
  activity.finish();
10872
- active.delete(record3);
11165
+ active.delete(record4);
10873
11166
  complete();
10874
11167
  };
10875
- active.add(record3);
11168
+ active.add(record4);
10876
11169
  server2.timeout(request, 0);
10877
11170
  try {
10878
11171
  const response = await activity.run(() => fetch(`${input.baseUrl}${apiPath}`, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
@@ -10887,8 +11180,8 @@ function grokBridge(input, timing = {}) {
10887
11180
  release();
10888
11181
  return new Response(null, { status: response.status });
10889
11182
  }
10890
- const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record3.abort, closing: () => closing, release, activity });
10891
- record3.cancel = cancel;
11183
+ const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record4.abort, closing: () => closing, release, activity });
11184
+ record4.cancel = cancel;
10892
11185
  return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
10893
11186
  } catch {
10894
11187
  release();
@@ -10898,11 +11191,11 @@ function grokBridge(input, timing = {}) {
10898
11191
  return { baseUrl: new URL("v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
10899
11192
  closing = true;
10900
11193
  const pending = [...active];
10901
- for (const record3 of pending)
10902
- record3.abort.abort();
10903
- await Promise.allSettled(pending.map(async (record3) => {
10904
- await record3.cancel?.();
10905
- await record3.done;
11194
+ for (const record4 of pending)
11195
+ record4.abort.abort();
11196
+ await Promise.allSettled(pending.map(async (record4) => {
11197
+ await record4.cancel?.();
11198
+ await record4.done;
10906
11199
  }));
10907
11200
  await server.stop(true);
10908
11201
  })() };
@@ -11175,7 +11468,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11175
11468
  env.ANTHROPIC_BASE_URL = input.baseUrl.replace(/\/v1$/, "");
11176
11469
  const nativeModel = (id2) => claudeNativeModelId(id2, input.models);
11177
11470
  Object.assign(env, claudeNativeModelEnvironment(input.nativePolicy?.env, input.models));
11178
- Object.assign(env, claudeContextEnvironment(providerBaseUrl));
11471
+ Object.assign(env, claudeContextEnvironment(providerBaseUrl, process.env, input.models.find((model3) => model3.id === input.model)?.contextWindow));
11179
11472
  env.ANTHROPIC_MODEL = nativeModel(input.model);
11180
11473
  env.ANTHROPIC_DEFAULT_MODEL = nativeModel(input.model);
11181
11474
  env.CLAUDE_CODE_SUBAGENT_MODEL = nativeModel(input.compiledPolicy?.roles.subagent ?? input.model);
@@ -15163,11 +15456,11 @@ var MAX_LOOKUPS_PER_RETRY = 4;
15163
15456
  var processKey = (entry) => `${entry.pid}@${entry.start}`;
15164
15457
  var SETTLED_MS = 120000;
15165
15458
  var SETTLED_SCAN_FACTOR = 5;
15166
- var staticFields = (record3) => {
15167
- const { lastUsedAt: _used, lastHolderAt: _holder, released: _released, holders: _holders, extendedAt: _extended, ...rest } = record3;
15459
+ var staticFields = (record4) => {
15460
+ const { lastUsedAt: _used, lastHolderAt: _holder, released: _released, holders: _holders, extendedAt: _extended, ...rest } = record4;
15168
15461
  return rest;
15169
15462
  };
15170
- var holderFields = (record3) => ({ lastUsedAt: record3.lastUsedAt, lastHolderAt: record3.lastHolderAt, released: record3.released, holders: record3.holders, ...record3.extendedAt !== undefined ? { extendedAt: record3.extendedAt } : {} });
15463
+ var holderFields = (record4) => ({ lastUsedAt: record4.lastUsedAt, lastHolderAt: record4.lastHolderAt, released: record4.released, holders: record4.holders, ...record4.extendedAt !== undefined ? { extendedAt: record4.extendedAt } : {} });
15171
15464
  var LAUNCH_HINT = "Start a new session with `switcher launch`. If this is a Claude Code background session, its background host still carries the ended launch: exit that host too, so the next `switcher launch` starts a new one.";
15172
15465
  var loopbackHosts = (port) => new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
15173
15466
  var errorBody = (status, code, message) => Response.json({ type: "error", error: { type: status === 401 ? "authentication_error" : status === 403 ? "permission_error" : status === 404 ? "not_found_error" : status === 400 ? "invalid_request_error" : "api_error", code, message } }, { status });
@@ -15230,7 +15523,7 @@ async function routeSettingsDirectory(path) {
15230
15523
  throw new Fault(400, "invalid_route", "A durable route's settings folder must be a private directory owned by this user (mode 0700).");
15231
15524
  return path;
15232
15525
  }
15233
- var routeFile = (record3) => record3.route ? join22(record3.route.settingsDir, `claude-route-${record3.id}.json`) : undefined;
15526
+ var routeFile = (record4) => record4.route ? join22(record4.route.settingsDir, `claude-route-${record4.id}.json`) : undefined;
15234
15527
  async function launchStateDirectory(path) {
15235
15528
  if (path === undefined)
15236
15529
  return;
@@ -15333,12 +15626,12 @@ async function startGatewayService(options = {}) {
15333
15626
  } else
15334
15627
  launch.eventsDropped = Math.min(1e6, launch.eventsDropped + 1);
15335
15628
  }
15336
- }, options.timing, { credential: () => credentialFor(launch)() });
15337
- const adopt = (record3, credential) => {
15338
- const launch = { record: record3, credential, events: [], eventBytes: 0, eventsDropped: 0, dirty: false, persistedAt: 0, usedPersistedAt: 0, recentAt: now() };
15629
+ }, options.timing, { credential: () => credentialFor(launch)(), log: (line) => log(`launch ${launch.record.id.slice(0, 8)} ${line}`) });
15630
+ const adopt = (record4, credential) => {
15631
+ const launch = { record: record4, credential, events: [], eventBytes: 0, eventsDropped: 0, dirty: false, persistedAt: 0, usedPersistedAt: 0, recentAt: now() };
15339
15632
  launch.handler = handlerFor(launch);
15340
- launches.set(record3.id, launch);
15341
- byDigest.set(record3.tokenDigest, launch);
15633
+ launches.set(record4.id, launch);
15634
+ byDigest.set(record4.tokenDigest, launch);
15342
15635
  return launch;
15343
15636
  };
15344
15637
  const endedPath = (id2) => join22(paths.ended, `${id2}.json`);
@@ -15349,8 +15642,8 @@ async function startGatewayService(options = {}) {
15349
15642
  return;
15350
15643
  });
15351
15644
  };
15352
- const retireRoute = async (record3) => {
15353
- const file = routeFile(record3);
15645
+ const retireRoute = async (record4) => {
15646
+ const file = routeFile(record4);
15354
15647
  if (!file)
15355
15648
  return;
15356
15649
  const info2 = await lstat11(file).catch(() => {
@@ -15361,12 +15654,12 @@ async function startGatewayService(options = {}) {
15361
15654
  `).catch(() => {
15362
15655
  return;
15363
15656
  });
15364
- await releaseAdoptedRoutes(record3);
15657
+ await releaseAdoptedRoutes(record4);
15365
15658
  };
15366
- const releaseAdoptedRoutes = async (record3) => {
15367
- if (!record3.route)
15659
+ const releaseAdoptedRoutes = async (record4) => {
15660
+ if (!record4.route)
15368
15661
  return;
15369
- const dir = record3.route.settingsDir;
15662
+ const dir = record4.route.settingsDir;
15370
15663
  const tokenOf = (value) => {
15371
15664
  if (!value || typeof value !== "object" || Array.isArray(value))
15372
15665
  return;
@@ -15395,7 +15688,7 @@ async function startGatewayService(options = {}) {
15395
15688
  continue;
15396
15689
  } else {
15397
15690
  const token = tokenOf(value);
15398
- if (token === undefined || sha256(token) !== record3.tokenDigest)
15691
+ if (token === undefined || sha256(token) !== record4.tokenDigest)
15399
15692
  continue;
15400
15693
  }
15401
15694
  await rm5(path2, { force: true });
@@ -15414,7 +15707,7 @@ async function startGatewayService(options = {}) {
15414
15707
  continue;
15415
15708
  const { env: _env, ...picker } = value;
15416
15709
  const token = tokenOf(value);
15417
- if (token === undefined || sha256(token) !== record3.tokenDigest)
15710
+ if (token === undefined || sha256(token) !== record4.tokenDigest)
15418
15711
  continue;
15419
15712
  await writePrivate(path, JSON.stringify(picker, null, 2) + `
15420
15713
  `);
@@ -15582,14 +15875,14 @@ async function startGatewayService(options = {}) {
15582
15875
  if (!holders.length)
15583
15876
  return fail();
15584
15877
  const { endedAt: _endedAt, ...fixed } = entry.record;
15585
- const record3 = { ...fixed, ...durable ? { routeRevived: true } : {}, lastUsedAt: at, lastHolderAt: at, released: true, holders };
15586
- await writePrivate(join22(paths.launches, `${record3.id}.json`), JSON.stringify(staticFields(record3)));
15587
- const launch = adopt(record3, entry.credential);
15878
+ const record4 = { ...fixed, ...durable ? { routeRevived: true } : {}, lastUsedAt: at, lastHolderAt: at, released: true, holders };
15879
+ await writePrivate(join22(paths.launches, `${record4.id}.json`), JSON.stringify(staticFields(record4)));
15880
+ const launch = adopt(record4, entry.credential);
15588
15881
  launch.probedAfterLauncher = true;
15589
15882
  track(launch, table, at);
15590
15883
  await persist(launch, true);
15591
15884
  await forgetEnded(entry);
15592
- log(`launch ${record3.id.slice(0, 8)} revived for a process that still uses it ${durable ? "through its durable route" : "under a current launch"}`);
15885
+ log(`launch ${record4.id.slice(0, 8)} revived for a process that still uses it ${durable ? "through its durable route" : "under a current launch"}`);
15593
15886
  return launch;
15594
15887
  } catch {
15595
15888
  return fail();
@@ -15713,7 +16006,7 @@ async function startGatewayService(options = {}) {
15713
16006
  }
15714
16007
  }
15715
16008
  const token = randomBytes2(32).toString("base64url"), at = now();
15716
- const record3 = {
16009
+ const record4 = {
15717
16010
  schema: 1,
15718
16011
  id: randomUUID7(),
15719
16012
  tokenDigest: sha256(token),
@@ -15728,12 +16021,12 @@ async function startGatewayService(options = {}) {
15728
16021
  ...stateDir ? { stateDir } : {},
15729
16022
  ...route2 ? { route: route2 } : {}
15730
16023
  };
15731
- const launch = adopt(record3, input.credential);
16024
+ const launch = adopt(record4, input.credential);
15732
16025
  launch.baseline = new Set([...table.values()].map(processKey));
15733
- await writePrivate(join22(paths.launches, `${record3.id}.json`), JSON.stringify(staticFields(record3)));
16026
+ await writePrivate(join22(paths.launches, `${record4.id}.json`), JSON.stringify(staticFields(record4)));
15734
16027
  await persist(launch, true);
15735
- log(`launch ${record3.id.slice(0, 8)} registered (${record3.gateway.harness}, ${record3.gateway.model})`);
15736
- return { id: record3.id, token, baseUrl: `${url}/${record3.gateway.protocol === "gemini-generate-content" ? "v1beta" : "v1"}`, ...route2 ? { releasesAdoptedRoutes: true } : {} };
16028
+ log(`launch ${record4.id.slice(0, 8)} registered (${record4.gateway.harness}, ${record4.gateway.model})`);
16029
+ return { id: record4.id, token, baseUrl: `${url}/${record4.gateway.protocol === "gemini-generate-content" ? "v1beta" : "v1"}`, ...route2 ? { releasesAdoptedRoutes: true } : {} };
15737
16030
  };
15738
16031
  const release = async (launch) => {
15739
16032
  const table = await processTable().catch(() => {
@@ -15764,7 +16057,7 @@ async function startGatewayService(options = {}) {
15764
16057
  if (method === "GET" && url2.pathname === "/v1/status")
15765
16058
  return Response.json({ service: "switcher-gateway", protocol: GATEWAY_PROTOCOL, version: VERSION, pid: process.pid, port, baseUrl: `http://127.0.0.1:${port}`, launches: launches.size, supervisor: options.supervisor ?? "none" });
15766
16059
  if (method === "GET" && url2.pathname === "/v1/launches")
15767
- return Response.json({ data: [...launches.values()].map(({ record: record3 }) => ({ id: record3.id, harness: record3.gateway.harness, model: record3.gateway.model, createdAt: new Date(record3.createdAt).toISOString(), lastUsedAt: new Date(record3.lastUsedAt).toISOString(), holders: record3.holders.length, released: record3.released, credential: record3.credential.source, durable: record3.route !== undefined })) });
16060
+ return Response.json({ data: [...launches.values()].map(({ record: record4 }) => ({ id: record4.id, harness: record4.gateway.harness, model: record4.gateway.model, createdAt: new Date(record4.createdAt).toISOString(), lastUsedAt: new Date(record4.lastUsedAt).toISOString(), holders: record4.holders.length, released: record4.released, credential: record4.credential.source, durable: record4.route !== undefined })) });
15768
16061
  if (method === "POST" && url2.pathname === "/v1/launches")
15769
16062
  return Response.json(await register(registrationSchema.parse(await json(request))), { status: 201 });
15770
16063
  if (method === "POST" && url2.pathname === "/v1/stop") {
@@ -15807,13 +16100,13 @@ async function startGatewayService(options = {}) {
15807
16100
  if (!/^[0-9a-f-]{36}\.json$/.test(name))
15808
16101
  continue;
15809
16102
  try {
15810
- const record3 = await readRecord(paths.launches, name.slice(0, -5));
15811
- const extend = record3.extendedAt === undefined || Math.max(record3.lastHolderAt, record3.lastUsedAt) > record3.extendedAt;
16103
+ const record4 = await readRecord(paths.launches, name.slice(0, -5));
16104
+ const extend = record4.extendedAt === undefined || Math.max(record4.lastHolderAt, record4.lastUsedAt) > record4.extendedAt;
15812
16105
  if (extend) {
15813
- record3.lastHolderAt = Math.max(record3.lastHolderAt, restoredAt);
15814
- record3.extendedAt = restoredAt;
16106
+ record4.lastHolderAt = Math.max(record4.lastHolderAt, restoredAt);
16107
+ record4.extendedAt = restoredAt;
15815
16108
  }
15816
- const launch = adopt(record3);
16109
+ const launch = adopt(record4);
15817
16110
  if (extend)
15818
16111
  await persist(launch, true);
15819
16112
  } catch {
@@ -15824,14 +16117,14 @@ async function startGatewayService(options = {}) {
15824
16117
  if (!/^[0-9a-f-]{36}\.json$/.test(name))
15825
16118
  continue;
15826
16119
  try {
15827
- const record3 = endedSchema.parse(await readPrivateJson(join22(paths.ended, name)));
15828
- if (record3.id !== name.slice(0, -5))
16120
+ const record4 = endedSchema.parse(await readPrivateJson(join22(paths.ended, name)));
16121
+ if (record4.id !== name.slice(0, -5))
15829
16122
  throw new Error("ended launch record id mismatch");
15830
- const entry = { record: record3, failed: new Map, lookups: [] };
15831
- if (launches.has(record3.id) || byDigest.has(record3.tokenDigest))
16123
+ const entry = { record: record4, failed: new Map, lookups: [] };
16124
+ if (launches.has(record4.id) || byDigest.has(record4.tokenDigest))
15832
16125
  await forgetEnded(entry);
15833
16126
  else
15834
- ended.set(record3.tokenDigest, entry);
16127
+ ended.set(record4.tokenDigest, entry);
15835
16128
  } catch {
15836
16129
  log(`ignored unreadable ended launch record ${name.slice(0, 8)}`);
15837
16130
  }