@hasna/switcher 0.2.25 → 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.25";
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;
@@ -2632,7 +2632,7 @@ var openapi_default = {
2632
2632
  openapi: "3.0.3",
2633
2633
  info: {
2634
2634
  title: "Switcher API",
2635
- version: "0.2.25",
2635
+ version: "0.2.26",
2636
2636
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2637
2637
  },
2638
2638
  security: [
@@ -8671,6 +8671,91 @@ function prepareOpenCodeMessages(baseUrl, body, suffix, credential, state = new
8671
8671
  } };
8672
8672
  }
8673
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
+
8674
8759
  // src/inference-gateway.ts
8675
8760
  import { createHash as createHash6, timingSafeEqual as timingSafeEqual3 } from "crypto";
8676
8761
  var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
@@ -8751,6 +8836,26 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8751
8836
  const upstreamFail = (status, code, message) => Response.json({ ...input.protocol === "anthropic-messages" ? { type: "error" } : {}, error: { type: "switcher_model_policy", code, message } }, { status });
8752
8837
  let closing = false, stopped;
8753
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
+ };
8754
8859
  const handle = async (request, server) => {
8755
8860
  if (closing)
8756
8861
  return fail(503, "closing");
@@ -8773,6 +8878,7 @@ function createInferenceHandler(input, timing = {}, options = {}) {
8773
8878
  const body = parsed.value;
8774
8879
  if (!body || typeof body !== "object" || Array.isArray(body))
8775
8880
  return fail(400, "invalid_request");
8881
+ await observeClaudeSession(request, body);
8776
8882
  let credential;
8777
8883
  try {
8778
8884
  credential = options.credential ? await options.credential() : input.credential;
@@ -9037,7 +9143,7 @@ function createInferenceGateway(input, timing = {}, options = {}) {
9037
9143
 
9038
9144
  // src/codex-model-policy.ts
9039
9145
  import { mkdir as mkdir5, readFile as readFile4, realpath as realpath3, stat as stat4, writeFile as writeFile7 } from "fs/promises";
9040
- 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";
9041
9147
  import { execFileSync as execFileSync2 } from "child_process";
9042
9148
  import { createHash as createHash7 } from "crypto";
9043
9149
  var dict = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
@@ -9057,7 +9163,7 @@ function codexAgentsFromEffectiveConfig(config, trustedProject = true, baseDir)
9057
9163
  const rawConfigFile = value.config_file;
9058
9164
  if (rawConfigFile !== undefined && typeof rawConfigFile !== "string")
9059
9165
  throw new Error(`Codex agents.${name}.config_file must be a string.`);
9060
- 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;
9061
9167
  if (rawConfigFile !== undefined && !configFile)
9062
9168
  throw new Error(`Codex agents.${name}.config_file must be absolute after precedence resolution.`);
9063
9169
  const definition = { trusted: trustedProject, config_file: configFile };
@@ -9186,16 +9292,16 @@ async function writeCodexAgentOverrides(result, stateDir) {
9186
9292
  const paths = {};
9187
9293
  for (const agent of result.agents) {
9188
9294
  const digest = createHash7("sha256").update(agent.name).digest("hex").slice(0, 16);
9189
- const path = join9(root, `agent-${digest}.toml`);
9295
+ const path = join10(root, `agent-${digest}.toml`);
9190
9296
  await writeFile7(path, renderCodexAgentToml(agent.config), { encoding: "utf8", mode: 384, flag: "wx" });
9191
9297
  paths[agent.name] = path;
9192
9298
  }
9193
9299
  return paths;
9194
9300
  }
9195
9301
  async function prepareCodexModelPolicy(input) {
9196
- 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"));
9197
9303
  const cwd = resolve5(input.cwd);
9198
- const globalPath = join9(home, "config.toml");
9304
+ const globalPath = join10(home, "config.toml");
9199
9305
  const readConfig = async (path) => {
9200
9306
  let info;
9201
9307
  try {
@@ -9219,7 +9325,7 @@ async function prepareCodexModelPolicy(input) {
9219
9325
  const global = await readConfig(globalPath) ?? {};
9220
9326
  const projects = dict(global.projects) ? global.projects : {};
9221
9327
  const markers = global.project_root_markers ?? [".git"];
9222
- 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("..")))
9223
9329
  throw new Error("Unsupported Codex project root markers.");
9224
9330
  const ancestorDirs = [];
9225
9331
  for (let dir = cwd;; dir = dirname4(dir)) {
@@ -9232,9 +9338,9 @@ async function prepareCodexModelPolicy(input) {
9232
9338
  for (const dir of ancestorDirs)
9233
9339
  for (const marker of markers) {
9234
9340
  try {
9235
- const info = await stat4(join9(dir, marker));
9341
+ const info = await stat4(join10(dir, marker));
9236
9342
  if (marker === ".git" && info.isDirectory())
9237
- await stat4(join9(dir, marker, "HEAD"));
9343
+ await stat4(join10(dir, marker, "HEAD"));
9238
9344
  projectRoot = dir;
9239
9345
  break findRoot;
9240
9346
  } catch {}
@@ -9259,7 +9365,7 @@ async function prepareCodexModelPolicy(input) {
9259
9365
  const layers = [{ path: globalPath, config: global }];
9260
9366
  const projectDirs = ancestorDirs.slice(0, ancestorDirs.indexOf(projectRoot) + 1).reverse();
9261
9367
  for (const dir of projectDirs) {
9262
- const path = join9(dir, ".codex", "config.toml");
9368
+ const path = join10(dir, ".codex", "config.toml");
9263
9369
  if (path === globalPath)
9264
9370
  continue;
9265
9371
  const decision = await trust(dir) ?? projectTrust ?? repoTrust;
@@ -9288,7 +9394,7 @@ async function prepareCodexModelPolicy(input) {
9288
9394
  return { ...result, agentConfigPaths: await writeCodexAgentOverrides(result, input.stateDir), configPaths: loaded };
9289
9395
  }
9290
9396
  async function readCodexAgentConfig(path) {
9291
- if (!isAbsolute8(path))
9397
+ if (!isAbsolute9(path))
9292
9398
  throw new Error("Codex agent config_file must be absolute before launch.");
9293
9399
  const canonical = await realpath3(path);
9294
9400
  const info = await stat4(canonical);
@@ -9303,18 +9409,18 @@ async function readCodexAgentConfig(path) {
9303
9409
  }
9304
9410
 
9305
9411
  // src/harnesses.ts
9306
- import { access as access3, lstat as lstat6, mkdir as mkdir10, open as open3, readFile as readFile6, readdir as readdir4, rename as rename2, writeFile as writeFile13, rm as rm2 } from "fs/promises";
9307
- 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";
9308
9414
  import { homedir as homedir8, tmpdir } from "os";
9309
- 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";
9310
9416
  import { execFile as execFile2 } from "child_process";
9311
9417
  import { promisify as promisify2 } from "util";
9312
9418
  import { createConnection } from "net";
9313
9419
 
9314
9420
  // src/aider-config.ts
9315
- import { readFile as readFile5, writeFile as writeFile8, lstat as lstat5, copyFile, rename, realpath as realpath4, access as access2 } from "fs/promises";
9316
- import { constants as constants3 } from "fs";
9317
- 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";
9318
9424
  import { homedir as homedir6 } from "os";
9319
9425
  import { parseDocument as parseDocument2 } from "yaml";
9320
9426
  var KEY2 = "SWITCHER_HARNESS_API_KEY";
@@ -9356,9 +9462,9 @@ async function gitRoot(path) {
9356
9462
  parent = dirname5(parent);
9357
9463
  }
9358
9464
  }
9359
- for (let dir = join10(parent, ...missing);; dir = dirname5(dir)) {
9465
+ for (let dir = join11(parent, ...missing);; dir = dirname5(dir)) {
9360
9466
  try {
9361
- await lstat5(join10(dir, ".git"));
9467
+ await lstat5(join11(dir, ".git"));
9362
9468
  return dir;
9363
9469
  } catch (error) {
9364
9470
  if (!["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
@@ -9371,9 +9477,9 @@ async function gitRoot(path) {
9371
9477
  var falseValue = (v) => v === undefined || v === null || v === false || v === 0 || typeof v === "string" && ["", "false", "no", "off", "0"].includes(v.toLowerCase());
9372
9478
  var startup = `yes-always gui browser upgrade install-main-branch just-check-update apply-clipboard-edits test lint commit`.split(" ");
9373
9479
  var safeParameters = new Set(`max_tokens temperature top_p top_k min_p stop seed reasoning_effort thinking`.split(" "));
9374
- 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;
9375
9481
  async function validateAiderConfiguration(cwd, args = [], home = process.env.HOME ?? homedir6()) {
9376
- if (!isAbsolute9(home))
9482
+ if (!isAbsolute10(home))
9377
9483
  throw new Error("Aider requires an absolute HOME to preserve native instruction paths.");
9378
9484
  const parsed = aiderArguments(args), cwdRoot = await gitRoot(cwd);
9379
9485
  const roots = new Set([resolve6(home), ...cwdRoot ? [cwdRoot] : [], resolve6(cwd)]);
@@ -9384,7 +9490,7 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
9384
9490
  }
9385
9491
  let effective = {};
9386
9492
  for (const root of roots) {
9387
- const path = join10(root, ".aider.conf.yml"), value = await data(path);
9493
+ const path = join11(root, ".aider.conf.yml"), value = await data(path);
9388
9494
  if (value !== undefined) {
9389
9495
  if (!object3(value))
9390
9496
  throw new Error(`Aider configuration must be a mapping: ${path}`);
@@ -9409,13 +9515,13 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
9409
9515
  }
9410
9516
  effective = { ...effective, ...normalized };
9411
9517
  }
9412
- const settings2 = await data(join10(root, ".aider.model.settings.yml"));
9518
+ const settings2 = await data(join11(root, ".aider.model.settings.yml"));
9413
9519
  if (settings2 !== undefined) {
9414
9520
  if (!Array.isArray(settings2))
9415
9521
  throw new Error("Aider model settings must be a list.");
9416
9522
  for (const entry of settings2)
9417
9523
  if (!object3(entry) || entry.extra_params !== undefined && (!object3(entry.extra_params) || Object.keys(entry.extra_params).some((key) => !safeParameters.has(key))))
9418
- 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")}`);
9419
9525
  }
9420
9526
  }
9421
9527
  if (effective.read !== undefined && !(typeof effective.read === "string" || Array.isArray(effective.read) && effective.read.every((v) => typeof v === "string")))
@@ -9423,7 +9529,7 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
9423
9529
  const reads = parsed.reads.length ? parsed.reads : typeof effective.read === "string" ? [effective.read] : effective.read ?? [];
9424
9530
  for (const path of reads) {
9425
9531
  try {
9426
- await access2(resolve6(cwd, expandHome(path, home)), constants3.R_OK);
9532
+ await access2(resolve6(cwd, expandHome(path, home)), constants4.R_OK);
9427
9533
  } catch {
9428
9534
  throw new Error(`Aider read-only instruction file is not readable: ${path}`);
9429
9535
  }
@@ -9459,26 +9565,26 @@ async function prepareAider(input) {
9459
9565
  } else if (parsed.args[i].startsWith("--read="))
9460
9566
  parsed.args[i] = "--read=" + expandHome(parsed.args[i].slice(7), sourceHome);
9461
9567
  }
9462
- const home = join10(input.stateDir, "aider-home");
9568
+ const home = join11(input.stateDir, "aider-home");
9463
9569
  await privateDirectory(home);
9464
9570
  const originalHome = process.env.HOME ?? homedir6();
9465
- 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")];
9466
- 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");
9467
9573
  await writeFile8(gitConfig, gitSources.map((path) => `[include]
9468
9574
  path = ${JSON.stringify(path)}
9469
9575
  `).join(""), { mode: 384, flag: "wx" });
9470
- const sessions = input.sessionDir ?? join10(input.stateDir, "sessions");
9576
+ const sessions = input.sessionDir ?? join11(input.stateDir, "sessions");
9471
9577
  await privateDirectory(sessions);
9472
- 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`);
9473
9579
  if (parsed.restore) {
9474
- const latest = join10(sessions, "latest.json");
9580
+ const latest = join11(sessions, "latest.json");
9475
9581
  await historyFile(latest).catch(() => {
9476
9582
  throw new Error("No valid completed Aider history is available for this profile.");
9477
9583
  });
9478
9584
  const previous = JSON.parse(await readFile5(latest, "utf8"));
9479
9585
  if (!object3(previous) || typeof previous.id !== "string" || !/^[-a-f0-9]{36}$/.test(previous.id))
9480
9586
  throw new Error("Invalid Aider history reference.");
9481
- const source = join10(sessions, `${previous.id}.chat.md`);
9587
+ const source = join11(sessions, `${previous.id}.chat.md`);
9482
9588
  await historyFile(source);
9483
9589
  await copyFile(source, history, 1);
9484
9590
  } else
@@ -9488,7 +9594,7 @@ async function prepareAider(input) {
9488
9594
  const model2 = aiderModelName(input.protocol, input.model);
9489
9595
  const weakModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.weak ?? input.model), editorModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.editor ?? input.model);
9490
9596
  const extra = { api_base: input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl, api_key: `os.environ/${KEY2}` };
9491
- 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");
9492
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 }));
9493
9599
  await writeFile8(settings2, JSON.stringify([...definitions, { name: "aider/extra_params", extra_params: extra }]), { mode: 384, flag: "wx" });
9494
9600
  await writeFile8(metadata, JSON.stringify(Object.fromEntries(input.models.map((m) => [aiderModelName(input.protocol, m.id), {
@@ -9507,7 +9613,7 @@ async function prepareAider(input) {
9507
9613
  return {
9508
9614
  executable: input.executable ?? "aider",
9509
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],
9510
- 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 },
9511
9617
  configPaths: [config, settings2, metadata, empty, gitConfig],
9512
9618
  warnings: [
9513
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."] : [],
@@ -9523,9 +9629,9 @@ async function prepareAider(input) {
9523
9629
  await historyFile(history);
9524
9630
  if (!/^#### /m.test((await readFile5(history, "utf8")).slice(originalHistoryLength)))
9525
9631
  return;
9526
- const pending = join10(sessions, `${id2}.latest.json`);
9632
+ const pending = join11(sessions, `${id2}.latest.json`);
9527
9633
  await writeFile8(pending, JSON.stringify({ id: id2 }), { mode: 384, flag: "wx" });
9528
- await rename(pending, join10(sessions, "latest.json"));
9634
+ await rename2(pending, join11(sessions, "latest.json"));
9529
9635
  }
9530
9636
  };
9531
9637
  }
@@ -9608,8 +9714,8 @@ function validateGrokResume(args) {
9608
9714
 
9609
9715
  // src/cline-backend.ts
9610
9716
  import { mkdir as mkdir6, writeFile as writeFile9 } from "fs/promises";
9611
- import { randomUUID as randomUUID2 } from "crypto";
9612
- 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";
9613
9719
  var ENV_BY_PROTOCOL = {
9614
9720
  "anthropic-messages": "ANTHROPIC_API_KEY",
9615
9721
  "openai-responses": "OPENAI_API_KEY",
@@ -9655,18 +9761,18 @@ async function prepareClineLaunch(input) {
9655
9761
  throw new Error(`Cline ${input.protocol} uses ${mapping.authStyle} authentication; use a provider with the native Cline auth contract.`);
9656
9762
  if (input.credential && /[\r\n]/.test(input.credential))
9657
9763
  throw new Error("Provider credential contains invalid header characters.");
9658
- if (!isAbsolute10(input.stateDir) || !isAbsolute10(input.cwd))
9764
+ if (!isAbsolute11(input.stateDir) || !isAbsolute11(input.cwd))
9659
9765
  throw new Error("Launch state and working directories must be absolute.");
9660
- const dataDir = join11(input.stateDir, "cline-data");
9661
- const sessionDir = input.sessionDir ?? join11(dataDir, "sessions");
9662
- const launchDir = join11(input.stateDir, `cline-launch-${randomUUID2()}`);
9663
- const settingsDir = join11(launchDir, "settings");
9664
- 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");
9665
9771
  await mkdir6(settingsDir, { recursive: true, mode: 448 });
9666
9772
  await mkdir6(configDir, { recursive: true, mode: 448 });
9667
9773
  const baseUrl = endpoint(input.baseUrl);
9668
9774
  const providerId = mapping.providerId;
9669
- const providersPath = await writeJson(join11(settingsDir, "providers.json"), {
9775
+ const providersPath = await writeJson(join12(settingsDir, "providers.json"), {
9670
9776
  version: 1,
9671
9777
  lastUsedProvider: providerId,
9672
9778
  modes: {},
@@ -9686,7 +9792,7 @@ async function prepareClineLaunch(input) {
9686
9792
  }
9687
9793
  }
9688
9794
  });
9689
- const modelsPath = await writeJson(join11(settingsDir, "models.json"), {
9795
+ const modelsPath = await writeJson(join12(settingsDir, "models.json"), {
9690
9796
  version: 1,
9691
9797
  providers: {
9692
9798
  [providerId]: {
@@ -9735,11 +9841,11 @@ async function prepareClineLaunch(input) {
9735
9841
  }
9736
9842
 
9737
9843
  // src/opencode2-config.ts
9738
- import { mkdir as mkdir7, open as open2, realpath as realpath5, readdir as readdir3, stat as stat5, writeFile as writeFile10 } from "fs/promises";
9739
- import { constants as constants4 } from "fs";
9740
- 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";
9741
9847
  import { homedir as homedir7 } from "os";
9742
- import { randomUUID as randomUUID3 } from "crypto";
9848
+ import { randomUUID as randomUUID4 } from "crypto";
9743
9849
  import { Database as Database2 } from "bun:sqlite";
9744
9850
  import { parse as parse3, parseTree as parseTree3 } from "jsonc-parser";
9745
9851
  import { parseDocument as parseDocument3 } from "yaml";
@@ -9753,7 +9859,7 @@ var maxTotalBytes2 = 8 * 1024 * 1024;
9753
9859
  var maxFiles2 = 256;
9754
9860
  var inside2 = (root, path) => {
9755
9861
  const rel = relative4(root, path);
9756
- return rel === "" || !isAbsolute11(rel) && rel !== ".." && !rel.startsWith("../");
9862
+ return rel === "" || !isAbsolute12(rel) && rel !== ".." && !rel.startsWith("../");
9757
9863
  };
9758
9864
  var action = (value) => ({ bash: "shell", task: "subagent", write: "edit", patch: "edit" })[value] ?? value;
9759
9865
  function invalid2(path, field) {
@@ -9805,7 +9911,7 @@ function permissions(value, path, home) {
9805
9911
  literal2(item.resource, path, "permission resource");
9806
9912
  if (!["read", "edit", "external_directory"].includes(item.action))
9807
9913
  return item;
9808
- 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;
9809
9915
  return { ...item, resource };
9810
9916
  });
9811
9917
  }
@@ -9833,8 +9939,8 @@ function jsonc2(text, path) {
9833
9939
  return record3(value, path, "configuration object");
9834
9940
  }
9835
9941
  async function checkRemoteConfiguration(dataHome) {
9836
- const path = join12(dataHome, "opencode", "opencode.db");
9837
- 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) => {
9838
9944
  if (error.code === "ENOENT")
9839
9945
  return false;
9840
9946
  throw error;
@@ -9874,23 +9980,23 @@ async function checkRemoteConfiguration(dataHome) {
9874
9980
  }
9875
9981
  async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9876
9982
  for (const name of ["HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "OPENCODE_CONFIG_DIR"])
9877
- if (env[name] && !isAbsolute11(env[name]))
9983
+ if (env[name] && !isAbsolute12(env[name]))
9878
9984
  throw new Error(`OpenCode 2 requires an absolute ${name} to preserve native configuration authority.`);
9879
9985
  const home = resolve7(env.HOME || homedir7());
9880
- 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"));
9881
9987
  const canonicalConfigRoot = await realpath5(configRoot).catch((error) => {
9882
9988
  if (error.code === "ENOENT")
9883
9989
  return configRoot;
9884
9990
  throw error;
9885
9991
  });
9886
- const dataHome = resolve7(env.XDG_DATA_HOME || join12(home, ".local", "share"));
9992
+ const dataHome = resolve7(env.XDG_DATA_HOME || join13(home, ".local", "share"));
9887
9993
  await checkRemoteConfiguration(dataHome);
9888
9994
  let files = 0, total = 0;
9889
9995
  const paths = [];
9890
9996
  async function read(path, optional = true) {
9891
9997
  let handle;
9892
9998
  try {
9893
- handle = await open2(path, constants4.O_RDONLY | constants4.O_NONBLOCK);
9999
+ handle = await open3(path, constants5.O_RDONLY | constants5.O_NONBLOCK);
9894
10000
  } catch (error) {
9895
10001
  if (optional && error.code === "ENOENT")
9896
10002
  return;
@@ -9923,7 +10029,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9923
10029
  invalid2(path, "agent prompt environment reference");
9924
10030
  let result = "", cursor = 0;
9925
10031
  for (const match of text.matchAll(/\{file:([^}]+)\}/g)) {
9926
- 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]);
9927
10033
  const content = (await read(requested, false)).trim();
9928
10034
  literal2(content, requested, "nested prompt variable reference");
9929
10035
  result += text.slice(cursor, match.index) + content;
@@ -9945,7 +10051,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9945
10051
  }
9946
10052
  async function agentsDirectory(directory2) {
9947
10053
  for (const source of ["agent", "agents", "mode", "modes"]) {
9948
- const base = join12(directory2, source), entries = [];
10054
+ const base = join13(directory2, source), entries = [];
9949
10055
  const visited = new Set;
9950
10056
  let examined = 0;
9951
10057
  async function walk(dir, depth) {
@@ -9955,7 +10061,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9955
10061
  if (visited.has(actual))
9956
10062
  return;
9957
10063
  visited.add(actual);
9958
- names = await readdir3(dir);
10064
+ names = await readdir4(dir);
9959
10065
  } catch (error) {
9960
10066
  if (error.code === "ENOENT")
9961
10067
  return;
@@ -9964,7 +10070,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9964
10070
  if (depth > 16 || (examined += names.length) > maxFiles2)
9965
10071
  throw new Error("OpenCode 2 agent policy exceeds its bounded directory limit.");
9966
10072
  for (const name of names) {
9967
- const path = join12(dir, name);
10073
+ const path = join13(dir, name);
9968
10074
  const info = await stat5(path);
9969
10075
  if (info.isDirectory()) {
9970
10076
  if (source === "agent" || source === "agents")
@@ -9998,8 +10104,8 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
9998
10104
  }
9999
10105
  }
10000
10106
  async function directory(path) {
10001
- await document(join12(path, "opencode.json"));
10002
- await document(join12(path, "opencode.jsonc"));
10107
+ await document(join13(path, "opencode.json"));
10108
+ await document(join13(path, "opencode.jsonc"));
10003
10109
  await agentsDirectory(path);
10004
10110
  }
10005
10111
  await directory(configRoot);
@@ -10014,11 +10120,11 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
10014
10120
  const projectEnabled = !["1", "true"].includes((env.OPENCODE_CONFIG_PROJECT_DISABLE ?? env.OPENCODE_DISABLE_PROJECT_CONFIG ?? "").toLowerCase());
10015
10121
  if (projectEnabled) {
10016
10122
  for (const path of [...ancestors].reverse()) {
10017
- await document(join12(path, "opencode.json"));
10018
- await document(join12(path, "opencode.jsonc"));
10123
+ await document(join13(path, "opencode.json"));
10124
+ await document(join13(path, "opencode.jsonc"));
10019
10125
  }
10020
10126
  for (const path of [...ancestors].reverse()) {
10021
- const candidate = join12(path, ".opencode");
10127
+ const candidate = join13(path, ".opencode");
10022
10128
  const canonical = await realpath5(candidate).catch((error) => {
10023
10129
  if (error.code === "ENOENT")
10024
10130
  return candidate;
@@ -10029,7 +10135,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
10029
10135
  }
10030
10136
  }
10031
10137
  if (env.OPENCODE_CONFIG_CONTENT)
10032
- 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") });
10033
10139
  const policy = [];
10034
10140
  const agents = Object.create(null);
10035
10141
  let defaultAgent;
@@ -10122,26 +10228,26 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
10122
10228
  instructions.push(`Instructions from: ${path}
10123
10229
  ${content}`);
10124
10230
  }
10125
- await instruction(join12(configRoot, "AGENTS.md"));
10231
+ await instruction(join13(configRoot, "AGENTS.md"));
10126
10232
  if (projectEnabled) {
10127
10233
  let stop = resolve7(cwd);
10128
10234
  if (inside2(home, resolve7(cwd)))
10129
10235
  stop = home;
10130
10236
  else
10131
10237
  for (const path of ancestors) {
10132
- if (await stat5(join12(path, ".git")).then(() => true, () => false)) {
10238
+ if (await stat5(join13(path, ".git")).then(() => true, () => false)) {
10133
10239
  stop = path;
10134
10240
  break;
10135
10241
  }
10136
10242
  }
10137
10243
  for (const path of ancestors) {
10138
- await instruction(join12(path, "AGENTS.md"));
10244
+ await instruction(join13(path, "AGENTS.md"));
10139
10245
  if (path === stop)
10140
10246
  break;
10141
10247
  }
10142
10248
  }
10143
- const privateHome = join12(stateDir, "opencode-home"), privateConfig = join12(stateDir, "opencode-config");
10144
- 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");
10145
10251
  await mkdir7(dirname6(instructionFile), { recursive: true, mode: 448 });
10146
10252
  await mkdir7(privateHome, { recursive: true, mode: 448 });
10147
10253
  await writeFile10(instructionFile, instructions.join(`
@@ -10149,13 +10255,13 @@ ${content}`);
10149
10255
  `), { flag: "wx", mode: 384 });
10150
10256
  return {
10151
10257
  config: { permissions: policy, agents, ...defaultAgent ? { default_agent: defaultAgent } : {}, experimental: { policies: [{ action: "provider.use", resource: "*", effect: "deny" }, { action: "provider.use", resource: providerID, effect: "allow" }] } },
10152
- 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" },
10153
10259
  instructionFile,
10154
10260
  sourcePaths: paths
10155
10261
  };
10156
10262
  }
10157
10263
  function openCode2ConfigText(config, providerID, keyEnv) {
10158
- const marker = randomUUID3();
10264
+ const marker = randomUUID4();
10159
10265
  const providers = config.providers;
10160
10266
  const selected = providers[providerID];
10161
10267
  const value = { ...config, providers: { ...providers, [providerID]: { ...selected, settings: { ...selected.settings, apiKey: marker } } } };
@@ -10164,8 +10270,8 @@ function openCode2ConfigText(config, providerID, keyEnv) {
10164
10270
  }
10165
10271
 
10166
10272
  // src/omp-backend.ts
10167
- import { mkdir as mkdir8, rm, writeFile as writeFile11 } from "fs/promises";
10168
- 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";
10169
10275
  var KEY3 = "SWITCHER_HARNESS_API_KEY";
10170
10276
  var API = {
10171
10277
  "anthropic-messages": "anthropic-messages",
@@ -10190,8 +10296,8 @@ async function prepareOmpLaunch(input) {
10190
10296
  const baseUrl = endpoint(input.baseUrl);
10191
10297
  if (input.credential && /[\r\n]/.test(input.credential))
10192
10298
  throw new Error("Provider credential contains invalid header characters.");
10193
- const agentDir = join13(input.stateDir, "omp-agent");
10194
- 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");
10195
10301
  await mkdir8(agentDir, { recursive: true, mode: 448 });
10196
10302
  await mkdir8(sessionDir, { recursive: true, mode: 448 });
10197
10303
  const api = API[input.protocol];
@@ -10217,8 +10323,8 @@ async function prepareOmpLaunch(input) {
10217
10323
  provider.apiKey = KEY3;
10218
10324
  provider.authHeader = true;
10219
10325
  }
10220
- const modelsPath = join13(agentDir, "models.yml");
10221
- const configPath = join13(agentDir, "config.yml");
10326
+ const modelsPath = join14(agentDir, "models.yml");
10327
+ const configPath = join14(agentDir, "config.yml");
10222
10328
  const selector = `switcher/${input.model}`;
10223
10329
  await writeFile11(modelsPath, JSON.stringify({ providers: { switcher: provider } }, null, 2) + `
10224
10330
  `, { mode: 384, flag: "wx" });
@@ -10243,7 +10349,7 @@ async function prepareOmpLaunch(input) {
10243
10349
  configPaths: [modelsPath, configPath],
10244
10350
  warnings,
10245
10351
  cleanup: async () => {
10246
- await rm(agentDir, { recursive: true, force: true });
10352
+ await rm2(agentDir, { recursive: true, force: true });
10247
10353
  }
10248
10354
  };
10249
10355
  }
@@ -10296,7 +10402,7 @@ function compileHermesModelPolicy(currentModel, roles2, baseUrl, apiMode = "chat
10296
10402
  // src/hermes-backend.ts
10297
10403
  import { createHash as createHash8, timingSafeEqual as timingSafeEqual4 } from "crypto";
10298
10404
  import { mkdir as mkdir9, symlink as symlink3, writeFile as writeFile12 } from "fs/promises";
10299
- import { isAbsolute as isAbsolute12, join as join14 } from "path";
10405
+ import { isAbsolute as isAbsolute13, join as join15 } from "path";
10300
10406
  var hermesApiMode = {
10301
10407
  "anthropic-messages": "anthropic_messages",
10302
10408
  "openai-responses": "codex_responses",
@@ -10440,7 +10546,7 @@ function createHermesBridge(input, timing = {}) {
10440
10546
  };
10441
10547
  }
10442
10548
  async function prepareHermesLaunch(input) {
10443
- if (!isAbsolute12(input.stateDir) || !isAbsolute12(input.cwd))
10549
+ if (!isAbsolute13(input.stateDir) || !isAbsolute13(input.cwd))
10444
10550
  throw new Error("Launch state and working directories must be absolute.");
10445
10551
  if (input.protocol !== "anthropic-messages" && input.protocol !== "openai-responses" && input.protocol !== "openai-chat")
10446
10552
  throw new Error("Hermes does not support this provider protocol.");
@@ -10450,12 +10556,12 @@ async function prepareHermesLaunch(input) {
10450
10556
  throw new Error("Hermes cannot safely select model IDs that differ only by letter case; update the provider catalog.");
10451
10557
  if (input.credential && /[\r\n]/.test(input.credential))
10452
10558
  throw new Error("Provider credential contains invalid header characters.");
10453
- const sessionDir = input.sessionDir ?? join14(input.stateDir, "hermes-session");
10454
- const sessionsDir = join14(sessionDir, "sessions");
10559
+ const sessionDir = input.sessionDir ?? join15(input.stateDir, "hermes-session");
10560
+ const sessionsDir = join15(sessionDir, "sessions");
10455
10561
  await mkdir9(input.stateDir, { recursive: true, mode: 448 });
10456
10562
  await mkdir9(sessionsDir, { recursive: true, mode: 448 });
10457
- await symlink3(join14(sessionDir, "state.db"), join14(input.stateDir, "state.db"));
10458
- 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"));
10459
10565
  const bridge = createHermesBridge(input);
10460
10566
  let policy;
10461
10567
  try {
@@ -10483,7 +10589,7 @@ async function prepareHermesLaunch(input) {
10483
10589
  }
10484
10590
  }
10485
10591
  };
10486
- const configPath = join14(input.stateDir, "config.yaml");
10592
+ const configPath = join15(input.stateDir, "config.yaml");
10487
10593
  try {
10488
10594
  await writeFile12(configPath, JSON.stringify(config, null, 2) + `
10489
10595
  `, { mode: 384, flag: "wx" });
@@ -10500,7 +10606,7 @@ async function prepareHermesLaunch(input) {
10500
10606
  SWITCHER_HERMES_AUX_API_KEY: bridge.token,
10501
10607
  OPENAI_API_KEY: bridge.token,
10502
10608
  OPENAI_BASE_URL: bridge.baseUrl,
10503
- CODEX_HOME: join14(input.stateDir, "codex-home")
10609
+ CODEX_HOME: join15(input.stateDir, "codex-home")
10504
10610
  },
10505
10611
  configPaths: [configPath],
10506
10612
  warnings: [
@@ -10716,19 +10822,19 @@ function validateHarnessVersion(harness, version2) {
10716
10822
  throw new Error("Gemini CLI 0.58.0 is required by the verified native settings and argument contract.");
10717
10823
  }
10718
10824
  async function jsonFile(dir, name, value) {
10719
- const path = join15(dir, name);
10825
+ const path = join16(dir, name);
10720
10826
  await writeFile13(path, JSON.stringify(value, null, 2) + `
10721
10827
  `, { mode: 384, flag: "wx" });
10722
10828
  return path;
10723
10829
  }
10724
10830
  function claudeSettingsDirectory(sessionDir) {
10725
- return join15(sessionDir, "settings");
10831
+ return join16(sessionDir, "settings");
10726
10832
  }
10727
10833
  async function durableJsonFile(dir, prefix, value) {
10728
10834
  const text = JSON.stringify(value, null, 2) + `
10729
10835
  `;
10730
10836
  await privateDirectory(dir);
10731
- 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`);
10732
10838
  const existing = await lstat6(path).catch(() => {
10733
10839
  return;
10734
10840
  });
@@ -10736,12 +10842,12 @@ async function durableJsonFile(dir, prefix, value) {
10736
10842
  return;
10737
10843
  }) === text)
10738
10844
  return path;
10739
- const temporary = `${path}.${randomUUID4()}.tmp`;
10845
+ const temporary = `${path}.${randomUUID5()}.tmp`;
10740
10846
  await writeFile13(temporary, text, { mode: 384, flag: "wx" });
10741
10847
  try {
10742
- await rename2(temporary, path);
10848
+ await rename3(temporary, path);
10743
10849
  } catch (error) {
10744
- await rm2(temporary, { force: true }).catch(() => {
10850
+ await rm3(temporary, { force: true }).catch(() => {
10745
10851
  return;
10746
10852
  });
10747
10853
  throw error;
@@ -10756,17 +10862,17 @@ async function routeJsonFile(path, value) {
10756
10862
  `, { mode: 384, flag: "wx" });
10757
10863
  const info = await lstat6(path);
10758
10864
  if (!info.isFile() || (info.mode & 63) !== 0 || info.uid !== process.getuid?.()) {
10759
- await rm2(path, { force: true });
10865
+ await rm3(path, { force: true });
10760
10866
  throw new Error("The Claude route settings file could not be created owner-only.");
10761
10867
  }
10762
10868
  return path;
10763
10869
  }
10764
10870
  async function adoptClaudeSettingsRoutes(dir, route2) {
10765
10871
  let adopted = 0;
10766
- for (const name of await readdir4(dir).catch(() => [])) {
10872
+ for (const name of await readdir5(dir).catch(() => [])) {
10767
10873
  if (!/^claude-settings-[0-9a-f]{32}\.json$/.test(name))
10768
10874
  continue;
10769
- const path = join15(dir, name);
10875
+ const path = join16(dir, name);
10770
10876
  const info = await lstat6(path).catch(() => {
10771
10877
  return;
10772
10878
  });
@@ -10780,9 +10886,9 @@ async function adoptClaudeSettingsRoutes(dir, route2) {
10780
10886
  }
10781
10887
  if (!value || typeof value !== "object" || Array.isArray(value) || !("modelPicker" in value))
10782
10888
  continue;
10783
- const temporary = `${path}.${randomUUID4()}.tmp`;
10889
+ const temporary = `${path}.${randomUUID5()}.tmp`;
10784
10890
  try {
10785
- const handle = await open3(temporary, "wx", 384);
10891
+ const handle = await open4(temporary, "wx", 384);
10786
10892
  try {
10787
10893
  await handle.writeFile(JSON.stringify({ ...value, ...route2 }, null, 2) + `
10788
10894
  `);
@@ -10790,10 +10896,10 @@ async function adoptClaudeSettingsRoutes(dir, route2) {
10790
10896
  } finally {
10791
10897
  await handle.close();
10792
10898
  }
10793
- await rename2(temporary, path);
10899
+ await rename3(temporary, path);
10794
10900
  adopted++;
10795
10901
  } catch {
10796
- await rm2(temporary, { force: true }).catch(() => {
10902
+ await rm3(temporary, { force: true }).catch(() => {
10797
10903
  return;
10798
10904
  });
10799
10905
  }
@@ -10804,7 +10910,7 @@ async function projectInstructionPaths(cwd) {
10804
10910
  let dir = resolve8(cwd);
10805
10911
  while (true) {
10806
10912
  for (const name of ["AGENTS.md", "CLAUDE.md", "CONTEXT.md"]) {
10807
- const path = join15(dir, name);
10913
+ const path = join16(dir, name);
10808
10914
  if (await access3(path).then(() => true, () => false))
10809
10915
  return [path];
10810
10916
  }
@@ -10881,7 +10987,7 @@ function expandHomePattern(value) {
10881
10987
  const record4 = value;
10882
10988
  const output = {};
10883
10989
  for (const [key, item] of Object.entries(record4)) {
10884
- const expanded = key === "~" ? homedir8() : key.startsWith("~/") ? join15(homedir8(), key.slice(2)) : key;
10990
+ const expanded = key === "~" ? homedir8() : key.startsWith("~/") ? join16(homedir8(), key.slice(2)) : key;
10885
10991
  output[expanded] = expandHomePattern(item);
10886
10992
  }
10887
10993
  return output;
@@ -10950,14 +11056,14 @@ async function agentPolicyFiles(dir, kind) {
10950
11056
  const visit = async (current, root) => {
10951
11057
  let entries;
10952
11058
  try {
10953
- entries = await readdir4(current, { withFileTypes: true });
11059
+ entries = await readdir5(current, { withFileTypes: true });
10954
11060
  } catch (error) {
10955
11061
  if (error.code === "ENOENT")
10956
11062
  return;
10957
11063
  throw error;
10958
11064
  }
10959
11065
  for (const entry of entries) {
10960
- const file = join15(current, entry.name);
11066
+ const file = join16(current, entry.name);
10961
11067
  if (entry.isDirectory())
10962
11068
  await visit(file, root);
10963
11069
  else if (entry.isFile() && entry.name.endsWith(".md"))
@@ -10965,7 +11071,7 @@ async function agentPolicyFiles(dir, kind) {
10965
11071
  }
10966
11072
  };
10967
11073
  for (const rootName of [kind, `${kind}s`])
10968
- await visit(join15(dir, rootName), join15(dir, rootName));
11074
+ await visit(join16(dir, rootName), join16(dir, rootName));
10969
11075
  return result.sort((a, b) => a.file.localeCompare(b.file));
10970
11076
  }
10971
11077
  async function readAgentPolicyFile(file, kind, root) {
@@ -11021,9 +11127,9 @@ async function preservedOpenCodePolicy(cwd) {
11021
11127
  result.mode = { ...result.mode ?? {}, [policy.name]: { permission: merged } };
11022
11128
  }
11023
11129
  };
11024
- 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");
11025
11131
  for (const name of ["config.json", "opencode.json", "opencode.jsonc"])
11026
- await apply(join15(originalConfig, name));
11132
+ await apply(join16(originalConfig, name));
11027
11133
  await applyMarkdown(originalConfig, "agent");
11028
11134
  await applyMarkdown(originalConfig, "mode");
11029
11135
  if (process.env.OPENCODE_CONFIG)
@@ -11039,22 +11145,22 @@ async function preservedOpenCodePolicy(cwd) {
11039
11145
  }
11040
11146
  for (const current of [...dirs].reverse())
11041
11147
  for (const name of ["opencode.jsonc", "opencode.json"])
11042
- await apply(join15(current, name));
11148
+ await apply(join16(current, name));
11043
11149
  for (const current of dirs) {
11044
- const configDir = join15(current, ".opencode");
11150
+ const configDir = join16(current, ".opencode");
11045
11151
  for (const name of ["opencode.json", "opencode.jsonc"])
11046
- await apply(join15(configDir, name));
11152
+ await apply(join16(configDir, name));
11047
11153
  await applyMarkdown(configDir, "agent");
11048
11154
  await applyMarkdown(configDir, "mode");
11049
11155
  }
11050
- const homeConfig = join15(homedir8(), ".opencode");
11156
+ const homeConfig = join16(homedir8(), ".opencode");
11051
11157
  for (const name of ["opencode.json", "opencode.jsonc"])
11052
- await apply(join15(homeConfig, name));
11158
+ await apply(join16(homeConfig, name));
11053
11159
  await applyMarkdown(homeConfig, "agent");
11054
11160
  await applyMarkdown(homeConfig, "mode");
11055
11161
  if (process.env.OPENCODE_CONFIG_DIR) {
11056
11162
  for (const name of ["opencode.json", "opencode.jsonc"])
11057
- await apply(join15(process.env.OPENCODE_CONFIG_DIR, name));
11163
+ await apply(join16(process.env.OPENCODE_CONFIG_DIR, name));
11058
11164
  await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "agent");
11059
11165
  await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "mode");
11060
11166
  }
@@ -11224,21 +11330,21 @@ var PRIME_UNIX_SOCKET_LIMIT = 100;
11224
11330
  var PRIME_DAEMON_STARTUP_TIMEOUT_MS = 30000;
11225
11331
  var PRIME_DAEMON_SHUTDOWN_TIMEOUT_MS = 5000;
11226
11332
  function primeSocketPaths(runtimeDir) {
11227
- const basename3 = `p-${randomUUID4().replaceAll("-", "").slice(0, 8)}.sock`;
11228
- const daemonSocket = join15(runtimeDir, basename3);
11333
+ const basename3 = `p-${randomUUID5().replaceAll("-", "").slice(0, 8)}.sock`;
11334
+ const daemonSocket = join16(runtimeDir, basename3);
11229
11335
  const uid = typeof process.getuid === "function" ? String(process.getuid()) : "user";
11230
- const workerDir = join15(runtimeDir, `prime-agent-${uid}`);
11336
+ const workerDir = join16(runtimeDir, `prime-agent-${uid}`);
11231
11337
  const workerKey = createHash9("sha256").update(daemonSocket).digest("hex").slice(0, 12);
11232
- const workerSocket = join15(workerDir, `worker-${workerKey}-${"x".repeat(12)}.sock`);
11338
+ const workerSocket = join16(workerDir, `worker-${workerKey}-${"x".repeat(12)}.sock`);
11233
11339
  const overlong = [daemonSocket, workerSocket].find((path) => Buffer.byteLength(path, "utf8") > PRIME_UNIX_SOCKET_LIMIT);
11234
- return { daemonSocket, runtimeDir, workerDir, workerPrefix: join15(workerDir, `worker-${workerKey}-`), overlong };
11340
+ return { daemonSocket, runtimeDir, workerDir, workerPrefix: join16(workerDir, `worker-${workerKey}-`), overlong };
11235
11341
  }
11236
11342
  async function primeSocketInfo() {
11237
11343
  const requested = tmpdir();
11238
11344
  const direct = primeSocketPaths(requested);
11239
11345
  if (!direct.overlong)
11240
11346
  return direct;
11241
- const fallback = join15(switcherHome(), "r");
11347
+ const fallback = join16(switcherHome(), "r");
11242
11348
  await privateDirectory(switcherHome());
11243
11349
  await privateDirectory(fallback);
11244
11350
  const scoped = primeSocketPaths(fallback);
@@ -11336,11 +11442,11 @@ async function primeStartSupervisor(input, executable, socketPath, env, onSpawn)
11336
11442
  }
11337
11443
  async function primeOwnedShutdown(socketPath, workerPrefix) {
11338
11444
  const exists = () => access3(socketPath).then(() => true, () => false);
11339
- 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))), () => []);
11340
11446
  if (!await exists())
11341
11447
  throw new Error(`Prime Agent owned daemon socket disappeared before cleanup (${socketPath}).`);
11342
11448
  let responseSeen = false;
11343
- const requestId = `switcher_${randomUUID4()}`;
11449
+ const requestId = `switcher_${randomUUID5()}`;
11344
11450
  let requestSent = false;
11345
11451
  await new Promise((resolve9, reject2) => {
11346
11452
  const socket = createConnection(socketPath);
@@ -11418,8 +11524,8 @@ async function primeRemainingSockets(socketPath, workerPrefix) {
11418
11524
  const daemon = await access3(socketPath).then(() => true, () => false);
11419
11525
  const workerDir = workerPrefix.slice(0, workerPrefix.lastIndexOf("/"));
11420
11526
  const prefix = workerPrefix.slice(workerPrefix.lastIndexOf("/") + 1);
11421
- const workers = await readdir4(workerDir).then((entries) => entries.filter((entry) => entry.startsWith(prefix)), () => []);
11422
- 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))];
11423
11529
  }
11424
11530
  function primeModel(input, api) {
11425
11531
  return input.models.map((model3) => ({
@@ -11437,7 +11543,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11437
11543
  if (!compatible(input.harness, input.protocol))
11438
11544
  throw new Error("Harness and provider protocol are incompatible.");
11439
11545
  validateHarnessVersion(input.harness, input.version);
11440
- if (!isAbsolute13(input.stateDir) || !isAbsolute13(input.cwd))
11546
+ if (!isAbsolute14(input.stateDir) || !isAbsolute14(input.cwd))
11441
11547
  throw new Error("Launch state and working directories must be absolute.");
11442
11548
  if (!input.models.length || !input.models.some((m) => m.id === input.model))
11443
11549
  throw new Error("Selected model is missing from the launch catalog.");
@@ -11541,8 +11647,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11541
11647
  throw new Error("Pi cannot safely select model IDs that differ only by letter case; update the provider catalog.");
11542
11648
  const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions", "gemini-generate-content": "gemini" }[input.protocol];
11543
11649
  const providerId = piProviderId(input, providerBaseUrl);
11544
- const agentDir = join15(input.stateDir, "pi-agent");
11545
- 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");
11546
11652
  const piBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
11547
11653
  await mkdir10(agentDir, { recursive: true, mode: 448 });
11548
11654
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
@@ -11567,9 +11673,9 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11567
11673
  const selected = dshArguments(args);
11568
11674
  const providerId = piProviderId(input, providerBaseUrl);
11569
11675
  const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
11570
- const home = join15(input.stateDir, "dsh-home");
11571
- const sessionDir = input.sessionDir ?? join15(input.stateDir, "dsh-state");
11572
- 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))
11573
11679
  throw new Error("DSH session directory must be absolute.");
11574
11680
  await mkdir10(home, { recursive: true, mode: 448 });
11575
11681
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
@@ -11590,7 +11696,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11590
11696
  }))
11591
11697
  } } } },
11592
11698
  { id: "agent-default-model", config: route2 },
11593
- { id: "session-persistence-jsonl", config: { root: join15(sessionDir, "sessions") } },
11699
+ { id: "session-persistence-jsonl", config: { root: join16(sessionDir, "sessions") } },
11594
11700
  { id: "attachment-local", config: { dshHome: sessionDir } },
11595
11701
  ...selected.profile === "acp" ? [{ id: "acp", config: route2 }] : []
11596
11702
  ];
@@ -11616,14 +11722,14 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11616
11722
  throw new Error("Prime Agent cannot safely select model IDs that differ only by letter case; update the provider catalog.");
11617
11723
  const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
11618
11724
  const providerId = primeProviderId(input, providerBaseUrl);
11619
- const sessionDir = input.sessionDir ?? join15(input.stateDir, "sessions");
11620
- const agentDir = join15(input.stateDir, "prime-agent");
11725
+ const sessionDir = input.sessionDir ?? join16(input.stateDir, "sessions");
11726
+ const agentDir = join16(input.stateDir, "prime-agent");
11621
11727
  const socketInfo = await primeSocketInfo();
11622
11728
  const { daemonSocket, runtimeDir, workerPrefix } = socketInfo;
11623
11729
  const primeBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
11624
11730
  await mkdir10(agentDir, { recursive: true, mode: 448 });
11625
11731
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
11626
- const file2 = join15(agentDir, "models.json");
11732
+ const file2 = join16(agentDir, "models.json");
11627
11733
  await writeFile13(file2, JSON.stringify({ providers: { [providerId]: {
11628
11734
  name: "Switcher",
11629
11735
  baseUrl: primeBaseUrl,
@@ -11715,13 +11821,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11715
11821
  const file2 = await jsonFile(input.stateDir, "opencode-legacy.json", config2);
11716
11822
  configPaths.push(file2);
11717
11823
  env.OPENCODE_CONFIG = file2;
11718
- const sessionDir = input.sessionDir ?? join15(input.stateDir, "sessions");
11824
+ const sessionDir = input.sessionDir ?? join16(input.stateDir, "sessions");
11719
11825
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
11720
- env.XDG_DATA_HOME = join15(sessionDir, "data");
11721
- env.XDG_CONFIG_HOME = join15(input.stateDir, "config");
11722
- env.XDG_CACHE_HOME = join15(input.stateDir, "cache");
11723
- env.XDG_STATE_HOME = join15(input.stateDir, "state");
11724
- 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");
11725
11831
  env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";
11726
11832
  env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config2);
11727
11833
  env[KEY4] = input.credential ?? "switcher-local-no-auth";
@@ -11745,7 +11851,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11745
11851
  const rolePolicy = compileOpenCodeModelPolicy({ providerId: providerID, mainModel: input.model, roles: input.compiledPolicy?.roles, preservedAgents: Object.entries(isolated.config.agents ?? {}).map(([name, agent]) => ({ ...agent, name })) });
11746
11852
  const modelRef = openCodeInvocationModel(args, rolePolicy, isolated.config.default_agent);
11747
11853
  const config = { ...isolated.config, ...rolePolicy.config, providers: { [providerID]: { name: "Switcher", env: [KEY4], package: `@opencode-ai/ai/providers/${packageName}`, settings: settings2, models } } };
11748
- const file = join15(input.stateDir, "opencode.json");
11854
+ const file = join16(input.stateDir, "opencode.json");
11749
11855
  await writeFile13(file, openCode2ConfigText(config, providerID, KEY4), { mode: 384, flag: "wx" });
11750
11856
  configPaths.push(file, isolated.instructionFile);
11751
11857
  Object.assign(env, isolated.env);
@@ -11830,7 +11936,7 @@ async function prepareHarnessLaunch(input) {
11830
11936
  validateHarnessVersion(input.harness, input.version);
11831
11937
  if (!compatible(input.harness, input.protocol))
11832
11938
  throw new Error("Harness and provider protocol are incompatible.");
11833
- if (!isAbsolute13(input.stateDir) || !isAbsolute13(input.cwd))
11939
+ if (!isAbsolute14(input.stateDir) || !isAbsolute14(input.cwd))
11834
11940
  throw new Error("Launch state and working directories must be absolute.");
11835
11941
  const compiledPolicy = compileModelPolicy(input.model, input.models, input.modelPolicy);
11836
11942
  if (input.harness === "antigravity" && input.model === antigravityHelperModel && compiledPolicy.roles.fast !== input.model)
@@ -11842,14 +11948,14 @@ async function prepareHarnessLaunch(input) {
11842
11948
  if (unsupported3.length)
11843
11949
  throw new Error(`${input.harness} does not expose native model controls for: ${unsupported3.join(", ")}.`);
11844
11950
  await mkdir10(input.stateDir, { recursive: true, mode: 448 });
11845
- 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 });
11846
11952
  const bridge = input.gatewayHost ? await input.gatewayHost.open({ ...input, compiledPolicy, catalogPath }).catch(async (error) => {
11847
- await rm2(catalogPath, { force: true });
11953
+ await rm3(catalogPath, { force: true });
11848
11954
  throw error;
11849
11955
  }) : createInferenceGateway({ ...input, compiledPolicy, catalogPath });
11850
11956
  const removeCatalog = async () => {
11851
11957
  if (!bridge.retainsState?.())
11852
- await rm2(catalogPath, { force: true });
11958
+ await rm3(catalogPath, { force: true });
11853
11959
  };
11854
11960
  try {
11855
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";
@@ -11870,9 +11976,9 @@ async function prepareHarnessLaunch(input) {
11870
11976
  }
11871
11977
 
11872
11978
  // src/ori-model-policy.ts
11873
- import { isAbsolute as isAbsolute14 } from "path";
11979
+ import { isAbsolute as isAbsolute15 } from "path";
11874
11980
  function prepareOriModelPolicy(target, prepared) {
11875
- if (!isAbsolute14(prepared.executable) || /[\0\r\n]/.test(prepared.executable))
11981
+ if (!isAbsolute15(prepared.executable) || /[\0\r\n]/.test(prepared.executable))
11876
11982
  throw new Error("Ori requires an absolute verified native executable.");
11877
11983
  const entries = Object.entries(prepared.env);
11878
11984
  if (entries.some(([key]) => !/^[A-Z_][A-Z0-9_]*$/.test(key)))
@@ -11896,8 +12002,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
11896
12002
  }
11897
12003
 
11898
12004
  // src/launcher.ts
11899
- import { lstat as lstat13, mkdir as mkdir14, mkdtemp, realpath as realpath8, rm as rm7, writeFile as writeFile18 } from "fs/promises";
11900
- 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";
11901
12007
 
11902
12008
  // src/provider-credential-onboarding.ts
11903
12009
  import { z as z9 } from "zod-v4";
@@ -11957,10 +12063,10 @@ async function verifyOpenCodeAuthentication(credential, fetchImpl) {
11957
12063
  // src/credentials.ts
11958
12064
  import { z as z8 } from "zod-v4";
11959
12065
  import { ExecutableTrustError, repairExecutablePermissions, validateExecutable } from "@hasna/contracts/executable-trust";
11960
- import { constants as constants5 } from "fs";
11961
- import { open as open4, readdir as readdir5, unlink, link, lstat as lstat7 } from "fs/promises";
11962
- import { join as join16, isAbsolute as isAbsolute15 } from "path";
11963
- 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";
11964
12070
  import { execFile as execFile3, spawn } from "child_process";
11965
12071
  import { promisify as promisify3 } from "util";
11966
12072
  import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
@@ -11985,7 +12091,7 @@ var credentialBindingSchema = z8.object({
11985
12091
  kind: z8.literal("vault"),
11986
12092
  key: vaultKeySchema,
11987
12093
  url: z8.string().max(2000).transform(endpoint).optional(),
11988
- 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"),
11989
12095
  operator
11990
12096
  }).strict()])
11991
12097
  }).strict().superRefine((binding, ctx) => {
@@ -12001,13 +12107,13 @@ class CredentialBindings {
12001
12107
  directory;
12002
12108
  constructor(env = process.env) {
12003
12109
  this.env = env;
12004
- this.directory = join16(switcherHome(env), "config", "credential-bindings");
12110
+ this.directory = join17(switcherHome(env), "config", "credential-bindings");
12005
12111
  }
12006
12112
  path(name) {
12007
- return join16(this.directory, parse2(reference, name) + ".json");
12113
+ return join17(this.directory, parse2(reference, name) + ".json");
12008
12114
  }
12009
12115
  async readableDirectory() {
12010
- 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]) {
12011
12117
  let info;
12012
12118
  try {
12013
12119
  info = await lstat7(path);
@@ -12027,7 +12133,7 @@ class CredentialBindings {
12027
12133
  return;
12028
12134
  let file;
12029
12135
  try {
12030
- 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);
12031
12137
  } catch (error) {
12032
12138
  if (error.code === "ENOENT")
12033
12139
  return;
@@ -12056,7 +12162,7 @@ class CredentialBindings {
12056
12162
  return [];
12057
12163
  let entries;
12058
12164
  try {
12059
- entries = await readdir5(this.directory);
12165
+ entries = await readdir6(this.directory);
12060
12166
  } catch (error) {
12061
12167
  if (error.code === "ENOENT")
12062
12168
  return [];
@@ -12076,10 +12182,10 @@ class CredentialBindings {
12076
12182
  if (binding.source.kind === "vault")
12077
12183
  await validateVaultExecutable(binding.source.executable);
12078
12184
  await privateDirectory(switcherHome(this.env));
12079
- await privateDirectory(join16(switcherHome(this.env), "config"));
12185
+ await privateDirectory(join17(switcherHome(this.env), "config"));
12080
12186
  await privateDirectory(this.directory);
12081
- const temporary = join16(this.directory, `.binding-${randomUUID5()}`);
12082
- const file = await open4(temporary, "wx", 384);
12187
+ const temporary = join17(this.directory, `.binding-${randomUUID6()}`);
12188
+ const file = await open5(temporary, "wx", 384);
12083
12189
  try {
12084
12190
  await file.writeFile(JSON.stringify(binding, null, 2) + `
12085
12191
  `);
@@ -12668,7 +12774,7 @@ async function launchCatalog(client, provider, dryRun = false, options = {}) {
12668
12774
  // src/harness-process.ts
12669
12775
  import { spawn as spawn2, spawnSync } from "child_process";
12670
12776
  import { EventEmitter } from "events";
12671
- import { existsSync, openSync, closeSync, writeSync, readSync, constants as constants6 } from "fs";
12777
+ import { existsSync, openSync, closeSync, writeSync, readSync, constants as constants7 } from "fs";
12672
12778
 
12673
12779
  // src/terminal-descriptors.ts
12674
12780
  async function terminalDescriptorDuplicator() {
@@ -12929,7 +13035,7 @@ async function runHarnessProcess(options) {
12929
13035
  process.stdin.on("data", relay);
12930
13036
  process.stdin.resume();
12931
13037
  } else {
12932
- controllingInput = openSync("/dev/tty", constants6.O_RDONLY | constants6.O_NONBLOCK);
13038
+ controllingInput = openSync("/dev/tty", constants7.O_RDONLY | constants7.O_NONBLOCK);
12933
13039
  stty(["raw", "-echo"]);
12934
13040
  const buffer = Buffer.alloc(4096);
12935
13041
  inputTimer = setInterval(() => {
@@ -13196,13 +13302,13 @@ function oriLaunchWarnings(target) {
13196
13302
 
13197
13303
  // src/chatgpt-launch.ts
13198
13304
  import { createHash as createHash13 } from "crypto";
13199
- import { writeFile as writeFile14, rm as rm4 } from "fs/promises";
13200
- import { join as join18 } from "path";
13305
+ import { writeFile as writeFile14, rm as rm5 } from "fs/promises";
13306
+ import { join as join19 } from "path";
13201
13307
  import { fileURLToPath } from "url";
13202
13308
 
13203
13309
  // src/desktop-state.ts
13204
- import { constants as constants7, closeSync as closeSync2, fstatSync, lstatSync, openSync as openSync2, readSync as readSync2 } from "fs";
13205
- import { open as open5, rm as rm3, lstat as lstat8, rename as rename3, chmod as chmod2, copyFile as copyFile2, link as link2 } from "fs/promises";
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";
13206
13312
  import { spawnSync as spawnSync2 } from "child_process";
13207
13313
  import { resolve as resolve9 } from "path";
13208
13314
  import { createHash as createHash12 } from "crypto";
@@ -13264,7 +13370,7 @@ async function safeDesktopSnapshot(path) {
13264
13370
  const info = await lstat8(path);
13265
13371
  admitDesktopFile(info);
13266
13372
  const metadataHash = admitDesktopMetadata(path, info);
13267
- const file = await open5(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
13373
+ const file = await open6(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
13268
13374
  try {
13269
13375
  const opened = await file.stat();
13270
13376
  admitOpenedDesktopFile(info, opened);
@@ -13293,7 +13399,7 @@ function safeDesktopSnapshotSync(path) {
13293
13399
  const info = lstatSync(path);
13294
13400
  admitDesktopFile(info);
13295
13401
  const metadataHash = admitDesktopMetadata(path, info);
13296
- const file = openSync2(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
13402
+ const file = openSync2(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
13297
13403
  try {
13298
13404
  const opened = fstatSync(file);
13299
13405
  admitOpenedDesktopFile(info, opened);
@@ -13331,7 +13437,7 @@ async function preserveDesktopFile(source, destination, expected) {
13331
13437
  if (copied.error || copied.status !== 0)
13332
13438
  throw new Fault(422, "desktop_state_permissions", "Desktop metadata preservation failed.");
13333
13439
  } else
13334
- await copyFile2(source, destination, constants7.COPYFILE_EXCL);
13440
+ await copyFile2(source, destination, constants8.COPYFILE_EXCL);
13335
13441
  if (!sameDesktopSnapshot(await safeDesktopSnapshot(source), expected) || !sameDesktopSnapshot(await safeDesktopSnapshot(destination), expected))
13336
13442
  throw new Fault(409, "desktop_state_changed", "Desktop original preservation readback failed.");
13337
13443
  }
@@ -13348,7 +13454,7 @@ async function exists(path) {
13348
13454
  }
13349
13455
  async function preserveConflict(path) {
13350
13456
  const target = conflictPath(path, "conflict");
13351
- await rename3(path, target);
13457
+ await rename4(path, target);
13352
13458
  return target;
13353
13459
  }
13354
13460
  async function restoreDisplaced(backup, path) {
@@ -13367,14 +13473,14 @@ async function restoreDisplaced(backup, path) {
13367
13473
  }
13368
13474
  throw error;
13369
13475
  }
13370
- await rm3(temporary, { force: true });
13476
+ await rm4(temporary, { force: true });
13371
13477
  if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), snapshot2))
13372
13478
  throw new Fault(409, "desktop_state_changed", `Desktop settings changed after restoration; original retained at ${backup}.`);
13373
13479
  } finally {
13374
13480
  if (await safeDesktopSnapshot(temporary).catch(() => {
13375
13481
  return;
13376
13482
  }) !== undefined)
13377
- await rm3(temporary, { force: true });
13483
+ await rm4(temporary, { force: true });
13378
13484
  }
13379
13485
  }
13380
13486
  async function replaceDesktopFile(path, temporary, expectedCurrent, expectedNew) {
@@ -13390,7 +13496,7 @@ async function replaceDesktopFile(path, temporary, expectedCurrent, expectedNew)
13390
13496
  throw new Fault(409, "desktop_state_changed", "Desktop replacement target appeared concurrently; existing state was preserved.");
13391
13497
  throw error;
13392
13498
  }
13393
- await rm3(temporary, { force: true });
13499
+ await rm4(temporary, { force: true });
13394
13500
  if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), expectedNew)) {
13395
13501
  const preserved = await preserveConflict(path);
13396
13502
  throw new Fault(409, "desktop_state_changed", `Desktop replacement changed after installation; foreign file preserved at ${preserved}.`);
@@ -13401,7 +13507,7 @@ async function replaceDesktopFile(path, temporary, expectedCurrent, expectedNew)
13401
13507
  let displaced = false;
13402
13508
  try {
13403
13509
  try {
13404
- await rename3(path, backup);
13510
+ await rename4(path, backup);
13405
13511
  displaced = true;
13406
13512
  } catch (error) {
13407
13513
  if (error.code === "ENOENT")
@@ -13431,7 +13537,7 @@ async function replaceDesktopFile(path, temporary, expectedCurrent, expectedNew)
13431
13537
  }
13432
13538
  throw error;
13433
13539
  }
13434
- await rm3(temporary, { force: true });
13540
+ await rm4(temporary, { force: true });
13435
13541
  if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), expectedNew)) {
13436
13542
  await restoreDisplaced(backup, path);
13437
13543
  displaced = false;
@@ -13454,7 +13560,7 @@ async function removeDesktopFile(path, expected, guard) {
13454
13560
  }
13455
13561
  const quarantine = conflictPath(path, "remove");
13456
13562
  try {
13457
- await rename3(path, quarantine);
13563
+ await rename4(path, quarantine);
13458
13564
  } catch (error) {
13459
13565
  if (error.code === "ENOENT")
13460
13566
  throw new Fault(409, "desktop_state_changed", "Desktop removal target disappeared; existing state was preserved.");
@@ -13481,7 +13587,7 @@ async function removeDesktopFile(path, expected, guard) {
13481
13587
  throw error;
13482
13588
  }
13483
13589
  }
13484
- await rm3(quarantine, { force: true });
13590
+ await rm4(quarantine, { force: true });
13485
13591
  if (await exists(path))
13486
13592
  throw new Fault(409, "desktop_state_changed", "Desktop removal target appeared concurrently; existing state was preserved.");
13487
13593
  }
@@ -13501,7 +13607,7 @@ async function writeDesktopPrivate(path, text, mode = 384, metadataSource, expec
13501
13607
  await preserveDesktopFile(metadataSource?.path ?? path, temporary, template);
13502
13608
  await chmod2(temporary, 384);
13503
13609
  }
13504
- 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);
13505
13611
  try {
13506
13612
  await file.truncate(0);
13507
13613
  await file.writeFile(text);
@@ -13517,7 +13623,7 @@ async function writeDesktopPrivate(path, text, mode = 384, metadataSource, expec
13517
13623
  if (await safeDesktopSnapshot(temporary).catch(() => {
13518
13624
  return;
13519
13625
  }) !== undefined)
13520
- await rm3(temporary, { force: true });
13626
+ await rm4(temporary, { force: true });
13521
13627
  }
13522
13628
  }
13523
13629
  async function desktopLease(path) {
@@ -13562,11 +13668,11 @@ async function openDesktopLease(path, readOnly2 = false) {
13562
13668
  }
13563
13669
 
13564
13670
  // src/native-state.ts
13565
- import { lstat as lstat9, mkdir as mkdir11, open as open6, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
13566
- 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";
13567
13673
  import { execFileSync as execFileSync3 } from "child_process";
13568
13674
  import { homedir as homedir9, userInfo as userInfo3 } from "os";
13569
- 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";
13570
13676
  function nativeStateRequested(tool, environment = process.env, explicit) {
13571
13677
  if (explicit !== undefined)
13572
13678
  return explicit;
@@ -13613,7 +13719,7 @@ async function info(path) {
13613
13719
  }
13614
13720
  }
13615
13721
  function absolute(value) {
13616
- if (!isAbsolute16(value) || value.includes("\x00"))
13722
+ if (!isAbsolute17(value) || value.includes("\x00"))
13617
13723
  throw new Fault(422, "native_state_path", "The shared native state directory must be an absolute path.");
13618
13724
  return resolve10(value);
13619
13725
  }
@@ -13721,10 +13827,10 @@ async function ensureNativeStateDirectory(path, create = true) {
13721
13827
  async function assertNativeStateIsolation(tool, home, environment = process.env) {
13722
13828
  home = absolute(home);
13723
13829
  const canonical = await resolveNativeState(tool, environment, { create: false });
13724
- 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}`)];
13725
13831
  const contains = (parent, child) => {
13726
13832
  const path = relative5(parent, child);
13727
- return path !== ".." && !path.startsWith("../") && !isAbsolute16(path);
13833
+ return path !== ".." && !path.startsWith("../") && !isAbsolute17(path);
13728
13834
  };
13729
13835
  if (roots.some((root) => root && (contains(root, home) || contains(home, root))))
13730
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.");
@@ -13732,8 +13838,8 @@ async function assertNativeStateIsolation(tool, home, environment = process.env)
13732
13838
  return;
13733
13839
  await assertNativeStateDirectory(home);
13734
13840
  for (const { name } of NATIVE_STATE_ENTRIES[tool]) {
13735
- await ensureNativeStateDirectory(dirname8(join17(home, name)), false);
13736
- if ((await info(join17(home, name)))?.isSymbolicLink())
13841
+ await ensureNativeStateDirectory(dirname8(join18(home, name)), false);
13842
+ if ((await info(join18(home, name)))?.isSymbolicLink())
13737
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.");
13738
13844
  }
13739
13845
  if (tool === "codex") {
@@ -13743,7 +13849,7 @@ async function assertNativeStateIsolation(tool, home, environment = process.env)
13743
13849
  }
13744
13850
  }
13745
13851
  function nativeStateLockPath(state) {
13746
- return join17(state.home, ".switcher-shared-state.lock");
13852
+ return join18(state.home, ".switcher-shared-state.lock");
13747
13853
  }
13748
13854
  function nativeStateLockFault(entry) {
13749
13855
  if (!entry?.isFile() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 63) !== 0)
@@ -13755,7 +13861,7 @@ async function withNativeStateLock(state, operation) {
13755
13861
  const path = nativeStateLockPath(state);
13756
13862
  let handle;
13757
13863
  try {
13758
- handle = await open6(path, "wx", 384);
13864
+ handle = await open7(path, "wx", 384);
13759
13865
  } catch (error) {
13760
13866
  if (error.code !== "EEXIST")
13761
13867
  throw error;
@@ -13780,7 +13886,7 @@ var ownedByUser = (entry) => entry.uid === process.getuid?.();
13780
13886
  var ownerProbe = ownedByUser;
13781
13887
  function strictlyInside(root, path) {
13782
13888
  const suffix = relative5(root, path);
13783
- return suffix !== "" && suffix !== ".." && !suffix.startsWith("../") && !isAbsolute16(suffix);
13889
+ return suffix !== "" && suffix !== ".." && !suffix.startsWith("../") && !isAbsolute17(suffix);
13784
13890
  }
13785
13891
  async function assertCorpusLink(link3, root) {
13786
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)}.`);
@@ -13823,7 +13929,7 @@ async function assertCorpusLink(link3, root) {
13823
13929
  canonical = await inspect(raw, () => realpath6(raw));
13824
13930
  else {
13825
13931
  const parent = await inspect(raw, () => realpath6(raw.slice(0, raw.length - last.length)));
13826
- canonical = join17(parent, last);
13932
+ canonical = join18(parent, last);
13827
13933
  }
13828
13934
  if (canonical === root)
13829
13935
  throw refuse("points at the shared directory itself");
@@ -13853,7 +13959,7 @@ async function assertShareableTree(path, budget = { entries: 0 }, depth = 0, roo
13853
13959
  if (depth === 0)
13854
13960
  await assertNativeStateDirectory(path);
13855
13961
  for await (const child of await opendir(path)) {
13856
- const nested = join17(path, child.name);
13962
+ const nested = join18(path, child.name);
13857
13963
  if (++budget.entries > 1e5)
13858
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)}.`);
13859
13965
  if (child.isSymbolicLink()) {
@@ -13874,12 +13980,12 @@ async function assertShareableTree(path, budget = { entries: 0 }, depth = 0, roo
13874
13980
  }
13875
13981
  }
13876
13982
  async function readCodexStateConfig(home) {
13877
- const path = join17(home, "config.toml"), entry = await info(path);
13983
+ const path = join18(home, "config.toml"), entry = await info(path);
13878
13984
  if (!entry)
13879
13985
  return {};
13880
13986
  if (!entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
13881
13987
  throw new Fault(422, "native_state_config", "The Codex instruction configuration cannot be read safely.");
13882
- const handle = await open6(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
13988
+ const handle = await open7(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
13883
13989
  let config;
13884
13990
  try {
13885
13991
  const opened = await handle.stat();
@@ -13909,11 +14015,11 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
13909
14015
  throw new Fault(422, "native_state_instructions", "Codex instruction configuration has an unsupported value.");
13910
14016
  if (CODEX_INSTRUCTION_FILE_KEYS.has(key)) {
13911
14017
  const path = resolve10(home, value), entry = await info(path);
13912
- const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute16(relativePath);
14018
+ const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute17(relativePath);
13913
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)
13914
14020
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
13915
14021
  await assertSafeAncestors(dirname8(path));
13916
- 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(() => {
13917
14023
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
13918
14024
  });
13919
14025
  try {
@@ -13954,7 +14060,7 @@ async function resolveNativeState(tool, environment = process.env, options = {})
13954
14060
  if (primary !== undefined && legacy !== undefined && absolute(primary) !== absolute(legacy))
13955
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.`);
13956
14062
  const userHome = absolute(environment.HOME ?? homedir9());
13957
- 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}`);
13958
14064
  if (credentialOverlay(selected))
13959
14065
  throw new Fault(422, "native_state_overlay", "An authentication profile cannot be the shared native state directory. Select its original native state directory.");
13960
14066
  const real = primary === undefined && legacy === undefined ? await resolveCorpusLink(selected) : selected;
@@ -14014,7 +14120,7 @@ async function directoryHasEntries(path) {
14014
14120
  }
14015
14121
  }
14016
14122
  async function legacyNativeStateWarnings(root, state) {
14017
- const directory = join17(root, state.tool === "codex" ? "desktop" : "desktop-claude");
14123
+ const directory = join18(root, state.tool === "codex" ? "desktop" : "desktop-claude");
14018
14124
  if (!await info(directory))
14019
14125
  return [];
14020
14126
  await assertNativeStateDirectory(directory);
@@ -14025,12 +14131,12 @@ async function legacyNativeStateWarnings(root, state) {
14025
14131
  throw new Fault(409, "native_state_inventory_limit", "Too many legacy desktop profiles to inspect safely.");
14026
14132
  if (!entry.isDirectory() || entry.isSymbolicLink())
14027
14133
  continue;
14028
- const home = join17(directory, entry.name, ...state.tool === "codex" ? ["codex"] : []);
14134
+ const home = join18(directory, entry.name, ...state.tool === "codex" ? ["codex"] : []);
14029
14135
  if (!await info(home))
14030
14136
  continue;
14031
14137
  await assertNativeStateDirectory(home);
14032
14138
  for (const name of [...NATIVE_STATE_ENTRIES[state.tool].map((item2) => item2.name), ...state.tool === "codex" ? ["state_5.sqlite", "session_index.jsonl"] : []]) {
14033
- const path = join17(home, name), item2 = await info(path);
14139
+ const path = join18(home, name), item2 = await info(path);
14034
14140
  if (!item2 || item2.isSymbolicLink())
14035
14141
  continue;
14036
14142
  if (item2.isFile() && item2.size > 0 || item2.isDirectory() && await directoryHasEntries(path)) {
@@ -14078,13 +14184,13 @@ async function preflightNativeStateProjection(state, overlayHome, plan = false)
14078
14184
  return;
14079
14185
  const contains = (parent, child) => {
14080
14186
  const suffix = relative5(parent, child);
14081
- return suffix !== ".." && !suffix.startsWith("../") && !isAbsolute16(suffix);
14187
+ return suffix !== ".." && !suffix.startsWith("../") && !isAbsolute17(suffix);
14082
14188
  };
14083
14189
  if (contains(state.home, overlayHome) || contains(overlayHome, state.home))
14084
14190
  throw new Fault(422, "native_state_overlap", "The shared corpus and authentication overlay must be separate directories.");
14085
14191
  await assertCodexDatabaseRedirectSafe(state, overlayHome);
14086
14192
  for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
14087
- 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);
14088
14194
  if (corpus)
14089
14195
  await ensureNativeStateDirectory(dirname8(target), false);
14090
14196
  if (overlay)
@@ -14107,7 +14213,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
14107
14213
  const createdFiles = [], createdDirectories = [];
14108
14214
  try {
14109
14215
  for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
14110
- 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);
14111
14217
  const targetParent = dirname8(target), destinationParent = dirname8(destination);
14112
14218
  if (!await info(targetParent))
14113
14219
  await createTrackedDirectory(targetParent, createdDirectories);
@@ -14123,7 +14229,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
14123
14229
  if (entry.kind === "directory")
14124
14230
  await createTrackedDirectory(target, createdDirectories);
14125
14231
  else {
14126
- const file = await open6(target, "wx", 384);
14232
+ const file = await open7(target, "wx", 384);
14127
14233
  await file.close();
14128
14234
  createdFiles.push(target);
14129
14235
  }
@@ -14206,20 +14312,20 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedSta
14206
14312
  if (sharedState && sharedState.tool !== "codex")
14207
14313
  throw new Fault(422, "native_state_tool", "ChatGPT requires the canonical Codex corpus.");
14208
14314
  await privateDirectory(sessionDir);
14209
- const home = join18(sessionDir, "codex"), userData = join18(sessionDir, "electron");
14315
+ const home = join19(sessionDir, "codex"), userData = join19(sessionDir, "electron");
14210
14316
  await privateDirectory(home);
14211
14317
  await privateDirectory(userData);
14212
- const release = await desktopLease(join18(sessionDir, "launch.sqlite"));
14318
+ const release = await desktopLease(join19(sessionDir, "launch.sqlite"));
14213
14319
  let released = false, authText;
14214
- 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");
14215
14321
  const cleanup = async () => {
14216
14322
  if (released)
14217
14323
  return;
14218
14324
  released = true;
14219
14325
  try {
14220
14326
  if (authText !== undefined && await safeDesktopRead(authPath) === authText) {
14221
- await rm4(authPath, { force: true });
14222
- await rm4(receiptPath, { force: true });
14327
+ await rm5(authPath, { force: true });
14328
+ await rm5(receiptPath, { force: true });
14223
14329
  }
14224
14330
  } finally {
14225
14331
  release();
@@ -14242,7 +14348,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedSta
14242
14348
  settings2.push('approval_policy="on-request"');
14243
14349
  if (!settings2.some((setting) => setting.startsWith("sandbox_mode=")))
14244
14350
  settings2.push('sandbox_mode="workspace-write"');
14245
- const configPath = join18(home, "config.toml");
14351
+ const configPath = join19(home, "config.toml");
14246
14352
  const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
14247
14353
  if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
14248
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.");
@@ -14269,7 +14375,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedSta
14269
14375
  `;
14270
14376
  await writeDesktopPrivate(receiptPath, digest(authText));
14271
14377
  await writeDesktopPrivate(authPath, authText);
14272
- const wrapper = join18(stateDir, "chatgpt-codex");
14378
+ const wrapper = join19(stateDir, "chatgpt-codex");
14273
14379
  const overrides = settings2.flatMap((setting) => ["-c", setting]);
14274
14380
  let bridge = "";
14275
14381
  if (sharedState) {
@@ -14315,19 +14421,19 @@ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join("
14315
14421
 
14316
14422
  // src/claude-desktop-launch.ts
14317
14423
  import { writeFile as writeFile17 } from "fs/promises";
14318
- import { join as join21 } from "path";
14424
+ import { join as join22 } from "path";
14319
14425
  // src/desktop-selection.ts
14320
- import { createHash as createHash14, randomUUID as randomUUID6 } from "crypto";
14321
- import { writeFile as writeFile15, rename as rename4 } from "fs/promises";
14322
- 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";
14323
14429
  var hash2 = (text) => createHash14("sha256").update(text).digest("hex");
14324
14430
  var conflict = () => new Fault(409, "desktop_config_changed", "Desktop configuration changed; existing bytes and the recovery receipt were preserved.");
14325
14431
  var invalid3 = () => new Fault(409, "desktop_recovery", "Desktop selection needs recovery by its owning supported version before another launch.");
14326
14432
  var identifier = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,80}$/.test(value);
14327
14433
  var admittedMode = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4095 && (value & 18) === 0;
14328
14434
  var matches = (actual, text, mode, metadataHash) => (actual?.text ?? null) === text && (actual?.mode ?? null) === mode && (actual?.metadataHash ?? null) === metadataHash;
14329
- var originalPath = (library, id2) => join19(library, `.switcher-original-${id2}.bak`);
14330
- 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`);
14331
14437
  function metadata(text) {
14332
14438
  if (text === null)
14333
14439
  return { entries: [] };
@@ -14386,7 +14492,7 @@ async function selectedUnchanged(library, r) {
14386
14492
  const selected = r.previousSelected;
14387
14493
  if (!selected)
14388
14494
  return;
14389
- const current = await safeDesktopRead(join19(library, selected.id + ".json"));
14495
+ const current = await safeDesktopRead(join20(library, selected.id + ".json"));
14390
14496
  if (selected.hash !== undefined) {
14391
14497
  if (selected.hash === null ? current !== undefined : current === undefined || hash2(current) !== selected.hash)
14392
14498
  throw conflict();
@@ -14396,7 +14502,7 @@ async function selectedUnchanged(library, r) {
14396
14502
  function selectedUnchangedSync(library, selected) {
14397
14503
  if (!selected)
14398
14504
  return true;
14399
- const current = safeDesktopSnapshotSync(join19(library, selected.id + ".json"))?.text;
14505
+ const current = safeDesktopSnapshotSync(join20(library, selected.id + ".json"))?.text;
14400
14506
  if (selected.hash !== undefined)
14401
14507
  return selected.hash === null ? current === undefined : current !== undefined && hash2(current) === selected.hash;
14402
14508
  return (current ?? null) === (selected.text ?? null);
@@ -14416,10 +14522,10 @@ async function preservedSelection(library, r, wasApplied) {
14416
14522
  return { backup, prepared };
14417
14523
  }
14418
14524
  async function recoverDesktopSelection(library) {
14419
- const path = join19(library, ".switcher-selection.json"), raw = await safeDesktopRead(path);
14525
+ const path = join20(library, ".switcher-selection.json"), raw = await safeDesktopRead(path);
14420
14526
  if (raw === undefined)
14421
14527
  return;
14422
- 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");
14423
14529
  let currentMeta = await safeDesktopSnapshot(metaPath);
14424
14530
  const r = upgradeReceipt(parsed, currentMeta);
14425
14531
  const currentConfig = await safeDesktopRead(configPath);
@@ -14476,7 +14582,7 @@ async function recoverDesktopSelection(library) {
14476
14582
  const receiptSnapshot = await safeDesktopSnapshot(path);
14477
14583
  if (!receiptSnapshot || receiptSnapshot.text !== raw)
14478
14584
  throw conflict();
14479
- const recoveredPath = path + ".recovered-" + randomUUID6(), retained = retainedReceipt(r);
14585
+ const recoveredPath = path + ".recovered-" + randomUUID7(), retained = retainedReceipt(r);
14480
14586
  if (retained !== raw) {
14481
14587
  await writeFile15(recoveredPath, retained, { mode: 384, flag: "wx" });
14482
14588
  const redacted = await safeDesktopSnapshot(recoveredPath);
@@ -14488,19 +14594,19 @@ async function recoverDesktopSelection(library) {
14488
14594
  await assertMetaRestored();
14489
14595
  const finalReceipt2 = await safeDesktopSnapshot(recoveredPath);
14490
14596
  if (!sameDesktopSnapshot(finalReceipt2, redacted)) {
14491
- const foreignPath = recoveredPath + ".foreign-" + randomUUID6();
14597
+ const foreignPath = recoveredPath + ".foreign-" + randomUUID7();
14492
14598
  if (finalReceipt2 !== undefined)
14493
- await rename4(recoveredPath, foreignPath);
14599
+ await rename5(recoveredPath, foreignPath);
14494
14600
  await writeDesktopPrivate(recoveredPath, retained, 384, undefined, { current: undefined });
14495
14601
  throw new Fault(409, "desktop_config_changed", `Desktop recovery receipt changed; redacted receipt preserved at ${recoveredPath}; foreign receipt preserved at ${foreignPath}.`);
14496
14602
  }
14497
14603
  return;
14498
14604
  }
14499
- await rename4(path, recoveredPath);
14605
+ await rename5(path, recoveredPath);
14500
14606
  const preserveRecovered = async (snapshot2) => {
14501
- const foreignPath = recoveredPath + ".foreign-" + randomUUID6();
14607
+ const foreignPath = recoveredPath + ".foreign-" + randomUUID7();
14502
14608
  if (snapshot2 !== undefined)
14503
- await rename4(recoveredPath, foreignPath);
14609
+ await rename5(recoveredPath, foreignPath);
14504
14610
  await writeDesktopPrivate(recoveredPath, raw, 384, undefined, { current: undefined });
14505
14611
  throw new Fault(409, "desktop_config_changed", `Desktop recovery receipt changed; original receipt preserved at ${recoveredPath}; foreign receipt preserved at ${foreignPath}.`);
14506
14612
  };
@@ -14514,11 +14620,11 @@ async function recoverDesktopSelection(library) {
14514
14620
  }
14515
14621
  async function applyDesktopSelection(library, config, label2, checkpoint) {
14516
14622
  await recoverDesktopSelection(library);
14517
- 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");
14518
14624
  const original = await safeDesktopSnapshot(metaPath), previousMeta = original?.text ?? null, previousMetaMode = original?.mode ?? null, previous = metadata(previousMeta);
14519
- 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;
14520
14626
  const previousSelected = previous.appliedId ? { id: previous.appliedId, hash: previousSelectedText === undefined ? null : hash2(previousSelectedText) } : null;
14521
- 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) + `
14522
14628
  `;
14523
14629
  const appliedMeta = JSON.stringify({ ...previous, appliedId: id2, entries: [...previous.entries, { id: id2, name: label2 }] }, null, 2) + `
14524
14630
  `;
@@ -14597,10 +14703,10 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
14597
14703
  }
14598
14704
 
14599
14705
  // src/claude-user-settings.ts
14600
- import { constants as constants9 } from "fs";
14601
- 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";
14602
14708
  import { homedir as homedir10 } from "os";
14603
- 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";
14604
14710
  var preferences = new Set([
14605
14711
  "$schema",
14606
14712
  "permissions",
@@ -14655,7 +14761,7 @@ async function readSettings(home, created) {
14655
14761
  }))
14656
14762
  return;
14657
14763
  await ensureNativeStateDirectory(home, false);
14658
- const path = join20(home, "settings.json");
14764
+ const path = join21(home, "settings.json");
14659
14765
  const entry = await lstat10(path).catch((error) => {
14660
14766
  if (error.code === "ENOENT")
14661
14767
  return;
@@ -14665,7 +14771,7 @@ async function readSettings(home, created) {
14665
14771
  return;
14666
14772
  if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || entry.uid !== process.getuid?.() || writableByOthers(entry) || entry.size > 1024 * 1024)
14667
14773
  throw invalid4(path);
14668
- const handle = await open7(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
14774
+ const handle = await open8(path, constants10.O_RDONLY | constants10.O_NOFOLLOW);
14669
14775
  try {
14670
14776
  const opened = await handle.stat();
14671
14777
  if (opened.dev !== entry.dev || opened.ino !== entry.ino || opened.nlink !== 1 || opened.size > 1024 * 1024)
@@ -14722,19 +14828,19 @@ function project(settings2, existing, path) {
14722
14828
  }
14723
14829
  async function prepareClaudeUserSettings(overlayHome, environment = process.env, corpusHome, options = {}) {
14724
14830
  overlayHome = resolve11(overlayHome);
14725
- const target = join20(overlayHome, "settings.json");
14831
+ const target = join21(overlayHome, "settings.json");
14726
14832
  const existing = await readSettings(overlayHome, options.write === false ? options.created : undefined);
14727
14833
  if (existing !== undefined) {
14728
14834
  project(existing, true, target);
14729
14835
  return [];
14730
14836
  }
14731
- 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"));
14732
14838
  if (sourceHome === overlayHome)
14733
14839
  return [];
14734
14840
  const source = await readSettings(sourceHome);
14735
14841
  if (source === undefined)
14736
14842
  return [];
14737
- const { settings: settings2, dropped } = project(source, false, join20(sourceHome, "settings.json"));
14843
+ const { settings: settings2, dropped } = project(source, false, join21(sourceHome, "settings.json"));
14738
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(", ")}.`] : [];
14739
14845
  if (options.write === false)
14740
14846
  return warnings;
@@ -14766,9 +14872,9 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
14766
14872
  const check2 = system?.assertAvailable ?? (() => assertClaudeDesktopAvailable(userData));
14767
14873
  await check2();
14768
14874
  await privateDirectory(userData);
14769
- const library = join21(userData, "configLibrary");
14875
+ const library = join22(userData, "configLibrary");
14770
14876
  await privateDirectory(library);
14771
- const release = await desktopLease(join21(library, ".switcher-lease.sqlite"));
14877
+ const release = await desktopLease(join22(library, ".switcher-lease.sqlite"));
14772
14878
  let selection, gateway, closed = false, cleanupError;
14773
14879
  const cleanup = async () => {
14774
14880
  if (closed) {
@@ -14789,7 +14895,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
14789
14895
  };
14790
14896
  try {
14791
14897
  await recoverDesktopSelection(library);
14792
- const localConfig = await safeDesktopRead(join21(userData, "claude_desktop_config.json"));
14898
+ const localConfig = await safeDesktopRead(join22(userData, "claude_desktop_config.json"));
14793
14899
  if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
14794
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.");
14795
14901
  const settingsWarnings = input.sharedState ? await prepareClaudeUserSettings(sessionDir, process.env, input.sharedState.home) : [];
@@ -14803,7 +14909,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
14803
14909
  if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
14804
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.");
14805
14911
  const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
14806
- const catalogPath = join21(input.stateDir, "claude-desktop-policy.json");
14912
+ const catalogPath = join22(input.stateDir, "claude-desktop-policy.json");
14807
14913
  await writeFile17(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
14808
14914
  gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
14809
14915
  selection = await applyDesktopSelection(library, {
@@ -15037,22 +15143,90 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
15037
15143
  }
15038
15144
  }
15039
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
+
15040
15213
  // src/gateway-client.ts
15041
15214
  import { spawn as spawn4 } from "child_process";
15042
15215
  import { closeSync as closeSync3, openSync as openSync3 } from "fs";
15043
- import { rm as rm6 } from "fs/promises";
15044
- import { join as join24 } from "path";
15216
+ import { rm as rm8 } from "fs/promises";
15217
+ import { join as join26 } from "path";
15045
15218
 
15046
15219
  // src/gateway-service.ts
15047
- import { createHash as createHash16, randomBytes as randomBytes2, randomUUID as randomUUID7 } from "crypto";
15048
- import { constants as constants10 } from "fs";
15049
- import { chmod as chmod3, lstat as lstat11, mkdir as mkdir12, open as open8, readdir as readdir7, readFile as readFile8, rename as rename5, rm as rm5, unlink as unlink3 } from "fs/promises";
15050
- 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";
15051
15225
  import { z as z10 } from "zod-v4";
15052
15226
 
15053
15227
  // src/process-table.ts
15054
15228
  import { createHash as createHash15 } from "crypto";
15055
- 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";
15056
15230
  var MAX_PROCESSES = 1e5;
15057
15231
  async function darwinTable() {
15058
15232
  const child = Bun.spawn(["/bin/ps", "-A", "-o", "pid=", "-o", "ppid=", "-o", "lstart="], {
@@ -15078,7 +15252,7 @@ async function darwinTable() {
15078
15252
  async function linuxTable() {
15079
15253
  const boot = (await readFile7("/proc/sys/kernel/random/boot_id", "utf8").catch(() => "")).trim();
15080
15254
  const table = new Map;
15081
- for (const name of await readdir6("/proc")) {
15255
+ for (const name of await readdir7("/proc")) {
15082
15256
  if (!/^\d+$/.test(name) || table.size >= MAX_PROCESSES)
15083
15257
  continue;
15084
15258
  let stat6;
@@ -15238,12 +15412,12 @@ async function linuxPeers(clientPort, serverPort) {
15238
15412
  if (!inodes.size)
15239
15413
  return [];
15240
15414
  const found = [];
15241
- for (const name of await readdir6("/proc")) {
15415
+ for (const name of await readdir7("/proc")) {
15242
15416
  if (!/^\d+$/.test(name))
15243
15417
  continue;
15244
15418
  let descriptors;
15245
15419
  try {
15246
- descriptors = await readdir6(`/proc/${name}/fd`);
15420
+ descriptors = await readdir7(`/proc/${name}/fd`);
15247
15421
  } catch {
15248
15422
  continue;
15249
15423
  }
@@ -15275,12 +15449,12 @@ var DEFAULT_SCAN_MS = 1000;
15275
15449
  var PERSIST_INTERVAL_MS = 5000;
15276
15450
  var USE_PERSIST_INTERVAL_MS = 60000;
15277
15451
  function gatewayPaths(env = process.env) {
15278
- const root = join22(switcherHome(env), "gateway");
15279
- const preferred = join22(root, "control.sock");
15452
+ const root = join24(switcherHome(env), "gateway");
15453
+ const preferred = join24(root, "control.sock");
15280
15454
  const name = `${createHash16("sha256").update(root).digest("hex").slice(0, 16)}.sock`;
15281
- const runtime = process.platform === "linux" && env.XDG_RUNTIME_DIR && isAbsolute17(env.XDG_RUNTIME_DIR) ? join22(env.XDG_RUNTIME_DIR, "switcher", name) : undefined;
15282
- const socket = Buffer.byteLength(preferred) <= SOCKET_PATH_LIMIT ? preferred : runtime && Buffer.byteLength(runtime) <= SOCKET_PATH_LIMIT ? runtime : join22("/tmp", `switcher-${process.getuid?.() ?? 0}`, name);
15283
- 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") };
15284
15458
  }
15285
15459
  var UNTRUSTED_FIX = "Another account may have created it: remove it (or set HASNA_SWITCHER_HOME to a shorter path) and launch again.";
15286
15460
  async function assertPrivateSocketDirectory(directory) {
@@ -15291,7 +15465,7 @@ async function assertPrivateSocketDirectory(directory) {
15291
15465
  async function assertTrustedControlSocket(socket) {
15292
15466
  const missing = () => new Fault(503, "gateway_unavailable", "The Switcher gateway service is not running. Run `switcher gateway status`.");
15293
15467
  try {
15294
- await assertPrivateSocketDirectory(dirname9(socket));
15468
+ await assertPrivateSocketDirectory(dirname10(socket));
15295
15469
  } catch (error) {
15296
15470
  if (error.code === "ENOENT")
15297
15471
  throw missing();
@@ -15327,7 +15501,7 @@ function accountHome() {
15327
15501
  const fields = result.exitCode === 0 ? result.stdout.toString().trim().split(`
15328
15502
  `)[0].split(":") : [];
15329
15503
  const home = fields[process.platform === "darwin" ? 8 : 5];
15330
- if (home && isAbsolute17(home))
15504
+ if (home && isAbsolute18(home))
15331
15505
  passwdHome = resolve13(home);
15332
15506
  } catch {}
15333
15507
  return passwdHome ?? undefined;
@@ -15356,7 +15530,7 @@ function gatewaySettings(env = process.env) {
15356
15530
  };
15357
15531
  }
15358
15532
  async function socketDirectory(paths) {
15359
- const directory = dirname9(paths.socket);
15533
+ const directory = dirname10(paths.socket);
15360
15534
  if (directory === paths.root)
15361
15535
  return;
15362
15536
  await mkdir12(directory, { mode: 448, recursive: true });
@@ -15418,8 +15592,8 @@ var gatewaySchema = z10.object({
15418
15592
  models: z10.array(modelSchema.strip()).min(1).max(20000),
15419
15593
  compiledPolicy: z10.unknown(),
15420
15594
  providerId: z10.string().max(200).optional(),
15421
- catalogPath: z10.string().max(4096).refine(isAbsolute17, "Use an absolute catalog path."),
15422
- 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.")
15423
15597
  }).strict();
15424
15598
  var credentialEnvSchema = z10.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
15425
15599
  var routeSchema = z10.object({ settingsDir: z10.string().max(4096) }).strict();
@@ -15454,6 +15628,17 @@ var endedSchema = staticSchema.omit({ stateDir: true }).extend({ endedAt: z10.nu
15454
15628
  var MAX_FAILED_PORTS = 64;
15455
15629
  var MAX_LOOKUPS_PER_RETRY = 4;
15456
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) || "-";
15457
15642
  var SETTLED_MS = 120000;
15458
15643
  var SETTLED_SCAN_FACTOR = 5;
15459
15644
  var staticFields = (record4) => {
@@ -15475,7 +15660,7 @@ async function liveGateway(socket) {
15475
15660
  }
15476
15661
  }
15477
15662
  async function readPrivateJson(path) {
15478
- 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);
15479
15664
  try {
15480
15665
  const info2 = await file.stat();
15481
15666
  if (!info2.isFile() || info2.size > 128 * 1024 * 1024 || (info2.mode & 63) !== 0 || info2.uid !== process.getuid?.())
@@ -15486,17 +15671,17 @@ async function readPrivateJson(path) {
15486
15671
  }
15487
15672
  }
15488
15673
  async function readRecord(directory, id2) {
15489
- const fixed = staticSchema.parse(await readPrivateJson(join22(directory, `${id2}.json`)));
15674
+ const fixed = staticSchema.parse(await readPrivateJson(join24(directory, `${id2}.json`)));
15490
15675
  if (fixed.id !== id2)
15491
15676
  throw new Error("launch record id mismatch");
15492
- 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), () => {
15493
15678
  return;
15494
15679
  });
15495
15680
  return { ...fixed, ...state ?? { lastUsedAt: fixed.createdAt, lastHolderAt: fixed.createdAt, released: false, holders: [] } };
15496
15681
  }
15497
15682
  async function writePrivate(path, text) {
15498
- const temporary = `${path}.${randomUUID7()}.tmp`;
15499
- const file = await open8(temporary, "wx", 384);
15683
+ const temporary = `${path}.${randomUUID9()}.tmp`;
15684
+ const file = await open10(temporary, "wx", 384);
15500
15685
  try {
15501
15686
  try {
15502
15687
  await file.writeFile(text);
@@ -15504,17 +15689,17 @@ async function writePrivate(path, text) {
15504
15689
  } finally {
15505
15690
  await file.close();
15506
15691
  }
15507
- await rename5(temporary, path);
15692
+ await rename7(temporary, path);
15508
15693
  } catch (error) {
15509
- await rm5(temporary, { force: true }).catch(() => {
15694
+ await rm7(temporary, { force: true }).catch(() => {
15510
15695
  return;
15511
15696
  });
15512
15697
  throw error;
15513
15698
  }
15514
15699
  }
15515
15700
  async function routeSettingsDirectory(path) {
15516
- const profile = dirname9(path);
15517
- 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")
15518
15703
  throw new Fault(400, "invalid_route", "A durable route's settings folder must be an absolute <state>/sessions/claude/<profile>/settings directory.");
15519
15704
  const info2 = await lstat11(path).catch(() => {
15520
15705
  return;
@@ -15523,11 +15708,11 @@ async function routeSettingsDirectory(path) {
15523
15708
  throw new Fault(400, "invalid_route", "A durable route's settings folder must be a private directory owned by this user (mode 0700).");
15524
15709
  return path;
15525
15710
  }
15526
- var routeFile = (record4) => record4.route ? join22(record4.route.settingsDir, `claude-route-${record4.id}.json`) : undefined;
15711
+ var routeFile = (record4) => record4.route ? join24(record4.route.settingsDir, `claude-route-${record4.id}.json`) : undefined;
15527
15712
  async function launchStateDirectory(path) {
15528
15713
  if (path === undefined)
15529
15714
  return;
15530
- 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)))
15531
15716
  throw new Fault(400, "invalid_state_dir", "The launch state directory must be an absolute launch-XXXXXX directory.");
15532
15717
  const info2 = await lstat11(path).catch(() => {
15533
15718
  return;
@@ -15548,6 +15733,7 @@ async function startGatewayService(options = {}) {
15548
15733
  const environmentProbe = options.environmentProbe ?? processesHoldingTokenDigest;
15549
15734
  const connectionPeers = options.connectionPeers ?? loopbackPeers;
15550
15735
  const log = options.log ?? ((line) => console.error(`switcher-gateway ${new Date().toISOString()} ${line}`));
15736
+ const station = logToken(hostname().split(".")[0]);
15551
15737
  const resolver = new CredentialResolver(env);
15552
15738
  const resolveCredential2 = options.resolveCredential ?? ((provider) => resolver.resolve(provider));
15553
15739
  const bindings = new CredentialBindings(env);
@@ -15576,7 +15762,7 @@ async function startGatewayService(options = {}) {
15576
15762
  launch.persistedAt = now();
15577
15763
  if (!launches.has(launch.record.id))
15578
15764
  return;
15579
- 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(() => {
15580
15766
  launch.dirty = true;
15581
15767
  });
15582
15768
  };
@@ -15611,12 +15797,32 @@ async function startGatewayService(options = {}) {
15611
15797
  }
15612
15798
  })();
15613
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
+ };
15614
15818
  const handlerFor = (launch) => createInferenceHandler({
15615
15819
  ...launch.record.gateway,
15616
15820
  compiledPolicy: compiledPolicy(launch.record.gateway.compiledPolicy),
15617
15821
  stateDir: launch.record.stateDir ?? paths.root,
15618
15822
  credential: undefined,
15823
+ ...launch.record.route ? { sessionDir: dirname10(launch.record.route.settingsDir) } : {},
15619
15824
  onRoutingEvent: (event) => {
15825
+ logRefusal(launch, event);
15620
15826
  if (launch.record.released)
15621
15827
  return;
15622
15828
  const bytes = Buffer.byteLength(JSON.stringify(event));
@@ -15634,11 +15840,11 @@ async function startGatewayService(options = {}) {
15634
15840
  byDigest.set(record4.tokenDigest, launch);
15635
15841
  return launch;
15636
15842
  };
15637
- const endedPath = (id2) => join22(paths.ended, `${id2}.json`);
15843
+ const endedPath = (id2) => join24(paths.ended, `${id2}.json`);
15638
15844
  const forgetEnded = async (entry) => {
15639
15845
  if (ended.get(entry.record.tokenDigest) === entry)
15640
15846
  ended.delete(entry.record.tokenDigest);
15641
- await rm5(endedPath(entry.record.id), { force: true }).catch(() => {
15847
+ await rm7(endedPath(entry.record.id), { force: true }).catch(() => {
15642
15848
  return;
15643
15849
  });
15644
15850
  };
@@ -15670,9 +15876,9 @@ async function startGatewayService(options = {}) {
15670
15876
  const token = [keys.ANTHROPIC_AUTH_TOKEN, keys.ANTHROPIC_API_KEY].find((item2) => typeof item2 === "string" && item2 !== "");
15671
15877
  return typeof token === "string" ? token : undefined;
15672
15878
  };
15673
- for (const name of await readdir7(dir).catch(() => [])) {
15879
+ for (const name of await readdir8(dir).catch(() => [])) {
15674
15880
  if (/^claude-settings-[0-9a-f]{32}\.json\.[0-9a-f-]{36}\.tmp$/.test(name)) {
15675
- const path2 = join22(dir, name);
15881
+ const path2 = join24(dir, name);
15676
15882
  try {
15677
15883
  const info2 = await lstat11(path2);
15678
15884
  if (!info2.isFile() || info2.uid !== process.getuid?.() || info2.size > 1024 * 1024)
@@ -15691,13 +15897,13 @@ async function startGatewayService(options = {}) {
15691
15897
  if (token === undefined || sha256(token) !== record4.tokenDigest)
15692
15898
  continue;
15693
15899
  }
15694
- await rm5(path2, { force: true });
15900
+ await rm7(path2, { force: true });
15695
15901
  } catch {}
15696
15902
  continue;
15697
15903
  }
15698
15904
  if (!/^claude-settings-[0-9a-f]{32}\.json$/.test(name))
15699
15905
  continue;
15700
- const path = join22(dir, name);
15906
+ const path = join24(dir, name);
15701
15907
  try {
15702
15908
  const info2 = await lstat11(path);
15703
15909
  if (!info2.isFile() || info2.nlink !== 1)
@@ -15754,15 +15960,15 @@ async function startGatewayService(options = {}) {
15754
15960
  await writePrivate(endedPath(launch.record.id), JSON.stringify(entry.record)).catch(() => {
15755
15961
  return;
15756
15962
  });
15757
- 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(() => {
15758
15964
  return;
15759
15965
  });
15760
- 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(() => {
15761
15967
  return;
15762
15968
  });
15763
15969
  const route2 = end ? undefined : routeFile(launch.record);
15764
15970
  if (route2) {
15765
- await rm5(route2, { force: true }).catch(() => {
15971
+ await rm7(route2, { force: true }).catch(() => {
15766
15972
  return;
15767
15973
  });
15768
15974
  await releaseAdoptedRoutes(launch.record);
@@ -15772,7 +15978,7 @@ async function startGatewayService(options = {}) {
15772
15978
  return;
15773
15979
  });
15774
15980
  if (directory)
15775
- await rm5(directory, { recursive: true, force: true }).catch(() => {
15981
+ await rm7(directory, { recursive: true, force: true }).catch(() => {
15776
15982
  return;
15777
15983
  });
15778
15984
  }
@@ -15876,7 +16082,7 @@ async function startGatewayService(options = {}) {
15876
16082
  return fail();
15877
16083
  const { endedAt: _endedAt, ...fixed } = entry.record;
15878
16084
  const record4 = { ...fixed, ...durable ? { routeRevived: true } : {}, lastUsedAt: at, lastHolderAt: at, released: true, holders };
15879
- await writePrivate(join22(paths.launches, `${record4.id}.json`), JSON.stringify(staticFields(record4)));
16085
+ await writePrivate(join24(paths.launches, `${record4.id}.json`), JSON.stringify(staticFields(record4)));
15880
16086
  const launch = adopt(record4, entry.credential);
15881
16087
  launch.probedAfterLauncher = true;
15882
16088
  track(launch, table, at);
@@ -16008,7 +16214,7 @@ async function startGatewayService(options = {}) {
16008
16214
  const token = randomBytes2(32).toString("base64url"), at = now();
16009
16215
  const record4 = {
16010
16216
  schema: 1,
16011
- id: randomUUID7(),
16217
+ id: randomUUID9(),
16012
16218
  tokenDigest: sha256(token),
16013
16219
  createdAt: at,
16014
16220
  lastUsedAt: at,
@@ -16023,7 +16229,7 @@ async function startGatewayService(options = {}) {
16023
16229
  };
16024
16230
  const launch = adopt(record4, input.credential);
16025
16231
  launch.baseline = new Set([...table.values()].map(processKey));
16026
- await writePrivate(join22(paths.launches, `${record4.id}.json`), JSON.stringify(staticFields(record4)));
16232
+ await writePrivate(join24(paths.launches, `${record4.id}.json`), JSON.stringify(staticFields(record4)));
16027
16233
  await persist(launch, true);
16028
16234
  log(`launch ${record4.id.slice(0, 8)} registered (${record4.gateway.harness}, ${record4.gateway.model})`);
16029
16235
  return { id: record4.id, token, baseUrl: `${url}/${record4.gateway.protocol === "gemini-generate-content" ? "v1beta" : "v1"}`, ...route2 ? { releasesAdoptedRoutes: true } : {} };
@@ -16096,7 +16302,7 @@ async function startGatewayService(options = {}) {
16096
16302
  const controlServer = Bun.serve({ unix: paths.socket, maxRequestBodySize: 256 * 1024 * 1024, fetch: control });
16097
16303
  await chmod3(paths.socket, 384);
16098
16304
  const restoredAt = now();
16099
- for (const name of await readdir7(paths.launches)) {
16305
+ for (const name of await readdir8(paths.launches)) {
16100
16306
  if (!/^[0-9a-f-]{36}\.json$/.test(name))
16101
16307
  continue;
16102
16308
  try {
@@ -16113,11 +16319,11 @@ async function startGatewayService(options = {}) {
16113
16319
  log(`ignored unreadable launch record ${name.slice(0, 8)}`);
16114
16320
  }
16115
16321
  }
16116
- for (const name of await readdir7(paths.ended)) {
16322
+ for (const name of await readdir8(paths.ended)) {
16117
16323
  if (!/^[0-9a-f-]{36}\.json$/.test(name))
16118
16324
  continue;
16119
16325
  try {
16120
- const record4 = endedSchema.parse(await readPrivateJson(join22(paths.ended, name)));
16326
+ const record4 = endedSchema.parse(await readPrivateJson(join24(paths.ended, name)));
16121
16327
  if (record4.id !== name.slice(0, -5))
16122
16328
  throw new Error("ended launch record id mismatch");
16123
16329
  const entry = { record: record4, failed: new Map, lookups: [] };
@@ -16164,9 +16370,9 @@ async function startGatewayService(options = {}) {
16164
16370
  }
16165
16371
 
16166
16372
  // src/gateway-supervisor.ts
16167
- import { randomUUID as randomUUID8 } from "crypto";
16168
- import { lstat as lstat12, mkdir as mkdir13, open as open9, readFile as readFile9, realpath as realpath7, rename as rename6, unlink as unlink4 } from "fs/promises";
16169
- 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";
16170
16376
  var LAUNCHD_LABEL = "com.hasna.switcher.gateway";
16171
16377
  var SYSTEMD_UNIT = "switcher-gateway.service";
16172
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)$/;
@@ -16189,7 +16395,7 @@ async function assertSafeServiceCommand(command, temporaryRoots = TEMPORARY_ROOT
16189
16395
  for (const candidate of new Set([real, path])) {
16190
16396
  if (temporaryRoots.some((root) => candidate === root || candidate.startsWith(`${root}/`)))
16191
16397
  throw refuse(path, `${candidate} is under a temporary directory`);
16192
- for (let current = candidate;; current = dirname10(current)) {
16398
+ for (let current = candidate;; current = dirname11(current)) {
16193
16399
  const info2 = await lstat12(current).catch(() => {
16194
16400
  throw refuse(path, `${current} could not be checked`);
16195
16401
  });
@@ -16199,7 +16405,7 @@ async function assertSafeServiceCommand(command, temporaryRoots = TEMPORARY_ROOT
16199
16405
  if ((info2.mode & 18) !== 0)
16200
16406
  throw refuse(path, `${current} is writable by other accounts`);
16201
16407
  }
16202
- if (current === dirname10(current))
16408
+ if (current === dirname11(current))
16203
16409
  break;
16204
16410
  }
16205
16411
  }
@@ -16214,7 +16420,7 @@ function supervisorFor(env = process.env, platform = process.platform, home = ac
16214
16420
  return platform === "darwin" ? "launchd" : platform === "linux" ? "systemd" : "none";
16215
16421
  }
16216
16422
  function launchdLogPath(home) {
16217
- return join23(home, "Library", "Logs", "Hasna", "switcher-gateway.log");
16423
+ return join25(home, "Library", "Logs", "Hasna", "switcher-gateway.log");
16218
16424
  }
16219
16425
  function requireHome(home) {
16220
16426
  if (!home)
@@ -16223,12 +16429,12 @@ function requireHome(home) {
16223
16429
  }
16224
16430
  function unitPath(supervisor, env = process.env, home = requireHome(accountHome())) {
16225
16431
  if (supervisor === "launchd")
16226
- return join23(home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
16227
- const config = env.XDG_CONFIG_HOME && isAbsolute18(env.XDG_CONFIG_HOME) ? env.XDG_CONFIG_HOME : join23(home, ".config");
16228
- 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);
16229
16435
  }
16230
16436
  function checkCommand(command) {
16231
- 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)))
16232
16438
  throw new Fault(400, "invalid_gateway_command", "The gateway service command must be absolute paths without quotes, backslashes, $, % or control characters.");
16233
16439
  }
16234
16440
  var xml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
@@ -16313,16 +16519,16 @@ async function writeUnit(path, content) {
16313
16519
  });
16314
16520
  if (previous === content)
16315
16521
  return false;
16316
- await mkdir13(dirname10(path), { recursive: true, mode: 493 });
16317
- const temporary = `${path}.${randomUUID8()}.tmp`;
16318
- 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);
16319
16525
  try {
16320
16526
  await file.writeFile(content);
16321
16527
  await file.sync();
16322
16528
  } finally {
16323
16529
  await file.close();
16324
16530
  }
16325
- await rename6(temporary, path);
16531
+ await rename8(temporary, path);
16326
16532
  return true;
16327
16533
  }
16328
16534
  async function installGatewayService(options) {
@@ -16515,7 +16721,7 @@ function createServiceGatewayHost(client, context) {
16515
16721
  catalogPath: input.catalogPath,
16516
16722
  cwd: input.cwd
16517
16723
  };
16518
- 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;
16519
16725
  if (route2)
16520
16726
  await privateDirectory(route2.settingsDir);
16521
16727
  const body2 = {
@@ -16537,10 +16743,18 @@ function createServiceGatewayHost(client, context) {
16537
16743
  durable = false;
16538
16744
  }
16539
16745
  } catch (error) {
16540
- (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.`);
16541
- 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.");
16542
16757
  }
16543
- const routeSettingsFile = durable && route2 ? join24(route2.settingsDir, `claude-route-${registration.id}.json`) : undefined;
16544
16758
  const adoptRoutes = routeSettingsFile !== undefined && registration.releasesAdoptedRoutes === true;
16545
16759
  if (routeSettingsFile && !adoptRoutes)
16546
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.");
@@ -16560,7 +16774,7 @@ function createServiceGatewayHost(client, context) {
16560
16774
  return;
16561
16775
  });
16562
16776
  if (routeSettingsFile)
16563
- await rm6(routeSettingsFile, { force: true }).catch(() => {
16777
+ await rm8(routeSettingsFile, { force: true }).catch(() => {
16564
16778
  return;
16565
16779
  });
16566
16780
  return;
@@ -16591,7 +16805,7 @@ function createServiceGatewayHost(client, context) {
16591
16805
  // src/launcher.ts
16592
16806
  var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
16593
16807
  async function writeOriCodexCatalog(stateDir, models) {
16594
- const path = join25(stateDir, "ori-codex-models.json");
16808
+ const path = join27(stateDir, "ori-codex-models.json");
16595
16809
  const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
16596
16810
  await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
16597
16811
  `, { mode: 384, flag: "wx" });
@@ -16685,7 +16899,7 @@ async function prepareOriForPlan(plan, options) {
16685
16899
  });
16686
16900
  try {
16687
16901
  const shim = prepareOriModelPolicy(request.target, native);
16688
- 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);
16689
16903
  await mkdir14(dir, { mode: 448 });
16690
16904
  await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
16691
16905
  return { contract, prepared: {
@@ -16705,12 +16919,12 @@ async function sharedNativeHome(state, root, profileId, environment = process.en
16705
16919
  const variable = state.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
16706
16920
  const configured = environment[variable] ? resolve14(environment[variable]) : undefined;
16707
16921
  const configuredCorpus = configured !== undefined && await realpath8(configured).catch(() => configured) === state.home;
16708
- 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;
16709
16923
  return { home, settingsEnvironment: configuredCorpus ? { ...environment, CLAUDE_CONFIG_DIR: undefined } : environment };
16710
16924
  }
16711
16925
  var SESSION_DIRECTORY_HARNESSES = ["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie", "claude"];
16712
16926
  function launchSessionDirectory(root, harness, profileId) {
16713
- return join25(root, "sessions", harness, profileId);
16927
+ return join27(root, "sessions", harness, profileId);
16714
16928
  }
16715
16929
  async function checkSharedNativeLaunch(state, root, profileId, options = {}) {
16716
16930
  const warnings = await legacyNativeStateWarnings(root, state);
@@ -16732,11 +16946,11 @@ async function checkSharedNativeLaunch(state, root, profileId, options = {}) {
16732
16946
  }
16733
16947
  function isolatedNativeHome(tool, root, profileId, options = {}, environment = process.env) {
16734
16948
  if (options.desktop)
16735
- return { home: join25(root, "desktop", profileId, "codex"), private: false };
16949
+ return { home: join27(root, "desktop", profileId, "codex"), private: false };
16736
16950
  if (options.claudeDesktop)
16737
- return { home: join25(root, "desktop-claude", profileId), private: false };
16951
+ return { home: join27(root, "desktop-claude", profileId), private: false };
16738
16952
  const configured = environment[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
16739
- 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 };
16740
16954
  }
16741
16955
  async function checkDirectLaunch(root, profileId, harness, options = {}) {
16742
16956
  const desktop = Boolean(options.desktop || options.claudeDesktop);
@@ -16783,6 +16997,8 @@ async function launch(client, profileId, options = {}) {
16783
16997
  throw new Error("--ori-executable requires --backend ori.");
16784
16998
  if (options.desktop && (plan.profile.harness !== "codex" || backend !== "direct"))
16785
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.");
16786
17002
  if (options.claudeDesktop && (options.desktop || plan.profile.harness !== "claude" || backend !== "direct" || options.executable || options.args?.length))
16787
17003
  throw new Error("Claude desktop requires its direct Messages gateway adapter without native CLI overrides.");
16788
17004
  const nativeExecutable = options.desktop?.codexExecutable ?? options.executable;
@@ -16793,9 +17009,9 @@ async function launch(client, profileId, options = {}) {
16793
17009
  validateHarnessVersion("gemini", detection?.version);
16794
17010
  if (backend === "direct" && plan.profile.harness === "aider")
16795
17011
  validateHarnessVersion(plan.profile.harness, detection?.version);
16796
- const root = resolve14(options.stateDir ?? join25(switcherHome(), "state"));
17012
+ const root = resolve14(options.stateDir ?? join27(switcherHome(), "state"));
16797
17013
  await privateDirectory(root);
16798
- const stateDir = await mkdtemp(join25(root, "launch-"));
17014
+ const stateDir = await mkdtemp(join27(root, "launch-"));
16799
17015
  let credential;
16800
17016
  if (backend === "direct") {
16801
17017
  try {
@@ -16803,7 +17019,7 @@ async function launch(client, profileId, options = {}) {
16803
17019
  if (plan.provider.credentialEnv && !credential)
16804
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.`);
16805
17021
  } catch (error) {
16806
- await rm7(stateDir, { recursive: true, force: true });
17022
+ await rm9(stateDir, { recursive: true, force: true });
16807
17023
  throw error;
16808
17024
  }
16809
17025
  }
@@ -16826,13 +17042,21 @@ async function launch(client, profileId, options = {}) {
16826
17042
  routingEventsDropped = Math.min(1e6, routingEventsDropped + 1);
16827
17043
  };
16828
17044
  let gatewayHost;
17045
+ let fallbackHost;
16829
17046
  if (options.gateway === "service" && backend === "direct" && !options.claudeDesktop && process.platform !== "win32") {
17047
+ let client2;
16830
17048
  try {
16831
- const client2 = options.connectGateway ? await options.connectGateway() : (await ensureGatewayService({ command: options.gatewayCommand ?? [process.execPath, Bun.main], supervise: options.gatewaySupervise ?? false })).client;
16832
- 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;
16833
17050
  } catch (error) {
16834
- 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 });
16835
17057
  }
17058
+ if (client2)
17059
+ gatewayHost = createServiceGatewayHost(client2, { holderPid: process.pid, stateDir, credentialEnv: credential ? plan.provider.credentialEnv : undefined, onRoutingEvent, requireDurableRoute: options.requireDurableRoute });
16836
17060
  }
16837
17061
  const finishRunOnce = async (candidate, body2, message) => {
16838
17062
  if (runFinalized)
@@ -16894,7 +17118,7 @@ async function launch(client, profileId, options = {}) {
16894
17118
  cwd: resolve14(options.cwd ?? process.cwd()),
16895
17119
  sharedState
16896
17120
  };
16897
- 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({
16898
17122
  harness: plan.profile.harness,
16899
17123
  baseUrl: plan.provider.baseUrl,
16900
17124
  protocol: plan.provider.protocol,
@@ -16913,7 +17137,7 @@ async function launch(client, profileId, options = {}) {
16913
17137
  cwd: resolve14(options.cwd ?? process.cwd()),
16914
17138
  version: detection?.version,
16915
17139
  sharedState,
16916
- gatewayHost,
17140
+ gatewayHost: gatewayHost ?? fallbackHost,
16917
17141
  ...SESSION_DIRECTORY_HARNESSES.includes(plan.profile.harness) ? { sessionDir: launchSessionDirectory(root, plan.profile.harness, profileId) } : {}
16918
17142
  });
16919
17143
  cleanup = prepared.cleanup;
@@ -16931,7 +17155,7 @@ async function launch(client, profileId, options = {}) {
16931
17155
  prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
16932
17156
  }
16933
17157
  if (options.desktop) {
16934
- 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);
16935
17159
  cleanup = prepared.cleanup;
16936
17160
  }
16937
17161
  for (const warning of [...plan.warnings, ...prepared.warnings])
@@ -17008,7 +17232,13 @@ async function launch(client, profileId, options = {}) {
17008
17232
  interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
17009
17233
  throw preparationSignal;
17010
17234
  }
17011
- 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) }));
17012
17242
  await cleanup?.();
17013
17243
  cleanup = undefined;
17014
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}.`);
@@ -17040,11 +17270,15 @@ async function launch(client, profileId, options = {}) {
17040
17270
  await cleanup?.();
17041
17271
  } finally {
17042
17272
  if (!gatewayHost?.retainedState())
17043
- await rm7(stateDir, { recursive: true, force: true });
17273
+ await rm9(stateDir, { recursive: true, force: true });
17044
17274
  }
17045
17275
  }
17046
17276
  }
17047
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
+
17048
17282
  // src/direct-launch.ts
17049
17283
  import { createHash as createHash17 } from "crypto";
17050
17284
  import { createInterface as createInterface3 } from "readline/promises";
@@ -17152,9 +17386,9 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
17152
17386
 
17153
17387
  // src/native-state-import.ts
17154
17388
  import { createHash as createHash18 } from "crypto";
17155
- import { constants as constants11 } from "fs";
17156
- import { lstat as lstat14, open as open10, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
17157
- 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";
17158
17392
  var MAX_FILES = 1e5;
17159
17393
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
17160
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.");
@@ -17171,12 +17405,12 @@ var identity = (s) => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeM
17171
17405
  var same = (a, b) => JSON.stringify(identity(a)) === JSON.stringify(identity(b));
17172
17406
  var inside3 = (parent, child) => {
17173
17407
  const path = relative8(parent, child);
17174
- return path !== ".." && !path.startsWith("../") && !isAbsolute19(path);
17408
+ return path !== ".." && !path.startsWith("../") && !isAbsolute20(path);
17175
17409
  };
17176
17410
  var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
17177
17411
  async function sessionId(path, expected) {
17178
- const nameId = basename6(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
17179
- 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);
17180
17414
  try {
17181
17415
  const before = await handle.stat();
17182
17416
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
@@ -17219,7 +17453,7 @@ async function checkSessionIdentities(plan) {
17219
17453
  for (const file of plan.files) {
17220
17454
  if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
17221
17455
  continue;
17222
- file.sessionId = await sessionId(join26(plan.source, file.path), file.source);
17456
+ file.sessionId = await sessionId(join28(plan.source, file.path), file.source);
17223
17457
  if (!file.sessionId)
17224
17458
  continue;
17225
17459
  const previous = ids.get(file.sessionId);
@@ -17243,7 +17477,7 @@ async function checkSessionIdentities(plan) {
17243
17477
  for await (const entry of await opendir2(directory)) {
17244
17478
  if (++seen > MAX_FILES || entry.isSymbolicLink())
17245
17479
  throw refused();
17246
- const path = join26(directory, entry.name);
17480
+ const path = join28(directory, entry.name);
17247
17481
  if (entry.isDirectory()) {
17248
17482
  await scan(path, depth + 1);
17249
17483
  continue;
@@ -17260,18 +17494,18 @@ async function checkSessionIdentities(plan) {
17260
17494
  file.existing = true;
17261
17495
  }
17262
17496
  }
17263
- await scan(join26(plan.state.home, "sessions"));
17264
- 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"));
17265
17499
  }
17266
17500
  async function fingerprint2(path, copyTo) {
17267
- const handle = await open10(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
17501
+ const handle = await open12(path, constants12.O_RDONLY | constants12.O_NOFOLLOW);
17268
17502
  let output, complete = false;
17269
17503
  try {
17270
17504
  const before = await handle.stat();
17271
17505
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
17272
17506
  throw refused();
17273
17507
  if (copyTo)
17274
- output = await open10(copyTo, "wx", 384);
17508
+ output = await open12(copyTo, "wx", 384);
17275
17509
  const hash3 = createHash18("sha256"), buffer = Buffer.alloc(64 * 1024);
17276
17510
  let bytes = 0;
17277
17511
  for (;; ) {
@@ -17305,7 +17539,7 @@ async function fingerprint2(path, copyTo) {
17305
17539
  }
17306
17540
  }
17307
17541
  async function planNativeStateImport(state, source, selection) {
17308
- if (!isAbsolute19(source) || source.includes("\x00"))
17542
+ if (!isAbsolute20(source) || source.includes("\x00"))
17309
17543
  throw refused();
17310
17544
  source = resolve15(source);
17311
17545
  if (inside3(source, state.home) || inside3(state.home, source))
@@ -17321,9 +17555,9 @@ async function planNativeStateImport(state, source, selection) {
17321
17555
  async function visit(path, kind) {
17322
17556
  if (++seen > MAX_FILES || path.split("/").length > 32)
17323
17557
  throw refused();
17324
- await ensureNativeStateDirectory(dirname11(join26(source, path)), false);
17325
- await ensureNativeStateDirectory(dirname11(join26(state.home, path)), false);
17326
- 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);
17327
17561
  if (!entry)
17328
17562
  return;
17329
17563
  if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
@@ -17342,7 +17576,7 @@ async function planNativeStateImport(state, source, selection) {
17342
17576
  }
17343
17577
  children.sort((a, b) => a.name.localeCompare(b.name));
17344
17578
  for (const child of children)
17345
- await visit(join26(path, child.name), child.kind);
17579
+ await visit(join28(path, child.name), child.kind);
17346
17580
  } else {
17347
17581
  const value = await fingerprint2(from);
17348
17582
  plan.bytes += value.bytes;
@@ -17396,14 +17630,14 @@ async function applyNativeStateImportUnlocked(plan) {
17396
17630
  throw refused();
17397
17631
  const requiredDirectories = new Set([plan.state.home]);
17398
17632
  for (const path of plan.directories) {
17399
- 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)) {
17400
17634
  requiredDirectories.add(directory);
17401
17635
  if (directory === plan.state.home)
17402
17636
  break;
17403
17637
  }
17404
17638
  }
17405
17639
  for (const file of plan.files.filter((file2) => !file2.existing)) {
17406
- 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)) {
17407
17641
  requiredDirectories.add(directory);
17408
17642
  if (directory === plan.state.home)
17409
17643
  break;
@@ -17424,9 +17658,9 @@ async function applyNativeStateImportUnlocked(plan) {
17424
17658
  for (const file of plan.files) {
17425
17659
  if (file.existing)
17426
17660
  continue;
17427
- 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()}`);
17428
17662
  staged.push({ temporary, target });
17429
- const copied = await fingerprint2(join26(plan.source, file.path), temporary);
17663
+ const copied = await fingerprint2(join28(plan.source, file.path), temporary);
17430
17664
  if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
17431
17665
  throw refused();
17432
17666
  }
@@ -17509,6 +17743,9 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
17509
17743
  switcher launch PROFILE [--backend direct|ori] [--share-native-state | --no-share-native-state] [--cwd DIR] [--executable PATH]
17510
17744
  [--ori-executable PATH] [--state-dir DIR]
17511
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]
17512
17749
  switcher runs list|get [ID]
17513
17750
  switcher credentials bind PRESET --vault-key KEY [--vault-url URL]
17514
17751
  [--vault-cli PATH] [--vault-account ACCOUNT | --vault-operator env]
@@ -17535,6 +17772,24 @@ so background processes the harness leaves running (such as Claude Code's daemon
17535
17772
  keep working after the launch exits. It runs under launchd (macOS) or systemd --user
17536
17773
  (Linux) for the default home and starts automatically. SWITCHER_GATEWAY=local uses
17537
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.
17538
17793
  --reasoning: none, minimal, low, medium, high, xhigh, max, ultra (provider support required).
17539
17794
  --dangerously-bypass-approvals-and-sandbox: full access without prompts or command sandboxing.
17540
17795
  PROTOCOL: anthropic-messages, openai-responses, openai-chat, gemini-generate-content
@@ -17602,7 +17857,7 @@ async function readModelPolicy(file, roleValues) {
17602
17857
  }
17603
17858
  return parse2(modelPolicySchema, { version: 1, roles: roles2 });
17604
17859
  }
17605
- async function main(args = process.argv.slice(2)) {
17860
+ async function main(args = process.argv.slice(2), internal = {}) {
17606
17861
  if (args.length === 1 && args[0] === "__credential-delivery")
17607
17862
  return deliverVaultCredential();
17608
17863
  const split = args.indexOf("--");
@@ -17660,7 +17915,9 @@ async function main(args = process.argv.slice(2)) {
17660
17915
  "keychain-service": { type: "string" },
17661
17916
  "keychain-account": { type: "string" },
17662
17917
  origin: { type: "string", multiple: true },
17663
- "exit-when-idle": { type: "boolean" }
17918
+ "exit-when-idle": { type: "boolean" },
17919
+ check: { type: "boolean" },
17920
+ print: { type: "boolean" }
17664
17921
  } });
17665
17922
  if (values2.help || !positionals.length) {
17666
17923
  console.log(HELP);
@@ -17668,6 +17925,10 @@ async function main(args = process.argv.slice(2)) {
17668
17925
  }
17669
17926
  const [command, action2, id2] = positionals;
17670
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.");
17671
17932
  if (command === "state") {
17672
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"]))
17673
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.");
@@ -17941,7 +18202,7 @@ async function main(args = process.argv.slice(2)) {
17941
18202
  const marked = process.env[`HASNA_${suffix}_STATE_HOME`] !== undefined || process.env[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
17942
18203
  if ((sharedNativeState || shareNativeState === false) && plan.profile.harness === "codex")
17943
18204
  assertHarnessArguments("codex", nativeArgs, { reservedCodexRoots: ["sqlite_home"] });
17944
- const root = resolve16(values2["state-dir"] ?? join27(switcherHome(), "state"));
18205
+ const root = resolve16(values2["state-dir"] ?? join29(switcherHome(), "state"));
17945
18206
  if (backend !== "direct")
17946
18207
  await checkPrivateDirectory(root);
17947
18208
  const nativeWarnings = backend === "direct" ? await checkDirectLaunch(root, profileId, plan.profile.harness, {
@@ -17966,7 +18227,7 @@ async function main(args = process.argv.slice(2)) {
17966
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" } } : {} });
17967
18228
  return;
17968
18229
  }
17969
- 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 });
17970
18231
  return;
17971
18232
  }
17972
18233
  if (editingModel) {
@@ -18076,6 +18337,142 @@ async function main(args = process.argv.slice(2)) {
18076
18337
  await runtime.close();
18077
18338
  }
18078
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
+ }
18079
18476
  function launchGatewayMode() {
18080
18477
  const mode = process.env.SWITCHER_GATEWAY?.trim() || "service";
18081
18478
  if (mode !== "local" && mode !== "service")
@@ -18171,10 +18568,12 @@ if (import.meta.main) {
18171
18568
  else
18172
18569
  main().catch((error) => {
18173
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." } }));
18174
- 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;
18175
18573
  });
18176
18574
  }
18177
18575
  export {
18178
18576
  readModelPolicy,
18179
- main
18577
+ main,
18578
+ ResumeFault
18180
18579
  };