@hasna/switcher 0.2.22 → 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.22";
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.22",
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));
8696
+ }
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." : ""}`;
8424
8707
  }
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.`;
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())
@@ -9010,7 +9303,7 @@ async function readCodexAgentConfig(path) {
9010
9303
  }
9011
9304
 
9012
9305
  // src/harnesses.ts
9013
- import { access as access3, lstat as lstat6, mkdir as mkdir10, readFile as readFile6, readdir as readdir4, rename as rename2, writeFile as writeFile13, rm as rm2 } from "fs/promises";
9306
+ import { access as access3, lstat as lstat6, mkdir as mkdir10, open as open3, readFile as readFile6, readdir as readdir4, rename as rename2, writeFile as writeFile13, rm as rm2 } from "fs/promises";
9014
9307
  import { basename as basename2, dirname as dirname7, join as join15, isAbsolute as isAbsolute13, resolve as resolve8 } from "path";
9015
9308
  import { homedir as homedir8, tmpdir } from "os";
9016
9309
  import { createHash as createHash9, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual5 } from "crypto";
@@ -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
  })()
@@ -10468,6 +10761,45 @@ async function routeJsonFile(path, value) {
10468
10761
  }
10469
10762
  return path;
10470
10763
  }
10764
+ async function adoptClaudeSettingsRoutes(dir, route2) {
10765
+ let adopted = 0;
10766
+ for (const name of await readdir4(dir).catch(() => [])) {
10767
+ if (!/^claude-settings-[0-9a-f]{32}\.json$/.test(name))
10768
+ continue;
10769
+ const path = join15(dir, name);
10770
+ const info = await lstat6(path).catch(() => {
10771
+ return;
10772
+ });
10773
+ if (!info?.isFile() || info.nlink !== 1 || (info.mode & 63) !== 0 || info.uid !== process.getuid?.())
10774
+ continue;
10775
+ let value;
10776
+ try {
10777
+ value = JSON.parse(await readFile6(path, "utf8"));
10778
+ } catch {
10779
+ continue;
10780
+ }
10781
+ if (!value || typeof value !== "object" || Array.isArray(value) || !("modelPicker" in value))
10782
+ continue;
10783
+ const temporary = `${path}.${randomUUID4()}.tmp`;
10784
+ try {
10785
+ const handle = await open3(temporary, "wx", 384);
10786
+ try {
10787
+ await handle.writeFile(JSON.stringify({ ...value, ...route2 }, null, 2) + `
10788
+ `);
10789
+ await handle.sync();
10790
+ } finally {
10791
+ await handle.close();
10792
+ }
10793
+ await rename2(temporary, path);
10794
+ adopted++;
10795
+ } catch {
10796
+ await rm2(temporary, { force: true }).catch(() => {
10797
+ return;
10798
+ });
10799
+ }
10800
+ }
10801
+ return adopted;
10802
+ }
10471
10803
  async function projectInstructionPaths(cwd) {
10472
10804
  let dir = resolve8(cwd);
10473
10805
  while (true) {
@@ -10546,9 +10878,9 @@ function toolsPermission(value, path) {
10546
10878
  function expandHomePattern(value) {
10547
10879
  if (typeof value !== "object" || value === null || Array.isArray(value))
10548
10880
  return value;
10549
- const record3 = value;
10881
+ const record4 = value;
10550
10882
  const output = {};
10551
- for (const [key, item] of Object.entries(record3)) {
10883
+ for (const [key, item] of Object.entries(record4)) {
10552
10884
  const expanded = key === "~" ? homedir8() : key.startsWith("~/") ? join15(homedir8(), key.slice(2)) : key;
10553
10885
  output[expanded] = expandHomePattern(item);
10554
10886
  }
@@ -10557,9 +10889,9 @@ function expandHomePattern(value) {
10557
10889
  function policyWithExpandedPatterns(value) {
10558
10890
  if (typeof value !== "object" || value === null || Array.isArray(value))
10559
10891
  return value;
10560
- const record3 = value;
10892
+ const record4 = value;
10561
10893
  const output = {};
10562
- for (const [key, item] of Object.entries(record3))
10894
+ for (const [key, item] of Object.entries(record4))
10563
10895
  output[key] = typeof item === "object" && item !== null && !Array.isArray(item) ? expandHomePattern(item) : item;
10564
10896
  return output;
10565
10897
  }
@@ -10824,16 +11156,16 @@ function grokBridge(input, timing = {}) {
10824
11156
  if (closing)
10825
11157
  return Response.json({ error: { message: "Bridge is closing" } }, { status: 503 });
10826
11158
  let complete;
10827
- const record3 = { abort: new AbortController, done: new Promise((resolve9) => {
11159
+ const record4 = { abort: new AbortController, done: new Promise((resolve9) => {
10828
11160
  complete = resolve9;
10829
11161
  }) };
10830
- const activity = createProviderRequest(request.signal, record3.abort.signal, timing);
11162
+ const activity = createProviderRequest(request.signal, record4.abort.signal, timing);
10831
11163
  const release = () => {
10832
11164
  activity.finish();
10833
- active.delete(record3);
11165
+ active.delete(record4);
10834
11166
  complete();
10835
11167
  };
10836
- active.add(record3);
11168
+ active.add(record4);
10837
11169
  server2.timeout(request, 0);
10838
11170
  try {
10839
11171
  const response = await activity.run(() => fetch(`${input.baseUrl}${apiPath}`, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
@@ -10848,8 +11180,8 @@ function grokBridge(input, timing = {}) {
10848
11180
  release();
10849
11181
  return new Response(null, { status: response.status });
10850
11182
  }
10851
- const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record3.abort, closing: () => closing, release, activity });
10852
- 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;
10853
11185
  return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
10854
11186
  } catch {
10855
11187
  release();
@@ -10859,11 +11191,11 @@ function grokBridge(input, timing = {}) {
10859
11191
  return { baseUrl: new URL("v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
10860
11192
  closing = true;
10861
11193
  const pending = [...active];
10862
- for (const record3 of pending)
10863
- record3.abort.abort();
10864
- await Promise.allSettled(pending.map(async (record3) => {
10865
- await record3.cancel?.();
10866
- 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;
10867
11199
  }));
10868
11200
  await server.stop(true);
10869
11201
  })() };
@@ -11136,7 +11468,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11136
11468
  env.ANTHROPIC_BASE_URL = input.baseUrl.replace(/\/v1$/, "");
11137
11469
  const nativeModel = (id2) => claudeNativeModelId(id2, input.models);
11138
11470
  Object.assign(env, claudeNativeModelEnvironment(input.nativePolicy?.env, input.models));
11139
- Object.assign(env, claudeContextEnvironment(providerBaseUrl));
11471
+ Object.assign(env, claudeContextEnvironment(providerBaseUrl, process.env, input.models.find((model3) => model3.id === input.model)?.contextWindow));
11140
11472
  env.ANTHROPIC_MODEL = nativeModel(input.model);
11141
11473
  env.ANTHROPIC_DEFAULT_MODEL = nativeModel(input.model);
11142
11474
  env.CLAUDE_CODE_SUBAGENT_MODEL = nativeModel(input.compiledPolicy?.roles.subagent ?? input.model);
@@ -11145,8 +11477,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11145
11477
  env[input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"] = input.credential ?? "switcher-local-no-auth";
11146
11478
  const picker = { modelPicker: { replaceBuiltInOptions: true, options: input.models.map((m) => ({ model: nativeModel(m.id), label: m.name, description: m.description?.slice(0, 300) })) } };
11147
11479
  const route2 = input.routeSettingsFile && input.credential ? { env: { ANTHROPIC_BASE_URL: env.ANTHROPIC_BASE_URL, ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", [input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"]: input.credential } } : undefined;
11148
- const file2 = route2 ? await routeJsonFile(input.routeSettingsFile, { ...picker, ...route2 }) : input.sessionDir ? await durableJsonFile(claudeSettingsDirectory(input.sessionDir), "claude-settings", picker) : await jsonFile(input.stateDir, "claude-settings.json", picker);
11480
+ const file2 = route2 ? await routeJsonFile(input.routeSettingsFile, { ...picker, ...route2 }) : input.sessionDir ? await durableJsonFile(claudeSettingsDirectory(input.sessionDir), "claude-picker", picker) : await jsonFile(input.stateDir, "claude-settings.json", picker);
11149
11481
  configPaths.push(file2);
11482
+ if (route2 && input.adoptRoutes) {
11483
+ const adopted = await adoptClaudeSettingsRoutes(dirname7(file2), route2);
11484
+ if (adopted)
11485
+ warnings.push(`Gave this launch's gateway route to ${adopted} earlier Claude settings file${adopted === 1 ? "" : "s"} of this profile; their background sessions use it when their host next starts them.`);
11486
+ }
11150
11487
  warnings.push("Claude managed settings and model allowlists can restrict the generated picker.");
