@hasna/switcher 0.2.21 → 0.2.23

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.21";
517
+ var version = "0.2.23";
518
518
 
519
519
  // src/version.ts
520
520
  var VERSION = version;
@@ -1836,6 +1836,17 @@ function claudeContextEnvironment(providerBaseUrl, environment = process.env) {
1836
1836
  return { CLAUDE_CODE_AUTO_COMPACT_WINDOW: "786432" };
1837
1837
  return {};
1838
1838
  }
1839
+ var CLAUDE_ONE_MILLION_CONTEXT = 1e6;
1840
+ function claudeNativeModelId(id, models) {
1841
+ if (/\[1m\]$/i.test(id))
1842
+ return id;
1843
+ const window = models.find((model) => model.id === id)?.contextWindow;
1844
+ return window !== undefined && window >= CLAUDE_ONE_MILLION_CONTEXT ? `${id}[1m]` : id;
1845
+ }
1846
+ var CLAUDE_MODEL_VARIABLES = new Set(["ANTHROPIC_MODEL", "ANTHROPIC_DEFAULT_MODEL", "CLAUDE_CODE_SUBAGENT_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_DEFAULT_FABLE_MODEL"]);
1847
+ function claudeNativeModelEnvironment(env, models) {
1848
+ return Object.fromEntries(Object.entries(env ?? {}).map(([name, value]) => [name, CLAUDE_MODEL_VARIABLES.has(name) ? claudeNativeModelId(value, models) : value]));
1849
+ }
1839
1850
 
1840
1851
  // src/opencode-model-policy.ts
