@hasna/switcher 0.2.19 → 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.19";
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.19",
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: [
@@ -7199,7 +7199,18 @@ function announceSwitcherLocalMode(home, write = (line) => {
7199
7199
  import { mkdir as mkdir4, lstat } from "fs/promises";
7200
7200
  async function privateDirectory(path) {
7201
7201
  await mkdir4(path, { recursive: true, mode: 448 });
7202
- const info = await lstat(path);
7202
+ assertPrivateEntry(await lstat(path));
7203
+ }
7204
+ async function checkPrivateDirectory(path) {
7205
+ const info = await lstat(path).catch((error) => {
7206
+ if (error.code === "ENOENT")
7207
+ return;
7208
+ throw error;
7209
+ });
7210
+ if (info)
7211
+ assertPrivateEntry(info);
7212
+ }
7213
+ function assertPrivateEntry(info) {
7203
7214
  if (!info.isDirectory() || info.isSymbolicLink())
7204
7215
  throw new Fault(500, "home_permissions", "Switcher data directory must be a real directory.");
7205
7216
  if (process.platform !== "win32" && ((info.mode & 63) !== 0 || info.uid !== process.getuid?.()))
@@ -10406,6 +10417,9 @@ async function jsonFile(dir, name, value) {
10406
10417
  `, { mode: 384, flag: "wx" });
10407
10418
  return path;
10408
10419
  }
10420
+ function claudeSettingsDirectory(sessionDir) {
10421
+ return join15(sessionDir, "settings");
10422
+ }
10409
10423
  async function durableJsonFile(dir, prefix, value) {
10410
10424
  const text = JSON.stringify(value, null, 2) + `
10411
10425
  `;
@@ -10430,6 +10444,19 @@ async function durableJsonFile(dir, prefix, value) {
10430
10444
  }
10431
10445
  return path;
10432
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
+ }
10433
10460
  async function projectInstructionPaths(cwd) {
10434
10461
  let dir = resolve8(cwd);
10435
10462
  while (true) {
@@ -11105,7 +11132,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11105
11132
  env.ANTHROPIC_AUTH_TOKEN = "";
11106
11133
  env[input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"] = input.credential ?? "switcher-local-no-auth";
11107
11134
  const picker = { modelPicker: { replaceBuiltInOptions: true, options: input.models.map((m) => ({ model: m.id, label: m.name, description: m.description?.slice(0, 300) })) } };
11108
- const file2 = input.sessionDir ? await durableJsonFile(join15(input.sessionDir, "settings"), "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);
11109
11137
  configPaths.push(file2);
11110
11138
  warnings.push("Claude managed settings and model allowlists can restrict the generated picker.");
11111
11139
  return { executable, args: ["--settings", file2, "--model", input.model, ...args], env, configPaths, warnings };
@@ -11476,7 +11504,7 @@ async function prepareHarnessLaunch(input) {
11476
11504
  };
11477
11505
  try {
11478
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";
11479
- 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 });
11480
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 () => {
11481
11509
  try {
11482
11510
  await prepared.cleanup?.();
@@ -11519,8 +11547,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
11519
11547
  }
11520
11548
 
11521
11549
  // src/launcher.ts
11522
- import { mkdir as mkdir14, mkdtemp, realpath as realpath8, rm as rm6, writeFile as writeFile18 } from "fs/promises";
11523
- import { join as join24, 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";
11524
11552
 
11525
11553
  // src/provider-credential-onboarding.ts
11526
11554
  import { z as z9 } from "zod-v4";
@@ -13365,19 +13393,24 @@ async function assertNativeStateIsolation(tool, home, environment = process.env)
13365
13393
  throw new Fault(409, "native_state_isolation_conflict", "This profile redirects its native database. Select a separate isolated profile; Switcher will not rewrite its existing configuration.");
13366
13394
  }
13367
13395
  }
13396
+ function nativeStateLockPath(state) {
13397
+ return join17(state.home, ".switcher-shared-state.lock");
13398
+ }
13399
+ function nativeStateLockFault(entry) {
13400
+ if (!entry?.isFile() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 63) !== 0)
13401
+ return new Fault(422, "native_state_lock", "The shared-state lock has unsafe ownership, permissions or type.");
13402
+ return new Fault(409, "native_state_busy", "Another Switcher projection/import owns this corpus, or a prior operation ended before releasing its lock. Inspect native processes and the lock before retrying.");
13403
+ }
13368
13404
  async function withNativeStateLock(state, operation) {
13369
13405
  await ensureNativeStateDirectory(state.home);
13370
- const path = join17(state.home, ".switcher-shared-state.lock");
13406
+ const path = nativeStateLockPath(state);
13371
13407
  let handle;
13372
13408
  try {
13373
13409
  handle = await open5(path, "wx", 384);
13374
13410
  } catch (error) {
13375
13411
  if (error.code !== "EEXIST")
13376
13412
  throw error;
13377
- const entry = await info(path);
13378
- if (!entry?.isFile() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 63) !== 0)
13379
- throw new Fault(422, "native_state_lock", "The shared-state lock has unsafe ownership, permissions or type.");
13380
- throw new Fault(409, "native_state_busy", "Another Switcher projection/import owns this corpus, or a prior operation ended before releasing its lock. Inspect native processes and the lock before retrying.");
13413
+ throw nativeStateLockFault(await info(path));
13381
13414
  }
13382
13415
  const identity = await handle.stat();
13383
13416
  try {
@@ -13547,10 +13580,13 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
13547
13580
  }
13548
13581
  return instructions;
13549
13582
  }
13550
- async function assertNativeInstructionOverlay(state, overlayHome) {
13583
+ async function assertNativeInstructionOverlay(state, overlayHome, options = {}) {
13551
13584
  if (state.tool !== "codex" || absolute(overlayHome) === state.home)
13552
13585
  return;
13553
- await assertNativeStateDirectory(overlayHome);
13586
+ if (options.plan && !await info(absolute(overlayHome)))
13587
+ await assertCreatableNativeStateDirectory(absolute(overlayHome));
13588
+ else
13589
+ await assertNativeStateDirectory(overlayHome);
13554
13590
  const config = await readCodexStateConfig(overlayHome);
13555
13591
  if (config.profiles !== undefined || config.include !== undefined)
13556
13592
  throw new Fault(422, "native_state_instruction_overlay", "Private Codex profile/include instruction overlays are not supported. Resolve their effective canonical instructions before launching.");
@@ -13670,10 +13706,25 @@ async function createTrackedDirectory(path, created) {
13670
13706
  await assertNativeStateDirectory(path);
13671
13707
  }
13672
13708
  }
13673
- async function projectNativeStateUnlocked(state, overlayHome) {
13709
+ async function assertCreatableNativeStateDirectory(path) {
13710
+ let existing = dirname8(path);
13711
+ while (!await info(existing) && existing !== dirname8(existing))
13712
+ existing = dirname8(existing);
13713
+ if (await realpath6(existing) !== existing)
13714
+ assertNativeDirectoryEntry(await info(path), path, true);
13715
+ await assertSafeAncestors(existing);
13716
+ }
13717
+ async function preflightNativeStateProjection(state, overlayHome, plan = false) {
13674
13718
  overlayHome = absolute(overlayHome);
13675
- await assertNativeStateDirectory(state.home);
13676
- await assertNativeStateDirectory(overlayHome);
13719
+ const corpus = !plan || Boolean(await info(state.home)), overlay = !plan || Boolean(await info(overlayHome));
13720
+ if (corpus)
13721
+ await assertNativeStateDirectory(state.home);
13722
+ else
13723
+ await ensureNativeStateDirectory(state.home, false);
13724
+ if (overlay)
13725
+ await assertNativeStateDirectory(overlayHome);
13726
+ else
13727
+ await assertCreatableNativeStateDirectory(overlayHome);
13677
13728
  if (overlayHome === state.home)
13678
13729
  return;
13679
13730
  const contains = (parent, child) => {
@@ -13685,9 +13736,11 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13685
13736
  await assertCodexDatabaseRedirectSafe(state, overlayHome);
13686
13737
  for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
13687
13738
  const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
13688
- await ensureNativeStateDirectory(dirname8(target), false);
13689
- await ensureNativeStateDirectory(dirname8(destination), false);
13690
- const source = await info(target), existing = await info(destination);
13739
+ if (corpus)
13740
+ await ensureNativeStateDirectory(dirname8(target), false);
13741
+ if (overlay)
13742
+ await ensureNativeStateDirectory(dirname8(destination), false);
13743
+ const source = corpus ? await info(target) : undefined, existing = overlay ? await info(destination) : undefined;
13691
13744
  if (source && (source.isSymbolicLink() || source.uid !== process.getuid?.() || writableByOthers(source) || source.isFile() && source.nlink !== 1 || (entry.kind === "directory" ? !source.isDirectory() : !source.isFile())))
13692
13745
  throw new Fault(422, "native_state_entry", `The shared native state entry ${displayPath(target)} must be a ${entry.kind === "directory" ? "real directory" : "regular file with a single link"} owned by you and not writable by other users. ${writeFix}.`);
13693
13746
  if (source?.isDirectory())
@@ -13695,6 +13748,12 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13695
13748
  if (existing && (!existing.isSymbolicLink() || resolve10(dirname8(destination), await readlink(destination)) !== target))
13696
13749
  throw new Fault(409, "native_state_migration_required", `This launch profile already contains native state at ${displayPath(destination)}, which is not a link to ${displayPath(target)}. Preserve and migrate its noncredential state before linking the shared corpus.`);
13697
13750
  }
13751
+ }
13752
+ async function projectNativeStateUnlocked(state, overlayHome) {
13753
+ overlayHome = absolute(overlayHome);
13754
+ await preflightNativeStateProjection(state, overlayHome);
13755
+ if (overlayHome === state.home)
13756
+ return;
13698
13757
  const createdLinks = [];
13699
13758
  const createdFiles = [], createdDirectories = [];
13700
13759
  try {
@@ -13752,6 +13811,14 @@ async function projectNativeState(state, overlayHome) {
13752
13811
  return;
13753
13812
  return withNativeStateLock(state, () => projectNativeStateUnlocked(state, overlayHome));
13754
13813
  }
13814
+ async function checkNativeStateProjection(state, overlayHome) {
13815
+ if (absolute(overlayHome) === state.home)
13816
+ return;
13817
+ const lock = await info(nativeStateLockPath(state));
13818
+ if (lock)
13819
+ throw nativeStateLockFault(lock);
13820
+ return preflightNativeStateProjection(state, overlayHome, true);
13821
+ }
13755
13822
 
13756
13823
  // src/chatgpt-launch.ts
13757
13824
  var object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -14184,7 +14251,7 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
14184
14251
  import { constants as constants9 } from "fs";
14185
14252
  import { lstat as lstat10, open as open6, writeFile as writeFile16 } from "fs/promises";
14186
14253
  import { homedir as homedir10 } from "os";
14187
- import { join as join20, resolve as resolve11 } from "path";
14254
+ import { join as join20, relative as relative6, resolve as resolve11 } from "path";
14188
14255
  var preferences = new Set([
14189
14256
  "$schema",
14190
14257
  "permissions",
@@ -14232,7 +14299,12 @@ function routingOrCredentialEnvironmentKey(key) {
14232
14299
  return /^(?:ANTHROPIC_|CLAUDE_CODE_USE_|CLAUDE_CODE_OAUTH|AWS_|GOOGLE_|VERTEX_|CLOUD_ML_|AZURE_|OTEL_EXPORTER_OTLP_HEADERS)/i.test(key) || /TOKEN|KEY|SECRET|PASSWORD|CREDENTIAL|AUTH|PROXY/i.test(key);
14233
14300
  }
14234
14301
  var invalid4 = (path) => new Fault(422, "claude_user_settings", `Claude user settings ${displayPath(path)} cannot be safely projected. Use a regular JSON file with a single link, owned by you and not writable by other users, with supported preferences and permission policy.`);
14235
- async function readSettings(home) {
14302
+ async function readSettings(home, created) {
14303
+ const inside3 = created !== undefined && ((suffix) => suffix !== ".." && !suffix.startsWith("../"))(relative6(created, home));
14304
+ if (inside3 && !await lstat10(home).catch(() => {
14305
+ return;
14306
+ }))
14307
+ return;
14236
14308
  await ensureNativeStateDirectory(home, false);
14237
14309
  const path = join20(home, "settings.json");
14238
14310
  const entry = await lstat10(path).catch((error) => {
@@ -14299,10 +14371,10 @@ function project(settings2, existing, path) {
14299
14371
  }
14300
14372
  return { settings: result, dropped };
14301
14373
  }
14302
- async function prepareClaudeUserSettings(overlayHome, environment = process.env, corpusHome) {
14374
+ async function prepareClaudeUserSettings(overlayHome, environment = process.env, corpusHome, options = {}) {
14303
14375
  overlayHome = resolve11(overlayHome);
14304
14376
  const target = join20(overlayHome, "settings.json");
14305
- const existing = await readSettings(overlayHome);
14377
+ const existing = await readSettings(overlayHome, options.write === false ? options.created : undefined);
14306
14378
  if (existing !== undefined) {
14307
14379
  project(existing, true, target);
14308
14380
  return [];
@@ -14314,6 +14386,9 @@ async function prepareClaudeUserSettings(overlayHome, environment = process.env,
14314
14386
  if (source === undefined)
14315
14387
  return [];
14316
14388
  const { settings: settings2, dropped } = project(source, false, join20(sourceHome, "settings.json"));
14389
+ const warnings = dropped.length ? [`Claude user settings not copied to this launch's private settings (unsupported keys): ${dropped.map((key) => JSON.stringify(key)).join(", ")}.`] : [];
14390
+ if (options.write === false)
14391
+ return warnings;
14317
14392
  await ensureNativeStateDirectory(overlayHome);
14318
14393
  try {
14319
14394
  await writeFile16(target, JSON.stringify(settings2, null, 2) + `
@@ -14325,7 +14400,7 @@ async function prepareClaudeUserSettings(overlayHome, environment = process.env,
14325
14400
  if (concurrent === undefined || JSON.stringify(project(concurrent, true, target).settings) !== JSON.stringify(settings2))
14326
14401
  throw new Fault(409, "claude_user_settings_changed", `The private Claude settings ${displayPath(target)} changed during preparation. Existing settings were preserved; retry after resolving the concurrent launch.`);
14327
14402
  }
14328
- return dropped.length ? [`Claude user settings not copied to this launch's private settings (unsupported keys): ${dropped.map((key) => JSON.stringify(key)).join(", ")}.`] : [];
14403
+ return warnings;
14329
14404
  }
14330
14405
 
14331
14406
  // src/claude-desktop-launch.ts
@@ -14616,6 +14691,8 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
14616
14691
  // src/gateway-client.ts
14617
14692
  import { spawn as spawn4 } from "child_process";
14618
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";
14619
14696
 
14620
14697
  // src/gateway-service.ts
14621
14698
  import { createHash as createHash16, randomBytes as randomBytes2, randomUUID as randomUUID7 } from "crypto";
@@ -14995,12 +15072,14 @@ var gatewaySchema = z10.object({
14995
15072
  cwd: z10.string().max(4096).refine(isAbsolute17, "Use an absolute working directory.")
14996
15073
  }).strict();
14997
15074
  var credentialEnvSchema = z10.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
15075
+ var routeSchema = z10.object({ settingsDir: z10.string().max(4096) }).strict();
14998
15076
  var registrationSchema = z10.object({
14999
15077
  holderPid: z10.number().int().positive(),
15000
15078
  gateway: gatewaySchema,
15001
15079
  credential: z10.string().min(1).max(64000).refine((value) => !/[\x00-\x1f\x7f]/.test(value), "Credential contains control characters.").optional(),
15002
15080
  credentialEnv: credentialEnvSchema.optional(),
15003
- stateDir: z10.string().max(4096).optional()
15081
+ stateDir: z10.string().max(4096).optional(),
15082
+ route: routeSchema.optional()
15004
15083
  }).strict();
15005
15084
  var holderSchema = z10.object({ pid: z10.number().int().positive(), start: z10.string().min(1).max(200) }).strict();
15006
15085
  var credentialSourceSchema = z10.discriminatedUnion("source", [
@@ -15016,7 +15095,9 @@ var staticSchema = z10.object({
15016
15095
  launcherPid: z10.number().int().positive(),
15017
15096
  gateway: gatewaySchema,
15018
15097
  credential: credentialSourceSchema,
15019
- stateDir: z10.string().max(4096).optional()
15098
+ stateDir: z10.string().max(4096).optional(),
15099
+ route: routeSchema.optional(),
15100
+ routeRevived: z10.literal(true).optional()
15020
15101
  }).strict();
15021
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();
15022
15103
  var endedSchema = staticSchema.omit({ stateDir: true }).extend({ endedAt: z10.number() }).strict();
@@ -15074,6 +15155,18 @@ async function writePrivate(path, text) {
15074
15155
  }
15075
15156
  await rename5(temporary, path);
15076
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;
15077
15170
  async function launchStateDirectory(path) {
15078
15171
  if (path === undefined)
15079
15172
  return;
@@ -15192,11 +15285,28 @@ async function startGatewayService(options = {}) {
15192
15285
  return;
15193
15286
  });
15194
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
+ };
15195
15305
  const pruneEnded = async (at) => {
15196
15306
  const entries = [...ended.values()].sort((a, b) => a.record.endedAt - b.record.endedAt);
15197
15307
  for (const [index, entry] of entries.entries())
15198
15308
  if (at - entry.record.endedAt > ENDED_MS || entries.length - index > MAX_ENDED)
15199
- await forgetEnded(entry);
15309
+ await expireEnded(entry);
15200
15310
  };
15201
15311
  const endedEntry = (launch) => {
15202
15312
  const { stateDir: _state, ...fixed } = staticFields(launch.record);
@@ -15234,6 +15344,11 @@ async function startGatewayService(options = {}) {
15234
15344
  await rm5(join22(paths.launches, `${launch.record.id}.json`), { force: true }).catch(() => {
15235
15345
  return;
15236
15346
  });
15347
+ const route2 = end ? undefined : routeFile(launch.record);
15348
+ if (route2)
15349
+ await rm5(route2, { force: true }).catch(() => {
15350
+ return;
15351
+ });
15237
15352
  if (removeState && launch.record.stateDir) {
15238
15353
  const directory = await launchStateDirectory(launch.record.stateDir).catch(() => {
15239
15354
  return;
@@ -15304,7 +15419,7 @@ async function startGatewayService(options = {}) {
15304
15419
  return entry.reviving;
15305
15420
  const at = now();
15306
15421
  if (at - entry.record.endedAt > ENDED_MS) {
15307
- forgetEnded(entry);
15422
+ expireEnded(entry);
15308
15423
  return;
15309
15424
  }
15310
15425
  const failedAt = entry.failed.get(clientPort);
@@ -15328,27 +15443,28 @@ async function startGatewayService(options = {}) {
15328
15443
  try {
15329
15444
  await entry.settled;
15330
15445
  const [peers, table] = await Promise.all([connectionPeers(clientPort, serverPort), processTable()]);
15331
- 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)));
15332
15447
  const underHolder = (pid) => {
15333
15448
  for (let current = pid, depth = 0;current !== undefined && current > 1 && depth < 256; current = table.get(current)?.ppid, depth++)
15334
15449
  if (held.has(current))
15335
15450
  return true;
15336
15451
  return false;
15337
15452
  };
15338
- 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 }));
15339
15455
  if (byDigest.has(digest2) || ended.get(digest2) !== entry)
15340
15456
  return byDigest.get(digest2);
15341
15457
  if (!holders.length)
15342
15458
  return fail();
15343
15459
  const { endedAt: _endedAt, ...fixed } = entry.record;
15344
- const record3 = { ...fixed, lastUsedAt: at, lastHolderAt: at, released: true, holders };
15460
+ const record3 = { ...fixed, ...durable ? { routeRevived: true } : {}, lastUsedAt: at, lastHolderAt: at, released: true, holders };
15345
15461
  await writePrivate(join22(paths.launches, `${record3.id}.json`), JSON.stringify(staticFields(record3)));
15346
15462
  const launch = adopt(record3, entry.credential);
15347
15463
  launch.probedAfterLauncher = true;
15348
15464
  track(launch, table, at);
15349
15465
  await persist(launch, true);
15350
15466
  await forgetEnded(entry);
15351
- 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"}`);
15352
15468
  return launch;
15353
15469
  } catch {
15354
15470
  return fail();
@@ -15408,7 +15524,7 @@ async function startGatewayService(options = {}) {
15408
15524
  const digest2 = sha256(token);
15409
15525
  const launch = byDigest.get(digest2) ?? await revive(digest2, server.requestIP(request)?.port, server.port);
15410
15526
  if (!launch)
15411
- 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}`);
15412
15528
  const at = now();
15413
15529
  launch.record.lastUsedAt = at;
15414
15530
  if (at - launch.usedPersistedAt >= USE_PERSIST_INTERVAL_MS) {
@@ -15454,6 +15570,9 @@ async function startGatewayService(options = {}) {
15454
15570
  if (!holder)
15455
15571
  throw new Fault(400, "holder_not_running", "The registering process is not running.");
15456
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.");
15457
15576
  const policy = compiledPolicy(input.gateway.compiledPolicy);
15458
15577
  if (policy.model !== input.gateway.model)
15459
15578
  throw new Fault(400, "invalid_request", "The compiled policy does not belong to the selected model.");
@@ -15481,7 +15600,8 @@ async function startGatewayService(options = {}) {
15481
15600
  holders: [{ pid: holder.pid, start: holder.start }],
15482
15601
  gateway: { ...input.gateway, compiledPolicy: policy },
15483
15602
  credential,
15484
- ...stateDir ? { stateDir } : {}
15603
+ ...stateDir ? { stateDir } : {},
15604
+ ...route2 ? { route: route2 } : {}
15485
15605
  };
15486
15606
  const launch = adopt(record3, input.credential);
15487
15607
  launch.baseline = new Set([...table.values()].map(processKey));
@@ -15519,7 +15639,7 @@ async function startGatewayService(options = {}) {
15519
15639
  if (method === "GET" && url2.pathname === "/v1/status")
15520
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" });
15521
15641
  if (method === "GET" && url2.pathname === "/v1/launches")
15522
- 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 })) });
15523
15643
  if (method === "POST" && url2.pathname === "/v1/launches")
15524
15644
  return Response.json(await register(registrationSchema.parse(await json(request))), { status: 201 });
15525
15645
  if (method === "POST" && url2.pathname === "/v1/stop") {
@@ -15977,26 +16097,39 @@ function createServiceGatewayHost(client, context) {
15977
16097
  catalogPath: input.catalogPath,
15978
16098
  cwd: input.cwd
15979
16099
  };
15980
- 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);
15981
16111
  try {
15982
- registration = await client.register({
15983
- holderPid: context.holderPid,
15984
- gateway,
15985
- ...input.credential ? { credential: input.credential } : {},
15986
- ...context.credentialEnv ? { credentialEnv: context.credentialEnv } : {},
15987
- ...context.stateDir ? { stateDir: context.stateDir } : {}
15988
- });
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
+ }
15989
16121
  } catch (error) {
15990
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.`);
15991
16123
  return createInferenceGateway(input);
15992
16124
  }
16125
+ const routeSettingsFile = durable && route2 ? join24(route2.settingsDir, `claude-route-${registration.id}.json`) : undefined;
15993
16126
  const lease = { id: registration.id, attached: attachedPid !== undefined, retained: false, done: false };
15994
16127
  leases.push(lease);
15995
16128
  if (attachedPid !== undefined)
15996
16129
  attaching.push(client.attach(lease.id, attachedPid).catch(() => {
15997
16130
  return;
15998
16131
  }));
15999
- 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 () => {
16000
16133
  if (lease.done)
16001
16134
  return;
16002
16135
  lease.done = true;
@@ -16005,6 +16138,10 @@ function createServiceGatewayHost(client, context) {
16005
16138
  await client.revoke(lease.id).catch(() => {
16006
16139
  return;
16007
16140
  });
16141
+ if (routeSettingsFile)
16142
+ await rm6(routeSettingsFile, { force: true }).catch(() => {
16143
+ return;
16144
+ });
16008
16145
  return;
16009
16146
  }
16010
16147
  try {
@@ -16033,7 +16170,7 @@ function createServiceGatewayHost(client, context) {
16033
16170
  // src/launcher.ts
16034
16171
  var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
16035
16172
  async function writeOriCodexCatalog(stateDir, models) {
16036
- const path = join24(stateDir, "ori-codex-models.json");
16173
+ const path = join25(stateDir, "ori-codex-models.json");
16037
16174
  const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
16038
16175
  await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
16039
16176
  `, { mode: 384, flag: "wx" });
@@ -16127,7 +16264,7 @@ async function prepareOriForPlan(plan, options) {
16127
16264
  });
16128
16265
  try {
16129
16266
  const shim = prepareOriModelPolicy(request.target, native);
16130
- 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);
16131
16268
  await mkdir14(dir, { mode: 448 });
16132
16269
  await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
16133
16270
  return { contract, prepared: {
@@ -16143,6 +16280,57 @@ async function prepareOriForPlan(plan, options) {
16143
16280
  throw error;
16144
16281
  }
16145
16282
  }
16283
+ async function sharedNativeHome(state, root, profileId, environment = process.env) {
16284
+ const variable = state.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
16285
+ const configured = environment[variable] ? resolve14(environment[variable]) : undefined;
16286
+ const configuredCorpus = configured !== undefined && await realpath8(configured).catch(() => configured) === state.home;
16287
+ const home = state.tool === "claude" && (!configured || configured === state.home || configuredCorpus) ? join25(root, "native-claude", profileId) : configured ?? state.home;
16288
+ return { home, settingsEnvironment: configuredCorpus ? { ...environment, CLAUDE_CONFIG_DIR: undefined } : environment };
16289
+ }
16290
+ var SESSION_DIRECTORY_HARNESSES = ["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie", "claude"];
16291
+ function launchSessionDirectory(root, harness, profileId) {
16292
+ return join25(root, "sessions", harness, profileId);
16293
+ }
16294
+ async function checkSharedNativeLaunch(state, root, profileId, options = {}) {
16295
+ const warnings = await legacyNativeStateWarnings(root, state);
16296
+ if (options.desktop)
16297
+ return warnings;
16298
+ const overlay = await sharedNativeHome(state, root, profileId);
16299
+ const suffix = relative7(root, overlay.home);
16300
+ const created = suffix !== ".." && !suffix.startsWith("../") && !await lstat13(root).catch(() => {
16301
+ return;
16302
+ }) ? root : undefined;
16303
+ if (created)
16304
+ await assertCreatableNativeStateDirectory(created);
16305
+ if (state.tool === "claude")
16306
+ warnings.push(...await prepareClaudeUserSettings(overlay.home, overlay.settingsEnvironment, state.home, { write: false, created }));
16307
+ await checkPrivateDirectory(overlay.home);
16308
+ await assertNativeInstructionOverlay(state, overlay.home, { plan: true });
16309
+ await checkNativeStateProjection(state, overlay.home);
16310
+ return warnings;
16311
+ }
16312
+ function isolatedNativeHome(tool, root, profileId, options = {}, environment = process.env) {
16313
+ if (options.desktop)
16314
+ return { home: join25(root, "desktop", profileId, "codex"), private: false };
16315
+ if (options.claudeDesktop)
16316
+ return { home: join25(root, "desktop-claude", profileId), private: false };
16317
+ const configured = environment[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
16318
+ return { home: configured ? resolve14(configured) : join25(root, `native-${tool}`, profileId), private: true };
16319
+ }
16320
+ async function checkDirectLaunch(root, profileId, harness, options = {}) {
16321
+ const desktop = Boolean(options.desktop || options.claudeDesktop);
16322
+ await checkPrivateDirectory(root);
16323
+ const warnings = options.sharedState ? await checkSharedNativeLaunch(options.sharedState, root, profileId, { desktop }) : [];
16324
+ if (options.isolated && (harness === "codex" || harness === "claude")) {
16325
+ const isolated = isolatedNativeHome(harness, root, profileId, options);
16326
+ await assertNativeStateIsolation(harness, isolated.home);
16327
+ if (isolated.private)
16328
+ await checkPrivateDirectory(isolated.home);
16329
+ }
16330
+ if (harness === "claude" && !desktop)
16331
+ await checkPrivateDirectory(claudeSettingsDirectory(launchSessionDirectory(root, harness, profileId)));
16332
+ return warnings;
16333
+ }
16146
16334
  async function launch(client, profileId, options = {}) {
16147
16335
  if (options.backend === "ori" && options.shareNativeState === false)
16148
16336
  throw new Fault(400, "native_state_backend", "Explicit native-state isolation requires the direct adapter; Ori isolation is not yet verified.");
@@ -16184,9 +16372,9 @@ async function launch(client, profileId, options = {}) {
16184
16372
  validateHarnessVersion("gemini", detection?.version);
16185
16373
  if (backend === "direct" && plan.profile.harness === "aider")
16186
16374
  validateHarnessVersion(plan.profile.harness, detection?.version);
16187
- const root = resolve14(options.stateDir ?? join24(switcherHome(), "state"));
16375
+ const root = resolve14(options.stateDir ?? join25(switcherHome(), "state"));
16188
16376
  await privateDirectory(root);
16189
- const stateDir = await mkdtemp(join24(root, "launch-"));
16377
+ const stateDir = await mkdtemp(join25(root, "launch-"));
16190
16378
  let credential;
16191
16379
  if (backend === "direct") {
16192
16380
  try {
@@ -16194,7 +16382,7 @@ async function launch(client, profileId, options = {}) {
16194
16382
  if (plan.provider.credentialEnv && !credential)
16195
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.`);
16196
16384
  } catch (error) {
16197
- await rm6(stateDir, { recursive: true, force: true });
16385
+ await rm7(stateDir, { recursive: true, force: true });
16198
16386
  throw error;
16199
16387
  }
16200
16388
  }
@@ -16253,28 +16441,22 @@ async function launch(client, profileId, options = {}) {
16253
16441
  const stateWarnings = sharedState ? ["Shared native state is enabled. Resumed conversation history uses this launch's selected provider and model; Switcher does not infer unverified original-provider provenance.", ...await legacyNativeStateWarnings(root, sharedState)] : [];
16254
16442
  let nativeHome2;
16255
16443
  if (sharedState && !options.desktop && !options.claudeDesktop) {
16256
- const variable = sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
16257
- const configured = process.env[variable] ? resolve14(process.env[variable]) : undefined;
16258
- const configuredCorpus = configured && await realpath8(configured).catch(() => configured) === sharedState.home;
16259
- nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home || configuredCorpus) ? join24(root, "native-claude", profileId) : configured ?? sharedState.home;
16444
+ const overlay = await sharedNativeHome(sharedState, root, profileId);
16445
+ nativeHome2 = overlay.home;
16260
16446
  if (sharedState.tool === "claude")
16261
- stateWarnings.push(...await prepareClaudeUserSettings(nativeHome2, configuredCorpus ? { ...process.env, CLAUDE_CONFIG_DIR: undefined } : process.env, sharedState.home));
16447
+ stateWarnings.push(...await prepareClaudeUserSettings(nativeHome2, overlay.settingsEnvironment, sharedState.home));
16262
16448
  await privateDirectory(nativeHome2);
16263
16449
  await assertNativeInstructionOverlay(sharedState, nativeHome2);
16264
16450
  await projectNativeState(sharedState, nativeHome2);
16265
16451
  }
16266
16452
  if (options.shareNativeState === false && backend === "direct") {
16267
16453
  const tool = plan.profile.harness;
16268
- if (options.desktop)
16269
- await assertNativeStateIsolation(tool, join24(root, "desktop", desktopState, "codex"));
16270
- else if (options.claudeDesktop)
16271
- await assertNativeStateIsolation(tool, join24(root, "desktop-claude", desktopState));
16272
- else {
16273
- const variable = tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
16274
- nativeHome2 = process.env[variable] ? resolve14(process.env[variable]) : join24(root, `native-${tool}`, profileId);
16275
- await assertNativeStateIsolation(tool, nativeHome2);
16276
- await privateDirectory(nativeHome2);
16277
- }
16454
+ const isolated = isolatedNativeHome(tool, root, desktopState, { desktop: Boolean(options.desktop), claudeDesktop: Boolean(options.claudeDesktop) });
16455
+ if (isolated.private)
16456
+ nativeHome2 = isolated.home;
16457
+ await assertNativeStateIsolation(tool, isolated.home);
16458
+ if (isolated.private)
16459
+ await privateDirectory(isolated.home);
16278
16460
  }
16279
16461
  const input = {
16280
16462
  harness: plan.profile.harness,
@@ -16291,7 +16473,7 @@ async function launch(client, profileId, options = {}) {
16291
16473
  cwd: resolve14(options.cwd ?? process.cwd()),
16292
16474
  sharedState
16293
16475
  };
16294
- 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({
16295
16477
  harness: plan.profile.harness,
16296
16478
  baseUrl: plan.provider.baseUrl,
16297
16479
  protocol: plan.provider.protocol,
@@ -16311,7 +16493,7 @@ async function launch(client, profileId, options = {}) {
16311
16493
  version: detection?.version,
16312
16494
  sharedState,
16313
16495
  gatewayHost,
16314
- ...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie", "claude"].includes(plan.profile.harness) ? { sessionDir: join24(root, "sessions", plan.profile.harness, profileId) } : {}
16496
+ ...SESSION_DIRECTORY_HARNESSES.includes(plan.profile.harness) ? { sessionDir: launchSessionDirectory(root, plan.profile.harness, profileId) } : {}
16315
16497
  });
16316
16498
  cleanup = prepared.cleanup;
16317
16499
  prepared = { ...prepared, warnings: [...prepared.warnings, ...stateWarnings] };
@@ -16328,7 +16510,7 @@ async function launch(client, profileId, options = {}) {
16328
16510
  prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
16329
16511
  }
16330
16512
  if (options.desktop) {
16331
- 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);
16332
16514
  cleanup = prepared.cleanup;
16333
16515
  }
16334
16516
  for (const warning of [...plan.warnings, ...prepared.warnings])
@@ -16437,7 +16619,7 @@ async function launch(client, profileId, options = {}) {
16437
16619
  await cleanup?.();
16438
16620
  } finally {
16439
16621
  if (!gatewayHost?.retainedState())
16440
- await rm6(stateDir, { recursive: true, force: true });
16622
+ await rm7(stateDir, { recursive: true, force: true });
16441
16623
  }
16442
16624
  }
16443
16625
  }
@@ -16550,14 +16732,14 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
16550
16732
  // src/native-state-import.ts
16551
16733
  import { createHash as createHash18 } from "crypto";
16552
16734
  import { constants as constants11 } from "fs";
16553
- import { lstat as lstat13, open as open9, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
16554
- import { basename as basename6, dirname as dirname11, isAbsolute as isAbsolute19, join as join25, relative as relative6, resolve as resolve15 } from "path";
16735
+ import { lstat as lstat14, open as open9, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink5 } from "fs/promises";
16736
+ import { basename as basename6, dirname as dirname11, isAbsolute as isAbsolute19, join as join26, relative as relative8, resolve as resolve15 } from "path";
16555
16737
  var MAX_FILES = 1e5;
16556
16738
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
16557
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.");
16558
16740
  async function info2(path) {
16559
16741
  try {
16560
- return await lstat13(path);
16742
+ return await lstat14(path);
16561
16743
  } catch (error) {
16562
16744
  if (error.code === "ENOENT")
16563
16745
  return;
@@ -16567,7 +16749,7 @@ async function info2(path) {
16567
16749
  var identity = (s) => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs, ctimeMs: s.ctimeMs });
16568
16750
  var same = (a, b) => JSON.stringify(identity(a)) === JSON.stringify(identity(b));
16569
16751
  var inside3 = (parent, child) => {
16570
- const path = relative6(parent, child);
16752
+ const path = relative8(parent, child);
16571
16753
  return path !== ".." && !path.startsWith("../") && !isAbsolute19(path);
16572
16754
  };
16573
16755
  var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
@@ -16587,7 +16769,7 @@ async function sessionId(path, expected) {
16587
16769
  length += read.bytesRead;
16588
16770
  newline = buffer.indexOf(10, 0);
16589
16771
  }
16590
- const after = await handle.stat(), named = await lstat13(path);
16772
+ const after = await handle.stat(), named = await lstat14(path);
16591
16773
  if (!same(before, after) || !same(after, named) || after.nlink !== 1 || named.nlink !== 1 || named.isSymbolicLink())
16592
16774
  throw refused();
16593
16775
  if (newline < 0 && before.size > buffer.length)
@@ -16616,7 +16798,7 @@ async function checkSessionIdentities(plan) {
16616
16798
  for (const file of plan.files) {
16617
16799
  if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
16618
16800
  continue;
16619
- file.sessionId = await sessionId(join25(plan.source, file.path), file.source);
16801
+ file.sessionId = await sessionId(join26(plan.source, file.path), file.source);
16620
16802
  if (!file.sessionId)
16621
16803
  continue;
16622
16804
  const previous = ids.get(file.sessionId);
@@ -16640,7 +16822,7 @@ async function checkSessionIdentities(plan) {
16640
16822
  for await (const entry of await opendir2(directory)) {
16641
16823
  if (++seen > MAX_FILES || entry.isSymbolicLink())
16642
16824
  throw refused();
16643
- const path = join25(directory, entry.name);
16825
+ const path = join26(directory, entry.name);
16644
16826
  if (entry.isDirectory()) {
16645
16827
  await scan(path, depth + 1);
16646
16828
  continue;
@@ -16657,8 +16839,8 @@ async function checkSessionIdentities(plan) {
16657
16839
  file.existing = true;
16658
16840
  }
16659
16841
  }
16660
- await scan(join25(plan.state.home, "sessions"));
16661
- 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"));
16662
16844
  }
16663
16845
  async function fingerprint2(path, copyTo) {
16664
16846
  const handle = await open9(path, constants11.O_RDONLY | constants11.O_NOFOLLOW);
@@ -16686,7 +16868,7 @@ async function fingerprint2(path, copyTo) {
16686
16868
  offset += (await output.write(chunk, offset, chunk.length - offset)).bytesWritten;
16687
16869
  }
16688
16870
  }
16689
- const after = await handle.stat(), named = await lstat13(path);
16871
+ const after = await handle.stat(), named = await lstat14(path);
16690
16872
  if (named.isSymbolicLink() || after.nlink !== 1 || named.nlink !== 1 || bytes !== before.size || !same(before, after) || !same(after, named))
16691
16873
  throw refused();
16692
16874
  await output?.sync();
@@ -16718,9 +16900,9 @@ async function planNativeStateImport(state, source, selection) {
16718
16900
  async function visit(path, kind) {
16719
16901
  if (++seen > MAX_FILES || path.split("/").length > 32)
16720
16902
  throw refused();
16721
- await ensureNativeStateDirectory(dirname11(join25(source, path)), false);
16722
- await ensureNativeStateDirectory(dirname11(join25(state.home, path)), false);
16723
- 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);
16724
16906
  if (!entry)
16725
16907
  return;
16726
16908
  if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
@@ -16739,7 +16921,7 @@ async function planNativeStateImport(state, source, selection) {
16739
16921
  }
16740
16922
  children.sort((a, b) => a.name.localeCompare(b.name));
16741
16923
  for (const child of children)
16742
- await visit(join25(path, child.name), child.kind);
16924
+ await visit(join26(path, child.name), child.kind);
16743
16925
  } else {
16744
16926
  const value = await fingerprint2(from);
16745
16927
  plan.bytes += value.bytes;
@@ -16793,14 +16975,14 @@ async function applyNativeStateImportUnlocked(plan) {
16793
16975
  throw refused();
16794
16976
  const requiredDirectories = new Set([plan.state.home]);
16795
16977
  for (const path of plan.directories) {
16796
- 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)) {
16797
16979
  requiredDirectories.add(directory);
16798
16980
  if (directory === plan.state.home)
16799
16981
  break;
16800
16982
  }
16801
16983
  }
16802
16984
  for (const file of plan.files.filter((file2) => !file2.existing)) {
16803
- 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)) {
16804
16986
  requiredDirectories.add(directory);
16805
16987
  if (directory === plan.state.home)
16806
16988
  break;
@@ -16821,9 +17003,9 @@ async function applyNativeStateImportUnlocked(plan) {
16821
17003
  for (const file of plan.files) {
16822
17004
  if (file.existing)
16823
17005
  continue;
16824
- 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()}`);
16825
17007
  staged.push({ temporary, target });
16826
- const copied = await fingerprint2(join25(plan.source, file.path), temporary);
17008
+ const copied = await fingerprint2(join26(plan.source, file.path), temporary);
16827
17009
  if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
16828
17010
  throw refused();
16829
17011
  }
@@ -17336,16 +17518,23 @@ async function main(args = process.argv.slice(2)) {
17336
17518
  const sharedNativeState = ["codex", "claude"].includes(plan.profile.harness) && nativeStateRequested(plan.profile.harness, process.env, shareNativeState);
17337
17519
  const suffix = plan.profile.harness.toUpperCase();
17338
17520
  const marked = process.env[`HASNA_${suffix}_STATE_HOME`] !== undefined || process.env[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
17339
- const nativeState = sharedNativeState ? { shared: true, consent: shareNativeState === true ? "command" : marked ? "environment" : "default" } : shareNativeState === false ? { shared: false, consent: "command" } : undefined;
17340
17521
  if ((sharedNativeState || shareNativeState === false) && plan.profile.harness === "codex")
17341
17522
  assertHarnessArguments("codex", nativeArgs, { reservedCodexRoots: ["sqlite_home"] });
17342
- if (sharedNativeState)
17523
+ const root = resolve16(values2["state-dir"] ?? join27(switcherHome(), "state"));
17524
+ if (backend !== "direct")
17525
+ await checkPrivateDirectory(root);
17526
+ const nativeWarnings = backend === "direct" ? await checkDirectLaunch(root, profileId, plan.profile.harness, {
17527
+ desktop: Boolean(desktop),
17528
+ claudeDesktop: Boolean(claudeApp),
17529
+ isolated: shareNativeState === false,
17530
+ ...sharedNativeState ? { sharedState: await resolveNativeState(plan.profile.harness, process.env, { create: false }) } : {}
17531
+ }) : [];
17532
+ const nativeState = sharedNativeState ? { shared: true, consent: shareNativeState === true ? "command" : marked ? "environment" : "default", ...nativeWarnings.length ? { warnings: nativeWarnings } : {} } : shareNativeState === false ? { shared: false, consent: "command" } : undefined;
17533
+ if (sharedNativeState && backend !== "direct")
17343
17534
  await resolveNativeState(plan.profile.harness, process.env, { create: false });
17344
- if (shareNativeState === false) {
17345
- const tool = plan.profile.harness, root = resolve16(values2["state-dir"] ?? join26(switcherHome(), "state"));
17346
- const configured = process.env[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
17347
- const home = desktop ? join26(root, "desktop", profileId, "codex") : claudeApp ? join26(root, "desktop-claude", profileId) : configured ? resolve16(configured) : join26(root, `native-${tool}`, profileId);
17348
- await assertNativeStateIsolation(tool, home);
17535
+ if (shareNativeState === false && backend !== "direct") {
17536
+ const tool = plan.profile.harness;
17537
+ await assertNativeStateIsolation(tool, isolatedNativeHome(tool, root, profileId, { desktop: Boolean(desktop), claudeDesktop: Boolean(claudeApp) }).home);
17349
17538
  }
17350
17539
  if (backend === "ori") {
17351
17540
  if (sharedNativeState)