@hasna/switcher 0.2.23 → 0.2.26

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.26";
518
518
 
519
519
  // src/version.ts
520
520
  var VERSION = version;
@@ -1109,7 +1109,7 @@ function assertHarnessArguments(harness, args, options = {}) {
1109
1109
 
1110
1110
  // src/cli.ts
1111
1111
  import { parseArgs } from "util";
1112
- import { join as join27, resolve as resolve16 } from "path";
1112
+ import { join as join29, resolve as resolve16 } from "path";
1113
1113
 
1114
1114
  // src/http.ts
1115
1115
  var MAX_BYTES = 16 * 1024 * 1024;
@@ -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.26",
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) {
@@ -8396,6 +8671,91 @@ function prepareOpenCodeMessages(baseUrl, body, suffix, credential, state = new
8396
8671
  } };
8397
8672
  }
8398
8673
 
8674
+ // src/claude-sessions.ts
8675
+ import { randomUUID as randomUUID2 } from "crypto";
8676
+ import { constants as constants3 } from "fs";
8677
+ import { open as open2, readdir as readdir3, rename, rm } from "fs/promises";
8678
+ import { isAbsolute as isAbsolute8, join as join9 } from "path";
8679
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
8680
+ var isClaudeSessionId = (value) => typeof value === "string" && UUID.test(value);
8681
+ var claudeSessionsDirectory = (sessionDir) => join9(sessionDir, "claude-sessions");
8682
+ function claudeRequestSessionId(headers, body) {
8683
+ const header = headers.get("x-claude-code-session-id");
8684
+ if (isClaudeSessionId(header))
8685
+ return header.toLowerCase();
8686
+ const userId = body?.metadata?.user_id;
8687
+ if (typeof userId !== "string" || userId.length > 4096)
8688
+ return;
8689
+ try {
8690
+ const value = JSON.parse(userId)?.session_id;
8691
+ if (isClaudeSessionId(value))
8692
+ return value.toLowerCase();
8693
+ } catch {}
8694
+ const legacy = /_session_([0-9a-f-]{36})$/i.exec(userId)?.[1];
8695
+ return isClaudeSessionId(legacy) ? legacy.toLowerCase() : undefined;
8696
+ }
8697
+ async function recordClaudeSession(sessionDir, session) {
8698
+ if (!isClaudeSessionId(session.sessionId))
8699
+ throw new Error("A Claude session id is a UUID.");
8700
+ if (!isAbsolute8(sessionDir) || !isAbsolute8(session.cwd))
8701
+ throw new Error("A Claude session record needs absolute paths.");
8702
+ const directory = claudeSessionsDirectory(sessionDir);
8703
+ await privateDirectory(directory);
8704
+ const id2 = session.sessionId.toLowerCase();
8705
+ const record3 = { schema: 1, sessionId: id2, cwd: session.cwd, observedAt: session.observedAt ?? new Date().toISOString() };
8706
+ const path = join9(directory, `${id2}.json`), temporary = `${path}.${randomUUID2()}.tmp`;
8707
+ const file = await open2(temporary, "wx", 384);
8708
+ try {
8709
+ try {
8710
+ await file.writeFile(JSON.stringify(record3) + `
8711
+ `);
8712
+ } finally {
8713
+ await file.close();
8714
+ }
8715
+ await rename(temporary, path);
8716
+ } catch (error) {
8717
+ await rm(temporary, { force: true }).catch(() => {
8718
+ return;
8719
+ });
8720
+ throw error;
8721
+ }
8722
+ return path;
8723
+ }
8724
+ async function readOwnedRecord(path) {
8725
+ const file = await open2(path, constants3.O_RDONLY | constants3.O_NOFOLLOW | constants3.O_NONBLOCK).catch(() => {
8726
+ return;
8727
+ });
8728
+ if (!file)
8729
+ return;
8730
+ try {
8731
+ const info = await file.stat();
8732
+ if (!info.isFile() || info.size > 64 * 1024 || (info.mode & 63) !== 0 || info.uid !== process.getuid?.())
8733
+ return;
8734
+ return JSON.parse(await file.readFile("utf8"));
8735
+ } catch {
8736
+ return;
8737
+ } finally {
8738
+ await file.close();
8739
+ }
8740
+ }
8741
+ async function findClaudeSession(root, sessionId) {
8742
+ if (!isClaudeSessionId(sessionId))
8743
+ return;
8744
+ const id2 = sessionId.toLowerCase(), base = join9(root, "sessions", "claude");
8745
+ let owner;
8746
+ for (const profileId of await readdir3(base).catch(() => [])) {
8747
+ if (!idSchema.safeParse(profileId).success)
8748
+ continue;
8749
+ const sessionDir = join9(base, profileId), path = join9(claudeSessionsDirectory(sessionDir), `${id2}.json`);
8750
+ const value = await readOwnedRecord(path);
8751
+ if (!value || value.schema !== 1 || value.sessionId !== id2 || typeof value.cwd !== "string" || !isAbsolute8(value.cwd) || typeof value.observedAt !== "string" || !Number.isFinite(Date.parse(value.observedAt)))
8752
+ continue;
8753
+ if (!owner || Date.parse(value.observedAt) > Date.parse(owner.observedAt))
8754
+ owner = { sessionId: id2, profileId, cwd: value.cwd, observedAt: value.observedAt, record: path, sessionDir };
8755
+ }
8756
+ return owner;
8757
+ }
8758
+
8399
8759
  // src/inference-gateway.ts
8400
8760
  import { createHash as createHash6, timingSafeEqual as timingSafeEqual3 } from "crypto";
8401
8761
  var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
@@ -8404,30 +8764,34 @@ var MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024;
8404
8764
  var REQUEST_BYTES_PER_CONTEXT_TOKEN = 16;
8405
8765
  var CLOSING_MESSAGE = "Switcher gateway: this launch is shutting down. Start a new session with `switcher launch`.";
8406
8766
  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
8767
  function toolDefinitionCount(body) {
8411
- const record2 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
8768
+ const record3 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
8412
8769
  const count = (value) => {
8413
8770
  if (!value)
8414
8771
  return 0;
8415
8772
  let total = Array.isArray(value.functions) ? value.functions.length : 0;
8416
8773
  for (const tool of Array.isArray(value.tools) ? value.tools : []) {
8417
- const declarations = record2(tool)?.functionDeclarations ?? record2(tool)?.function_declarations;
8774
+ const declarations = record3(tool)?.functionDeclarations ?? record3(tool)?.function_declarations;
8418
8775
  total += Array.isArray(declarations) ? declarations.length : 1;
8419
8776
  }
8420
8777
  return total;
8421
8778
  };
8422
- const top = record2(body);
8423
- return count(top) + count(record2(top?.generateContentRequest));
8779
+ const top = record3(body);
8780
+ return count(top) + count(record3(top?.generateContentRequest));
8424
8781
  }
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.`;
8782
+ var safeProviderId = (providerId) => idSchema.safeParse(providerId).success ? providerId : undefined;
8783
+ var sentText = (sent) => `Switcher sent ${sent.tools} tool definition${sent.tools === 1 ? "" : "s"} in a ${Math.ceil(sent.bytes / 1024)} KB request.`;
8784
+ function providerSaid(detail) {
8785
+ if (!detail.message)
8786
+ return `The provider gave no readable error message${detail.type ? ` (error type ${detail.type})` : ""}.`;
8787
+ return `The provider said${detail.type ? ` (${detail.type})` : ""}: ${detail.message}${/[.!?\u2026]$/.test(detail.message) ? "" : "."}`;
8788
+ }
8789
+ function upstreamRejectionMessage(status, providerId, sent, detail) {
8790
+ const id2 = safeProviderId(providerId), provider = id2 ? `the provider ${id2}` : "the provider";
8791
+ 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." : ""}`;
8792
+ }
8793
+ function rejectionLogLine(status, providerId, sent, detail) {
8794
+ 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
8795
  }
8432
8796
  function requestBodyLimit(models, policy) {
8433
8797
  const allowed = new Set(policy.allowedModels);
@@ -8469,8 +8833,29 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8469
8833
  const bodyLimit = requestBodyLimit(input.models, input.compiledPolicy);
8470
8834
  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
8835
  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 });
8836
+ const upstreamFail = (status, code, message) => Response.json({ ...input.protocol === "anthropic-messages" ? { type: "error" } : {}, error: { type: "switcher_model_policy", code, message } }, { status });
8472
8837
  let closing = false, stopped;
8473
8838
  const active = new Set;
8839
+ const claudeSessions = new Map;
8840
+ const observeClaudeSession = (request, body) => {
8841
+ if (input.harness !== "claude" || !input.sessionDir)
8842
+ return;
8843
+ const sessionId = claudeRequestSessionId(request.headers, body);
8844
+ if (!sessionId)
8845
+ return;
8846
+ let pending = claudeSessions.get(sessionId);
8847
+ if (!pending && claudeSessions.size < 1e4) {
8848
+ pending = recordClaudeSession(input.sessionDir, { sessionId, cwd: input.cwd }).then(() => {
8849
+ return;
8850
+ }, () => {
8851
+ try {
8852
+ options.log?.("claude session record could not be written");
8853
+ } catch {}
8854
+ });
8855
+ claudeSessions.set(sessionId, pending);
8856
+ }
8857
+ return pending;
8858
+ };
8474
8859
  const handle = async (request, server) => {
8475
8860
  if (closing)
8476
8861
  return fail(503, "closing");
@@ -8493,6 +8878,7 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8493
8878
  const body = parsed.value;
8494
8879
  if (!body || typeof body !== "object" || Array.isArray(body))
8495
8880
  return fail(400, "invalid_request");
8881
+ await observeClaudeSession(request, body);
8496
8882
  let credential;
8497
8883
  try {
8498
8884
  credential = options.credential ? await options.credential() : input.credential;
@@ -8540,6 +8926,15 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8540
8926
  }
8541
8927
  event.resolvedModel = resolved;
8542
8928
  event.decision = resolved === requested ? "allow" : "alias";
8929
+ let forwarded = body;
8930
+ if (input.protocol === "anthropic-messages" && deepSeekMessagesRoute(input.baseUrl)) {
8931
+ const rewritten = rewriteDeepSeekMessages(body);
8932
+ forwarded = rewritten.body;
8933
+ if (rewritten.change)
8934
+ try {
8935
+ options.log?.(deepSeekRewriteLogLine(safeProviderId(input.providerId) ?? "unknown", rewritten.change));
8936
+ } catch {}
8937
+ }
8543
8938
  let current = event, response;
8544
8939
  const emitted = new Set;
8545
8940
  const flush = () => {
@@ -8550,15 +8945,15 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8550
8945
  };
8551
8946
  const abort = new AbortController;
8552
8947
  let complete;
8553
- const record2 = { abort, done: new Promise((r) => complete = r) };
8948
+ const record3 = { abort, done: new Promise((r) => complete = r) };
8554
8949
  const activity = createProviderRequest(request.signal, abort.signal, timing);
8555
8950
  const release = () => {
8556
8951
  activity.finish();
8557
8952
  flush();
8558
- active.delete(record2);
8953
+ active.delete(record3);
8559
8954
  complete();
8560
8955
  };
8561
- active.add(record2);
8956
+ active.add(record3);
8562
8957
  const signal = activity.fetchOptions.signal;
8563
8958
  server.timeout(request, 0);
8564
8959
  const headers = { "content-type": "application/json" };
@@ -8587,7 +8982,7 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8587
8982
  flush();
8588
8983
  current = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), resolvedModel: model, decision: "fallback", reason: "explicit_transient_fallback", ...effort.success ? { reasoningEffort: effort.data } : {} };
8589
8984
  }
8590
- const payload = structuredClone(body);
8985
+ const payload = structuredClone(forwarded);
8591
8986
  if (gemini) {
8592
8987
  if (payload.model !== undefined)
8593
8988
  payload.model = `models/${model}`;
@@ -8631,18 +9026,22 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8631
9026
  if (!response)
8632
9027
  throw new Error("provider_request_failed");
8633
9028
  if (!response.ok) {
8634
- const overflow = await isContextOverflow(response);
9029
+ const detail = await readUpstreamError(response, [credential]);
9030
+ const overflow = detail.overflow;
8635
9031
  const paymentRequired = response.status === 402;
8636
9032
  if (overflow)
8637
9033
  current.reason = "context_length_exceeded";
8638
9034
  else if (paymentRequired)
8639
9035
  current.reason = "provider_payment_required";
8640
9036
  release();
9037
+ try {
9038
+ options.log?.(rejectionLogLine(response.status, input.providerId, sent, detail));
9039
+ } catch {}
8641
9040
  if (overflow)
8642
9041
  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
9042
  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);
9043
+ 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)}`);
9044
+ const rejected = upstreamFail(response.status >= 300 && response.status < 400 ? 502 : response.status, `upstream_http_${response.status}`, upstreamRejectionMessage(response.status, input.providerId, sent, detail));
8646
9045
  const retryAfter = response.headers.get("retry-after");
8647
9046
  if ((response.status === 429 || response.status === 503) && retryAfter && retryAfter.length <= 128 && (/^\d+$/.test(retryAfter) || Number.isFinite(Date.parse(retryAfter))))
8648
9047
  rejected.headers.set("retry-after", retryAfter);
@@ -8689,7 +9088,7 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8689
9088
  const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort, closing: () => closing, release, activity, inspect, interrupted: (reason) => {
8690
9089
  current.reason = reason;
8691
9090
  } });
8692
- record2.cancel = cancel;
9091
+ record3.cancel = cancel;
8693
9092
  return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
8694
9093
  } catch (error) {
8695
9094
  if (error instanceof Fault)
@@ -8722,11 +9121,11 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8722
9121
  })()
8723
9122
  };
8724
9123
  }
8725
- function createInferenceGateway(input, timing = {}) {
9124
+ function createInferenceGateway(input, timing = {}, options = {}) {
8726
9125
  const token = crypto.randomUUID() + crypto.randomUUID();
8727
9126
  const digest = (value) => createHash6("sha256").update(value).digest();
8728
9127
  const expected = digest(token);
8729
- const handler = createInferenceHandler(input, timing);
9128
+ const handler = createInferenceHandler(input, timing, options);
8730
9129
  let stopped;
8731
9130
  const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: handler.bodyLimit, idleTimeout: 255, async fetch(request, server2) {
8732
9131
  if (handler.closing())
@@ -8744,7 +9143,7 @@ function createInferenceGateway(input, timing = {}) {
8744
9143
 
8745
9144
  // src/codex-model-policy.ts
8746
9145
  import { mkdir as mkdir5, readFile as readFile4, realpath as realpath3, stat as stat4, writeFile as writeFile7 } from "fs/promises";
8747
- import { dirname as dirname4, isAbsolute as isAbsolute8, join as join9, resolve as resolve5 } from "path";
9146
+ import { dirname as dirname4, isAbsolute as isAbsolute9, join as join10, resolve as resolve5 } from "path";
8748
9147
  import { execFileSync as execFileSync2 } from "child_process";
8749
9148
  import { createHash as createHash7 } from "crypto";
8750
9149
  var dict = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
@@ -8764,7 +9163,7 @@ function codexAgentsFromEffectiveConfig(config, trustedProject = true, baseDir)
8764
9163
  const rawConfigFile = value.config_file;
8765
9164
  if (rawConfigFile !== undefined && typeof rawConfigFile !== "string")
8766
9165
  throw new Error(`Codex agents.${name}.config_file must be a string.`);
8767
- const configFile = rawConfigFile === undefined ? undefined : isAbsolute8(rawConfigFile) ? rawConfigFile : baseDir ? resolve5(baseDir, rawConfigFile) : undefined;
9166
+ const configFile = rawConfigFile === undefined ? undefined : isAbsolute9(rawConfigFile) ? rawConfigFile : baseDir ? resolve5(baseDir, rawConfigFile) : undefined;
8768
9167
  if (rawConfigFile !== undefined && !configFile)
8769
9168
  throw new Error(`Codex agents.${name}.config_file must be absolute after precedence resolution.`);
8770
9169
  const definition = { trusted: trustedProject, config_file: configFile };
@@ -8893,16 +9292,16 @@ async function writeCodexAgentOverrides(result, stateDir) {
8893
9292
  const paths = {};
8894
9293
  for (const agent of result.agents) {
8895
9294
  const digest = createHash7("sha256").update(agent.name).digest("hex").slice(0, 16);
8896
- const path = join9(root, `agent-${digest}.toml`);
9295
+ const path = join10(root, `agent-${digest}.toml`);
8897
9296
  await writeFile7(path, renderCodexAgentToml(agent.config), { encoding: "utf8", mode: 384, flag: "wx" });
8898
9297
  paths[agent.name] = path;
8899
9298
  }
8900
9299
  return paths;
8901
9300
  }
8902
9301
  async function prepareCodexModelPolicy(input) {
8903
- const home = resolve5(input.home ?? process.env.CODEX_HOME ?? join9(process.env.HOME ?? "/", ".codex"));
9302
+ const home = resolve5(input.home ?? process.env.CODEX_HOME ?? join10(process.env.HOME ?? "/", ".codex"));
8904
9303
  const cwd = resolve5(input.cwd);
8905
- const globalPath = join9(home, "config.toml");
9304
+ const globalPath = join10(home, "config.toml");
8906
9305
  const readConfig = async (path) => {
8907
9306
  let info;
8908
9307
  try {
@@ -8926,7 +9325,7 @@ async function prepareCodexModelPolicy(input) {
8926
9325
  const global = await readConfig(globalPath) ?? {};
8927
9326
  const projects = dict(global.projects) ? global.projects : {};
8928
9327
  const markers = global.project_root_markers ?? [".git"];
8929
- if (!Array.isArray(markers) || markers.some((m) => typeof m !== "string" || isAbsolute8(m) || m.includes("..")))
9328
+ if (!Array.isArray(markers) || markers.some((m) => typeof m !== "string" || isAbsolute9(m) || m.includes("..")))
8930
9329
  throw new Error("Unsupported Codex project root markers.");
8931
9330
  const ancestorDirs = [];
8932
9331
  for (let dir = cwd;; dir = dirname4(dir)) {
@@ -8939,9 +9338,9 @@ async function prepareCodexModelPolicy(input) {
8939
9338
  for (const dir of ancestorDirs)
8940
9339
  for (const marker of markers) {
8941
9340
  try {
8942
- const info = await stat4(join9(dir, marker));
9341
+ const info = await stat4(join10(dir, marker));
8943
9342
  if (marker === ".git" && info.isDirectory())
8944
- await stat4(join9(dir, marker, "HEAD"));
9343
+ await stat4(join10(dir, marker, "HEAD"));
8945
9344
  projectRoot = dir;
8946
9345
  break findRoot;
8947
9346
  } catch {}
@@ -8966,7 +9365,7 @@ async function prepareCodexModelPolicy(input) {
8966
9365
  const layers = [{ path: globalPath, config: global }];
8967
9366
  const projectDirs = ancestorDirs.slice(0, ancestorDirs.indexOf(projectRoot) + 1).reverse();
8968
9367
  for (const dir of projectDirs) {
8969
- const path = join9(dir, ".codex", "config.toml");
9368
+ const path = join10(dir, ".codex", "config.toml");
8970
9369
  if (path === globalPath)
8971
9370
  continue;
8972
9371
  const decision = await trust(dir) ?? projectTrust ?? repoTrust;
@@ -8995,7 +9394,7 @@ async function prepareCodexModelPolicy(input) {
8995
9394
  return { ...result, agentConfigPaths: await writeCodexAgentOverrides(result, input.stateDir), configPaths: loaded };
8996
9395
  }
8997
9396
  async function readCodexAgentConfig(path) {
8998
- if (!isAbsolute8(path))
9397
+ if (!isAbsolute9(path))
8999
9398
  throw new Error("Codex agent config_file must be absolute before launch.");
9000
9399
  const canonical = await realpath3(path);
9001
9400
  const info = await stat4(canonical);
@@ -9010,18 +9409,18 @@ async function readCodexAgentConfig(path) {
9010
9409
  }
9011
9410
 
9012
9411
  // src/harnesses.ts
9013
- 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
- import { basename as basename2, dirname as dirname7, join as join15, isAbsolute as isAbsolute13, resolve as resolve8 } from "path";
9412
+ import { access as access3, lstat as lstat6, mkdir as mkdir10, open as open4, readFile as readFile6, readdir as readdir5, rename as rename3, writeFile as writeFile13, rm as rm3 } from "fs/promises";
9413
+ import { basename as basename2, dirname as dirname7, join as join16, isAbsolute as isAbsolute14, resolve as resolve8 } from "path";
9015
9414
  import { homedir as homedir8, tmpdir } from "os";
9016
- import { createHash as createHash9, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual5 } from "crypto";
9415
+ import { createHash as createHash9, randomUUID as randomUUID5, timingSafeEqual as timingSafeEqual5 } from "crypto";
9017
9416
  import { execFile as execFile2 } from "child_process";
9018
9417
  import { promisify as promisify2 } from "util";
9019
9418
  import { createConnection } from "net";
9020
9419
 
9021
9420
  // src/aider-config.ts
9022
- import { readFile as readFile5, writeFile as writeFile8, lstat as lstat5, copyFile, rename, realpath as realpath4, access as access2 } from "fs/promises";
9023
- import { constants as constants3 } from "fs";
9024
- import { dirname as dirname5, basename, join as join10, resolve as resolve6, isAbsolute as isAbsolute9 } from "path";
9421
+ import { readFile as readFile5, writeFile as writeFile8, lstat as lstat5, copyFile, rename as rename2, realpath as realpath4, access as access2 } from "fs/promises";
9422
+ import { constants as constants4 } from "fs";
9423
+ import { dirname as dirname5, basename, join as join11, resolve as resolve6, isAbsolute as isAbsolute10 } from "path";
9025
9424
  import { homedir as homedir6 } from "os";
9026
9425
  import { parseDocument as parseDocument2 } from "yaml";
9027
9426
  var KEY2 = "SWITCHER_HARNESS_API_KEY";
@@ -9063,9 +9462,9 @@ async function gitRoot(path) {
9063
9462
  parent = dirname5(parent);
9064
9463
  }
9065
9464
  }
9066
- for (let dir = join10(parent, ...missing);; dir = dirname5(dir)) {
9465
+ for (let dir = join11(parent, ...missing);; dir = dirname5(dir)) {
9067
9466
  try {
9068
- await lstat5(join10(dir, ".git"));
9467
+ await lstat5(join11(dir, ".git"));
9069
9468
  return dir;
9070
9469
  } catch (error) {
9071
9470
  if (!["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
@@ -9078,9 +9477,9 @@ async function gitRoot(path) {
9078
9477
  var falseValue = (v) => v === undefined || v === null || v === false || v === 0 || typeof v === "string" && ["", "false", "no", "off", "0"].includes(v.toLowerCase());
9079
9478
  var startup = `yes-always gui browser upgrade install-main-branch just-check-update apply-clipboard-edits test lint commit`.split(" ");
9080
9479
  var safeParameters = new Set(`max_tokens temperature top_p top_k min_p stop seed reasoning_effort thinking`.split(" "));
9081
- var expandHome = (path, home) => path === "~" ? home : path.startsWith("~/") ? join10(home, path.slice(2)) : path;
9480
+ var expandHome = (path, home) => path === "~" ? home : path.startsWith("~/") ? join11(home, path.slice(2)) : path;
9082
9481
  async function validateAiderConfiguration(cwd, args = [], home = process.env.HOME ?? homedir6()) {
9083
- if (!isAbsolute9(home))
9482
+ if (!isAbsolute10(home))
9084
9483
  throw new Error("Aider requires an absolute HOME to preserve native instruction paths.");
9085
9484
  const parsed = aiderArguments(args), cwdRoot = await gitRoot(cwd);
9086
9485
  const roots = new Set([resolve6(home), ...cwdRoot ? [cwdRoot] : [], resolve6(cwd)]);
@@ -9091,7 +9490,7 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
9091
9490
  }
9092
9491
  let effective = {};
9093
9492
  for (const root of roots) {
9094
- const path = join10(root, ".aider.conf.yml"), value = await data(path);
9493
+ const path = join11(root, ".aider.conf.yml"), value = await data(path);
9095
9494
  if (value !== undefined) {
9096
9495
  if (!object3(value))
9097
9496
  throw new Error(`Aider configuration must be a mapping: ${path}`);
@@ -9116,13 +9515,13 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
9116
9515
  }
9117
9516
  effective = { ...effective, ...normalized };
9118
9517
  }
9119
- const settings2 = await data(join10(root, ".aider.model.settings.yml"));
9518
+ const settings2 = await data(join11(root, ".aider.model.settings.yml"));
9120
9519
  if (settings2 !== undefined) {
9121
9520
  if (!Array.isArray(settings2))
9122
9521
  throw new Error("Aider model settings must be a list.");
9123
9522
  for (const entry of settings2)
9124
9523
  if (!object3(entry) || entry.extra_params !== undefined && (!object3(entry.extra_params) || Object.keys(entry.extra_params).some((key) => !safeParameters.has(key))))
9125
- throw new Error(`Aider custom transport or callback model settings cannot be preserved safely: ${join10(root, ".aider.model.settings.yml")}`);
9524
+ throw new Error(`Aider custom transport or callback model settings cannot be preserved safely: ${join11(root, ".aider.model.settings.yml")}`);
9126
9525
  }
9127
9526
  }
9128
9527
  if (effective.read !== undefined && !(typeof effective.read === "string" || Array.isArray(effective.read) && effective.read.every((v) => typeof v === "string")))
@@ -9130,7 +9529,7 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
9130
9529
  const reads = parsed.reads.length ? parsed.reads : typeof effective.read === "string" ? [effective.read] : effective.read ?? [];
9131
9530
  for (const path of reads) {
9132
9531
  try {
9133
- await access2(resolve6(cwd, expandHome(path, home)), constants3.R_OK);
9532
+ await access2(resolve6(cwd, expandHome(path, home)), constants4.R_OK);
9134
9533
  } catch {
9135
9534
  throw new Error(`Aider read-only instruction file is not readable: ${path}`);
9136
9535
  }
@@ -9166,26 +9565,26 @@ async function prepareAider(input) {
9166
9565
  } else if (parsed.args[i].startsWith("--read="))
9167
9566
  parsed.args[i] = "--read=" + expandHome(parsed.args[i].slice(7), sourceHome);
9168
9567
  }
9169
- const home = join10(input.stateDir, "aider-home");
9568
+ const home = join11(input.stateDir, "aider-home");
9170
9569
  await privateDirectory(home);
9171
9570
  const originalHome = process.env.HOME ?? homedir6();
9172
- const gitSources = process.env.GIT_CONFIG_GLOBAL ? [resolve6(process.env.GIT_CONFIG_GLOBAL)] : [join10(process.env.XDG_CONFIG_HOME ?? join10(originalHome, ".config"), "git", "config"), join10(originalHome, ".gitconfig")];
9173
- const gitConfig = join10(home, ".gitconfig");
9571
+ const gitSources = process.env.GIT_CONFIG_GLOBAL ? [resolve6(process.env.GIT_CONFIG_GLOBAL)] : [join11(process.env.XDG_CONFIG_HOME ?? join11(originalHome, ".config"), "git", "config"), join11(originalHome, ".gitconfig")];
9572
+ const gitConfig = join11(home, ".gitconfig");
9174
9573
  await writeFile8(gitConfig, gitSources.map((path) => `[include]
