@hasna/switcher 0.2.12 → 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.12";
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 join24, 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;
@@ -2570,7 +2570,7 @@ var openapi_default = {
2570
2570
  openapi: "3.0.3",
2571
2571
  info: {
2572
2572
  title: "Switcher API",
2573
- version: "0.2.12",
2573
+ version: "0.2.13",
2574
2574
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2575
2575
  },
2576
2576
  security: [
@@ -11353,8 +11353,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
11353
11353
  }
11354
11354
 
11355
11355
  // src/launcher.ts
11356
- import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile18 } from "fs/promises";
11357
- import { join as join22, resolve as resolve12 } from "path";
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";
11358
11358
 
11359
11359
  // src/provider-credential-onboarding.ts
11360
11360
  import { z as z9 } from "zod";
@@ -12647,28 +12647,66 @@ function oriLaunchWarnings(target) {
12647
12647
  }
12648
12648
 
12649
12649
  // src/chatgpt-launch.ts
12650
- import { createHash as createHash12 } from "crypto";
12650
+ import { createHash as createHash13 } from "crypto";
12651
12651
  import { writeFile as writeFile14, rm as rm4 } from "fs/promises";
12652
12652
  import { join as join18 } from "path";
12653
12653
  import { fileURLToPath } from "url";
12654
12654
 
12655
12655
  // src/desktop-state.ts
12656
12656
  import { constants as constants7, closeSync as closeSync2, fstatSync, lstatSync, openSync as openSync2, readSync as readSync2 } from "fs";
12657
- import { open as open4, rm as rm3, lstat as lstat7, rename as rename2, chmod as chmod2 } from "fs/promises";
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";
12658
12661
  var desktopReadLimit = 1024 * 1024;
12659
12662
  function admitDesktopFile(info) {
12660
- if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1 || info.uid !== process.getuid?.() || (info.mode & 18) !== 0 || info.size > desktopReadLimit)
12661
- throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user.");
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();
12662
12700
  }
12663
12701
  function admitOpenedDesktopFile(info, opened) {
12664
- if (opened.dev !== info.dev || opened.ino !== info.ino || opened.nlink !== 1 || opened.size > desktopReadLimit || opened.mode !== info.mode || opened.uid !== info.uid)
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)
12665
12703
  throw new Fault(409, "desktop_state_changed", "Desktop settings changed while being read.");
12666
12704
  }
12667
- function desktopSnapshot(bytes, length, opened, after) {
12668
- if (length > desktopReadLimit || length !== opened.size || after.size !== opened.size || after.mtimeMs !== opened.mtimeMs || after.ctimeMs !== opened.ctimeMs || after.mode !== opened.mode)
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)
12669
12707
  throw new Fault(409, "desktop_state_changed", "Desktop settings changed while being read.");
12670
12708
  try {
12671
- return { text: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, length)), mode: after.mode & 4095 };
12709
+ return { text: new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, length)), mode: after.mode & 4095, metadataHash };
12672
12710
  } catch {
12673
12711
  throw new Fault(422, "desktop_state_encoding", "Desktop settings must be valid UTF-8; original bytes were left unchanged.");
12674
12712
  }