11151
11488
  return { executable, args: ["--settings", file2, "--model", nativeModel(input.model), ...args], env, configPaths, warnings };
11152
11489
  }
@@ -11516,7 +11853,7 @@ async function prepareHarnessLaunch(input) {
11516
11853
  };
11517
11854
  try {
11518
11855
  const nativeAuth = input.protocol === "gemini-generate-content" ? "x-api-key" : input.harness === "claude" ? input.authStyle === "x-api-key" ? "x-api-key" : "bearer" : input.protocol === "anthropic-messages" ? "x-api-key" : "bearer";
11519
- const prepared = await prepareTransportLaunch({ ...input, providerBaseUrl: input.baseUrl, baseUrl: bridge.baseUrl, credential: bridge.token, authStyle: nativeAuth, compiledPolicy, nativePolicy, routeSettingsFile: input.harness === "claude" ? bridge.routeSettingsFile : undefined });
11856
+ const prepared = await prepareTransportLaunch({ ...input, providerBaseUrl: input.baseUrl, baseUrl: bridge.baseUrl, credential: bridge.token, authStyle: nativeAuth, compiledPolicy, nativePolicy, routeSettingsFile: input.harness === "claude" ? bridge.routeSettingsFile : undefined, adoptRoutes: input.harness === "claude" && bridge.adoptRoutes === true });
11520
11857
  return { ...prepared, configPaths: [...prepared.configPaths, catalogPath], warnings: [...prepared.warnings, "Switcher injects model guidance into every managed inference request and permits only models authorized by the launch policy, including catalog selection when enabled. The gateway translates the selected credential to the provider authentication header. The full catalog remains discoverable."], cleanup: async () => {
11521
11858
  try {
11522
11859
  await prepared.cleanup?.();
@@ -11621,7 +11958,7 @@ async function verifyOpenCodeAuthentication(credential, fetchImpl) {
11621
11958
  import { z as z8 } from "zod-v4";
11622
11959
  import { ExecutableTrustError, repairExecutablePermissions, validateExecutable } from "@hasna/contracts/executable-trust";
11623
11960
  import { constants as constants5 } from "fs";
11624
- import { open as open3, readdir as readdir5, unlink, link, lstat as lstat7 } from "fs/promises";
11961
+ import { open as open4, readdir as readdir5, unlink, link, lstat as lstat7 } from "fs/promises";
11625
11962
  import { join as join16, isAbsolute as isAbsolute15 } from "path";
11626
11963
  import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
11627
11964
  import { execFile as execFile3, spawn } from "child_process";
@@ -11690,7 +12027,7 @@ class CredentialBindings {
11690
12027
  return;
11691
12028
  let file;
11692
12029
  try {
11693
- file = await open3(path, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
12030
+ file = await open4(path, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
11694
12031
  } catch (error) {
11695
12032
  if (error.code === "ENOENT")
11696
12033
  return;
@@ -11742,7 +12079,7 @@ class CredentialBindings {
11742
12079
  await privateDirectory(join16(switcherHome(this.env), "config"));
11743
12080
  await privateDirectory(this.directory);
11744
12081
  const temporary = join16(this.directory, `.binding-${randomUUID5()}`);
11745
- const file = await open3(temporary, "wx", 384);
12082
+ const file = await open4(temporary, "wx", 384);
11746
12083
  try {
11747
12084
  await file.writeFile(JSON.stringify(binding, null, 2) + `
11748
12085
  `);
@@ -12865,7 +13202,7 @@ import { fileURLToPath } from "url";
12865
13202
 
12866
13203
  // src/desktop-state.ts
12867
13204
  import { constants as constants7, closeSync as closeSync2, fstatSync, lstatSync, openSync as openSync2, readSync as readSync2 } from "fs";
12868
- import { open as open4, rm as rm3, lstat as lstat8, rename as rename3, chmod as chmod2, copyFile as copyFile2, link as link2 } from "fs/promises";
13205
+ import { open as open5, rm as rm3, lstat as lstat8, rename as rename3, chmod as chmod2, copyFile as copyFile2, link as link2 } from "fs/promises";
12869
13206
  import { spawnSync as spawnSync2 } from "child_process";
12870
13207
  import { resolve as resolve9 } from "path";
12871
13208
  import { createHash as createHash12 } from "crypto";
@@ -12927,7 +13264,7 @@ async function safeDesktopSnapshot(path) {
12927
13264
  const info = await lstat8(path);
12928
13265
  admitDesktopFile(info);
12929
13266
  const metadataHash = admitDesktopMetadata(path, info);
12930
- const file = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
13267
+ const file = await open5(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12931
13268
  try {
12932
13269
  const opened = await file.stat();
12933
13270
  admitOpenedDesktopFile(info, opened);
@@ -13164,7 +13501,7 @@ async function writeDesktopPrivate(path, text, mode = 384, metadataSource, expec
13164
13501
  await preserveDesktopFile(metadataSource?.path ?? path, temporary, template);
13165
13502
  await chmod2(temporary, 384);
13166
13503
  }
13167
- const file = await open4(temporary, constants7.O_RDWR | constants7.O_NOFOLLOW | (template ? 0 : constants7.O_CREAT | constants7.O_EXCL), 384);
13504
+ const file = await open5(temporary, constants7.O_RDWR | constants7.O_NOFOLLOW | (template ? 0 : constants7.O_CREAT | constants7.O_EXCL), 384);
13168
13505
  try {
13169
13506
  await file.truncate(0);
13170
13507
  await file.writeFile(text);
@@ -13225,7 +13562,7 @@ async function openDesktopLease(path, readOnly2 = false) {
13225
13562
  }
13226
13563
 
13227
13564
  // src/native-state.ts
13228
- import { lstat as lstat9, mkdir as mkdir11, open as open5, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
13565
+ import { lstat as lstat9, mkdir as mkdir11, open as open6, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
13229
13566
  import { constants as constants8, lstatSync as lstatSync2, realpathSync } from "fs";
13230
13567
  import { execFileSync as execFileSync3 } from "child_process";
13231
13568
  import { homedir as homedir9, userInfo as userInfo3 } from "os";
@@ -13418,7 +13755,7 @@ async function withNativeStateLock(state, operation) {
13418
13755
  const path = nativeStateLockPath(state);
13419
13756
  let handle;
13420
13757
  try {
13421
- handle = await open5(path, "wx", 384);
13758
+ handle = await open6(path, "wx", 384);
13422
13759
  } catch (error) {
13423
13760
  if (error.code !== "EEXIST")
13424
13761
  throw error;
@@ -13542,7 +13879,7 @@ async function readCodexStateConfig(home) {
13542
13879
  return {};
13543
13880
  if (!entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
13544
13881
  throw new Fault(422, "native_state_config", "The Codex instruction configuration cannot be read safely.");
13545
- const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
13882
+ const handle = await open6(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
13546
13883
  let config;
13547
13884
  try {
13548
13885
  const opened = await handle.stat();
@@ -13576,7 +13913,7 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
13576
13913
  if (!contained && path !== allowedExternalFiles[key] || !entry || !entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || ![0, process.getuid?.()].includes(entry.uid) || (entry.mode & 18) !== 0 || await realpath6(path) !== path)
13577
13914
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
13578
13915
  await assertSafeAncestors(dirname8(path));
13579
- const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW).catch(() => {
13916
+ const handle = await open6(path, constants8.O_RDONLY | constants8.O_NOFOLLOW).catch(() => {
13580
13917
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
13581
13918
  });
13582
13919
  try {
@@ -13786,7 +14123,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13786
14123
  if (entry.kind === "directory")
13787
14124
  await createTrackedDirectory(target, createdDirectories);
13788
14125
  else {
13789
- const file = await open5(target, "wx", 384);
14126
+ const file = await open6(target, "wx", 384);
13790
14127
  await file.close();
13791
14128
  createdFiles.push(target);
13792
14129
  }
@@ -14261,7 +14598,7 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
14261
14598
 
14262
14599
  // src/claude-user-settings.ts
14263
14600
  import { constants as constants9 } from "fs";
14264
- import { lstat as lstat10, open as open6, writeFile as writeFile16 } from "fs/promises";
14601
+ import { lstat as lstat10, open as open7, writeFile as writeFile16 } from "fs/promises";
14265
14602
  import { homedir as homedir10 } from "os";
14266
14603
  import { join as join20, relative as relative6, resolve as resolve11 } from "path";
14267
14604
  var preferences = new Set([
@@ -14328,7 +14665,7 @@ async function readSettings(home, created) {
14328
14665
  return;
14329
14666
  if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || entry.uid !== process.getuid?.() || writableByOthers(entry) || entry.size > 1024 * 1024)
14330
14667
  throw invalid4(path);
14331
- const handle = await open6(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
14668
+ const handle = await open7(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
14332
14669
  try {
14333
14670
  const opened = await handle.stat();
14334
14671
  if (opened.dev !== entry.dev || opened.ino !== entry.ino || opened.nlink !== 1 || opened.size > 1024 * 1024)
@@ -14709,7 +15046,7 @@ import { join as join24 } from "path";
14709
15046
  // src/gateway-service.ts
14710
15047
  import { createHash as createHash16, randomBytes as randomBytes2, randomUUID as randomUUID7 } from "crypto";
14711
15048
  import { constants as constants10 } from "fs";
14712
- import { chmod as chmod3, lstat as lstat11, mkdir as mkdir12, open as open7, readdir as readdir7, rename as rename5, rm as rm5, unlink as unlink3 } from "fs/promises";
15049
+ import { chmod as chmod3, lstat as lstat11, mkdir as mkdir12, open as open8, readdir as readdir7, readFile as readFile8, rename as rename5, rm as rm5, unlink as unlink3 } from "fs/promises";
14713
15050
  import { basename as basename5, dirname as dirname9, isAbsolute as isAbsolute17, join as join22, resolve as resolve13 } from "path";
14714
15051
  import { z as z10 } from "zod-v4";
14715
15052
 
@@ -14928,6 +15265,7 @@ var MAX_HOLDERS = 4096;
14928
15265
  var MAX_PROBE_CANDIDATES = 4096;
14929
15266
  var PROBE_INTERVAL_MS = 60000;
14930
15267
  var ENDED_MS = 30 * 24 * 3600000;
15268
+ var ADOPTION_TEMP_STALE_MS = 60000;
14931
15269
  var MAX_ENDED = 1000;
14932
15270
  var REVIVE_RETRY_MS = 5000;
14933
15271
  var MAX_EVENTS = 1000;
@@ -15118,11 +15456,11 @@ var MAX_LOOKUPS_PER_RETRY = 4;
15118
15456
  var processKey = (entry) => `${entry.pid}@${entry.start}`;
15119
15457
  var SETTLED_MS = 120000;
15120
15458
  var SETTLED_SCAN_FACTOR = 5;
15121
- var staticFields = (record3) => {
15122
- 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;
15123
15461
  return rest;
15124
15462
  };
15125
- 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 } : {} });
15126
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.";
15127
15465
  var loopbackHosts = (port) => new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
15128
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 });
@@ -15137,7 +15475,7 @@ async function liveGateway(socket) {
15137
15475
  }
15138
15476
  }
15139
15477
  async function readPrivateJson(path) {
15140
- const file = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
15478
+ const file = await open8(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
15141
15479
  try {
15142
15480
  const info2 = await file.stat();
15143
15481
  if (!info2.isFile() || info2.size > 128 * 1024 * 1024 || (info2.mode & 63) !== 0 || info2.uid !== process.getuid?.())
@@ -15158,14 +15496,21 @@ async function readRecord(directory, id2) {
15158
15496
  }
15159
15497
  async function writePrivate(path, text) {
15160
15498
  const temporary = `${path}.${randomUUID7()}.tmp`;
15161
- const file = await open7(temporary, "wx", 384);
15499
+ const file = await open8(temporary, "wx", 384);
15162
15500
  try {
15163
- await file.writeFile(text);
15164
- await file.sync();
15165
- } finally {
15166
- await file.close();
15501
+ try {
15502
+ await file.writeFile(text);
15503
+ await file.sync();
15504
+ } finally {
15505
+ await file.close();
15506
+ }
15507
+ await rename5(temporary, path);
15508
+ } catch (error) {
15509
+ await rm5(temporary, { force: true }).catch(() => {
15510
+ return;
15511
+ });
15512
+ throw error;
15167
15513
  }
15168
- await rename5(temporary, path);
15169
15514
  }
15170
15515
  async function routeSettingsDirectory(path) {
15171
15516
  const profile = dirname9(path);
@@ -15178,7 +15523,7 @@ async function routeSettingsDirectory(path) {
15178
15523
  throw new Fault(400, "invalid_route", "A durable route's settings folder must be a private directory owned by this user (mode 0700).");
15179
15524
  return path;
15180
15525
  }
15181
- 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;
15182
15527
  async function launchStateDirectory(path) {
15183
15528
  if (path === undefined)
15184
15529
  return;
@@ -15281,12 +15626,12 @@ async function startGatewayService(options = {}) {
15281
15626
  } else
15282
15627
  launch.eventsDropped = Math.min(1e6, launch.eventsDropped + 1);
15283
15628
  }
15284
- }, options.timing, { credential: () => credentialFor(launch)() });
15285
- const adopt = (record3, credential) => {
15286
- 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() };
15287
15632
  launch.handler = handlerFor(launch);
15288
- launches.set(record3.id, launch);
15289
- byDigest.set(record3.tokenDigest, launch);
15633
+ launches.set(record4.id, launch);
15634
+ byDigest.set(record4.tokenDigest, launch);
15290
15635
  return launch;
15291
15636
  };
15292
15637
  const endedPath = (id2) => join22(paths.ended, `${id2}.json`);
@@ -15297,8 +15642,8 @@ async function startGatewayService(options = {}) {
15297
15642
  return;
15298
15643
  });
15299
15644
  };
15300
- const retireRoute = async (record3) => {
15301
- const file = routeFile(record3);
15645
+ const retireRoute = async (record4) => {
15646
+ const file = routeFile(record4);
15302
15647
  if (!file)
15303
15648
  return;
15304
15649
  const info2 = await lstat11(file).catch(() => {
@@ -15309,6 +15654,65 @@ async function startGatewayService(options = {}) {
15309
15654
  `).catch(() => {
15310
15655
  return;
15311
15656
  });
15657
+ await releaseAdoptedRoutes(record4);
15658
+ };
15659
+ const releaseAdoptedRoutes = async (record4) => {
15660
+ if (!record4.route)
15661
+ return;
15662
+ const dir = record4.route.settingsDir;
15663
+ const tokenOf = (value) => {
15664
+ if (!value || typeof value !== "object" || Array.isArray(value))
15665
+ return;
15666
+ const env2 = value.env;
15667
+ if (!env2 || typeof env2 !== "object" || Array.isArray(env2))
15668
+ return;
15669
+ const keys = env2;
15670
+ const token = [keys.ANTHROPIC_AUTH_TOKEN, keys.ANTHROPIC_API_KEY].find((item2) => typeof item2 === "string" && item2 !== "");
15671
+ return typeof token === "string" ? token : undefined;
15672
+ };
15673
+ for (const name of await readdir7(dir).catch(() => [])) {
15674
+ if (/^claude-settings-[0-9a-f]{32}\.json\.[0-9a-f-]{36}\.tmp$/.test(name)) {
15675
+ const path2 = join22(dir, name);
15676
+ try {
15677
+ const info2 = await lstat11(path2);
15678
+ if (!info2.isFile() || info2.uid !== process.getuid?.() || info2.size > 1024 * 1024)
15679
+ continue;
15680
+ let value;
15681
+ try {
15682
+ value = JSON.parse(await readFile8(path2, "utf8"));
15683
+ } catch {
15684
+ value = undefined;
15685
+ }
15686
+ if (value === undefined) {
15687
+ if (Date.now() - info2.mtimeMs <= ADOPTION_TEMP_STALE_MS)
15688
+ continue;
15689
+ } else {
15690
+ const token = tokenOf(value);
15691
+ if (token === undefined || sha256(token) !== record4.tokenDigest)
15692
+ continue;
15693
+ }
15694
+ await rm5(path2, { force: true });
15695
+ } catch {}
15696
+ continue;
15697
+ }
15698
+ if (!/^claude-settings-[0-9a-f]{32}\.json$/.test(name))
15699
+ continue;
15700
+ const path = join22(dir, name);
15701
+ try {
15702
+ const info2 = await lstat11(path);
15703
+ if (!info2.isFile() || info2.nlink !== 1)
15704
+ continue;
15705
+ const value = await readPrivateJson(path);
15706
+ if (!value || typeof value !== "object" || Array.isArray(value))
15707
+ continue;
15708
+ const { env: _env, ...picker } = value;
15709
+ const token = tokenOf(value);
15710
+ if (token === undefined || sha256(token) !== record4.tokenDigest)
15711
+ continue;
15712
+ await writePrivate(path, JSON.stringify(picker, null, 2) + `
15713
+ `);
15714
+ } catch {}
15715
+ }
15312
15716
  };
15313
15717
  const expireEnded = async (entry) => {
15314
15718
  await forgetEnded(entry);
@@ -15357,10 +15761,12 @@ async function startGatewayService(options = {}) {
15357
15761
  return;
15358
15762
  });
15359
15763
  const route2 = end ? undefined : routeFile(launch.record);
15360
- if (route2)
15764
+ if (route2) {
15361
15765
  await rm5(route2, { force: true }).catch(() => {
15362
15766
  return;
15363
15767
  });
15768
+ await releaseAdoptedRoutes(launch.record);
15769
+ }
15364
15770
  if (removeState && launch.record.stateDir) {
15365
15771
  const directory = await launchStateDirectory(launch.record.stateDir).catch(() => {
15366
15772
  return;
@@ -15469,14 +15875,14 @@ async function startGatewayService(options = {}) {
15469
15875
  if (!holders.length)
15470
15876
  return fail();
15471
15877
  const { endedAt: _endedAt, ...fixed } = entry.record;
15472
- const record3 = { ...fixed, ...durable ? { routeRevived: true } : {}, lastUsedAt: at, lastHolderAt: at, released: true, holders };
15473
- await writePrivate(join22(paths.launches, `${record3.id}.json`), JSON.stringify(staticFields(record3)));
15474
- 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);
15475
15881
  launch.probedAfterLauncher = true;
15476
15882
  track(launch, table, at);
15477
15883
  await persist(launch, true);
15478
15884
  await forgetEnded(entry);
15479
- 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"}`);
15480
15886
  return launch;
15481
15887
  } catch {
15482
15888
  return fail();
@@ -15600,7 +16006,7 @@ async function startGatewayService(options = {}) {
15600
16006
  }
15601
16007
  }
15602
16008
  const token = randomBytes2(32).toString("base64url"), at = now();
15603
- const record3 = {
16009
+ const record4 = {
15604
16010
  schema: 1,
15605
16011
  id: randomUUID7(),
15606
16012
  tokenDigest: sha256(token),
@@ -15615,12 +16021,12 @@ async function startGatewayService(options = {}) {
15615
16021
  ...stateDir ? { stateDir } : {},
15616
16022
  ...route2 ? { route: route2 } : {}
15617
16023
  };
15618
- const launch = adopt(record3, input.credential);
16024
+ const launch = adopt(record4, input.credential);
15619
16025
  launch.baseline = new Set([...table.values()].map(processKey));
15620
- 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)));
15621
16027
  await persist(launch, true);
15622
- log(`launch ${record3.id.slice(0, 8)} registered (${record3.gateway.harness}, ${record3.gateway.model})`);
15623
- return { id: record3.id, token, baseUrl: `${url}/${record3.gateway.protocol === "gemini-generate-content" ? "v1beta" : "v1"}` };
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 } : {} };
15624
16030
  };
15625
16031
  const release = async (launch) => {
15626
16032
  const table = await processTable().catch(() => {
@@ -15651,7 +16057,7 @@ async function startGatewayService(options = {}) {
15651
16057
  if (method === "GET" && url2.pathname === "/v1/status")
15652
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" });
15653
16059
  if (method === "GET" && url2.pathname === "/v1/launches")
15654
- 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 })) });
15655
16061
  if (method === "POST" && url2.pathname === "/v1/launches")
15656
16062
  return Response.json(await register(registrationSchema.parse(await json(request))), { status: 201 });
15657
16063
  if (method === "POST" && url2.pathname === "/v1/stop") {
@@ -15694,13 +16100,13 @@ async function startGatewayService(options = {}) {
15694
16100
  if (!/^[0-9a-f-]{36}\.json$/.test(name))
15695
16101
  continue;
15696
16102
  try {
15697
- const record3 = await readRecord(paths.launches, name.slice(0, -5));
15698
- 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;
15699
16105
  if (extend) {
15700
- record3.lastHolderAt = Math.max(record3.lastHolderAt, restoredAt);
15701
- record3.extendedAt = restoredAt;
16106
+ record4.lastHolderAt = Math.max(record4.lastHolderAt, restoredAt);
16107
+ record4.extendedAt = restoredAt;
15702
16108
  }
15703
- const launch = adopt(record3);
16109
+ const launch = adopt(record4);
15704
16110
  if (extend)
15705
16111
  await persist(launch, true);
15706
16112
  } catch {
@@ -15711,14 +16117,14 @@ async function startGatewayService(options = {}) {
15711
16117
  if (!/^[0-9a-f-]{36}\.json$/.test(name))
15712
16118
  continue;
15713
16119
  try {
15714
- const record3 = endedSchema.parse(await readPrivateJson(join22(paths.ended, name)));
15715
- 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))
15716
16122
  throw new Error("ended launch record id mismatch");
15717
- const entry = { record: record3, failed: new Map, lookups: [] };
15718
- 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))
15719
16125
  await forgetEnded(entry);
15720
16126
  else
15721
- ended.set(record3.tokenDigest, entry);
16127
+ ended.set(record4.tokenDigest, entry);
15722
16128
  } catch {
15723
16129
  log(`ignored unreadable ended launch record ${name.slice(0, 8)}`);
15724
16130
  }
@@ -15759,7 +16165,7 @@ async function startGatewayService(options = {}) {
15759
16165
 
15760
16166
  // src/gateway-supervisor.ts
15761
16167
  import { randomUUID as randomUUID8 } from "crypto";
15762
- import { lstat as lstat12, mkdir as mkdir13, open as open8, readFile as readFile8, realpath as realpath7, rename as rename6, unlink as unlink4 } from "fs/promises";
16168
+ import { lstat as lstat12, mkdir as mkdir13, open as open9, readFile as readFile9, realpath as realpath7, rename as rename6, unlink as unlink4 } from "fs/promises";
15763
16169
  import { dirname as dirname10, isAbsolute as isAbsolute18, join as join23 } from "path";
15764
16170
  var LAUNCHD_LABEL = "com.hasna.switcher.gateway";
15765
16171
  var SYSTEMD_UNIT = "switcher-gateway.service";
@@ -15902,14 +16308,14 @@ var defaultRunner = async (argv) => {
15902
16308
  }
15903
16309
  };
15904
16310
  async function writeUnit(path, content) {
15905
- const previous = await readFile8(path, "utf8").catch(() => {
16311
+ const previous = await readFile9(path, "utf8").catch(() => {
15906
16312
  return;
15907
16313
  });
15908
16314
  if (previous === content)
15909
16315
  return false;
15910
16316
  await mkdir13(dirname10(path), { recursive: true, mode: 493 });
15911
16317
  const temporary = `${path}.${randomUUID8()}.tmp`;
15912
- const file = await open8(temporary, "wx", 420);
16318
+ const file = await open9(temporary, "wx", 420);
15913
16319
  try {
15914
16320
  await file.writeFile(content);
15915
16321
  await file.sync();
@@ -16135,13 +16541,16 @@ function createServiceGatewayHost(client, context) {
16135
16541
  return createInferenceGateway(input);
16136
16542
  }
16137
16543
  const routeSettingsFile = durable && route2 ? join24(route2.settingsDir, `claude-route-${registration.id}.json`) : undefined;
16544
+ const adoptRoutes = routeSettingsFile !== undefined && registration.releasesAdoptedRoutes === true;
16545
+ if (routeSettingsFile && !adoptRoutes)
16546
+ (context.warn ?? console.error)("switcher: The running gateway predates 0.2.23 and cannot take a route back from earlier Claude settings files, so Claude sessions dispatched before 0.2.21 are left as they are. Run `switcher gateway install` to restart it on this version.");
16138
16547
  const lease = { id: registration.id, attached: attachedPid !== undefined, retained: false, done: false };
16139
16548
  leases.push(lease);
16140
16549
  if (attachedPid !== undefined)
16141
16550
  attaching.push(client.attach(lease.id, attachedPid).catch(() => {
16142
16551
  return;
16143
16552
  }));
16144
- return { baseUrl: registration.baseUrl, token: registration.token, ...routeSettingsFile ? { routeSettingsFile } : {}, retainsState: () => lease.retained, cleanup: async () => {
16553
+ return { baseUrl: registration.baseUrl, token: registration.token, ...routeSettingsFile ? { routeSettingsFile } : {}, ...adoptRoutes ? { adoptRoutes } : {}, retainsState: () => lease.retained, cleanup: async () => {
16145
16554
  if (lease.done)
16146
16555
  return;
16147
16556
  lease.done = true;
@@ -16744,7 +17153,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
16744
17153
  // src/native-state-import.ts
16745
17154
  import { createHash as createHash18 } from "crypto";
16746
17155
  import { constants as constants11 } from "fs";
16747
- import { lstat as lstat14, open as open9, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
17156
+ import { lstat as lstat14, open as open10, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
16748
17157
  import { basename as basename6, dirname as dirname11, isAbsolute as isAbsolute19, join as join26, relative as relative8, resolve as resolve15 } from "path";
16749
17158
  var MAX_FILES = 1e5;
16750
17159
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
@@ -16767,7 +17176,7 @@ var inside3 = (parent, child) => {
16767
17176
  var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
16768
17177
  async function sessionId(path, expected) {
16769
17178
  const nameId = basename6(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
16770
- const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
17179
+ const handle = await open10(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
16771
17180
  try {
16772
17181
  const before = await handle.stat();
16773
17182
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
@@ -16855,14 +17264,14 @@ async function checkSessionIdentities(plan) {
16855
17264
  await scan(join26(plan.state.home, "archived_sessions"));
16856
17265
  }
16857
17266
  async function fingerprint2(path, copyTo) {
16858
- const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
17267
+ const handle = await open10(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
16859
17268
  let output, complete = false;
16860
17269
  try {
16861
17270
  const before = await handle.stat();
16862
17271
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
16863
17272
  throw refused();
16864
17273
  if (copyTo)
16865
- output = await open9(copyTo, "wx", 384);
17274
+ output = await open10(copyTo, "wx", 384);
16866
17275
  const hash3 = createHash18("sha256"), buffer = Buffer.alloc(64 * 1024);
16867
17276
  let bytes = 0;
16868
17277
  for (;; ) {