9175
9574
  path = ${JSON.stringify(path)}
9176
9575
  `).join(""), { mode: 384, flag: "wx" });
9177
- const sessions = input.sessionDir ?? join10(input.stateDir, "sessions");
9576
+ const sessions = input.sessionDir ?? join11(input.stateDir, "sessions");
9178
9577
  await privateDirectory(sessions);
9179
- const id2 = crypto.randomUUID(), history = join10(sessions, `${id2}.chat.md`), inputHistory = join10(sessions, `${id2}.input`);
9578
+ const id2 = crypto.randomUUID(), history = join11(sessions, `${id2}.chat.md`), inputHistory = join11(sessions, `${id2}.input`);
9180
9579
  if (parsed.restore) {
9181
- const latest = join10(sessions, "latest.json");
9580
+ const latest = join11(sessions, "latest.json");
9182
9581
  await historyFile(latest).catch(() => {
9183
9582
  throw new Error("No valid completed Aider history is available for this profile.");
9184
9583
  });
9185
9584
  const previous = JSON.parse(await readFile5(latest, "utf8"));
9186
9585
  if (!object3(previous) || typeof previous.id !== "string" || !/^[-a-f0-9]{36}$/.test(previous.id))
9187
9586
  throw new Error("Invalid Aider history reference.");
9188
- const source = join10(sessions, `${previous.id}.chat.md`);
9587
+ const source = join11(sessions, `${previous.id}.chat.md`);
9189
9588
  await historyFile(source);
9190
9589
  await copyFile(source, history, 1);
9191
9590
  } else
@@ -9195,7 +9594,7 @@ async function prepareAider(input) {
9195
9594
  const model2 = aiderModelName(input.protocol, input.model);
9196
9595
  const weakModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.weak ?? input.model), editorModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.editor ?? input.model);
9197
9596
  const extra = { api_base: input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl, api_key: `os.environ/${KEY2}` };
9198
- const settings2 = join10(input.stateDir, "aider-model-settings.json"), metadata = join10(input.stateDir, "aider-model-metadata.json"), config = join10(input.stateDir, "aider-config.json"), empty = join10(input.stateDir, "aider-empty.env");
9597
+ const settings2 = join11(input.stateDir, "aider-model-settings.json"), metadata = join11(input.stateDir, "aider-model-metadata.json"), config = join11(input.stateDir, "aider-config.json"), empty = join11(input.stateDir, "aider-empty.env");
9199
9598
  const definitions = input.models.map((m) => ({ name: aiderModelName(input.protocol, m.id), edit_format: "whole", use_repo_map: true, weak_model_name: weakModel, editor_model_name: editorModel, extra_params: extra }));
9200
9599
  await writeFile8(settings2, JSON.stringify([...definitions, { name: "aider/extra_params", extra_params: extra }]), { mode: 384, flag: "wx" });
9201
9600
  await writeFile8(metadata, JSON.stringify(Object.fromEntries(input.models.map((m) => [aiderModelName(input.protocol, m.id), {
@@ -9214,7 +9613,7 @@ async function prepareAider(input) {
9214
9613
  return {
9215
9614
  executable: input.executable ?? "aider",
9216
9615
  args: ["--config", config, "--model", model2, "--weak-model", weakModel, "--editor-model", editorModel, "--set-env", "PYTHON_DOTENV_DISABLED=1", "--api-key", "SWITCHER_UNUSED=unused", ...aliases, ...parsed.args],
9217
- env: { HOME: home, XDG_CONFIG_HOME: join10(home, "config"), XDG_CACHE_HOME: join10(home, "cache"), XDG_DATA_HOME: join10(home, "data"), PYTHON_DOTENV_DISABLED: "1", LITELLM_LOCAL_MODEL_COST_MAP: "True", [KEY2]: input.credential, [input.protocol === "anthropic-messages" ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY"]: input.credential },
9616
+ env: { HOME: home, XDG_CONFIG_HOME: join11(home, "config"), XDG_CACHE_HOME: join11(home, "cache"), XDG_DATA_HOME: join11(home, "data"), PYTHON_DOTENV_DISABLED: "1", LITELLM_LOCAL_MODEL_COST_MAP: "True", [KEY2]: input.credential, [input.protocol === "anthropic-messages" ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY"]: input.credential },
9218
9617
  configPaths: [config, settings2, metadata, empty, gitConfig],
9219
9618
  warnings: [
9220
9619
  ...input.protocol === "openai-responses" ? ["Aider 0.86.2 with LiteLLM 1.81.10 uses buffered Responses requests even when native streaming is requested; incremental upstream Responses output is unavailable through this adapter."] : [],
@@ -9230,9 +9629,9 @@ async function prepareAider(input) {
9230
9629
  await historyFile(history);
9231
9630
  if (!/^#### /m.test((await readFile5(history, "utf8")).slice(originalHistoryLength)))
9232
9631
  return;
9233
- const pending = join10(sessions, `${id2}.latest.json`);
9632
+ const pending = join11(sessions, `${id2}.latest.json`);
9234
9633
  await writeFile8(pending, JSON.stringify({ id: id2 }), { mode: 384, flag: "wx" });
9235
- await rename(pending, join10(sessions, "latest.json"));
9634
+ await rename2(pending, join11(sessions, "latest.json"));
9236
9635
  }
9237
9636
  };
9238
9637
  }
@@ -9315,8 +9714,8 @@ function validateGrokResume(args) {
9315
9714
 
9316
9715
  // src/cline-backend.ts
9317
9716
  import { mkdir as mkdir6, writeFile as writeFile9 } from "fs/promises";
9318
- import { randomUUID as randomUUID2 } from "crypto";
9319
- import { isAbsolute as isAbsolute10, join as join11 } from "path";
9717
+ import { randomUUID as randomUUID3 } from "crypto";
9718
+ import { isAbsolute as isAbsolute11, join as join12 } from "path";
9320
9719
  var ENV_BY_PROTOCOL = {
9321
9720
  "anthropic-messages": "ANTHROPIC_API_KEY",
9322
9721
  "openai-responses": "OPENAI_API_KEY",
@@ -9362,18 +9761,18 @@ async function prepareClineLaunch(input) {
9362
9761
  throw new Error(`Cline ${input.protocol} uses ${mapping.authStyle} authentication; use a provider with the native Cline auth contract.`);
9363
9762
  if (input.credential && /[\r\n]/.test(input.credential))
9364
9763
  throw new Error("Provider credential contains invalid header characters.");
9365
- if (!isAbsolute10(input.stateDir) || !isAbsolute10(input.cwd))
9764
+ if (!isAbsolute11(input.stateDir) || !isAbsolute11(input.cwd))
9366
9765
  throw new Error("Launch state and working directories must be absolute.");
9367
- const dataDir = join11(input.stateDir, "cline-data");
9368
- const sessionDir = input.sessionDir ?? join11(dataDir, "sessions");
9369
- const launchDir = join11(input.stateDir, `cline-launch-${randomUUID2()}`);
9370
- const settingsDir = join11(launchDir, "settings");
9371
- const configDir = join11(launchDir, "config");
9766
+ const dataDir = join12(input.stateDir, "cline-data");
9767
+ const sessionDir = input.sessionDir ?? join12(dataDir, "sessions");
9768
+ const launchDir = join12(input.stateDir, `cline-launch-${randomUUID3()}`);
9769
+ const settingsDir = join12(launchDir, "settings");
9770
+ const configDir = join12(launchDir, "config");
9372
9771
  await mkdir6(settingsDir, { recursive: true, mode: 448 });
9373
9772
  await mkdir6(configDir, { recursive: true, mode: 448 });
9374
9773
  const baseUrl = endpoint(input.baseUrl);
9375
9774
  const providerId = mapping.providerId;
9376
- const providersPath = await writeJson(join11(settingsDir, "providers.json"), {
9775
+ const providersPath = await writeJson(join12(settingsDir, "providers.json"), {
9377
9776
  version: 1,
9378
9777
  lastUsedProvider: providerId,
9379
9778
  modes: {},
@@ -9393,7 +9792,7 @@ async function prepareClineLaunch(input) {
9393
9792
  }
9394
9793
  }
9395
9794
  });
9396
- const modelsPath = await writeJson(join11(settingsDir, "models.json"), {
9795
+ const modelsPath = await writeJson(join12(settingsDir, "models.json"), {
9397
9796
  version: 1,
9398
9797
  providers: {
9399
9798
  [providerId]: {
@@ -9442,11 +9841,11 @@ async function prepareClineLaunch(input) {
9442
9841
  }
9443
9842
 
9444
9843
  // src/opencode2-config.ts
9445
- import { mkdir as mkdir7, open as open2, realpath as realpath5, readdir as readdir3, stat as stat5, writeFile as writeFile10 } from "fs/promises";
9446
- import { constants as constants4 } from "fs";
9447
- import { dirname as dirname6, isAbsolute as isAbsolute11, join as join12, relative as relative4, resolve as resolve7 } from "path";
9844
+ import { mkdir as mkdir7, open as open3, realpath as realpath5, readdir as readdir4, stat as stat5, writeFile as writeFile10 } from "fs/promises";
9845
+ import { constants as constants5 } from "fs";
9846
+ import { dirname as dirname6, isAbsolute as isAbsolute12, join as join13, relative as relative4, resolve as resolve7 } from "path";
9448
9847
  import { homedir as homedir7 } from "os";
9449
- import { randomUUID as randomUUID3 } from "crypto";
9848
+ import { randomUUID as randomUUID4 } from "crypto";
9450
9849
  import { Database as Database2 } from "bun:sqlite";
9451
9850
  import { parse as parse3, parseTree as parseTree3 } from "jsonc-parser";
9452
9851
  import { parseDocument as parseDocument3 } from "yaml";
@@ -9460,13 +9859,13 @@ var maxTotalBytes2 = 8 * 1024 * 1024;
9460
9859
  var maxFiles2 = 256;
9461
9860
  var inside2 = (root, path) => {
9462
9861
  const rel = relative4(root, path);
9463
- return rel === "" || !isAbsolute11(rel) && rel !== ".." && !rel.startsWith("../");
9862
+ return rel === "" || !isAbsolute12(rel) && rel !== ".." && !rel.startsWith("../");
9464
9863
  };
9465
9864
  var action = (value) => ({ bash: "shell", task: "subagent", write: "edit", patch: "edit" })[value] ?? value;
9466
9865
  function invalid2(path, field) {
9467
9866
  throw new Error(`OpenCode 2 cannot preserve ${field} in ${path}; use a supported explicit permission or agent declaration.`);
9468
9867
  }
9469
- function record2(value, path, field) {
9868
+ function record3(value, path, field) {
9470
9869
  if (!object4(value))
9471
9870
  invalid2(path, field);
9472
9871
  return value;
@@ -9484,15 +9883,15 @@ function literal2(value, path, field) {
9484
9883
  function permissions(value, path, home) {
9485
9884
  const result = [];
9486
9885
  if (own2(value, "tools"))
9487
- for (const [name, enabled] of Object.entries(record2(value.tools, path, "tools permission"))) {
9886
+ for (const [name, enabled] of Object.entries(record3(value.tools, path, "tools permission"))) {
9488
9887
  if (typeof enabled !== "boolean")
9489
9888
  invalid2(path, "tools permission");
9490
9889
  result.push({ action: action(name), resource: "*", effect: enabled ? "allow" : "deny" });
9491
9890
  }
9492
9891
  if (own2(value, "permission")) {
9493
- const legacy = typeof value.permission === "string" ? { "*": value.permission } : record2(value.permission, path, "permission");
9892
+ const legacy = typeof value.permission === "string" ? { "*": value.permission } : record3(value.permission, path, "permission");
9494
9893
  for (const [name, permission2] of Object.entries(legacy)) {
9495
- const entries = typeof permission2 === "string" ? { "*": permission2 } : record2(permission2, path, "permission");
9894
+ const entries = typeof permission2 === "string" ? { "*": permission2 } : record3(permission2, path, "permission");
9496
9895
  for (const [resource, item] of Object.entries(entries)) {
9497
9896
  const parsed = effect.safeParse(item);
9498
9897
  if (!parsed.success)
@@ -9512,7 +9911,7 @@ function permissions(value, path, home) {
9512
9911
  literal2(item.resource, path, "permission resource");
9513
9912
  if (!["read", "edit", "external_directory"].includes(item.action))
9514
9913
  return item;
9515
- const resource = item.resource === "~" || item.resource === "$HOME" ? home : item.resource.startsWith("~/") ? join12(home, item.resource.slice(2)) : item.resource.startsWith("$HOME/") || item.resource.startsWith("$HOME\\") ? join12(home, item.resource.slice(6)) : item.resource;
9914
+ const resource = item.resource === "~" || item.resource === "$HOME" ? home : item.resource.startsWith("~/") ? join13(home, item.resource.slice(2)) : item.resource.startsWith("$HOME/") || item.resource.startsWith("$HOME\\") ? join13(home, item.resource.slice(6)) : item.resource;
9516
9915
  return { ...item, resource };
9517
9916
  });
9518
9917
  }
@@ -9537,11 +9936,11 @@ function jsonc2(text, path) {
9537
9936
  if (errors.length)
9538
9937
  invalid2(path, "JSON/JSONC configuration");
9539
9938
  rejectDuplicateKeys2(parseTree3(text), path);
9540
- return record2(value, path, "configuration object");
9939
+ return record3(value, path, "configuration object");
9541
9940
  }
9542
9941
  async function checkRemoteConfiguration(dataHome) {
9543
- const path = join12(dataHome, "opencode", "opencode.db");
9544
- const legacyAuth = await stat5(join12(dataHome, "opencode", "auth.json")).then(() => true, (error) => {
9942
+ const path = join13(dataHome, "opencode", "opencode.db");
9943
+ const legacyAuth = await stat5(join13(dataHome, "opencode", "auth.json")).then(() => true, (error) => {
9545
9944
  if (error.code === "ENOENT")
9546
9945
  return false;
9547
9946
  throw error;
@@ -9581,23 +9980,23 @@ async function checkRemoteConfiguration(dataHome) {
9581
9980
  }
9582
9981
  async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9583
9982
  for (const name of ["HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "OPENCODE_CONFIG_DIR"])
9584
- if (env[name] && !isAbsolute11(env[name]))
9983
+ if (env[name] && !isAbsolute12(env[name]))
9585
9984
  throw new Error(`OpenCode 2 requires an absolute ${name} to preserve native configuration authority.`);
9586
9985
  const home = resolve7(env.HOME || homedir7());
9587
- const configRoot = resolve7(env.OPENCODE_CONFIG_DIR || join12(env.XDG_CONFIG_HOME || join12(home, ".config"), "opencode"));
9986
+ const configRoot = resolve7(env.OPENCODE_CONFIG_DIR || join13(env.XDG_CONFIG_HOME || join13(home, ".config"), "opencode"));
9588
9987
  const canonicalConfigRoot = await realpath5(configRoot).catch((error) => {
9589
9988
  if (error.code === "ENOENT")
9590
9989
  return configRoot;
9591
9990
  throw error;
9592
9991
  });
9593
- const dataHome = resolve7(env.XDG_DATA_HOME || join12(home, ".local", "share"));
9992
+ const dataHome = resolve7(env.XDG_DATA_HOME || join13(home, ".local", "share"));
9594
9993
  await checkRemoteConfiguration(dataHome);
9595
9994
  let files = 0, total = 0;
9596
9995
  const paths = [];
9597
9996
  async function read(path, optional = true) {
9598
9997
  let handle;
9599
9998
  try {
9600
- handle = await open2(path, constants4.O_RDONLY | constants4.O_NONBLOCK);
9999
+ handle = await open3(path, constants5.O_RDONLY | constants5.O_NONBLOCK);
9601
10000
  } catch (error) {
9602
10001
  if (optional && error.code === "ENOENT")
9603
10002
  return;
@@ -9630,7 +10029,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9630
10029
  invalid2(path, "agent prompt environment reference");
9631
10030
  let result = "", cursor = 0;
9632
10031
  for (const match of text.matchAll(/\{file:([^}]+)\}/g)) {
9633
- const requested = match[1].startsWith("~/") ? join12(home, match[1].slice(2)) : resolve7(dirname6(path), match[1]);
10032
+ const requested = match[1].startsWith("~/") ? join13(home, match[1].slice(2)) : resolve7(dirname6(path), match[1]);
9634
10033
  const content = (await read(requested, false)).trim();
9635
10034
  literal2(content, requested, "nested prompt variable reference");
9636
10035
  result += text.slice(cursor, match.index) + content;
@@ -9652,7 +10051,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9652
10051
  }
9653
10052
  async function agentsDirectory(directory2) {
9654
10053
  for (const source of ["agent", "agents", "mode", "modes"]) {
9655
- const base = join12(directory2, source), entries = [];
10054
+ const base = join13(directory2, source), entries = [];
9656
10055
  const visited = new Set;
9657
10056
  let examined = 0;
9658
10057
  async function walk(dir, depth) {
@@ -9662,7 +10061,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9662
10061
  if (visited.has(actual))
9663
10062
  return;
9664
10063
  visited.add(actual);
9665
- names = await readdir3(dir);
10064
+ names = await readdir4(dir);
9666
10065
  } catch (error) {
9667
10066
  if (error.code === "ENOENT")
9668
10067
  return;
@@ -9671,7 +10070,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9671
10070
  if (depth > 16 || (examined += names.length) > maxFiles2)
9672
10071
  throw new Error("OpenCode 2 agent policy exceeds its bounded directory limit.");
9673
10072
  for (const name of names) {
9674
- const path = join12(dir, name);
10073
+ const path = join13(dir, name);
9675
10074
  const info = await stat5(path);
9676
10075
  if (info.isDirectory()) {
9677
10076
  if (source === "agent" || source === "agents")
@@ -9690,7 +10089,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9690
10089
  if (parsed.errors.length)
9691
10090
  invalid2(path, "agent YAML frontmatter");
9692
10091
  try {
9693
- data2 = record2(parsed.toJS({ maxAliasCount: 0 }), path, "agent YAML frontmatter");
10092
+ data2 = record3(parsed.toJS({ maxAliasCount: 0 }), path, "agent YAML frontmatter");
9694
10093
  } catch {
9695
10094
  invalid2(path, "agent YAML frontmatter");
9696
10095
  }
@@ -9705,8 +10104,8 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9705
10104
  }
9706
10105
  }
9707
10106
  async function directory(path) {
9708
- await document(join12(path, "opencode.json"));
9709
- await document(join12(path, "opencode.jsonc"));
10107
+ await document(join13(path, "opencode.json"));
10108
+ await document(join13(path, "opencode.jsonc"));
9710
10109
  await agentsDirectory(path);
9711
10110
  }
9712
10111
  await directory(configRoot);
@@ -9721,11 +10120,11 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9721
10120
  const projectEnabled = !["1", "true"].includes((env.OPENCODE_CONFIG_PROJECT_DISABLE ?? env.OPENCODE_DISABLE_PROJECT_CONFIG ?? "").toLowerCase());
9722
10121
  if (projectEnabled) {
9723
10122
  for (const path of [...ancestors].reverse()) {
9724
- await document(join12(path, "opencode.json"));
9725
- await document(join12(path, "opencode.jsonc"));
10123
+ await document(join13(path, "opencode.json"));
10124
+ await document(join13(path, "opencode.jsonc"));
9726
10125
  }
9727
10126
  for (const path of [...ancestors].reverse()) {
9728
- const candidate = join12(path, ".opencode");
10127
+ const candidate = join13(path, ".opencode");
9729
10128
  const canonical = await realpath5(candidate).catch((error) => {
9730
10129
  if (error.code === "ENOENT")
9731
10130
  return candidate;
@@ -9736,7 +10135,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9736
10135
  }
9737
10136
  }
9738
10137
  if (env.OPENCODE_CONFIG_CONTENT)
9739
- documents.push({ path: join12(cwd, "OPENCODE_CONFIG_CONTENT"), value: jsonc2(env.OPENCODE_CONFIG_CONTENT, "OPENCODE_CONFIG_CONTENT") });
10138
+ documents.push({ path: join13(cwd, "OPENCODE_CONFIG_CONTENT"), value: jsonc2(env.OPENCODE_CONFIG_CONTENT, "OPENCODE_CONFIG_CONTENT") });
9740
10139
  const policy = [];
9741
10140
  const agents = Object.create(null);
9742
10141
  let defaultAgent;
@@ -9765,9 +10164,9 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9765
10164
  policies.push(...parsed.data);
9766
10165
  }
9767
10166
  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") : {};
10167
+ const legacy = own2(value, "agent") ? record3(value.agent, path, "agent") : {};
10168
+ const modes = own2(value, "mode") ? record3(value.mode, path, "mode") : {};
10169
+ const native = own2(value, "agents") ? record3(value.agents, path, "agents") : {};
9771
10170
  const selected = new Map(Object.entries(legacy).map(([name, item]) => [name, { item, legacy: true, primary: false }]));
9772
10171
  for (const [name, item] of Object.entries(modes))
9773
10172
  selected.set(name, { item, legacy: true, primary: true });
@@ -9775,7 +10174,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9775
10174
  selected.set(name, { item, legacy: false, primary: false });
9776
10175
  for (const [name, entry] of selected) {
9777
10176
  literal2(name, path, "agent name");
9778
- const item = record2(entry.item, path, "agent");
10177
+ const item = record3(entry.item, path, "agent");
9779
10178
  const target = agents[name] ??= {};
9780
10179
  const system = entry.legacy ? item.prompt : item.system;
9781
10180
  if (system !== undefined)
@@ -9829,26 +10228,26 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9829
10228
  instructions.push(`Instructions from: ${path}
9830
10229
  ${content}`);
9831
10230
  }
9832
- await instruction(join12(configRoot, "AGENTS.md"));
10231
+ await instruction(join13(configRoot, "AGENTS.md"));
9833
10232
  if (projectEnabled) {
9834
10233
  let stop = resolve7(cwd);
9835
10234
  if (inside2(home, resolve7(cwd)))
9836
10235
  stop = home;
9837
10236
  else
9838
10237
  for (const path of ancestors) {
9839
- if (await stat5(join12(path, ".git")).then(() => true, () => false)) {
10238
+ if (await stat5(join13(path, ".git")).then(() => true, () => false)) {
9840
10239
  stop = path;
9841
10240
  break;
9842
10241
  }
9843
10242
  }
9844
10243
  for (const path of ancestors) {
9845
- await instruction(join12(path, "AGENTS.md"));
10244
+ await instruction(join13(path, "AGENTS.md"));
9846
10245
  if (path === stop)
9847
10246
  break;
9848
10247
  }
9849
10248
  }
9850
- const privateHome = join12(stateDir, "opencode-home"), privateConfig = join12(stateDir, "opencode-config");
9851
- const instructionFile = join12(privateConfig, "opencode", "AGENTS.md");
10249
+ const privateHome = join13(stateDir, "opencode-home"), privateConfig = join13(stateDir, "opencode-config");
10250
+ const instructionFile = join13(privateConfig, "opencode", "AGENTS.md");
9852
10251
  await mkdir7(dirname6(instructionFile), { recursive: true, mode: 448 });
9853
10252
  await mkdir7(privateHome, { recursive: true, mode: 448 });
9854
10253
  await writeFile10(instructionFile, instructions.join(`
@@ -9856,13 +10255,13 @@ ${content}`);
9856
10255
  `), { flag: "wx", mode: 384 });
9857
10256
  return {
9858
10257
  config: { permissions: policy, agents, ...defaultAgent ? { default_agent: defaultAgent } : {}, experimental: { policies: [{ action: "provider.use", resource: "*", effect: "deny" }, { action: "provider.use", resource: providerID, effect: "allow" }] } },
9859
- env: { HOME: privateHome, XDG_CONFIG_HOME: privateConfig, OPENCODE_CONFIG_DIR: join12(privateConfig, "opencode"), XDG_CACHE_HOME: join12(stateDir, "opencode-cache"), XDG_STATE_HOME: join12(stateDir, "opencode-state"), XDG_DATA_HOME: dataHome, OPENCODE_DISABLE_PROJECT_CONFIG: "true", OPENCODE_CONFIG_PROJECT_DISABLE: "true", OPENCODE_DISABLE_MODELS_FETCH: "true" },
10258
+ env: { HOME: privateHome, XDG_CONFIG_HOME: privateConfig, OPENCODE_CONFIG_DIR: join13(privateConfig, "opencode"), XDG_CACHE_HOME: join13(stateDir, "opencode-cache"), XDG_STATE_HOME: join13(stateDir, "opencode-state"), XDG_DATA_HOME: dataHome, OPENCODE_DISABLE_PROJECT_CONFIG: "true", OPENCODE_CONFIG_PROJECT_DISABLE: "true", OPENCODE_DISABLE_MODELS_FETCH: "true" },
9860
10259
  instructionFile,
9861
10260
  sourcePaths: paths
9862
10261
  };
