@hasna/switcher 0.2.11 → 0.2.13

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.11";
517
+ var version = "0.2.13";
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 join23, resolve as resolve14 } from "path";
1112
+ import { join as join24, resolve as resolve15 } from "path";
1113
1113
 
1114
1114
  // src/http.ts
1115
1115
  var MAX_BYTES = 16 * 1024 * 1024;
@@ -1319,7 +1319,7 @@ function providerCredential(provider, env = process.env) {
1319
1319
  import { execFile } from "child_process";
1320
1320
  import { access, stat as stat3 } from "fs/promises";
1321
1321
  import { constants as constants2 } from "fs";
1322
- import { homedir as homedir2 } from "os";
1322
+ import { homedir as homedir2, userInfo as userInfo2 } from "os";
1323
1323
  import { isAbsolute as isAbsolute3, join as join3 } from "path";
1324
1324
  import { promisify } from "util";
1325
1325
  var execute = promisify(execFile);
@@ -1412,6 +1412,28 @@ async function detectClaudeDesktopApp(appPath, system = host) {
1412
1412
  }
1413
1413
  throw new Fault(404, "app_not_installed", "Install the current Claude macOS desktop app or supply its absolute .app path with --app-path.");
1414
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
+ }
1415
1437
 
1416
1438
  // src/sdk.ts
