@hasna/switcher 0.2.10 → 0.2.12

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.10";
517
+ var version = "0.2.12";
518
518
 
519
519
  // src/version.ts
520
520
  var VERSION = version;
@@ -1109,6 +1109,7 @@ function assertHarnessArguments(harness, args, options = {}) {
1109
1109
 
1110
1110
  // src/cli.ts
1111
1111
  import { parseArgs } from "util";
1112
+ import { join as join24, resolve as resolve14 } from "path";
1112
1113
 
1113
1114
  // src/http.ts
1114
1115
  var MAX_BYTES = 16 * 1024 * 1024;
@@ -1318,7 +1319,7 @@ function providerCredential(provider, env = process.env) {
1318
1319
  import { execFile } from "child_process";
1319
1320
  import { access, stat as stat3 } from "fs/promises";
1320
1321
  import { constants as constants2 } from "fs";
1321
- import { homedir as homedir2 } from "os";
1322
+ import { homedir as homedir2, userInfo as userInfo2 } from "os";
1322
1323
  import { isAbsolute as isAbsolute3, join as join3 } from "path";
1323
1324
  import { promisify } from "util";
1324
1325
  var execute = promisify(execFile);
@@ -1371,9 +1372,14 @@ async function detectChatGPTApp(appPath, system = host) {
1371
1372
  const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
1372
1373
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
1373
1374
  continue;
1374
- const executable = join3(path, "Contents/MacOS", name), codexExecutable = join3(path, "Contents/Resources/codex");
1375
- if (await system.executable(executable) && await system.executable(codexExecutable))
1376
- return { path, executable, codexExecutable, bundleId, version: version2 };
1375
+ const executable = join3(path, "Contents/MacOS", name);
1376
+ if (!await system.executable(executable))
1377
+ continue;
1378
+ for (const relative2 of ["Contents/Resources/codex", "Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex"]) {
1379
+ const codexExecutable = join3(path, relative2);
1380
+ if (await system.executable(codexExecutable))
1381
+ return { path, executable, codexExecutable, bundleId, version: version2 };
1382
+ }
1377
1383
  } catch {}
1378
1384
  }
1379
1385
  throw new Fault(404, "app_not_installed", "Install the current ChatGPT/Codex macOS app or use --app-path with its absolute .app path. Legacy ChatGPT Classic cannot run custom Codex providers.");
@@ -1406,6 +1412,28 @@ async function detectClaudeDesktopApp(appPath, system = host) {
1406
1412
  }
1407
1413
  throw new Fault(404, "app_not_installed", "Install the current Claude macOS desktop app or supply its absolute .app path with --app-path.");
1408
1414
  }