9863
10262
  }
9864
10263
  function openCode2ConfigText(config, providerID, keyEnv) {
9865
- const marker = randomUUID3();
10264
+ const marker = randomUUID4();
9866
10265
  const providers = config.providers;
9867
10266
  const selected = providers[providerID];
9868
10267
  const value = { ...config, providers: { ...providers, [providerID]: { ...selected, settings: { ...selected.settings, apiKey: marker } } } };
@@ -9871,8 +10270,8 @@ function openCode2ConfigText(config, providerID, keyEnv) {
9871
10270
  }
9872
10271
 
9873
10272
  // src/omp-backend.ts
9874
- import { mkdir as mkdir8, rm, writeFile as writeFile11 } from "fs/promises";
9875
- import { join as join13 } from "path";
10273
+ import { mkdir as mkdir8, rm as rm2, writeFile as writeFile11 } from "fs/promises";
10274
+ import { join as join14 } from "path";
9876
10275
  var KEY3 = "SWITCHER_HARNESS_API_KEY";
9877
10276
  var API = {
9878
10277
  "anthropic-messages": "anthropic-messages",
@@ -9897,8 +10296,8 @@ async function prepareOmpLaunch(input) {
9897
10296
  const baseUrl = endpoint(input.baseUrl);
9898
10297
  if (input.credential && /[\r\n]/.test(input.credential))
9899
10298
  throw new Error("Provider credential contains invalid header characters.");
9900
- const agentDir = join13(input.stateDir, "omp-agent");
9901
- const sessionDir = input.sessionDir ?? join13(input.stateDir, "sessions");
10299
+ const agentDir = join14(input.stateDir, "omp-agent");
10300
+ const sessionDir = input.sessionDir ?? join14(input.stateDir, "sessions");
9902
10301
  await mkdir8(agentDir, { recursive: true, mode: 448 });
9903
10302
  await mkdir8(sessionDir, { recursive: true, mode: 448 });
9904
10303
  const api = API[input.protocol];
@@ -9924,8 +10323,8 @@ async function prepareOmpLaunch(input) {
9924
10323
  provider.apiKey = KEY3;
9925
10324
  provider.authHeader = true;
9926
10325
  }
9927
- const modelsPath = join13(agentDir, "models.yml");
9928
- const configPath = join13(agentDir, "config.yml");
10326
+ const modelsPath = join14(agentDir, "models.yml");
10327
+ const configPath = join14(agentDir, "config.yml");
9929
10328
  const selector = `switcher/${input.model}`;
9930
10329
  await writeFile11(modelsPath, JSON.stringify({ providers: { switcher: provider } }, null, 2) + `
9931
10330
  `, { mode: 384, flag: "wx" });
@@ -9950,7 +10349,7 @@ async function prepareOmpLaunch(input) {
9950
10349
  configPaths: [modelsPath, configPath],
9951
10350
  warnings,
9952
10351
  cleanup: async () => {
9953
- await rm(agentDir, { recursive: true, force: true });
10352
+ await rm2(agentDir, { recursive: true, force: true });
9954
10353
  }
9955
10354
  };
9956
10355
  }
@@ -10003,7 +10402,7 @@ function compileHermesModelPolicy(currentModel, roles2, baseUrl, apiMode = "chat
10003
10402
  // src/hermes-backend.ts
10004
10403
  import { createHash as createHash8, timingSafeEqual as timingSafeEqual4 } from "crypto";
10005
10404
  import { mkdir as mkdir9, symlink as symlink3, writeFile as writeFile12 } from "fs/promises";
10006
- import { isAbsolute as isAbsolute12, join as join14 } from "path";
10405
+ import { isAbsolute as isAbsolute13, join as join15 } from "path";
10007
10406
  var hermesApiMode = {
10008
10407
  "anthropic-messages": "anthropic_messages",
10009
10408
  "openai-responses": "codex_responses",
@@ -10067,7 +10466,7 @@ function createHermesBridge(input, timing = {}) {
10067
10466
  return Response.json({ error: { message: "Model is outside the Switcher launch catalog" } }, { status: 403 });
10068
10467
  const abortController = new AbortController;
10069
10468
  let complete;
10070
- const record3 = {
10469
+ const record4 = {
10071
10470
  abort: abortController,
10072
10471
  done: new Promise((resolve8) => {
10073
10472
  complete = resolve8;
@@ -10076,11 +10475,11 @@ function createHermesBridge(input, timing = {}) {
10076
10475
  const activity = createProviderRequest(request.signal, abortController.signal, timing);
10077
10476
  const release = () => {
10078
10477
  activity.finish();
10079
- active.delete(record3);
10478
+ active.delete(record4);
10080
10479
  complete();
10081
10480
  };
10082
- active.add(record3);
10083
- record3.cancel = async () => {
10481
+ active.add(record4);
10482
+ record4.cancel = async () => {
10084
10483
  abortController.abort();
10085
10484
  release();
10086
10485
  };
@@ -10116,7 +10515,7 @@ function createHermesBridge(input, timing = {}) {
10116
10515
  return new Response(null, { status: upstream.status });
10117
10516
  }
10118
10517
  const { stream, cancel } = proxyProviderStream({ response: upstream, protocol: input.protocol, requestSignal: request.signal, abort: abortController, closing: () => closing, release, activity });
10119
- record3.cancel = cancel;
10518
+ record4.cancel = cancel;
10120
10519
  return new Response(stream, {
10121
10520
  status: upstream.status,
10122
10521
  headers: {
@@ -10136,18 +10535,18 @@ function createHermesBridge(input, timing = {}) {
10136
10535
  cleanup: () => stopped ??= (async () => {
10137
10536
  closing = true;
10138
10537
  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;
10538
+ for (const record4 of pending)
10539
+ record4.abort.abort();
10540
+ await Promise.allSettled(pending.map(async (record4) => {
10541
+ await record4.cancel?.();
10542
+ await record4.done;
10144
10543
  }));
10145
10544
  await server.stop(true);
10146
10545
  })()
10147
10546
  };
10148
10547
  }
10149
10548
  async function prepareHermesLaunch(input) {
10150
- if (!isAbsolute12(input.stateDir) || !isAbsolute12(input.cwd))
10549
+ if (!isAbsolute13(input.stateDir) || !isAbsolute13(input.cwd))
10151
10550
  throw new Error("Launch state and working directories must be absolute.");
10152
10551
  if (input.protocol !== "anthropic-messages" && input.protocol !== "openai-responses" && input.protocol !== "openai-chat")
10153
10552
  throw new Error("Hermes does not support this provider protocol.");
@@ -10157,12 +10556,12 @@ async function prepareHermesLaunch(input) {
10157
10556
  throw new Error("Hermes cannot safely select model IDs that differ only by letter case; update the provider catalog.");
10158
10557
  if (input.credential && /[\r\n]/.test(input.credential))
10159
10558
  throw new Error("Provider credential contains invalid header characters.");
10160
- const sessionDir = input.sessionDir ?? join14(input.stateDir, "hermes-session");
10161
- const sessionsDir = join14(sessionDir, "sessions");
10559
+ const sessionDir = input.sessionDir ?? join15(input.stateDir, "hermes-session");
10560
+ const sessionsDir = join15(sessionDir, "sessions");
10162
10561
  await mkdir9(input.stateDir, { recursive: true, mode: 448 });
10163
10562
  await mkdir9(sessionsDir, { recursive: true, mode: 448 });
10164
- await symlink3(join14(sessionDir, "state.db"), join14(input.stateDir, "state.db"));
10165
- await symlink3(sessionsDir, join14(input.stateDir, "sessions"));
10563
+ await symlink3(join15(sessionDir, "state.db"), join15(input.stateDir, "state.db"));
10564
+ await symlink3(sessionsDir, join15(input.stateDir, "sessions"));
10166
10565
  const bridge = createHermesBridge(input);
10167
10566
  let policy;
10168
10567
  try {
@@ -10190,7 +10589,7 @@ async function prepareHermesLaunch(input) {
10190
10589
  }
10191
10590
  }
10192
10591
  };
10193
- const configPath = join14(input.stateDir, "config.yaml");
10592
+ const configPath = join15(input.stateDir, "config.yaml");
10194
10593
  try {
10195
10594
  await writeFile12(configPath, JSON.stringify(config, null, 2) + `
10196
10595
  `, { mode: 384, flag: "wx" });
@@ -10207,7 +10606,7 @@ async function prepareHermesLaunch(input) {
10207
10606
  SWITCHER_HERMES_AUX_API_KEY: bridge.token,
10208
10607
  OPENAI_API_KEY: bridge.token,
10209
10608
  OPENAI_BASE_URL: bridge.baseUrl,
10210
- CODEX_HOME: join14(input.stateDir, "codex-home")
10609
+ CODEX_HOME: join15(input.stateDir, "codex-home")
10211
10610
  },
10212
10611
  configPaths: [configPath],
10213
10612
  warnings: [
@@ -10423,19 +10822,19 @@ function validateHarnessVersion(harness, version2) {
10423
10822
  throw new Error("Gemini CLI 0.58.0 is required by the verified native settings and argument contract.");
10424
10823
  }
10425
10824
  async function jsonFile(dir, name, value) {
10426
- const path = join15(dir, name);
10825
+ const path = join16(dir, name);
10427
10826
  await writeFile13(path, JSON.stringify(value, null, 2) + `
10428
10827
  `, { mode: 384, flag: "wx" });
10429
10828
  return path;
10430
10829
  }
10431
10830
  function claudeSettingsDirectory(sessionDir) {
10432
- return join15(sessionDir, "settings");
10831
+ return join16(sessionDir, "settings");
10433
10832
  }
10434
10833
  async function durableJsonFile(dir, prefix, value) {
10435
10834
  const text = JSON.stringify(value, null, 2) + `
10436
10835
  `;
10437
10836
  await privateDirectory(dir);
10438
- const path = join15(dir, `${prefix}-${createHash9("sha256").update(text).digest("hex").slice(0, 32)}.json`);
10837
+ const path = join16(dir, `${prefix}-${createHash9("sha256").update(text).digest("hex").slice(0, 32)}.json`);
10439
10838
  const existing = await lstat6(path).catch(() => {
10440
10839
  return;
10441
10840
  });
@@ -10443,12 +10842,12 @@ async function durableJsonFile(dir, prefix, value) {
10443
10842
  return;
10444
10843
  }) === text)
10445
10844
  return path;
10446
- const temporary = `${path}.${randomUUID4()}.tmp`;
10845
+ const temporary = `${path}.${randomUUID5()}.tmp`;
10447
10846
  await writeFile13(temporary, text, { mode: 384, flag: "wx" });
10448
10847
  try {
10449
- await rename2(temporary, path);
10848
+ await rename3(temporary, path);
10450
10849
  } catch (error) {
10451
- await rm2(temporary, { force: true }).catch(() => {
10850
+ await rm3(temporary, { force: true }).catch(() => {
10452
10851
  return;
10453
10852
  });
10454
10853
  throw error;
@@ -10463,17 +10862,17 @@ async function routeJsonFile(path, value) {
10463
10862
  `, { mode: 384, flag: "wx" });
10464
10863
  const info = await lstat6(path);
10465
10864
  if (!info.isFile() || (info.mode & 63) !== 0 || info.uid !== process.getuid?.()) {
10466
- await rm2(path, { force: true });
10865
+ await rm3(path, { force: true });
10467
10866
  throw new Error("The Claude route settings file could not be created owner-only.");
10468
10867
  }
10469
10868
  return path;
10470
10869
  }
10471
10870
  async function adoptClaudeSettingsRoutes(dir, route2) {
10472
10871
  let adopted = 0;
10473
- for (const name of await readdir4(dir).catch(() => [])) {
10872
+ for (const name of await readdir5(dir).catch(() => [])) {
10474
10873
  if (!/^claude-settings-[0-9a-f]{32}\.json$/.test(name))
10475
10874
  continue;
10476
- const path = join15(dir, name);
10875
+ const path = join16(dir, name);
10477
10876
  const info = await lstat6(path).catch(() => {
10478
10877
  return;
10479
10878
  });
@@ -10487,9 +10886,9 @@ async function adoptClaudeSettingsRoutes(dir, route2) {
10487
10886
  }
10488
10887
  if (!value || typeof value !== "object" || Array.isArray(value) || !("modelPicker" in value))
10489
10888
  continue;
10490
- const temporary = `${path}.${randomUUID4()}.tmp`;
10889
+ const temporary = `${path}.${randomUUID5()}.tmp`;
10491
10890
  try {
10492
- const handle = await open3(temporary, "wx", 384);
10891
+ const handle = await open4(temporary, "wx", 384);
10493
10892
  try {
10494
10893
  await handle.writeFile(JSON.stringify({ ...value, ...route2 }, null, 2) + `
10495
10894
  `);
@@ -10497,10 +10896,10 @@ async function adoptClaudeSettingsRoutes(dir, route2) {
10497
10896
  } finally {
10498
10897
  await handle.close();
10499
10898
  }
10500
- await rename2(temporary, path);
10899
+ await rename3(temporary, path);
10501
10900
  adopted++;
10502
10901
  } catch {
10503
- await rm2(temporary, { force: true }).catch(() => {
10902
+ await rm3(temporary, { force: true }).catch(() => {
10504
10903
  return;
10505
10904
  });
10506
10905
  }
@@ -10511,7 +10910,7 @@ async function projectInstructionPaths(cwd) {
10511
10910
  let dir = resolve8(cwd);
10512
10911
  while (true) {
10513
10912
  for (const name of ["AGENTS.md", "CLAUDE.md", "CONTEXT.md"]) {
10514
- const path = join15(dir, name);
10913
+ const path = join16(dir, name);
10515
10914
  if (await access3(path).then(() => true, () => false))
10516
10915
  return [path];
10517
10916
  }
@@ -10585,10 +10984,10 @@ function toolsPermission(value, path) {
10585
10984
  function expandHomePattern(value) {
10586
10985
  if (typeof value !== "object" || value === null || Array.isArray(value))
10587
10986
  return value;
10588
- const record3 = value;
10987
+ const record4 = value;
10589
10988
  const output = {};
10590
- for (const [key, item] of Object.entries(record3)) {
10591
- const expanded = key === "~" ? homedir8() : key.startsWith("~/") ? join15(homedir8(), key.slice(2)) : key;
10989
+ for (const [key, item] of Object.entries(record4)) {
10990
+ const expanded = key === "~" ? homedir8() : key.startsWith("~/") ? join16(homedir8(), key.slice(2)) : key;
10592
10991
  output[expanded] = expandHomePattern(item);
10593
10992
  }
10594
10993
  return output;
@@ -10596,9 +10995,9 @@ function expandHomePattern(value) {
10596
10995
  function policyWithExpandedPatterns(value) {
10597
10996
  if (typeof value !== "object" || value === null || Array.isArray(value))
10598
10997
  return value;
10599
- const record3 = value;
10998
+ const record4 = value;
10600
10999
  const output = {};
10601
- for (const [key, item] of Object.entries(record3))
11000
+ for (const [key, item] of Object.entries(record4))
10602
11001
  output[key] = typeof item === "object" && item !== null && !Array.isArray(item) ? expandHomePattern(item) : item;
10603
11002
  return output;
10604
11003
  }
@@ -10657,14 +11056,14 @@ async function agentPolicyFiles(dir, kind) {
10657
11056
  const visit = async (current, root) => {
10658
11057
  let entries;
10659
11058
  try {
10660
- entries = await readdir4(current, { withFileTypes: true });
11059
+ entries = await readdir5(current, { withFileTypes: true });
10661
11060
  } catch (error) {
10662
11061
  if (error.code === "ENOENT")
10663
11062
  return;
10664
11063
  throw error;
10665
11064
  }
10666
11065
  for (const entry of entries) {
10667
- const file = join15(current, entry.name);
11066
+ const file = join16(current, entry.name);
10668
11067
  if (entry.isDirectory())
10669
11068
  await visit(file, root);
10670
11069
  else if (entry.isFile() && entry.name.endsWith(".md"))
@@ -10672,7 +11071,7 @@ async function agentPolicyFiles(dir, kind) {
10672
11071
  }
10673
11072
  };
10674
11073
  for (const rootName of [kind, `${kind}s`])
10675
- await visit(join15(dir, rootName), join15(dir, rootName));
11074
+ await visit(join16(dir, rootName), join16(dir, rootName));
10676
11075
  return result.sort((a, b) => a.file.localeCompare(b.file));
10677
11076
  }
10678
11077
  async function readAgentPolicyFile(file, kind, root) {
@@ -10728,9 +11127,9 @@ async function preservedOpenCodePolicy(cwd) {
10728
11127
  result.mode = { ...result.mode ?? {}, [policy.name]: { permission: merged } };
10729
11128
  }
10730
11129
  };
10731
- const originalConfig = join15(process.env.XDG_CONFIG_HOME ?? join15(homedir8(), ".config"), "opencode");
11130
+ const originalConfig = join16(process.env.XDG_CONFIG_HOME ?? join16(homedir8(), ".config"), "opencode");
10732
11131
  for (const name of ["config.json", "opencode.json", "opencode.jsonc"])
10733
- await apply(join15(originalConfig, name));
11132
+ await apply(join16(originalConfig, name));
10734
11133
  await applyMarkdown(originalConfig, "agent");
10735
11134
  await applyMarkdown(originalConfig, "mode");
10736
11135
  if (process.env.OPENCODE_CONFIG)
@@ -10746,22 +11145,22 @@ async function preservedOpenCodePolicy(cwd) {
10746
11145
  }
10747
11146
  for (const current of [...dirs].reverse())
10748
11147
  for (const name of ["opencode.jsonc", "opencode.json"])
10749
- await apply(join15(current, name));
11148
+ await apply(join16(current, name));
10750
11149
  for (const current of dirs) {
10751
- const configDir = join15(current, ".opencode");
11150
+ const configDir = join16(current, ".opencode");
10752
11151
  for (const name of ["opencode.json", "opencode.jsonc"])
10753
- await apply(join15(configDir, name));
11152
+ await apply(join16(configDir, name));
10754
11153
  await applyMarkdown(configDir, "agent");
10755
11154
  await applyMarkdown(configDir, "mode");
10756
11155
  }
10757
- const homeConfig = join15(homedir8(), ".opencode");
11156
+ const homeConfig = join16(homedir8(), ".opencode");
10758
11157
  for (const name of ["opencode.json", "opencode.jsonc"])
10759
- await apply(join15(homeConfig, name));
11158
+ await apply(join16(homeConfig, name));
10760
11159
  await applyMarkdown(homeConfig, "agent");
10761
11160
  await applyMarkdown(homeConfig, "mode");
10762
11161
  if (process.env.OPENCODE_CONFIG_DIR) {
10763
11162
  for (const name of ["opencode.json", "opencode.jsonc"])
10764
- await apply(join15(process.env.OPENCODE_CONFIG_DIR, name));
11163
+ await apply(join16(process.env.OPENCODE_CONFIG_DIR, name));
10765
11164
  await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "agent");
10766
11165
  await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "mode");
10767
11166
  }
@@ -10863,16 +11262,16 @@ function grokBridge(input, timing = {}) {
10863
11262
  if (closing)
10864
11263
  return Response.json({ error: { message: "Bridge is closing" } }, { status: 503 });
10865
11264
  let complete;
10866
- const record3 = { abort: new AbortController, done: new Promise((resolve9) => {
11265
+ const record4 = { abort: new AbortController, done: new Promise((resolve9) => {
10867
11266
  complete = resolve9;
10868
11267
  }) };
10869
- const activity = createProviderRequest(request.signal, record3.abort.signal, timing);
11268
+ const activity = createProviderRequest(request.signal, record4.abort.signal, timing);
10870
11269
  const release = () => {
10871
11270
  activity.finish();
10872
- active.delete(record3);
11271
+ active.delete(record4);
10873
11272
  complete();
10874
11273
  };
10875
- active.add(record3);
11274
+ active.add(record4);
10876
11275
  server2.timeout(request, 0);
10877
11276
  try {
10878
11277
  const response = await activity.run(() => fetch(`${input.baseUrl}${apiPath}`, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
@@ -10887,8 +11286,8 @@ function grokBridge(input, timing = {}) {
10887
11286
  release();
10888
11287
  return new Response(null, { status: response.status });
10889
11288
  }
10890
- const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record3.abort, closing: () => closing, release, activity });
10891
- record3.cancel = cancel;
11289
+ const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record4.abort, closing: () => closing, release, activity });
11290
+ record4.cancel = cancel;
10892
11291
  return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
10893
11292
  } catch {
10894
11293
  release();
@@ -10898,11 +11297,11 @@ function grokBridge(input, timing = {}) {
10898
11297
  return { baseUrl: new URL("v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
10899
11298
  closing = true;
10900
11299
  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;
11300
+ for (const record4 of pending)
11301
+ record4.abort.abort();
11302
+ await Promise.allSettled(pending.map(async (record4) => {
11303
+ await record4.cancel?.();
11304
+ await record4.done;
10906
11305
  }));
10907
11306
  await server.stop(true);
10908
11307
  })() };
@@ -10931,21 +11330,21 @@ var PRIME_UNIX_SOCKET_LIMIT = 100;
10931
11330
  var PRIME_DAEMON_STARTUP_TIMEOUT_MS = 30000;
10932
11331
  var PRIME_DAEMON_SHUTDOWN_TIMEOUT_MS = 5000;
10933
11332
  function primeSocketPaths(runtimeDir) {
10934
- const basename3 = `p-${randomUUID4().replaceAll("-", "").slice(0, 8)}.sock`;
10935
- const daemonSocket = join15(runtimeDir, basename3);
11333
+ const basename3 = `p-${randomUUID5().replaceAll("-", "").slice(0, 8)}.sock`;
11334
+ const daemonSocket = join16(runtimeDir, basename3);
10936
11335
  const uid = typeof process.getuid === "function" ? String(process.getuid()) : "user";
10937
- const workerDir = join15(runtimeDir, `prime-agent-${uid}`);
11336
+ const workerDir = join16(runtimeDir, `prime-agent-${uid}`);
10938
11337
  const workerKey = createHash9("sha256").update(daemonSocket).digest("hex").slice(0, 12);
10939
- const workerSocket = join15(workerDir, `worker-${workerKey}-${"x".repeat(12)}.sock`);
11338
+ const workerSocket = join16(workerDir, `worker-${workerKey}-${"x".repeat(12)}.sock`);
10940
11339
  const overlong = [daemonSocket, workerSocket].find((path) => Buffer.byteLength(path, "utf8") > PRIME_UNIX_SOCKET_LIMIT);
10941
- return { daemonSocket, runtimeDir, workerDir, workerPrefix: join15(workerDir, `worker-${workerKey}-`), overlong };
11340
+ return { daemonSocket, runtimeDir, workerDir, workerPrefix: join16(workerDir, `worker-${workerKey}-`), overlong };
10942
11341
  }
10943
11342
  async function primeSocketInfo() {
10944
11343
  const requested = tmpdir();
10945
11344
  const direct = primeSocketPaths(requested);
10946
11345
  if (!direct.overlong)
10947
11346
  return direct;
10948
- const fallback = join15(switcherHome(), "r");
11347
+ const fallback = join16(switcherHome(), "r");
10949
11348
  await privateDirectory(switcherHome());
10950
11349
  await privateDirectory(fallback);
10951
11350
  const scoped = primeSocketPaths(fallback);
@@ -11043,11 +11442,11 @@ async function primeStartSupervisor(input, executable, socketPath, env, onSpawn)
11043
11442
  }
11044
11443
  async function primeOwnedShutdown(socketPath, workerPrefix) {
11045
11444
  const exists = () => access3(socketPath).then(() => true, () => false);
11046
- const workerEntries = () => readdir4(workerPrefix.slice(0, workerPrefix.lastIndexOf("/"))).then((entries) => entries.filter((entry) => entry.startsWith(workerPrefix.slice(workerPrefix.lastIndexOf("/") + 1))), () => []);
11445
+ const workerEntries = () => readdir5(workerPrefix.slice(0, workerPrefix.lastIndexOf("/"))).then((entries) => entries.filter((entry) => entry.startsWith(workerPrefix.slice(workerPrefix.lastIndexOf("/") + 1))), () => []);
11047
11446
  if (!await exists())
11048
11447
  throw new Error(`Prime Agent owned daemon socket disappeared before cleanup (${socketPath}).`);
11049
11448
  let responseSeen = false;
11050
- const requestId = `switcher_${randomUUID4()}`;
11449
+ const requestId = `switcher_${randomUUID5()}`;
11051
11450
  let requestSent = false;
11052
11451
  await new Promise((resolve9, reject2) => {
11053
11452
  const socket = createConnection(socketPath);
@@ -11125,8 +11524,8 @@ async function primeRemainingSockets(socketPath, workerPrefix) {
11125
11524
  const daemon = await access3(socketPath).then(() => true, () => false);
11126
11525
  const workerDir = workerPrefix.slice(0, workerPrefix.lastIndexOf("/"));
11127
11526
  const prefix = workerPrefix.slice(workerPrefix.lastIndexOf("/") + 1);
11128
- const workers = await readdir4(workerDir).then((entries) => entries.filter((entry) => entry.startsWith(prefix)), () => []);
11129
- return [...daemon ? [socketPath] : [], ...workers.map((entry) => join15(workerDir, entry))];
11527
+ const workers = await readdir5(workerDir).then((entries) => entries.filter((entry) => entry.startsWith(prefix)), () => []);
11528
+ return [...daemon ? [socketPath] : [], ...workers.map((entry) => join16(workerDir, entry))];
11130
11529
  }
11131
11530
  function primeModel(input, api) {
11132
11531
  return input.models.map((model3) => ({
@@ -11144,7 +11543,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11144
11543
  if (!compatible(input.harness, input.protocol))
11145
11544
  throw new Error("Harness and provider protocol are incompatible.");
11146
11545
  validateHarnessVersion(input.harness, input.version);
11147
- if (!isAbsolute13(input.stateDir) || !isAbsolute13(input.cwd))
11546
+ if (!isAbsolute14(input.stateDir) || !isAbsolute14(input.cwd))
11148
11547
  throw new Error("Launch state and working directories must be absolute.");
11149
11548
  if (!input.models.length || !input.models.some((m) => m.id === input.model))
11150
11549
  throw new Error("Selected model is missing from the launch catalog.");
@@ -11175,7 +11574,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11175
11574
  env.ANTHROPIC_BASE_URL = input.baseUrl.replace(/\/v1$/, "");
11176
11575
  const nativeModel = (id2) => claudeNativeModelId(id2, input.models);
11177
11576
  Object.assign(env, claudeNativeModelEnvironment(input.nativePolicy?.env, input.models));
11178
- Object.assign(env, claudeContextEnvironment(providerBaseUrl));
11577
+ Object.assign(env, claudeContextEnvironment(providerBaseUrl, process.env, input.models.find((model3) => model3.id === input.model)?.contextWindow));
11179
11578
  env.ANTHROPIC_MODEL = nativeModel(input.model);
11180
11579
  env.ANTHROPIC_DEFAULT_MODEL = nativeModel(input.model);
11181
11580
  env.CLAUDE_CODE_SUBAGENT_MODEL = nativeModel(input.compiledPolicy?.roles.subagent ?? input.model);
@@ -11248,8 +11647,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11248
11647
  throw new Error("Pi cannot safely select model IDs that differ only by letter case; update the provider catalog.");
11249
11648
  const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions", "gemini-generate-content": "gemini" }[input.protocol];
11250
11649
  const providerId = piProviderId(input, providerBaseUrl);
11251
- const agentDir = join15(input.stateDir, "pi-agent");
11252
- const sessionDir = input.sessionDir ?? join15(input.stateDir, "sessions");
11650
+ const agentDir = join16(input.stateDir, "pi-agent");
11651
+ const sessionDir = input.sessionDir ?? join16(input.stateDir, "sessions");
11253
11652
  const piBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
11254
11653
  await mkdir10(agentDir, { recursive: true, mode: 448 });
11255
11654
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
@@ -11274,9 +11673,9 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11274
11673
  const selected = dshArguments(args);
11275
11674
  const providerId = piProviderId(input, providerBaseUrl);
11276
11675
  const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
11277
- const home = join15(input.stateDir, "dsh-home");
11278
- const sessionDir = input.sessionDir ?? join15(input.stateDir, "dsh-state");
11279
- if (!isAbsolute13(sessionDir))
11676
+ const home = join16(input.stateDir, "dsh-home");
11677
+ const sessionDir = input.sessionDir ?? join16(input.stateDir, "dsh-state");
11678
+ if (!isAbsolute14(sessionDir))
11280
11679
  throw new Error("DSH session directory must be absolute.");
11281
11680
  await mkdir10(home, { recursive: true, mode: 448 });
11282
11681
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
@@ -11297,7 +11696,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11297
11696
  }))
11298
11697
  } } } },
11299
11698
  { id: "agent-default-model", config: route2 },
11300
- { id: "session-persistence-jsonl", config: { root: join15(sessionDir, "sessions") } },
11699
+ { id: "session-persistence-jsonl", config: { root: join16(sessionDir, "sessions") } },
11301
11700
  { id: "attachment-local", config: { dshHome: sessionDir } },
11302
11701
  ...selected.profile === "acp" ? [{ id: "acp", config: route2 }] : []
11303
11702
  ];
@@ -11323,14 +11722,14 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11323
11722
  throw new Error("Prime Agent cannot safely select model IDs that differ only by letter case; update the provider catalog.");
11324
11723
  const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
11325
11724
  const providerId = primeProviderId(input, providerBaseUrl);
11326
- const sessionDir = input.sessionDir ?? join15(input.stateDir, "sessions");
11327
- const agentDir = join15(input.stateDir, "prime-agent");
11725
+ const sessionDir = input.sessionDir ?? join16(input.stateDir, "sessions");
11726
+ const agentDir = join16(input.stateDir, "prime-agent");
11328
11727
  const socketInfo = await primeSocketInfo();
11329
11728
  const { daemonSocket, runtimeDir, workerPrefix } = socketInfo;
11330
11729
  const primeBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
11331
11730
  await mkdir10(agentDir, { recursive: true, mode: 448 });
11332
11731
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
11333
- const file2 = join15(agentDir, "models.json");
11732
+ const file2 = join16(agentDir, "models.json");
11334
11733
  await writeFile13(file2, JSON.stringify({ providers: { [providerId]: {
11335
11734
  name: "Switcher",
11336
11735
  baseUrl: primeBaseUrl,
@@ -11422,13 +11821,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11422
11821
  const file2 = await jsonFile(input.stateDir, "opencode-legacy.json", config2);
11423
11822
  configPaths.push(file2);
11424
11823
  env.OPENCODE_CONFIG = file2;
11425
- const sessionDir = input.sessionDir ?? join15(input.stateDir, "sessions");
11824
+ const sessionDir = input.sessionDir ?? join16(input.stateDir, "sessions");
11426
11825
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
11427
- env.XDG_DATA_HOME = join15(sessionDir, "data");
11428
- env.XDG_CONFIG_HOME = join15(input.stateDir, "config");
11429
- env.XDG_CACHE_HOME = join15(input.stateDir, "cache");
11430
- env.XDG_STATE_HOME = join15(input.stateDir, "state");
11431
- env.HOME = join15(input.stateDir, "home");
11826
+ env.XDG_DATA_HOME = join16(sessionDir, "data");
11827
+ env.XDG_CONFIG_HOME = join16(input.stateDir, "config");
11828
+ env.XDG_CACHE_HOME = join16(input.stateDir, "cache");
11829
+ env.XDG_STATE_HOME = join16(input.stateDir, "state");
11830
+ env.HOME = join16(input.stateDir, "home");
11432
11831
  env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";
11433
11832
  env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config2);
11434
11833
  env[KEY4] = input.credential ?? "switcher-local-no-auth";
@@ -11452,7 +11851,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11452
11851
  const rolePolicy = compileOpenCodeModelPolicy({ providerId: providerID, mainModel: input.model, roles: input.compiledPolicy?.roles, preservedAgents: Object.entries(isolated.config.agents ?? {}).map(([name, agent]) => ({ ...agent, name })) });
11453
11852
  const modelRef = openCodeInvocationModel(args, rolePolicy, isolated.config.default_agent);
11454
11853
  const config = { ...isolated.config, ...rolePolicy.config, providers: { [providerID]: { name: "Switcher", env: [KEY4], package: `@opencode-ai/ai/providers/${packageName}`, settings: settings2, models } } };
11455
- const file = join15(input.stateDir, "opencode.json");
11854
+ const file = join16(input.stateDir, "opencode.json");
11456
11855
  await writeFile13(file, openCode2ConfigText(config, providerID, KEY4), { mode: 384, flag: "wx" });
11457
11856
  configPaths.push(file, isolated.instructionFile);
11458
11857
  Object.assign(env, isolated.env);
@@ -11537,7 +11936,7 @@ async function prepareHarnessLaunch(input) {
11537
11936
  validateHarnessVersion(input.harness, input.version);
11538
11937
  if (!compatible(input.harness, input.protocol))
11539
11938
  throw new Error("Harness and provider protocol are incompatible.");
11540
- if (!isAbsolute13(input.stateDir) || !isAbsolute13(input.cwd))
11939
+ if (!isAbsolute14(input.stateDir) || !isAbsolute14(input.cwd))
11541
11940
  throw new Error("Launch state and working directories must be absolute.");
11542
11941
  const compiledPolicy = compileModelPolicy(input.model, input.models, input.modelPolicy);
11543
11942
  if (input.harness === "antigravity" && input.model === antigravityHelperModel && compiledPolicy.roles.fast !== input.model)
@@ -11549,14 +11948,14 @@ async function prepareHarnessLaunch(input) {
11549
11948
  if (unsupported3.length)
11550
11949
  throw new Error(`${input.harness} does not expose native model controls for: ${unsupported3.join(", ")}.`);
11551
11950
  await mkdir10(input.stateDir, { recursive: true, mode: 448 });
11552
- const catalogPath = await jsonFile(input.stateDir, `switcher-model-policy-${randomUUID4()}.json`, { policy: compiledPolicy, models: input.models });
11951
+ const catalogPath = await jsonFile(input.stateDir, `switcher-model-policy-${randomUUID5()}.json`, { policy: compiledPolicy, models: input.models });
11553
11952
  const bridge = input.gatewayHost ? await input.gatewayHost.open({ ...input, compiledPolicy, catalogPath }).catch(async (error) => {
11554
- await rm2(catalogPath, { force: true });
11953
+ await rm3(catalogPath, { force: true });
11555
11954
  throw error;
11556
11955
  }) : createInferenceGateway({ ...input, compiledPolicy, catalogPath });
11557
11956
  const removeCatalog = async () => {
11558
11957
  if (!bridge.retainsState?.())
11559
- await rm2(catalogPath, { force: true });
11958
+ await rm3(catalogPath, { force: true });
11560
11959
  };
11561
11960
  try {
11562
11961
  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";
@@ -11577,9 +11976,9 @@ async function prepareHarnessLaunch(input) {
11577
11976
  }
11578
11977
 
11579
11978
  // src/ori-model-policy.ts
11580
- import { isAbsolute as isAbsolute14 } from "path";
11979
+ import { isAbsolute as isAbsolute15 } from "path";
11581
11980
  function prepareOriModelPolicy(target, prepared) {
11582
- if (!isAbsolute14(prepared.executable) || /[\0\r\n]/.test(prepared.executable))
11981
+ if (!isAbsolute15(prepared.executable) || /[\0\r\n]/.test(prepared.executable))
11583
11982
  throw new Error("Ori requires an absolute verified native executable.");
11584
11983
  const entries = Object.entries(prepared.env);
11585
11984
  if (entries.some(([key]) => !/^[A-Z_][A-Z0-9_]*$/.test(key)))
@@ -11603,8 +12002,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
11603
12002
  }
11604
12003
 
11605
12004
  // src/launcher.ts
11606
- import { lstat as lstat13, mkdir as mkdir14, mkdtemp, realpath as realpath8, rm as rm7, writeFile as writeFile18 } from "fs/promises";
11607
- import { join as join25, relative as relative7, resolve as resolve14 } from "path";
12005
+ import { lstat as lstat13, mkdir as mkdir14, mkdtemp, realpath as realpath8, rm as rm9, writeFile as writeFile18 } from "fs/promises";
12006
+ import { join as join27, relative as relative7, resolve as resolve14 } from "path";
11608
12007
 
11609
12008
  // src/provider-credential-onboarding.ts
11610
12009
  import { z as z9 } from "zod-v4";
@@ -11664,10 +12063,10 @@ async function verifyOpenCodeAuthentication(credential, fetchImpl) {
11664
12063
  // src/credentials.ts
11665
12064
  import { z as z8 } from "zod-v4";
11666
12065
  import { ExecutableTrustError, repairExecutablePermissions, validateExecutable } from "@hasna/contracts/executable-trust";
11667
- import { constants as constants5 } from "fs";
11668
- import { open as open4, readdir as readdir5, unlink, link, lstat as lstat7 } from "fs/promises";
11669
- import { join as join16, isAbsolute as isAbsolute15 } from "path";
11670
- import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
12066
+ import { constants as constants6 } from "fs";
12067
+ import { open as open5, readdir as readdir6, unlink, link, lstat as lstat7 } from "fs/promises";
12068
+ import { join as join17, isAbsolute as isAbsolute16 } from "path";
12069
+ import { createHash as createHash10, randomUUID as randomUUID6 } from "crypto";
11671
12070
  import { execFile as execFile3, spawn } from "child_process";
11672
12071
  import { promisify as promisify3 } from "util";
11673
12072
  import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
@@ -11692,7 +12091,7 @@ var credentialBindingSchema = z8.object({
11692
12091
  kind: z8.literal("vault"),
11693
12092
  key: vaultKeySchema,
11694
12093
  url: z8.string().max(2000).transform(endpoint).optional(),
11695
- executable: z8.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute15, "Secrets executable must be an absolute path"),
12094
+ executable: z8.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute16, "Secrets executable must be an absolute path"),
11696
12095
  operator
11697
12096
  }).strict()])
11698
12097
  }).strict().superRefine((binding, ctx) => {
@@ -11708,13 +12107,13 @@ class CredentialBindings {
11708
12107
  directory;
11709
12108
  constructor(env = process.env) {
11710
12109
  this.env = env;
11711
- this.directory = join16(switcherHome(env), "config", "credential-bindings");
12110
+ this.directory = join17(switcherHome(env), "config", "credential-bindings");
11712
12111
  }
11713
12112
  path(name) {
11714
- return join16(this.directory, parse2(reference, name) + ".json");
12113
+ return join17(this.directory, parse2(reference, name) + ".json");
11715
12114
  }
11716
12115
  async readableDirectory() {
11717
- for (const path of [switcherHome(this.env), join16(switcherHome(this.env), "config"), this.directory]) {
12116
+ for (const path of [switcherHome(this.env), join17(switcherHome(this.env), "config"), this.directory]) {
11718
12117
  let info;
11719
12118
  try {
11720
12119
  info = await lstat7(path);
@@ -11734,7 +12133,7 @@ class CredentialBindings {
11734
12133
  return;
11735
12134
  let file;
11736
12135
  try {
11737
- file = await open4(path, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
12136
+ file = await open5(path, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
11738
12137
  } catch (error) {
11739
12138
  if (error.code === "ENOENT")
11740
12139
  return;
@@ -11763,7 +12162,7 @@ class CredentialBindings {
11763
12162
  return [];
11764
12163
  let entries;
11765
12164
  try {
11766
- entries = await readdir5(this.directory);
12165
+ entries = await readdir6(this.directory);
11767
12166
  } catch (error) {
11768
12167
  if (error.code === "ENOENT")
11769
12168
  return [];
@@ -11783,10 +12182,10 @@ class CredentialBindings {
11783
12182
  if (binding.source.kind === "vault")
11784
12183
  await validateVaultExecutable(binding.source.executable);
11785
12184
  await privateDirectory(switcherHome(this.env));
11786
- await privateDirectory(join16(switcherHome(this.env), "config"));
12185
+ await privateDirectory(join17(switcherHome(this.env), "config"));
11787
12186
  await privateDirectory(this.directory);
11788
- const temporary = join16(this.directory, `.binding-${randomUUID5()}`);
11789
- const file = await open4(temporary, "wx", 384);
12187
+ const temporary = join17(this.directory, `.binding-${randomUUID6()}`);
12188
+ const file = await open5(temporary, "wx", 384);
11790
12189
  try {
11791
12190
  await file.writeFile(JSON.stringify(binding, null, 2) + `
11792
12191
  `);
@@ -12375,7 +12774,7 @@ async function launchCatalog(client, provider, dryRun = false, options = {}) {
12375
12774
  // src/harness-process.ts
12376
12775
  import { spawn as spawn2, spawnSync } from "child_process";
12377
12776
  import { EventEmitter } from "events";
12378
- import { existsSync, openSync, closeSync, writeSync, readSync, constants as constants6 } from "fs";
12777
+ import { existsSync, openSync, closeSync, writeSync, readSync, constants as constants7 } from "fs";
12379
12778
 
12380
12779
  // src/terminal-descriptors.ts
12381
12780
  async function terminalDescriptorDuplicator() {
@@ -12636,7 +13035,7 @@ async function runHarnessProcess(options) {
12636
13035
  process.stdin.on("data", relay);
12637
13036
  process.stdin.resume();
12638
13037
  } else {
12639
- controllingInput = openSync("/dev/tty", constants6.O_RDONLY | constants6.O_NONBLOCK);
13038
+ controllingInput = openSync("/dev/tty", constants7.O_RDONLY | constants7.O_NONBLOCK);
12640
13039
  stty(["raw", "-echo"]);
12641
13040
  const buffer = Buffer.alloc(4096);
12642
13041
  inputTimer = setInterval(() => {
@@ -12903,13 +13302,13 @@ function oriLaunchWarnings(target) {
12903
13302
 
12904
13303
  // src/chatgpt-launch.ts
12905
13304
  import { createHash as createHash13 } from "crypto";
12906
- import { writeFile as writeFile14, rm as rm4 } from "fs/promises";
12907
- import { join as join18 } from "path";
13305
+ import { writeFile as writeFile14, rm as rm5 } from "fs/promises";
13306
+ import { join as join19 } from "path";
12908
13307
  import { fileURLToPath } from "url";
12909
13308
 
12910
13309
  // src/desktop-state.ts
12911
- import { constants as constants7, closeSync as closeSync2, fstatSync, lstatSync, openSync as openSync2, readSync as readSync2 } from "fs";
12912
- 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";
13310
+ import { constants as constants8, closeSync as closeSync2, fstatSync, lstatSync, openSync as openSync2, readSync as readSync2 } from "fs";
13311
+ import { open as open6, rm as rm4, lstat as lstat8, rename as rename4, chmod as chmod2, copyFile as copyFile2, link as link2 } from "fs/promises";
12913
13312
  import { spawnSync as spawnSync2 } from "child_process";
12914
13313
  import { resolve as resolve9 } from "path";
12915
13314
  import { createHash as createHash12 } from "crypto";
@@ -12971,7 +13370,7 @@ async function safeDesktopSnapshot(path) {
12971
13370
  const info = await lstat8(path);
12972
13371
  admitDesktopFile(info);
12973
13372
  const metadataHash = admitDesktopMetadata(path, info);
12974
- const file = await open5(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
13373
+ const file = await open6(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
12975
13374
  try {
12976
13375
  const opened = await file.stat();
12977
13376
  admitOpenedDesktopFile(info, opened);
@@ -13000,7 +13399,7 @@ function safeDesktopSnapshotSync(path) {
13000
13399
  const info = lstatSync(path);
13001
13400
  admitDesktopFile(info);
13002
13401
  const metadataHash = admitDesktopMetadata(path, info);
13003
- const file = openSync2(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
13402
+ const file = openSync2(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
13004
13403
  try {
13005
13404
  const opened = fstatSync(file);
13006
13405
  admitOpenedDesktopFile(info, opened);
@@ -13038,7 +13437,7 @@ async function preserveDesktopFile(source, destination, expected) {
13038
13437
  if (copied.error || copied.status !== 0)
13039
13438
  throw new Fault(422, "desktop_state_permissions", "Desktop metadata preservation failed.");
13040
13439
  } else
13041
- await copyFile2(source, destination, constants7.COPYFILE_EXCL);
13440
+ await copyFile2(source, destination, constants8.COPYFILE_EXCL);
13042
13441
  if (!sameDesktopSnapshot(await safeDesktopSnapshot(source), expected) || !sameDesktopSnapshot(await safeDesktopSnapshot(destination), expected))
13043
13442
  throw new Fault(409, "desktop_state_changed", "Desktop original preservation readback failed.");
13044
13443
  }
@@ -13055,7 +13454,7 @@ async function exists(path) {
13055
13454
  }
13056
13455
  async function preserveConflict(path) {
13057
13456
  const target = conflictPath(path, "conflict");
13058
- await rename3(path, target);
13457
+ await rename4(path, target);
13059
13458
  return target;
13060
13459
  }
13061
13460
  async function restoreDisplaced(backup, path) {
@@ -13074,14 +13473,14 @@ async function restoreDisplaced(backup, path) {
13074
13473
  }
13075
13474
  throw error;
13076
13475
  }
13077
- await rm3(temporary, { force: true });
13476
+ await rm4(temporary, { force: true });
13078
13477
  if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), snapshot2))
13079
13478
  throw new Fault(409, "desktop_state_changed", `Desktop settings changed after restoration; original retained at ${backup}.`);
13080
13479
  } finally {
13081
13480
  if (await safeDesktopSnapshot(temporary).catch(() => {
13082
13481
  return;
13083
13482
  }) !== undefined)
13084
- await rm3(temporary, { force: true });
13483
+ await rm4(temporary, { force: true });
13085
13484
  }
13086
13485
  }
13087
13486
  async function replaceDesktopFile(path, temporary, expectedCurrent, expectedNew) {
@@ -13097,7 +13496,7 @@ async function replaceDesktopFile(path, temporary, expectedCurrent, expectedNew)
13097
13496
  throw new Fault(409, "desktop_state_changed", "Desktop replacement target appeared concurrently; existing state was preserved.");
13098
13497
  throw error;
13099
13498
  }
13100
- await rm3(temporary, { force: true });
13499
+ await rm4(temporary, { force: true });
13101
13500
  if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), expectedNew)) {
13102
13501
  const preserved = await preserveConflict(path);
13103
13502
  throw new Fault(409, "desktop_state_changed", `Desktop replacement changed after installation; foreign file preserved at ${preserved}.`);
@@ -13108,7 +13507,7 @@ async function replaceDesktopFile(path, temporary, expectedCurrent, expectedNew)
13108
13507
  let displaced = false;
13109
13508
  try {
13110
13509
  try {
13111
- await rename3(path, backup);
13510
+ await rename4(path, backup);
13112
13511
  displaced = true;
13113
13512
  } catch (error) {
13114
13513
  if (error.code === "ENOENT")
@@ -13138,7 +13537,7 @@ async function replaceDesktopFile(path, temporary, expectedCurrent, expectedNew)
13138
13537
  }
13139
13538
  throw error;
13140
13539
  }
13141
- await rm3(temporary, { force: true });
13540
+ await rm4(temporary, { force: true });
13142
13541
  if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), expectedNew)) {
13143
13542
  await restoreDisplaced(backup, path);
13144
13543
  displaced = false;
@@ -13161,7 +13560,7 @@ async function removeDesktopFile(path, expected, guard) {
13161
13560
  }
13162
13561
  const quarantine = conflictPath(path, "remove");
13163
13562
  try {
13164
- await rename3(path, quarantine);
13563
+ await rename4(path, quarantine);
13165
13564
  } catch (error) {
13166
13565
  if (error.code === "ENOENT")
13167
13566
  throw new Fault(409, "desktop_state_changed", "Desktop removal target disappeared; existing state was preserved.");
@@ -13188,7 +13587,7 @@ async function removeDesktopFile(path, expected, guard) {
13188
13587
  throw error;
13189
13588
  }
13190
13589
  }
13191
- await rm3(quarantine, { force: true });
13590
+ await rm4(quarantine, { force: true });
13192
13591
  if (await exists(path))
13193
13592
  throw new Fault(409, "desktop_state_changed", "Desktop removal target appeared concurrently; existing state was preserved.");
13194
13593
  }
@@ -13208,7 +13607,7 @@ async function writeDesktopPrivate(path, text, mode = 384, metadataSource, expec
13208
13607
  await preserveDesktopFile(metadataSource?.path ?? path, temporary, template);
13209
13608
  await chmod2(temporary, 384);
13210
13609
  }
13211
- const file = await open5(temporary, constants7.O_RDWR | constants7.O_NOFOLLOW | (template ? 0 : constants7.O_CREAT | constants7.O_EXCL), 384);
13610
+ const file = await open6(temporary, constants8.O_RDWR | constants8.O_NOFOLLOW | (template ? 0 : constants8.O_CREAT | constants8.O_EXCL), 384);
13212
13611
  try {
13213
13612
  await file.truncate(0);
13214
13613
  await file.writeFile(text);
@@ -13224,7 +13623,7 @@ async function writeDesktopPrivate(path, text, mode = 384, metadataSource, expec
13224
13623
  if (await safeDesktopSnapshot(temporary).catch(() => {
13225
13624
  return;
13226
13625
  }) !== undefined)
13227
- await rm3(temporary, { force: true });
13626
+ await rm4(temporary, { force: true });
13228
13627
  }
13229
13628
  }
13230
13629
  async function desktopLease(path) {
@@ -13269,11 +13668,11 @@ async function openDesktopLease(path, readOnly2 = false) {
13269
13668
  }
13270
13669
 
13271
13670
  // src/native-state.ts
13272
- 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";
13273
- import { constants as constants8, lstatSync as lstatSync2, realpathSync } from "fs";
13671
+ import { lstat as lstat9, mkdir as mkdir11, open as open7, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
13672
+ import { constants as constants9, lstatSync as lstatSync2, realpathSync } from "fs";
13274
13673
  import { execFileSync as execFileSync3 } from "child_process";
13275
13674
  import { homedir as homedir9, userInfo as userInfo3 } from "os";
13276
- import { dirname as dirname8, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve10 } from "path";
13675
+ import { dirname as dirname8, isAbsolute as isAbsolute17, join as join18, relative as relative5, resolve as resolve10 } from "path";
13277
13676
  function nativeStateRequested(tool, environment = process.env, explicit) {
13278
13677
  if (explicit !== undefined)
13279
13678
  return explicit;
@@ -13320,7 +13719,7 @@ async function info(path) {
13320
13719
  }
13321
13720
  }
13322
13721
  function absolute(value) {
13323
- if (!isAbsolute16(value) || value.includes("\x00"))
13722
+ if (!isAbsolute17(value) || value.includes("\x00"))
13324
13723
  throw new Fault(422, "native_state_path", "The shared native state directory must be an absolute path.");
13325
13724
  return resolve10(value);
13326
13725
  }
@@ -13428,10 +13827,10 @@ async function ensureNativeStateDirectory(path, create = true) {
13428
13827
  async function assertNativeStateIsolation(tool, home, environment = process.env) {
13429
13828
  home = absolute(home);
13430
13829
  const canonical = await resolveNativeState(tool, environment, { create: false });
13431
- const roots = [canonical.home, canonical.sqliteHome, join17(absolute(environment.HOME ?? homedir9()), `.${tool}`)];
13830
+ const roots = [canonical.home, canonical.sqliteHome, join18(absolute(environment.HOME ?? homedir9()), `.${tool}`)];
13432
13831
  const contains = (parent, child) => {
13433
13832
  const path = relative5(parent, child);
13434
- return path !== ".." && !path.startsWith("../") && !isAbsolute16(path);
13833
+ return path !== ".." && !path.startsWith("../") && !isAbsolute17(path);
13435
13834
  };
13436
13835
  if (roots.some((root) => root && (contains(root, home) || contains(home, root))))
13437
13836
  throw new Fault(409, "native_state_isolation_conflict", "The isolated home overlaps a canonical native corpus or database. Select a distinct private home; Switcher will not alter existing state.");
@@ -13439,8 +13838,8 @@ async function assertNativeStateIsolation(tool, home, environment = process.env)
13439
13838
  return;
13440
13839
  await assertNativeStateDirectory(home);
13441
13840
  for (const { name } of NATIVE_STATE_ENTRIES[tool]) {
13442
- await ensureNativeStateDirectory(dirname8(join17(home, name)), false);
13443
- if ((await info(join17(home, name)))?.isSymbolicLink())
13841
+ await ensureNativeStateDirectory(dirname8(join18(home, name)), false);
13842
+ if ((await info(join18(home, name)))?.isSymbolicLink())
13444
13843
  throw new Fault(409, "native_state_isolation_conflict", "This profile already links native state. Select a separate isolated profile; Switcher will not remove its existing shared links.");
13445
13844
  }
13446
13845
  if (tool === "codex") {
@@ -13450,7 +13849,7 @@ async function assertNativeStateIsolation(tool, home, environment = process.env)
13450
13849
  }
13451
13850
  }
13452
13851
  function nativeStateLockPath(state) {
13453
- return join17(state.home, ".switcher-shared-state.lock");
13852
+ return join18(state.home, ".switcher-shared-state.lock");
13454
13853
  }
13455
13854
  function nativeStateLockFault(entry) {
13456
13855
  if (!entry?.isFile() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 63) !== 0)
@@ -13462,7 +13861,7 @@ async function withNativeStateLock(state, operation) {
13462
13861
  const path = nativeStateLockPath(state);
13463
13862
  let handle;
13464
13863
  try {
13465
- handle = await open6(path, "wx", 384);
13864
+ handle = await open7(path, "wx", 384);
13466
13865
  } catch (error) {
13467
13866
  if (error.code !== "EEXIST")
13468
13867
  throw error;
@@ -13487,7 +13886,7 @@ var ownedByUser = (entry) => entry.uid === process.getuid?.();
13487
13886
  var ownerProbe = ownedByUser;
13488
13887
  function strictlyInside(root, path) {
13489
13888
  const suffix = relative5(root, path);
13490
- return suffix !== "" && suffix !== ".." && !suffix.startsWith("../") && !isAbsolute16(suffix);
13889
+ return suffix !== "" && suffix !== ".." && !suffix.startsWith("../") && !isAbsolute17(suffix);
13491
13890
  }
13492
13891
  async function assertCorpusLink(link3, root) {
13493
13892
  const refuse = (why) => new Fault(422, "native_state_entry", `The shared native state entry ${displayPath(link3)} is a symbolic link that ${why}. Shared entries must be regular files, directories, or links you own to another entry inside ${displayPath(root)}.`);
@@ -13530,7 +13929,7 @@ async function assertCorpusLink(link3, root) {
13530
13929
  canonical = await inspect(raw, () => realpath6(raw));
13531
13930
  else {
13532
13931
  const parent = await inspect(raw, () => realpath6(raw.slice(0, raw.length - last.length)));
13533
- canonical = join17(parent, last);
13932
+ canonical = join18(parent, last);
13534
13933
  }
13535
13934
  if (canonical === root)
13536
13935
  throw refuse("points at the shared directory itself");
@@ -13560,7 +13959,7 @@ async function assertShareableTree(path, budget = { entries: 0 }, depth = 0, roo
13560
13959
  if (depth === 0)
13561
13960
  await assertNativeStateDirectory(path);
13562
13961
  for await (const child of await opendir(path)) {
13563
- const nested = join17(path, child.name);
13962
+ const nested = join18(path, child.name);
13564
13963
  if (++budget.entries > 1e5)
13565
13964
  throw new Fault(422, "native_state_inventory_limit", `The shared native corpus exceeds the safe projection inventory limit of 100,000 entries at ${displayPath(nested)}.`);
13566
13965
  if (child.isSymbolicLink()) {
@@ -13581,12 +13980,12 @@ async function assertShareableTree(path, budget = { entries: 0 }, depth = 0, roo
13581
13980
  }
13582
13981
  }
13583
13982
  async function readCodexStateConfig(home) {
13584
- const path = join17(home, "config.toml"), entry = await info(path);
13983
+ const path = join18(home, "config.toml"), entry = await info(path);
13585
13984
  if (!entry)
13586
13985
  return {};
13587
13986
  if (!entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
13588
13987
  throw new Fault(422, "native_state_config", "The Codex instruction configuration cannot be read safely.");
13589
- const handle = await open6(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
13988
+ const handle = await open7(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
13590
13989
  let config;
13591
13990
  try {
13592
13991
  const opened = await handle.stat();
@@ -13616,11 +14015,11 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
13616
14015
  throw new Fault(422, "native_state_instructions", "Codex instruction configuration has an unsupported value.");
13617
14016
  if (CODEX_INSTRUCTION_FILE_KEYS.has(key)) {
13618
14017
  const path = resolve10(home, value), entry = await info(path);
13619
- const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute16(relativePath);
14018
+ const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute17(relativePath);
13620
14019
  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)
13621
14020
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
13622
14021
  await assertSafeAncestors(dirname8(path));
13623
- const handle = await open6(path, constants8.O_RDONLY | constants8.O_NOFOLLOW).catch(() => {
14022
+ const handle = await open7(path, constants9.O_RDONLY | constants9.O_NOFOLLOW).catch(() => {
13624
14023
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
13625
14024
  });
13626
14025
  try {
@@ -13661,7 +14060,7 @@ async function resolveNativeState(tool, environment = process.env, options = {})
13661
14060
  if (primary !== undefined && legacy !== undefined && absolute(primary) !== absolute(legacy))
13662
14061
  throw new Fault(409, "native_state_identity_conflict", `The ${marker} and ${legacyMarker} corpus identities disagree. Select one exact shared native state directory before launching.`);
13663
14062
  const userHome = absolute(environment.HOME ?? homedir9());
13664
- let selected = primary !== undefined ? absolute(primary) : legacy !== undefined ? absolute(legacy) : join17(userHome, `.${tool}`);
14063
+ let selected = primary !== undefined ? absolute(primary) : legacy !== undefined ? absolute(legacy) : join18(userHome, `.${tool}`);
13665
14064
  if (credentialOverlay(selected))
13666
14065
  throw new Fault(422, "native_state_overlay", "An authentication profile cannot be the shared native state directory. Select its original native state directory.");
13667
14066
  const real = primary === undefined && legacy === undefined ? await resolveCorpusLink(selected) : selected;
@@ -13721,7 +14120,7 @@ async function directoryHasEntries(path) {
13721
14120
  }
13722
14121
  }
13723
14122
  async function legacyNativeStateWarnings(root, state) {
13724
- const directory = join17(root, state.tool === "codex" ? "desktop" : "desktop-claude");
14123
+ const directory = join18(root, state.tool === "codex" ? "desktop" : "desktop-claude");
13725
14124
  if (!await info(directory))
13726
14125
  return [];
13727
14126
  await assertNativeStateDirectory(directory);
@@ -13732,12 +14131,12 @@ async function legacyNativeStateWarnings(root, state) {
13732
14131
  throw new Fault(409, "native_state_inventory_limit", "Too many legacy desktop profiles to inspect safely.");
13733
14132
  if (!entry.isDirectory() || entry.isSymbolicLink())
13734
14133
  continue;
13735
- const home = join17(directory, entry.name, ...state.tool === "codex" ? ["codex"] : []);
14134
+ const home = join18(directory, entry.name, ...state.tool === "codex" ? ["codex"] : []);
13736
14135
  if (!await info(home))
13737
14136
  continue;
13738
14137
  await assertNativeStateDirectory(home);
13739
14138
  for (const name of [...NATIVE_STATE_ENTRIES[state.tool].map((item2) => item2.name), ...state.tool === "codex" ? ["state_5.sqlite", "session_index.jsonl"] : []]) {
13740
- const path = join17(home, name), item2 = await info(path);
14139
+ const path = join18(home, name), item2 = await info(path);
13741
14140
  if (!item2 || item2.isSymbolicLink())
13742
14141
  continue;
13743
14142
  if (item2.isFile() && item2.size > 0 || item2.isDirectory() && await directoryHasEntries(path)) {
@@ -13785,13 +14184,13 @@ async function preflightNativeStateProjection(state, overlayHome, plan = false)
13785
14184
  return;
13786
14185
  const contains = (parent, child) => {
13787
14186
  const suffix = relative5(parent, child);
13788
- return suffix !== ".." && !suffix.startsWith("../") && !isAbsolute16(suffix);
14187
+ return suffix !== ".." && !suffix.startsWith("../") && !isAbsolute17(suffix);
13789
14188
  };
13790
14189
  if (contains(state.home, overlayHome) || contains(overlayHome, state.home))
13791
14190
  throw new Fault(422, "native_state_overlap", "The shared corpus and authentication overlay must be separate directories.");
13792
14191
  await assertCodexDatabaseRedirectSafe(state, overlayHome);
13793
14192
  for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
13794
- const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
14193
+ const target = join18(state.home, entry.name), destination = join18(overlayHome, entry.name);
13795
14194
  if (corpus)
13796
14195
  await ensureNativeStateDirectory(dirname8(target), false);
13797
14196
  if (overlay)
@@ -13814,7 +14213,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13814
14213
  const createdFiles = [], createdDirectories = [];
13815
14214
  try {
13816
14215
  for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
13817
- const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
14216
+ const target = join18(state.home, entry.name), destination = join18(overlayHome, entry.name);
13818
14217
  const targetParent = dirname8(target), destinationParent = dirname8(destination);
13819
14218
  if (!await info(targetParent))
13820
14219
  await createTrackedDirectory(targetParent, createdDirectories);
@@ -13830,7 +14229,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13830
14229
  if (entry.kind === "directory")
13831
14230
  await createTrackedDirectory(target, createdDirectories);
13832
14231
  else {
13833
- const file = await open6(target, "wx", 384);
14232
+ const file = await open7(target, "wx", 384);
13834
14233
  await file.close();
13835
14234
  createdFiles.push(target);
13836
14235
  }
@@ -13913,20 +14312,20 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedSta
13913
14312
  if (sharedState && sharedState.tool !== "codex")
13914
14313
  throw new Fault(422, "native_state_tool", "ChatGPT requires the canonical Codex corpus.");
13915
14314
  await privateDirectory(sessionDir);
13916
- const home = join18(sessionDir, "codex"), userData = join18(sessionDir, "electron");
14315
+ const home = join19(sessionDir, "codex"), userData = join19(sessionDir, "electron");
13917
14316
  await privateDirectory(home);
13918
14317
  await privateDirectory(userData);
13919
- const release = await desktopLease(join18(sessionDir, "launch.sqlite"));
14318
+ const release = await desktopLease(join19(sessionDir, "launch.sqlite"));
13920
14319
  let released = false, authText;
13921
- const authPath = join18(home, "auth.json"), receiptPath = join18(home, ".switcher-auth.sha256");
14320
+ const authPath = join19(home, "auth.json"), receiptPath = join19(home, ".switcher-auth.sha256");
13922
14321
  const cleanup = async () => {
13923
14322
  if (released)
13924
14323
  return;
13925
14324
  released = true;
13926
14325
  try {
13927
14326
  if (authText !== undefined && await safeDesktopRead(authPath) === authText) {
13928
- await rm4(authPath, { force: true });
13929
- await rm4(receiptPath, { force: true });
14327
+ await rm5(authPath, { force: true });
14328
+ await rm5(receiptPath, { force: true });
13930
14329
  }
13931
14330
  } finally {
13932
14331
  release();
@@ -13949,7 +14348,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedSta
13949
14348
  settings2.push('approval_policy="on-request"');
13950
14349
  if (!settings2.some((setting) => setting.startsWith("sandbox_mode=")))
13951
14350
  settings2.push('sandbox_mode="workspace-write"');
13952
- const configPath = join18(home, "config.toml");
14351
+ const configPath = join19(home, "config.toml");
13953
14352
  const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
13954
14353
  if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
13955
14354
  throw new Fault(409, "desktop_auth_changed", "This isolated desktop profile contains authentication that Switcher did not create. Sign out of that provider profile before launching it again; Switcher will not overwrite it.");
@@ -13976,7 +14375,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedSta
13976
14375
  `;
13977
14376
  await writeDesktopPrivate(receiptPath, digest(authText));
13978
14377
  await writeDesktopPrivate(authPath, authText);
13979
- const wrapper = join18(stateDir, "chatgpt-codex");
14378
+ const wrapper = join19(stateDir, "chatgpt-codex");
13980
14379
  const overrides = settings2.flatMap((setting) => ["-c", setting]);
13981
14380
  let bridge = "";
13982
14381
  if (sharedState) {
@@ -14022,19 +14421,19 @@ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join("
14022
14421
 
14023
14422
  // src/claude-desktop-launch.ts
14024
14423
  import { writeFile as writeFile17 } from "fs/promises";
14025
- import { join as join21 } from "path";
14424
+ import { join as join22 } from "path";
14026
14425
  // src/desktop-selection.ts
14027
- import { createHash as createHash14, randomUUID as randomUUID6 } from "crypto";
14028
- import { writeFile as writeFile15, rename as rename4 } from "fs/promises";
14029
- import { join as join19 } from "path";
14426
+ import { createHash as createHash14, randomUUID as randomUUID7 } from "crypto";
14427
+ import { writeFile as writeFile15, rename as rename5 } from "fs/promises";
14428
+ import { join as join20 } from "path";
14030
14429
  var hash2 = (text) => createHash14("sha256").update(text).digest("hex");
14031
14430
  var conflict = () => new Fault(409, "desktop_config_changed", "Desktop configuration changed; existing bytes and the recovery receipt were preserved.");
14032
14431
  var invalid3 = () => new Fault(409, "desktop_recovery", "Desktop selection needs recovery by its owning supported version before another launch.");
14033
14432
  var identifier = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,80}$/.test(value);
14034
14433
  var admittedMode = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4095 && (value & 18) === 0;
14035
14434
  var matches = (actual, text, mode, metadataHash) => (actual?.text ?? null) === text && (actual?.mode ?? null) === mode && (actual?.metadataHash ?? null) === metadataHash;
14036
- var originalPath = (library, id2) => join19(library, `.switcher-original-${id2}.bak`);
14037
- var preparedPath = (library, id2) => join19(library, `.switcher-selected-${id2}.tmp`);
14435
+ var originalPath = (library, id2) => join20(library, `.switcher-original-${id2}.bak`);
14436
+ var preparedPath = (library, id2) => join20(library, `.switcher-selected-${id2}.tmp`);
14038
14437
  function metadata(text) {
14039
14438
  if (text === null)
14040
14439
  return { entries: [] };
@@ -14093,7 +14492,7 @@ async function selectedUnchanged(library, r) {
14093
14492
  const selected = r.previousSelected;
14094
14493
  if (!selected)
14095
14494
  return;
14096
- const current = await safeDesktopRead(join19(library, selected.id + ".json"));
14495
+ const current = await safeDesktopRead(join20(library, selected.id + ".json"));
14097
14496
  if (selected.hash !== undefined) {
14098
14497
  if (selected.hash === null ? current !== undefined : current === undefined || hash2(current) !== selected.hash)
14099
14498
  throw conflict();
@@ -14103,7 +14502,7 @@ async function selectedUnchanged(library, r) {
14103
14502
  function selectedUnchangedSync(library, selected) {
14104
14503
  if (!selected)
14105
14504
  return true;
14106
- const current = safeDesktopSnapshotSync(join19(library, selected.id + ".json"))?.text;
14505
+ const current = safeDesktopSnapshotSync(join20(library, selected.id + ".json"))?.text;
14107
14506
  if (selected.hash !== undefined)
14108
14507
  return selected.hash === null ? current === undefined : current !== undefined && hash2(current) === selected.hash;
14109
14508
  return (current ?? null) === (selected.text ?? null);
@@ -14123,10 +14522,10 @@ async function preservedSelection(library, r, wasApplied) {
14123
14522
  return { backup, prepared };
14124
14523
  }
14125
14524
  async function recoverDesktopSelection(library) {
14126
- const path = join19(library, ".switcher-selection.json"), raw = await safeDesktopRead(path);
14525
+ const path = join20(library, ".switcher-selection.json"), raw = await safeDesktopRead(path);
14127
14526
  if (raw === undefined)
14128
14527
  return;
14129
- const parsed = receipt(raw), metaPath = join19(library, "_meta.json"), configPath = join19(library, parsed.id + ".json");
14528
+ const parsed = receipt(raw), metaPath = join20(library, "_meta.json"), configPath = join20(library, parsed.id + ".json");
14130
14529
  let currentMeta = await safeDesktopSnapshot(metaPath);
14131
14530
  const r = upgradeReceipt(parsed, currentMeta);
14132
14531
  const currentConfig = await safeDesktopRead(configPath);
@@ -14183,7 +14582,7 @@ async function recoverDesktopSelection(library) {
14183
14582
  const receiptSnapshot = await safeDesktopSnapshot(path);
14184
14583
  if (!receiptSnapshot || receiptSnapshot.text !== raw)
14185
14584
  throw conflict();
14186
- const recoveredPath = path + ".recovered-" + randomUUID6(), retained = retainedReceipt(r);
14585
+ const recoveredPath = path + ".recovered-" + randomUUID7(), retained = retainedReceipt(r);
14187
14586
  if (retained !== raw) {
14188
14587
  await writeFile15(recoveredPath, retained, { mode: 384, flag: "wx" });
14189
14588
  const redacted = await safeDesktopSnapshot(recoveredPath);
@@ -14195,19 +14594,19 @@ async function recoverDesktopSelection(library) {
14195
14594
  await assertMetaRestored();
14196
14595
  const finalReceipt2 = await safeDesktopSnapshot(recoveredPath);
14197
14596
  if (!sameDesktopSnapshot(finalReceipt2, redacted)) {
14198
- const foreignPath = recoveredPath + ".foreign-" + randomUUID6();
14597
+ const foreignPath = recoveredPath + ".foreign-" + randomUUID7();
14199
14598
  if (finalReceipt2 !== undefined)
14200
- await rename4(recoveredPath, foreignPath);
14599
+ await rename5(recoveredPath, foreignPath);
14201
14600
  await writeDesktopPrivate(recoveredPath, retained, 384, undefined, { current: undefined });
14202
14601
  throw new Fault(409, "desktop_config_changed", `Desktop recovery receipt changed; redacted receipt preserved at ${recoveredPath}; foreign receipt preserved at ${foreignPath}.`);
14203
14602
  }
14204
14603
  return;
14205
14604
  }
14206
- await rename4(path, recoveredPath);
14605
+ await rename5(path, recoveredPath);
14207
14606
  const preserveRecovered = async (snapshot2) => {
14208
- const foreignPath = recoveredPath + ".foreign-" + randomUUID6();
14607
+ const foreignPath = recoveredPath + ".foreign-" + randomUUID7();
14209
14608
  if (snapshot2 !== undefined)
14210
- await rename4(recoveredPath, foreignPath);
14609
+ await rename5(recoveredPath, foreignPath);
14211
14610
  await writeDesktopPrivate(recoveredPath, raw, 384, undefined, { current: undefined });
14212
14611
  throw new Fault(409, "desktop_config_changed", `Desktop recovery receipt changed; original receipt preserved at ${recoveredPath}; foreign receipt preserved at ${foreignPath}.`);
14213
14612
  };
@@ -14221,11 +14620,11 @@ async function recoverDesktopSelection(library) {
14221
14620
  }
14222
14621
  async function applyDesktopSelection(library, config, label2, checkpoint) {
14223
14622
  await recoverDesktopSelection(library);
14224
- const path = join19(library, ".switcher-selection.json"), metaPath = join19(library, "_meta.json");
14623
+ const path = join20(library, ".switcher-selection.json"), metaPath = join20(library, "_meta.json");
14225
14624
  const original = await safeDesktopSnapshot(metaPath), previousMeta = original?.text ?? null, previousMetaMode = original?.mode ?? null, previous = metadata(previousMeta);
14226
- const previousSelectedText = previous.appliedId ? await safeDesktopRead(join19(library, previous.appliedId + ".json")) : undefined;
14625
+ const previousSelectedText = previous.appliedId ? await safeDesktopRead(join20(library, previous.appliedId + ".json")) : undefined;
14227
14626
  const previousSelected = previous.appliedId ? { id: previous.appliedId, hash: previousSelectedText === undefined ? null : hash2(previousSelectedText) } : null;
14228
- const id2 = randomUUID6(), configPath = join19(library, id2 + ".json"), text = JSON.stringify(config, null, 2) + `
14627
+ const id2 = randomUUID7(), configPath = join20(library, id2 + ".json"), text = JSON.stringify(config, null, 2) + `
14229
14628
  `;
14230
14629
  const appliedMeta = JSON.stringify({ ...previous, appliedId: id2, entries: [...previous.entries, { id: id2, name: label2 }] }, null, 2) + `
14231
14630
  `;
@@ -14304,10 +14703,10 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
14304
14703
  }
14305
14704
 
14306
14705
  // src/claude-user-settings.ts
14307
- import { constants as constants9 } from "fs";
14308
- import { lstat as lstat10, open as open7, writeFile as writeFile16 } from "fs/promises";
14706
+ import { constants as constants10 } from "fs";
14707
+ import { lstat as lstat10, open as open8, writeFile as writeFile16 } from "fs/promises";
14309
14708
  import { homedir as homedir10 } from "os";
14310
- import { join as join20, relative as relative6, resolve as resolve11 } from "path";
14709
+ import { join as join21, relative as relative6, resolve as resolve11 } from "path";
14311
14710
  var preferences = new Set([
14312
14711
  "$schema",
14313
14712
  "permissions",
@@ -14362,7 +14761,7 @@ async function readSettings(home, created) {
14362
14761
  }))
14363
14762
  return;
14364
14763
  await ensureNativeStateDirectory(home, false);
14365
- const path = join20(home, "settings.json");
14764
+ const path = join21(home, "settings.json");
14366
14765
  const entry = await lstat10(path).catch((error) => {
14367
14766
  if (error.code === "ENOENT")
14368
14767
  return;
@@ -14372,7 +14771,7 @@ async function readSettings(home, created) {
14372
14771
  return;
14373
14772
  if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || entry.uid !== process.getuid?.() || writableByOthers(entry) || entry.size > 1024 * 1024)
14374
14773
  throw invalid4(path);
14375
- const handle = await open7(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
14774
+ const handle = await open8(path, constants10.O_RDONLY | constants10.O_NOFOLLOW);
14376
14775
  try {
14377
14776
  const opened = await handle.stat();
14378
14777
  if (opened.dev !== entry.dev || opened.ino !== entry.ino || opened.nlink !== 1 || opened.size > 1024 * 1024)
@@ -14429,19 +14828,19 @@ function project(settings2, existing, path) {
14429
14828
  }
14430
14829
  async function prepareClaudeUserSettings(overlayHome, environment = process.env, corpusHome, options = {}) {
14431
14830
  overlayHome = resolve11(overlayHome);
14432
- const target = join20(overlayHome, "settings.json");
14831
+ const target = join21(overlayHome, "settings.json");
14433
14832
  const existing = await readSettings(overlayHome, options.write === false ? options.created : undefined);
14434
14833
  if (existing !== undefined) {
14435
14834
  project(existing, true, target);
14436
14835
  return [];
14437
14836
  }
14438
- const sourceHome = resolve11(environment.CLAUDE_CONFIG_DIR ?? corpusHome ?? join20(environment.HOME ?? homedir10(), ".claude"));
14837
+ const sourceHome = resolve11(environment.CLAUDE_CONFIG_DIR ?? corpusHome ?? join21(environment.HOME ?? homedir10(), ".claude"));
14439
14838
  if (sourceHome === overlayHome)
14440
14839
  return [];
14441
14840
  const source = await readSettings(sourceHome);
14442
14841
  if (source === undefined)
14443
14842
  return [];
14444
- const { settings: settings2, dropped } = project(source, false, join20(sourceHome, "settings.json"));
14843
+ const { settings: settings2, dropped } = project(source, false, join21(sourceHome, "settings.json"));
14445
14844
  const warnings = dropped.length ? [`Claude user settings not copied to this launch's private settings (unsupported keys): ${dropped.map((key) => JSON.stringify(key)).join(", ")}.`] : [];
14446
14845
  if (options.write === false)
14447
14846
  return warnings;
@@ -14473,9 +14872,9 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
14473
14872
  const check2 = system?.assertAvailable ?? (() => assertClaudeDesktopAvailable(userData));
14474
14873
  await check2();
14475
14874
  await privateDirectory(userData);
14476
- const library = join21(userData, "configLibrary");
14875
+ const library = join22(userData, "configLibrary");
14477
14876
  await privateDirectory(library);
14478
- const release = await desktopLease(join21(library, ".switcher-lease.sqlite"));
14877
+ const release = await desktopLease(join22(library, ".switcher-lease.sqlite"));
14479
14878
  let selection, gateway, closed = false, cleanupError;
14480
14879
  const cleanup = async () => {
14481
14880
  if (closed) {
@@ -14496,7 +14895,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
14496
14895
  };
14497
14896
  try {
14498
14897
  await recoverDesktopSelection(library);
14499
- const localConfig = await safeDesktopRead(join21(userData, "claude_desktop_config.json"));
14898
+ const localConfig = await safeDesktopRead(join22(userData, "claude_desktop_config.json"));
14500
14899
  if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
14501
14900
  throw new Fault(409, "desktop_mode", "Claude's third-party profile is set to standard account mode. Select third-party mode in Claude before launching this gateway.");
14502
14901
  const settingsWarnings = input.sharedState ? await prepareClaudeUserSettings(sessionDir, process.env, input.sharedState.home) : [];
@@ -14510,7 +14909,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
14510
14909
  if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
14511
14910
  throw new Fault(409, "desktop_alias_conflict", "The model policy conflicts with Claude desktop's reserved switcher/sonnet, switcher/opus or switcher/haiku routing aliases.");
14512
14911
  const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
14513
- const catalogPath = join21(input.stateDir, "claude-desktop-policy.json");
14912
+ const catalogPath = join22(input.stateDir, "claude-desktop-policy.json");
14514
14913
  await writeFile17(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
14515
14914
  gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
14516
14915
  selection = await applyDesktopSelection(library, {
@@ -14744,22 +15143,90 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
14744
15143
  }
14745
15144
  }
14746
15145
 
15146
+ // src/gateway-fallback.ts
15147
+ import { randomUUID as randomUUID8 } from "crypto";
15148
+ import { open as open9, rename as rename6, rm as rm6 } from "fs/promises";
15149
+ import { basename as basename5, dirname as dirname9, join as join23 } from "path";
15150
+ var PER_LAUNCH_GATEWAY_DIRECTORY = "per-launch-gateways";
15151
+ async function writeRecord(path, record4) {
15152
+ await privateDirectory(dirname9(path));
15153
+ const temporary = `${path}.${randomUUID8()}.tmp`;
15154
+ const file = await open9(temporary, "wx", 384);
15155
+ try {
15156
+ try {
15157
+ await file.writeFile(JSON.stringify(record4, null, 2) + `
15158
+ `);
15159
+ } finally {
15160
+ await file.close();
15161
+ }
15162
+ await rename6(temporary, path);
15163
+ } catch (error) {
15164
+ await rm6(temporary, { force: true }).catch(() => {
15165
+ return;
15166
+ });
15167
+ throw error;
15168
+ }
15169
+ }
15170
+ function perLaunchGatewayRecordPath(stateDir) {
15171
+ return join23(dirname9(stateDir), PER_LAUNCH_GATEWAY_DIRECTORY, `${basename5(stateDir)}.json`);
15172
+ }
15173
+ async function openPerLaunchGateway(input, context) {
15174
+ const lease = createInferenceGateway(input);
15175
+ const port = Number(new URL(lease.baseUrl).port);
15176
+ let path, record4;
15177
+ if (context.stateDir) {
15178
+ path = perLaunchGatewayRecordPath(context.stateDir);
15179
+ record4 = {
15180
+ schema: 1,
15181
+ launchId: basename5(context.stateDir),
15182
+ port,
15183
+ harness: input.harness,
15184
+ model: input.model,
15185
+ cwd: input.cwd,
15186
+ ...input.sessionDir ? { sessionDir: input.sessionDir } : {},
15187
+ launcherPid: process.pid,
15188
+ reason: context.reason,
15189
+ createdAt: new Date().toISOString()
15190
+ };
15191
+ try {
15192
+ await writeRecord(path, record4);
15193
+ } catch {
15194
+ path = undefined;
15195
+ }
15196
+ }
15197
+ (context.warn ?? console.error)(`switcher: WARNING: ${context.reason}; this launch uses a per-launch gateway on 127.0.0.1:${port} that stops when this command exits. ` + `A session that outlives this launch, or is resumed later outside Switcher, cannot reach that port and every request fails. ` + `${path ? `Recorded in ${path}. ` : ""}Check \`switcher gateway status\` and run \`switcher gateway install\`, then start the session again with \`switcher launch\` (a Claude session: \`switcher resume <session id>\`).`);
15198
+ return { ...lease, cleanup: async () => {
15199
+ try {
15200
+ await lease.cleanup();
15201
+ } finally {
15202
+ if (path && record4)
15203
+ await writeRecord(path, { ...record4, endedAt: new Date().toISOString() }).catch(() => {
15204
+ return;
15205
+ });
15206
+ }
15207
+ } };
15208
+ }
15209
+ function perLaunchGatewayHost(context) {
15210
+ return { open: (input) => openPerLaunchGateway(input, context) };
15211
+ }
15212
+
14747
15213
  // src/gateway-client.ts
14748
15214
  import { spawn as spawn4 } from "child_process";
14749
15215
  import { closeSync as closeSync3, openSync as openSync3 } from "fs";
14750
- import { rm as rm6 } from "fs/promises";
14751
- import { join as join24 } from "path";
15216
+ import { rm as rm8 } from "fs/promises";
15217
+ import { join as join26 } from "path";
14752
15218
 
14753
15219
  // src/gateway-service.ts
14754
- import { createHash as createHash16, randomBytes as randomBytes2, randomUUID as randomUUID7 } from "crypto";
14755
- import { constants as constants10 } from "fs";
14756
- 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";
14757
- import { basename as basename5, dirname as dirname9, isAbsolute as isAbsolute17, join as join22, resolve as resolve13 } from "path";
15220
+ import { createHash as createHash16, randomBytes as randomBytes2, randomUUID as randomUUID9 } from "crypto";
15221
+ import { constants as constants11 } from "fs";
15222
+ import { hostname } from "os";
15223
+ import { chmod as chmod3, lstat as lstat11, mkdir as mkdir12, open as open10, readdir as readdir8, readFile as readFile8, rename as rename7, rm as rm7, unlink as unlink3 } from "fs/promises";
15224
+ import { basename as basename6, dirname as dirname10, isAbsolute as isAbsolute18, join as join24, resolve as resolve13 } from "path";
14758
15225
  import { z as z10 } from "zod-v4";
14759
15226
 
14760
15227
  // src/process-table.ts
14761
15228
  import { createHash as createHash15 } from "crypto";
14762
- import { readdir as readdir6, readFile as readFile7, readlink as readlink2 } from "fs/promises";
15229
+ import { readdir as readdir7, readFile as readFile7, readlink as readlink2 } from "fs/promises";
14763
15230
  var MAX_PROCESSES = 1e5;
14764
15231
  async function darwinTable() {
14765
15232
  const child = Bun.spawn(["/bin/ps", "-A", "-o", "pid=", "-o", "ppid=", "-o", "lstart="], {
@@ -14785,7 +15252,7 @@ async function darwinTable() {
14785
15252
  async function linuxTable() {
14786
15253
  const boot = (await readFile7("/proc/sys/kernel/random/boot_id", "utf8").catch(() => "")).trim();
14787
15254
  const table = new Map;
14788
- for (const name of await readdir6("/proc")) {
15255
+ for (const name of await readdir7("/proc")) {
14789
15256
  if (!/^\d+$/.test(name) || table.size >= MAX_PROCESSES)
14790
15257
  continue;
14791
15258
  let stat6;
@@ -14945,12 +15412,12 @@ async function linuxPeers(clientPort, serverPort) {
14945
15412
  if (!inodes.size)
14946
15413
  return [];
14947
15414
  const found = [];
14948
- for (const name of await readdir6("/proc")) {
15415
+ for (const name of await readdir7("/proc")) {
14949
15416
  if (!/^\d+$/.test(name))
14950
15417
  continue;
14951
15418
  let descriptors;
14952
15419
  try {
14953
- descriptors = await readdir6(`/proc/${name}/fd`);
15420
+ descriptors = await readdir7(`/proc/${name}/fd`);
14954
15421
  } catch {
14955
15422
  continue;
14956
15423
  }
@@ -14982,12 +15449,12 @@ var DEFAULT_SCAN_MS = 1000;
14982
15449
  var PERSIST_INTERVAL_MS = 5000;
14983
15450
  var USE_PERSIST_INTERVAL_MS = 60000;
14984
15451
  function gatewayPaths(env = process.env) {
14985
- const root = join22(switcherHome(env), "gateway");
14986
- const preferred = join22(root, "control.sock");
15452
+ const root = join24(switcherHome(env), "gateway");
15453
+ const preferred = join24(root, "control.sock");
14987
15454
  const name = `${createHash16("sha256").update(root).digest("hex").slice(0, 16)}.sock`;
14988
- const runtime = process.platform === "linux" && env.XDG_RUNTIME_DIR && isAbsolute17(env.XDG_RUNTIME_DIR) ? join22(env.XDG_RUNTIME_DIR, "switcher", name) : undefined;
14989
- const socket = Buffer.byteLength(preferred) <= SOCKET_PATH_LIMIT ? preferred : runtime && Buffer.byteLength(runtime) <= SOCKET_PATH_LIMIT ? runtime : join22("/tmp", `switcher-${process.getuid?.() ?? 0}`, name);
14990
- return { root, socket, launches: join22(root, "launches"), ended: join22(root, "ended"), config: join22(root, "config.json"), log: join22(root, "service.log") };
15455
+ const runtime = process.platform === "linux" && env.XDG_RUNTIME_DIR && isAbsolute18(env.XDG_RUNTIME_DIR) ? join24(env.XDG_RUNTIME_DIR, "switcher", name) : undefined;
15456
+ const socket = Buffer.byteLength(preferred) <= SOCKET_PATH_LIMIT ? preferred : runtime && Buffer.byteLength(runtime) <= SOCKET_PATH_LIMIT ? runtime : join24("/tmp", `switcher-${process.getuid?.() ?? 0}`, name);
15457
+ return { root, socket, launches: join24(root, "launches"), ended: join24(root, "ended"), config: join24(root, "config.json"), log: join24(root, "service.log") };
14991
15458
  }
14992
15459
  var UNTRUSTED_FIX = "Another account may have created it: remove it (or set HASNA_SWITCHER_HOME to a shorter path) and launch again.";
14993
15460
  async function assertPrivateSocketDirectory(directory) {
@@ -14998,7 +15465,7 @@ async function assertPrivateSocketDirectory(directory) {
14998
15465
  async function assertTrustedControlSocket(socket) {
14999
15466
  const missing = () => new Fault(503, "gateway_unavailable", "The Switcher gateway service is not running. Run `switcher gateway status`.");
15000
15467
  try {
15001
- await assertPrivateSocketDirectory(dirname9(socket));
15468
+ await assertPrivateSocketDirectory(dirname10(socket));
15002
15469
  } catch (error) {
15003
15470
  if (error.code === "ENOENT")
15004
15471
  throw missing();
@@ -15034,7 +15501,7 @@ function accountHome() {
15034
15501
  const fields = result.exitCode === 0 ? result.stdout.toString().trim().split(`
15035
15502
  `)[0].split(":") : [];
15036
15503
  const home = fields[process.platform === "darwin" ? 8 : 5];
15037
- if (home && isAbsolute17(home))
15504
+ if (home && isAbsolute18(home))
15038
15505
  passwdHome = resolve13(home);
15039
15506
  } catch {}
15040
15507
  return passwdHome ?? undefined;
@@ -15063,7 +15530,7 @@ function gatewaySettings(env = process.env) {
15063
15530
  };
15064
15531
  }
15065
15532
  async function socketDirectory(paths) {
15066
- const directory = dirname9(paths.socket);
15533
+ const directory = dirname10(paths.socket);
15067
15534
  if (directory === paths.root)
15068
15535
  return;
15069
15536
  await mkdir12(directory, { mode: 448, recursive: true });
@@ -15125,8 +15592,8 @@ var gatewaySchema = z10.object({
15125
15592
  models: z10.array(modelSchema.strip()).min(1).max(20000),
15126
15593
  compiledPolicy: z10.unknown(),
15127
15594
  providerId: z10.string().max(200).optional(),
15128
- catalogPath: z10.string().max(4096).refine(isAbsolute17, "Use an absolute catalog path."),
15129
- cwd: z10.string().max(4096).refine(isAbsolute17, "Use an absolute working directory.")
15595
+ catalogPath: z10.string().max(4096).refine(isAbsolute18, "Use an absolute catalog path."),
15596
+ cwd: z10.string().max(4096).refine(isAbsolute18, "Use an absolute working directory.")
15130
15597
  }).strict();
15131
15598
  var credentialEnvSchema = z10.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
15132
15599
  var routeSchema = z10.object({ settingsDir: z10.string().max(4096) }).strict();
@@ -15161,13 +15628,24 @@ var endedSchema = staticSchema.omit({ stateDir: true }).extend({ endedAt: z10.nu
15161
15628
  var MAX_FAILED_PORTS = 64;
15162
15629
  var MAX_LOOKUPS_PER_RETRY = 4;
15163
15630
  var processKey = (entry) => `${entry.pid}@${entry.start}`;
15631
+ var REFUSAL_LINES_PER_MINUTE = 30;
15632
+ function refusalClass(event) {
15633
+ if (event.decision === "reject")
15634
+ return event.reason ?? "rejected";
15635
+ if (event.upstreamStatus !== undefined && event.upstreamStatus >= 400)
15636
+ return event.reason ?? `upstream_http_${event.upstreamStatus}`;
15637
+ if (event.reason === "network_error" || event.reason === "provider_idle_timeout")
15638
+ return event.reason;
15639
+ return;
15640
+ }
15641
+ var logToken = (value) => value?.replace(/[^A-Za-z0-9._:/-]/g, "_").slice(0, 80) || "-";
15164
15642
  var SETTLED_MS = 120000;
15165
15643
  var SETTLED_SCAN_FACTOR = 5;
15166
- var staticFields = (record3) => {
15167
- const { lastUsedAt: _used, lastHolderAt: _holder, released: _released, holders: _holders, extendedAt: _extended, ...rest } = record3;
15644
+ var staticFields = (record4) => {
15645
+ const { lastUsedAt: _used, lastHolderAt: _holder, released: _released, holders: _holders, extendedAt: _extended, ...rest } = record4;
15168
15646
  return rest;
15169
15647
  };
15170
- var holderFields = (record3) => ({ lastUsedAt: record3.lastUsedAt, lastHolderAt: record3.lastHolderAt, released: record3.released, holders: record3.holders, ...record3.extendedAt !== undefined ? { extendedAt: record3.extendedAt } : {} });
15648
+ var holderFields = (record4) => ({ lastUsedAt: record4.lastUsedAt, lastHolderAt: record4.lastHolderAt, released: record4.released, holders: record4.holders, ...record4.extendedAt !== undefined ? { extendedAt: record4.extendedAt } : {} });
15171
15649
  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
15650
  var loopbackHosts = (port) => new Set([`127.0.0.1:${port}`, `localhost:${port}`, `[::1]:${port}`]);
15173
15651
  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 });
@@ -15182,7 +15660,7 @@ async function liveGateway(socket) {
15182
15660
  }
15183
15661
  }
15184
15662
  async function readPrivateJson(path) {
15185
- const file = await open8(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
15663
+ const file = await open10(path, constants11.O_RDONLY | constants11.O_NOFOLLOW | constants11.O_NONBLOCK);
15186
15664
  try {
15187
15665
  const info2 = await file.stat();
15188
15666
  if (!info2.isFile() || info2.size > 128 * 1024 * 1024 || (info2.mode & 63) !== 0 || info2.uid !== process.getuid?.())
@@ -15193,17 +15671,17 @@ async function readPrivateJson(path) {
15193
15671
  }
15194
15672
  }
15195
15673
  async function readRecord(directory, id2) {
15196
- const fixed = staticSchema.parse(await readPrivateJson(join22(directory, `${id2}.json`)));
15674
+ const fixed = staticSchema.parse(await readPrivateJson(join24(directory, `${id2}.json`)));
15197
15675
  if (fixed.id !== id2)
15198
15676
  throw new Error("launch record id mismatch");
15199
- const state = await readPrivateJson(join22(directory, `${id2}.holders.json`)).then((value) => holderStateSchema.parse(value), () => {
15677
+ const state = await readPrivateJson(join24(directory, `${id2}.holders.json`)).then((value) => holderStateSchema.parse(value), () => {
15200
15678
  return;
15201
15679
  });
15202
15680
  return { ...fixed, ...state ?? { lastUsedAt: fixed.createdAt, lastHolderAt: fixed.createdAt, released: false, holders: [] } };
15203
15681
  }
15204
15682
  async function writePrivate(path, text) {
15205
- const temporary = `${path}.${randomUUID7()}.tmp`;
15206
- const file = await open8(temporary, "wx", 384);
15683
+ const temporary = `${path}.${randomUUID9()}.tmp`;
15684
+ const file = await open10(temporary, "wx", 384);
15207
15685
  try {
15208
15686
  try {
15209
15687
  await file.writeFile(text);
@@ -15211,17 +15689,17 @@ async function writePrivate(path, text) {
15211
15689
  } finally {
15212
15690
  await file.close();
15213
15691
  }
15214
- await rename5(temporary, path);
15692
+ await rename7(temporary, path);
15215
15693
  } catch (error) {
15216
- await rm5(temporary, { force: true }).catch(() => {
15694
+ await rm7(temporary, { force: true }).catch(() => {
15217
15695
  return;
15218
15696
  });
15219
15697
  throw error;
15220
15698
  }
15221
15699
  }
15222
15700
  async function routeSettingsDirectory(path) {
15223
- const profile = dirname9(path);
15224
- if (!isAbsolute17(path) || resolve13(path) !== path || basename5(path) !== "settings" || basename5(dirname9(profile)) !== "claude" || basename5(dirname9(dirname9(profile))) !== "sessions")
15701
+ const profile = dirname10(path);
15702
+ if (!isAbsolute18(path) || resolve13(path) !== path || basename6(path) !== "settings" || basename6(dirname10(profile)) !== "claude" || basename6(dirname10(dirname10(profile))) !== "sessions")
15225
15703
  throw new Fault(400, "invalid_route", "A durable route's settings folder must be an absolute <state>/sessions/claude/<profile>/settings directory.");
15226
15704
  const info2 = await lstat11(path).catch(() => {
15227
15705
  return;
@@ -15230,11 +15708,11 @@ async function routeSettingsDirectory(path) {
15230
15708
  throw new Fault(400, "invalid_route", "A durable route's settings folder must be a private directory owned by this user (mode 0700).");
15231
15709
  return path;
15232
15710
  }
15233
- var routeFile = (record3) => record3.route ? join22(record3.route.settingsDir, `claude-route-${record3.id}.json`) : undefined;
15711
+ var routeFile = (record4) => record4.route ? join24(record4.route.settingsDir, `claude-route-${record4.id}.json`) : undefined;
15234
15712
  async function launchStateDirectory(path) {
15235
15713
  if (path === undefined)
15236
15714
  return;
15237
- if (!isAbsolute17(path) || resolve13(path) !== path || !/^launch-[A-Za-z0-9]{6}$/.test(basename5(path)))
15715
+ if (!isAbsolute18(path) || resolve13(path) !== path || !/^launch-[A-Za-z0-9]{6}$/.test(basename6(path)))
15238
15716
  throw new Fault(400, "invalid_state_dir", "The launch state directory must be an absolute launch-XXXXXX directory.");
15239
15717
  const info2 = await lstat11(path).catch(() => {
15240
15718
  return;
@@ -15255,6 +15733,7 @@ async function startGatewayService(options = {}) {
15255
15733
  const environmentProbe = options.environmentProbe ?? processesHoldingTokenDigest;
15256
15734
  const connectionPeers = options.connectionPeers ?? loopbackPeers;
15257
15735
  const log = options.log ?? ((line) => console.error(`switcher-gateway ${new Date().toISOString()} ${line}`));
15736
+ const station = logToken(hostname().split(".")[0]);
15258
15737
  const resolver = new CredentialResolver(env);
15259
15738
  const resolveCredential2 = options.resolveCredential ?? ((provider) => resolver.resolve(provider));
15260
15739
  const bindings = new CredentialBindings(env);
@@ -15283,7 +15762,7 @@ async function startGatewayService(options = {}) {
15283
15762
  launch.persistedAt = now();
15284
15763
  if (!launches.has(launch.record.id))
15285
15764
  return;
15286
- await writePrivate(join22(paths.launches, `${launch.record.id}.holders.json`), JSON.stringify(holderFields(launch.record))).catch(() => {
15765
+ await writePrivate(join24(paths.launches, `${launch.record.id}.holders.json`), JSON.stringify(holderFields(launch.record))).catch(() => {
15287
15766
  launch.dirty = true;
15288
15767
  });
15289
15768
  };
@@ -15318,12 +15797,32 @@ async function startGatewayService(options = {}) {
15318
15797
  }
15319
15798
  })();
15320
15799
  };
15800
+ const logRefusal = (launch, event) => {
15801
+ const kind = refusalClass(event);
15802
+ if (!kind)
15803
+ return;
15804
+ const minute = Math.floor(now() / 60000);
15805
+ if (launch.refusalMinute !== minute) {
15806
+ launch.refusalMinute = minute;
15807
+ launch.refusalLines = 0;
15808
+ }
15809
+ if ((launch.refusalLines ?? 0) >= REFUSAL_LINES_PER_MINUTE) {
15810
+ launch.refusalSuppressed = (launch.refusalSuppressed ?? 0) + 1;
15811
+ return;
15812
+ }
15813
+ launch.refusalLines = (launch.refusalLines ?? 0) + 1;
15814
+ const suppressed = launch.refusalSuppressed ? ` suppressed=${launch.refusalSuppressed}` : "";
15815
+ launch.refusalSuppressed = 0;
15816
+ log(`refusal launch ${launch.record.id.slice(0, 8)} station=${station} harness=${logToken(launch.record.gateway.harness)} model=${logToken(event.requestedModel)} decision=${event.decision} status=${event.upstreamStatus ?? "-"} class=${logToken(kind)}${suppressed}`);
15817
+ };
15321
15818
  const handlerFor = (launch) => createInferenceHandler({
15322
15819
  ...launch.record.gateway,
15323
15820
  compiledPolicy: compiledPolicy(launch.record.gateway.compiledPolicy),
15324
15821
  stateDir: launch.record.stateDir ?? paths.root,
15325
15822
  credential: undefined,
15823
+ ...launch.record.route ? { sessionDir: dirname10(launch.record.route.settingsDir) } : {},
15326
15824
  onRoutingEvent: (event) => {
15825
+ logRefusal(launch, event);
15327
15826
  if (launch.record.released)
15328
15827
  return;
15329
15828
  const bytes = Buffer.byteLength(JSON.stringify(event));
@@ -15333,24 +15832,24 @@ async function startGatewayService(options = {}) {
15333
15832
  } else
15334
15833
  launch.eventsDropped = Math.min(1e6, launch.eventsDropped + 1);
15335
15834
  }
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() };
15835
+ }, options.timing, { credential: () => credentialFor(launch)(), log: (line) => log(`launch ${launch.record.id.slice(0, 8)} ${line}`) });
15836
+ const adopt = (record4, credential) => {
15837
+ const launch = { record: record4, credential, events: [], eventBytes: 0, eventsDropped: 0, dirty: false, persistedAt: 0, usedPersistedAt: 0, recentAt: now() };
15339
15838
  launch.handler = handlerFor(launch);
15340
- launches.set(record3.id, launch);
15341
- byDigest.set(record3.tokenDigest, launch);
15839
+ launches.set(record4.id, launch);
15840
+ byDigest.set(record4.tokenDigest, launch);
15342
15841
  return launch;
15343
15842
  };
15344
- const endedPath = (id2) => join22(paths.ended, `${id2}.json`);
15843
+ const endedPath = (id2) => join24(paths.ended, `${id2}.json`);
15345
15844
  const forgetEnded = async (entry) => {
15346
15845
  if (ended.get(entry.record.tokenDigest) === entry)
15347
15846
  ended.delete(entry.record.tokenDigest);
15348
- await rm5(endedPath(entry.record.id), { force: true }).catch(() => {
15847
+ await rm7(endedPath(entry.record.id), { force: true }).catch(() => {
15349
15848
  return;
15350
15849
  });
15351
15850
  };
15352
- const retireRoute = async (record3) => {
15353
- const file = routeFile(record3);
15851
+ const retireRoute = async (record4) => {
15852
+ const file = routeFile(record4);
15354
15853
  if (!file)
15355
15854
  return;
15356
15855
  const info2 = await lstat11(file).catch(() => {
@@ -15361,12 +15860,12 @@ async function startGatewayService(options = {}) {
15361
15860
  `).catch(() => {
15362
15861
  return;
15363
15862
  });
15364
- await releaseAdoptedRoutes(record3);
15863
+ await releaseAdoptedRoutes(record4);
15365
15864
  };
15366
- const releaseAdoptedRoutes = async (record3) => {
15367
- if (!record3.route)
15865
+ const releaseAdoptedRoutes = async (record4) => {
15866
+ if (!record4.route)
15368
15867
  return;
15369
- const dir = record3.route.settingsDir;
15868
+ const dir = record4.route.settingsDir;
15370
15869
  const tokenOf = (value) => {
15371
15870
  if (!value || typeof value !== "object" || Array.isArray(value))
15372
15871
  return;
@@ -15377,9 +15876,9 @@ async function startGatewayService(options = {}) {
15377
15876
  const token = [keys.ANTHROPIC_AUTH_TOKEN, keys.ANTHROPIC_API_KEY].find((item2) => typeof item2 === "string" && item2 !== "");
15378
15877
  return typeof token === "string" ? token : undefined;
15379
15878
  };
15380
- for (const name of await readdir7(dir).catch(() => [])) {
15879
+ for (const name of await readdir8(dir).catch(() => [])) {
15381
15880
  if (/^claude-settings-[0-9a-f]{32}\.json\.[0-9a-f-]{36}\.tmp$/.test(name)) {
15382
- const path2 = join22(dir, name);
15881
+ const path2 = join24(dir, name);
15383
15882
  try {
15384
15883
  const info2 = await lstat11(path2);
15385
15884
  if (!info2.isFile() || info2.uid !== process.getuid?.() || info2.size > 1024 * 1024)
@@ -15395,16 +15894,16 @@ async function startGatewayService(options = {}) {
15395
15894
  continue;
15396
15895
  } else {
15397
15896
  const token = tokenOf(value);
15398
- if (token === undefined || sha256(token) !== record3.tokenDigest)
15897
+ if (token === undefined || sha256(token) !== record4.tokenDigest)
15399
15898
  continue;
15400
15899
  }
15401
- await rm5(path2, { force: true });
15900
+ await rm7(path2, { force: true });
15402
15901
  } catch {}
15403
15902
  continue;
15404
15903
  }
15405
15904
  if (!/^claude-settings-[0-9a-f]{32}\.json$/.test(name))
15406
15905
  continue;
15407
- const path = join22(dir, name);
15906
+ const path = join24(dir, name);
15408
15907
  try {
15409
15908
  const info2 = await lstat11(path);
15410
15909
  if (!info2.isFile() || info2.nlink !== 1)
@@ -15414,7 +15913,7 @@ async function startGatewayService(options = {}) {
15414
15913
  continue;
15415
15914
  const { env: _env, ...picker } = value;
15416
15915
  const token = tokenOf(value);
15417
- if (token === undefined || sha256(token) !== record3.tokenDigest)
15916
+ if (token === undefined || sha256(token) !== record4.tokenDigest)
15418
15917
  continue;
15419
15918
  await writePrivate(path, JSON.stringify(picker, null, 2) + `
15420
15919
  `);
@@ -15461,15 +15960,15 @@ async function startGatewayService(options = {}) {
15461
15960
  await writePrivate(endedPath(launch.record.id), JSON.stringify(entry.record)).catch(() => {
15462
15961
  return;
15463
15962
  });
15464
- await rm5(join22(paths.launches, `${launch.record.id}.holders.json`), { force: true }).catch(() => {
15963
+ await rm7(join24(paths.launches, `${launch.record.id}.holders.json`), { force: true }).catch(() => {
15465
15964
  return;
15466
15965
  });
15467
- await rm5(join22(paths.launches, `${launch.record.id}.json`), { force: true }).catch(() => {
15966
+ await rm7(join24(paths.launches, `${launch.record.id}.json`), { force: true }).catch(() => {
15468
15967
  return;
15469
15968
  });
15470
15969
  const route2 = end ? undefined : routeFile(launch.record);
15471
15970
  if (route2) {
15472
- await rm5(route2, { force: true }).catch(() => {
15971
+ await rm7(route2, { force: true }).catch(() => {
15473
15972
  return;
15474
15973
  });
15475
15974
  await releaseAdoptedRoutes(launch.record);
@@ -15479,7 +15978,7 @@ async function startGatewayService(options = {}) {
15479
15978
  return;
15480
15979
  });
15481
15980
  if (directory)
15482
- await rm5(directory, { recursive: true, force: true }).catch(() => {
15981
+ await rm7(directory, { recursive: true, force: true }).catch(() => {
15483
15982
  return;
15484
15983
  });
15485
15984
  }
@@ -15582,14 +16081,14 @@ async function startGatewayService(options = {}) {
15582
16081
  if (!holders.length)
15583
16082
  return fail();
15584
16083
  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);
16084
+ const record4 = { ...fixed, ...durable ? { routeRevived: true } : {}, lastUsedAt: at, lastHolderAt: at, released: true, holders };
16085
+ await writePrivate(join24(paths.launches, `${record4.id}.json`), JSON.stringify(staticFields(record4)));
16086
+ const launch = adopt(record4, entry.credential);
15588
16087
  launch.probedAfterLauncher = true;
15589
16088
  track(launch, table, at);
15590
16089
  await persist(launch, true);
15591
16090
  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"}`);
16091
+ 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
16092
  return launch;
15594
16093
  } catch {
15595
16094
  return fail();
@@ -15713,9 +16212,9 @@ async function startGatewayService(options = {}) {
15713
16212
  }
15714
16213
  }
15715
16214
  const token = randomBytes2(32).toString("base64url"), at = now();
15716
- const record3 = {
16215
+ const record4 = {
15717
16216
  schema: 1,
15718
- id: randomUUID7(),
16217
+ id: randomUUID9(),
15719
16218
  tokenDigest: sha256(token),
15720
16219
  createdAt: at,
15721
16220
  lastUsedAt: at,
@@ -15728,12 +16227,12 @@ async function startGatewayService(options = {}) {
15728
16227
  ...stateDir ? { stateDir } : {},
15729
16228
  ...route2 ? { route: route2 } : {}
15730
16229
  };
15731
- const launch = adopt(record3, input.credential);
16230
+ const launch = adopt(record4, input.credential);
15732
16231
  launch.baseline = new Set([...table.values()].map(processKey));
15733
- await writePrivate(join22(paths.launches, `${record3.id}.json`), JSON.stringify(staticFields(record3)));
16232
+ await writePrivate(join24(paths.launches, `${record4.id}.json`), JSON.stringify(staticFields(record4)));
15734
16233
  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 } : {} };
16234
+ log(`launch ${record4.id.slice(0, 8)} registered (${record4.gateway.harness}, ${record4.gateway.model})`);
16235
+ return { id: record4.id, token, baseUrl: `${url}/${record4.gateway.protocol === "gemini-generate-content" ? "v1beta" : "v1"}`, ...route2 ? { releasesAdoptedRoutes: true } : {} };
15737
16236
  };
15738
16237
  const release = async (launch) => {
15739
16238
  const table = await processTable().catch(() => {
@@ -15764,7 +16263,7 @@ async function startGatewayService(options = {}) {
15764
16263
  if (method === "GET" && url2.pathname === "/v1/status")
15765
16264
  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
16265
  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 })) });
16266
+ 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
16267
  if (method === "POST" && url2.pathname === "/v1/launches")
15769
16268
  return Response.json(await register(registrationSchema.parse(await json(request))), { status: 201 });
15770
16269
  if (method === "POST" && url2.pathname === "/v1/stop") {
@@ -15803,35 +16302,35 @@ async function startGatewayService(options = {}) {
15803
16302
  const controlServer = Bun.serve({ unix: paths.socket, maxRequestBodySize: 256 * 1024 * 1024, fetch: control });
15804
16303
  await chmod3(paths.socket, 384);
15805
16304
  const restoredAt = now();
15806
- for (const name of await readdir7(paths.launches)) {
16305
+ for (const name of await readdir8(paths.launches)) {
15807
16306
  if (!/^[0-9a-f-]{36}\.json$/.test(name))
15808
16307
  continue;
15809
16308
  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;
16309
+ const record4 = await readRecord(paths.launches, name.slice(0, -5));
16310
+ const extend = record4.extendedAt === undefined || Math.max(record4.lastHolderAt, record4.lastUsedAt) > record4.extendedAt;
15812
16311
  if (extend) {
15813
- record3.lastHolderAt = Math.max(record3.lastHolderAt, restoredAt);
15814
- record3.extendedAt = restoredAt;
16312
+ record4.lastHolderAt = Math.max(record4.lastHolderAt, restoredAt);
16313
+ record4.extendedAt = restoredAt;
15815
16314
  }
15816
- const launch = adopt(record3);
16315
+ const launch = adopt(record4);
15817
16316
  if (extend)
15818
16317
  await persist(launch, true);
15819
16318
  } catch {
15820
16319
  log(`ignored unreadable launch record ${name.slice(0, 8)}`);
15821
16320
  }
15822
16321
  }
15823
- for (const name of await readdir7(paths.ended)) {
16322
+ for (const name of await readdir8(paths.ended)) {
15824
16323
  if (!/^[0-9a-f-]{36}\.json$/.test(name))
15825
16324
  continue;
15826
16325
  try {
15827
- const record3 = endedSchema.parse(await readPrivateJson(join22(paths.ended, name)));
15828
- if (record3.id !== name.slice(0, -5))
16326
+ const record4 = endedSchema.parse(await readPrivateJson(join24(paths.ended, name)));
16327
+ if (record4.id !== name.slice(0, -5))
15829
16328
  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))
16329
+ const entry = { record: record4, failed: new Map, lookups: [] };
16330
+ if (launches.has(record4.id) || byDigest.has(record4.tokenDigest))
15832
16331
  await forgetEnded(entry);
15833
16332
  else
15834
- ended.set(record3.tokenDigest, entry);
16333
+ ended.set(record4.tokenDigest, entry);
15835
16334
  } catch {
15836
16335
  log(`ignored unreadable ended launch record ${name.slice(0, 8)}`);
15837
16336
  }
@@ -15871,9 +16370,9 @@ async function startGatewayService(options = {}) {
15871
16370
  }
15872
16371
 
15873
16372
  // src/gateway-supervisor.ts
15874
- import { randomUUID as randomUUID8 } from "crypto";
15875
- 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";
15876
- import { dirname as dirname10, isAbsolute as isAbsolute18, join as join23 } from "path";
16373
+ import { randomUUID as randomUUID10 } from "crypto";
16374
+ import { lstat as lstat12, mkdir as mkdir13, open as open11, readFile as readFile9, realpath as realpath7, rename as rename8, unlink as unlink4 } from "fs/promises";
16375
+ import { dirname as dirname11, isAbsolute as isAbsolute19, join as join25 } from "path";
15877
16376
  var LAUNCHD_LABEL = "com.hasna.switcher.gateway";
15878
16377
  var SYSTEMD_UNIT = "switcher-gateway.service";
15879
16378
  var SERVICE_ENV = /^(HOME|USER|LOGNAME|PATH|LANG|LC_ALL|TMPDIR|XDG_RUNTIME_DIR|XDG_CONFIG_HOME|XDG_STATE_HOME|HASNA_HOME|HASNA_CONFIG_HOME|HASNA_SWITCHER_HOME|SWITCHER_GATEWAY_PORT|SWITCHER_GATEWAY_GRACE_SECONDS|SWITCHER_GATEWAY_SCAN_MS|SWITCHER_GATEWAY_EXIT_IDLE_SECONDS)$/;
@@ -15896,7 +16395,7 @@ async function assertSafeServiceCommand(command, temporaryRoots = TEMPORARY_ROOT
15896
16395
  for (const candidate of new Set([real, path])) {
15897
16396
  if (temporaryRoots.some((root) => candidate === root || candidate.startsWith(`${root}/`)))
15898
16397
  throw refuse(path, `${candidate} is under a temporary directory`);
15899
- for (let current = candidate;; current = dirname10(current)) {
16398
+ for (let current = candidate;; current = dirname11(current)) {
15900
16399
  const info2 = await lstat12(current).catch(() => {
15901
16400
  throw refuse(path, `${current} could not be checked`);
15902
16401
  });
@@ -15906,7 +16405,7 @@ async function assertSafeServiceCommand(command, temporaryRoots = TEMPORARY_ROOT
15906
16405
  if ((info2.mode & 18) !== 0)
15907
16406
  throw refuse(path, `${current} is writable by other accounts`);
15908
16407
  }
15909
- if (current === dirname10(current))
16408
+ if (current === dirname11(current))
15910
16409
  break;
15911
16410
  }
15912
16411
  }
@@ -15921,7 +16420,7 @@ function supervisorFor(env = process.env, platform = process.platform, home = ac
15921
16420
  return platform === "darwin" ? "launchd" : platform === "linux" ? "systemd" : "none";
15922
16421
  }
15923
16422
  function launchdLogPath(home) {
15924
- return join23(home, "Library", "Logs", "Hasna", "switcher-gateway.log");
16423
+ return join25(home, "Library", "Logs", "Hasna", "switcher-gateway.log");
15925
16424
  }
15926
16425
  function requireHome(home) {
15927
16426
  if (!home)
@@ -15930,12 +16429,12 @@ function requireHome(home) {
15930
16429
  }
15931
16430
  function unitPath(supervisor, env = process.env, home = requireHome(accountHome())) {
15932
16431
  if (supervisor === "launchd")
15933
- return join23(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
15934
- const config = env.XDG_CONFIG_HOME && isAbsolute18(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join23(home, ".config");
15935
- return join23(config, "systemd", "user", SYSTEMD_UNIT);
16432
+ return join25(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
16433
+ const config = env.XDG_CONFIG_HOME && isAbsolute19(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join25(home, ".config");
16434
+ return join25(config, "systemd", "user", SYSTEMD_UNIT);
15936
16435
  }
15937
16436
  function checkCommand(command) {
15938
- if (command.length < 2 || !command.every((part) => isAbsolute18(part) && !/[\x00-\x1f\x7f"\\%$`]/.test(part)))
16437
+ if (command.length < 2 || !command.every((part) => isAbsolute19(part) && !/[\x00-\x1f\x7f"\\%$`]/.test(part)))
15939
16438
  throw new Fault(400, "invalid_gateway_command", "The gateway service command must be absolute paths without quotes, backslashes, $, % or control characters.");
15940
16439
  }
15941
16440
  var xml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
@@ -16020,16 +16519,16 @@ async function writeUnit(path, content) {
16020
16519
  });
16021
16520
  if (previous === content)
16022
16521
  return false;
16023
- await mkdir13(dirname10(path), { recursive: true, mode: 493 });
16024
- const temporary = `${path}.${randomUUID8()}.tmp`;
16025
- const file = await open9(temporary, "wx", 420);
16522
+ await mkdir13(dirname11(path), { recursive: true, mode: 493 });
16523
+ const temporary = `${path}.${randomUUID10()}.tmp`;
16524
+ const file = await open11(temporary, "wx", 420);
16026
16525
  try {
16027
16526
  await file.writeFile(content);
16028
16527
  await file.sync();
16029
16528
  } finally {
16030
16529
  await file.close();
16031
16530
  }
16032
- await rename6(temporary, path);
16531
+ await rename8(temporary, path);
16033
16532
  return true;
16034
16533
  }
16035
16534
  async function installGatewayService(options) {
@@ -16222,7 +16721,7 @@ function createServiceGatewayHost(client, context) {
16222
16721
  catalogPath: input.catalogPath,
16223
16722
  cwd: input.cwd
16224
16723
  };
16225
- const route2 = input.harness === "claude" && input.sessionDir ? { settingsDir: join24(input.sessionDir, "settings") } : undefined;
16724
+ const route2 = input.harness === "claude" && input.sessionDir ? { settingsDir: join26(input.sessionDir, "settings") } : undefined;
16226
16725
  if (route2)
16227
16726
  await privateDirectory(route2.settingsDir);
16228
16727
  const body2 = {
@@ -16244,10 +16743,18 @@ function createServiceGatewayHost(client, context) {
16244
16743
  durable = false;
16245
16744
  }
16246
16745
  } catch (error) {
16247
- (context.warn ?? console.error)(`switcher: The persistent gateway refused this launch (${error instanceof Fault ? error.code : "unavailable"}); it uses a per-launch gateway that stops when this command exits.`);
16248
- return createInferenceGateway(input);
16746
+ const reason = `The persistent gateway refused this launch (${error instanceof Fault ? error.code : "unavailable"})`;
16747
+ if (context.requireDurableRoute)
16748
+ throw new Fault(503, "gateway_route_unavailable", `${reason}, and this command needs its durable route. Check \`switcher gateway status\` and run \`switcher gateway install\`.`);
16749
+ return openPerLaunchGateway(input, { reason, stateDir: context.stateDir, warn: context.warn });
16750
+ }
16751
+ const routeSettingsFile = durable && route2 ? join26(route2.settingsDir, `claude-route-${registration.id}.json`) : undefined;
16752
+ if (context.requireDurableRoute && !routeSettingsFile) {
16753
+ await client.revoke(registration.id).catch(() => {
16754
+ return;
16755
+ });
16756
+ throw new Fault(503, "gateway_route_unavailable", "The persistent gateway gave this launch no durable Claude route (it is older than this switcher, or the launch is not a Claude CLI launch). Run `switcher gateway install` to restart it on this version.");
16249
16757
  }
16250
- const routeSettingsFile = durable && route2 ? join24(route2.settingsDir, `claude-route-${registration.id}.json`) : undefined;
16251
16758
  const adoptRoutes = routeSettingsFile !== undefined && registration.releasesAdoptedRoutes === true;
16252
16759
  if (routeSettingsFile && !adoptRoutes)
16253
16760
  (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.");
@@ -16267,7 +16774,7 @@ function createServiceGatewayHost(client, context) {
16267
16774
  return;
16268
16775
  });
16269
16776
  if (routeSettingsFile)
16270
- await rm6(routeSettingsFile, { force: true }).catch(() => {
16777
+ await rm8(routeSettingsFile, { force: true }).catch(() => {
16271
16778
  return;
16272
16779
  });
16273
16780
  return;
@@ -16298,7 +16805,7 @@ function createServiceGatewayHost(client, context) {
16298
16805
  // src/launcher.ts
16299
16806
  var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
16300
16807
  async function writeOriCodexCatalog(stateDir, models) {
16301
- const path = join25(stateDir, "ori-codex-models.json");
16808
+ const path = join27(stateDir, "ori-codex-models.json");
16302
16809
  const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
16303
16810
  await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
16304
16811
  `, { mode: 384, flag: "wx" });
@@ -16392,7 +16899,7 @@ async function prepareOriForPlan(plan, options) {
16392
16899
  });
16393
16900
  try {
16394
16901
  const shim = prepareOriModelPolicy(request.target, native);
16395
- const dir = join25(options.stateDir, "ori-bin"), path = join25(dir, shim.name);
16902
+ const dir = join27(options.stateDir, "ori-bin"), path = join27(dir, shim.name);
16396
16903
  await mkdir14(dir, { mode: 448 });
16397
16904
  await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
16398
16905
  return { contract, prepared: {
@@ -16412,12 +16919,12 @@ async function sharedNativeHome(state, root, profileId, environment = process.en
16412
16919
  const variable = state.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
16413
16920
  const configured = environment[variable] ? resolve14(environment[variable]) : undefined;
16414
16921
  const configuredCorpus = configured !== undefined && await realpath8(configured).catch(() => configured) === state.home;
16415
- const home = state.tool === "claude" && (!configured || configured === state.home || configuredCorpus) ? join25(root, "native-claude", profileId) : configured ?? state.home;
16922
+ const home = state.tool === "claude" && (!configured || configured === state.home || configuredCorpus) ? join27(root, "native-claude", profileId) : configured ?? state.home;
16416
16923
  return { home, settingsEnvironment: configuredCorpus ? { ...environment, CLAUDE_CONFIG_DIR: undefined } : environment };
16417
16924
  }
16418
16925
  var SESSION_DIRECTORY_HARNESSES = ["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie", "claude"];
16419
16926
  function launchSessionDirectory(root, harness, profileId) {
16420
- return join25(root, "sessions", harness, profileId);
16927
+ return join27(root, "sessions", harness, profileId);
16421
16928
  }
16422
16929
  async function checkSharedNativeLaunch(state, root, profileId, options = {}) {
16423
16930
  const warnings = await legacyNativeStateWarnings(root, state);
@@ -16439,11 +16946,11 @@ async function checkSharedNativeLaunch(state, root, profileId, options = {}) {
16439
16946
  }
16440
16947
  function isolatedNativeHome(tool, root, profileId, options = {}, environment = process.env) {
16441
16948
  if (options.desktop)
16442
- return { home: join25(root, "desktop", profileId, "codex"), private: false };
16949
+ return { home: join27(root, "desktop", profileId, "codex"), private: false };
16443
16950
  if (options.claudeDesktop)
16444
- return { home: join25(root, "desktop-claude", profileId), private: false };
16951
+ return { home: join27(root, "desktop-claude", profileId), private: false };
16445
16952
  const configured = environment[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
16446
- return { home: configured ? resolve14(configured) : join25(root, `native-${tool}`, profileId), private: true };
16953
+ return { home: configured ? resolve14(configured) : join27(root, `native-${tool}`, profileId), private: true };
16447
16954
  }
16448
16955
  async function checkDirectLaunch(root, profileId, harness, options = {}) {
16449
16956
  const desktop = Boolean(options.desktop || options.claudeDesktop);
@@ -16490,6 +16997,8 @@ async function launch(client, profileId, options = {}) {
16490
16997
  throw new Error("--ori-executable requires --backend ori.");
16491
16998
  if (options.desktop && (plan.profile.harness !== "codex" || backend !== "direct"))
16492
16999
  throw new Error("ChatGPT requires the direct Codex provider adapter.");
17000
+ if (options.requireDurableRoute && (options.gateway !== "service" || backend !== "direct" || options.claudeDesktop || options.desktop || plan.profile.harness !== "claude" || process.platform === "win32"))
17001
+ throw new Fault(503, "gateway_route_unavailable", "This command needs a durable route on the persistent gateway, which only a direct Claude CLI launch with SWITCHER_GATEWAY=service (the default) on macOS or Linux gets.");
16493
17002
  if (options.claudeDesktop && (options.desktop || plan.profile.harness !== "claude" || backend !== "direct" || options.executable || options.args?.length))
16494
17003
  throw new Error("Claude desktop requires its direct Messages gateway adapter without native CLI overrides.");
16495
17004
  const nativeExecutable = options.desktop?.codexExecutable ?? options.executable;
@@ -16500,9 +17009,9 @@ async function launch(client, profileId, options = {}) {
16500
17009
  validateHarnessVersion("gemini", detection?.version);
16501
17010
  if (backend === "direct" && plan.profile.harness === "aider")
16502
17011
  validateHarnessVersion(plan.profile.harness, detection?.version);
16503
- const root = resolve14(options.stateDir ?? join25(switcherHome(), "state"));
17012
+ const root = resolve14(options.stateDir ?? join27(switcherHome(), "state"));
16504
17013
  await privateDirectory(root);
16505
- const stateDir = await mkdtemp(join25(root, "launch-"));
17014
+ const stateDir = await mkdtemp(join27(root, "launch-"));
16506
17015
  let credential;
16507
17016
  if (backend === "direct") {
16508
17017
  try {
@@ -16510,7 +17019,7 @@ async function launch(client, profileId, options = {}) {
16510
17019
  if (plan.provider.credentialEnv && !credential)
16511
17020
  throw new Fault(400, "credential_setup_required", `Provider credential setup is required. Run: ${providerCredentialSetupCommand(plan.provider)}. Or provide ${plan.provider.credentialEnv} in this launch process.`);
16512
17021
  } catch (error) {
16513
- await rm7(stateDir, { recursive: true, force: true });
17022
+ await rm9(stateDir, { recursive: true, force: true });
16514
17023
  throw error;
16515
17024
  }
16516
17025
  }
@@ -16533,13 +17042,21 @@ async function launch(client, profileId, options = {}) {
16533
17042
  routingEventsDropped = Math.min(1e6, routingEventsDropped + 1);
16534
17043
  };
16535
17044
  let gatewayHost;
17045
+ let fallbackHost;
16536
17046
  if (options.gateway === "service" && backend === "direct" && !options.claudeDesktop && process.platform !== "win32") {
17047
+ let client2;
16537
17048
  try {
16538
- const client2 = options.connectGateway ? await options.connectGateway() : (await ensureGatewayService({ command: options.gatewayCommand ?? [process.execPath, Bun.main], supervise: options.gatewaySupervise ?? false })).client;
16539
- gatewayHost = createServiceGatewayHost(client2, { holderPid: process.pid, stateDir, credentialEnv: credential ? plan.provider.credentialEnv : undefined, onRoutingEvent });
17049
+ client2 = options.connectGateway ? await options.connectGateway() : (await ensureGatewayService({ command: options.gatewayCommand ?? [process.execPath, Bun.main], supervise: options.gatewaySupervise ?? false })).client;
16540
17050
  } catch (error) {
16541
- console.error(`switcher: The persistent gateway is unavailable (${error instanceof Fault ? error.message : "it could not start"}); this launch uses a per-launch gateway that stops when this command exits.`);
17051
+ const reason = `The persistent gateway is unavailable (${error instanceof Fault ? error.message : "it could not start"})`;
17052
+ if (options.requireDurableRoute) {
17053
+ await rm9(stateDir, { recursive: true, force: true });
17054
+ throw new Fault(503, "gateway_route_unavailable", `${reason}, and this command needs its durable route. Check \`switcher gateway status\` and run \`switcher gateway install\`.`);
17055
+ }
17056
+ fallbackHost = perLaunchGatewayHost({ reason, stateDir });
16542
17057
  }
17058
+ if (client2)
17059
+ gatewayHost = createServiceGatewayHost(client2, { holderPid: process.pid, stateDir, credentialEnv: credential ? plan.provider.credentialEnv : undefined, onRoutingEvent, requireDurableRoute: options.requireDurableRoute });
16543
17060
  }
16544
17061
  const finishRunOnce = async (candidate, body2, message) => {
16545
17062
  if (runFinalized)
@@ -16601,7 +17118,7 @@ async function launch(client, profileId, options = {}) {
16601
17118
  cwd: resolve14(options.cwd ?? process.cwd()),
16602
17119
  sharedState
16603
17120
  };
16604
- let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join25(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
17121
+ let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join27(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
16605
17122
  harness: plan.profile.harness,
16606
17123
  baseUrl: plan.provider.baseUrl,
16607
17124
  protocol: plan.provider.protocol,
@@ -16620,7 +17137,7 @@ async function launch(client, profileId, options = {}) {
16620
17137
  cwd: resolve14(options.cwd ?? process.cwd()),
16621
17138
  version: detection?.version,
16622
17139
  sharedState,
16623
- gatewayHost,
17140
+ gatewayHost: gatewayHost ?? fallbackHost,
16624
17141
  ...SESSION_DIRECTORY_HARNESSES.includes(plan.profile.harness) ? { sessionDir: launchSessionDirectory(root, plan.profile.harness, profileId) } : {}
16625
17142
  });
16626
17143
  cleanup = prepared.cleanup;
@@ -16638,7 +17155,7 @@ async function launch(client, profileId, options = {}) {
16638
17155
  prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
16639
17156
  }
16640
17157
  if (options.desktop) {
16641
- prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join25(root, "desktop", desktopState), sharedState);
17158
+ prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join27(root, "desktop", desktopState), sharedState);
16642
17159
  cleanup = prepared.cleanup;
16643
17160
  }
16644
17161
  for (const warning of [...plan.warnings, ...prepared.warnings])
@@ -16715,7 +17232,13 @@ async function launch(client, profileId, options = {}) {
16715
17232
  interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
16716
17233
  throw preparationSignal;
16717
17234
  }
16718
- const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve14(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime, onSpawn: (pid) => gatewayHost?.attach(pid) });
17235
+ let code, interrupted = false;
17236
+ if (options.prepareOnly) {
17237
+ gatewayHost?.attach(process.pid);
17238
+ await options.prepareOnly({ executable: prepared.executable, args: prepared.args, env: prepared.env, cwd: resolve14(options.cwd ?? process.cwd()) });
17239
+ code = 0;
17240
+ } else
17241
+ ({ code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve14(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime, onSpawn: (pid) => gatewayHost?.attach(pid) }));
16719
17242
  await cleanup?.();
16720
17243
  cleanup = undefined;
16721
17244
  await finishRunOnce(run, { status: interrupted ? "interrupted" : code === 0 ? "exited" : "failed", exitCode: code }, `switcher: Harness exited ${code}; final metadata could not be saved for run ${run.id}.`);
@@ -16747,11 +17270,15 @@ async function launch(client, profileId, options = {}) {
16747
17270
  await cleanup?.();
16748
17271
  } finally {
16749
17272
  if (!gatewayHost?.retainedState())
16750
- await rm7(stateDir, { recursive: true, force: true });
17273
+ await rm9(stateDir, { recursive: true, force: true });
16751
17274
  }
16752
17275
  }
16753
17276
  }
16754
17277
 
17278
+ // src/cli.ts
17279
+ import { open as openFile, rename as rename9, rm as rm10 } from "fs/promises";
17280
+ import { randomUUID as randomUUID11 } from "crypto";
17281
+
16755
17282
  // src/direct-launch.ts
16756
17283
  import { createHash as createHash17 } from "crypto";
16757
17284
  import { createInterface as createInterface3 } from "readline/promises";
@@ -16859,9 +17386,9 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
16859
17386
 
16860
17387
  // src/native-state-import.ts
16861
17388
  import { createHash as createHash18 } from "crypto";
16862
- import { constants as constants11 } from "fs";
16863
- import { lstat as lstat14, open as open10, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
16864
- import { basename as basename6, dirname as dirname11, isAbsolute as isAbsolute19, join as join26, relative as relative8, resolve as resolve15 } from "path";
17389
+ import { constants as constants12 } from "fs";
17390
+ import { lstat as lstat14, open as open12, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
17391
+ import { basename as basename7, dirname as dirname12, isAbsolute as isAbsolute20, join as join28, relative as relative8, resolve as resolve15 } from "path";
16865
17392
  var MAX_FILES = 1e5;
16866
17393
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
16867
17394
  var refused = () => new Fault(409, "native_state_import_conflict", "Native state import found changed, unsafe or divergent data. No existing file will be replaced. Keep the original directory and resolve the conflict explicitly.");
@@ -16878,12 +17405,12 @@ var identity = (s) => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeM
16878
17405
  var same = (a, b) => JSON.stringify(identity(a)) === JSON.stringify(identity(b));
16879
17406
  var inside3 = (parent, child) => {
16880
17407
  const path = relative8(parent, child);
16881
- return path !== ".." && !path.startsWith("../") && !isAbsolute19(path);
17408
+ return path !== ".." && !path.startsWith("../") && !isAbsolute20(path);
16882
17409
  };
16883
17410
  var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
16884
17411
  async function sessionId(path, expected) {
16885
- const nameId = basename6(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
16886
- const handle = await open10(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
17412
+ const nameId = basename7(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
17413
+ const handle = await open12(path, constants12.O_RDONLY | constants12.O_NOFOLLOW);
16887
17414
  try {
16888
17415
  const before = await handle.stat();
16889
17416
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
@@ -16926,7 +17453,7 @@ async function checkSessionIdentities(plan) {
16926
17453
  for (const file of plan.files) {
16927
17454
  if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
16928
17455
  continue;
16929
- file.sessionId = await sessionId(join26(plan.source, file.path), file.source);
17456
+ file.sessionId = await sessionId(join28(plan.source, file.path), file.source);
16930
17457
  if (!file.sessionId)
16931
17458
  continue;
16932
17459
  const previous = ids.get(file.sessionId);
@@ -16950,7 +17477,7 @@ async function checkSessionIdentities(plan) {
16950
17477
  for await (const entry of await opendir2(directory)) {
16951
17478
  if (++seen > MAX_FILES || entry.isSymbolicLink())
16952
17479
  throw refused();
16953
- const path = join26(directory, entry.name);
17480
+ const path = join28(directory, entry.name);
16954
17481
  if (entry.isDirectory()) {
16955
17482
  await scan(path, depth + 1);
16956
17483
  continue;
@@ -16967,18 +17494,18 @@ async function checkSessionIdentities(plan) {
16967
17494
  file.existing = true;
16968
17495
  }
16969
17496
  }
16970
- await scan(join26(plan.state.home, "sessions"));
16971
- await scan(join26(plan.state.home, "archived_sessions"));
17497
+ await scan(join28(plan.state.home, "sessions"));
17498
+ await scan(join28(plan.state.home, "archived_sessions"));
16972
17499
  }
16973
17500
  async function fingerprint2(path, copyTo) {
16974
- const handle = await open10(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
17501
+ const handle = await open12(path, constants12.O_RDONLY | constants12.O_NOFOLLOW);
16975
17502
  let output, complete = false;
16976
17503
  try {
16977
17504
  const before = await handle.stat();
16978
17505
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
16979
17506
  throw refused();
16980
17507
  if (copyTo)
16981
- output = await open10(copyTo, "wx", 384);
17508
+ output = await open12(copyTo, "wx", 384);
16982
17509
  const hash3 = createHash18("sha256"), buffer = Buffer.alloc(64 * 1024);
16983
17510
  let bytes = 0;
16984
17511
  for (;; ) {
@@ -17012,7 +17539,7 @@ async function fingerprint2(path, copyTo) {
17012
17539
  }
17013
17540
  }
17014
17541
  async function planNativeStateImport(state, source, selection) {
17015
- if (!isAbsolute19(source) || source.includes("\x00"))
17542
+ if (!isAbsolute20(source) || source.includes("\x00"))
17016
17543
  throw refused();
17017
17544
  source = resolve15(source);
17018
17545
  if (inside3(source, state.home) || inside3(state.home, source))
@@ -17028,9 +17555,9 @@ async function planNativeStateImport(state, source, selection) {
17028
17555
  async function visit(path, kind) {
17029
17556
  if (++seen > MAX_FILES || path.split("/").length > 32)
17030
17557
  throw refused();
17031
- await ensureNativeStateDirectory(dirname11(join26(source, path)), false);
17032
- await ensureNativeStateDirectory(dirname11(join26(state.home, path)), false);
17033
- const from = join26(source, path), to = join26(state.home, path), entry = await info2(from), target = await info2(to);
17558
+ await ensureNativeStateDirectory(dirname12(join28(source, path)), false);
17559
+ await ensureNativeStateDirectory(dirname12(join28(state.home, path)), false);
17560
+ const from = join28(source, path), to = join28(state.home, path), entry = await info2(from), target = await info2(to);
17034
17561
  if (!entry)
17035
17562
  return;
17036
17563
  if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
@@ -17049,7 +17576,7 @@ async function planNativeStateImport(state, source, selection) {
17049
17576
  }
17050
17577
  children.sort((a, b) => a.name.localeCompare(b.name));
17051
17578
  for (const child of children)
17052
- await visit(join26(path, child.name), child.kind);
17579
+ await visit(join28(path, child.name), child.kind);
17053
17580
  } else {
17054
17581
  const value = await fingerprint2(from);
17055
17582
  plan.bytes += value.bytes;
@@ -17103,14 +17630,14 @@ async function applyNativeStateImportUnlocked(plan) {
17103
17630
  throw refused();
17104
17631
  const requiredDirectories = new Set([plan.state.home]);
17105
17632
  for (const path of plan.directories) {
17106
- for (let directory = join26(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname11(directory)) {
17633
+ for (let directory = join28(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname12(directory)) {
17107
17634
  requiredDirectories.add(directory);
17108
17635
  if (directory === plan.state.home)
17109
17636
  break;
17110
17637
  }
17111
17638
  }
17112
17639
  for (const file of plan.files.filter((file2) => !file2.existing)) {
17113
- for (let directory = dirname11(join26(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname11(directory)) {
17640
+ for (let directory = dirname12(join28(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname12(directory)) {
17114
17641
  requiredDirectories.add(directory);
17115
17642
  if (directory === plan.state.home)
17116
17643
  break;
@@ -17131,9 +17658,9 @@ async function applyNativeStateImportUnlocked(plan) {
17131
17658
  for (const file of plan.files) {
17132
17659
  if (file.existing)
17133
17660
  continue;
17134
- const target = join26(plan.state.home, file.path), temporary = join26(dirname11(target), `.switcher-import-${crypto.randomUUID()}`);
17661
+ const target = join28(plan.state.home, file.path), temporary = join28(dirname12(target), `.switcher-import-${crypto.randomUUID()}`);
17135
17662
  staged.push({ temporary, target });
17136
- const copied = await fingerprint2(join26(plan.source, file.path), temporary);
17663
+ const copied = await fingerprint2(join28(plan.source, file.path), temporary);
17137
17664
  if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
17138
17665
  throw refused();
17139
17666
  }
@@ -17216,6 +17743,9 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
17216
17743
  switcher launch PROFILE [--backend direct|ori] [--share-native-state | --no-share-native-state] [--cwd DIR] [--executable PATH]
17217
17744
  [--ori-executable PATH] [--state-dir DIR]
17218
17745
  [--timeout SECONDS] -- [native harness arguments]
17746
+ switcher resume CLAUDE_SESSION_ID [--check | --print | --dry-run] [--cwd DIR] [--state-dir DIR]
17747
+ [--executable PATH] [--share-native-state | --no-share-native-state]
17748
+ [--timeout SECONDS] -- [native Claude arguments]
17219
17749
  switcher runs list|get [ID]
17220
17750
  switcher credentials bind PRESET --vault-key KEY [--vault-url URL]
17221
17751
  [--vault-cli PATH] [--vault-account ACCOUNT | --vault-operator env]
@@ -17242,6 +17772,24 @@ so background processes the harness leaves running (such as Claude Code's daemon
17242
17772
  keep working after the launch exits. It runs under launchd (macOS) or systemd --user
17243
17773
  (Linux) for the default home and starts automatically. SWITCHER_GATEWAY=local uses
17244
17774
  the older per-launch gateway that stops with the launch.
17775
+ If the persistent gateway cannot be used, a launch falls back to a per-launch gateway: it
17776
+ warns on stderr with the reason and port and records it in STATE/per-launch-gateways/launch-XXXXXX.json
17777
+ (STATE is ~/.hasna/switcher/state or --state-dir). A session left running or resumed after
17778
+ that launch ends cannot reach the port.
17779
+ resume relaunches a Claude session Switcher launched on its own profile and route, as
17780
+ switcher launch PROFILE --cwd DIR -- --resume ID would, never as a plain claude --resume.
17781
+ The gateway records each Claude session it serves in
17782
+ STATE/sessions/claude/PROFILE/claude-sessions/SESSION_ID.json (the cwd and time inside);
17783
+ the newest record across profiles names the profile. --cwd overrides the recorded cwd.
17784
+ --check read-only: prints {"owned","profile","cwd","recordPath"} on one line.
17785
+ --print registers the lease, writes the --settings route file and an owner-only env
17786
+ file (STATE/resume/SESSION_ID.env, export NAME='value' lines), prints
17787
+ {"argv","cwd","envKeys","envFile","routeFile","lease"} and does not start Claude.
17788
+ The route is durable: the gateway serves it again on first use for 30 days.
17789
+ --dry-run prints the profile, cwd and argv without registering anything.
17790
+ Exit codes: 0 ok (otherwise the harness's own code once it runs), 2 usage,
17791
+ 3 no Switcher record owns the session, 4 profile missing or not a Claude profile,
17792
+ 5 route or lease unavailable (for example the persistent gateway is down), 1 other errors.
17245
17793
  --reasoning: none, minimal, low, medium, high, xhigh, max, ultra (provider support required).
17246
17794
  --dangerously-bypass-approvals-and-sandbox: full access without prompts or command sandboxing.
17247
17795
  PROTOCOL: anthropic-messages, openai-responses, openai-chat, gemini-generate-content
@@ -17309,7 +17857,7 @@ async function readModelPolicy(file, roleValues) {
17309
17857
  }
17310
17858
  return parse2(modelPolicySchema, { version: 1, roles: roles2 });
17311
17859
  }
17312
- async function main(args = process.argv.slice(2)) {
17860
+ async function main(args = process.argv.slice(2), internal = {}) {
17313
17861
  if (args.length === 1 && args[0] === "__credential-delivery")
17314
17862
  return deliverVaultCredential();
17315
17863
  const split = args.indexOf("--");
@@ -17367,7 +17915,9 @@ async function main(args = process.argv.slice(2)) {
17367
17915
  "keychain-service": { type: "string" },
17368
17916
  "keychain-account": { type: "string" },
17369
17917
  origin: { type: "string", multiple: true },
17370
- "exit-when-idle": { type: "boolean" }
17918
+ "exit-when-idle": { type: "boolean" },
17919
+ check: { type: "boolean" },
17920
+ print: { type: "boolean" }
17371
17921
  } });
17372
17922
  if (values2.help || !positionals.length) {
17373
17923
  console.log(HELP);
@@ -17375,6 +17925,10 @@ async function main(args = process.argv.slice(2)) {
17375
17925
  }
17376
17926
  const [command, action2, id2] = positionals;
17377
17927
  const output = (value) => console.log(JSON.stringify(value, null, 2));
17928
+ if (command === "resume")
17929
+ return resumeCommand(positionals, values2, nativeArgs);
17930
+ if (values2.check !== undefined || values2.print !== undefined)
17931
+ throw new Fault(400, "conflicting_options", "--check and --print belong to switcher resume.");
17378
17932
  if (command === "state") {
17379
17933
  if (action2 !== "import" || !["codex", "claude"].includes(id2) || !values2.from || positionals.length !== 3 || nativeArgs.length || Object.keys(values2).some((key) => !["from", "entry", "apply", "plan-digest", "dry-run", "json"].includes(key)) || values2.apply && values2["dry-run"] || Boolean(values2.apply) !== Boolean(values2["plan-digest"]) || values2["plan-digest"] !== undefined && !/^[a-f0-9]{64}$/.test(values2["plan-digest"]))
17380
17934
  throw new Fault(400, "invalid_request", "Use switcher state import codex|claude --from LEGACY_NATIVE_HOME [--entry NAME]... [--dry-run | --apply --plan-digest SHA256]. The default is a read-only dry run.");
@@ -17648,7 +18202,7 @@ async function main(args = process.argv.slice(2)) {
17648
18202
  const marked = process.env[`HASNA_${suffix}_STATE_HOME`] !== undefined || process.env[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
17649
18203
  if ((sharedNativeState || shareNativeState === false) && plan.profile.harness === "codex")
17650
18204
  assertHarnessArguments("codex", nativeArgs, { reservedCodexRoots: ["sqlite_home"] });
17651
- const root = resolve16(values2["state-dir"] ?? join27(switcherHome(), "state"));
18205
+ const root = resolve16(values2["state-dir"] ?? join29(switcherHome(), "state"));
17652
18206
  if (backend !== "direct")
17653
18207
  await checkPrivateDirectory(root);
17654
18208
  const nativeWarnings = backend === "direct" ? await checkDirectLaunch(root, profileId, plan.profile.harness, {
@@ -17673,7 +18227,7 @@ async function main(args = process.argv.slice(2)) {
17673
18227
  output({ ...plan, ...desktop ? { desktop: { ...desktop, mode: sharedNativeState ? "shared-state-private-auth" : "isolated-provider", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...claudeApp ? { desktop: { ...claudeApp, mode: "claude-3p-gateway", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...nativeState ? { nativeState } : {}, ...reasoning ? { reasoning } : {}, ...dangerouslyBypassApprovalsAndSandbox ? { permissions: { approvalPolicy: "never", sandboxMode: "danger-full-access" } } : {} });
17674
18228
  return;
17675
18229
  }
17676
- process.exitCode = await launch(client, profileId, { gateway: launchGatewayMode(), gatewayCommand: gatewayServiceCommand().command, gatewaySupervise: gatewayServiceCommand().linked, desktop, claudeDesktop: claudeApp, shareNativeState, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)) });
18230
+ process.exitCode = await launch(client, profileId, { gateway: launchGatewayMode(), gatewayCommand: gatewayServiceCommand().command, gatewaySupervise: gatewayServiceCommand().linked, desktop, claudeDesktop: claudeApp, shareNativeState, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)), ...internal.launchOptions });
17677
18231
  return;
17678
18232
  }
17679
18233
  if (editingModel) {
@@ -17783,6 +18337,142 @@ async function main(args = process.argv.slice(2)) {
17783
18337
  await runtime.close();
17784
18338
  }
17785
18339
  }
18340
+
18341
+ class ResumeFault extends Fault {
18342
+ exitCode;
18343
+ constructor(exitCode, status, code, message) {
18344
+ super(status, code, message);
18345
+ this.exitCode = exitCode;
18346
+ }
18347
+ }
18348
+ var RESUME_USAGE = "Use switcher resume CLAUDE_SESSION_ID [--check | --print | --dry-run] [--cwd DIR] [--state-dir DIR] [--executable PATH] [--share-native-state | --no-share-native-state] [--timeout SECONDS] [-- native Claude arguments].";
18349
+ var shellQuote = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
18350
+ async function writeEnvironmentFile(path, env) {
18351
+ const names = Object.keys(env).sort();
18352
+ if (names.some((name) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)))
18353
+ throw new Fault(500, "invalid_environment", "The launch environment has a variable name a shell cannot set.");
18354
+ await privateDirectory(join29(path, ".."));
18355
+ const temporary = `${path}.${randomUUID11()}.tmp`;
18356
+ const file = await openFile(temporary, "wx", 384);
18357
+ try {
18358
+ try {
18359
+ await file.writeFile(names.map((name) => `export ${name}=${shellQuote(env[name])}
18360
+ `).join(""));
18361
+ } finally {
18362
+ await file.close();
18363
+ }
18364
+ await rename9(temporary, path);
18365
+ } catch (error) {
18366
+ await rm10(temporary, { force: true }).catch(() => {
18367
+ return;
18368
+ });
18369
+ throw error;
18370
+ }
18371
+ }
18372
+ async function resumeCommand(positionals, values2, nativeArgs) {
18373
+ const usage2 = (message = RESUME_USAGE) => new ResumeFault(2, 400, "invalid_request", message);
18374
+ const allowed = ["check", "print", "dry-run", "cwd", "state-dir", "executable", "share-native-state", "no-share-native-state", "timeout", "json"];
18375
+ if (positionals.length !== 2 || Object.keys(values2).some((name) => !allowed.includes(name)))
18376
+ throw usage2();
18377
+ const sessionId2 = positionals[1];
18378
+ if (!isClaudeSessionId(sessionId2))
18379
+ throw usage2("A Claude session id is a UUID, as claude --resume takes it.");
18380
+ if (["check", "print", "dry-run"].filter((name) => values2[name]).length > 1)
18381
+ throw usage2("Use only one of --check, --print and --dry-run.");
18382
+ if (values2["share-native-state"] && values2["no-share-native-state"])
18383
+ throw usage2("Use only one of --share-native-state and --no-share-native-state.");
18384
+ if (values2.check && Object.keys(values2).some((name) => !["check", "state-dir", "json"].includes(name)) || values2.check && nativeArgs.length)
18385
+ throw usage2("--check takes only --state-dir.");
18386
+ if (values2.timeout !== undefined && (values2.print || values2["dry-run"]))
18387
+ throw usage2("--timeout applies only when switcher resume starts Claude itself.");
18388
+ const conflicting = nativeArgs.find((arg) => /^(--resume|--continue|--session-id)(=|$)/.test(arg) || arg === "-r" || arg === "-c");
18389
+ if (conflicting)
18390
+ throw usage2(`switcher resume passes --resume ${sessionId2} itself; remove ${conflicting.split("=")[0]} from the native arguments.`);
18391
+ const root = resolve16(values2["state-dir"] ?? join29(switcherHome(), "state"));
18392
+ const owner = await findClaudeSession(root, sessionId2);
18393
+ if (values2.check) {
18394
+ console.log(JSON.stringify({ owned: Boolean(owner), profile: owner?.profileId ?? null, cwd: owner?.cwd ?? null, recordPath: owner?.record ?? null }));
18395
+ process.exitCode = owner ? 0 : 3;
18396
+ return;
18397
+ }
18398
+ if (!owner)
18399
+ throw new ResumeFault(3, 404, "session_not_owned", `No Switcher launch recorded Claude session ${sessionId2} in ${root}. Switcher does not resume it without its launch's route: a plain \`claude --resume\` sends the session's stored model to Claude's default endpoint. If you know the profile it ran under, run \`switcher launch PROFILE --cwd DIR -- --resume ${sessionId2}\`.`);
18400
+ const cwd = resolve16(values2.cwd ?? owner.cwd);
18401
+ const native = ["--resume", sessionId2, ...nativeArgs];
18402
+ const launchArgs = [
18403
+ "launch",
18404
+ owner.profileId,
18405
+ "--cwd",
18406
+ cwd,
18407
+ ...values2["state-dir"] !== undefined ? ["--state-dir", root] : [],
18408
+ ...values2.executable !== undefined ? ["--executable", String(values2.executable)] : [],
18409
+ ...values2["share-native-state"] ? ["--share-native-state"] : [],
18410
+ ...values2["no-share-native-state"] ? ["--no-share-native-state"] : [],
18411
+ ...values2.timeout !== undefined ? ["--timeout", String(values2.timeout)] : [],
18412
+ "--",
18413
+ ...native
18414
+ ];
18415
+ const runtime = await openCliRuntime(Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("SWITCHER_PROVIDER_"))));
18416
+ let dryRun;
18417
+ try {
18418
+ let profile;
18419
+ try {
18420
+ profile = await runtime.client.getProfile(owner.profileId);
18421
+ } catch (error) {
18422
+ if (error instanceof SwitcherError && error.status === 404)
18423
+ throw new ResumeFault(4, 404, "profile_missing", `Claude session ${sessionId2} ran under profile ${owner.profileId}, which no longer exists. Recreate it, or run \`switcher launch PROFILE --cwd ${cwd} -- --resume ${sessionId2}\` with another Claude profile.`);
18424
+ throw error;
18425
+ }
18426
+ if (profile.harness !== "claude")
18427
+ throw new ResumeFault(4, 409, "profile_not_claude", `Profile ${owner.profileId} now launches ${profile.harness}, not Claude, so it cannot resume Claude session ${sessionId2}.`);
18428
+ if (values2["dry-run"]) {
18429
+ await launchCatalog(runtime.client, await runtime.client.getProvider(profile.providerId), true);
18430
+ const plan = await runtime.client.launchPlan(owner.profileId);
18431
+ const model3 = claudeNativeModelId(plan.profile.model, plan.catalog.models);
18432
+ dryRun = {
18433
+ sessionId: sessionId2,
18434
+ profile: owner.profileId,
18435
+ provider: plan.provider.id,
18436
+ model: plan.profile.model,
18437
+ cwd,
18438
+ recordPath: owner.record,
18439
+ observedAt: owner.observedAt,
18440
+ exec: ["switcher", ...launchArgs],
18441
+ argv: [values2.executable ?? "claude", "--settings", join29(owner.sessionDir, "settings", "claude-route-<launch id>.json"), "--model", model3, ...native]
18442
+ };
18443
+ }
18444
+ } finally {
18445
+ await runtime.close();
18446
+ }
18447
+ if (dryRun) {
18448
+ console.log(JSON.stringify(dryRun, null, 2));
18449
+ return;
18450
+ }
18451
+ if (!values2.print)
18452
+ return main(launchArgs);
18453
+ const prepareOnly = async (prepared) => {
18454
+ const routeFile2 = prepared.args[prepared.args.indexOf("--settings") + 1];
18455
+ if (prepared.args.indexOf("--settings") < 0 || !/claude-route-[0-9a-f-]{36}\.json$/.test(routeFile2 ?? ""))
18456
+ throw new ResumeFault(5, 503, "gateway_route_unavailable", "The launch got no durable Claude route file, so a Claude started after this command could not reach its gateway.");
18457
+ const envFile = join29(root, "resume", `${sessionId2.toLowerCase()}.env`);
18458
+ await writeEnvironmentFile(envFile, prepared.env);
18459
+ console.log(JSON.stringify({
18460
+ argv: [prepared.executable, ...prepared.args],
18461
+ cwd: prepared.cwd,
18462
+ envKeys: Object.keys(prepared.env).sort(),
18463
+ envFile,
18464
+ routeFile: routeFile2,
18465
+ lease: { durable: true, revivedOnUseForDays: 30, note: "The lease is released when this command exits; the gateway serves its durable route again on the first request from any process of this user, for 30 days after it ends." }
18466
+ }));
18467
+ };
18468
+ try {
18469
+ await main(launchArgs, { launchOptions: { requireDurableRoute: true, prepareOnly } });
18470
+ } catch (error) {
18471
+ if (error instanceof Fault && !(error instanceof ResumeFault) && ["gateway_route_unavailable", "gateway_unavailable", "gateway_socket_untrusted", "gateway_protocol_mismatch", "gateway_unsupported"].includes(error.code))
18472
+ throw new ResumeFault(5, error.status, error.code, error.message);
18473
+ throw error;
18474
+ }
18475
+ }
17786
18476
  function launchGatewayMode() {
17787
18477
  const mode = process.env.SWITCHER_GATEWAY?.trim() || "service";
17788
18478
  if (mode !== "local" && mode !== "service")
@@ -17878,10 +18568,12 @@ if (import.meta.main) {
17878
18568
  else
17879
18569
  main().catch((error) => {
17880
18570
  console.error(JSON.stringify({ error: error instanceof SwitcherError ? { code: error.code, message: error.message, requestId: error.requestId } : error instanceof Fault ? { code: error.code, message: error.message } : { message: error instanceof Error ? error.message : "Command failed." } }));
17881
- process.exitCode = error instanceof CommandInterrupted ? error.exitCode : error instanceof SwitcherError && error.code === "interrupted" ? process.exitCode ?? 1 : 1;
18571
+ const resumeUsage = process.argv.slice(2).find((arg) => !arg.startsWith("-")) === "resume" && typeof error?.code === "string" && error.code.startsWith("ERR_PARSE_ARGS");
18572
+ process.exitCode = error instanceof ResumeFault ? error.exitCode : resumeUsage ? 2 : error instanceof CommandInterrupted ? error.exitCode : error instanceof SwitcherError && error.code === "interrupted" ? process.exitCode ?? 1 : 1;
17882
18573
  });
17883
18574
  }
17884
18575
  export {
17885
18576
  readModelPolicy,
17886
- main
18577
+ main,
18578
+ ResumeFault
17887
18579
  };