@hasna/switcher 0.2.20 → 0.2.21

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.20";
517
+ var version = "0.2.21";
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 join26, resolve as resolve16 } from "path";
1112
+ import { join as join27, resolve as resolve16 } from "path";
1113
1113
 
1114
1114
  // src/http.ts
1115
1115
  var MAX_BYTES = 16 * 1024 * 1024;
@@ -2570,7 +2570,7 @@ var openapi_default = {
2570
2570
  openapi: "3.0.3",
2571
2571
  info: {
2572
2572
  title: "Switcher API",
2573
- version: "0.2.20",
2573
+ version: "0.2.21",
2574
2574
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2575
2575
  },
2576
2576
  security: [
@@ -10444,6 +10444,19 @@ async function durableJsonFile(dir, prefix, value) {
10444
10444
  }
10445
10445
  return path;
10446
10446
  }
10447
+ async function routeJsonFile(path, value) {
10448
+ if (!/^claude-route-[0-9a-f-]{36}\.json$/.test(basename2(path)))
10449
+ throw new Error("A Claude route settings file must be named claude-route-<launch id>.json.");
10450
+ await privateDirectory(dirname7(path));
10451
+ await writeFile13(path, JSON.stringify(value, null, 2) + `
10452
+ `, { mode: 384, flag: "wx" });
10453
+ const info = await lstat6(path);
10454
+ if (!info.isFile() || (info.mode & 63) !== 0 || info.uid !== process.getuid?.()) {
10455
+ await rm2(path, { force: true });
10456
+ throw new Error("The Claude route settings file could not be created owner-only.");
10457
+ }
10458
+ return path;
10459
+ }
10447
10460
  async function projectInstructionPaths(cwd) {
10448
10461
  let dir = resolve8(cwd);
10449
10462
  while (true) {
@@ -11119,7 +11132,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11119
11132
  env.ANTHROPIC_AUTH_TOKEN = "";
11120
11133
  env[input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"] = input.credential ?? "switcher-local-no-auth";
11121
11134
  const picker = { modelPicker: { replaceBuiltInOptions: true, options: input.models.map((m) => ({ model: m.id, label: m.name, description: m.description?.slice(0, 300) })) } };
11122
- const file2 = input.sessionDir ? await durableJsonFile(claudeSettingsDirectory(input.sessionDir), "claude-settings", picker) : await jsonFile(input.stateDir, "claude-settings.json", picker);
11135
+ 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);
11123
11137
  configPaths.push(file2);
11124
11138
  warnings.push("Claude managed settings and model allowlists can restrict the generated picker.");
11125
11139
  return { executable, args: ["--settings", file2, "--model", input.model, ...args], env, configPaths, warnings };
@@ -11490,7 +11504,7 @@ async function prepareHarnessLaunch(input) {
11490
11504
  };
11491
11505
  try {
11492
11506
  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";
11493
- const prepared = await prepareTransportLaunch({ ...input, providerBaseUrl: input.baseUrl, baseUrl: bridge.baseUrl, credential: bridge.token, authStyle: nativeAuth, compiledPolicy, nativePolicy });
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 });
11494
11508
  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 () => {
11495
11509
  try {
11496
11510
  await prepared.cleanup?.();
@@ -11533,8 +11547,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
11533
11547
  }
11534
11548
 
11535
11549
  // src/launcher.ts
11536
- import { lstat as lstat13, mkdir as mkdir14, mkdtemp, realpath as realpath8, rm as rm6, writeFile as writeFile18 } from "fs/promises";
11537
- import { join as join24, relative as relative7, resolve as resolve14 } from "path";
11550
+ import { lstat as lstat13, mkdir as mkdir14, mkdtemp, realpath as realpath8, rm as rm7, writeFile as writeFile18 } from "fs/promises";
11551
+ import { join as join25, relative as relative7, resolve as resolve14 } from "path";
11538
11552
 
11539
11553
  // src/provider-credential-onboarding.ts
11540
11554
  import { z as z9 } from "zod-v4";
@@ -14677,6 +14691,8 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
14677
14691
  // src/gateway-client.ts
14678
14692
  import { spawn as spawn4 } from "child_process";
14679
14693
  import { closeSync as closeSync3, openSync as openSync3 } from "fs";
14694
+ import { rm as rm6 } from "fs/promises";
14695
+ import { join as join24 } from "path";
14680
14696
 
14681
14697
  // src/gateway-service.ts
14682
14698
  import { createHash as createHash16, randomBytes as randomBytes2, randomUUID as randomUUID7 } from "crypto";
@@ -15056,12 +15072,14 @@ var gatewaySchema = z10.object({
15056
15072
  cwd: z10.string().max(4096).refine(isAbsolute17, "Use an absolute working directory.")
15057
15073
  }).strict();
15058
15074
  var credentialEnvSchema = z10.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
15075
+ var routeSchema = z10.object({ settingsDir: z10.string().max(4096) }).strict();
15059
15076
  var registrationSchema = z10.object({
15060
15077
  holderPid: z10.number().int().positive(),
15061
15078
  gateway: gatewaySchema,
15062
15079
  credential: z10.string().min(1).max(64000).refine((value) => !/[\x00-\x1f\x7f]/.test(value), "Credential contains control characters.").optional(),
15063
15080
  credentialEnv: credentialEnvSchema.optional(),
15064
- stateDir: z10.string().max(4096).optional()
15081
+ stateDir: z10.string().max(4096).optional(),
15082
+ route: routeSchema.optional()
15065
15083
  }).strict();
15066
15084
  var holderSchema = z10.object({ pid: z10.number().int().positive(), start: z10.string().min(1).max(200) }).strict();
15067
15085
  var credentialSourceSchema = z10.discriminatedUnion("source", [
@@ -15077,7 +15095,9 @@ var staticSchema = z10.object({
15077
15095
  launcherPid: z10.number().int().positive(),
15078
15096
  gateway: gatewaySchema,
15079
15097
  credential: credentialSourceSchema,
15080
- stateDir: z10.string().max(4096).optional()
15098
+ stateDir: z10.string().max(4096).optional(),
15099
+ route: routeSchema.optional(),
15100
+ routeRevived: z10.literal(true).optional()
15081
15101
  }).strict();
15082
15102
  var holderStateSchema = z10.object({ lastUsedAt: z10.number(), lastHolderAt: z10.number(), released: z10.boolean(), holders: z10.array(holderSchema).max(MAX_HOLDERS), extendedAt: z10.number().optional() }).strict();
15083
15103
  var endedSchema = staticSchema.omit({ stateDir: true }).extend({ endedAt: z10.number() }).strict();
@@ -15135,6 +15155,18 @@ async function writePrivate(path, text) {
15135
15155
  }
15136
15156
  await rename5(temporary, path);
15137
15157
  }
15158
+ async function routeSettingsDirectory(path) {
15159
+ const profile = dirname9(path);
15160
+ if (!isAbsolute17(path) || resolve13(path) !== path || basename5(path) !== "settings" || basename5(dirname9(profile)) !== "claude" || basename5(dirname9(dirname9(profile))) !== "sessions")
15161
+ throw new Fault(400, "invalid_route", "A durable route's settings folder must be an absolute <state>/sessions/claude/<profile>/settings directory.");
15162
+ const info2 = await lstat11(path).catch(() => {
15163
+ return;
15164
+ });
15165
+ if (!info2?.isDirectory() || info2.isSymbolicLink() || info2.uid !== process.getuid?.() || (info2.mode & 63) !== 0)
15166
+ throw new Fault(400, "invalid_route", "A durable route's settings folder must be a private directory owned by this user (mode 0700).");
15167
+ return path;
15168
+ }
15169
+ var routeFile = (record3) => record3.route ? join22(record3.route.settingsDir, `claude-route-${record3.id}.json`) : undefined;
15138
15170
  async function launchStateDirectory(path) {
15139
15171
  if (path === undefined)
15140
15172
  return;
@@ -15253,11 +15285,28 @@ async function startGatewayService(options = {}) {
15253
15285
  return;
15254
15286
  });
15255
15287
  };
15288
+ const retireRoute = async (record3) => {
15289
+ const file = routeFile(record3);
15290
+ if (!file)
15291
+ return;
15292
+ const info2 = await lstat11(file).catch(() => {
15293
+ return;
15294
+ });
15295
+ if (info2?.isFile() && info2.uid === process.getuid?.())
15296
+ await writePrivate(file, `{}
15297
+ `).catch(() => {
15298
+ return;
15299
+ });
15300
+ };
15301
+ const expireEnded = async (entry) => {
15302
+ await forgetEnded(entry);
15303
+ await retireRoute(entry.record);
15304
+ };
15256
15305
  const pruneEnded = async (at) => {
15257
15306
  const entries = [...ended.values()].sort((a, b) => a.record.endedAt - b.record.endedAt);
15258
15307
  for (const [index, entry] of entries.entries())
15259
15308
  if (at - entry.record.endedAt > ENDED_MS || entries.length - index > MAX_ENDED)
15260
- await forgetEnded(entry);
15309
+ await expireEnded(entry);
15261
15310
  };
15262
15311
  const endedEntry = (launch) => {
15263
15312
  const { stateDir: _state, ...fixed } = staticFields(launch.record);
@@ -15295,6 +15344,11 @@ async function startGatewayService(options = {}) {
15295
15344
  await rm5(join22(paths.launches, `${launch.record.id}.json`), { force: true }).catch(() => {
15296
15345
  return;
15297
15346
  });
15347
+ const route2 = end ? undefined : routeFile(launch.record);
15348
+ if (route2)
15349
+ await rm5(route2, { force: true }).catch(() => {
15350
+ return;
15351
+ });
15298
15352
  if (removeState && launch.record.stateDir) {
15299
15353
  const directory = await launchStateDirectory(launch.record.stateDir).catch(() => {
15300
15354
  return;
@@ -15365,7 +15419,7 @@ async function startGatewayService(options = {}) {
15365
15419
  return entry.reviving;
15366
15420
  const at = now();
15367
15421
  if (at - entry.record.endedAt > ENDED_MS) {
15368
- forgetEnded(entry);
15422
+ expireEnded(entry);
15369
15423
  return;
15370
15424
  }
15371
15425
  const failedAt = entry.failed.get(clientPort);
@@ -15389,27 +15443,28 @@ async function startGatewayService(options = {}) {
15389
15443
  try {
15390
15444
  await entry.settled;
15391
15445
  const [peers, table] = await Promise.all([connectionPeers(clientPort, serverPort), processTable()]);
15392
- const held = new Set([...launches.values()].flatMap((launch2) => liveHolders(launch2, table).map((holder) => holder.pid)));
15446
+ const held = new Set([...launches.values()].filter((launch2) => !launch2.record.routeRevived).flatMap((launch2) => liveHolders(launch2, table).map((holder) => holder.pid)));
15393
15447
  const underHolder = (pid) => {
15394
15448
  for (let current = pid, depth = 0;current !== undefined && current > 1 && depth < 256; current = table.get(current)?.ppid, depth++)
15395
15449
  if (held.has(current))
15396
15450
  return true;
15397
15451
  return false;
15398
15452
  };
15399
- const holders = [...new Set(peers)].filter((pid) => pid !== process.pid && table.has(pid) && underHolder(pid)).slice(0, MAX_HOLDERS).map((pid) => ({ pid, start: table.get(pid).start }));
15453
+ const durable = entry.record.route !== undefined;
15454
+ const holders = [...new Set(peers)].filter((pid) => pid !== process.pid && table.has(pid) && (durable || underHolder(pid))).slice(0, MAX_HOLDERS).map((pid) => ({ pid, start: table.get(pid).start }));
15400
15455
  if (byDigest.has(digest2) || ended.get(digest2) !== entry)
15401
15456
  return byDigest.get(digest2);
15402
15457
  if (!holders.length)
15403
15458
  return fail();
15404
15459
  const { endedAt: _endedAt, ...fixed } = entry.record;
15405
- const record3 = { ...fixed, lastUsedAt: at, lastHolderAt: at, released: true, holders };
15460
+ const record3 = { ...fixed, ...durable ? { routeRevived: true } : {}, lastUsedAt: at, lastHolderAt: at, released: true, holders };
15406
15461
  await writePrivate(join22(paths.launches, `${record3.id}.json`), JSON.stringify(staticFields(record3)));
15407
15462
  const launch = adopt(record3, entry.credential);
15408
15463
  launch.probedAfterLauncher = true;
15409
15464
  track(launch, table, at);
15410
15465
  await persist(launch, true);
15411
15466
  await forgetEnded(entry);
15412
- log(`launch ${record3.id.slice(0, 8)} revived for a process that still uses it under a current launch`);
15467
+ log(`launch ${record3.id.slice(0, 8)} revived for a process that still uses it ${durable ? "through its durable route" : "under a current launch"}`);
15413
15468
  return launch;
15414
15469
  } catch {
15415
15470
  return fail();
@@ -15469,7 +15524,7 @@ async function startGatewayService(options = {}) {
15469
15524
  const digest2 = sha256(token);
15470
15525
  const launch = byDigest.get(digest2) ?? await revive(digest2, server.requestIP(request)?.port, server.port);
15471
15526
  if (!launch)
15472
- return errorBody(401, "switcher_gateway_launch_unknown", `Switcher gateway: this session's launch is no longer registered (it was revoked, it ended more than 30 days ago, or the gateway state was reset), or this request did not come from a process of this user running under a current launch. ${LAUNCH_HINT}`);
15527
+ return errorBody(401, "switcher_gateway_launch_unknown", `Switcher gateway: this session's launch is no longer registered (it was revoked, it ended more than 30 days ago, or the gateway state was reset), or this request for the ended launch did not come from a process of this user running under a current launch, or from any running process of this user for a durable Claude route. ${LAUNCH_HINT}`);
15473
15528
  const at = now();
15474
15529
  launch.record.lastUsedAt = at;
15475
15530
  if (at - launch.usedPersistedAt >= USE_PERSIST_INTERVAL_MS) {
@@ -15515,6 +15570,9 @@ async function startGatewayService(options = {}) {
15515
15570
  if (!holder)
15516
15571
  throw new Fault(400, "holder_not_running", "The registering process is not running.");
15517
15572
  const stateDir = await launchStateDirectory(input.stateDir);
15573
+ const route2 = input.route ? { settingsDir: await routeSettingsDirectory(input.route.settingsDir) } : undefined;
15574
+ if (route2 && input.gateway.harness !== "claude")
15575
+ throw new Fault(400, "invalid_route", "Only Claude launches keep a durable route.");
15518
15576
  const policy = compiledPolicy(input.gateway.compiledPolicy);
15519
15577
  if (policy.model !== input.gateway.model)
15520
15578
  throw new Fault(400, "invalid_request", "The compiled policy does not belong to the selected model.");
@@ -15542,7 +15600,8 @@ async function startGatewayService(options = {}) {
15542
15600
  holders: [{ pid: holder.pid, start: holder.start }],
15543
15601
  gateway: { ...input.gateway, compiledPolicy: policy },
15544
15602
  credential,
15545
- ...stateDir ? { stateDir } : {}
15603
+ ...stateDir ? { stateDir } : {},
15604
+ ...route2 ? { route: route2 } : {}
15546
15605
  };
15547
15606
  const launch = adopt(record3, input.credential);
15548
15607
  launch.baseline = new Set([...table.values()].map(processKey));
@@ -15580,7 +15639,7 @@ async function startGatewayService(options = {}) {
15580
15639
  if (method === "GET" && url2.pathname === "/v1/status")
15581
15640
  return Response.json({ service: "switcher-gateway", protocol: GATEWAY_PROTOCOL, version: VERSION, pid: process.pid, port, baseUrl: `http://127.0.0.1:${port}`, launches: launches.size, supervisor: options.supervisor ?? "none" });
15582
15641
  if (method === "GET" && url2.pathname === "/v1/launches")
15583
- return Response.json({ data: [...launches.values()].map(({ record: record3 }) => ({ id: record3.id, harness: record3.gateway.harness, model: record3.gateway.model, createdAt: new Date(record3.createdAt).toISOString(), lastUsedAt: new Date(record3.lastUsedAt).toISOString(), holders: record3.holders.length, released: record3.released, credential: record3.credential.source })) });
15642
+ return Response.json({ data: [...launches.values()].map(({ record: record3 }) => ({ id: record3.id, harness: record3.gateway.harness, model: record3.gateway.model, createdAt: new Date(record3.createdAt).toISOString(), lastUsedAt: new Date(record3.lastUsedAt).toISOString(), holders: record3.holders.length, released: record3.released, credential: record3.credential.source, durable: record3.route !== undefined })) });
15584
15643
  if (method === "POST" && url2.pathname === "/v1/launches")
15585
15644
  return Response.json(await register(registrationSchema.parse(await json(request))), { status: 201 });
15586
15645
  if (method === "POST" && url2.pathname === "/v1/stop") {
@@ -16038,26 +16097,39 @@ function createServiceGatewayHost(client, context) {
16038
16097
  catalogPath: input.catalogPath,
16039
16098
  cwd: input.cwd
16040
16099
  };
16041
- let registration;
16100
+ const route2 = input.harness === "claude" && input.sessionDir ? { settingsDir: join24(input.sessionDir, "settings") } : undefined;
16101
+ if (route2)
16102
+ await privateDirectory(route2.settingsDir);
16103
+ const body2 = {
16104
+ holderPid: context.holderPid,
16105
+ gateway,
16106
+ ...input.credential ? { credential: input.credential } : {},
16107
+ ...context.credentialEnv ? { credentialEnv: context.credentialEnv } : {},
16108
+ ...context.stateDir ? { stateDir: context.stateDir } : {}
16109
+ };
16110
+ let registration, durable = Boolean(route2);
16042
16111
  try {
16043
- registration = await client.register({
16044
- holderPid: context.holderPid,
16045
- gateway,
16046
- ...input.credential ? { credential: input.credential } : {},
16047
- ...context.credentialEnv ? { credentialEnv: context.credentialEnv } : {},
16048
- ...context.stateDir ? { stateDir: context.stateDir } : {}
16049
- });
16112
+ try {
16113
+ registration = await client.register(route2 ? { ...body2, route: route2 } : body2);
16114
+ } catch (error) {
16115
+ if (!(route2 && error instanceof Fault && error.code === "invalid_request" && /route/.test(error.message)))
16116
+ throw error;
16117
+ (context.warn ?? console.error)("switcher: The running gateway predates durable Claude routes; a background session restarted after this launch ends may lose its route. Run `switcher gateway install` to restart it on this version.");
16118
+ registration = await client.register(body2);
16119
+ durable = false;
16120
+ }
16050
16121
  } catch (error) {
16051
16122
  (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.`);
16052
16123
  return createInferenceGateway(input);
16053
16124
  }
16125
+ const routeSettingsFile = durable && route2 ? join24(route2.settingsDir, `claude-route-${registration.id}.json`) : undefined;
16054
16126
  const lease = { id: registration.id, attached: attachedPid !== undefined, retained: false, done: false };
16055
16127
  leases.push(lease);
16056
16128
  if (attachedPid !== undefined)
16057
16129
  attaching.push(client.attach(lease.id, attachedPid).catch(() => {
16058
16130
  return;
16059
16131
  }));
16060
- return { baseUrl: registration.baseUrl, token: registration.token, retainsState: () => lease.retained, cleanup: async () => {
16132
+ return { baseUrl: registration.baseUrl, token: registration.token, ...routeSettingsFile ? { routeSettingsFile } : {}, retainsState: () => lease.retained, cleanup: async () => {
16061
16133
  if (lease.done)
16062
16134
  return;
16063
16135
  lease.done = true;
@@ -16066,6 +16138,10 @@ function createServiceGatewayHost(client, context) {
16066
16138
  await client.revoke(lease.id).catch(() => {
16067
16139
  return;
16068
16140
  });
16141
+ if (routeSettingsFile)
16142
+ await rm6(routeSettingsFile, { force: true }).catch(() => {
16143
+ return;
16144
+ });
16069
16145
  return;
16070
16146
  }
16071
16147
  try {
@@ -16094,7 +16170,7 @@ function createServiceGatewayHost(client, context) {
16094
16170
  // src/launcher.ts
16095
16171
  var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
16096
16172
  async function writeOriCodexCatalog(stateDir, models) {
16097
- const path = join24(stateDir, "ori-codex-models.json");
16173
+ const path = join25(stateDir, "ori-codex-models.json");
16098
16174
  const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
16099
16175
  await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
16100
16176
  `, { mode: 384, flag: "wx" });
@@ -16188,7 +16264,7 @@ async function prepareOriForPlan(plan, options) {
16188
16264
  });
16189
16265
  try {
16190
16266
  const shim = prepareOriModelPolicy(request.target, native);
16191
- const dir = join24(options.stateDir, "ori-bin"), path = join24(dir, shim.name);
16267
+ const dir = join25(options.stateDir, "ori-bin"), path = join25(dir, shim.name);
16192
16268
  await mkdir14(dir, { mode: 448 });
16193
16269
  await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
16194
16270
  return { contract, prepared: {
@@ -16208,12 +16284,12 @@ async function sharedNativeHome(state, root, profileId, environment = process.en
16208
16284
  const variable = state.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
16209
16285
  const configured = environment[variable] ? resolve14(environment[variable]) : undefined;
16210
16286
  const configuredCorpus = configured !== undefined && await realpath8(configured).catch(() => configured) === state.home;
16211
- const home = state.tool === "claude" && (!configured || configured === state.home || configuredCorpus) ? join24(root, "native-claude", profileId) : configured ?? state.home;
16287
+ const home = state.tool === "claude" && (!configured || configured === state.home || configuredCorpus) ? join25(root, "native-claude", profileId) : configured ?? state.home;
16212
16288
  return { home, settingsEnvironment: configuredCorpus ? { ...environment, CLAUDE_CONFIG_DIR: undefined } : environment };
16213
16289
  }
16214
16290
  var SESSION_DIRECTORY_HARNESSES = ["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie", "claude"];
16215
16291
  function launchSessionDirectory(root, harness, profileId) {
16216
- return join24(root, "sessions", harness, profileId);
16292
+ return join25(root, "sessions", harness, profileId);
16217
16293
  }
16218
16294
  async function checkSharedNativeLaunch(state, root, profileId, options = {}) {
16219
16295
  const warnings = await legacyNativeStateWarnings(root, state);
@@ -16235,11 +16311,11 @@ async function checkSharedNativeLaunch(state, root, profileId, options = {}) {
16235
16311
  }
16236
16312
  function isolatedNativeHome(tool, root, profileId, options = {}, environment = process.env) {
16237
16313
  if (options.desktop)
16238
- return { home: join24(root, "desktop", profileId, "codex"), private: false };
16314
+ return { home: join25(root, "desktop", profileId, "codex"), private: false };
16239
16315
  if (options.claudeDesktop)
16240
- return { home: join24(root, "desktop-claude", profileId), private: false };
16316
+ return { home: join25(root, "desktop-claude", profileId), private: false };
16241
16317
  const configured = environment[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
16242
- return { home: configured ? resolve14(configured) : join24(root, `native-${tool}`, profileId), private: true };
16318
+ return { home: configured ? resolve14(configured) : join25(root, `native-${tool}`, profileId), private: true };
16243
16319
  }
16244
16320
  async function checkDirectLaunch(root, profileId, harness, options = {}) {
16245
16321
  const desktop = Boolean(options.desktop || options.claudeDesktop);
@@ -16296,9 +16372,9 @@ async function launch(client, profileId, options = {}) {
16296
16372
  validateHarnessVersion("gemini", detection?.version);
16297
16373
  if (backend === "direct" && plan.profile.harness === "aider")
16298
16374
  validateHarnessVersion(plan.profile.harness, detection?.version);
16299
- const root = resolve14(options.stateDir ?? join24(switcherHome(), "state"));
16375
+ const root = resolve14(options.stateDir ?? join25(switcherHome(), "state"));
16300
16376
  await privateDirectory(root);
16301
- const stateDir = await mkdtemp(join24(root, "launch-"));
16377
+ const stateDir = await mkdtemp(join25(root, "launch-"));
16302
16378
  let credential;
16303
16379
  if (backend === "direct") {
16304
16380
  try {
@@ -16306,7 +16382,7 @@ async function launch(client, profileId, options = {}) {
16306
16382
  if (plan.provider.credentialEnv && !credential)
16307
16383
  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.`);
16308
16384
  } catch (error) {
16309
- await rm6(stateDir, { recursive: true, force: true });
16385
+ await rm7(stateDir, { recursive: true, force: true });
16310
16386
  throw error;
16311
16387
  }
16312
16388
  }
@@ -16397,7 +16473,7 @@ async function launch(client, profileId, options = {}) {
16397
16473
  cwd: resolve14(options.cwd ?? process.cwd()),
16398
16474
  sharedState
16399
16475
  };
16400
- let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join24(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
16476
+ 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({
16401
16477
  harness: plan.profile.harness,
16402
16478
  baseUrl: plan.provider.baseUrl,
16403
16479
  protocol: plan.provider.protocol,
@@ -16434,7 +16510,7 @@ async function launch(client, profileId, options = {}) {
16434
16510
  prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
16435
16511
  }
16436
16512
  if (options.desktop) {
16437
- prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join24(root, "desktop", desktopState), sharedState);
16513
+ prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join25(root, "desktop", desktopState), sharedState);
16438
16514
  cleanup = prepared.cleanup;
16439
16515
  }
16440
16516
  for (const warning of [...plan.warnings, ...prepared.warnings])
@@ -16543,7 +16619,7 @@ async function launch(client, profileId, options = {}) {
16543
16619
  await cleanup?.();
16544
16620
  } finally {
16545
16621
  if (!gatewayHost?.retainedState())
16546
- await rm6(stateDir, { recursive: true, force: true });
16622
+ await rm7(stateDir, { recursive: true, force: true });
16547
16623
  }
16548
16624
  }
16549
16625
  }
@@ -16657,7 +16733,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
16657
16733
  import { createHash as createHash18 } from "crypto";
16658
16734
  import { constants as constants11 } from "fs";
16659
16735
  import { lstat as lstat14, open as open9, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
16660
- import { basename as basename6, dirname as dirname11, isAbsolute as isAbsolute19, join as join25, relative as relative8, resolve as resolve15 } from "path";
16736
+ import { basename as basename6, dirname as dirname11, isAbsolute as isAbsolute19, join as join26, relative as relative8, resolve as resolve15 } from "path";
16661
16737
  var MAX_FILES = 1e5;
16662
16738
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
16663
16739
  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.");
@@ -16722,7 +16798,7 @@ async function checkSessionIdentities(plan) {
16722
16798
  for (const file of plan.files) {
16723
16799
  if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
16724
16800
  continue;
16725
- file.sessionId = await sessionId(join25(plan.source, file.path), file.source);
16801
+ file.sessionId = await sessionId(join26(plan.source, file.path), file.source);
16726
16802
  if (!file.sessionId)
16727
16803
  continue;
16728
16804
  const previous = ids.get(file.sessionId);
@@ -16746,7 +16822,7 @@ async function checkSessionIdentities(plan) {
16746
16822
  for await (const entry of await opendir2(directory)) {
16747
16823
  if (++seen > MAX_FILES || entry.isSymbolicLink())
16748
16824
  throw refused();
16749
- const path = join25(directory, entry.name);
16825
+ const path = join26(directory, entry.name);
16750
16826
  if (entry.isDirectory()) {
16751
16827
  await scan(path, depth + 1);
16752
16828
  continue;
@@ -16763,8 +16839,8 @@ async function checkSessionIdentities(plan) {
16763
16839
  file.existing = true;
16764
16840
  }
16765
16841
  }
16766
- await scan(join25(plan.state.home, "sessions"));
16767
- await scan(join25(plan.state.home, "archived_sessions"));
16842
+ await scan(join26(plan.state.home, "sessions"));
16843
+ await scan(join26(plan.state.home, "archived_sessions"));
16768
16844
  }
16769
16845
  async function fingerprint2(path, copyTo) {
16770
16846
  const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
@@ -16824,9 +16900,9 @@ async function planNativeStateImport(state, source, selection) {
16824
16900
  async function visit(path, kind) {
16825
16901
  if (++seen > MAX_FILES || path.split("/").length > 32)
16826
16902
  throw refused();
16827
- await ensureNativeStateDirectory(dirname11(join25(source, path)), false);
16828
- await ensureNativeStateDirectory(dirname11(join25(state.home, path)), false);
16829
- const from = join25(source, path), to = join25(state.home, path), entry = await info2(from), target = await info2(to);
16903
+ await ensureNativeStateDirectory(dirname11(join26(source, path)), false);
16904
+ await ensureNativeStateDirectory(dirname11(join26(state.home, path)), false);
16905
+ const from = join26(source, path), to = join26(state.home, path), entry = await info2(from), target = await info2(to);
16830
16906
  if (!entry)
16831
16907
  return;
16832
16908
  if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
@@ -16845,7 +16921,7 @@ async function planNativeStateImport(state, source, selection) {
16845
16921
  }
16846
16922
  children.sort((a, b) => a.name.localeCompare(b.name));
16847
16923
  for (const child of children)
16848
- await visit(join25(path, child.name), child.kind);
16924
+ await visit(join26(path, child.name), child.kind);
16849
16925
  } else {
16850
16926
  const value = await fingerprint2(from);
16851
16927
  plan.bytes += value.bytes;
@@ -16899,14 +16975,14 @@ async function applyNativeStateImportUnlocked(plan) {
16899
16975
  throw refused();
16900
16976
  const requiredDirectories = new Set([plan.state.home]);
16901
16977
  for (const path of plan.directories) {
16902
- for (let directory = join25(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname11(directory)) {
16978
+ for (let directory = join26(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname11(directory)) {
16903
16979
  requiredDirectories.add(directory);
16904
16980
  if (directory === plan.state.home)
16905
16981
  break;
16906
16982
  }
16907
16983
  }
16908
16984
  for (const file of plan.files.filter((file2) => !file2.existing)) {
16909
- for (let directory = dirname11(join25(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname11(directory)) {
16985
+ for (let directory = dirname11(join26(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname11(directory)) {
16910
16986
  requiredDirectories.add(directory);
16911
16987
  if (directory === plan.state.home)
16912
16988
  break;
@@ -16927,9 +17003,9 @@ async function applyNativeStateImportUnlocked(plan) {
16927
17003
  for (const file of plan.files) {
16928
17004
  if (file.existing)
16929
17005
  continue;
16930
- const target = join25(plan.state.home, file.path), temporary = join25(dirname11(target), `.switcher-import-${crypto.randomUUID()}`);
17006
+ const target = join26(plan.state.home, file.path), temporary = join26(dirname11(target), `.switcher-import-${crypto.randomUUID()}`);
16931
17007
  staged.push({ temporary, target });
16932
- const copied = await fingerprint2(join25(plan.source, file.path), temporary);
17008
+ const copied = await fingerprint2(join26(plan.source, file.path), temporary);
16933
17009
  if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
16934
17010
  throw refused();
16935
17011
  }
@@ -17444,7 +17520,7 @@ async function main(args = process.argv.slice(2)) {
17444
17520
  const marked = process.env[`HASNA_${suffix}_STATE_HOME`] !== undefined || process.env[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
17445
17521
  if ((sharedNativeState || shareNativeState === false) && plan.profile.harness === "codex")
17446
17522
  assertHarnessArguments("codex", nativeArgs, { reservedCodexRoots: ["sqlite_home"] });
17447
- const root = resolve16(values2["state-dir"] ?? join26(switcherHome(), "state"));
17523
+ const root = resolve16(values2["state-dir"] ?? join27(switcherHome(), "state"));
17448
17524
  if (backend !== "direct")
17449
17525
  await checkPrivateDirectory(root);
17450
17526
  const nativeWarnings = backend === "direct" ? await checkDirectLaunch(root, profileId, plan.profile.harness, {
@@ -30,6 +30,12 @@ export type HarnessLaunchInput = {
30
30
  sharedState?: NativeState;
31
31
  /** Hosts the launch's inference gateway; a per-launch listener when absent. */
32
32
  gatewayHost?: GatewayHost;
33
+ /**
34
+ * Claude only: where to write the session's --settings file when its gateway token
35
+ * outlives the launch (see GatewayLease.routeSettingsFile). The file then carries the
36
+ * route in its env block, so a session the background host restarts keeps it.
37
+ */
38
+ routeSettingsFile?: string;
33
39
  };
34
40
  export type PreparedLaunch = {
35
41
  executable: string;