1415
+ var claudeDesktopDataDirectory = () => join3(homedir2(), "Library/Application Support/Claude-3p");
1416
+ function validateClaudeDesktopVersion(app) {
1417
+ const version2 = app.version.split(".").map(Number);
1418
+ if (version2.length < 3 || version2.some((n) => !Number.isSafeInteger(n)) || version2[0] < 1 || version2[0] === 1 && version2[1] < 52386)
1419
+ throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for the gateway adapter.");
1420
+ }
1421
+ async function assertClaudeDesktopAvailable(userData) {
1422
+ for (const path of [join3("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
1423
+ if (await access(path).then(() => true, () => false))
1424
+ throw new Fault(409, "desktop_managed", "Claude has managed preferences; Switcher will not override them.");
1425
+ let openFiles;
1426
+ try {
1427
+ openFiles = (await execute("/usr/sbin/lsof", ["-n", "-P", "-Fpn", "-a", "-u", String(process.getuid?.()), "-c", "Claude"], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, timeout: 8000 })).stdout;
1428
+ } catch (error) {
1429
+ if (error.code === 1)
1430
+ return;
1431
+ throw new Fault(409, "desktop_process_check", "Could not check whether Claude's third-party profile is already running.");
1432
+ }
1433
+ if (openFiles.split(`
1434
+ `).some((line) => line.startsWith("n" + userData + "/")))
1435
+ throw new Fault(409, "desktop_busy", "Claude's third-party instance is already running.");
1436
+ }
1409
1437
 
1410
1438
  // src/sdk.ts
1411
1439
  class SwitcherError extends Error {
@@ -1884,7 +1912,6 @@ import { parseTree as parseTree2, getNodeValue } from "jsonc-parser";
1884
1912
 
1885
1913
  // src/runtime.ts
1886
1914
  import { randomBytes } from "crypto";
1887
- import { mkdir as mkdir4, lstat } from "fs/promises";
1888
1915
  import { homedir as homedir3 } from "os";
1889
1916
  import { isAbsolute as isAbsolute4, join as join4, resolve as resolve3 } from "path";
1890
1917
 
@@ -2543,7 +2570,7 @@ var openapi_default = {
2543
2570
  openapi: "3.0.3",
2544
2571
  info: {
2545
2572
  title: "Switcher API",
2546
- version: "0.2.10",
2573
+ version: "0.2.12",
2547
2574
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2548
2575
  },
2549
2576
  security: [
@@ -7122,13 +7149,8 @@ function announceSwitcherLocalMode(home, write = (line) => {
7122
7149
  `);
7123
7150
  }
7124
7151
 
7125
- // src/runtime.ts
7126
- var REMOTE_API_CONFIG_MISSING = "remote_api_config_missing";
7127
- function switcherHome(env = process.env) {
7128
- const override = env.HASNA_HOME?.trim();
7129
- const root = override && isAbsolute4(override) ? override : join4(env.HOME?.trim() || homedir3(), ".hasna");
7130
- return resolve3(env.HASNA_SWITCHER_HOME ?? join4(root, "switcher"));
7131
- }
7152
+ // src/private-directory.ts
7153
+ import { mkdir as mkdir4, lstat } from "fs/promises";
7132
7154
  async function privateDirectory(path) {
7133
7155
  await mkdir4(path, { recursive: true, mode: 448 });
7134
7156
  const info = await lstat(path);
@@ -7137,6 +7159,14 @@ async function privateDirectory(path) {
7137
7159
  if (process.platform !== "win32" && ((info.mode & 63) !== 0 || info.uid !== process.getuid?.()))
7138
7160
  throw new Fault(500, "home_permissions", "Switcher data directory must be owned by this user and accessible only to its owner (mode 0700).");
7139
7161
  }
7162
+
7163
+ // src/runtime.ts
7164
+ var REMOTE_API_CONFIG_MISSING = "remote_api_config_missing";
7165
+ function switcherHome(env = process.env) {
7166
+ const override = env.HASNA_HOME?.trim();
7167
+ const root = override && isAbsolute4(override) ? override : join4(env.HOME?.trim() || homedir3(), ".hasna");
7168
+ return resolve3(env.HASNA_SWITCHER_HOME ?? join4(root, "switcher"));
7169
+ }
7140
7170
  async function openCliRuntime(env = process.env, resolveCredential) {
7141
7171
  const providerEnv = Object.fromEntries(Object.entries(env).filter(([name]) => name.startsWith("SWITCHER_PROVIDER_")));
7142
7172
  const remote = () => ({ client: clientFromEnv(env), mode: "remote", providerEnv, close: async () => {} });
@@ -11323,8 +11353,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
11323
11353
  }
11324
11354
 
11325
11355
  // src/launcher.ts
11326
- import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile17 } from "fs/promises";
11327
- import { join as join20, resolve as resolve11 } from "path";
11356
+ import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile18 } from "fs/promises";
11357
+ import { join as join22, resolve as resolve12 } from "path";
11328
11358
 
11329
11359
  // src/provider-credential-onboarding.ts
11330
11360
  import { z as z9 } from "zod";
@@ -12618,29 +12648,103 @@ function oriLaunchWarnings(target) {
12618
12648
 
12619
12649
  // src/chatgpt-launch.ts
12620
12650
  import { createHash as createHash12 } from "crypto";
12621
- import { writeFile as writeFile15, rm as rm4 } from "fs/promises";
12651
+ import { writeFile as writeFile14, rm as rm4 } from "fs/promises";
12622
12652
  import { join as join18 } from "path";
12623
12653
  import { fileURLToPath } from "url";
12624
12654
 
12625
12655
  // src/desktop-state.ts
12626
- import { Database as Database3 } from "bun:sqlite";
12627
- import { readFile as readFile7, writeFile as writeFile14, rm as rm3, lstat as lstat7, rename as rename2, chmod as chmod2 } from "fs/promises";
12628
- async function safeDesktopRead(path) {
12656
+ import { constants as constants7, closeSync as closeSync2, fstatSync, lstatSync, openSync as openSync2, readSync as readSync2 } from "fs";
12657
+ import { open as open4, rm as rm3, lstat as lstat7, rename as rename2, chmod as chmod2 } from "fs/promises";
12658
+ var desktopReadLimit = 1024 * 1024;
12659
+ function admitDesktopFile(info) {
12660
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== process.getuid?.() || (info.mode & 18) !== 0 || info.size > desktopReadLimit)
12661
+ throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user.");
12662
+ }
12663
+ function admitOpenedDesktopFile(info, opened) {
12664
+ if (opened.dev !== info.dev || opened.ino !== info.ino || opened.nlink !== 1 || opened.size > desktopReadLimit || opened.mode !== info.mode || opened.uid !== info.uid)
12665
+ throw new Fault(409, "desktop_state_changed", "Desktop settings changed while being read.");
12666
+ }
12667
+ function desktopSnapshot(bytes, length, opened, after) {
12668
+ if (length > desktopReadLimit || length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs || after.mode !== opened.mode)
12669
+ throw new Fault(409, "desktop_state_changed", "Desktop settings changed while being read.");
12670
+ try {
12671
+ return { text: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, length)), mode: after.mode & 4095 };
12672
+ } catch {
12673
+ throw new Fault(422, "desktop_state_encoding", "Desktop settings must be valid UTF-8; original bytes were left unchanged.");
12674
+ }
12675
+ }
12676
+ async function safeDesktopSnapshot(path) {
12629
12677
  try {
12630
12678
  const info = await lstat7(path);
12631
- if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
12632
- throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user.");
12633
- return await readFile7(path, "utf8");
12679
+ admitDesktopFile(info);
12680
+ const file = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12681
+ try {
12682
+ const opened = await file.stat();
12683
+ admitOpenedDesktopFile(info, opened);
12684
+ const bytes = Buffer.alloc(desktopReadLimit + 1);
12685
+ let length = 0;
12686
+ while (length < bytes.length) {
12687
+ const read = await file.read(bytes, length, bytes.length - length, length);
12688
+ if (read.bytesRead === 0)
12689
+ break;
12690
+ length += read.bytesRead;
12691
+ }
12692
+ return desktopSnapshot(bytes, length, opened, await file.stat());
12693
+ } finally {
12694
+ await file.close();
12695
+ }
12634
12696
  } catch (error) {
12635
12697
  if (error.code === "ENOENT")
12636
12698
  return;
12637
12699
  throw error;
12638
12700
  }
12639
12701
  }
12640
- async function writeDesktopPrivate(path, text) {
12702
+ function safeDesktopSnapshotSync(path) {
12703
+ try {
12704
+ const info = lstatSync(path);
12705
+ admitDesktopFile(info);
12706
+ const file = openSync2(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12707
+ try {
12708
+ const opened = fstatSync(file);
12709
+ admitOpenedDesktopFile(info, opened);
12710
+ const bytes = Buffer.alloc(desktopReadLimit + 1);
12711
+ let length = 0;
12712
+ while (length < bytes.length) {
12713
+ const count = readSync2(file, bytes, length, bytes.length - length, length);
12714
+ if (count === 0)
12715
+ break;
12716
+ length += count;
12717
+ }
12718
+ const snapshot2 = desktopSnapshot(bytes, length, opened, fstatSync(file));
12719
+ admitOpenedDesktopFile(opened, lstatSync(path));
12720
+ return snapshot2;
12721
+ } finally {
12722
+ closeSync2(file);
12723
+ }
12724
+ } catch (error) {
12725
+ if (error.code === "ENOENT")
12726
+ return;
12727
+ throw error;
12728
+ }
12729
+ }
12730
+ async function safeDesktopRead(path) {
12731
+ return (await safeDesktopSnapshot(path))?.text;
12732
+ }
12733
+ async function writeDesktopPrivate(path, text, mode = 384) {
12734
+ if (!Number.isInteger(mode) || mode < 0 || mode > 4095 || (mode & 18) !== 0)
12735
+ throw new Fault(422, "desktop_state_permissions", "Desktop settings restoration requires an admitted original mode.");
12641
12736
  const temporary = path + "." + crypto.randomUUID() + ".tmp";
12642
12737
  try {
12643
- await writeFile14(temporary, text, { mode: 384, flag: "wx" });
12738
+ const file = await open4(temporary, "wx", 384);
12739
+ try {
12740
+ await file.writeFile(text);
12741
+ await file.chmod(mode);
12742
+ } finally {
12743
+ await file.close();
12744
+ }
12745
+ const written = await safeDesktopSnapshot(temporary);
12746
+ if (written?.text !== text || written.mode !== mode)
12747
+ throw new Fault(409, "desktop_state_changed", "Desktop settings restoration readback failed.");
12644
12748
  await rename2(temporary, path);
12645
12749
  } finally {
12646
12750
  await rm3(temporary, { force: true });
@@ -12649,13 +12753,13 @@ async function writeDesktopPrivate(path, text) {
12649
12753
  async function desktopLease(path) {
12650
12754
  try {
12651
12755
  const info = await lstat7(path);
12652
- if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
12756
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== process.getuid?.() || (info.mode & 18) !== 0)
12653
12757
  throw new Fault(422, "desktop_state_permissions", "Desktop lease must be a regular file owned by this user.");
12654
12758
  } catch (error) {
12655
12759
  if (error.code !== "ENOENT")
12656
12760
  throw error;
12657
12761
  }
12658
- const lease = new Database3(path);
12762
+ const lease = await openDesktopLease(path);
12659
12763
  try {
12660
12764
  await chmod2(path, 384);
12661
12765
  lease.exec("PRAGMA busy_timeout=0; CREATE TABLE IF NOT EXISTS lease (id INTEGER PRIMARY KEY); BEGIN EXCLUSIVE;");
@@ -12671,15 +12775,32 @@ async function desktopLease(path) {
12671
12775
  }
12672
12776
  };
12673
12777
  }
12778
+ async function openDesktopLease(path, readOnly2 = false) {
12779
+ try {
12780
+ if (process.versions.bun) {
12781
+ const { Database: Database3 } = await import("bun:sqlite");
12782
+ return readOnly2 ? new Database3(path, { readonly: true }) : new Database3(path);
12783
+ }
12784
+ const [major, minor] = process.versions.node.split(".").map(Number);
12785
+ if (major !== 24 || minor < 20)
12786
+ throw new Error("unsupported runtime");
12787
+ const { DatabaseSync } = await import("node:sqlite");
12788
+ return new DatabaseSync(path, { readOnly: readOnly2 });
12789
+ } catch {
12790
+ throw new Fault(422, "desktop_runtime", "Desktop gateway state requires Bun or Node 24.20 or newer in the Node 24 release line with node:sqlite.");
12791
+ }
12792
+ }
12674
12793
 
12675
12794
  // src/native-state.ts
12676
- import { lstat as lstat8, mkdir as mkdir11, open as open4, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
12677
- import { constants as constants7 } from "fs";
12795
+ import { lstat as lstat8, mkdir as mkdir11, open as open5, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
12796
+ import { constants as constants8, lstatSync as lstatSync2, realpathSync } from "fs";
12678
12797
  import { homedir as homedir9 } from "os";
12679
12798
  import { dirname as dirname8, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve9 } from "path";
12680
- function nativeStateRequested(tool, environment = process.env, explicit = false) {
12799
+ function nativeStateRequested(tool, environment = process.env, explicit) {
12800
+ if (explicit !== undefined)
12801
+ return explicit;
12681
12802
  const suffix = tool.toUpperCase();
12682
- return explicit || environment[`HASNA_${suffix}_STATE_HOME`] !== undefined || environment[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
12803
+ return tool === "claude" || environment[`HASNA_${suffix}_STATE_HOME`] !== undefined || environment[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
12683
12804
  }
12684
12805
  function validateNativeStateVersion(tool, version2) {
12685
12806
  if (tool !== "codex")
@@ -12703,11 +12824,11 @@ var CODEX_INSTRUCTION_KEYS = [
12703
12824
  ];
12704
12825
  var NATIVE_STATE_ENTRIES = {
12705
12826
  codex: [
12706
- ...["sessions", "archived_sessions", "thread-writer-locks", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12827
+ ...["sessions", "archived_sessions", "thread-writer-locks", "skills", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12707
12828
  ...["history.jsonl", "AGENTS.md", "AGENTS.override.md"].map((name) => ({ name, kind: "file" }))
12708
12829
  ],
12709
12830
  claude: [
12710
- ...["projects", "todos", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12831
+ ...["projects", "todos", "skills", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12711
12832
  ...["history.jsonl", "CLAUDE.md"].map((name) => ({ name, kind: "file" }))
12712
12833
  ]
12713
12834
  };
@@ -12728,20 +12849,26 @@ function absolute(value) {
12728
12849
  function credentialOverlay(path) {
12729
12850
  return /(?:^|\/)subscriptions\/profiles\//.test(path) || /(?:^|\/)switcher\/state\/(?:desktop|desktop-claude|launch-[^/]+)\//.test(path);
12730
12851
  }
12852
+ function assertSafeAncestor(ancestor) {
12853
+ const stickyRoot = ancestor.uid === 0 && (ancestor.mode & 512) !== 0;
12854
+ if (!ancestor.isDirectory() || ancestor.isSymbolicLink() || ![0, process.getuid?.()].includes(ancestor.uid) || (ancestor.mode & 18) !== 0 && !stickyRoot)
12855
+ throw new Fault(422, "native_state_permissions", "Shared native state has an unsafe ancestor directory.");
12856
+ }
12731
12857
  async function assertSafeAncestors(path) {
12732
12858
  for (let parent = path;; parent = dirname8(parent)) {
12733
- const ancestor = await lstat8(parent);
12734
- const stickyRoot = ancestor.uid === 0 && (ancestor.mode & 512) !== 0;
12735
- if (!ancestor.isDirectory() || ancestor.isSymbolicLink() || ![0, process.getuid?.()].includes(ancestor.uid) || (ancestor.mode & 18) !== 0 && !stickyRoot)
12736
- throw new Fault(422, "native_state_permissions", "Shared native state has an unsafe ancestor directory.");
12859
+ assertSafeAncestor(await lstat8(parent));
12737
12860
  if (parent === dirname8(parent))
12738
12861
  break;
12739
12862
  }
12740
12863
  }
12864
+ function assertNativeDirectoryEntry(entry, redirected = false) {
12865
+ if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || redirected)
12866
+ throw new Fault(422, "native_state_permissions", "Shared native state must be an owned directory without writable or symbolic-link redirection.");
12867
+ }
12741
12868
  async function assertNativeStateDirectory(path) {
12742
12869
  const entry = await info(path);
12743
- if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || await realpath6(path) !== path)
12744
- throw new Fault(422, "native_state_permissions", "Shared native state must be an owned directory without writable or symbolic-link redirection.");
12870
+ assertNativeDirectoryEntry(entry);
12871
+ assertNativeDirectoryEntry(entry, await realpath6(path) !== path);
12745
12872
  await assertSafeAncestors(dirname8(path));
12746
12873
  }
12747
12874
  async function ensureNativeStateDirectory(path, create = true) {
@@ -12756,12 +12883,36 @@ async function ensureNativeStateDirectory(path, create = true) {
12756
12883
  });
12757
12884
  await assertNativeStateDirectory(path);
12758
12885
  }
12886
+ async function assertNativeStateIsolation(tool, home, environment = process.env) {
12887
+ home = absolute(home);
12888
+ const canonical = await resolveNativeState(tool, environment, { create: false });
12889
+ const roots = [canonical.home, canonical.sqliteHome, join17(absolute(environment.HOME ?? homedir9()), `.${tool}`)];
12890
+ const contains = (parent, child) => {
12891
+ const path = relative5(parent, child);
12892
+ return path !== ".." && !path.startsWith("../") && !isAbsolute16(path);
12893
+ };
12894
+ if (roots.some((root) => root && (contains(root, home) || contains(home, root))))
12895
+ throw new Fault(409, "native_state_isolation_conflict", "The isolated home overlaps a canonical native corpus or database. Select a distinct private home; Switcher will not alter existing state.");
12896
+ if (!await info(home))
12897
+ return;
12898
+ await assertNativeStateDirectory(home);
12899
+ for (const { name } of NATIVE_STATE_ENTRIES[tool]) {
12900
+ await ensureNativeStateDirectory(dirname8(join17(home, name)), false);
12901
+ if ((await info(join17(home, name)))?.isSymbolicLink())
12902
+ throw new Fault(409, "native_state_isolation_conflict", "This profile already links native state. Select a separate isolated profile; Switcher will not remove its existing shared links.");
12903
+ }
12904
+ if (tool === "codex") {
12905
+ const config = await readCodexStateConfig(home);
12906
+ if (config.sqlite_home !== undefined && (typeof config.sqlite_home !== "string" || absolute(config.sqlite_home) !== home))
12907
+ 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.");
12908
+ }
12909
+ }
12759
12910
  async function withNativeStateLock(state, operation) {
12760
12911
  await ensureNativeStateDirectory(state.home);
12761
12912
  const path = join17(state.home, ".switcher-shared-state.lock");
12762
12913
  let handle;
12763
12914
  try {
12764
- handle = await open4(path, "wx", 384);
12915
+ handle = await open5(path, "wx", 384);
12765
12916
  } catch (error) {
12766
12917
  if (error.code !== "EEXIST")
12767
12918
  throw error;
@@ -12812,7 +12963,7 @@ async function readCodexStateConfig(home) {
12812
12963
  return {};
12813
12964
  if (!entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
12814
12965
  throw new Fault(422, "native_state_config", "The Codex instruction configuration cannot be read safely.");
12815
- const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12966
+ const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
12816
12967
  let config;
12817
12968
  try {
12818
12969
  const opened = await handle.stat();
@@ -12846,7 +12997,7 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
12846
12997
  if (!contained && path !== allowedExternalFiles[key] || !entry || !entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || ![0, process.getuid?.()].includes(entry.uid) || (entry.mode & 18) !== 0 || await realpath6(path) !== path)
12847
12998
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
12848
12999
  await assertSafeAncestors(dirname8(path));
12849
- const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW).catch(() => {
13000
+ const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW).catch(() => {
12850
13001
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
12851
13002
  });
12852
13003
  try {
@@ -13029,7 +13180,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13029
13180
  if (entry.kind === "directory")
13030
13181
  await createTrackedDirectory(target, createdDirectories);
13031
13182
  else {
13032
- const file = await open4(target, "wx", 384);
13183
+ const file = await open5(target, "wx", 384);
13033
13184
  await file.close();
13034
13185
  createdFiles.push(target);
13035
13186
  }
@@ -13181,7 +13332,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedSta
13181
13332
  fi
13182
13333
  `;
13183
13334
  }
13184
- await writeFile15(wrapper, `#!/bin/sh
13335
+ await writeFile14(wrapper, `#!/bin/sh
13185
13336
  set -eu
13186
13337
  unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
13187
13338
  export CODEX_HOME=${quote2(home)}
@@ -13212,37 +13363,254 @@ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join("
13212
13363
  }
13213
13364
 
13214
13365
  // src/claude-desktop-launch.ts
13215
- import { createHash as createHash13 } from "crypto";
13216
- import { execFile as execFile5 } from "child_process";
13217
- import { access as access4, rm as rm5, writeFile as writeFile16 } from "fs/promises";
13218
- import { homedir as homedir10, userInfo as userInfo2 } from "os";
13366
+ import { writeFile as writeFile17 } from "fs/promises";
13367
+ import { join as join21 } from "path";
13368
+ // src/desktop-selection.ts
13369
+ import { createHash as createHash13, randomUUID as randomUUID6 } from "crypto";
13370
+ import { rm as rm5, writeFile as writeFile15 } from "fs/promises";
13219
13371
  import { join as join19 } from "path";
13220
- import { promisify as promisify5 } from "util";
13221
- var execute4 = promisify5(execFile5);
13222
13372
  var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
13223
- var claudeDesktopDataDirectory = () => join19(homedir10(), "Library/Application Support/Claude-3p");
13224
- async function assertAvailable(userData) {
13225
- for (const path of [join19("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
13226
- if (await access4(path).then(() => true, () => false))
13227
- throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
13228
- let openFiles;
13373
+ var conflict = () => new Fault(409, "desktop_config_changed", "Desktop configuration changed; existing bytes and the recovery receipt were preserved.");
13374
+ var invalid3 = () => new Fault(409, "desktop_recovery", "Desktop selection needs recovery by its owning supported version before another launch.");
13375
+ var identifier = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,80}$/.test(value);
13376
+ var admittedMode = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4095 && (value & 18) === 0;
13377
+ var matches = (actual, text, mode) => (actual?.text ?? null) === text && (actual?.mode ?? null) === mode;
13378
+ function metadata(text) {
13379
+ if (text === null)
13380
+ return { entries: [] };
13381
+ let value;
13229
13382
  try {
13230
- openFiles = (await execute4("/usr/sbin/lsof", ["-n", "-P", "-Fpn", "-a", "-u", String(process.getuid?.()), "-c", "Claude"], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, timeout: 8000 })).stdout;
13383
+ value = JSON.parse(text);
13384
+ } catch {
13385
+ throw invalid3();
13386
+ }
13387
+ if (!value || typeof value !== "object" || Array.isArray(value))
13388
+ throw invalid3();
13389
+ const m = value;
13390
+ if (!Array.isArray(m.entries) || m.entries.some((x) => !x || typeof x !== "object" || Array.isArray(x)) || m.appliedId !== undefined && !identifier(m.appliedId))
13391
+ throw invalid3();
13392
+ return m;
13393
+ }
13394
+ function receipt(text) {
13395
+ let r;
13396
+ try {
13397
+ r = JSON.parse(text);
13398
+ } catch {
13399
+ throw invalid3();
13400
+ }
13401
+ if (r?.version !== 3 || !identifier(r.id) || !/^[0-9a-f-]{36}$/.test(r.id) || !/^[a-f0-9]{64}$/.test(r.configHash) || r.previousMeta !== null && typeof r.previousMeta !== "string" || typeof r.appliedMeta !== "string" || (r.previousMeta === null ? r.previousMetaMode !== null : !admittedMode(r.previousMetaMode)) || r.previousSelected !== null && (!r.previousSelected || !identifier(r.previousSelected.id) || r.previousSelected.text !== null && typeof r.previousSelected.text !== "string"))
13402
+ throw invalid3();
13403
+ const before = metadata(r.previousMeta), after = metadata(r.appliedMeta);
13404
+ if (after.appliedId !== r.id || before.appliedId === r.id || (before.appliedId ?? null) !== (r.previousSelected?.id ?? null))
13405
+ throw invalid3();
13406
+ return r;
13407
+ }
13408
+ async function selectedUnchanged(library, r) {
13409
+ if (r.previousSelected && (await safeDesktopRead(join19(library, r.previousSelected.id + ".json")) ?? null) !== r.previousSelected.text)
13410
+ throw conflict();
13411
+ }
13412
+ async function recoverDesktopSelection(library) {
13413
+ const path = join19(library, ".switcher-selection.json"), raw = await safeDesktopRead(path);
13414
+ if (raw === undefined)
13415
+ return;
13416
+ const r = receipt(raw), metaPath = join19(library, "_meta.json"), configPath = join19(library, r.id + ".json");
13417
+ const currentMeta = await safeDesktopSnapshot(metaPath), currentConfig = await safeDesktopRead(configPath);
13418
+ const wasOriginal = matches(currentMeta, r.previousMeta, r.previousMetaMode), wasApplied = matches(currentMeta, r.appliedMeta, 384);
13419
+ await selectedUnchanged(library, r);
13420
+ if (!wasOriginal && !wasApplied)
13421
+ throw conflict();
13422
+ if (currentConfig !== undefined && hash2(currentConfig) !== r.configHash || wasApplied && currentConfig === undefined)
13423
+ throw conflict();
13424
+ if (await safeDesktopRead(path) !== raw)
13425
+ throw conflict();
13426
+ if (!matches(await safeDesktopSnapshot(metaPath), currentMeta?.text ?? null, currentMeta?.mode ?? null))
13427
+ throw conflict();
13428
+ if (wasApplied) {
13429
+ if (r.previousMeta === null)
13430
+ await rm5(metaPath);
13431
+ else
13432
+ await writeDesktopPrivate(metaPath, r.previousMeta, r.previousMetaMode);
13433
+ if (!matches(await safeDesktopSnapshot(metaPath), r.previousMeta, r.previousMetaMode))
13434
+ throw conflict();
13435
+ }
13436
+ if (currentConfig !== undefined) {
13437
+ if (hash2(await safeDesktopRead(configPath) ?? "") !== r.configHash)
13438
+ throw conflict();
13439
+ await rm5(configPath);
13440
+ }
13441
+ if (await safeDesktopRead(path) !== raw)
13442
+ throw conflict();
13443
+ await rm5(path);
13444
+ }
13445
+ async function applyDesktopSelection(library, config, label2, checkpoint) {
13446
+ await recoverDesktopSelection(library);
13447
+ const path = join19(library, ".switcher-selection.json"), metaPath = join19(library, "_meta.json");
13448
+ const original = await safeDesktopSnapshot(metaPath), previousMeta = original?.text ?? null, previousMetaMode = original?.mode ?? null, previous = metadata(previousMeta);
13449
+ const previousSelected = previous.appliedId ? { id: previous.appliedId, text: await safeDesktopRead(join19(library, previous.appliedId + ".json")) ?? null } : null;
13450
+ const id2 = randomUUID6(), configPath = join19(library, id2 + ".json"), text = JSON.stringify(config, null, 2) + `
13451
+ `;
13452
+ const appliedMeta = JSON.stringify({ ...previous, appliedId: id2, entries: [...previous.entries, { id: id2, name: label2 }] }, null, 2) + `
13453
+ `;
13454
+ const r = { version: 3, id: id2, configHash: hash2(text), previousMeta, previousMetaMode, appliedMeta, previousSelected };
13455
+ const journal = JSON.stringify(r) + `
13456
+ `;
13457
+ if (Buffer.byteLength(journal) > 1024 * 1024)
13458
+ throw invalid3();
13459
+ await writeFile15(path, journal, { mode: 384, flag: "wx" });
13460
+ const unchanged = async () => {
13461
+ if (await safeDesktopRead(path) !== journal)
13462
+ throw conflict();
13463
+ await selectedUnchanged(library, r);
13464
+ };
13465
+ try {
13466
+ await unchanged();
13467
+ await checkpoint?.("preserved");
13468
+ if (!matches(await safeDesktopSnapshot(metaPath), previousMeta, previousMetaMode))
13469
+ throw conflict();
13470
+ await selectedUnchanged(library, r);
13471
+ await writeFile15(configPath, text, { mode: 384, flag: "wx" });
13472
+ if (await safeDesktopRead(configPath) !== text)
13473
+ throw conflict();
13474
+ await checkpoint?.("config");
13475
+ await unchanged();
13476
+ if (!matches(await safeDesktopSnapshot(metaPath), previousMeta, previousMetaMode))
13477
+ throw conflict();
13478
+ await writeDesktopPrivate(metaPath, appliedMeta);
13479
+ if (!matches(await safeDesktopSnapshot(metaPath), appliedMeta, 384))
13480
+ throw conflict();
13481
+ await checkpoint?.("selected");
13231
13482
  } catch (error) {
13232
- if (error.code === 1)
13483
+ try {
13484
+ if (await safeDesktopRead(path) === journal)
13485
+ await recoverDesktopSelection(library);
13486
+ } catch {}
13487
+ throw error;
13488
+ }
13489
+ const assertCurrentSync = () => {
13490
+ if (safeDesktopSnapshotSync(path)?.text !== journal)
13491
+ throw conflict();
13492
+ if (previousSelected && (safeDesktopSnapshotSync(join19(library, previousSelected.id + ".json"))?.text ?? null) !== previousSelected.text)
13493
+ throw conflict();
13494
+ if (!matches(safeDesktopSnapshotSync(metaPath), appliedMeta, 384) || safeDesktopSnapshotSync(configPath)?.text !== text)
13495
+ throw conflict();
13496
+ };
13497
+ return {
13498
+ configPath,
13499
+ assertCurrentSync,
13500
+ async assertCurrent() {
13501
+ assertCurrentSync();
13502
+ },
13503
+ async restore() {
13504
+ if (await safeDesktopRead(path) !== journal)
13505
+ throw conflict();
13506
+ await recoverDesktopSelection(library);
13507
+ }
13508
+ };
13509
+ }
13510
+
13511
+ // src/claude-user-settings.ts
13512
+ import { constants as constants9 } from "fs";
13513
+ import { lstat as lstat9, open as open6, writeFile as writeFile16 } from "fs/promises";
13514
+ import { homedir as homedir10 } from "os";
13515
+ import { join as join20, resolve as resolve10 } from "path";
13516
+ var preferences = new Set([
13517
+ "$schema",
13518
+ "permissions",
13519
+ "sandbox",
13520
+ "language",
13521
+ "outputStyle",
13522
+ "alwaysThinkingEnabled",
13523
+ "effortLevel",
13524
+ "cleanupPeriodDays",
13525
+ "autoUpdatesChannel",
13526
+ "includeCoAuthoredBy",
13527
+ "attribution",
13528
+ "respectGitignore",
13529
+ "spinnerTipsEnabled",
13530
+ "spinnerVerbs",
13531
+ "spinnerTipsOverride",
13532
+ "terminalProgressBarEnabled",
13533
+ "prefersReducedMotion",
13534
+ "showTurnDuration",
13535
+ "showClearContextOnPlanAccept",
13536
+ "showCompactionHistory",
13537
+ "teammateMode"
13538
+ ]);
13539
+ var routing3 = new Set(["model", "modelPicker", "fallbackModel"]);
13540
+ var invalid4 = () => new Fault(422, "claude_user_settings", "Claude user settings cannot be safely projected. Use a regular owned JSON settings file with supported preferences and permission policy.");
13541
+ async function readSettings(home) {
13542
+ await ensureNativeStateDirectory(home, false);
13543
+ const path = join20(home, "settings.json");
13544
+ const entry = await lstat9(path).catch((error) => {
13545
+ if (error.code === "ENOENT")
13233
13546
  return;
13234
- throw new Fault(409, "desktop_process_check", "Could not check whether Claude's third-party profile is already running.");
13547
+ throw error;
13548
+ });
13549
+ if (!entry)
13550
+ return;
13551
+ if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
13552
+ throw invalid4();
13553
+ const handle = await open6(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
13554
+ try {
13555
+ const opened = await handle.stat();
13556
+ if (opened.dev !== entry.dev || opened.ino !== entry.ino || opened.nlink !== 1 || opened.size > 1024 * 1024)
13557
+ throw invalid4();
13558
+ const value = JSON.parse(await handle.readFile("utf8"));
13559
+ if (!value || typeof value !== "object" || Array.isArray(value))
13560
+ throw invalid4();
13561
+ return value;
13562
+ } catch (error) {
13563
+ if (error instanceof Fault)
13564
+ throw error;
13565
+ throw invalid4();
13566
+ } finally {
13567
+ await handle.close();
13235
13568
  }
13236
- if (openFiles.split(`
13237
- `).some((line) => line.startsWith("n" + userData + "/")))
13238
- throw new Fault(409, "desktop_busy", "Claude's third-party instance is already running. Quit that instance before changing its provider; the normal Claude instance can stay open.");
13239
13569
  }
13240
- function metadata(text) {
13241
- const value = text === undefined ? { entries: [] } : JSON.parse(text);
13242
- if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((item2) => !item2 || typeof item2 !== "object" || Array.isArray(item2)))
13243
- throw new Fault(422, "desktop_config_invalid", "Claude's configuration library metadata is invalid.");
13244
- return value;
13570
+ function project(settings2, existing) {
13571
+ const result = {};
13572
+ for (const [key, value] of Object.entries(settings2)) {
13573
+ if (routing3.has(key)) {
13574
+ if (existing && key === "fallbackModel")
13575
+ throw new Fault(409, "claude_settings_routing", "The private Claude settings select a fallback model. Resolve that conflict with the Switcher profile before launching.");
13576
+ continue;
13577
+ }
13578
+ if (key === "env" && value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0)
13579
+ continue;
13580
+ if (!preferences.has(key))
13581
+ throw new Fault(422, "claude_settings_unsupported", "Claude user settings contain an unsupported environment, helper or capability setting. Keep credentials and provider routing in the selected profile; resolve this settings projection explicitly before launching.");
13582
+ result[key] = value;
13583
+ }
13584
+ return result;
13245
13585
  }
13586
+ async function prepareClaudeUserSettings(overlayHome, environment = process.env) {
13587
+ overlayHome = resolve10(overlayHome);
13588
+ const existing = await readSettings(overlayHome);
13589
+ if (existing !== undefined) {
13590
+ project(existing, true);
13591
+ return;
13592
+ }
13593
+ const sourceHome = resolve10(environment.CLAUDE_CONFIG_DIR ?? join20(environment.HOME ?? homedir10(), ".claude"));
13594
+ if (sourceHome === overlayHome)
13595
+ return;
13596
+ const source = await readSettings(sourceHome);
13597
+ if (source === undefined)
13598
+ return;
13599
+ const settings2 = project(source, false);
13600
+ await ensureNativeStateDirectory(overlayHome);
13601
+ try {
13602
+ await writeFile16(join20(overlayHome, "settings.json"), JSON.stringify(settings2, null, 2) + `
13603
+ `, { mode: 384, flag: "wx" });
13604
+ } catch (error) {
13605
+ if (error.code !== "EEXIST")
13606
+ throw error;
13607
+ const concurrent = await readSettings(overlayHome);
13608
+ if (concurrent === undefined || JSON.stringify(project(concurrent, true)) !== JSON.stringify(settings2))
13609
+ throw new Fault(409, "claude_user_settings_changed", "The private Claude settings changed during preparation. Existing settings were preserved; retry after resolving the concurrent launch.");
13610
+ }
13611
+ }
13612
+
13613
+ // src/claude-desktop-launch.ts
13246
13614
  async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13247
13615
  if (input.harness !== "claude")
13248
13616
  throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
@@ -13251,53 +13619,39 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13251
13619
  validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
13252
13620
  if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
13253
13621
  throw new Fault(400, "desktop_arguments", "Claude desktop uses its own effort and permission controls; native CLI arguments and Codex-only launch controls are not accepted.");
13254
- const version2 = app.version.split(".").map(Number);
13255
- if (version2.length < 3 || version2.some((n) => !Number.isSafeInteger(n)) || version2[0] < 1 || version2[0] === 1 && version2[1] < 52386)
13256
- throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
13622
+ validateClaudeDesktopVersion(app);
13257
13623
  const userData = system?.userData ?? claudeDesktopDataDirectory();
13258
- const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
13624
+ const check2 = system?.assertAvailable ?? (() => assertClaudeDesktopAvailable(userData));
13259
13625
  await check2();
13260
13626
  await privateDirectory(userData);
13261
- const library = join19(userData, "configLibrary");
13627
+ const library = join21(userData, "configLibrary");
13262
13628
  await privateDirectory(library);
13263
- const release = await desktopLease(join19(library, ".switcher-lease.sqlite"));
13264
- const metaPath = join19(library, "_meta.json"), receiptPath = join19(library, ".switcher-selection.json");
13265
- let receipt, gateway, closed = false;
13266
- const restore = async (record3) => {
13267
- if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
13268
- throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
13269
- const configPath = join19(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
13270
- if (current !== undefined && hash2(current) !== record3.configHash)
13271
- throw new Fault(409, "desktop_config_changed", "The Switcher Claude configuration was edited outside this launch. Switcher will preserve it; review the configuration library before relaunching.");
13272
- const currentMeta = await safeDesktopRead(metaPath);
13273
- if (currentMeta !== record3.appliedMeta && currentMeta !== (record3.previousMeta ?? undefined))
13274
- throw new Fault(409, "desktop_config_changed", "Claude's selected configuration changed during this launch. Switcher will preserve the changed selection; review its configuration library before relaunching.");
13275
- if (record3.previousMeta === null)
13276
- await rm5(metaPath, { force: true });
13277
- else
13278
- await writeDesktopPrivate(metaPath, record3.previousMeta);
13279
- await rm5(configPath, { force: true });
13280
- await rm5(receiptPath, { force: true });
13281
- };
13629
+ const release = await desktopLease(join21(library, ".switcher-lease.sqlite"));
13630
+ let selection, gateway, closed = false, cleanupError;
13282
13631
  const cleanup = async () => {
13283
- if (closed)
13632
+ if (closed) {
13633
+ if (cleanupError)
13634
+ throw cleanupError;
13284
13635
  return;
13285
- closed = true;
13636
+ }
13286
13637
  try {
13287
13638
  await gateway?.cleanup();
13288
- if (receipt)
13289
- await restore(receipt);
13639
+ await selection?.restore();
13640
+ } catch (error) {
13641
+ cleanupError = error;
13642
+ throw error;
13290
13643
  } finally {
13644
+ closed = true;
13291
13645
  release();
13292
13646
  }
13293
13647
  };
13294
13648
  try {
13295
- const recovery = await safeDesktopRead(receiptPath);
13296
- if (recovery)
13297
- await restore(JSON.parse(recovery));
13298
- const localConfig = await safeDesktopRead(join19(userData, "claude_desktop_config.json"));
13649
+ await recoverDesktopSelection(library);
13650
+ const localConfig = await safeDesktopRead(join21(userData, "claude_desktop_config.json"));
13299
13651
  if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
13300
13652
  throw new Fault(409, "desktop_mode", "Claude's third-party profile is set to standard account mode. Select third-party mode in Claude before launching this gateway.");
13653
+ if (input.sharedState)
13654
+ await prepareClaudeUserSettings(sessionDir);
13301
13655
  await privateDirectory(sessionDir);
13302
13656
  if (input.sharedState)
13303
13657
  await projectNativeState(input.sharedState, sessionDir);
@@ -13308,31 +13662,27 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13308
13662
  if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
13309
13663
  throw new Fault(409, "desktop_alias_conflict", "The model policy conflicts with Claude desktop's reserved switcher/sonnet, switcher/opus or switcher/haiku routing aliases.");
13310
13664
  const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
13311
- const catalogPath = join19(input.stateDir, "claude-desktop-policy.json");
13312
- await writeFile16(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
13665
+ const catalogPath = join21(input.stateDir, "claude-desktop-policy.json");
13666
+ await writeFile17(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
13313
13667
  gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
13314
- const id2 = crypto.randomUUID(), configPath = join19(library, id2 + ".json");
13315
- const config = JSON.stringify({
13668
+ selection = await applyDesktopSelection(library, {
13316
13669
  inferenceProvider: "gateway",
13317
13670
  inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
13318
13671
  inferenceGatewayApiKey: gateway.token,
13319
13672
  inferenceGatewayAuthScheme: "bearer",
13320
13673
  modelDiscoveryEnabled: false,
13321
13674
  inferenceModels: Object.entries(targets).map(([tier, model3]) => ({ name: "switcher/" + tier, labelOverride: model3, anthropicFamilyTier: tier, isFamilyDefault: true }))
13322
- });
13323
- const previousMeta = await safeDesktopRead(metaPath);
13324
- const meta = metadata(previousMeta);
13325
- const appliedMeta = JSON.stringify({ ...meta, appliedId: id2, entries: [...meta.entries, { id: id2, name: `Switcher: ${input.providerId ?? "provider"} / ${input.model}` }] });
13326
- receipt = { id: id2, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
13327
- await writeDesktopPrivate(configPath, config);
13328
- await writeDesktopPrivate(receiptPath, JSON.stringify(receipt));
13329
- await writeDesktopPrivate(metaPath, appliedMeta);
13675
+ }, `Switcher: ${input.providerId ?? "provider"} / ${input.model}`);
13676
+ const configPath = selection.configPath;
13330
13677
  return {
13331
13678
  executable: app.executable,
13332
13679
  args: [],
13333
13680
  env: { ...input.sharedState ? nativeStateEnvironment(input.sharedState) : {}, CLAUDE_CONFIG_DIR: sessionDir },
13334
13681
  configPaths: [catalogPath, configPath],
13335
- beforeLaunch: check2,
13682
+ beforeLaunch: async () => {
13683
+ await check2();
13684
+ await selection.assertCurrent();
13685
+ },
13336
13686
  cleanup,
13337
13687
  warnings: [`Claude desktop gateway: ${input.providerId ?? "provider"} / ${input.model}. Uses the shared Claude-3p profile, separate from the normal Claude account. Quit this instance before switching providers; keep Switcher running until then. The previous configuration selection is restored on exit. Managed settings and native permissions remain authoritative.`]
13338
13688
  };
@@ -13347,7 +13697,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13347
13697
  // src/codex-session-discovery.ts
13348
13698
  import { spawn as spawn3 } from "child_process";
13349
13699
  import { createInterface as createInterface2 } from "readline/promises";
13350
- import { basename as basename3, resolve as resolve10 } from "path";
13700
+ import { basename as basename3, resolve as resolve11 } from "path";
13351
13701
  var object6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
13352
13702
  var unavailable2 = () => new Fault(422, "codex_session_discovery", "Native Codex session discovery failed. No conversation was started. Retry discovery or provide an exact session ID.");
13353
13703
  async function listCodexSessions(prepared, cwd, query) {
@@ -13362,11 +13712,11 @@ async function listCodexSessions(prepared, cwd, query) {
13362
13712
  let done = false, initialized = false, pending = Buffer.alloc(0), responseBytes = 0;
13363
13713
  let killTimer;
13364
13714
  let resolvePage, rejectPage;
13365
- const result = new Promise((resolve11, reject2) => {
13366
- resolvePage = resolve11;
13715
+ const result = new Promise((resolve12, reject2) => {
13716
+ resolvePage = resolve12;
13367
13717
  rejectPage = reject2;
13368
13718
  });
13369
- const closed = new Promise((resolve11) => child.once("close", () => resolve11()));
13719
+ const closed = new Promise((resolve12) => child.once("close", () => resolve12()));
13370
13720
  const stop = () => {
13371
13721
  child.stdin.destroy();
13372
13722
  child.kill("SIGTERM");
@@ -13465,16 +13815,16 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
13465
13815
  break;
13466
13816
  }
13467
13817
  if (nativeArgs[i].startsWith("--cd="))
13468
- effectiveCwd = resolve10(cwd, nativeArgs[i].slice(5));
13818
+ effectiveCwd = resolve11(cwd, nativeArgs[i].slice(5));
13469
13819
  else if (nativeArgs[i].startsWith("-C") && nativeArgs[i].length > 2)
13470
- effectiveCwd = resolve10(cwd, nativeArgs[i].slice(2));
13820
+ effectiveCwd = resolve11(cwd, nativeArgs[i].slice(2));
13471
13821
  if (codexOptionRequestsHelp(nativeArgs[i]))
13472
13822
  return nativeArgs;
13473
13823
  if (codexOptionTakesValue(nativeArgs[i])) {
13474
13824
  if (nativeArgs[i] === "--cd" || nativeArgs[i] === "-C") {
13475
13825
  if (!nativeArgs[i + 1])
13476
13826
  throw unavailable2();
13477
- effectiveCwd = resolve10(cwd, nativeArgs[i + 1]);
13827
+ effectiveCwd = resolve11(cwd, nativeArgs[i + 1]);
13478
13828
  }
13479
13829
  i++;
13480
13830
  continue;
@@ -13549,9 +13899,9 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
13549
13899
  // src/launcher.ts
13550
13900
  var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
13551
13901
  async function writeOriCodexCatalog(stateDir, models) {
13552
- const path = join20(stateDir, "ori-codex-models.json");
13902
+ const path = join22(stateDir, "ori-codex-models.json");
13553
13903
  const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
13554
- await writeFile17(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
13904
+ await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
13555
13905
  `, { mode: 384, flag: "wx" });
13556
13906
  return path;
13557
13907
  }
@@ -13589,7 +13939,7 @@ async function oriRequestForPlan(plan, options = {}) {
13589
13939
  throw new Error("Grok API-key authentication is disabled by GROK_DISABLE_API_KEY_AUTH. This provider launch cannot proceed under that native authentication policy.");
13590
13940
  if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
13591
13941
  throw new Error("Grok requires a native team login through GROK_FORCE_LOGIN_TEAM_ID. This provider launch cannot proceed under that native authentication policy.");
13592
- const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve11(options.cwd) : undefined });
13942
+ const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve12(options.cwd) : undefined });
13593
13943
  const native = requireOriHarness(contract, target);
13594
13944
  if (!native.path)
13595
13945
  throw new Error("Ori did not report the native harness executable path.");
@@ -13637,15 +13987,15 @@ async function prepareOriForPlan(plan, options) {
13637
13987
  executable: detection.executable,
13638
13988
  version: detection.version,
13639
13989
  stateDir: options.stateDir,
13640
- cwd: resolve11(options.cwd ?? process.cwd()),
13990
+ cwd: resolve12(options.cwd ?? process.cwd()),
13641
13991
  args: options.args ?? [],
13642
13992
  sharedState: options.sharedState
13643
13993
  });
13644
13994
  try {
13645
13995
  const shim = prepareOriModelPolicy(request.target, native);
13646
- const dir = join20(options.stateDir, "ori-bin"), path = join20(dir, shim.name);
13996
+ const dir = join22(options.stateDir, "ori-bin"), path = join22(dir, shim.name);
13647
13997
  await mkdir12(dir, { mode: 448 });
13648
- await writeFile17(path, shim.script, { mode: 448, flag: "wx" });
13998
+ await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
13649
13999
  return { contract, prepared: {
13650
14000
  ...ori,
13651
14001
  env: { ...ori.env, ...shim.env, PATH: `${dir}:${ori.env.PATH ?? process.env.PATH ?? ""}` },
@@ -13660,6 +14010,8 @@ async function prepareOriForPlan(plan, options) {
13660
14010
  }
13661
14011
  }
13662
14012
  async function launch(client, profileId, options = {}) {
14013
+ if (options.backend === "ori" && options.shareNativeState === false)
14014
+ throw new Fault(400, "native_state_backend", "Explicit native-state isolation requires the direct adapter; Ori isolation is not yet verified.");
13663
14015
  const launchDeadline = options.timeoutMs === undefined ? undefined : Date.now() + options.timeoutMs;
13664
14016
  const profile = await client.getProfile(profileId);
13665
14017
  if ((options.reasoning || options.dangerouslyBypassApprovalsAndSandbox) && (profile.harness !== "codex" || (options.backend ?? "direct") !== "direct"))
@@ -13667,7 +14019,7 @@ async function launch(client, profileId, options = {}) {
13667
14019
  assertHarnessArguments(profile.harness, options.args ?? []);
13668
14020
  if (profile.harness === "gemini" || profile.harness === "antigravity")
13669
14021
  validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
13670
- await validateHarnessConfiguration(profile.harness, resolve11(options.cwd ?? process.cwd()), options.args);
14022
+ await validateHarnessConfiguration(profile.harness, resolve12(options.cwd ?? process.cwd()), options.args);
13671
14023
  if (profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((process.env.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
13672
14024
  throw new Error("Grok API-key authentication is disabled by GROK_DISABLE_API_KEY_AUTH. This provider launch cannot proceed under that native authentication policy.");
13673
14025
  if (profile.harness === "grok" && process.env.GROK_FORCE_LOGIN_TEAM_ID?.trim())
@@ -13676,7 +14028,7 @@ async function launch(client, profileId, options = {}) {
13676
14028
  await client.refreshModels(profile.providerId);
13677
14029
  const plan = await client.launchPlan(profileId);
13678
14030
  assertHarnessArguments(plan.profile.harness, options.args ?? []);
13679
- await validateHarnessConfiguration(plan.profile.harness, resolve11(options.cwd ?? process.cwd()), options.args);
14031
+ await validateHarnessConfiguration(plan.profile.harness, resolve12(options.cwd ?? process.cwd()), options.args);
13680
14032
  if (options.credentialPreflight && providerCredentialFingerprint(plan.provider) !== options.credentialPreflight)
13681
14033
  throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
13682
14034
  const backend = options.backend ?? "direct";
@@ -13698,9 +14050,9 @@ async function launch(client, profileId, options = {}) {
13698
14050
  validateHarnessVersion("gemini", detection?.version);
13699
14051
  if (backend === "direct" && plan.profile.harness === "aider")
13700
14052
  validateHarnessVersion(plan.profile.harness, detection?.version);
13701
- const root = resolve11(options.stateDir ?? join20(switcherHome(), "state"));
14053
+ const root = resolve12(options.stateDir ?? join22(switcherHome(), "state"));
13702
14054
  await privateDirectory(root);
13703
- const stateDir = await mkdtemp(join20(root, "launch-"));
14055
+ const stateDir = await mkdtemp(join22(root, "launch-"));
13704
14056
  let credential;
13705
14057
  if (backend === "direct") {
13706
14058
  try {
@@ -13744,27 +14096,42 @@ async function launch(client, profileId, options = {}) {
13744
14096
  return;
13745
14097
  });
13746
14098
  try {
13747
- if (options.shareNativeState && plan.profile.harness !== "codex" && plan.profile.harness !== "claude")
13748
- throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
13749
- const shareRequested = (plan.profile.harness === "codex" || plan.profile.harness === "claude") && nativeStateRequested(plan.profile.harness, process.env, Boolean(options.shareNativeState));
14099
+ if (options.shareNativeState !== undefined && plan.profile.harness !== "codex" && plan.profile.harness !== "claude")
14100
+ throw new Fault(400, "native_state_harness", "Native-state options are supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
14101
+ const shareRequested = (plan.profile.harness === "codex" || plan.profile.harness === "claude") && nativeStateRequested(plan.profile.harness, process.env, options.shareNativeState);
13750
14102
  if (shareRequested && backend !== "direct")
13751
14103
  throw new Fault(400, "native_state_backend", "Shared native state currently requires the directly verified native adapter; Ori state/resume integration is not yet accepted.");
13752
- if (shareRequested && plan.profile.harness === "codex") {
14104
+ if ((shareRequested || options.shareNativeState === false) && plan.profile.harness === "codex")
13753
14105
  assertHarnessArguments("codex", options.args ?? [], { reservedCodexRoots: ["sqlite_home"] });
14106
+ if (shareRequested && plan.profile.harness === "codex")
13754
14107
  validateNativeStateVersion("codex", detection?.version);
13755
- }
13756
14108
  const sharedState = shareRequested ? await resolveNativeState(plan.profile.harness) : undefined;
13757
14109
  const desktopState = profileId;
13758
- const stateWarnings = sharedState ? ["Shared native state is explicitly enabled. Resumed conversation history uses this launch's selected provider and model; Switcher does not infer unverified original-provider provenance.", ...await legacyNativeStateWarnings(root, sharedState)] : [];
14110
+ 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)] : [];
13759
14111
  let nativeHome2;
13760
14112
  if (sharedState && !options.desktop && !options.claudeDesktop) {
13761
14113
  const variable = sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
13762
- const configured = process.env[variable] ? resolve11(process.env[variable]) : undefined;
13763
- nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join20(root, "native-claude", profileId) : configured ?? sharedState.home;
14114
+ const configured = process.env[variable] ? resolve12(process.env[variable]) : undefined;
14115
+ nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join22(root, "native-claude", profileId) : configured ?? sharedState.home;
14116
+ if (sharedState.tool === "claude")
14117
+ await prepareClaudeUserSettings(nativeHome2);
13764
14118
  await privateDirectory(nativeHome2);
13765
14119
  await assertNativeInstructionOverlay(sharedState, nativeHome2);
13766
14120
  await projectNativeState(sharedState, nativeHome2);
13767
14121
  }
14122
+ if (options.shareNativeState === false && backend === "direct") {
14123
+ const tool = plan.profile.harness;
14124
+ if (options.desktop)
14125
+ await assertNativeStateIsolation(tool, join22(root, "desktop", desktopState, "codex"));
14126
+ else if (options.claudeDesktop)
14127
+ await assertNativeStateIsolation(tool, join22(root, "desktop-claude", desktopState));
14128
+ else {
14129
+ const variable = tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
14130
+ nativeHome2 = process.env[variable] ? resolve12(process.env[variable]) : join22(root, `native-${tool}`, profileId);
14131
+ await assertNativeStateIsolation(tool, nativeHome2);
14132
+ await privateDirectory(nativeHome2);
14133
+ }
14134
+ }
13768
14135
  const input = {
13769
14136
  harness: plan.profile.harness,
13770
14137
  baseUrl: plan.provider.baseUrl,
@@ -13777,10 +14144,10 @@ async function launch(client, profileId, options = {}) {
13777
14144
  onRoutingEvent,
13778
14145
  credential,
13779
14146
  stateDir,
13780
- cwd: resolve11(options.cwd ?? process.cwd()),
14147
+ cwd: resolve12(options.cwd ?? process.cwd()),
13781
14148
  sharedState
13782
14149
  };
13783
- let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join20(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
14150
+ let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join22(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
13784
14151
  harness: plan.profile.harness,
13785
14152
  baseUrl: plan.provider.baseUrl,
13786
14153
  protocol: plan.provider.protocol,
@@ -13796,18 +14163,19 @@ async function launch(client, profileId, options = {}) {
13796
14163
  executable: nativeExecutable ?? detection?.executable,
13797
14164
  args: options.args ?? [],
13798
14165
  stateDir,
13799
- cwd: resolve11(options.cwd ?? process.cwd()),
14166
+ cwd: resolve12(options.cwd ?? process.cwd()),
13800
14167
  version: detection?.version,
13801
14168
  sharedState,
13802
- ...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie"].includes(plan.profile.harness) ? { sessionDir: join20(root, "sessions", plan.profile.harness, profileId) } : {}
14169
+ ...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie"].includes(plan.profile.harness) ? { sessionDir: join22(root, "sessions", plan.profile.harness, profileId) } : {}
13803
14170
  });
13804
14171
  cleanup = prepared.cleanup;
13805
14172
  prepared = { ...prepared, warnings: [...prepared.warnings, ...stateWarnings] };
13806
- if (sharedState)
14173
+ if (sharedState || nativeHome2)
13807
14174
  prepared = { ...prepared, env: {
13808
14175
  ...prepared.env,
13809
- ...nativeStateEnvironment(sharedState),
13810
- ...nativeHome2 ? { [sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"]: nativeHome2 } : {}
14176
+ ...sharedState ? nativeStateEnvironment(sharedState) : {},
14177
+ ...nativeHome2 ? { [plan.profile.harness === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"]: nativeHome2 } : {},
14178
+ ...nativeHome2 && options.shareNativeState === false && plan.profile.harness === "codex" ? { CODEX_SQLITE_HOME: nativeHome2 } : {}
13811
14179
  } };
13812
14180
  if (sharedState?.tool === "codex" && !options.desktop && backend === "direct" && options.args?.length) {
13813
14181
  const baseArgs = prepared.args.slice(0, prepared.args.length - options.args.length);
@@ -13815,7 +14183,7 @@ async function launch(client, profileId, options = {}) {
13815
14183
  prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
13816
14184
  }
13817
14185
  if (options.desktop) {
13818
- prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join20(root, "desktop", desktopState), sharedState);
14186
+ prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join22(root, "desktop", desktopState), sharedState);
13819
14187
  cleanup = prepared.cleanup;
13820
14188
  }
13821
14189
  for (const warning of [...plan.warnings, ...prepared.warnings])
@@ -13892,7 +14260,7 @@ async function launch(client, profileId, options = {}) {
13892
14260
  interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
13893
14261
  throw preparationSignal;
13894
14262
  }
13895
- const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve11(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
14263
+ const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve12(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
13896
14264
  await cleanup?.();
13897
14265
  cleanup = undefined;
13898
14266
  await finishRunOnce(run, { status: interrupted ? "interrupted" : code === 0 ? "exited" : "failed", exitCode: code }, `switcher: Harness exited ${code}; final metadata could not be saved for run ${run.id}.`);
@@ -13909,8 +14277,8 @@ async function launch(client, profileId, options = {}) {
13909
14277
  } finally {
13910
14278
  if (lateCreateRunFinalization) {
13911
14279
  let finalizationTimer;
13912
- const finalizationTimeout = new Promise((resolve12) => {
13913
- finalizationTimer = setTimeout(resolve12, LATE_RUN_FINALIZATION_TIMEOUT_MS);
14280
+ const finalizationTimeout = new Promise((resolve13) => {
14281
+ finalizationTimer = setTimeout(resolve13, LATE_RUN_FINALIZATION_TIMEOUT_MS);
13914
14282
  });
13915
14283
  try {
13916
14284
  await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
@@ -14035,15 +14403,15 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
14035
14403
 
14036
14404
  // src/native-state-import.ts
14037
14405
  import { createHash as createHash15 } from "crypto";
14038
- import { constants as constants8 } from "fs";
14039
- import { lstat as lstat9, open as open5, opendir as opendir2, link as link2, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
14040
- import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join21, relative as relative6, resolve as resolve12 } from "path";
14406
+ import { constants as constants10 } from "fs";
14407
+ import { lstat as lstat10, open as open7, opendir as opendir2, link as link2, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
14408
+ import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join23, relative as relative6, resolve as resolve13 } from "path";
14041
14409
  var MAX_FILES = 1e5;
14042
14410
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
14043
14411
  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.");
14044
14412
  async function info2(path) {
14045
14413
  try {
14046
- return await lstat9(path);
14414
+ return await lstat10(path);
14047
14415
  } catch (error) {
14048
14416
  if (error.code === "ENOENT")
14049
14417
  return;
@@ -14059,7 +14427,7 @@ var inside3 = (parent, child) => {
14059
14427
  var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
14060
14428
  async function sessionId(path, expected) {
14061
14429
  const nameId = basename4(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
14062
- const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
14430
+ const handle = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW);
14063
14431
  try {
14064
14432
  const before = await handle.stat();
14065
14433
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
@@ -14073,7 +14441,7 @@ async function sessionId(path, expected) {
14073
14441
  length += read.bytesRead;
14074
14442
  newline = buffer.indexOf(10, 0);
14075
14443
  }
14076
- const after = await handle.stat(), named = await lstat9(path);
14444
+ const after = await handle.stat(), named = await lstat10(path);
14077
14445
  if (!same(before, after) || !same(after, named) || after.nlink !== 1 || named.nlink !== 1 || named.isSymbolicLink())
14078
14446
  throw refused();
14079
14447
  if (newline < 0 && before.size > buffer.length)
@@ -14102,7 +14470,7 @@ async function checkSessionIdentities(plan) {
14102
14470
  for (const file of plan.files) {
14103
14471
  if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
14104
14472
  continue;
14105
- file.sessionId = await sessionId(join21(plan.source, file.path), file.source);
14473
+ file.sessionId = await sessionId(join23(plan.source, file.path), file.source);
14106
14474
  if (!file.sessionId)
14107
14475
  continue;
14108
14476
  const previous = ids.get(file.sessionId);
@@ -14126,7 +14494,7 @@ async function checkSessionIdentities(plan) {
14126
14494
  for await (const entry of await opendir2(directory)) {
14127
14495
  if (++seen > MAX_FILES || entry.isSymbolicLink())
14128
14496
  throw refused();
14129
- const path = join21(directory, entry.name);
14497
+ const path = join23(directory, entry.name);
14130
14498
  if (entry.isDirectory()) {
14131
14499
  await scan(path, depth + 1);
14132
14500
  continue;
@@ -14143,18 +14511,18 @@ async function checkSessionIdentities(plan) {
14143
14511
  file.existing = true;
14144
14512
  }
14145
14513
  }
14146
- await scan(join21(plan.state.home, "sessions"));
14147
- await scan(join21(plan.state.home, "archived_sessions"));
14514
+ await scan(join23(plan.state.home, "sessions"));
14515
+ await scan(join23(plan.state.home, "archived_sessions"));
14148
14516
  }
14149
14517
  async function fingerprint2(path, copyTo) {
14150
- const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
14518
+ const handle = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW);
14151
14519
  let output, complete = false;
14152
14520
  try {
14153
14521
  const before = await handle.stat();
14154
14522
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
14155
14523
  throw refused();
14156
14524
  if (copyTo)
14157
- output = await open5(copyTo, "wx", 384);
14525
+ output = await open7(copyTo, "wx", 384);
14158
14526
  const hash3 = createHash15("sha256"), buffer = Buffer.alloc(64 * 1024);
14159
14527
  let bytes = 0;
14160
14528
  for (;; ) {
@@ -14172,7 +14540,7 @@ async function fingerprint2(path, copyTo) {
14172
14540
  offset += (await output.write(chunk, offset, chunk.length - offset)).bytesWritten;
14173
14541
  }
14174
14542
  }
14175
- const after = await handle.stat(), named = await lstat9(path);
14543
+ const after = await handle.stat(), named = await lstat10(path);
14176
14544
  if (named.isSymbolicLink() || after.nlink !== 1 || named.nlink !== 1 || bytes !== before.size || !same(before, after) || !same(after, named))
14177
14545
  throw refused();
14178
14546
  await output?.sync();
@@ -14190,12 +14558,12 @@ async function fingerprint2(path, copyTo) {
14190
14558
  async function planNativeStateImport(state, source, selection) {
14191
14559
  if (!isAbsolute17(source) || source.includes("\x00"))
14192
14560
  throw refused();
14193
- source = resolve12(source);
14561
+ source = resolve13(source);
14194
14562
  if (inside3(source, state.home) || inside3(state.home, source))
14195
14563
  throw refused();
14196
14564
  await assertNativeStateDirectory(source);
14197
14565
  await ensureNativeStateDirectory(state.home, false);
14198
- const allowed = NATIVE_STATE_ENTRIES[state.tool].filter((entry) => entry.name !== "thread-writer-locks");
14566
+ const allowed = NATIVE_STATE_ENTRIES[state.tool].filter((entry) => !["thread-writer-locks", "skills"].includes(entry.name));
14199
14567
  const entries = selection?.length ? [...new Set(selection)] : allowed.map((entry) => entry.name);
14200
14568
  if (entries.some((name) => !allowed.some((entry) => entry.name === name)))
14201
14569
  throw refused();
@@ -14204,9 +14572,9 @@ async function planNativeStateImport(state, source, selection) {
14204
14572
  async function visit(path, kind) {
14205
14573
  if (++seen > MAX_FILES || path.split("/").length > 32)
14206
14574
  throw refused();
14207
- await ensureNativeStateDirectory(dirname9(join21(source, path)), false);
14208
- await ensureNativeStateDirectory(dirname9(join21(state.home, path)), false);
14209
- const from = join21(source, path), to = join21(state.home, path), entry = await info2(from), target = await info2(to);
14575
+ await ensureNativeStateDirectory(dirname9(join23(source, path)), false);
14576
+ await ensureNativeStateDirectory(dirname9(join23(state.home, path)), false);
14577
+ const from = join23(source, path), to = join23(state.home, path), entry = await info2(from), target = await info2(to);
14210
14578
  if (!entry)
14211
14579
  return;
14212
14580
  if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
@@ -14225,7 +14593,7 @@ async function planNativeStateImport(state, source, selection) {
14225
14593
  }
14226
14594
  children.sort((a, b) => a.name.localeCompare(b.name));
14227
14595
  for (const child of children)
14228
- await visit(join21(path, child.name), child.kind);
14596
+ await visit(join23(path, child.name), child.kind);
14229
14597
  } else {
14230
14598
  const value = await fingerprint2(from);
14231
14599
  plan.bytes += value.bytes;
@@ -14279,14 +14647,14 @@ async function applyNativeStateImportUnlocked(plan) {
14279
14647
  throw refused();
14280
14648
  const requiredDirectories = new Set([plan.state.home]);
14281
14649
  for (const path of plan.directories) {
14282
- for (let directory = join21(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname9(directory)) {
14650
+ for (let directory = join23(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname9(directory)) {
14283
14651
  requiredDirectories.add(directory);
14284
14652
  if (directory === plan.state.home)
14285
14653
  break;
14286
14654
  }
14287
14655
  }
14288
14656
  for (const file of plan.files.filter((file2) => !file2.existing)) {
14289
- for (let directory = dirname9(join21(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname9(directory)) {
14657
+ for (let directory = dirname9(join23(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname9(directory)) {
14290
14658
  requiredDirectories.add(directory);
14291
14659
  if (directory === plan.state.home)
14292
14660
  break;
@@ -14307,9 +14675,9 @@ async function applyNativeStateImportUnlocked(plan) {
14307
14675
  for (const file of plan.files) {
14308
14676
  if (file.existing)
14309
14677
  continue;
14310
- const target = join21(plan.state.home, file.path), temporary = join21(dirname9(target), `.switcher-import-${crypto.randomUUID()}`);
14678
+ const target = join23(plan.state.home, file.path), temporary = join23(dirname9(target), `.switcher-import-${crypto.randomUUID()}`);
14311
14679
  staged.push({ temporary, target });
14312
- const copied = await fingerprint2(join21(plan.source, file.path), temporary);
14680
+ const copied = await fingerprint2(join23(plan.source, file.path), temporary);
14313
14681
  if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
14314
14682
  throw refused();
14315
14683
  }
@@ -14365,11 +14733,11 @@ async function applyNativeStateImport(plan) {
14365
14733
  var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your provider and model
14366
14734
 
14367
14735
  switcher launch chatgpt --provider PROVIDER --model MODEL [--reasoning EFFORT]
14368
- [--dangerously-bypass-approvals-and-sandbox] [--share-native-state]
14736
+ [--dangerously-bypass-approvals-and-sandbox] [--share-native-state | --no-share-native-state]
14369
14737
  [--app-path /absolute/ChatGPT.app]
14370
14738
  [--dry-run] [--cwd DIR] [--timeout SECONDS]
14371
14739
  switcher launch claude-desktop --provider PROVIDER --model MODEL
14372
- [--share-native-state] [--app-path /absolute/Claude.app] [--dry-run]
14740
+ [--share-native-state | --no-share-native-state] [--app-path /absolute/Claude.app] [--dry-run]
14373
14741
  switcher providers presets [ID]
14374
14742
  switcher providers list [--search TEXT] [--limit N] [--offset N]
14375
14743
  switcher providers add ID --url URL --protocol PROTOCOL [--credential-env NAME]
@@ -14387,8 +14755,8 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
14387
14755
  switcher profiles add ID --provider ID --harness HARNESS --model MODEL [--model-policy-file FILE] [--role-model ROLE=MODEL]
14388
14756
  switcher profiles update ID --file profile.json --version N
14389
14757
  switcher profiles delete ID --version N
14390
- switcher launch HARNESS --provider PROVIDER [--model MODEL] [--share-native-state] [--dry-run]
14391
- switcher launch PROFILE [--backend direct|ori] [--share-native-state] [--cwd DIR] [--executable PATH]
14758
+ switcher launch HARNESS --provider PROVIDER [--model MODEL] [--share-native-state | --no-share-native-state] [--dry-run]
14759
+ switcher launch PROFILE [--backend direct|ori] [--share-native-state | --no-share-native-state] [--cwd DIR] [--executable PATH]
14392
14760
  [--ori-executable PATH] [--state-dir DIR]
14393
14761
  [--timeout SECONDS] -- [native harness arguments]
14394
14762
  switcher runs list|get [ID]
@@ -14403,7 +14771,9 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
14403
14771
 
14404
14772
  HARNESS: claude, codex, grok, opencode, opencode2, pi, omp, dsh, cline, hermes, prime-agent, gemini, antigravity, junie, aider, kilo
14405
14773
  chatgpt launches the installed macOS desktop app with private login data.
14406
- Use --share-native-state to project the canonical noncredential Codex/Claude corpus.
14774
+ Claude shares canonical sessions, skills and instructions by default.
14775
+ Use --no-share-native-state for isolation. Codex currently requires
14776
+ --share-native-state or a canonical state marker.
14407
14777
  Its local Codex conversations use the selected Responses-compatible provider.
14408
14778
  claude-desktop launches Claude in its separate Claude-3p gateway profile with a
14409
14779
  Messages-compatible provider. Quit that instance before switching providers.
@@ -14490,6 +14860,7 @@ async function main(args = process.argv.slice(2)) {
14490
14860
  reasoning: { type: "string" },
14491
14861
  "dangerously-bypass-approvals-and-sandbox": { type: "boolean" },
14492
14862
  "share-native-state": { type: "boolean" },
14863
+ "no-share-native-state": { type: "boolean" },
14493
14864
  from: { type: "string" },
14494
14865
  entry: { type: "string", multiple: true },
14495
14866
  apply: { type: "boolean" },
@@ -14553,16 +14924,19 @@ async function main(args = process.argv.slice(2)) {
14553
14924
  }
14554
14925
  if (values2.from !== undefined || values2.entry !== undefined || values2.apply !== undefined || values2["plan-digest"] !== undefined)
14555
14926
  throw new Fault(400, "conflicting_options", "--from, --entry, --plan-digest, --dry-run and --apply belong to switcher state import.");
14556
- if (values2["share-native-state"] && command !== "launch")
14557
- throw new Fault(400, "conflicting_options", "--share-native-state belongs to a Codex, ChatGPT, Claude CLI or Claude desktop launch.");
14927
+ if (values2["share-native-state"] && values2["no-share-native-state"])
14928
+ throw new Fault(400, "conflicting_options", "Use only one of --share-native-state and --no-share-native-state.");
14929
+ const shareNativeState = values2["no-share-native-state"] ? false : values2["share-native-state"];
14930
+ if (shareNativeState !== undefined && command !== "launch")
14931
+ throw new Fault(400, "conflicting_options", "--share-native-state and --no-share-native-state belong to a Codex, ChatGPT, Claude CLI or Claude desktop launch.");
14558
14932
  const reasoning = values2.reasoning === undefined ? undefined : parse2(reasoningEffortSchema, values2.reasoning);
14559
14933
  const dangerouslyBypassApprovalsAndSandbox = values2["dangerously-bypass-approvals-and-sandbox"];
14560
14934
  if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" || values2.provider && !["chatgpt", "codex"].includes(action2) || values2.backend && values2.backend !== "direct"))
14561
14935
  throw new Fault(400, "conflicting_options", "--reasoning and --dangerously-bypass-approvals-and-sandbox require a direct Codex or ChatGPT launch.");
14562
14936
  const chatgpt = command === "launch" && action2 === "chatgpt" && values2.provider !== undefined;
14563
14937
  const claudeDesktop = command === "launch" && action2 === "claude-desktop" && values2.provider !== undefined;
14564
- if (values2["share-native-state"] && values2.provider !== undefined && !["codex", "claude", "chatgpt", "claude-desktop"].includes(action2))
14565
- throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
14938
+ if (shareNativeState !== undefined && values2.provider !== undefined && !["codex", "claude", "chatgpt", "claude-desktop"].includes(action2))
14939
+ throw new Fault(400, "native_state_harness", "Native-state options are supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
14566
14940
  if (values2["app-path"] !== undefined && !chatgpt && !claudeDesktop)
14567
14941
  throw new Fault(400, "conflicting_options", "--app-path belongs to launch chatgpt or claude-desktop --provider PROVIDER --model MODEL.");
14568
14942
  if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 || values2.executable !== undefined || values2.backend !== undefined || values2["ori-executable"] !== undefined))
@@ -14665,6 +15039,8 @@ async function main(args = process.argv.slice(2)) {
14665
15039
  const backend = values2.backend ?? "direct";
14666
15040
  if (backend !== "direct" && backend !== "ori")
14667
15041
  throw new Fault(400, "invalid_backend", "Use --backend direct or --backend ori.");
15042
+ if (command === "launch" && backend === "ori" && values2["no-share-native-state"])
15043
+ throw new Fault(400, "native_state_backend", "Explicit native-state isolation requires the direct adapter; Ori isolation is not yet verified.");
14668
15044
  if (command !== "launch" && (values2.backend !== undefined || values2["ori-executable"] !== undefined))
14669
15045
  throw new Fault(400, "conflicting_options", "--backend and --ori-executable belong to launch.");
14670
15046
  if (command === "launch" && backend === "ori" && values2.executable !== undefined)
@@ -14768,8 +15144,8 @@ async function main(args = process.argv.slice(2)) {
14768
15144
  if (values2.model || values2.protocol || values2.url || values2["credential-env"] || values2["model-policy-file"] || values2["role-model"])
14769
15145
  throw new Error("Use --provider PROVIDER for a direct launch, or update the saved profile explicitly.");
14770
15146
  const profile = await client.getProfile(profileId);
14771
- if (values2["share-native-state"] && !["codex", "claude"].includes(profile.harness))
14772
- throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
15147
+ if (shareNativeState !== undefined && !["codex", "claude"].includes(profile.harness))
15148
+ throw new Fault(400, "native_state_harness", "Native-state options are supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
14773
15149
  assertHarnessArguments(profile.harness, nativeArgs);
14774
15150
  await validateHarnessConfiguration(profile.harness, values2.cwd ?? process.cwd(), nativeArgs);
14775
15151
  const provider = await client.getProvider(profile.providerId);
@@ -14796,24 +15172,32 @@ async function main(args = process.argv.slice(2)) {
14796
15172
  codexReasoning(model3, plan.provider.baseUrl, reasoning);
14797
15173
  }
14798
15174
  assertHarnessArguments(plan.profile.harness, nativeArgs);
14799
- if (values2["share-native-state"] && !["codex", "claude"].includes(plan.profile.harness))
14800
- throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
14801
- const sharedNativeState = ["codex", "claude"].includes(plan.profile.harness) && nativeStateRequested(plan.profile.harness, process.env, Boolean(values2["share-native-state"]));
14802
- if (sharedNativeState) {
14803
- if (plan.profile.harness === "codex")
14804
- assertHarnessArguments("codex", nativeArgs, { reservedCodexRoots: ["sqlite_home"] });
15175
+ if (shareNativeState !== undefined && !["codex", "claude"].includes(plan.profile.harness))
15176
+ throw new Fault(400, "native_state_harness", "Native-state options are supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
15177
+ const sharedNativeState = ["codex", "claude"].includes(plan.profile.harness) && nativeStateRequested(plan.profile.harness, process.env, shareNativeState);
15178
+ const suffix = plan.profile.harness.toUpperCase();
15179
+ const marked = process.env[`HASNA_${suffix}_STATE_HOME`] !== undefined || process.env[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
15180
+ const nativeState = sharedNativeState ? { shared: true, consent: shareNativeState === true ? "command" : marked ? "environment" : "default" } : shareNativeState === false ? { shared: false, consent: "command" } : undefined;
15181
+ if ((sharedNativeState || shareNativeState === false) && plan.profile.harness === "codex")
15182
+ assertHarnessArguments("codex", nativeArgs, { reservedCodexRoots: ["sqlite_home"] });
15183
+ if (sharedNativeState)
14805
15184
  await resolveNativeState(plan.profile.harness, process.env, { create: false });
15185
+ if (shareNativeState === false) {
15186
+ const tool = plan.profile.harness, root = resolve14(values2["state-dir"] ?? join24(switcherHome(), "state"));
15187
+ const configured = process.env[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
15188
+ const home = desktop ? join24(root, "desktop", profileId, "codex") : claudeApp ? join24(root, "desktop-claude", profileId) : configured ? resolve14(configured) : join24(root, `native-${tool}`, profileId);
15189
+ await assertNativeStateIsolation(tool, home);
14806
15190
  }
14807
15191
  if (backend === "ori") {
14808
15192
  if (sharedNativeState)
14809
15193
  throw new Fault(400, "native_state_backend", "Shared native state currently requires the directly verified native adapter; Ori state/resume integration is not yet accepted.");
14810
15194
  const { contract, warnings } = await validateOriForPlan(plan, { oriExecutable: values2["ori-executable"], args: nativeArgs, cwd: values2.cwd });
14811
- output({ ...plan, backend: { kind: "ori", executable: contract.executable, version: contract.version, target: plan.profile.harness, provider: "openrouter", model: plan.profile.model, warnings: [...plan.warnings, ...warnings] }, ...sharedNativeState ? { nativeState: { shared: true, consent: values2["share-native-state"] ? "command" : "environment" } } : {} });
15195
+ output({ ...plan, backend: { kind: "ori", executable: contract.executable, version: contract.version, target: plan.profile.harness, provider: "openrouter", model: plan.profile.model, warnings: [...plan.warnings, ...warnings] }, ...nativeState ? { nativeState } : {} });
14812
15196
  } else
14813
- output({ ...plan, ...desktop ? { desktop: { ...desktop, mode: sharedNativeState ? "shared-state-private-auth" : "isolated-provider", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...claudeApp ? { desktop: { ...claudeApp, mode: "claude-3p-gateway", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...sharedNativeState ? { nativeState: { shared: true, consent: values2["share-native-state"] ? "command" : "environment" } } : {}, ...reasoning ? { reasoning } : {}, ...dangerouslyBypassApprovalsAndSandbox ? { permissions: { approvalPolicy: "never", sandboxMode: "danger-full-access" } } : {} });
15197
+ output({ ...plan, ...desktop ? { desktop: { ...desktop, mode: sharedNativeState ? "shared-state-private-auth" : "isolated-provider", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...claudeApp ? { desktop: { ...claudeApp, mode: "claude-3p-gateway", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...nativeState ? { nativeState } : {}, ...reasoning ? { reasoning } : {}, ...dangerouslyBypassApprovalsAndSandbox ? { permissions: { approvalPolicy: "never", sandboxMode: "danger-full-access" } } : {} });
14814
15198
  return;
14815
15199
  }
14816
- process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, shareNativeState: Boolean(values2["share-native-state"]), reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)) });
15200
+ process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, shareNativeState, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)) });
14817
15201
  return;
14818
15202
  }
14819
15203
  if (editingModel) {