1417
1439
  class SwitcherError extends Error {
@@ -1890,7 +1912,6 @@ import { parseTree as parseTree2, getNodeValue } from "jsonc-parser";
1890
1912
 
1891
1913
  // src/runtime.ts
1892
1914
  import { randomBytes } from "crypto";
1893
- import { mkdir as mkdir4, lstat } from "fs/promises";
1894
1915
  import { homedir as homedir3 } from "os";
1895
1916
  import { isAbsolute as isAbsolute4, join as join4, resolve as resolve3 } from "path";
1896
1917
 
@@ -2549,7 +2570,7 @@ var openapi_default = {
2549
2570
  openapi: "3.0.3",
2550
2571
  info: {
2551
2572
  title: "Switcher API",
2552
- version: "0.2.11",
2573
+ version: "0.2.13",
2553
2574
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2554
2575
  },
2555
2576
  security: [
@@ -7128,13 +7149,8 @@ function announceSwitcherLocalMode(home, write = (line) => {
7128
7149
  `);
7129
7150
  }
7130
7151
 
7131
- // src/runtime.ts
7132
- var REMOTE_API_CONFIG_MISSING = "remote_api_config_missing";
7133
- function switcherHome(env = process.env) {
7134
- const override = env.HASNA_HOME?.trim();
7135
- const root = override && isAbsolute4(override) ? override : join4(env.HOME?.trim() || homedir3(), ".hasna");
7136
- return resolve3(env.HASNA_SWITCHER_HOME ?? join4(root, "switcher"));
7137
- }
7152
+ // src/private-directory.ts
7153
+ import { mkdir as mkdir4, lstat } from "fs/promises";
7138
7154
  async function privateDirectory(path) {
7139
7155
  await mkdir4(path, { recursive: true, mode: 448 });
7140
7156
  const info = await lstat(path);
@@ -7143,6 +7159,14 @@ async function privateDirectory(path) {
7143
7159
  if (process.platform !== "win32" && ((info.mode & 63) !== 0 || info.uid !== process.getuid?.()))
7144
7160
  throw new Fault(500, "home_permissions", "Switcher data directory must be owned by this user and accessible only to its owner (mode 0700).");
7145
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
+ }
7146
7170
  async function openCliRuntime(env = process.env, resolveCredential) {
7147
7171
  const providerEnv = Object.fromEntries(Object.entries(env).filter(([name]) => name.startsWith("SWITCHER_PROVIDER_")));
7148
7172
  const remote = () => ({ client: clientFromEnv(env), mode: "remote", providerEnv, close: async () => {} });
@@ -11329,8 +11353,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
11329
11353
  }
11330
11354
 
11331
11355
  // src/launcher.ts
11332
- import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile18 } from "fs/promises";
11333
- import { join as join21, resolve as resolve12 } from "path";
11356
+ import { mkdir as mkdir12, mkdtemp, rm as rm5, writeFile as writeFile18 } from "fs/promises";
11357
+ import { join as join22, resolve as resolve13 } from "path";
11334
11358
 
11335
11359
  // src/provider-credential-onboarding.ts
11336
11360
  import { z as z9 } from "zod";
@@ -12623,45 +12647,341 @@ function oriLaunchWarnings(target) {
12623
12647
  }
12624
12648
 
12625
12649
  // src/chatgpt-launch.ts
12626
- import { createHash as createHash12 } from "crypto";
12627
- import { writeFile as writeFile15, rm as rm4 } from "fs/promises";
12650
+ import { createHash as createHash13 } from "crypto";
12651
+ import { writeFile as writeFile14, rm as rm4 } from "fs/promises";
12628
12652
  import { join as join18 } from "path";
12629
12653
  import { fileURLToPath } from "url";
12630
12654
 
12631
12655
  // src/desktop-state.ts
12632
- import { Database as Database3 } from "bun:sqlite";
12633
- import { readFile as readFile7, writeFile as writeFile14, rm as rm3, lstat as lstat7, rename as rename2, chmod as chmod2 } from "fs/promises";
12634
- 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, copyFile as copyFile2, link as link2 } from "fs/promises";
12658
+ import { spawnSync as spawnSync2 } from "child_process";
12659
+ import { resolve as resolve9 } from "path";
12660
+ import { createHash as createHash12 } from "crypto";
12661
+ var desktopReadLimit = 1024 * 1024;
12662
+ function admitDesktopFile(info) {
12663
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== process.getuid?.() || info.gid !== process.getgid?.() || (info.mode & 18) !== 0 || info.size > desktopReadLimit)
12664
+ throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user and their primary group.");
12665
+ }
12666
+ function admitDesktopMetadata(path, info) {
12667
+ const attributes = [];
12668
+ const hash2 = () => createHash12("sha256").update(JSON.stringify({ gid: info.gid, attributes })).digest("hex");
12669
+ if (process.platform !== "darwin")
12670
+ return hash2();
12671
+ const deadline = Date.now() + 2000;
12672
+ const inspect = (executable, args, maxBuffer) => {
12673
+ const remaining = deadline - Date.now();
12674
+ if (remaining <= 0)
12675
+ throw new Fault(422, "desktop_state_permissions", "Desktop metadata inspection timed out.");
12676
+ const result = spawnSync2(executable, args, { encoding: "utf8", env: { LC_ALL: "C" }, stdio: ["ignore", "pipe", "ignore"], timeout: remaining, maxBuffer });
12677
+ if (result.error || result.status !== 0)
12678
+ throw new Fault(422, "desktop_state_permissions", `Desktop security metadata could not be verified (${result.error?.code === "ETIMEDOUT" ? "inspection_timeout" : "inspection_exit"}).`);
12679
+ return result.stdout;
12680
+ };
12681
+ const listing = inspect("/bin/ls", ["-ldneO@", resolve9(path)], 64 * 1024);
12682
+ const lines = listing.trimEnd().split(`
12683
+ `), fields = lines[0]?.trim().split(/\s+/);
12684
+ const refused = !fields || !/^-[-rwxStTs]{9}@?$/.test(fields[0] ?? "") ? "mode_or_acl" : fields[1] !== "1" ? "link_count" : fields[2] !== String(info.uid) ? "owner" : fields[3] !== String(info.gid) ? "group" : fields[4] !== "-" ? "file_flags" : lines.slice(1).some((line) => !line.startsWith("\t") || /^\s*\d+:/.test(line)) ? "metadata_records" : undefined;
12685
+ if (refused)
12686
+ throw new Fault(422, "desktop_state_permissions", `Desktop settings security metadata cannot be safely restored (${refused}).`);
12687
+ const names = inspect("/usr/bin/xattr", [resolve9(path)], 64 * 1024).trimEnd().split(`
12688
+ `).filter(Boolean).sort();
12689
+ if (names.length > 64 || new Set(names).size !== names.length || names.some((name) => name.length > 255 || /[\x00-\x1f\x7f]/.test(name)))
12690
+ throw new Fault(422, "desktop_state_permissions", "Desktop extended attributes exceed bounded inspection.");
12691
+ let total = 0;
12692
+ for (const name of names) {
12693
+ const hex = inspect("/usr/bin/xattr", ["-px", name, resolve9(path)], 2 * desktopReadLimit + 64 * 1024).replace(/\s/g, "");
12694
+ total += hex.length / 2;
12695
+ if (hex.length % 2 || !/^[0-9a-fA-F]*$/.test(hex) || total > desktopReadLimit)
12696
+ throw new Fault(422, "desktop_state_permissions", "Desktop extended attributes exceed bounded inspection.");
12697
+ attributes.push({ name, digest: createHash12("sha256").update(Buffer.from(hex, "hex")).digest("hex") });
12698
+ }
12699
+ return hash2();
12700
+ }
12701
+ function admitOpenedDesktopFile(info, opened) {
12702
+ if (opened.dev !== info.dev || opened.ino !== info.ino || opened.nlink !== 1 || opened.size > desktopReadLimit || opened.mode !== info.mode || opened.uid !== info.uid || opened.gid !== info.gid || opened.ctimeMs !== info.ctimeMs)
12703
+ throw new Fault(409, "desktop_state_changed", "Desktop settings changed while being read.");
12704
+ }
12705
+ function desktopSnapshot(bytes, length, opened, after, metadataHash) {
12706
+ if (length > desktopReadLimit || length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs || after.mode !== opened.mode || after.gid !== opened.gid)
12707
+ throw new Fault(409, "desktop_state_changed", "Desktop settings changed while being read.");
12708
+ try {
12709
+ return { text: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, length)), mode: after.mode & 4095, metadataHash };
12710
+ } catch {
12711
+ throw new Fault(422, "desktop_state_encoding", "Desktop settings must be valid UTF-8; original bytes were left unchanged.");
12712
+ }
12713
+ }
12714
+ async function safeDesktopSnapshot(path) {
12635
12715
  try {
12636
12716
  const info = await lstat7(path);
12637
- if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
12638
- throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user.");
12639
- return await readFile7(path, "utf8");
12717
+ admitDesktopFile(info);
12718
+ const metadataHash = admitDesktopMetadata(path, info);
12719
+ const file = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12720
+ try {
12721
+ const opened = await file.stat();
12722
+ admitOpenedDesktopFile(info, opened);
12723
+ const bytes = Buffer.alloc(desktopReadLimit + 1);
12724
+ let length = 0;
12725
+ while (length < bytes.length) {
12726
+ const read = await file.read(bytes, length, bytes.length - length, length);
12727
+ if (read.bytesRead === 0)
12728
+ break;
12729
+ length += read.bytesRead;
12730
+ }
12731
+ const snapshot2 = desktopSnapshot(bytes, length, opened, await file.stat(), metadataHash);
12732
+ admitOpenedDesktopFile(opened, lstatSync(path));
12733
+ return snapshot2;
12734
+ } finally {
12735
+ await file.close();
12736
+ }
12640
12737
  } catch (error) {
12641
12738
  if (error.code === "ENOENT")
12642
12739
  return;
12643
12740
  throw error;
12644
12741
  }
12645
12742
  }
12646
- async function writeDesktopPrivate(path, text) {
12647
- const temporary = path + "." + crypto.randomUUID() + ".tmp";
12743
+ function safeDesktopSnapshotSync(path) {
12744
+ try {
12745
+ const info = lstatSync(path);
12746
+ admitDesktopFile(info);
12747
+ const metadataHash = admitDesktopMetadata(path, info);
12748
+ const file = openSync2(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12749
+ try {
12750
+ const opened = fstatSync(file);
12751
+ admitOpenedDesktopFile(info, opened);
12752
+ const bytes = Buffer.alloc(desktopReadLimit + 1);
12753
+ let length = 0;
12754
+ while (length < bytes.length) {
12755
+ const count = readSync2(file, bytes, length, bytes.length - length, length);
12756
+ if (count === 0)
12757
+ break;
12758
+ length += count;
12759
+ }
12760
+ const snapshot2 = desktopSnapshot(bytes, length, opened, fstatSync(file), metadataHash);
12761
+ admitOpenedDesktopFile(opened, lstatSync(path));
12762
+ return snapshot2;
12763
+ } finally {
12764
+ closeSync2(file);
12765
+ }
12766
+ } catch (error) {
12767
+ if (error.code === "ENOENT")
12768
+ return;
12769
+ throw error;
12770
+ }
12771
+ }
12772
+ async function safeDesktopRead(path) {
12773
+ return (await safeDesktopSnapshot(path))?.text;
12774
+ }
12775
+ function sameDesktopSnapshot(a, b) {
12776
+ return a?.text === b?.text && a?.mode === b?.mode && a?.metadataHash === b?.metadataHash;
12777
+ }
12778
+ async function preserveDesktopFile(source, destination, expected) {
12779
+ if (await safeDesktopSnapshot(destination) !== undefined || !sameDesktopSnapshot(await safeDesktopSnapshot(source), expected))
12780
+ throw new Fault(409, "desktop_state_changed", "Desktop preservation target or source changed.");
12781
+ if (process.platform === "darwin") {
12782
+ const copied = spawnSync2("/bin/cp", ["-pn", resolve9(source), resolve9(destination)], { env: { LC_ALL: "C" }, stdio: "ignore", timeout: 2000 });
12783
+ if (copied.error || copied.status !== 0)
12784
+ throw new Fault(422, "desktop_state_permissions", "Desktop metadata preservation failed.");
12785
+ } else
12786
+ await copyFile2(source, destination, constants7.COPYFILE_EXCL);
12787
+ if (!sameDesktopSnapshot(await safeDesktopSnapshot(source), expected) || !sameDesktopSnapshot(await safeDesktopSnapshot(destination), expected))
12788
+ throw new Fault(409, "desktop_state_changed", "Desktop original preservation readback failed.");
12789
+ }
12790
+ var conflictPath = (path, suffix) => path + "." + crypto.randomUUID() + "." + suffix;
12791
+ async function exists(path) {
12648
12792
  try {
12649
- await writeFile14(temporary, text, { mode: 384, flag: "wx" });
12650
- await rename2(temporary, path);
12793
+ await lstat7(path);
12794
+ return true;
12795
+ } catch (error) {
12796
+ if (error.code === "ENOENT")
12797
+ return false;
12798
+ throw error;
12799
+ }
12800
+ }
12801
+ async function preserveConflict(path) {
12802
+ const target = conflictPath(path, "conflict");
12803
+ await rename2(path, target);
12804
+ return target;
12805
+ }
12806
+ async function restoreDisplaced(backup, path) {
12807
+ const snapshot2 = await safeDesktopSnapshot(backup);
12808
+ if (!snapshot2)
12809
+ throw new Fault(409, "desktop_state_changed", "Desktop displaced state is missing; existing state was preserved.");
12810
+ const temporary = conflictPath(path, "restore");
12811
+ try {
12812
+ await preserveDesktopFile(backup, temporary, snapshot2);
12813
+ try {
12814
+ await link2(temporary, path);
12815
+ } catch (error) {
12816
+ if (error.code === "EEXIST") {
12817
+ const preserved = await preserveConflict(path);
12818
+ throw new Fault(409, "desktop_state_changed", `Desktop settings changed; foreign file preserved at ${preserved}; original retained at ${backup}.`);
12819
+ }
12820
+ throw error;
12821
+ }
12822
+ await rm3(temporary, { force: true });
12823
+ if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), snapshot2))
12824
+ throw new Fault(409, "desktop_state_changed", `Desktop settings changed after restoration; original retained at ${backup}.`);
12651
12825
  } finally {
12826
+ if (await safeDesktopSnapshot(temporary).catch(() => {
12827
+ return;
12828
+ }) !== undefined)
12829
+ await rm3(temporary, { force: true });
12830
+ }
12831
+ }
12832
+ async function replaceDesktopFile(path, temporary, expectedCurrent, expectedNew) {
12833
+ if (!sameDesktopSnapshot(await safeDesktopSnapshot(temporary), expectedNew))
12834
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement bytes changed before installation.");
12835
+ if (expectedCurrent === undefined) {
12836
+ if (await exists(path))
12837
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement target appeared concurrently; existing state was preserved.");
12838
+ try {
12839
+ await link2(temporary, path);
12840
+ } catch (error) {
12841
+ if (error.code === "EEXIST")
12842
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement target appeared concurrently; existing state was preserved.");
12843
+ throw error;
12844
+ }
12652
12845
  await rm3(temporary, { force: true });
12846
+ if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), expectedNew)) {
12847
+ const preserved = await preserveConflict(path);
12848
+ throw new Fault(409, "desktop_state_changed", `Desktop replacement changed after installation; foreign file preserved at ${preserved}.`);
12849
+ }
12850
+ return;
12851
+ }
12852
+ const backup = conflictPath(path, "previous");
12853
+ let displaced = false;
12854
+ try {
12855
+ try {
12856
+ await rename2(path, backup);
12857
+ displaced = true;
12858
+ } catch (error) {
12859
+ if (error.code === "ENOENT")
12860
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement target disappeared; existing state was preserved.");
12861
+ throw error;
12862
+ }
12863
+ let current;
12864
+ try {
12865
+ current = await safeDesktopSnapshot(backup);
12866
+ } catch {
12867
+ await restoreDisplaced(backup, path);
12868
+ displaced = false;
12869
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement target changed; existing state was preserved.");
12870
+ }
12871
+ if (!sameDesktopSnapshot(current, expectedCurrent)) {
12872
+ await restoreDisplaced(backup, path);
12873
+ displaced = false;
12874
+ throw new Fault(409, "desktop_state_changed", "Desktop settings changed before replacement; existing state was preserved.");
12875
+ }
12876
+ try {
12877
+ await link2(temporary, path);
12878
+ } catch (error) {
12879
+ if (error.code === "EEXIST") {
12880
+ await restoreDisplaced(backup, path);
12881
+ displaced = false;
12882
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement target appeared concurrently; existing state was preserved.");
12883
+ }
12884
+ throw error;
12885
+ }
12886
+ await rm3(temporary, { force: true });
12887
+ if (!sameDesktopSnapshot(await safeDesktopSnapshot(path), expectedNew)) {
12888
+ await restoreDisplaced(backup, path);
12889
+ displaced = false;
12890
+ throw new Fault(409, "desktop_state_changed", "Desktop replacement changed after installation; existing state was preserved.");
12891
+ }
12892
+ displaced = false;
12893
+ } finally {
12894
+ if (displaced) {
12895
+ try {
12896
+ await restoreDisplaced(backup, path);
12897
+ } catch {}
12898
+ }
12899
+ }
12900
+ }
12901
+ async function removeDesktopFile(path, expected, guard) {
12902
+ if (expected === undefined) {
12903
+ if (await exists(path))
12904
+ throw new Fault(409, "desktop_state_changed", "Desktop removal target appeared concurrently; existing state was preserved.");
12905
+ return;
12906
+ }
12907
+ const quarantine = conflictPath(path, "remove");
12908
+ try {
12909
+ await rename2(path, quarantine);
12910
+ } catch (error) {
12911
+ if (error.code === "ENOENT")
12912
+ throw new Fault(409, "desktop_state_changed", "Desktop removal target disappeared; existing state was preserved.");
12913
+ throw error;
12914
+ }
12915
+ let moved;
12916
+ try {
12917
+ moved = await safeDesktopSnapshot(quarantine);
12918
+ } catch {
12919
+ await restoreDisplaced(quarantine, path);
12920
+ throw new Fault(409, "desktop_state_changed", "Desktop removal target changed; existing state was preserved.");
12921
+ }
12922
+ if (!sameDesktopSnapshot(moved, expected)) {
12923
+ await restoreDisplaced(quarantine, path);
12924
+ throw new Fault(409, "desktop_state_changed", "Desktop removal target changed; existing state was preserved.");
12925
+ }
12926
+ if (guard) {
12927
+ try {
12928
+ await guard();
12929
+ } catch (error) {
12930
+ try {
12931
+ await restoreDisplaced(quarantine, path);
12932
+ } catch {}
12933
+ throw error;
12934
+ }
12935
+ }
12936
+ await rm3(quarantine, { force: true });
12937
+ if (await exists(path))
12938
+ throw new Fault(409, "desktop_state_changed", "Desktop removal target appeared concurrently; existing state was preserved.");
12939
+ }
12940
+ async function writeDesktopPrivate(path, text, mode = 384, metadataSource, expectation) {
12941
+ if (!Number.isInteger(mode) || mode < 0 || mode > 4095 || (mode & 18) !== 0)
12942
+ throw new Fault(422, "desktop_state_permissions", "Desktop settings restoration requires an admitted original mode.");
12943
+ const observed = await safeDesktopSnapshot(path);
12944
+ if (expectation && !sameDesktopSnapshot(observed, expectation.current))
12945
+ throw new Fault(409, "desktop_state_changed", "Desktop settings changed before restoration; existing state was preserved.");
12946
+ const expectedCurrent = expectation ? expectation.current : observed;
12947
+ const template = metadataSource?.snapshot ?? expectedCurrent;
12948
+ if (metadataSource && !sameDesktopSnapshot(await safeDesktopSnapshot(metadataSource.path), template))
12949
+ throw new Fault(409, "desktop_state_changed", "Desktop restoration original changed or is missing.");
12950
+ const temporary = path + "." + crypto.randomUUID() + ".tmp";
12951
+ try {
12952
+ if (template) {
12953
+ await preserveDesktopFile(metadataSource?.path ?? path, temporary, template);
12954
+ await chmod2(temporary, 384);
12955
+ }
12956
+ const file = await open4(temporary, constants7.O_RDWR | constants7.O_NOFOLLOW | (template ? 0 : constants7.O_CREAT | constants7.O_EXCL), 384);
12957
+ try {
12958
+ await file.truncate(0);
12959
+ await file.writeFile(text);
12960
+ await file.chmod(mode);
12961
+ } finally {
12962
+ await file.close();
12963
+ }
12964
+ const written = await safeDesktopSnapshot(temporary);
12965
+ if (written?.text !== text || written.mode !== mode || template && written.metadataHash !== template.metadataHash)
12966
+ throw new Fault(409, "desktop_state_changed", "Desktop settings restoration readback failed.");
12967
+ await replaceDesktopFile(path, temporary, expectedCurrent, written);
12968
+ } finally {
12969
+ if (await safeDesktopSnapshot(temporary).catch(() => {
12970
+ return;
12971
+ }) !== undefined)
12972
+ await rm3(temporary, { force: true });
12653
12973
  }
12654
12974
  }
12655
12975
  async function desktopLease(path) {
12656
12976
  try {
12657
12977
  const info = await lstat7(path);
12658
- if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
12978
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== process.getuid?.() || (info.mode & 18) !== 0)
12659
12979
  throw new Fault(422, "desktop_state_permissions", "Desktop lease must be a regular file owned by this user.");
12660
12980
  } catch (error) {
12661
12981
  if (error.code !== "ENOENT")
12662
12982
  throw error;
12663
12983
  }
12664
- const lease = new Database3(path);
12984
+ const lease = await openDesktopLease(path);
12665
12985
  try {
12666
12986
  await chmod2(path, 384);
12667
12987
  lease.exec("PRAGMA busy_timeout=0; CREATE TABLE IF NOT EXISTS lease (id INTEGER PRIMARY KEY); BEGIN EXCLUSIVE;");
@@ -12677,12 +12997,27 @@ async function desktopLease(path) {
12677
12997
  }
12678
12998
  };
12679
12999
  }
13000
+ async function openDesktopLease(path, readOnly2 = false) {
13001
+ try {
13002
+ if (process.versions.bun) {
13003
+ const { Database: Database3 } = await import("bun:sqlite");
13004
+ return readOnly2 ? new Database3(path, { readonly: true }) : new Database3(path);
13005
+ }
13006
+ const [major, minor] = process.versions.node.split(".").map(Number);
13007
+ if (major !== 24 || minor < 20)
13008
+ throw new Error("unsupported runtime");
13009
+ const { DatabaseSync } = await import("node:sqlite");
13010
+ return new DatabaseSync(path, { readOnly: readOnly2 });
13011
+ } catch {
13012
+ 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.");
13013
+ }
13014
+ }
12680
13015
 
12681
13016
  // src/native-state.ts
12682
- 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";
12683
- import { constants as constants7 } from "fs";
13017
+ 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";
13018
+ import { constants as constants8, lstatSync as lstatSync2, realpathSync } from "fs";
12684
13019
  import { homedir as homedir9 } from "os";
12685
- import { dirname as dirname8, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve9 } from "path";
13020
+ import { dirname as dirname8, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve10 } from "path";
12686
13021
  function nativeStateRequested(tool, environment = process.env, explicit) {
12687
13022
  if (explicit !== undefined)
12688
13023
  return explicit;
@@ -12731,25 +13066,31 @@ async function info(path) {
12731
13066
  function absolute(value) {
12732
13067
  if (!isAbsolute16(value) || value.includes("\x00"))
12733
13068
  throw new Fault(422, "native_state_path", "The shared native state directory must be an absolute path.");
12734
- return resolve9(value);
13069
+ return resolve10(value);
12735
13070
  }
12736
13071
  function credentialOverlay(path) {
12737
13072
  return /(?:^|\/)subscriptions\/profiles\//.test(path) || /(?:^|\/)switcher\/state\/(?:desktop|desktop-claude|launch-[^/]+)\//.test(path);
12738
13073
  }
13074
+ function assertSafeAncestor(ancestor) {
13075
+ const stickyRoot = ancestor.uid === 0 && (ancestor.mode & 512) !== 0;
13076
+ if (!ancestor.isDirectory() || ancestor.isSymbolicLink() || ![0, process.getuid?.()].includes(ancestor.uid) || (ancestor.mode & 18) !== 0 && !stickyRoot)
13077
+ throw new Fault(422, "native_state_permissions", "Shared native state has an unsafe ancestor directory.");
13078
+ }
12739
13079
  async function assertSafeAncestors(path) {
12740
13080
  for (let parent = path;; parent = dirname8(parent)) {
12741
- const ancestor = await lstat8(parent);
12742
- const stickyRoot = ancestor.uid === 0 && (ancestor.mode & 512) !== 0;
12743
- if (!ancestor.isDirectory() || ancestor.isSymbolicLink() || ![0, process.getuid?.()].includes(ancestor.uid) || (ancestor.mode & 18) !== 0 && !stickyRoot)
12744
- throw new Fault(422, "native_state_permissions", "Shared native state has an unsafe ancestor directory.");
13081
+ assertSafeAncestor(await lstat8(parent));
12745
13082
  if (parent === dirname8(parent))
12746
13083
  break;
12747
13084
  }
12748
13085
  }
13086
+ function assertNativeDirectoryEntry(entry, redirected = false) {
13087
+ if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || redirected)
13088
+ throw new Fault(422, "native_state_permissions", "Shared native state must be an owned directory without writable or symbolic-link redirection.");
13089
+ }
12749
13090
  async function assertNativeStateDirectory(path) {
12750
13091
  const entry = await info(path);
12751
- if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || await realpath6(path) !== path)
12752
- throw new Fault(422, "native_state_permissions", "Shared native state must be an owned directory without writable or symbolic-link redirection.");
13092
+ assertNativeDirectoryEntry(entry);
13093
+ assertNativeDirectoryEntry(entry, await realpath6(path) !== path);
12753
13094
  await assertSafeAncestors(dirname8(path));
12754
13095
  }
12755
13096
  async function ensureNativeStateDirectory(path, create = true) {
@@ -12793,7 +13134,7 @@ async function withNativeStateLock(state, operation) {
12793
13134
  const path = join17(state.home, ".switcher-shared-state.lock");
12794
13135
  let handle;
12795
13136
  try {
12796
- handle = await open4(path, "wx", 384);
13137
+ handle = await open5(path, "wx", 384);
12797
13138
  } catch (error) {
12798
13139
  if (error.code !== "EEXIST")
12799
13140
  throw error;
@@ -12844,7 +13185,7 @@ async function readCodexStateConfig(home) {
12844
13185
  return {};
12845
13186
  if (!entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
12846
13187
  throw new Fault(422, "native_state_config", "The Codex instruction configuration cannot be read safely.");
12847
- const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
13188
+ const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
12848
13189
  let config;
12849
13190
  try {
12850
13191
  const opened = await handle.stat();
@@ -12873,12 +13214,12 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
12873
13214
  if (!valid)
12874
13215
  throw new Fault(422, "native_state_instructions", "Codex instruction configuration has an unsupported value.");
12875
13216
  if (CODEX_INSTRUCTION_FILE_KEYS.has(key)) {
12876
- const path = resolve9(home, value), entry = await info(path);
13217
+ const path = resolve10(home, value), entry = await info(path);
12877
13218
  const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute16(relativePath);
12878
13219
  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)
12879
13220
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
12880
13221
  await assertSafeAncestors(dirname8(path));
12881
- const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW).catch(() => {
13222
+ const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW).catch(() => {
12882
13223
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
12883
13224
  });
12884
13225
  try {
@@ -13038,7 +13379,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13038
13379
  throw new Fault(422, "native_state_entry", "A shared native state entry has an unsupported type, owner or permissions.");
13039
13380
  if (source?.isDirectory())
13040
13381
  await assertShareableTree(target);
13041
- if (existing && (!existing.isSymbolicLink() || resolve9(dirname8(destination), await readlink(destination)) !== target))
13382
+ if (existing && (!existing.isSymbolicLink() || resolve10(dirname8(destination), await readlink(destination)) !== target))
13042
13383
  throw new Fault(409, "native_state_migration_required", "This launch profile already contains native state. Preserve and migrate its noncredential state before linking the shared corpus.");
13043
13384
  }
13044
13385
  const createdLinks = [];
@@ -13061,7 +13402,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13061
13402
  if (entry.kind === "directory")
13062
13403
  await createTrackedDirectory(target, createdDirectories);
13063
13404
  else {
13064
- const file = await open4(target, "wx", 384);
13405
+ const file = await open5(target, "wx", 384);
13065
13406
  await file.close();
13066
13407
  createdFiles.push(target);
13067
13408
  }
@@ -13074,7 +13415,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13074
13415
  } catch (error) {
13075
13416
  for (const item2 of createdLinks.reverse()) {
13076
13417
  try {
13077
- if ((await info(item2.destination))?.isSymbolicLink() && resolve9(dirname8(item2.destination), await readlink(item2.destination)) === item2.target)
13418
+ if ((await info(item2.destination))?.isSymbolicLink() && resolve10(dirname8(item2.destination), await readlink(item2.destination)) === item2.target)
13078
13419
  await unlink2(item2.destination);
13079
13420
  } catch {}
13080
13421
  }
@@ -13130,7 +13471,7 @@ function clearSwitcherModelState(config) {
13130
13471
  delete config.memories;
13131
13472
  }
13132
13473
  }
13133
- var digest = (value) => createHash12("sha256").update(value).digest("hex");
13474
+ var digest = (value) => createHash13("sha256").update(value).digest("hex");
13134
13475
  var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
13135
13476
  async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedState) {
13136
13477
  if (sharedState && sharedState.tool !== "codex")
@@ -13213,7 +13554,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedSta
13213
13554
  fi
13214
13555
  `;
13215
13556
  }
13216
- await writeFile15(wrapper, `#!/bin/sh
13557
+ await writeFile14(wrapper, `#!/bin/sh
13217
13558
  set -eu
13218
13559
  unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
13219
13560
  export CODEX_HOME=${quote2(home)}
@@ -13244,18 +13585,293 @@ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join("
13244
13585
  }
13245
13586
 
13246
13587
  // src/claude-desktop-launch.ts
13247
- import { createHash as createHash13 } from "crypto";
13248
- import { execFile as execFile5 } from "child_process";
13249
- import { access as access4, rm as rm5, writeFile as writeFile17 } from "fs/promises";
13250
- import { homedir as homedir11, userInfo as userInfo2 } from "os";
13251
- import { join as join20 } from "path";
13252
- import { promisify as promisify5 } from "util";
13588
+ import { writeFile as writeFile17 } from "fs/promises";
13589
+ import { join as join21 } from "path";
13590
+ // src/desktop-selection.ts
13591
+ import { createHash as createHash14, randomUUID as randomUUID6 } from "crypto";
13592
+ import { writeFile as writeFile15, rename as rename3 } from "fs/promises";
13593
+ import { join as join19 } from "path";
13594
+ var hash2 = (text) => createHash14("sha256").update(text).digest("hex");
13595
+ var conflict = () => new Fault(409, "desktop_config_changed", "Desktop configuration changed; existing bytes and the recovery receipt were preserved.");
13596
+ var invalid3 = () => new Fault(409, "desktop_recovery", "Desktop selection needs recovery by its owning supported version before another launch.");
13597
+ var identifier = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,80}$/.test(value);
13598
+ var admittedMode = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4095 && (value & 18) === 0;
13599
+ var matches = (actual, text, mode, metadataHash) => (actual?.text ?? null) === text && (actual?.mode ?? null) === mode && (actual?.metadataHash ?? null) === metadataHash;
13600
+ var originalPath = (library, id2) => join19(library, `.switcher-original-${id2}.bak`);
13601
+ var preparedPath = (library, id2) => join19(library, `.switcher-selected-${id2}.tmp`);
13602
+ function metadata(text) {
13603
+ if (text === null)
13604
+ return { entries: [] };
13605
+ let value;
13606
+ try {
13607
+ value = JSON.parse(text);
13608
+ } catch {
13609
+ throw invalid3();
13610
+ }
13611
+ if (!value || typeof value !== "object" || Array.isArray(value))
13612
+ throw invalid3();
13613
+ const m = value;
13614
+ if (!Array.isArray(m.entries) || m.entries.some((x) => !x || typeof x !== "object" || Array.isArray(x)) || m.appliedId !== undefined && !identifier(m.appliedId))
13615
+ throw invalid3();
13616
+ return m;
13617
+ }
13618
+ function v4Receipt(value) {
13619
+ const r = value;
13620
+ if (r?.version !== 4 || !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.previousMeta === null ? r.previousMetadataHash !== null : typeof r.previousMetadataHash !== "string" || !/^[a-f0-9]{64}$/.test(r.previousMetadataHash)) || typeof r.appliedMetadataHash !== "string" || !/^[a-f0-9]{64}$/.test(r.appliedMetadataHash) || r.previousMetadataHash !== null && r.appliedMetadataHash !== r.previousMetadataHash || r.previousSelected !== null && (!r.previousSelected || !identifier(r.previousSelected.id) || r.previousSelected.hash === undefined && r.previousSelected.text === undefined || r.previousSelected.hash !== undefined && r.previousSelected.text !== undefined || r.previousSelected.hash !== undefined && r.previousSelected.hash !== null && (typeof r.previousSelected.hash !== "string" || !/^[a-f0-9]{64}$/.test(r.previousSelected.hash)) || r.previousSelected.text !== undefined && r.previousSelected.text !== null && typeof r.previousSelected.text !== "string"))
13621
+ throw invalid3();
13622
+ const before = metadata(r.previousMeta), after = metadata(r.appliedMeta);
13623
+ if (after.appliedId !== r.id || before.appliedId === r.id || (before.appliedId ?? null) !== (r.previousSelected?.id ?? null))
13624
+ throw invalid3();
13625
+ return r;
13626
+ }
13627
+ function receipt(text) {
13628
+ let value;
13629
+ try {
13630
+ value = JSON.parse(text);
13631
+ } catch {
13632
+ throw invalid3();
13633
+ }
13634
+ if (value?.version === 4)
13635
+ return v4Receipt(value);
13636
+ const r = value;
13637
+ if (!r || typeof r !== "object" || Array.isArray(r) || Object.keys(r).sort().join(",") !== "appliedMeta,configHash,id,previousMeta" || !identifier(r.id) || !/^[0-9a-f-]{36}$/.test(r.id) || typeof r.configHash !== "string" || !/^[a-f0-9]{64}$/.test(r.configHash) || r.previousMeta !== null || typeof r.appliedMeta !== "string")
13638
+ throw invalid3();
13639
+ return { id: r.id, configHash: r.configHash, previousMeta: null, appliedMeta: r.appliedMeta };
13640
+ }
13641
+ function upgradeReceipt(r, currentMeta) {
13642
+ if ("version" in r)
13643
+ return r;
13644
+ return {
13645
+ version: 4,
13646
+ id: r.id,
13647
+ configHash: r.configHash,
13648
+ previousMeta: null,
13649
+ previousMetaMode: null,
13650
+ previousMetadataHash: null,
13651
+ appliedMeta: r.appliedMeta,
13652
+ appliedMetadataHash: currentMeta?.metadataHash ?? "0".repeat(64),
13653
+ previousSelected: null
13654
+ };
13655
+ }
13656
+ async function selectedUnchanged(library, r) {
13657
+ const selected = r.previousSelected;
13658
+ if (!selected)
13659
+ return;
13660
+ const current = await safeDesktopRead(join19(library, selected.id + ".json"));
13661
+ if (selected.hash !== undefined) {
13662
+ if (selected.hash === null ? current !== undefined : current === undefined || hash2(current) !== selected.hash)
13663
+ throw conflict();
13664
+ } else if ((current ?? null) !== (selected.text ?? null))
13665
+ throw conflict();
13666
+ }
13667
+ function selectedUnchangedSync(library, selected) {
13668
+ if (!selected)
13669
+ return true;
13670
+ const current = safeDesktopSnapshotSync(join19(library, selected.id + ".json"))?.text;
13671
+ if (selected.hash !== undefined)
13672
+ return selected.hash === null ? current === undefined : current !== undefined && hash2(current) === selected.hash;
13673
+ return (current ?? null) === (selected.text ?? null);
13674
+ }
13675
+ function retainedReceipt(r) {
13676
+ const selected = r.previousSelected;
13677
+ if (!selected || selected.text === undefined)
13678
+ return JSON.stringify(r) + `
13679
+ `;
13680
+ return JSON.stringify({ ...r, previousSelected: { id: selected.id, hash: selected.hash ?? (selected.text === null ? null : hash2(selected.text)) } }) + `
13681
+ `;
13682
+ }
13683
+ async function preservedSelection(library, r, wasApplied) {
13684
+ const backup = await safeDesktopSnapshot(originalPath(library, r.id)), prepared = await safeDesktopSnapshot(preparedPath(library, r.id));
13685
+ if (backup && !matches(backup, r.previousMeta, r.previousMetaMode, r.previousMetadataHash) || wasApplied && r.previousMeta !== null && !backup || prepared && !matches(prepared, r.appliedMeta, 384, r.appliedMetadataHash))
13686
+ throw conflict();
13687
+ return { backup, prepared };
13688
+ }
13689
+ async function recoverDesktopSelection(library) {
13690
+ const path = join19(library, ".switcher-selection.json"), raw = await safeDesktopRead(path);
13691
+ if (raw === undefined)
13692
+ return;
13693
+ const parsed = receipt(raw), metaPath = join19(library, "_meta.json"), configPath = join19(library, parsed.id + ".json");
13694
+ let currentMeta = await safeDesktopSnapshot(metaPath);
13695
+ const r = upgradeReceipt(parsed, currentMeta);
13696
+ const currentConfig = await safeDesktopRead(configPath);
13697
+ if (currentMeta === undefined && r.previousMeta !== null) {
13698
+ const preserved = await safeDesktopSnapshot(originalPath(library, r.id));
13699
+ if (!matches(preserved, r.previousMeta, r.previousMetaMode, r.previousMetadataHash))
13700
+ throw conflict();
13701
+ await writeDesktopPrivate(metaPath, r.previousMeta, r.previousMetaMode, { path: originalPath(library, r.id), snapshot: { text: r.previousMeta, mode: r.previousMetaMode, metadataHash: r.previousMetadataHash } }, { current: undefined });
13702
+ currentMeta = await safeDesktopSnapshot(metaPath);
13703
+ }
13704
+ const wasOriginal = matches(currentMeta, r.previousMeta, r.previousMetaMode, r.previousMetadataHash), wasApplied = matches(currentMeta, r.appliedMeta, 384, r.appliedMetadataHash);
13705
+ const { backup, prepared } = await preservedSelection(library, r, wasApplied);
13706
+ await selectedUnchanged(library, r);
13707
+ if (!wasOriginal && !wasApplied)
13708
+ throw conflict();
13709
+ if (currentConfig !== undefined && hash2(currentConfig) !== r.configHash || wasApplied && currentConfig === undefined)
13710
+ throw conflict();
13711
+ if (await safeDesktopRead(path) !== raw)
13712
+ throw conflict();
13713
+ if (!matches(await safeDesktopSnapshot(metaPath), currentMeta?.text ?? null, currentMeta?.mode ?? null, currentMeta?.metadataHash ?? null))
13714
+ throw conflict();
13715
+ const assertMetaRestored = async () => {
13716
+ if (!matches(await safeDesktopSnapshot(metaPath), r.previousMeta, r.previousMetaMode, r.previousMetadataHash))
13717
+ throw conflict();
13718
+ };
13719
+ const assertRestored = async () => {
13720
+ await assertMetaRestored();
13721
+ if (await safeDesktopRead(path) !== raw)
13722
+ throw conflict();
13723
+ };
13724
+ if (wasApplied) {
13725
+ if (r.previousMeta === null) {
13726
+ if (!currentMeta)
13727
+ throw conflict();
13728
+ await removeDesktopFile(metaPath, currentMeta);
13729
+ } else
13730
+ await writeDesktopPrivate(metaPath, r.previousMeta, r.previousMetaMode, { path: originalPath(library, r.id), snapshot: { text: r.previousMeta, mode: r.previousMetaMode, metadataHash: r.previousMetadataHash } }, { current: currentMeta });
13731
+ await assertRestored();
13732
+ }
13733
+ if (prepared) {
13734
+ if (!matches(safeDesktopSnapshotSync(preparedPath(library, r.id)), r.appliedMeta, 384, r.appliedMetadataHash))
13735
+ throw conflict();
13736
+ await removeDesktopFile(preparedPath(library, r.id), prepared, assertRestored);
13737
+ }
13738
+ if (backup && !matches(safeDesktopSnapshotSync(originalPath(library, r.id)), r.previousMeta, r.previousMetaMode, r.previousMetadataHash))
13739
+ throw conflict();
13740
+ if (currentConfig !== undefined) {
13741
+ const configSnapshot = await safeDesktopSnapshot(configPath);
13742
+ if (!configSnapshot || hash2(configSnapshot.text) !== r.configHash)
13743
+ throw conflict();
13744
+ await removeDesktopFile(configPath, configSnapshot, assertRestored);
13745
+ }
13746
+ await assertRestored();
13747
+ const receiptSnapshot = await safeDesktopSnapshot(path);
13748
+ if (!receiptSnapshot || receiptSnapshot.text !== raw)
13749
+ throw conflict();
13750
+ const recoveredPath = path + ".recovered-" + randomUUID6(), retained = retainedReceipt(r);
13751
+ if (retained !== raw) {
13752
+ await writeFile15(recoveredPath, retained, { mode: 384, flag: "wx" });
13753
+ const redacted = await safeDesktopSnapshot(recoveredPath);
13754
+ if (!redacted || redacted.text !== retained || redacted.mode !== 384)
13755
+ throw conflict();
13756
+ if (await safeDesktopRead(path) !== raw)
13757
+ throw conflict();
13758
+ await removeDesktopFile(path, receiptSnapshot, assertMetaRestored);
13759
+ await assertMetaRestored();
13760
+ const finalReceipt2 = await safeDesktopSnapshot(recoveredPath);
13761
+ if (!sameDesktopSnapshot(finalReceipt2, redacted)) {
13762
+ const foreignPath = recoveredPath + ".foreign-" + randomUUID6();
13763
+ if (finalReceipt2 !== undefined)
13764
+ await rename3(recoveredPath, foreignPath);
13765
+ await writeDesktopPrivate(recoveredPath, retained, 384, undefined, { current: undefined });
13766
+ throw new Fault(409, "desktop_config_changed", `Desktop recovery receipt changed; redacted receipt preserved at ${recoveredPath}; foreign receipt preserved at ${foreignPath}.`);
13767
+ }
13768
+ return;
13769
+ }
13770
+ await rename3(path, recoveredPath);
13771
+ const preserveRecovered = async (snapshot2) => {
13772
+ const foreignPath = recoveredPath + ".foreign-" + randomUUID6();
13773
+ if (snapshot2 !== undefined)
13774
+ await rename3(recoveredPath, foreignPath);
13775
+ await writeDesktopPrivate(recoveredPath, raw, 384, undefined, { current: undefined });
13776
+ throw new Fault(409, "desktop_config_changed", `Desktop recovery receipt changed; original receipt preserved at ${recoveredPath}; foreign receipt preserved at ${foreignPath}.`);
13777
+ };
13778
+ const recoveredSnapshot = await safeDesktopSnapshot(recoveredPath);
13779
+ if (!sameDesktopSnapshot(recoveredSnapshot, receiptSnapshot))
13780
+ await preserveRecovered(recoveredSnapshot);
13781
+ await assertMetaRestored();
13782
+ const finalReceipt = await safeDesktopSnapshot(recoveredPath);
13783
+ if (!sameDesktopSnapshot(finalReceipt, receiptSnapshot))
13784
+ await preserveRecovered(finalReceipt);
13785
+ }
13786
+ async function applyDesktopSelection(library, config, label2, checkpoint) {
13787
+ await recoverDesktopSelection(library);
13788
+ const path = join19(library, ".switcher-selection.json"), metaPath = join19(library, "_meta.json");
13789
+ const original = await safeDesktopSnapshot(metaPath), previousMeta = original?.text ?? null, previousMetaMode = original?.mode ?? null, previous = metadata(previousMeta);
13790
+ const previousSelectedText = previous.appliedId ? await safeDesktopRead(join19(library, previous.appliedId + ".json")) : undefined;
13791
+ const previousSelected = previous.appliedId ? { id: previous.appliedId, hash: previousSelectedText === undefined ? null : hash2(previousSelectedText) } : null;
13792
+ const id2 = randomUUID6(), configPath = join19(library, id2 + ".json"), text = JSON.stringify(config, null, 2) + `
13793
+ `;
13794
+ const appliedMeta = JSON.stringify({ ...previous, appliedId: id2, entries: [...previous.entries, { id: id2, name: label2 }] }, null, 2) + `
13795
+ `;
13796
+ const previousMetadataHash = original?.metadataHash ?? null;
13797
+ const r = { version: 4, id: id2, configHash: hash2(text), previousMeta, previousMetaMode, previousMetadataHash, appliedMeta, appliedMetadataHash: "0".repeat(64), previousSelected };
13798
+ if (Buffer.byteLength(JSON.stringify(r) + `
13799
+ `) > 1024 * 1024)
13800
+ throw invalid3();
13801
+ if (original)
13802
+ await preserveDesktopFile(metaPath, originalPath(library, id2), original);
13803
+ await writeDesktopPrivate(preparedPath(library, id2), appliedMeta, 384, original ? { path: originalPath(library, id2), snapshot: original } : undefined, { current: undefined });
13804
+ const prepared = await safeDesktopSnapshot(preparedPath(library, id2));
13805
+ if (!prepared || prepared.text !== appliedMeta || prepared.mode !== 384)
13806
+ throw conflict();
13807
+ r.appliedMetadataHash = prepared.metadataHash;
13808
+ const journal = JSON.stringify(r) + `
13809
+ `;
13810
+ if (Buffer.byteLength(journal) > 1024 * 1024)
13811
+ throw invalid3();
13812
+ await writeFile15(path, journal, { mode: 384, flag: "wx" });
13813
+ const unchanged = async () => {
13814
+ if (await safeDesktopRead(path) !== journal)
13815
+ throw conflict();
13816
+ await selectedUnchanged(library, r);
13817
+ };
13818
+ try {
13819
+ await unchanged();
13820
+ await checkpoint?.("preserved");
13821
+ if (!matches(await safeDesktopSnapshot(metaPath), previousMeta, previousMetaMode, previousMetadataHash))
13822
+ throw conflict();
13823
+ await selectedUnchanged(library, r);
13824
+ await writeFile15(configPath, text, { mode: 384, flag: "wx" });
13825
+ if (await safeDesktopRead(configPath) !== text)
13826
+ throw conflict();
13827
+ await checkpoint?.("config");
13828
+ await unchanged();
13829
+ const preparedCurrent = await safeDesktopSnapshot(preparedPath(library, id2));
13830
+ if (!preparedCurrent || !matches(preparedCurrent, appliedMeta, 384, r.appliedMetadataHash))
13831
+ throw conflict();
13832
+ const currentMeta = await safeDesktopSnapshot(metaPath);
13833
+ if (!matches(currentMeta, previousMeta, previousMetaMode, previousMetadataHash))
13834
+ throw conflict();
13835
+ await replaceDesktopFile(metaPath, preparedPath(library, id2), currentMeta, preparedCurrent);
13836
+ if (!matches(await safeDesktopSnapshot(metaPath), appliedMeta, 384, r.appliedMetadataHash))
13837
+ throw conflict();
13838
+ await checkpoint?.("selected");
13839
+ } catch (error) {
13840
+ try {
13841
+ if (await safeDesktopRead(path) === journal)
13842
+ await recoverDesktopSelection(library);
13843
+ } catch {}
13844
+ throw error;
13845
+ }
13846
+ const assertCurrentSync = () => {
13847
+ if (safeDesktopSnapshotSync(path)?.text !== journal)
13848
+ throw conflict();
13849
+ if (original && !matches(safeDesktopSnapshotSync(originalPath(library, id2)), previousMeta, previousMetaMode, previousMetadataHash))
13850
+ throw conflict();
13851
+ if (!selectedUnchangedSync(library, previousSelected))
13852
+ throw conflict();
13853
+ if (!matches(safeDesktopSnapshotSync(metaPath), appliedMeta, 384, r.appliedMetadataHash) || safeDesktopSnapshotSync(configPath)?.text !== text)
13854
+ throw conflict();
13855
+ };
13856
+ return {
13857
+ configPath,
13858
+ assertCurrentSync,
13859
+ async assertCurrent() {
13860
+ assertCurrentSync();
13861
+ },
13862
+ async restore() {
13863
+ if (await safeDesktopRead(path) !== journal)
13864
+ throw conflict();
13865
+ await recoverDesktopSelection(library);
13866
+ }
13867
+ };
13868
+ }
13253
13869
 
13254
13870
  // src/claude-user-settings.ts
13255
- import { constants as constants8 } from "fs";
13256
- import { lstat as lstat9, open as open5, writeFile as writeFile16 } from "fs/promises";
13871
+ import { constants as constants9 } from "fs";
13872
+ import { lstat as lstat9, open as open6, writeFile as writeFile16 } from "fs/promises";
13257
13873
  import { homedir as homedir10 } from "os";
13258
- import { join as join19, resolve as resolve10 } from "path";
13874
+ import { join as join20, resolve as resolve11 } from "path";
13259
13875
  var preferences = new Set([
13260
13876
  "$schema",
13261
13877
  "permissions",
@@ -13280,10 +13896,10 @@ var preferences = new Set([
13280
13896
  "teammateMode"
13281
13897
  ]);
13282
13898
  var routing3 = new Set(["model", "modelPicker", "fallbackModel"]);
13283
- var invalid3 = () => 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.");
13899
+ 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.");
13284
13900
  async function readSettings(home) {
13285
13901
  await ensureNativeStateDirectory(home, false);
13286
- const path = join19(home, "settings.json");
13902
+ const path = join20(home, "settings.json");
13287
13903
  const entry = await lstat9(path).catch((error) => {
13288
13904
  if (error.code === "ENOENT")
13289
13905
  return;
@@ -13292,20 +13908,20 @@ async function readSettings(home) {
13292
13908
  if (!entry)
13293
13909
  return;
13294
13910
  if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
13295
- throw invalid3();
13296
- const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
13911
+ throw invalid4();
13912
+ const handle = await open6(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
13297
13913
  try {
13298
13914
  const opened = await handle.stat();
13299
13915
  if (opened.dev !== entry.dev || opened.ino !== entry.ino || opened.nlink !== 1 || opened.size > 1024 * 1024)
13300
- throw invalid3();
13916
+ throw invalid4();
13301
13917
  const value = JSON.parse(await handle.readFile("utf8"));
13302
13918
  if (!value || typeof value !== "object" || Array.isArray(value))
13303
- throw invalid3();
13919
+ throw invalid4();
13304
13920
  return value;
13305
13921
  } catch (error) {
13306
13922
  if (error instanceof Fault)
13307
13923
  throw error;
13308
- throw invalid3();
13924
+ throw invalid4();
13309
13925
  } finally {
13310
13926
  await handle.close();
13311
13927
  }
@@ -13327,13 +13943,13 @@ function project(settings2, existing) {
13327
13943
  return result;
13328
13944
  }
13329
13945
  async function prepareClaudeUserSettings(overlayHome, environment = process.env) {
13330
- overlayHome = resolve10(overlayHome);
13946
+ overlayHome = resolve11(overlayHome);
13331
13947
  const existing = await readSettings(overlayHome);
13332
13948
  if (existing !== undefined) {
13333
13949
  project(existing, true);
13334
13950
  return;
13335
13951
  }
13336
- const sourceHome = resolve10(environment.CLAUDE_CONFIG_DIR ?? join19(environment.HOME ?? homedir10(), ".claude"));
13952
+ const sourceHome = resolve11(environment.CLAUDE_CONFIG_DIR ?? join20(environment.HOME ?? homedir10(), ".claude"));
13337
13953
  if (sourceHome === overlayHome)
13338
13954
  return;
13339
13955
  const source = await readSettings(sourceHome);
@@ -13342,7 +13958,7 @@ async function prepareClaudeUserSettings(overlayHome, environment = process.env)
13342
13958
  const settings2 = project(source, false);
13343
13959
  await ensureNativeStateDirectory(overlayHome);
13344
13960
  try {
13345
- await writeFile16(join19(overlayHome, "settings.json"), JSON.stringify(settings2, null, 2) + `
13961
+ await writeFile16(join20(overlayHome, "settings.json"), JSON.stringify(settings2, null, 2) + `
13346
13962
  `, { mode: 384, flag: "wx" });
13347
13963
  } catch (error) {
13348
13964
  if (error.code !== "EEXIST")
@@ -13354,31 +13970,6 @@ async function prepareClaudeUserSettings(overlayHome, environment = process.env)
13354
13970
  }
13355
13971
 
13356
13972
  // src/claude-desktop-launch.ts
13357
- var execute4 = promisify5(execFile5);
13358
- var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
13359
- var claudeDesktopDataDirectory = () => join20(homedir11(), "Library/Application Support/Claude-3p");
13360
- async function assertAvailable(userData) {
13361
- for (const path of [join20("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
13362
- if (await access4(path).then(() => true, () => false))
13363
- throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
13364
- let openFiles;
13365
- try {
13366
- 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;
13367
- } catch (error) {
13368
- if (error.code === 1)
13369
- return;
13370
- throw new Fault(409, "desktop_process_check", "Could not check whether Claude's third-party profile is already running.");
13371
- }
13372
- if (openFiles.split(`
13373
- `).some((line) => line.startsWith("n" + userData + "/")))
13374
- 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.");
13375
- }
13376
- function metadata(text) {
13377
- const value = text === undefined ? { entries: [] } : JSON.parse(text);
13378
- if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((item2) => !item2 || typeof item2 !== "object" || Array.isArray(item2)))
13379
- throw new Fault(422, "desktop_config_invalid", "Claude's configuration library metadata is invalid.");
13380
- return value;
13381
- }
13382
13973
  async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13383
13974
  if (input.harness !== "claude")
13384
13975
  throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
@@ -13387,51 +13978,35 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13387
13978
  validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
13388
13979
  if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
13389
13980
  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.");
13390
- const version2 = app.version.split(".").map(Number);
13391
- if (version2.length < 3 || version2.some((n) => !Number.isSafeInteger(n)) || version2[0] < 1 || version2[0] === 1 && version2[1] < 52386)
13392
- throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
13981
+ validateClaudeDesktopVersion(app);
13393
13982
  const userData = system?.userData ?? claudeDesktopDataDirectory();
13394
- const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
13983
+ const check2 = system?.assertAvailable ?? (() => assertClaudeDesktopAvailable(userData));
13395
13984
  await check2();
13396
13985
  await privateDirectory(userData);
13397
- const library = join20(userData, "configLibrary");
13986
+ const library = join21(userData, "configLibrary");
13398
13987
  await privateDirectory(library);
13399
- const release = await desktopLease(join20(library, ".switcher-lease.sqlite"));
13400
- const metaPath = join20(library, "_meta.json"), receiptPath = join20(library, ".switcher-selection.json");
13401
- let receipt, gateway, closed = false;
13402
- const restore = async (record3) => {
13403
- if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
13404
- throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
13405
- const configPath = join20(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
13406
- if (current !== undefined && hash2(current) !== record3.configHash)
13407
- 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.");
13408
- const currentMeta = await safeDesktopRead(metaPath);
13409
- if (currentMeta !== record3.appliedMeta && currentMeta !== (record3.previousMeta ?? undefined))
13410
- 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.");
13411
- if (record3.previousMeta === null)
13412
- await rm5(metaPath, { force: true });
13413
- else
13414
- await writeDesktopPrivate(metaPath, record3.previousMeta);
13415
- await rm5(configPath, { force: true });
13416
- await rm5(receiptPath, { force: true });
13417
- };
13988
+ const release = await desktopLease(join21(library, ".switcher-lease.sqlite"));
13989
+ let selection, gateway, closed = false, cleanupError;
13418
13990
  const cleanup = async () => {
13419
- if (closed)
13991
+ if (closed) {
13992
+ if (cleanupError)
13993
+ throw cleanupError;
13420
13994
  return;
13421
- closed = true;
13995
+ }
13422
13996
  try {
13423
13997
  await gateway?.cleanup();
13424
- if (receipt)
13425
- await restore(receipt);
13998
+ await selection?.restore();
13999
+ } catch (error) {
14000
+ cleanupError = error;
14001
+ throw error;
13426
14002
  } finally {
14003
+ closed = true;
13427
14004
  release();
13428
14005
  }
13429
14006
  };
13430
14007
  try {
13431
- const recovery = await safeDesktopRead(receiptPath);
13432
- if (recovery)
13433
- await restore(JSON.parse(recovery));
13434
- const localConfig = await safeDesktopRead(join20(userData, "claude_desktop_config.json"));
14008
+ await recoverDesktopSelection(library);
14009
+ const localConfig = await safeDesktopRead(join21(userData, "claude_desktop_config.json"));
13435
14010
  if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
13436
14011
  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.");
13437
14012
  if (input.sharedState)
@@ -13446,31 +14021,27 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13446
14021
  if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
13447
14022
  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.");
13448
14023
  const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
13449
- const catalogPath = join20(input.stateDir, "claude-desktop-policy.json");
14024
+ const catalogPath = join21(input.stateDir, "claude-desktop-policy.json");
13450
14025
  await writeFile17(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
13451
14026
  gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
13452
- const id2 = crypto.randomUUID(), configPath = join20(library, id2 + ".json");
13453
- const config = JSON.stringify({
14027
+ selection = await applyDesktopSelection(library, {
13454
14028
  inferenceProvider: "gateway",
13455
14029
  inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
13456
14030
  inferenceGatewayApiKey: gateway.token,
13457
14031
  inferenceGatewayAuthScheme: "bearer",
13458
14032
  modelDiscoveryEnabled: false,
13459
14033
  inferenceModels: Object.entries(targets).map(([tier, model3]) => ({ name: "switcher/" + tier, labelOverride: model3, anthropicFamilyTier: tier, isFamilyDefault: true }))
13460
- });
13461
- const previousMeta = await safeDesktopRead(metaPath);
13462
- const meta = metadata(previousMeta);
13463
- const appliedMeta = JSON.stringify({ ...meta, appliedId: id2, entries: [...meta.entries, { id: id2, name: `Switcher: ${input.providerId ?? "provider"} / ${input.model}` }] });
13464
- receipt = { id: id2, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
13465
- await writeDesktopPrivate(configPath, config);
13466
- await writeDesktopPrivate(receiptPath, JSON.stringify(receipt));
13467
- await writeDesktopPrivate(metaPath, appliedMeta);
14034
+ }, `Switcher: ${input.providerId ?? "provider"} / ${input.model}`);
14035
+ const configPath = selection.configPath;
13468
14036
  return {
13469
14037
  executable: app.executable,
13470
14038
  args: [],
13471
14039
  env: { ...input.sharedState ? nativeStateEnvironment(input.sharedState) : {}, CLAUDE_CONFIG_DIR: sessionDir },
13472
14040
  configPaths: [catalogPath, configPath],
13473
- beforeLaunch: check2,
14041
+ beforeLaunch: async () => {
14042
+ await check2();
14043
+ await selection.assertCurrent();
14044
+ },
13474
14045
  cleanup,
13475
14046
  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.`]
13476
14047
  };
@@ -13485,7 +14056,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13485
14056
  // src/codex-session-discovery.ts
13486
14057
  import { spawn as spawn3 } from "child_process";
13487
14058
  import { createInterface as createInterface2 } from "readline/promises";
13488
- import { basename as basename3, resolve as resolve11 } from "path";
14059
+ import { basename as basename3, resolve as resolve12 } from "path";
13489
14060
  var object6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
13490
14061
  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.");
13491
14062
  async function listCodexSessions(prepared, cwd, query) {
@@ -13500,11 +14071,11 @@ async function listCodexSessions(prepared, cwd, query) {
13500
14071
  let done = false, initialized = false, pending = Buffer.alloc(0), responseBytes = 0;
13501
14072
  let killTimer;
13502
14073
  let resolvePage, rejectPage;
13503
- const result = new Promise((resolve12, reject2) => {
13504
- resolvePage = resolve12;
14074
+ const result = new Promise((resolve13, reject2) => {
14075
+ resolvePage = resolve13;
13505
14076
  rejectPage = reject2;
13506
14077
  });
13507
- const closed = new Promise((resolve12) => child.once("close", () => resolve12()));
14078
+ const closed = new Promise((resolve13) => child.once("close", () => resolve13()));
13508
14079
  const stop = () => {
13509
14080
  child.stdin.destroy();
13510
14081
  child.kill("SIGTERM");
@@ -13603,16 +14174,16 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
13603
14174
  break;
13604
14175
  }
13605
14176
  if (nativeArgs[i].startsWith("--cd="))
13606
- effectiveCwd = resolve11(cwd, nativeArgs[i].slice(5));
14177
+ effectiveCwd = resolve12(cwd, nativeArgs[i].slice(5));
13607
14178
  else if (nativeArgs[i].startsWith("-C") && nativeArgs[i].length > 2)
13608
- effectiveCwd = resolve11(cwd, nativeArgs[i].slice(2));
14179
+ effectiveCwd = resolve12(cwd, nativeArgs[i].slice(2));
13609
14180
  if (codexOptionRequestsHelp(nativeArgs[i]))
13610
14181
  return nativeArgs;
13611
14182
  if (codexOptionTakesValue(nativeArgs[i])) {
13612
14183
  if (nativeArgs[i] === "--cd" || nativeArgs[i] === "-C") {
13613
14184
  if (!nativeArgs[i + 1])
13614
14185
  throw unavailable2();
13615
- effectiveCwd = resolve11(cwd, nativeArgs[i + 1]);
14186
+ effectiveCwd = resolve12(cwd, nativeArgs[i + 1]);
13616
14187
  }
13617
14188
  i++;
13618
14189
  continue;
@@ -13687,7 +14258,7 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
13687
14258
  // src/launcher.ts
13688
14259
  var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
13689
14260
  async function writeOriCodexCatalog(stateDir, models) {
13690
- const path = join21(stateDir, "ori-codex-models.json");
14261
+ const path = join22(stateDir, "ori-codex-models.json");
13691
14262
  const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
13692
14263
  await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
13693
14264
  `, { mode: 384, flag: "wx" });
@@ -13727,7 +14298,7 @@ async function oriRequestForPlan(plan, options = {}) {
13727
14298
  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.");
13728
14299
  if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
13729
14300
  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.");
13730
- const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve12(options.cwd) : undefined });
14301
+ const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve13(options.cwd) : undefined });
13731
14302
  const native = requireOriHarness(contract, target);
13732
14303
  if (!native.path)
13733
14304
  throw new Error("Ori did not report the native harness executable path.");
@@ -13775,13 +14346,13 @@ async function prepareOriForPlan(plan, options) {
13775
14346
  executable: detection.executable,
13776
14347
  version: detection.version,
13777
14348
  stateDir: options.stateDir,
13778
- cwd: resolve12(options.cwd ?? process.cwd()),
14349
+ cwd: resolve13(options.cwd ?? process.cwd()),
13779
14350
  args: options.args ?? [],
13780
14351
  sharedState: options.sharedState
13781
14352
  });
13782
14353
  try {
13783
14354
  const shim = prepareOriModelPolicy(request.target, native);
13784
- const dir = join21(options.stateDir, "ori-bin"), path = join21(dir, shim.name);
14355
+ const dir = join22(options.stateDir, "ori-bin"), path = join22(dir, shim.name);
13785
14356
  await mkdir12(dir, { mode: 448 });
13786
14357
  await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
13787
14358
  return { contract, prepared: {
@@ -13807,7 +14378,7 @@ async function launch(client, profileId, options = {}) {
13807
14378
  assertHarnessArguments(profile.harness, options.args ?? []);
13808
14379
  if (profile.harness === "gemini" || profile.harness === "antigravity")
13809
14380
  validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
13810
- await validateHarnessConfiguration(profile.harness, resolve12(options.cwd ?? process.cwd()), options.args);
14381
+ await validateHarnessConfiguration(profile.harness, resolve13(options.cwd ?? process.cwd()), options.args);
13811
14382
  if (profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((process.env.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
13812
14383
  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.");
13813
14384
  if (profile.harness === "grok" && process.env.GROK_FORCE_LOGIN_TEAM_ID?.trim())
@@ -13816,7 +14387,7 @@ async function launch(client, profileId, options = {}) {
13816
14387
  await client.refreshModels(profile.providerId);
13817
14388
  const plan = await client.launchPlan(profileId);
13818
14389
  assertHarnessArguments(plan.profile.harness, options.args ?? []);
13819
- await validateHarnessConfiguration(plan.profile.harness, resolve12(options.cwd ?? process.cwd()), options.args);
14390
+ await validateHarnessConfiguration(plan.profile.harness, resolve13(options.cwd ?? process.cwd()), options.args);
13820
14391
  if (options.credentialPreflight && providerCredentialFingerprint(plan.provider) !== options.credentialPreflight)
13821
14392
  throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
13822
14393
  const backend = options.backend ?? "direct";
@@ -13838,9 +14409,9 @@ async function launch(client, profileId, options = {}) {
13838
14409
  validateHarnessVersion("gemini", detection?.version);
13839
14410
  if (backend === "direct" && plan.profile.harness === "aider")
13840
14411
  validateHarnessVersion(plan.profile.harness, detection?.version);
13841
- const root = resolve12(options.stateDir ?? join21(switcherHome(), "state"));
14412
+ const root = resolve13(options.stateDir ?? join22(switcherHome(), "state"));
13842
14413
  await privateDirectory(root);
13843
- const stateDir = await mkdtemp(join21(root, "launch-"));
14414
+ const stateDir = await mkdtemp(join22(root, "launch-"));
13844
14415
  let credential;
13845
14416
  if (backend === "direct") {
13846
14417
  try {
@@ -13848,7 +14419,7 @@ async function launch(client, profileId, options = {}) {
13848
14419
  if (plan.provider.credentialEnv && !credential)
13849
14420
  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.`);
13850
14421
  } catch (error) {
13851
- await rm6(stateDir, { recursive: true, force: true });
14422
+ await rm5(stateDir, { recursive: true, force: true });
13852
14423
  throw error;
13853
14424
  }
13854
14425
  }
@@ -13899,8 +14470,8 @@ async function launch(client, profileId, options = {}) {
13899
14470
  let nativeHome2;
13900
14471
  if (sharedState && !options.desktop && !options.claudeDesktop) {
13901
14472
  const variable = sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
13902
- const configured = process.env[variable] ? resolve12(process.env[variable]) : undefined;
13903
- nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join21(root, "native-claude", profileId) : configured ?? sharedState.home;
14473
+ const configured = process.env[variable] ? resolve13(process.env[variable]) : undefined;
14474
+ nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join22(root, "native-claude", profileId) : configured ?? sharedState.home;
13904
14475
  if (sharedState.tool === "claude")
13905
14476
  await prepareClaudeUserSettings(nativeHome2);
13906
14477
  await privateDirectory(nativeHome2);
@@ -13910,12 +14481,12 @@ async function launch(client, profileId, options = {}) {
13910
14481
  if (options.shareNativeState === false && backend === "direct") {
13911
14482
  const tool = plan.profile.harness;
13912
14483
  if (options.desktop)
13913
- await assertNativeStateIsolation(tool, join21(root, "desktop", desktopState, "codex"));
14484
+ await assertNativeStateIsolation(tool, join22(root, "desktop", desktopState, "codex"));
13914
14485
  else if (options.claudeDesktop)
13915
- await assertNativeStateIsolation(tool, join21(root, "desktop-claude", desktopState));
14486
+ await assertNativeStateIsolation(tool, join22(root, "desktop-claude", desktopState));
13916
14487
  else {
13917
14488
  const variable = tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
13918
- nativeHome2 = process.env[variable] ? resolve12(process.env[variable]) : join21(root, `native-${tool}`, profileId);
14489
+ nativeHome2 = process.env[variable] ? resolve13(process.env[variable]) : join22(root, `native-${tool}`, profileId);
13919
14490
  await assertNativeStateIsolation(tool, nativeHome2);
13920
14491
  await privateDirectory(nativeHome2);
13921
14492
  }
@@ -13932,10 +14503,10 @@ async function launch(client, profileId, options = {}) {
13932
14503
  onRoutingEvent,
13933
14504
  credential,
13934
14505
  stateDir,
13935
- cwd: resolve12(options.cwd ?? process.cwd()),
14506
+ cwd: resolve13(options.cwd ?? process.cwd()),
13936
14507
  sharedState
13937
14508
  };
13938
- let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join21(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
14509
+ 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({
13939
14510
  harness: plan.profile.harness,
13940
14511
  baseUrl: plan.provider.baseUrl,
13941
14512
  protocol: plan.provider.protocol,
@@ -13951,10 +14522,10 @@ async function launch(client, profileId, options = {}) {
13951
14522
  executable: nativeExecutable ?? detection?.executable,
13952
14523
  args: options.args ?? [],
13953
14524
  stateDir,
13954
- cwd: resolve12(options.cwd ?? process.cwd()),
14525
+ cwd: resolve13(options.cwd ?? process.cwd()),
13955
14526
  version: detection?.version,
13956
14527
  sharedState,
13957
- ...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie"].includes(plan.profile.harness) ? { sessionDir: join21(root, "sessions", plan.profile.harness, profileId) } : {}
14528
+ ...["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) } : {}
13958
14529
  });
13959
14530
  cleanup = prepared.cleanup;
13960
14531
  prepared = { ...prepared, warnings: [...prepared.warnings, ...stateWarnings] };
@@ -13971,7 +14542,7 @@ async function launch(client, profileId, options = {}) {
13971
14542
  prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
13972
14543
  }
13973
14544
  if (options.desktop) {
13974
- prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join21(root, "desktop", desktopState), sharedState);
14545
+ prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join22(root, "desktop", desktopState), sharedState);
13975
14546
  cleanup = prepared.cleanup;
13976
14547
  }
13977
14548
  for (const warning of [...plan.warnings, ...prepared.warnings])
@@ -14048,7 +14619,7 @@ async function launch(client, profileId, options = {}) {
14048
14619
  interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
14049
14620
  throw preparationSignal;
14050
14621
  }
14051
- 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 });
14622
+ const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve13(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
14052
14623
  await cleanup?.();
14053
14624
  cleanup = undefined;
14054
14625
  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}.`);
@@ -14065,8 +14636,8 @@ async function launch(client, profileId, options = {}) {
14065
14636
  } finally {
14066
14637
  if (lateCreateRunFinalization) {
14067
14638
  let finalizationTimer;
14068
- const finalizationTimeout = new Promise((resolve13) => {
14069
- finalizationTimer = setTimeout(resolve13, LATE_RUN_FINALIZATION_TIMEOUT_MS);
14639
+ const finalizationTimeout = new Promise((resolve14) => {
14640
+ finalizationTimer = setTimeout(resolve14, LATE_RUN_FINALIZATION_TIMEOUT_MS);
14070
14641
  });
14071
14642
  try {
14072
14643
  await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
@@ -14079,13 +14650,13 @@ async function launch(client, profileId, options = {}) {
14079
14650
  try {
14080
14651
  await cleanup?.();
14081
14652
  } finally {
14082
- await rm6(stateDir, { recursive: true, force: true });
14653
+ await rm5(stateDir, { recursive: true, force: true });
14083
14654
  }
14084
14655
  }
14085
14656
  }
14086
14657
 
14087
14658
  // src/direct-launch.ts
14088
- import { createHash as createHash14 } from "crypto";
14659
+ import { createHash as createHash15 } from "crypto";
14089
14660
  import { createInterface as createInterface3 } from "readline/promises";
14090
14661
  var absent2 = (error) => error instanceof SwitcherError && error.status === 404;
14091
14662
  async function resolveLaunchProvider(client, selector, options = {}) {
@@ -14166,7 +14737,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
14166
14737
  const policy = modelPolicy ?? (harness === "codex" ? { version: 1, selection: "catalog" } : undefined);
14167
14738
  const normalizedPolicy = policy === undefined ? undefined : parse2(modelPolicySchema, policy);
14168
14739
  const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
14169
- const hash3 = createHash14("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
14740
+ const hash3 = createHash15("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
14170
14741
  const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
14171
14742
  let existing;
14172
14743
  try {
@@ -14190,10 +14761,10 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
14190
14761
  }
14191
14762
 
14192
14763
  // src/native-state-import.ts
14193
- import { createHash as createHash15 } from "crypto";
14194
- import { constants as constants9 } from "fs";
14195
- import { lstat as lstat10, open as open6, opendir as opendir2, link as link2, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
14196
- import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join22, relative as relative6, resolve as resolve13 } from "path";
14764
+ import { createHash as createHash16 } from "crypto";
14765
+ import { constants as constants10 } from "fs";
14766
+ import { lstat as lstat10, open as open7, opendir as opendir2, link as link3, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
14767
+ import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join23, relative as relative6, resolve as resolve14 } from "path";
14197
14768
  var MAX_FILES = 1e5;
14198
14769
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
14199
14770
  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.");
@@ -14215,7 +14786,7 @@ var inside3 = (parent, child) => {
14215
14786
  var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
14216
14787
  async function sessionId(path, expected) {
14217
14788
  const nameId = basename4(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
14218
- const handle = await open6(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
14789
+ const handle = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW);
14219
14790
  try {
14220
14791
  const before = await handle.stat();
14221
14792
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
@@ -14258,7 +14829,7 @@ async function checkSessionIdentities(plan) {
14258
14829
  for (const file of plan.files) {
14259
14830
  if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
14260
14831
  continue;
14261
- file.sessionId = await sessionId(join22(plan.source, file.path), file.source);
14832
+ file.sessionId = await sessionId(join23(plan.source, file.path), file.source);
14262
14833
  if (!file.sessionId)
14263
14834
  continue;
14264
14835
  const previous = ids.get(file.sessionId);
@@ -14282,7 +14853,7 @@ async function checkSessionIdentities(plan) {
14282
14853
  for await (const entry of await opendir2(directory)) {
14283
14854
  if (++seen > MAX_FILES || entry.isSymbolicLink())
14284
14855
  throw refused();
14285
- const path = join22(directory, entry.name);
14856
+ const path = join23(directory, entry.name);
14286
14857
  if (entry.isDirectory()) {
14287
14858
  await scan(path, depth + 1);
14288
14859
  continue;
@@ -14299,19 +14870,19 @@ async function checkSessionIdentities(plan) {
14299
14870
  file.existing = true;
14300
14871
  }
14301
14872
  }
14302
- await scan(join22(plan.state.home, "sessions"));
14303
- await scan(join22(plan.state.home, "archived_sessions"));
14873
+ await scan(join23(plan.state.home, "sessions"));
14874
+ await scan(join23(plan.state.home, "archived_sessions"));
14304
14875
  }
14305
14876
  async function fingerprint2(path, copyTo) {
14306
- const handle = await open6(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
14877
+ const handle = await open7(path, constants10.O_RDONLY | constants10.O_NOFOLLOW);
14307
14878
  let output, complete = false;
14308
14879
  try {
14309
14880
  const before = await handle.stat();
14310
14881
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
14311
14882
  throw refused();
14312
14883
  if (copyTo)
14313
- output = await open6(copyTo, "wx", 384);
14314
- const hash3 = createHash15("sha256"), buffer = Buffer.alloc(64 * 1024);
14884
+ output = await open7(copyTo, "wx", 384);
14885
+ const hash3 = createHash16("sha256"), buffer = Buffer.alloc(64 * 1024);
14315
14886
  let bytes = 0;
14316
14887
  for (;; ) {
14317
14888
  const read = await handle.read(buffer, 0, buffer.length, null);
@@ -14346,7 +14917,7 @@ async function fingerprint2(path, copyTo) {
14346
14917
  async function planNativeStateImport(state, source, selection) {
14347
14918
  if (!isAbsolute17(source) || source.includes("\x00"))
14348
14919
  throw refused();
14349
- source = resolve13(source);
14920
+ source = resolve14(source);
14350
14921
  if (inside3(source, state.home) || inside3(state.home, source))
14351
14922
  throw refused();
14352
14923
  await assertNativeStateDirectory(source);
@@ -14360,9 +14931,9 @@ async function planNativeStateImport(state, source, selection) {
14360
14931
  async function visit(path, kind) {
14361
14932
  if (++seen > MAX_FILES || path.split("/").length > 32)
14362
14933
  throw refused();
14363
- await ensureNativeStateDirectory(dirname9(join22(source, path)), false);
14364
- await ensureNativeStateDirectory(dirname9(join22(state.home, path)), false);
14365
- const from = join22(source, path), to = join22(state.home, path), entry = await info2(from), target = await info2(to);
14934
+ await ensureNativeStateDirectory(dirname9(join23(source, path)), false);
14935
+ await ensureNativeStateDirectory(dirname9(join23(state.home, path)), false);
14936
+ const from = join23(source, path), to = join23(state.home, path), entry = await info2(from), target = await info2(to);
14366
14937
  if (!entry)
14367
14938
  return;
14368
14939
  if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
@@ -14381,7 +14952,7 @@ async function planNativeStateImport(state, source, selection) {
14381
14952
  }
14382
14953
  children.sort((a, b) => a.name.localeCompare(b.name));
14383
14954
  for (const child of children)
14384
- await visit(join22(path, child.name), child.kind);
14955
+ await visit(join23(path, child.name), child.kind);
14385
14956
  } else {
14386
14957
  const value = await fingerprint2(from);
14387
14958
  plan.bytes += value.bytes;
@@ -14403,7 +14974,7 @@ async function planNativeStateImport(state, source, selection) {
14403
14974
  return plan;
14404
14975
  }
14405
14976
  function nativeStateImportDigest(plan) {
14406
- return createHash15("sha256").update(JSON.stringify({
14977
+ return createHash16("sha256").update(JSON.stringify({
14407
14978
  tool: plan.state.tool,
14408
14979
  source: plan.source,
14409
14980
  destination: plan.state.home,
@@ -14435,14 +15006,14 @@ async function applyNativeStateImportUnlocked(plan) {
14435
15006
  throw refused();
14436
15007
  const requiredDirectories = new Set([plan.state.home]);
14437
15008
  for (const path of plan.directories) {
14438
- for (let directory = join22(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname9(directory)) {
15009
+ for (let directory = join23(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname9(directory)) {
14439
15010
  requiredDirectories.add(directory);
14440
15011
  if (directory === plan.state.home)
14441
15012
  break;
14442
15013
  }
14443
15014
  }
14444
15015
  for (const file of plan.files.filter((file2) => !file2.existing)) {
14445
- for (let directory = dirname9(join22(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname9(directory)) {
15016
+ for (let directory = dirname9(join23(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname9(directory)) {
14446
15017
  requiredDirectories.add(directory);
14447
15018
  if (directory === plan.state.home)
14448
15019
  break;
@@ -14463,15 +15034,15 @@ async function applyNativeStateImportUnlocked(plan) {
14463
15034
  for (const file of plan.files) {
14464
15035
  if (file.existing)
14465
15036
  continue;
14466
- const target = join22(plan.state.home, file.path), temporary = join22(dirname9(target), `.switcher-import-${crypto.randomUUID()}`);
15037
+ const target = join23(plan.state.home, file.path), temporary = join23(dirname9(target), `.switcher-import-${crypto.randomUUID()}`);
14467
15038
  staged.push({ temporary, target });
14468
- const copied = await fingerprint2(join22(plan.source, file.path), temporary);
15039
+ const copied = await fingerprint2(join23(plan.source, file.path), temporary);
14469
15040
  if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
14470
15041
  throw refused();
14471
15042
  }
14472
15043
  for (const item2 of staged) {
14473
15044
  try {
14474
- await link2(item2.temporary, item2.target);
15045
+ await link3(item2.temporary, item2.target);
14475
15046
  published++;
14476
15047
  } catch (error) {
14477
15048
  if (published)
@@ -14971,9 +15542,9 @@ async function main(args = process.argv.slice(2)) {
14971
15542
  if (sharedNativeState)
14972
15543
  await resolveNativeState(plan.profile.harness, process.env, { create: false });
14973
15544
  if (shareNativeState === false) {
14974
- const tool = plan.profile.harness, root = resolve14(values2["state-dir"] ?? join23(switcherHome(), "state"));
15545
+ const tool = plan.profile.harness, root = resolve15(values2["state-dir"] ?? join24(switcherHome(), "state"));
14975
15546
  const configured = process.env[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
14976
- const home = desktop ? join23(root, "desktop", profileId, "codex") : claudeApp ? join23(root, "desktop-claude", profileId) : configured ? resolve14(configured) : join23(root, `native-${tool}`, profileId);
15547
+ const home = desktop ? join24(root, "desktop", profileId, "codex") : claudeApp ? join24(root, "desktop-claude", profileId) : configured ? resolve15(configured) : join24(root, `native-${tool}`, profileId);
14977
15548
  await assertNativeStateIsolation(tool, home);
14978
15549
  }
14979
15550
  if (backend === "ori") {