1841
1852
  var routeForAgent = (agent) => {
@@ -2570,7 +2581,7 @@ var openapi_default = {
2570
2581
  openapi: "3.0.3",
2571
2582
  info: {
2572
2583
  title: "Switcher API",
2573
- version: "0.2.21",
2584
+ version: "0.2.23",
2574
2585
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2575
2586
  },
2576
2587
  security: [
@@ -8999,7 +9010,7 @@ async function readCodexAgentConfig(path) {
8999
9010
  }
9000
9011
 
9001
9012
  // src/harnesses.ts
9002
- import { access as access3, lstat as lstat6, mkdir as mkdir10, readFile as readFile6, readdir as readdir4, rename as rename2, writeFile as writeFile13, rm as rm2 } from "fs/promises";
9013
+ import { access as access3, lstat as lstat6, mkdir as mkdir10, open as open3, readFile as readFile6, readdir as readdir4, rename as rename2, writeFile as writeFile13, rm as rm2 } from "fs/promises";
9003
9014
  import { basename as basename2, dirname as dirname7, join as join15, isAbsolute as isAbsolute13, resolve as resolve8 } from "path";
9004
9015
  import { homedir as homedir8, tmpdir } from "os";
9005
9016
  import { createHash as createHash9, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual5 } from "crypto";
@@ -10457,6 +10468,45 @@ async function routeJsonFile(path, value) {
10457
10468
  }
10458
10469
  return path;
10459
10470
  }
10471
+ async function adoptClaudeSettingsRoutes(dir, route2) {
10472
+ let adopted = 0;
10473
+ for (const name of await readdir4(dir).catch(() => [])) {
10474
+ if (!/^claude-settings-[0-9a-f]{32}\.json$/.test(name))
10475
+ continue;
10476
+ const path = join15(dir, name);
10477
+ const info = await lstat6(path).catch(() => {
10478
+ return;
10479
+ });
10480
+ if (!info?.isFile() || info.nlink !== 1 || (info.mode & 63) !== 0 || info.uid !== process.getuid?.())
10481
+ continue;
10482
+ let value;
10483
+ try {
10484
+ value = JSON.parse(await readFile6(path, "utf8"));
10485
+ } catch {
10486
+ continue;
10487
+ }
10488
+ if (!value || typeof value !== "object" || Array.isArray(value) || !("modelPicker" in value))
10489
+ continue;
10490
+ const temporary = `${path}.${randomUUID4()}.tmp`;
10491
+ try {
10492
+ const handle = await open3(temporary, "wx", 384);
10493
+ try {
10494
+ await handle.writeFile(JSON.stringify({ ...value, ...route2 }, null, 2) + `
10495
+ `);
10496
+ await handle.sync();
10497
+ } finally {
10498
+ await handle.close();
10499
+ }
10500
+ await rename2(temporary, path);
10501
+ adopted++;
10502
+ } catch {
10503
+ await rm2(temporary, { force: true }).catch(() => {
10504
+ return;
10505
+ });
10506
+ }
10507
+ }
10508
+ return adopted;
10509
+ }
10460
10510
  async function projectInstructionPaths(cwd) {
10461
10511
  let dir = resolve8(cwd);
10462
10512
  while (true) {
@@ -11123,20 +11173,26 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11123
11173
  return prepareAider(input);
11124
11174
  if (input.harness === "claude") {
11125
11175
  env.ANTHROPIC_BASE_URL = input.baseUrl.replace(/\/v1$/, "");
11126
- Object.assign(env, input.nativePolicy?.env);
11176
+ const nativeModel = (id2) => claudeNativeModelId(id2, input.models);
11177
+ Object.assign(env, claudeNativeModelEnvironment(input.nativePolicy?.env, input.models));
11127
11178
  Object.assign(env, claudeContextEnvironment(providerBaseUrl));
11128
- env.ANTHROPIC_MODEL = input.model;
11129
- env.ANTHROPIC_DEFAULT_MODEL = input.model;
11130
- env.CLAUDE_CODE_SUBAGENT_MODEL = input.compiledPolicy?.roles.subagent ?? input.model;
11179
+ env.ANTHROPIC_MODEL = nativeModel(input.model);
11180
+ env.ANTHROPIC_DEFAULT_MODEL = nativeModel(input.model);
11181
+ env.CLAUDE_CODE_SUBAGENT_MODEL = nativeModel(input.compiledPolicy?.roles.subagent ?? input.model);
11131
11182
  env.ANTHROPIC_API_KEY = "";
11132
11183
  env.ANTHROPIC_AUTH_TOKEN = "";
11133
11184
  env[input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"] = input.credential ?? "switcher-local-no-auth";
11134
- const picker = { modelPicker: { replaceBuiltInOptions: true, options: input.models.map((m) => ({ model: m.id, label: m.name, description: m.description?.slice(0, 300) })) } };
11185
+ const picker = { modelPicker: { replaceBuiltInOptions: true, options: input.models.map((m) => ({ model: nativeModel(m.id), label: m.name, description: m.description?.slice(0, 300) })) } };
11135
11186
  const route2 = input.routeSettingsFile && input.credential ? { env: { ANTHROPIC_BASE_URL: env.ANTHROPIC_BASE_URL, ANTHROPIC_API_KEY: "", ANTHROPIC_AUTH_TOKEN: "", [input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"]: input.credential } } : undefined;
11136
- const file2 = route2 ? await routeJsonFile(input.routeSettingsFile, { ...picker, ...route2 }) : input.sessionDir ? await durableJsonFile(claudeSettingsDirectory(input.sessionDir), "claude-settings", picker) : await jsonFile(input.stateDir, "claude-settings.json", picker);
11187
+ const file2 = route2 ? await routeJsonFile(input.routeSettingsFile, { ...picker, ...route2 }) : input.sessionDir ? await durableJsonFile(claudeSettingsDirectory(input.sessionDir), "claude-picker", picker) : await jsonFile(input.stateDir, "claude-settings.json", picker);
11137
11188
  configPaths.push(file2);
11189
+ if (route2 && input.adoptRoutes) {
11190
+ const adopted = await adoptClaudeSettingsRoutes(dirname7(file2), route2);
11191
+ if (adopted)
11192
+ warnings.push(`Gave this launch's gateway route to ${adopted} earlier Claude settings file${adopted === 1 ? "" : "s"} of this profile; their background sessions use it when their host next starts them.`);
11193
+ }
11138
11194
  warnings.push("Claude managed settings and model allowlists can restrict the generated picker.");
11139
- return { executable, args: ["--settings", file2, "--model", input.model, ...args], env, configPaths, warnings };
11195
+ return { executable, args: ["--settings", file2, "--model", nativeModel(input.model), ...args], env, configPaths, warnings };
11140
11196
  }
11141
11197
  if (input.harness === "codex") {
11142
11198
  const rolePolicy2 = await prepareCodexModelPolicy({ home: input.sharedState?.home, cwd: input.cwd, stateDir: input.stateDir, model: input.model, policy: input.modelPolicy ? { version: 1, ...input.modelPolicy } : undefined, switcherProvider: "switcher", switcherBaseUrl: input.baseUrl });
@@ -11504,7 +11560,7 @@ async function prepareHarnessLaunch(input) {
11504
11560
  };
11505
11561
  try {
11506
11562
  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";
11507
- const prepared = await prepareTransportLaunch({ ...input, providerBaseUrl: input.baseUrl, baseUrl: bridge.baseUrl, credential: bridge.token, authStyle: nativeAuth, compiledPolicy, nativePolicy, routeSettingsFile: input.harness === "claude" ? bridge.routeSettingsFile : undefined });
11563
+ const prepared = await prepareTransportLaunch({ ...input, providerBaseUrl: input.baseUrl, baseUrl: bridge.baseUrl, credential: bridge.token, authStyle: nativeAuth, compiledPolicy, nativePolicy, routeSettingsFile: input.harness === "claude" ? bridge.routeSettingsFile : undefined, adoptRoutes: input.harness === "claude" && bridge.adoptRoutes === true });
11508
11564
  return { ...prepared, configPaths: [...prepared.configPaths, catalogPath], warnings: [...prepared.warnings, "Switcher injects model guidance into every managed inference request and permits only models authorized by the launch policy, including catalog selection when enabled. The gateway translates the selected credential to the provider authentication header. The full catalog remains discoverable."], cleanup: async () => {
11509
11565
  try {
11510
11566
  await prepared.cleanup?.();
@@ -11609,7 +11665,7 @@ async function verifyOpenCodeAuthentication(credential, fetchImpl) {
11609
11665
  import { z as z8 } from "zod-v4";
11610
11666
  import { ExecutableTrustError, repairExecutablePermissions, validateExecutable } from "@hasna/contracts/executable-trust";
11611
11667
  import { constants as constants5 } from "fs";
11612
- import { open as open3, readdir as readdir5, unlink, link, lstat as lstat7 } from "fs/promises";
11668
+ import { open as open4, readdir as readdir5, unlink, link, lstat as lstat7 } from "fs/promises";
11613
11669
  import { join as join16, isAbsolute as isAbsolute15 } from "path";
11614
11670
  import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
11615
11671
  import { execFile as execFile3, spawn } from "child_process";
@@ -11678,7 +11734,7 @@ class CredentialBindings {
11678
11734
  return;
11679
11735
  let file;
11680
11736
  try {
11681
- file = await open3(path, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
11737
+ file = await open4(path, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
11682
11738
  } catch (error) {
11683
11739
  if (error.code === "ENOENT")
11684
11740
  return;
@@ -11730,7 +11786,7 @@ class CredentialBindings {
11730
11786
  await privateDirectory(join16(switcherHome(this.env), "config"));
11731
11787
  await privateDirectory(this.directory);
11732
11788
  const temporary = join16(this.directory, `.binding-${randomUUID5()}`);
11733
- const file = await open3(temporary, "wx", 384);
11789
+ const file = await open4(temporary, "wx", 384);
11734
11790
  try {
11735
11791
  await file.writeFile(JSON.stringify(binding, null, 2) + `
11736
11792
  `);
@@ -12853,7 +12909,7 @@ import { fileURLToPath } from "url";
12853
12909
 
12854
12910
  // src/desktop-state.ts
12855
12911
  import { constants as constants7, closeSync as closeSync2, fstatSync, lstatSync, openSync as openSync2, readSync as readSync2 } from "fs";
12856
- import { open as open4, rm as rm3, lstat as lstat8, rename as rename3, chmod as chmod2, copyFile as copyFile2, link as link2 } from "fs/promises";
12912
+ import { open as open5, rm as rm3, lstat as lstat8, rename as rename3, chmod as chmod2, copyFile as copyFile2, link as link2 } from "fs/promises";
12857
12913
  import { spawnSync as spawnSync2 } from "child_process";
12858
12914
  import { resolve as resolve9 } from "path";
12859
12915
  import { createHash as createHash12 } from "crypto";
@@ -12915,7 +12971,7 @@ async function safeDesktopSnapshot(path) {
12915
12971
  const info = await lstat8(path);
12916
12972
  admitDesktopFile(info);
12917
12973
  const metadataHash = admitDesktopMetadata(path, info);
12918
- const file = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12974
+ const file = await open5(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12919
12975
  try {
12920
12976
  const opened = await file.stat();
12921
12977
  admitOpenedDesktopFile(info, opened);
@@ -13152,7 +13208,7 @@ async function writeDesktopPrivate(path, text, mode = 384, metadataSource, expec
13152
13208
  await preserveDesktopFile(metadataSource?.path ?? path, temporary, template);
13153
13209
  await chmod2(temporary, 384);
13154
13210
  }
13155
- const file = await open4(temporary, constants7.O_RDWR | constants7.O_NOFOLLOW | (template ? 0 : constants7.O_CREAT | constants7.O_EXCL), 384);
13211
+ const file = await open5(temporary, constants7.O_RDWR | constants7.O_NOFOLLOW | (template ? 0 : constants7.O_CREAT | constants7.O_EXCL), 384);
13156
13212
  try {
13157
13213
  await file.truncate(0);
13158
13214
  await file.writeFile(text);
@@ -13213,7 +13269,7 @@ async function openDesktopLease(path, readOnly2 = false) {
13213
13269
  }
13214
13270
 
13215
13271
  // src/native-state.ts
13216
- import { lstat as lstat9, mkdir as mkdir11, open as open5, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
13272
+ import { lstat as lstat9, mkdir as mkdir11, open as open6, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
13217
13273
  import { constants as constants8, lstatSync as lstatSync2, realpathSync } from "fs";
13218
13274
  import { execFileSync as execFileSync3 } from "child_process";
13219
13275
  import { homedir as homedir9, userInfo as userInfo3 } from "os";
@@ -13406,7 +13462,7 @@ async function withNativeStateLock(state, operation) {
13406
13462
  const path = nativeStateLockPath(state);
13407
13463
  let handle;
13408
13464
  try {
13409
- handle = await open5(path, "wx", 384);
13465
+ handle = await open6(path, "wx", 384);
13410
13466
  } catch (error) {
13411
13467
  if (error.code !== "EEXIST")
13412
13468
  throw error;
@@ -13530,7 +13586,7 @@ async function readCodexStateConfig(home) {
13530
13586
  return {};
13531
13587
  if (!entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
13532
13588
  throw new Fault(422, "native_state_config", "The Codex instruction configuration cannot be read safely.");
13533
- const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
13589
+ const handle = await open6(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
13534
13590
  let config;
13535
13591
  try {
13536
13592
  const opened = await handle.stat();
@@ -13564,7 +13620,7 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
13564
13620
  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)
13565
13621
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
13566
13622
  await assertSafeAncestors(dirname8(path));
13567
- const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW).catch(() => {
13623
+ const handle = await open6(path, constants8.O_RDONLY | constants8.O_NOFOLLOW).catch(() => {
13568
13624
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
13569
13625
  });
13570
13626
  try {
@@ -13774,7 +13830,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13774
13830
  if (entry.kind === "directory")
13775
13831
  await createTrackedDirectory(target, createdDirectories);
13776
13832
  else {
13777
- const file = await open5(target, "wx", 384);
13833
+ const file = await open6(target, "wx", 384);
13778
13834
  await file.close();
13779
13835
  createdFiles.push(target);
13780
13836
  }
@@ -14249,7 +14305,7 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
14249
14305
 
14250
14306
  // src/claude-user-settings.ts
14251
14307
  import { constants as constants9 } from "fs";
14252
- import { lstat as lstat10, open as open6, writeFile as writeFile16 } from "fs/promises";
14308
+ import { lstat as lstat10, open as open7, writeFile as writeFile16 } from "fs/promises";
14253
14309
  import { homedir as homedir10 } from "os";
14254
14310
  import { join as join20, relative as relative6, resolve as resolve11 } from "path";
14255
14311
  var preferences = new Set([
@@ -14316,7 +14372,7 @@ async function readSettings(home, created) {
14316
14372
  return;
14317
14373
  if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || entry.uid !== process.getuid?.() || writableByOthers(entry) || entry.size > 1024 * 1024)
14318
14374
  throw invalid4(path);
14319
- const handle = await open6(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
14375
+ const handle = await open7(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
14320
14376
  try {
14321
14377
  const opened = await handle.stat();
14322
14378
  if (opened.dev !== entry.dev || opened.ino !== entry.ino || opened.nlink !== 1 || opened.size > 1024 * 1024)
@@ -14697,7 +14753,7 @@ import { join as join24 } from "path";
14697
14753
  // src/gateway-service.ts
14698
14754
  import { createHash as createHash16, randomBytes as randomBytes2, randomUUID as randomUUID7 } from "crypto";
14699
14755
  import { constants as constants10 } from "fs";
14700
- import { chmod as chmod3, lstat as lstat11, mkdir as mkdir12, open as open7, readdir as readdir7, rename as rename5, rm as rm5, unlink as unlink3 } from "fs/promises";
14756
+ import { chmod as chmod3, lstat as lstat11, mkdir as mkdir12, open as open8, readdir as readdir7, readFile as readFile8, rename as rename5, rm as rm5, unlink as unlink3 } from "fs/promises";
14701
14757
  import { basename as basename5, dirname as dirname9, isAbsolute as isAbsolute17, join as join22, resolve as resolve13 } from "path";
14702
14758
  import { z as z10 } from "zod-v4";
14703
14759
 
@@ -14916,6 +14972,7 @@ var MAX_HOLDERS = 4096;
14916
14972
  var MAX_PROBE_CANDIDATES = 4096;
14917
14973
  var PROBE_INTERVAL_MS = 60000;
14918
14974
  var ENDED_MS = 30 * 24 * 3600000;
14975
+ var ADOPTION_TEMP_STALE_MS = 60000;
14919
14976
  var MAX_ENDED = 1000;
14920
14977
  var REVIVE_RETRY_MS = 5000;
14921
14978
  var MAX_EVENTS = 1000;
@@ -15125,7 +15182,7 @@ async function liveGateway(socket) {
15125
15182
  }
15126
15183
  }
15127
15184
  async function readPrivateJson(path) {
15128
- const file = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
15185
+ const file = await open8(path, constants10.O_RDONLY | constants10.O_NOFOLLOW | constants10.O_NONBLOCK);
15129
15186
  try {
15130
15187
  const info2 = await file.stat();
15131
15188
  if (!info2.isFile() || info2.size > 128 * 1024 * 1024 || (info2.mode & 63) !== 0 || info2.uid !== process.getuid?.())
@@ -15146,14 +15203,21 @@ async function readRecord(directory, id2) {
15146
15203
  }
15147
15204
  async function writePrivate(path, text) {
15148
15205
  const temporary = `${path}.${randomUUID7()}.tmp`;
15149
- const file = await open7(temporary, "wx", 384);
15206
+ const file = await open8(temporary, "wx", 384);
15150
15207
  try {
15151
- await file.writeFile(text);
15152
- await file.sync();
15153
- } finally {
15154
- await file.close();
15208
+ try {
15209
+ await file.writeFile(text);
15210
+ await file.sync();
15211
+ } finally {
15212
+ await file.close();
15213
+ }
15214
+ await rename5(temporary, path);
15215
+ } catch (error) {
15216
+ await rm5(temporary, { force: true }).catch(() => {
15217
+ return;
15218
+ });
15219
+ throw error;
15155
15220
  }
15156
- await rename5(temporary, path);
15157
15221
  }
15158
15222
  async function routeSettingsDirectory(path) {
15159
15223
  const profile = dirname9(path);
@@ -15297,6 +15361,65 @@ async function startGatewayService(options = {}) {
15297
15361
  `).catch(() => {
15298
15362
  return;
15299
15363
  });
15364
+ await releaseAdoptedRoutes(record3);
15365
+ };
15366
+ const releaseAdoptedRoutes = async (record3) => {
15367
+ if (!record3.route)
15368
+ return;
15369
+ const dir = record3.route.settingsDir;
15370
+ const tokenOf = (value) => {
15371
+ if (!value || typeof value !== "object" || Array.isArray(value))
15372
+ return;
15373
+ const env2 = value.env;
15374
+ if (!env2 || typeof env2 !== "object" || Array.isArray(env2))
15375
+ return;
15376
+ const keys = env2;
15377
+ const token = [keys.ANTHROPIC_AUTH_TOKEN, keys.ANTHROPIC_API_KEY].find((item2) => typeof item2 === "string" && item2 !== "");
15378
+ return typeof token === "string" ? token : undefined;
15379
+ };
15380
+ for (const name of await readdir7(dir).catch(() => [])) {
15381
+ if (/^claude-settings-[0-9a-f]{32}\.json\.[0-9a-f-]{36}\.tmp$/.test(name)) {
15382
+ const path2 = join22(dir, name);
15383
+ try {
15384
+ const info2 = await lstat11(path2);
15385
+ if (!info2.isFile() || info2.uid !== process.getuid?.() || info2.size > 1024 * 1024)
15386
+ continue;
15387
+ let value;
15388
+ try {
15389
+ value = JSON.parse(await readFile8(path2, "utf8"));
15390
+ } catch {
15391
+ value = undefined;
15392
+ }
15393
+ if (value === undefined) {
15394
+ if (Date.now() - info2.mtimeMs <= ADOPTION_TEMP_STALE_MS)
15395
+ continue;
15396
+ } else {
15397
+ const token = tokenOf(value);
15398
+ if (token === undefined || sha256(token) !== record3.tokenDigest)
15399
+ continue;
15400
+ }
15401
+ await rm5(path2, { force: true });
15402
+ } catch {}
15403
+ continue;
15404
+ }
15405
+ if (!/^claude-settings-[0-9a-f]{32}\.json$/.test(name))
15406
+ continue;
15407
+ const path = join22(dir, name);
15408
+ try {
15409
+ const info2 = await lstat11(path);
15410
+ if (!info2.isFile() || info2.nlink !== 1)
15411
+ continue;
15412
+ const value = await readPrivateJson(path);
15413
+ if (!value || typeof value !== "object" || Array.isArray(value))
15414
+ continue;
15415
+ const { env: _env, ...picker } = value;
15416
+ const token = tokenOf(value);
15417
+ if (token === undefined || sha256(token) !== record3.tokenDigest)
15418
+ continue;
15419
+ await writePrivate(path, JSON.stringify(picker, null, 2) + `
15420
+ `);
15421
+ } catch {}
15422
+ }
15300
15423
  };
15301
15424
  const expireEnded = async (entry) => {
15302
15425
  await forgetEnded(entry);
@@ -15345,10 +15468,12 @@ async function startGatewayService(options = {}) {
15345
15468
  return;
15346
15469
  });
15347
15470
  const route2 = end ? undefined : routeFile(launch.record);
15348
- if (route2)
15471
+ if (route2) {
15349
15472
  await rm5(route2, { force: true }).catch(() => {
15350
15473
  return;
15351
15474
  });
15475
+ await releaseAdoptedRoutes(launch.record);
15476
+ }
15352
15477
  if (removeState && launch.record.stateDir) {
15353
15478
  const directory = await launchStateDirectory(launch.record.stateDir).catch(() => {
15354
15479
  return;
@@ -15608,7 +15733,7 @@ async function startGatewayService(options = {}) {
15608
15733
  await writePrivate(join22(paths.launches, `${record3.id}.json`), JSON.stringify(staticFields(record3)));
15609
15734
  await persist(launch, true);
15610
15735
  log(`launch ${record3.id.slice(0, 8)} registered (${record3.gateway.harness}, ${record3.gateway.model})`);
15611
- return { id: record3.id, token, baseUrl: `${url}/${record3.gateway.protocol === "gemini-generate-content" ? "v1beta" : "v1"}` };
15736
+ return { id: record3.id, token, baseUrl: `${url}/${record3.gateway.protocol === "gemini-generate-content" ? "v1beta" : "v1"}`, ...route2 ? { releasesAdoptedRoutes: true } : {} };
15612
15737
  };
15613
15738
  const release = async (launch) => {
15614
15739
  const table = await processTable().catch(() => {
@@ -15747,7 +15872,7 @@ async function startGatewayService(options = {}) {
15747
15872
 
15748
15873
  // src/gateway-supervisor.ts
15749
15874
  import { randomUUID as randomUUID8 } from "crypto";
15750
- import { lstat as lstat12, mkdir as mkdir13, open as open8, readFile as readFile8, realpath as realpath7, rename as rename6, unlink as unlink4 } from "fs/promises";
15875
+ import { lstat as lstat12, mkdir as mkdir13, open as open9, readFile as readFile9, realpath as realpath7, rename as rename6, unlink as unlink4 } from "fs/promises";
15751
15876
  import { dirname as dirname10, isAbsolute as isAbsolute18, join as join23 } from "path";
15752
15877
  var LAUNCHD_LABEL = "com.hasna.switcher.gateway";
15753
15878
  var SYSTEMD_UNIT = "switcher-gateway.service";
@@ -15890,14 +16015,14 @@ var defaultRunner = async (argv) => {
15890
16015
  }
15891
16016
  };
15892
16017
  async function writeUnit(path, content) {
15893
- const previous = await readFile8(path, "utf8").catch(() => {
16018
+ const previous = await readFile9(path, "utf8").catch(() => {
15894
16019
  return;
15895
16020
  });
15896
16021
  if (previous === content)
15897
16022
  return false;
15898
16023
  await mkdir13(dirname10(path), { recursive: true, mode: 493 });
15899
16024
  const temporary = `${path}.${randomUUID8()}.tmp`;
15900
- const file = await open8(temporary, "wx", 420);
16025
+ const file = await open9(temporary, "wx", 420);
15901
16026
  try {
15902
16027
  await file.writeFile(content);
15903
16028
  await file.sync();
@@ -16123,13 +16248,16 @@ function createServiceGatewayHost(client, context) {
16123
16248
  return createInferenceGateway(input);
16124
16249
  }
16125
16250
  const routeSettingsFile = durable && route2 ? join24(route2.settingsDir, `claude-route-${registration.id}.json`) : undefined;
16251
+ const adoptRoutes = routeSettingsFile !== undefined && registration.releasesAdoptedRoutes === true;
16252
+ if (routeSettingsFile && !adoptRoutes)
16253
+ (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.");
16126
16254
  const lease = { id: registration.id, attached: attachedPid !== undefined, retained: false, done: false };
16127
16255
  leases.push(lease);
16128
16256
  if (attachedPid !== undefined)
16129
16257
  attaching.push(client.attach(lease.id, attachedPid).catch(() => {
16130
16258
  return;
16131
16259
  }));
16132
- return { baseUrl: registration.baseUrl, token: registration.token, ...routeSettingsFile ? { routeSettingsFile } : {}, retainsState: () => lease.retained, cleanup: async () => {
16260
+ return { baseUrl: registration.baseUrl, token: registration.token, ...routeSettingsFile ? { routeSettingsFile } : {}, ...adoptRoutes ? { adoptRoutes } : {}, retainsState: () => lease.retained, cleanup: async () => {
16133
16261
  if (lease.done)
16134
16262
  return;
16135
16263
  lease.done = true;
@@ -16732,7 +16860,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
16732
16860
  // src/native-state-import.ts
16733
16861
  import { createHash as createHash18 } from "crypto";
16734
16862
  import { constants as constants11 } from "fs";
16735
- import { lstat as lstat14, open as open9, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
16863
+ import { lstat as lstat14, open as open10, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
16736
16864
  import { basename as basename6, dirname as dirname11, isAbsolute as isAbsolute19, join as join26, relative as relative8, resolve as resolve15 } from "path";
16737
16865
  var MAX_FILES = 1e5;
16738
16866
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
@@ -16755,7 +16883,7 @@ var inside3 = (parent, child) => {
16755
16883
  var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
16756
16884
  async function sessionId(path, expected) {
16757
16885
  const nameId = basename6(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
16758
- const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
16886
+ const handle = await open10(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
16759
16887
  try {
16760
16888
  const before = await handle.stat();
16761
16889
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
@@ -16843,14 +16971,14 @@ async function checkSessionIdentities(plan) {
16843
16971
  await scan(join26(plan.state.home, "archived_sessions"));
16844
16972
  }
16845
16973
  async function fingerprint2(path, copyTo) {
16846
- const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
16974
+ const handle = await open10(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
16847
16975
  let output, complete = false;
16848
16976
  try {
16849
16977
  const before = await handle.stat();
16850
16978
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
16851
16979
  throw refused();
16852
16980
  if (copyTo)
16853
- output = await open9(copyTo, "wx", 384);
16981
+ output = await open10(copyTo, "wx", 384);
16854
16982
  const hash3 = createHash18("sha256"), buffer = Buffer.alloc(64 * 1024);
16855
16983
  let bytes = 0;
16856
16984
  for (;; ) {
@@ -14,6 +14,7 @@ type Registration = {
14
14
  id: string;
15
15
  token: string;
16
16
  baseUrl: string;
17
+ releasesAdoptedRoutes?: boolean;
17
18
  };
18
19
  type Release = {
19
20
  retained: boolean;
@@ -36,6 +36,8 @@ export type HarnessLaunchInput = {
36
36
  * route in its env block, so a session the background host restarts keeps it.
37
37
  */
38
38
  routeSettingsFile?: string;
39
+ /** Claude only: give the durable route to the profile's earlier picker files (see GatewayLease.adoptRoutes). */
40
+ adoptRoutes?: boolean;
39
41
  };
40
42
  export type PreparedLaunch = {
41
43
  executable: string;