@@ -12677,6 +12715,7 @@ async function safeDesktopSnapshot(path) {
12677
12715
  try {
12678
12716
  const info = await lstat7(path);
12679
12717
  admitDesktopFile(info);
12718
+ const metadataHash = admitDesktopMetadata(path, info);
12680
12719
  const file = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12681
12720
  try {
12682
12721
  const opened = await file.stat();
@@ -12689,7 +12728,9 @@ async function safeDesktopSnapshot(path) {
12689
12728
  break;
12690
12729
  length += read.bytesRead;
12691
12730
  }
12692
- return desktopSnapshot(bytes, length, opened, await file.stat());
12731
+ const snapshot2 = desktopSnapshot(bytes, length, opened, await file.stat(), metadataHash);
12732
+ admitOpenedDesktopFile(opened, lstatSync(path));
12733
+ return snapshot2;
12693
12734
  } finally {
12694
12735
  await file.close();
12695
12736
  }
@@ -12703,6 +12744,7 @@ function safeDesktopSnapshotSync(path) {
12703
12744
  try {
12704
12745
  const info = lstatSync(path);
12705
12746
  admitDesktopFile(info);
12747
+ const metadataHash = admitDesktopMetadata(path, info);
12706
12748
  const file = openSync2(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12707
12749
  try {
12708
12750
  const opened = fstatSync(file);
@@ -12715,7 +12757,7 @@ function safeDesktopSnapshotSync(path) {
12715
12757
  break;
12716
12758
  length += count;
12717
12759
  }
12718
- const snapshot2 = desktopSnapshot(bytes, length, opened, fstatSync(file));
12760
+ const snapshot2 = desktopSnapshot(bytes, length, opened, fstatSync(file), metadataHash);
12719
12761
  admitOpenedDesktopFile(opened, lstatSync(path));
12720
12762
  return snapshot2;
12721
12763
  } finally {
@@ -12730,24 +12772,204 @@ function safeDesktopSnapshotSync(path) {
12730
12772
  async function safeDesktopRead(path) {
12731
12773
  return (await safeDesktopSnapshot(path))?.text;
12732
12774
  }
12733
- async function writeDesktopPrivate(path, text, mode = 384) {
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) {
12792
+ try {
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}.`);
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
+ }
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) {
12734
12941
  if (!Number.isInteger(mode) || mode < 0 || mode > 4095 || (mode & 18) !== 0)
12735
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.");
12736
12950
  const temporary = path + "." + crypto.randomUUID() + ".tmp";
12737
12951
  try {
12738
- const file = await open4(temporary, "wx", 384);
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);
12739
12957
  try {
12958
+ await file.truncate(0);
12740
12959
  await file.writeFile(text);
12741
12960
  await file.chmod(mode);
12742
12961
  } finally {
12743
12962
  await file.close();
12744
12963
  }
12745
12964
  const written = await safeDesktopSnapshot(temporary);
12746
- if (written?.text !== text || written.mode !== mode)
12965
+ if (written?.text !== text || written.mode !== mode || template && written.metadataHash !== template.metadataHash)
12747
12966
  throw new Fault(409, "desktop_state_changed", "Desktop settings restoration readback failed.");
12748
- await rename2(temporary, path);
12967
+ await replaceDesktopFile(path, temporary, expectedCurrent, written);
12749
12968
  } finally {
12750
- await rm3(temporary, { force: true });
12969
+ if (await safeDesktopSnapshot(temporary).catch(() => {
12970
+ return;
12971
+ }) !== undefined)
12972
+ await rm3(temporary, { force: true });
12751
12973
  }
12752
12974
  }
12753
12975
  async function desktopLease(path) {
@@ -12795,7 +13017,7 @@ async function openDesktopLease(path, readOnly2 = false) {
12795
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";
12796
13018
  import { constants as constants8, lstatSync as lstatSync2, realpathSync } from "fs";
12797
13019
  import { homedir as homedir9 } from "os";
12798
- 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";
12799
13021
  function nativeStateRequested(tool, environment = process.env, explicit) {
12800
13022
  if (explicit !== undefined)
12801
13023
  return explicit;
@@ -12844,7 +13066,7 @@ async function info(path) {
12844
13066
  function absolute(value) {
12845
13067
  if (!isAbsolute16(value) || value.includes("\x00"))
12846
13068
  throw new Fault(422, "native_state_path", "The shared native state directory must be an absolute path.");
12847
- return resolve9(value);
13069
+ return resolve10(value);
12848
13070
  }
12849
13071
  function credentialOverlay(path) {
12850
13072
  return /(?:^|\/)subscriptions\/profiles\//.test(path) || /(?:^|\/)switcher\/state\/(?:desktop|desktop-claude|launch-[^/]+)\//.test(path);
@@ -12992,7 +13214,7 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
12992
13214
  if (!valid)
12993
13215
  throw new Fault(422, "native_state_instructions", "Codex instruction configuration has an unsupported value.");
12994
13216
  if (CODEX_INSTRUCTION_FILE_KEYS.has(key)) {
12995
- const path = resolve9(home, value), entry = await info(path);
13217
+ const path = resolve10(home, value), entry = await info(path);
12996
13218
  const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute16(relativePath);
12997
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)
12998
13220
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
@@ -13157,7 +13379,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13157
13379
  throw new Fault(422, "native_state_entry", "A shared native state entry has an unsupported type, owner or permissions.");
13158
13380
  if (source?.isDirectory())
13159
13381
  await assertShareableTree(target);
13160
- if (existing && (!existing.isSymbolicLink() || resolve9(dirname8(destination), await readlink(destination)) !== target))
13382
+ if (existing && (!existing.isSymbolicLink() || resolve10(dirname8(destination), await readlink(destination)) !== target))
13161
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.");
13162
13384
  }
13163
13385
  const createdLinks = [];
@@ -13193,7 +13415,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13193
13415
  } catch (error) {
13194
13416
  for (const item2 of createdLinks.reverse()) {
13195
13417
  try {
13196
- 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)
13197
13419
  await unlink2(item2.destination);
13198
13420
  } catch {}
13199
13421
  }
@@ -13249,7 +13471,7 @@ function clearSwitcherModelState(config) {
13249
13471
  delete config.memories;
13250
13472
  }
13251
13473
  }
13252
- var digest = (value) => createHash12("sha256").update(value).digest("hex");
13474
+ var digest = (value) => createHash13("sha256").update(value).digest("hex");
13253
13475
  var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
13254
13476
  async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedState) {
13255
13477
  if (sharedState && sharedState.tool !== "codex")
@@ -13366,15 +13588,17 @@ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join("
13366
13588
  import { writeFile as writeFile17 } from "fs/promises";
13367
13589
  import { join as join21 } from "path";
13368
13590
  // src/desktop-selection.ts
13369
- import { createHash as createHash13, randomUUID as randomUUID6 } from "crypto";
13370
- import { rm as rm5, writeFile as writeFile15 } from "fs/promises";
13591
+ import { createHash as createHash14, randomUUID as randomUUID6 } from "crypto";
13592
+ import { writeFile as writeFile15, rename as rename3 } from "fs/promises";
13371
13593
  import { join as join19 } from "path";
13372
- var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
13594
+ var hash2 = (text) => createHash14("sha256").update(text).digest("hex");
13373
13595
  var conflict = () => new Fault(409, "desktop_config_changed", "Desktop configuration changed; existing bytes and the recovery receipt were preserved.");
13374
13596
  var invalid3 = () => new Fault(409, "desktop_recovery", "Desktop selection needs recovery by its owning supported version before another launch.");
13375
13597
  var identifier = (value) => typeof value === "string" && /^[A-Za-z0-9_-]{1,80}$/.test(value);
13376
13598
  var admittedMode = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 4095 && (value & 18) === 0;
13377
- var matches = (actual, text, mode) => (actual?.text ?? null) === text && (actual?.mode ?? null) === mode;
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`);
13378
13602
  function metadata(text) {
13379
13603
  if (text === null)
13380
13604
  return { entries: [] };
@@ -13391,31 +13615,94 @@ function metadata(text) {
13391
13615
  throw invalid3();
13392
13616
  return m;
13393
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
+ }
13394
13627
  function receipt(text) {
13395
- let r;
13628
+ let value;
13396
13629
  try {
13397
- r = JSON.parse(text);
13630
+ value = JSON.parse(text);
13398
13631
  } catch {
13399
13632
  throw invalid3();
13400
13633
  }
13401
- if (r?.version !== 3 || !identifier(r.id) || !/^[0-9a-f-]{36}$/.test(r.id) || !/^[a-f0-9]{64}$/.test(r.configHash) || r.previousMeta !== null && typeof r.previousMeta !== "string" || typeof r.appliedMeta !== "string" || (r.previousMeta === null ? r.previousMetaMode !== null : !admittedMode(r.previousMetaMode)) || r.previousSelected !== null && (!r.previousSelected || !identifier(r.previousSelected.id) || r.previousSelected.text !== null && typeof r.previousSelected.text !== "string"))
13402
- throw invalid3();
13403
- const before = metadata(r.previousMeta), after = metadata(r.appliedMeta);
13404
- if (after.appliedId !== r.id || before.appliedId === r.id || (before.appliedId ?? null) !== (r.previousSelected?.id ?? null))
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")
13405
13638
  throw invalid3();
13406
- return r;
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
+ };
13407
13655
  }
13408
13656
  async function selectedUnchanged(library, r) {
13409
- if (r.previousSelected && (await safeDesktopRead(join19(library, r.previousSelected.id + ".json")) ?? null) !== r.previousSelected.text)
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))
13410
13665
  throw conflict();
13411
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
+ }
13412
13689
  async function recoverDesktopSelection(library) {
13413
13690
  const path = join19(library, ".switcher-selection.json"), raw = await safeDesktopRead(path);
13414
13691
  if (raw === undefined)
13415
13692
  return;
13416
- const r = receipt(raw), metaPath = join19(library, "_meta.json"), configPath = join19(library, r.id + ".json");
13417
- const currentMeta = await safeDesktopSnapshot(metaPath), currentConfig = await safeDesktopRead(configPath);
13418
- const wasOriginal = matches(currentMeta, r.previousMeta, r.previousMetaMode), wasApplied = matches(currentMeta, r.appliedMeta, 384);
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);
13419
13706
  await selectedUnchanged(library, r);
13420
13707
  if (!wasOriginal && !wasApplied)
13421
13708
  throw conflict();
@@ -13423,35 +13710,101 @@ async function recoverDesktopSelection(library) {
13423
13710
  throw conflict();
13424
13711
  if (await safeDesktopRead(path) !== raw)
13425
13712
  throw conflict();
13426
- if (!matches(await safeDesktopSnapshot(metaPath), currentMeta?.text ?? null, currentMeta?.mode ?? null))
13713
+ if (!matches(await safeDesktopSnapshot(metaPath), currentMeta?.text ?? null, currentMeta?.mode ?? null, currentMeta?.metadataHash ?? null))
13427
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
+ };
13428
13724
  if (wasApplied) {
13429
- if (r.previousMeta === null)
13430
- await rm5(metaPath);
13431
- else
13432
- await writeDesktopPrivate(metaPath, r.previousMeta, r.previousMetaMode);
13433
- if (!matches(await safeDesktopSnapshot(metaPath), r.previousMeta, r.previousMetaMode))
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))
13434
13735
  throw conflict();
13736
+ await removeDesktopFile(preparedPath(library, r.id), prepared, assertRestored);
13435
13737
  }
13738
+ if (backup && !matches(safeDesktopSnapshotSync(originalPath(library, r.id)), r.previousMeta, r.previousMetaMode, r.previousMetadataHash))
13739
+ throw conflict();
13436
13740
  if (currentConfig !== undefined) {
13437
- if (hash2(await safeDesktopRead(configPath) ?? "") !== r.configHash)
13741
+ const configSnapshot = await safeDesktopSnapshot(configPath);
13742
+ if (!configSnapshot || hash2(configSnapshot.text) !== r.configHash)
13438
13743
  throw conflict();
13439
- await rm5(configPath);
13744
+ await removeDesktopFile(configPath, configSnapshot, assertRestored);
13440
13745
  }
13441
- if (await safeDesktopRead(path) !== raw)
13746
+ await assertRestored();
13747
+ const receiptSnapshot = await safeDesktopSnapshot(path);
13748
+ if (!receiptSnapshot || receiptSnapshot.text !== raw)
13442
13749
  throw conflict();
13443
- await rm5(path);
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);
13444
13785
  }
13445
13786
  async function applyDesktopSelection(library, config, label2, checkpoint) {
13446
13787
  await recoverDesktopSelection(library);
13447
13788
  const path = join19(library, ".switcher-selection.json"), metaPath = join19(library, "_meta.json");
13448
13789
  const original = await safeDesktopSnapshot(metaPath), previousMeta = original?.text ?? null, previousMetaMode = original?.mode ?? null, previous = metadata(previousMeta);
13449
- const previousSelected = previous.appliedId ? { id: previous.appliedId, text: await safeDesktopRead(join19(library, previous.appliedId + ".json")) ?? null } : null;
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;
13450
13792
  const id2 = randomUUID6(), configPath = join19(library, id2 + ".json"), text = JSON.stringify(config, null, 2) + `
13451
13793
  `;
13452
13794
  const appliedMeta = JSON.stringify({ ...previous, appliedId: id2, entries: [...previous.entries, { id: id2, name: label2 }] }, null, 2) + `
13453
13795
  `;
13454
- const r = { version: 3, id: id2, configHash: hash2(text), previousMeta, previousMetaMode, appliedMeta, previousSelected };
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;
13455
13808
  const journal = JSON.stringify(r) + `
13456
13809
  `;
13457
13810
  if (Buffer.byteLength(journal) > 1024 * 1024)
@@ -13465,7 +13818,7 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
13465
13818
  try {
13466
13819
  await unchanged();
13467
13820
  await checkpoint?.("preserved");
13468
- if (!matches(await safeDesktopSnapshot(metaPath), previousMeta, previousMetaMode))
13821
+ if (!matches(await safeDesktopSnapshot(metaPath), previousMeta, previousMetaMode, previousMetadataHash))
13469
13822
  throw conflict();
13470
13823
  await selectedUnchanged(library, r);
13471
13824
  await writeFile15(configPath, text, { mode: 384, flag: "wx" });
@@ -13473,10 +13826,14 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
13473
13826
  throw conflict();
13474
13827
  await checkpoint?.("config");
13475
13828
  await unchanged();
13476
- if (!matches(await safeDesktopSnapshot(metaPath), previousMeta, previousMetaMode))
13829
+ const preparedCurrent = await safeDesktopSnapshot(preparedPath(library, id2));
13830
+ if (!preparedCurrent || !matches(preparedCurrent, appliedMeta, 384, r.appliedMetadataHash))
13477
13831
  throw conflict();
13478
- await writeDesktopPrivate(metaPath, appliedMeta);
13479
- if (!matches(await safeDesktopSnapshot(metaPath), appliedMeta, 384))
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))
13480
13837
  throw conflict();
13481
13838
  await checkpoint?.("selected");
13482
13839
  } catch (error) {
@@ -13489,9 +13846,11 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
13489
13846
  const assertCurrentSync = () => {
13490
13847
  if (safeDesktopSnapshotSync(path)?.text !== journal)
13491
13848
  throw conflict();
13492
- if (previousSelected && (safeDesktopSnapshotSync(join19(library, previousSelected.id + ".json"))?.text ?? null) !== previousSelected.text)
13849
+ if (original && !matches(safeDesktopSnapshotSync(originalPath(library, id2)), previousMeta, previousMetaMode, previousMetadataHash))
13850
+ throw conflict();
13851
+ if (!selectedUnchangedSync(library, previousSelected))
13493
13852
  throw conflict();
13494
- if (!matches(safeDesktopSnapshotSync(metaPath), appliedMeta, 384) || safeDesktopSnapshotSync(configPath)?.text !== text)
13853
+ if (!matches(safeDesktopSnapshotSync(metaPath), appliedMeta, 384, r.appliedMetadataHash) || safeDesktopSnapshotSync(configPath)?.text !== text)
13495
13854
  throw conflict();
13496
13855
  };
13497
13856
  return {
@@ -13512,7 +13871,7 @@ async function applyDesktopSelection(library, config, label2, checkpoint) {
13512
13871
  import { constants as constants9 } from "fs";
13513
13872
  import { lstat as lstat9, open as open6, writeFile as writeFile16 } from "fs/promises";
13514
13873
  import { homedir as homedir10 } from "os";
13515
- import { join as join20, resolve as resolve10 } from "path";
13874
+ import { join as join20, resolve as resolve11 } from "path";
13516
13875
  var preferences = new Set([
13517
13876
  "$schema",
13518
13877
  "permissions",
@@ -13584,13 +13943,13 @@ function project(settings2, existing) {
13584
13943
  return result;
13585
13944
  }
13586
13945
  async function prepareClaudeUserSettings(overlayHome, environment = process.env) {
13587
- overlayHome = resolve10(overlayHome);
13946
+ overlayHome = resolve11(overlayHome);
13588
13947
  const existing = await readSettings(overlayHome);
13589
13948
  if (existing !== undefined) {
13590
13949
  project(existing, true);
13591
13950
  return;
13592
13951
  }
13593
- const sourceHome = resolve10(environment.CLAUDE_CONFIG_DIR ?? join20(environment.HOME ?? homedir10(), ".claude"));
13952
+ const sourceHome = resolve11(environment.CLAUDE_CONFIG_DIR ?? join20(environment.HOME ?? homedir10(), ".claude"));
13594
13953
  if (sourceHome === overlayHome)
13595
13954
  return;
13596
13955
  const source = await readSettings(sourceHome);
@@ -13697,7 +14056,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13697
14056
  // src/codex-session-discovery.ts
13698
14057
  import { spawn as spawn3 } from "child_process";
13699
14058
  import { createInterface as createInterface2 } from "readline/promises";
13700
- import { basename as basename3, resolve as resolve11 } from "path";
14059
+ import { basename as basename3, resolve as resolve12 } from "path";
13701
14060
  var object6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
13702
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.");
13703
14062
  async function listCodexSessions(prepared, cwd, query) {
@@ -13712,11 +14071,11 @@ async function listCodexSessions(prepared, cwd, query) {
13712
14071
  let done = false, initialized = false, pending = Buffer.alloc(0), responseBytes = 0;
13713
14072
  let killTimer;
13714
14073
  let resolvePage, rejectPage;
13715
- const result = new Promise((resolve12, reject2) => {
13716
- resolvePage = resolve12;
14074
+ const result = new Promise((resolve13, reject2) => {
14075
+ resolvePage = resolve13;
13717
14076
  rejectPage = reject2;
13718
14077
  });
13719
- const closed = new Promise((resolve12) => child.once("close", () => resolve12()));
14078
+ const closed = new Promise((resolve13) => child.once("close", () => resolve13()));
13720
14079
  const stop = () => {
13721
14080
  child.stdin.destroy();
13722
14081
  child.kill("SIGTERM");
@@ -13815,16 +14174,16 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
13815
14174
  break;
13816
14175
  }
13817
14176
  if (nativeArgs[i].startsWith("--cd="))
13818
- effectiveCwd = resolve11(cwd, nativeArgs[i].slice(5));
14177
+ effectiveCwd = resolve12(cwd, nativeArgs[i].slice(5));
13819
14178
  else if (nativeArgs[i].startsWith("-C") && nativeArgs[i].length > 2)
13820
- effectiveCwd = resolve11(cwd, nativeArgs[i].slice(2));
14179
+ effectiveCwd = resolve12(cwd, nativeArgs[i].slice(2));
13821
14180
  if (codexOptionRequestsHelp(nativeArgs[i]))
13822
14181
  return nativeArgs;
13823
14182
  if (codexOptionTakesValue(nativeArgs[i])) {
13824
14183
  if (nativeArgs[i] === "--cd" || nativeArgs[i] === "-C") {
13825
14184
  if (!nativeArgs[i + 1])
13826
14185
  throw unavailable2();
13827
- effectiveCwd = resolve11(cwd, nativeArgs[i + 1]);
14186
+ effectiveCwd = resolve12(cwd, nativeArgs[i + 1]);
13828
14187
  }
13829
14188
  i++;
13830
14189
  continue;
@@ -13939,7 +14298,7 @@ async function oriRequestForPlan(plan, options = {}) {
13939
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.");
13940
14299
  if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
13941
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.");
13942
- 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 });
13943
14302
  const native = requireOriHarness(contract, target);
13944
14303
  if (!native.path)
13945
14304
  throw new Error("Ori did not report the native harness executable path.");
@@ -13987,7 +14346,7 @@ async function prepareOriForPlan(plan, options) {
13987
14346
  executable: detection.executable,
13988
14347
  version: detection.version,
13989
14348
  stateDir: options.stateDir,
13990
- cwd: resolve12(options.cwd ?? process.cwd()),
14349
+ cwd: resolve13(options.cwd ?? process.cwd()),
13991
14350
  args: options.args ?? [],
13992
14351
  sharedState: options.sharedState
13993
14352
  });
@@ -14019,7 +14378,7 @@ async function launch(client, profileId, options = {}) {
14019
14378
  assertHarnessArguments(profile.harness, options.args ?? []);
14020
14379
  if (profile.harness === "gemini" || profile.harness === "antigravity")
14021
14380
  validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
14022
- await validateHarnessConfiguration(profile.harness, resolve12(options.cwd ?? process.cwd()), options.args);
14381
+ await validateHarnessConfiguration(profile.harness, resolve13(options.cwd ?? process.cwd()), options.args);
14023
14382
  if (profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((process.env.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
14024
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.");
14025
14384
  if (profile.harness === "grok" && process.env.GROK_FORCE_LOGIN_TEAM_ID?.trim())
@@ -14028,7 +14387,7 @@ async function launch(client, profileId, options = {}) {
14028
14387
  await client.refreshModels(profile.providerId);
14029
14388
  const plan = await client.launchPlan(profileId);
14030
14389
  assertHarnessArguments(plan.profile.harness, options.args ?? []);
14031
- 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);
14032
14391
  if (options.credentialPreflight && providerCredentialFingerprint(plan.provider) !== options.credentialPreflight)
14033
14392
  throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
14034
14393
  const backend = options.backend ?? "direct";
@@ -14050,7 +14409,7 @@ async function launch(client, profileId, options = {}) {
14050
14409
  validateHarnessVersion("gemini", detection?.version);
14051
14410
  if (backend === "direct" && plan.profile.harness === "aider")
14052
14411
  validateHarnessVersion(plan.profile.harness, detection?.version);
14053
- const root = resolve12(options.stateDir ?? join22(switcherHome(), "state"));
14412
+ const root = resolve13(options.stateDir ?? join22(switcherHome(), "state"));
14054
14413
  await privateDirectory(root);
14055
14414
  const stateDir = await mkdtemp(join22(root, "launch-"));
14056
14415
  let credential;
@@ -14060,7 +14419,7 @@ async function launch(client, profileId, options = {}) {
14060
14419
  if (plan.provider.credentialEnv && !credential)
14061
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.`);
14062
14421
  } catch (error) {
14063
- await rm6(stateDir, { recursive: true, force: true });
14422
+ await rm5(stateDir, { recursive: true, force: true });
14064
14423
  throw error;
14065
14424
  }
14066
14425
  }
@@ -14111,7 +14470,7 @@ async function launch(client, profileId, options = {}) {
14111
14470
  let nativeHome2;
14112
14471
  if (sharedState && !options.desktop && !options.claudeDesktop) {
14113
14472
  const variable = sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
14114
- const configured = process.env[variable] ? resolve12(process.env[variable]) : undefined;
14473
+ const configured = process.env[variable] ? resolve13(process.env[variable]) : undefined;
14115
14474
  nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join22(root, "native-claude", profileId) : configured ?? sharedState.home;
14116
14475
  if (sharedState.tool === "claude")
14117
14476
  await prepareClaudeUserSettings(nativeHome2);
@@ -14127,7 +14486,7 @@ async function launch(client, profileId, options = {}) {
14127
14486
  await assertNativeStateIsolation(tool, join22(root, "desktop-claude", desktopState));
14128
14487
  else {
14129
14488
  const variable = tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
14130
- nativeHome2 = process.env[variable] ? resolve12(process.env[variable]) : join22(root, `native-${tool}`, profileId);
14489
+ nativeHome2 = process.env[variable] ? resolve13(process.env[variable]) : join22(root, `native-${tool}`, profileId);
14131
14490
  await assertNativeStateIsolation(tool, nativeHome2);
14132
14491
  await privateDirectory(nativeHome2);
14133
14492
  }
@@ -14144,7 +14503,7 @@ async function launch(client, profileId, options = {}) {
14144
14503
  onRoutingEvent,
14145
14504
  credential,
14146
14505
  stateDir,
14147
- cwd: resolve12(options.cwd ?? process.cwd()),
14506
+ cwd: resolve13(options.cwd ?? process.cwd()),
14148
14507
  sharedState
14149
14508
  };
14150
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({
@@ -14163,7 +14522,7 @@ async function launch(client, profileId, options = {}) {
14163
14522
  executable: nativeExecutable ?? detection?.executable,
14164
14523
  args: options.args ?? [],
14165
14524
  stateDir,
14166
- cwd: resolve12(options.cwd ?? process.cwd()),
14525
+ cwd: resolve13(options.cwd ?? process.cwd()),
14167
14526
  version: detection?.version,
14168
14527
  sharedState,
14169
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) } : {}
@@ -14260,7 +14619,7 @@ async function launch(client, profileId, options = {}) {
14260
14619
  interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
14261
14620
  throw preparationSignal;
14262
14621
  }
14263
- const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve12(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
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 });
14264
14623
  await cleanup?.();
14265
14624
  cleanup = undefined;
14266
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}.`);
@@ -14277,8 +14636,8 @@ async function launch(client, profileId, options = {}) {
14277
14636
  } finally {
14278
14637
  if (lateCreateRunFinalization) {
14279
14638
  let finalizationTimer;
14280
- const finalizationTimeout = new Promise((resolve13) => {
14281
- finalizationTimer = setTimeout(resolve13, LATE_RUN_FINALIZATION_TIMEOUT_MS);
14639
+ const finalizationTimeout = new Promise((resolve14) => {
14640
+ finalizationTimer = setTimeout(resolve14, LATE_RUN_FINALIZATION_TIMEOUT_MS);
14282
14641
  });
14283
14642
  try {
14284
14643
  await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
@@ -14291,13 +14650,13 @@ async function launch(client, profileId, options = {}) {
14291
14650
  try {
14292
14651
  await cleanup?.();
14293
14652
  } finally {
14294
- await rm6(stateDir, { recursive: true, force: true });
14653
+ await rm5(stateDir, { recursive: true, force: true });
14295
14654
  }
14296
14655
  }
14297
14656
  }
14298
14657
 
14299
14658
  // src/direct-launch.ts
14300
- import { createHash as createHash14 } from "crypto";
14659
+ import { createHash as createHash15 } from "crypto";
14301
14660
  import { createInterface as createInterface3 } from "readline/promises";
14302
14661
  var absent2 = (error) => error instanceof SwitcherError && error.status === 404;
14303
14662
  async function resolveLaunchProvider(client, selector, options = {}) {
@@ -14378,7 +14737,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
14378
14737
  const policy = modelPolicy ?? (harness === "codex" ? { version: 1, selection: "catalog" } : undefined);
14379
14738
  const normalizedPolicy = policy === undefined ? undefined : parse2(modelPolicySchema, policy);
14380
14739
  const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
14381
- 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);
14382
14741
  const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
14383
14742
  let existing;
14384
14743
  try {
@@ -14402,10 +14761,10 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
14402
14761
  }
14403
14762
 
14404
14763
  // src/native-state-import.ts
14405
- import { createHash as createHash15 } from "crypto";
14764
+ import { createHash as createHash16 } from "crypto";
14406
14765
  import { constants as constants10 } from "fs";
14407
- import { lstat as lstat10, open as open7, opendir as opendir2, link as link2, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
14408
- import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join23, relative as relative6, resolve as resolve13 } from "path";
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";
14409
14768
  var MAX_FILES = 1e5;
14410
14769
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
14411
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.");
@@ -14523,7 +14882,7 @@ async function fingerprint2(path, copyTo) {
14523
14882
  throw refused();
14524
14883
  if (copyTo)
14525
14884
  output = await open7(copyTo, "wx", 384);
14526
- const hash3 = createHash15("sha256"), buffer = Buffer.alloc(64 * 1024);
14885
+ const hash3 = createHash16("sha256"), buffer = Buffer.alloc(64 * 1024);
14527
14886
  let bytes = 0;
14528
14887
  for (;; ) {
14529
14888
  const read = await handle.read(buffer, 0, buffer.length, null);
@@ -14558,7 +14917,7 @@ async function fingerprint2(path, copyTo) {
14558
14917
  async function planNativeStateImport(state, source, selection) {
14559
14918
  if (!isAbsolute17(source) || source.includes("\x00"))
14560
14919
  throw refused();
14561
- source = resolve13(source);
14920
+ source = resolve14(source);
14562
14921
  if (inside3(source, state.home) || inside3(state.home, source))
14563
14922
  throw refused();
14564
14923
  await assertNativeStateDirectory(source);
@@ -14615,7 +14974,7 @@ async function planNativeStateImport(state, source, selection) {
14615
14974
  return plan;
14616
14975
  }
14617
14976
  function nativeStateImportDigest(plan) {
14618
- return createHash15("sha256").update(JSON.stringify({
14977
+ return createHash16("sha256").update(JSON.stringify({
14619
14978
  tool: plan.state.tool,
14620
14979
  source: plan.source,
14621
14980
  destination: plan.state.home,
@@ -14683,7 +15042,7 @@ async function applyNativeStateImportUnlocked(plan) {
14683
15042
  }
14684
15043
  for (const item2 of staged) {
14685
15044
  try {
14686
- await link2(item2.temporary, item2.target);
15045
+ await link3(item2.temporary, item2.target);
14687
15046
  published++;
14688
15047
  } catch (error) {
14689
15048
  if (published)
@@ -15183,9 +15542,9 @@ async function main(args = process.argv.slice(2)) {
15183
15542
  if (sharedNativeState)
15184
15543
  await resolveNativeState(plan.profile.harness, process.env, { create: false });
15185
15544
  if (shareNativeState === false) {
15186
- const tool = plan.profile.harness, root = resolve14(values2["state-dir"] ?? join24(switcherHome(), "state"));
15545
+ const tool = plan.profile.harness, root = resolve15(values2["state-dir"] ?? join24(switcherHome(), "state"));
15187
15546
  const configured = process.env[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
15188
- const home = desktop ? join24(root, "desktop", profileId, "codex") : claudeApp ? join24(root, "desktop-claude", profileId) : configured ? resolve14(configured) : join24(root, `native-${tool}`, profileId);
15547
+ const home = desktop ? join24(root, "desktop", profileId, "codex") : claudeApp ? join24(root, "desktop-claude", profileId) : configured ? resolve15(configured) : join24(root, `native-${tool}`, profileId);
15189
15548
  await assertNativeStateIsolation(tool, home);
15190
15549
  }
15191
15550
  if (backend === "ori") {