@hasna/switcher 0.2.7 → 0.2.8

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
@@ -911,7 +911,66 @@ var short = {
911
911
  "prime-agent": { required: "p", optional: "", boolean: "hv" },
912
912
  gemini: { required: "mpieo", optional: "rw", boolean: "shvydl" }
913
913
  };
914
- var providerKeys = new Set(["model", "model_provider", "model_providers", "model_catalog_json", "review_model", "agents", "memories"]);
914
+ var providerKeys = new Set(["model", "model_provider", "provider", "model_providers", "model_catalog_json", "review_model", "agents", "memories"]);
915
+ function codexOptionTakesValue(option) {
916
+ return values.codex.includes(option) || option.length === 2 && option[0] === "-" && short.codex.required.includes(option[1]);
917
+ }
918
+ function codexOptionRequestsHelp(option) {
919
+ if (["--help", "--version", "-h", "-V"].includes(option))
920
+ return true;
921
+ if (!/^-[^-]/.test(option))
922
+ return false;
923
+ for (let index = 1;index < option.length; index++) {
924
+ const name = option[index];
925
+ if (name === "h" || name === "V")
926
+ return true;
927
+ if (short.codex.required.includes(name))
928
+ return false;
929
+ }
930
+ return false;
931
+ }
932
+ function codexConfigPath(key) {
933
+ if (key.length > 4096 || /[\r\n\0]/.test(key))
934
+ throw new Error("Invalid Codex configuration key.");
935
+ let value = Bun.TOML.parse(`${key} = 0`);
936
+ const path = [];
937
+ while (value !== 0) {
938
+ if (value === null || typeof value !== "object" || Array.isArray(value))
939
+ throw new Error("Invalid Codex configuration key.");
940
+ const entries = Object.entries(value);
941
+ if (entries.length !== 1)
942
+ throw new Error("Ambiguous Codex configuration key.");
943
+ path.push(entries[0][0]);
944
+ value = entries[0][1];
945
+ }
946
+ if (!path.length)
947
+ throw new Error("Invalid Codex configuration key.");
948
+ return path;
949
+ }
950
+ function codexConfigRoots(key) {
951
+ return [codexConfigPath(key)[0]];
952
+ }
953
+ function codexCommandIndex(args) {
954
+ for (let i = 0;i < args.length; i++) {
955
+ const arg = args[i];
956
+ if (arg === "--")
957
+ return -1;
958
+ if (!arg.startsWith("-"))
959
+ return i;
960
+ if (arg.startsWith("--")) {
961
+ if (!arg.includes("=") && values.codex.includes(arg))
962
+ i++;
963
+ continue;
964
+ }
965
+ for (let j = 1;j < arg.length; j++)
966
+ if (short.codex.required.includes(arg[j])) {
967
+ if (j === arg.length - 1)
968
+ i++;
969
+ break;
970
+ }
971
+ }
972
+ return -1;
973
+ }
915
974
  function geminiPolicyArguments(input, originalHome) {
916
975
  const args = [...input], expand = (value) => value.split(",").map((part) => {
917
976
  const path = part.trim();
@@ -944,9 +1003,9 @@ function geminiPolicyArguments(input, originalHome) {
944
1003
  function codexProviderOverride(value) {
945
1004
  const key = value.slice(0, value.indexOf("=") < 0 ? value.length : value.indexOf("=")).trim();
946
1005
  try {
947
- return Object.keys(Bun.TOML.parse(`${key} = 0`)).some((root) => providerKeys.has(root));
1006
+ return codexConfigRoots(key).some((root) => providerKeys.has(root));
948
1007
  } catch {
949
- return /^(model|model_provider|model_providers|model_catalog_json|review_model|agents|memories)(?:\s*\.|\s*$)/.test(key);
1008
+ return /^(model|model_provider|provider|model_providers|model_catalog_json|review_model|agents|memories)(?:\s*\.|\s*$)/.test(key);
950
1009
  }
951
1010
  }
952
1011
  function assertHarnessArguments(harness, args, options = {}) {
@@ -977,7 +1036,16 @@ function assertHarnessArguments(harness, args, options = {}) {
977
1036
  }
978
1037
  }
979
1038
  const config = (value) => {
980
- if (harness === "codex" && (options.reserveCodexConfig || codexProviderOverride(value)))
1039
+ if (harness !== "codex")
1040
+ return;
1041
+ const key = value.slice(0, value.indexOf("=") < 0 ? value.length : value.indexOf("=")).trim();
1042
+ let reserved3 = false;
1043
+ try {
1044
+ reserved3 = codexConfigRoots(key).some((root) => options.reservedCodexRoots?.includes(root));
1045
+ } catch {
1046
+ reserved3 = Boolean(options.reservedCodexRoots?.some((root) => new RegExp(`^${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s*\\.|\\s*$)`).test(key)));
1047
+ }
1048
+ if (options.reserveCodexConfig || codexProviderOverride(value) || reserved3)
981
1049
  reject();
982
1050
  };
983
1051
  let hermesChat = false;
@@ -8491,7 +8559,7 @@ import { execFileSync as execFileSync2 } from "child_process";
8491
8559
  import { createHash as createHash7 } from "crypto";
8492
8560
  var dict = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
8493
8561
  var model = (v) => JSON.stringify(v);
8494
- var codexRoutingKeys = new Set(["model", "model_provider", "model_providers", "model_catalog_json", "base_url", "wire_api", "env_key", "env_http_headers", "http_headers", "auth_command", "include"]);
8562
+ var codexRoutingKeys = new Set(["model", "model_provider", "provider", "model_providers", "model_catalog_json", "base_url", "wire_api", "env_key", "env_http_headers", "http_headers", "auth_command", "include"]);
8495
8563
  var codexTransportKeys = new Set(["mcp_servers", "mcp_server", "transport", "transports", "plugins"]);
8496
8564
  function codexAgentsFromEffectiveConfig(config, trustedProject = true, baseDir) {
8497
8565
  const raw = config.agents;
@@ -8554,7 +8622,7 @@ function scanNested(value, path) {
8554
8622
  if (!dict(value))
8555
8623
  return value;
8556
8624
  for (const [key, item] of Object.entries(value)) {
8557
- if (codexTransportKeys.has(key) || key === "config_file" || key === "include" || key === "model_providers" || key === "base_url" || key === "auth_command" || key === "model_instructions_file")
8625
+ if (codexTransportKeys.has(key) || key === "config_file" || key === "include" || key === "model" || key === "model_provider" || key === "provider" || key === "model_providers" || key === "base_url" || key === "wire_api" || key === "env_key" || key === "env_http_headers" || key === "http_headers" || key === "auth_command" || key === "model_instructions_file")
8558
8626
  reject(`${path}.${key}`);
8559
8627
  if (key === "agents" && dict(item)) {
8560
8628
  for (const [name, role] of Object.entries(item))
@@ -10850,7 +10918,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
10850
10918
  return { executable, args: ["--settings", file2, "--model", input.model, ...args], env, configPaths, warnings };
10851
10919
  }
10852
10920
  if (input.harness === "codex") {
10853
- const rolePolicy2 = await prepareCodexModelPolicy({ cwd: input.cwd, stateDir: input.stateDir, model: input.model, policy: input.modelPolicy ? { version: 1, ...input.modelPolicy } : undefined, switcherProvider: "switcher", switcherBaseUrl: input.baseUrl });
10921
+ const rolePolicy2 = await prepareCodexModelPolicy({ home: input.sharedState?.home, cwd: input.cwd, stateDir: input.stateDir, model: input.model, policy: input.modelPolicy ? { version: 1, ...input.modelPolicy } : undefined, switcherProvider: "switcher", switcherBaseUrl: input.baseUrl });
10854
10922
  const selectableModels = input.models.filter((model3) => input.compiledPolicy?.allowedModels.includes(model3.id) ?? true);
10855
10923
  const file2 = await jsonFile(input.stateDir, "codex-models.json", { models: selectableModels.map((model3, index) => codexModel(model3, index, providerBaseUrl, model3.id === input.model ? input.reasoning : undefined)) });
10856
10924
  configPaths.push(file2);
@@ -10871,6 +10939,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
10871
10939
  overrides.push("-c", `agents.${name}.config_file=${quote(path)}`);
10872
10940
  }
10873
10941
  overrides.push("-c", `memories.extract_model=${quote(input.model)}`, "-c", `memories.consolidation_model=${quote(input.model)}`);
10942
+ if (input.sharedState?.sqliteHome)
10943
+ overrides.push("-c", `sqlite_home=${quote(input.sharedState.sqliteHome)}`);
10874
10944
  if (input.reasoning)
10875
10945
  overrides.push("-c", `model_reasoning_effort=${quote(input.reasoning)}`);
10876
10946
  if (input.dangerouslyBypassApprovalsAndSandbox)
@@ -11119,7 +11189,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11119
11189
  return { executable, args: native, env, configPaths, warnings };
11120
11190
  }
11121
11191
  async function prepareTransportLaunch(input) {
11122
- assertHarnessArguments(input.harness, input.args ?? []);
11192
+ assertHarnessArguments(input.harness, input.args ?? [], input.sharedState?.tool === "codex" ? { reservedCodexRoots: ["sqlite_home"] } : {});
11123
11193
  if (input.harness === "kilo") {
11124
11194
  await validateKiloConfiguration(input.cwd, [...input.args ?? []]);
11125
11195
  if (input.protocol === "gemini-generate-content")
@@ -11184,7 +11254,7 @@ async function prepareTransportLaunch(input) {
11184
11254
  }
11185
11255
  }
11186
11256
  async function prepareHarnessLaunch(input) {
11187
- assertHarnessArguments(input.harness, input.args ?? []);
11257
+ assertHarnessArguments(input.harness, input.args ?? [], input.sharedState?.tool === "codex" ? { reservedCodexRoots: ["sqlite_home"] } : {});
11188
11258
  if (input.harness === "gemini" && input.authStyle !== "x-api-key")
11189
11259
  throw new Error("Gemini CLI requires x-api-key authentication.");
11190
11260
  validateHarnessVersion(input.harness, input.version);
@@ -11249,8 +11319,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
11249
11319
  }
11250
11320
 
11251
11321
  // src/launcher.ts
11252
- import { mkdir as mkdir11, mkdtemp, rm as rm6, writeFile as writeFile17 } from "fs/promises";
11253
- import { join as join19, resolve as resolve9 } from "path";
11322
+ import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile17 } from "fs/promises";
11323
+ import { join as join20, resolve as resolve11 } from "path";
11254
11324
 
11255
11325
  // src/provider-credential-onboarding.ts
11256
11326
  import { z as z8 } from "zod";
@@ -11801,6 +11871,7 @@ async function deliverVaultCredential() {
11801
11871
 
11802
11872
  // src/provider-credential-onboarding.ts
11803
11873
  var absent = (error) => error instanceof SwitcherError && error.status === 404;
11874
+ var MAX_CREDENTIAL_MATCHES = 256;
11804
11875
  var secretMetadataSchema = z8.object({
11805
11876
  key: vaultKeySchema,
11806
11877
  type: z8.enum(["api_key", "password", "token", "credential", "other"]),
@@ -11840,7 +11911,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
11840
11911
  const operator2 = await resolveVaultOperatorEnvironment(provisional, env);
11841
11912
  const entries = new Map;
11842
11913
  for (const query of searchTerms(provider)) {
11843
- const output = await runVaultCommand(provisional, ["search", query, "--json"], env, {}, {
11914
+ const output = await runVaultCommand(provisional, ["search", query, "--json", "--full", "--limit", String(MAX_CREDENTIAL_MATCHES + 1)], env, {}, {
11844
11915
  captureBytes: 256 * 1024,
11845
11916
  oversizeCode: "vault_metadata_oversized",
11846
11917
  oversizeMessage: "Secrets returned too much credential metadata; narrow the vault naming or bind an exact key explicitly.",
@@ -11854,12 +11925,14 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
11854
11925
  } catch {
11855
11926
  throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned invalid credential metadata JSON.");
11856
11927
  }
11857
- const result = secretMetadataSchema.array().max(1000).safeParse(parsed);
11928
+ if (Array.isArray(parsed) && parsed.length > MAX_CREDENTIAL_MATCHES)
11929
+ throw new Fault(422, "credential_matches_too_many", "More than 256 credential metadata rows matched. Bind an exact vault key explicitly.");
11930
+ const result = secretMetadataSchema.array().max(MAX_CREDENTIAL_MATCHES).safeParse(parsed);
11858
11931
  if (!result.success)
11859
11932
  throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned an unsupported credential metadata shape.");
11860
11933
  for (const entry of result.data)
11861
11934
  entries.set(entry.key, entry);
11862
- if (entries.size > 256)
11935
+ if (entries.size > MAX_CREDENTIAL_MATCHES)
11863
11936
  throw new Fault(422, "credential_matches_too_many", "More than 256 credential references matched. Bind an exact vault key explicitly.");
11864
11937
  }
11865
11938
  return [...entries.values()].sort((a, b) => a.key.localeCompare(b.key)).map((entry) => ({ account: operator2.source, key: entry.key, url: operator2.url, executable: vaultExecutable, operator: { kind: "contracts", expectedSource: operator2.source, expectedTier: operator2.tier } }));
@@ -12583,7 +12656,8 @@ function oriLaunchWarnings(target) {
12583
12656
  // src/chatgpt-launch.ts
12584
12657
  import { createHash as createHash12 } from "crypto";
12585
12658
  import { writeFile as writeFile15, rm as rm4 } from "fs/promises";
12586
- import { join as join17 } from "path";
12659
+ import { join as join18 } from "path";
12660
+ import { fileURLToPath } from "url";
12587
12661
 
12588
12662
  // src/desktop-state.ts
12589
12663
  import { Database as Database3 } from "bun:sqlite";
@@ -12635,6 +12709,401 @@ async function desktopLease(path) {
12635
12709
  };
12636
12710
  }
12637
12711
 
12712
+ // src/native-state.ts
12713
+ import { lstat as lstat8, mkdir as mkdir11, open as open4, opendir, readlink as readlink2, realpath as realpath7, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
12714
+ import { constants as constants7 } from "fs";
12715
+ import { homedir as homedir9 } from "os";
12716
+ import { dirname as dirname9, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve9 } from "path";
12717
+ function nativeStateRequested(tool, environment = process.env, explicit = false) {
12718
+ const suffix = tool.toUpperCase();
12719
+ return explicit || environment[`HASNA_${suffix}_STATE_HOME`] !== undefined || environment[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
12720
+ }
12721
+ function validateNativeStateVersion(tool, version) {
12722
+ if (tool !== "codex")
12723
+ return;
12724
+ const match = version?.match(/(\d+)\.(\d+)\.(\d+)/), actual = match?.slice(1).map(Number);
12725
+ if (!actual || actual[0] !== 0 || actual[1] < 154)
12726
+ throw new Fault(422, "native_state_version", "Shared Codex state requires Codex 0.154.0 or newer, whose metadata and resume protocol has been acceptance-tested by Switcher.");
12727
+ }
12728
+ var CODEX_INSTRUCTION_KEYS = [
12729
+ "instructions",
12730
+ "developer_instructions",
12731
+ "model_instructions_file",
12732
+ "compact_prompt",
12733
+ "experimental_compact_prompt_file",
12734
+ "include_permissions_instructions",
12735
+ "include_apps_instructions",
12736
+ "include_collaboration_mode_instructions",
12737
+ "include_environment_context",
12738
+ "project_doc_max_bytes",
12739
+ "project_doc_fallback_filenames"
12740
+ ];
12741
+ var NATIVE_STATE_ENTRIES = {
12742
+ codex: [
12743
+ ...["sessions", "archived_sessions", "thread-writer-locks", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12744
+ ...["history.jsonl", "AGENTS.md", "AGENTS.override.md"].map((name) => ({ name, kind: "file" }))
12745
+ ],
12746
+ claude: [
12747
+ ...["projects", "todos", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12748
+ ...["history.jsonl", "CLAUDE.md"].map((name) => ({ name, kind: "file" }))
12749
+ ]
12750
+ };
12751
+ async function info(path) {
12752
+ try {
12753
+ return await lstat8(path);
12754
+ } catch (error) {
12755
+ if (error.code === "ENOENT")
12756
+ return;
12757
+ throw error;
12758
+ }
12759
+ }
12760
+ function absolute(value) {
12761
+ if (!isAbsolute16(value) || value.includes("\x00"))
12762
+ throw new Fault(422, "native_state_path", "The shared native state directory must be an absolute path.");
12763
+ return resolve9(value);
12764
+ }
12765
+ function credentialOverlay(path) {
12766
+ return /(?:^|\/)subscriptions\/profiles\//.test(path) || /(?:^|\/)switcher\/state\/(?:desktop|desktop-claude|launch-[^/]+)\//.test(path);
12767
+ }
12768
+ async function assertSafeAncestors(path) {
12769
+ for (let parent = path;; parent = dirname9(parent)) {
12770
+ const ancestor = await lstat8(parent);
12771
+ const stickyRoot = ancestor.uid === 0 && (ancestor.mode & 512) !== 0;
12772
+ if (!ancestor.isDirectory() || ancestor.isSymbolicLink() || ![0, process.getuid?.()].includes(ancestor.uid) || (ancestor.mode & 18) !== 0 && !stickyRoot)
12773
+ throw new Fault(422, "native_state_permissions", "Shared native state has an unsafe ancestor directory.");
12774
+ if (parent === dirname9(parent))
12775
+ break;
12776
+ }
12777
+ }
12778
+ async function assertNativeStateDirectory(path) {
12779
+ const entry = await info(path);
12780
+ if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || await realpath7(path) !== path)
12781
+ throw new Fault(422, "native_state_permissions", "Shared native state must be an owned directory without writable or symbolic-link redirection.");
12782
+ await assertSafeAncestors(dirname9(path));
12783
+ }
12784
+ async function ensureNativeStateDirectory(path, create = true) {
12785
+ if (await info(path))
12786
+ return assertNativeStateDirectory(path);
12787
+ await ensureNativeStateDirectory(dirname9(path), create);
12788
+ if (!create)
12789
+ return;
12790
+ await mkdir11(path, { mode: 448 }).catch((error) => {
12791
+ if (error.code !== "EEXIST")
12792
+ throw error;
12793
+ });
12794
+ await assertNativeStateDirectory(path);
12795
+ }
12796
+ async function withNativeStateLock(state, operation) {
12797
+ await ensureNativeStateDirectory(state.home);
12798
+ const path = join17(state.home, ".switcher-shared-state.lock");
12799
+ let handle;
12800
+ try {
12801
+ handle = await open4(path, "wx", 384);
12802
+ } catch (error) {
12803
+ if (error.code !== "EEXIST")
12804
+ throw error;
12805
+ const entry = await info(path);
12806
+ if (!entry?.isFile() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 63) !== 0)
12807
+ throw new Fault(422, "native_state_lock", "The shared-state lock has unsafe ownership, permissions or type.");
12808
+ throw new Fault(409, "native_state_busy", "Another Switcher projection/import owns this corpus, or a prior operation ended before releasing its lock. Inspect native processes and the lock before retrying.");
12809
+ }
12810
+ const identity = await handle.stat();
12811
+ try {
12812
+ return await operation();
12813
+ } finally {
12814
+ await handle.close();
12815
+ try {
12816
+ const entry = await lstat8(path);
12817
+ if (entry.dev === identity.dev && entry.ino === identity.ino)
12818
+ await unlink2(path);
12819
+ } catch (error) {
12820
+ if (error.code !== "ENOENT")
12821
+ throw error;
12822
+ }
12823
+ }
12824
+ }
12825
+ async function assertShareableTree(path, budget = { entries: 0 }, depth = 0) {
12826
+ if (depth > 32)
12827
+ throw new Fault(422, "native_state_inventory_limit", "The shared native corpus exceeds the safe projection inventory limit.");
12828
+ if (depth === 0)
12829
+ await assertNativeStateDirectory(path);
12830
+ for await (const child of await opendir(path)) {
12831
+ if (++budget.entries > 1e5 || child.isSymbolicLink())
12832
+ throw new Fault(422, "native_state_entry", "A shared native state tree contains an unsupported link or exceeds the safe inventory limit.");
12833
+ const nested = join17(path, child.name), entry = await lstat8(nested);
12834
+ if (entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0)
12835
+ throw new Fault(422, "native_state_entry", "A shared native state entry has unsafe ownership or writable permissions.");
12836
+ if (child.isDirectory()) {
12837
+ if (!entry.isDirectory())
12838
+ throw new Fault(422, "native_state_entry", "A shared native state directory changed during inspection.");
12839
+ await assertShareableTree(nested, budget, depth + 1);
12840
+ continue;
12841
+ }
12842
+ if (!child.isFile() || !entry.isFile() || entry.nlink !== 1)
12843
+ throw new Fault(422, "native_state_entry", "A shared native state tree contains an unsupported file type or hardlink.");
12844
+ }
12845
+ }
12846
+ async function readCodexStateConfig(home) {
12847
+ const path = join17(home, "config.toml"), entry = await info(path);
12848
+ if (!entry)
12849
+ return {};
12850
+ if (!entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
12851
+ throw new Fault(422, "native_state_config", "The Codex instruction configuration cannot be read safely.");
12852
+ const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12853
+ let config;
12854
+ try {
12855
+ const opened = await handle.stat();
12856
+ if (opened.ino !== entry.ino || opened.dev !== entry.dev || opened.nlink !== 1 || opened.size > 1024 * 1024)
12857
+ throw new Fault(409, "native_state_config", "The Codex instruction configuration changed during preparation.");
12858
+ config = Bun.TOML.parse(await handle.readFile("utf8"));
12859
+ } catch (error) {
12860
+ if (error instanceof Fault)
12861
+ throw error;
12862
+ throw new Fault(422, "native_state_config", "The Codex instruction configuration is invalid.");
12863
+ } finally {
12864
+ await handle.close();
12865
+ }
12866
+ if (config.profile !== undefined || config.include !== undefined)
12867
+ throw new Fault(422, "native_state_config", "Codex profile/include selection is unsupported by the verified shared-state instruction contract. Resolve that effective configuration before launching; Switcher will not silently discard its instructions.");
12868
+ return config;
12869
+ }
12870
+ var CODEX_INSTRUCTION_FILE_KEYS = new Set(["model_instructions_file", "experimental_compact_prompt_file"]);
12871
+ async function codexInstructionProjection(home, config, allowedExternalFiles = {}) {
12872
+ const instructions = {};
12873
+ for (const key of CODEX_INSTRUCTION_KEYS) {
12874
+ const value = config[key];
12875
+ if (value === undefined)
12876
+ continue;
12877
+ const valid = key.startsWith("include_") ? typeof value === "boolean" : key === "project_doc_max_bytes" ? typeof value === "number" && Number.isSafeInteger(value) && value >= 0 : key === "project_doc_fallback_filenames" ? Array.isArray(value) && value.every((item2) => typeof item2 === "string" && !item2.includes("\x00")) : typeof value === "string" && !value.includes("\x00");
12878
+ if (!valid)
12879
+ throw new Fault(422, "native_state_instructions", "Codex instruction configuration has an unsupported value.");
12880
+ if (CODEX_INSTRUCTION_FILE_KEYS.has(key)) {
12881
+ const path = resolve9(home, value), entry = await info(path);
12882
+ const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute16(relativePath);
12883
+ if (!contained && path !== allowedExternalFiles[key] || !entry || !entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || ![0, process.getuid?.()].includes(entry.uid) || (entry.mode & 18) !== 0 || await realpath7(path) !== path)
12884
+ throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
12885
+ await assertSafeAncestors(dirname9(path));
12886
+ const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW).catch(() => {
12887
+ throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
12888
+ });
12889
+ try {
12890
+ const opened = await handle.stat();
12891
+ if (opened.ino !== entry.ino || opened.dev !== entry.dev || opened.nlink !== 1)
12892
+ throw new Fault(409, "native_state_instructions", "The configured instruction file changed during preparation.");
12893
+ } finally {
12894
+ await handle.close();
12895
+ }
12896
+ instructions[key] = path;
12897
+ } else
12898
+ instructions[key] = value;
12899
+ }
12900
+ return instructions;
12901
+ }
12902
+ async function assertNativeInstructionOverlay(state, overlayHome) {
12903
+ if (state.tool !== "codex" || absolute(overlayHome) === state.home)
12904
+ return;
12905
+ await assertNativeStateDirectory(overlayHome);
12906
+ const config = await readCodexStateConfig(overlayHome);
12907
+ if (config.profiles !== undefined || config.include !== undefined)
12908
+ throw new Fault(422, "native_state_instruction_overlay", "Private Codex profile/include instruction overlays are not supported. Resolve their effective canonical instructions before launching.");
12909
+ const expected = state.instructions ?? {};
12910
+ const allowedExternalFiles = Object.fromEntries([...CODEX_INSTRUCTION_FILE_KEYS].flatMap((key) => typeof expected[key] === "string" ? [[key, expected[key]]] : []));
12911
+ const actual = await codexInstructionProjection(overlayHome, config, allowedExternalFiles);
12912
+ if (CODEX_INSTRUCTION_KEYS.some((key) => JSON.stringify(actual[key]) !== JSON.stringify(expected[key])))
12913
+ throw new Fault(409, "native_state_instruction_overlay", "This Codex authentication home has missing or conflicting canonical instructions. Refresh its instruction projection before launching; Switcher will not rewrite private account configuration.");
12914
+ }
12915
+ async function resolveNativeState(tool, environment = process.env, options = {}) {
12916
+ if (process.platform === "win32")
12917
+ throw new Fault(422, "unsupported_platform", "Shared native state currently requires POSIX ownership, no-follow and symlink semantics on Linux or macOS.");
12918
+ const suffix = tool.toUpperCase();
12919
+ const marker = `HASNA_${suffix}_STATE_HOME`, legacyMarker = `SUBSCRIPTIONS_SHARED_HOME_${suffix}`;
12920
+ const primary = environment[marker], legacy = environment[legacyMarker];
12921
+ if (primary !== undefined && legacy !== undefined && absolute(primary) !== absolute(legacy))
12922
+ throw new Fault(409, "native_state_identity_conflict", `The ${marker} and ${legacyMarker} corpus identities disagree. Select one exact shared native state directory before launching.`);
12923
+ const userHome = absolute(environment.HOME ?? homedir9());
12924
+ const selected = primary !== undefined ? absolute(primary) : legacy !== undefined ? absolute(legacy) : join17(userHome, `.${tool}`);
12925
+ if (credentialOverlay(selected))
12926
+ throw new Fault(422, "native_state_overlay", "An authentication profile cannot be the shared native state directory. Select its original native state directory.");
12927
+ await ensureNativeStateDirectory(selected, options.create !== false);
12928
+ if (tool === "claude")
12929
+ return { tool, home: selected, marker };
12930
+ const config = await readCodexStateConfig(selected);
12931
+ let sqliteHome = selected;
12932
+ if (config.sqlite_home !== undefined) {
12933
+ if (typeof config.sqlite_home !== "string")
12934
+ throw new Fault(422, "native_state_config", "Codex sqlite_home must be an absolute directory.");
12935
+ sqliteHome = absolute(config.sqlite_home);
12936
+ if (credentialOverlay(sqliteHome))
12937
+ throw new Fault(422, "native_state_overlay", "Codex SQLite state cannot belong to an authentication profile.");
12938
+ await ensureNativeStateDirectory(sqliteHome, options.create !== false);
12939
+ }
12940
+ const instructions = await codexInstructionProjection(selected, config);
12941
+ return { tool, home: selected, sqliteHome, marker, instructions };
12942
+ }
12943
+ function nativeStateEnvironment(state) {
12944
+ return state.tool === "codex" && state.sqliteHome ? { CODEX_SQLITE_HOME: state.sqliteHome } : {};
12945
+ }
12946
+ async function assertCodexDatabaseRedirectSafe(state, overlayHome) {
12947
+ if (state.tool !== "codex")
12948
+ return;
12949
+ const config = await readCodexStateConfig(overlayHome);
12950
+ const previous = config.sqlite_home;
12951
+ if (previous !== undefined && typeof previous !== "string")
12952
+ throw new Fault(422, "native_state_config", "The previous Codex sqlite_home must be an absolute directory.");
12953
+ const roots = new Set([overlayHome, ...typeof previous === "string" ? [absolute(previous)] : []]);
12954
+ for (const root of roots) {
12955
+ if (root === (state.sqliteHome ?? state.home) || !await info(root))
12956
+ continue;
12957
+ await assertNativeStateDirectory(root);
12958
+ const before = await lstat8(root);
12959
+ let inspected = 0;
12960
+ for await (const entry of await opendir(root)) {
12961
+ if (++inspected > 1e4)
12962
+ throw new Fault(409, "native_state_inventory_limit", "Native database inventory exceeded its bounded limit; no state was projected.");
12963
+ if (/^(?:state|logs|goals|memories|queue|thread_history)_\d+\.sqlite(?:-(?:wal|shm))?$/.test(entry.name))
12964
+ throw new Fault(409, "native_state_migration_required", "This profile retains native database metadata. Reconcile its catalog and history before redirecting shared state.");
12965
+ }
12966
+ const after = await lstat8(root);
12967
+ if (after.isSymbolicLink() || before.dev !== after.dev || before.ino !== after.ino || before.mtimeMs !== after.mtimeMs)
12968
+ throw new Fault(409, "native_state_inventory_changed", "Native database inventory changed; no state was projected.");
12969
+ }
12970
+ }
12971
+ async function directoryHasEntries(path) {
12972
+ const directory = await opendir(path);
12973
+ try {
12974
+ return Boolean(await directory.read());
12975
+ } finally {
12976
+ await directory.close();
12977
+ }
12978
+ }
12979
+ async function legacyNativeStateWarnings(root, state) {
12980
+ const directory = join17(root, state.tool === "codex" ? "desktop" : "desktop-claude");
12981
+ if (!await info(directory))
12982
+ return [];
12983
+ await assertNativeStateDirectory(directory);
12984
+ const pending = [];
12985
+ let inspected = 0;
12986
+ for await (const entry of await opendir(directory)) {
12987
+ if (++inspected > 1000)
12988
+ throw new Fault(409, "native_state_inventory_limit", "Too many legacy desktop profiles to inspect safely.");
12989
+ if (!entry.isDirectory() || entry.isSymbolicLink())
12990
+ continue;
12991
+ const home = join17(directory, entry.name, ...state.tool === "codex" ? ["codex"] : []);
12992
+ if (!await info(home))
12993
+ continue;
12994
+ await assertNativeStateDirectory(home);
12995
+ for (const name of [...NATIVE_STATE_ENTRIES[state.tool].map((item2) => item2.name), ...state.tool === "codex" ? ["state_5.sqlite", "session_index.jsonl"] : []]) {
12996
+ const path = join17(home, name), item2 = await info(path);
12997
+ if (!item2 || item2.isSymbolicLink())
12998
+ continue;
12999
+ if (item2.isFile() && item2.size > 0 || item2.isDirectory() && await directoryHasEntries(path)) {
13000
+ pending.push(home);
13001
+ break;
13002
+ }
13003
+ }
13004
+ }
13005
+ const display = (path) => {
13006
+ const value = JSON.stringify(path).replace(/[\u007f-\u009f\u061c\u200e\u200f\u2028-\u202e\u2066-\u2069]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
13007
+ return value.length > 768 ? `${value.slice(0, 384)}...${value.slice(-381)}` : value;
13008
+ };
13009
+ const warnings = pending.slice(0, 10).map((home) => `Legacy native state is preserved at ${display(home)}; migration is pending. Inspect with switcher state import ${state.tool} --from ${display(home)}. A copied snapshot does not retire the original or migrate its SQLite/index metadata.`);
13010
+ if (pending.length > warnings.length)
13011
+ warnings.push(`${pending.length - warnings.length} additional legacy ${state.tool} state directories are pending migration; inspect the Switcher state root before launch.`);
13012
+ return warnings;
13013
+ }
13014
+ async function createTrackedDirectory(path, created) {
13015
+ try {
13016
+ await mkdir11(path, { mode: 448 });
13017
+ created.push(path);
13018
+ } catch (error) {
13019
+ if (error.code !== "EEXIST")
13020
+ throw error;
13021
+ await assertNativeStateDirectory(path);
13022
+ }
13023
+ }
13024
+ async function projectNativeStateUnlocked(state, overlayHome) {
13025
+ overlayHome = absolute(overlayHome);
13026
+ await assertNativeStateDirectory(state.home);
13027
+ await assertNativeStateDirectory(overlayHome);
13028
+ if (overlayHome === state.home)
13029
+ return;
13030
+ const contains = (parent, child) => {
13031
+ const suffix = relative5(parent, child);
13032
+ return suffix !== ".." && !suffix.startsWith("../") && !isAbsolute16(suffix);
13033
+ };
13034
+ if (contains(state.home, overlayHome) || contains(overlayHome, state.home))
13035
+ throw new Fault(422, "native_state_overlap", "The shared corpus and authentication overlay must be separate directories.");
13036
+ await assertCodexDatabaseRedirectSafe(state, overlayHome);
13037
+ for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
13038
+ const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
13039
+ await ensureNativeStateDirectory(dirname9(target), false);
13040
+ await ensureNativeStateDirectory(dirname9(destination), false);
13041
+ const source = await info(target), existing = await info(destination);
13042
+ if (source && (source.isSymbolicLink() || source.uid !== process.getuid?.() || (source.mode & 18) !== 0 || source.isFile() && source.nlink !== 1 || (entry.kind === "directory" ? !source.isDirectory() : !source.isFile())))
13043
+ throw new Fault(422, "native_state_entry", "A shared native state entry has an unsupported type, owner or permissions.");
13044
+ if (source?.isDirectory())
13045
+ await assertShareableTree(target);
13046
+ if (existing && (!existing.isSymbolicLink() || resolve9(dirname9(destination), await readlink2(destination)) !== target))
13047
+ 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.");
13048
+ }
13049
+ const createdLinks = [];
13050
+ const createdFiles = [], createdDirectories = [];
13051
+ try {
13052
+ for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
13053
+ const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
13054
+ const targetParent = dirname9(target), destinationParent = dirname9(destination);
13055
+ if (!await info(targetParent))
13056
+ await createTrackedDirectory(targetParent, createdDirectories);
13057
+ else
13058
+ await assertNativeStateDirectory(targetParent);
13059
+ if (!await info(destinationParent))
13060
+ await createTrackedDirectory(destinationParent, createdDirectories);
13061
+ else
13062
+ await assertNativeStateDirectory(destinationParent);
13063
+ if (entry.kind === "file" && !await info(target))
13064
+ continue;
13065
+ if (!await info(target)) {
13066
+ if (entry.kind === "directory")
13067
+ await createTrackedDirectory(target, createdDirectories);
13068
+ else {
13069
+ const file = await open4(target, "wx", 384);
13070
+ await file.close();
13071
+ createdFiles.push(target);
13072
+ }
13073
+ }
13074
+ if (!await info(destination)) {
13075
+ await symlink4(target, destination, entry.kind === "directory" ? "dir" : "file");
13076
+ createdLinks.push({ destination, target });
13077
+ }
13078
+ }
13079
+ } catch (error) {
13080
+ for (const item2 of createdLinks.reverse()) {
13081
+ try {
13082
+ if ((await info(item2.destination))?.isSymbolicLink() && resolve9(dirname9(item2.destination), await readlink2(item2.destination)) === item2.target)
13083
+ await unlink2(item2.destination);
13084
+ } catch {}
13085
+ }
13086
+ for (const path of createdFiles.reverse()) {
13087
+ try {
13088
+ const entry = await info(path);
13089
+ if (entry?.isFile() && entry.nlink === 1 && entry.size === 0)
13090
+ await unlink2(path);
13091
+ } catch {}
13092
+ }
13093
+ for (const path of [...new Set(createdDirectories)].sort((a, b) => b.length - a.length)) {
13094
+ try {
13095
+ await rmdir(path);
13096
+ } catch {}
13097
+ }
13098
+ throw error;
13099
+ }
13100
+ }
13101
+ async function projectNativeState(state, overlayHome) {
13102
+ if (absolute(overlayHome) === state.home)
13103
+ return;
13104
+ return withNativeStateLock(state, () => projectNativeStateUnlocked(state, overlayHome));
13105
+ }
13106
+
12638
13107
  // src/chatgpt-launch.ts
12639
13108
  var object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
12640
13109
  function merge2(base, overlay) {
@@ -12643,16 +13112,41 @@ function merge2(base, overlay) {
12643
13112
  result[key] = object5(value) && object5(result[key]) ? merge2(result[key], value) : value;
12644
13113
  return result;
12645
13114
  }
13115
+ function clearSwitcherModelState(config) {
13116
+ for (const key of [...codexRoutingKeys, "review_model", "sqlite_home", "model_reasoning_effort", "cli_auth_credentials_store", "forced_login_method", ...CODEX_INSTRUCTION_KEYS])
13117
+ delete config[key];
13118
+ if (object5(config.agents)) {
13119
+ for (const key of ["default_subagent_model", "default_subagent_reasoning_effort", "default_subagent_reasoning_summary"])
13120
+ delete config.agents[key];
13121
+ for (const [name, value] of Object.entries(config.agents))
13122
+ if (object5(value)) {
13123
+ for (const key of ["model", "model_provider", "provider", "config_file"])
13124
+ delete value[key];
13125
+ if (!Object.keys(value).length)
13126
+ delete config.agents[name];
13127
+ }
13128
+ if (!Object.keys(config.agents).length)
13129
+ delete config.agents;
13130
+ }
13131
+ if (object5(config.memories)) {
13132
+ delete config.memories.extract_model;
13133
+ delete config.memories.consolidation_model;
13134
+ if (!Object.keys(config.memories).length)
13135
+ delete config.memories;
13136
+ }
13137
+ }
12646
13138
  var digest = (value) => createHash12("sha256").update(value).digest("hex");
12647
13139
  var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
12648
- async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
13140
+ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedState) {
13141
+ if (sharedState && sharedState.tool !== "codex")
13142
+ throw new Fault(422, "native_state_tool", "ChatGPT requires the canonical Codex corpus.");
12649
13143
  await privateDirectory(sessionDir);
12650
- const home = join17(sessionDir, "codex"), userData = join17(sessionDir, "electron");
13144
+ const home = join18(sessionDir, "codex"), userData = join18(sessionDir, "electron");
12651
13145
  await privateDirectory(home);
12652
13146
  await privateDirectory(userData);
12653
- const release = await desktopLease(join17(sessionDir, "launch.sqlite"));
13147
+ const release = await desktopLease(join18(sessionDir, "launch.sqlite"));
12654
13148
  let released = false, authText;
12655
- const authPath = join17(home, "auth.json"), receiptPath = join17(home, ".switcher-auth.sha256");
13149
+ const authPath = join18(home, "auth.json"), receiptPath = join18(home, ".switcher-auth.sha256");
12656
13150
  const cleanup = async () => {
12657
13151
  if (released)
12658
13152
  return;
@@ -12667,18 +13161,23 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
12667
13161
  }
12668
13162
  };
12669
13163
  try {
13164
+ if (sharedState)
13165
+ await projectNativeState(sharedState, home);
12670
13166
  const settings2 = [];
12671
13167
  for (let i = 0;i < native.args.length; i += 2) {
12672
13168
  if (native.args[i] !== "-c" || typeof native.args[i + 1] !== "string")
12673
13169
  throw new Fault(400, "desktop_arguments", "Desktop launches accept provider/model settings, not native CLI commands.");
12674
- settings2.push(native.args[i + 1]);
13170
+ if (!sharedState?.sqliteHome || !native.args[i + 1].startsWith("sqlite_home="))
13171
+ settings2.push(native.args[i + 1]);
12675
13172
  }
12676
13173
  settings2.push('cli_auth_credentials_store="file"', 'forced_login_method="api"');
13174
+ if (sharedState?.sqliteHome)
13175
+ settings2.push(`sqlite_home=${JSON.stringify(sharedState.sqliteHome)}`);
12677
13176
  if (!settings2.some((setting) => setting.startsWith("approval_policy=")))
12678
13177
  settings2.push('approval_policy="on-request"');
12679
13178
  if (!settings2.some((setting) => setting.startsWith("sandbox_mode=")))
12680
13179
  settings2.push('sandbox_mode="workspace-write"');
12681
- const configPath = join17(home, "config.toml");
13180
+ const configPath = join18(home, "config.toml");
12682
13181
  const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
12683
13182
  if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
12684
13183
  throw new Fault(409, "desktop_auth_changed", "This isolated desktop profile contains authentication that Switcher did not create. Sign out of that provider profile before launching it again; Switcher will not overwrite it.");
@@ -12689,6 +13188,12 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
12689
13188
  if (error.code !== "ENOENT")
12690
13189
  throw new Fault(422, "desktop_config_invalid", "The desktop profile config cannot be read safely.");
12691
13190
  }
13191
+ if (sharedState) {
13192
+ if (["profile", "profiles", "include"].some((key2) => existing[key2] !== undefined))
13193
+ throw new Fault(409, "desktop_config_routing", "The private desktop overlay contains profile/include routing that cannot be reconciled with shared native state. Review the overlay before launching.");
13194
+ clearSwitcherModelState(existing);
13195
+ Object.assign(existing, sharedState.instructions);
13196
+ }
12692
13197
  const config = merge2(existing, Bun.TOML.parse(settings2.join(`
12693
13198
  `)));
12694
13199
  await writeDesktopPrivate(configPath, renderCodexAgentToml(config));
@@ -12699,8 +13204,20 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
12699
13204
  `;
12700
13205
  await writeDesktopPrivate(receiptPath, digest(authText));
12701
13206
  await writeDesktopPrivate(authPath, authText);
12702
- const wrapper = join17(stateDir, "chatgpt-codex");
13207
+ const wrapper = join18(stateDir, "chatgpt-codex");
12703
13208
  const overrides = settings2.flatMap((setting) => ["-c", setting]);
13209
+ let bridge = "";
13210
+ if (sharedState) {
13211
+ const entry = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./codex-state-bridge.ts" : "../codex-state-bridge.js", import.meta.url));
13212
+ const ownedKeys = new Set(["model_provider", "model_providers", "model_catalog_json", "review_model", "agents", "memories", "sqlite_home"]);
13213
+ const routing3 = Object.fromEntries(Object.entries(config).filter(([key2]) => ownedKeys.has(key2)));
13214
+ if (typeof config.model !== "string")
13215
+ throw new Fault(500, "desktop_model_missing", "Desktop preparation did not receive its selected model.");
13216
+ bridge = `if [ "\${1-}" = app-server ]; then
13217
+ exec ${[process.execPath, entry, app.codexExecutable, config.model, JSON.stringify(routing3)].map(quote2).join(" ")} "$@" ${overrides.map(quote2).join(" ")}
13218
+ fi
13219
+ `;
13220
+ }
12704
13221
  await writeFile15(wrapper, `#!/bin/sh
12705
13222
  set -eu
12706
13223
  unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
@@ -12708,15 +13225,15 @@ export CODEX_HOME=${quote2(home)}
12708
13225
  if [ "\${1-}" = sandbox ]; then
12709
13226
  exec ${quote2(app.codexExecutable)} "$@"
12710
13227
  fi
12711
- exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
13228
+ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
12712
13229
  `, { mode: 448, flag: "wx" });
12713
13230
  return {
12714
13231
  ...native,
12715
13232
  executable: app.executable,
12716
13233
  args: [`--user-data-dir=${userData}`],
12717
- env: { ...native.env, CODEX_HOME: home, CODEX_ELECTRON_USER_DATA_PATH: userData, CODEX_CLI_PATH: wrapper, CODEX_APP_SERVER_FORCE_CLI: "1", CODEX_APP_SERVER_USE_LOCAL_DAEMON: "0" },
13234
+ env: { ...native.env, ...sharedState ? nativeStateEnvironment(sharedState) : {}, CODEX_HOME: home, CODEX_ELECTRON_USER_DATA_PATH: userData, CODEX_CLI_PATH: wrapper, CODEX_APP_SERVER_FORCE_CLI: "1", CODEX_APP_SERVER_USE_LOCAL_DAEMON: "0" },
12718
13235
  configPaths: [...native.configPaths, configPath, wrapper],
12719
- warnings: [...native.warnings, `ChatGPT provider profile: ${sessionDir}. Local Codex conversations use this provider; ChatGPT cloud Chat/Work and account-only features are not redirected. Keep Switcher running until you quit this app instance.`],
13236
+ warnings: [...native.warnings, `ChatGPT provider state is isolated.${sharedState ? " Allowlisted local sessions and instructions use the explicitly selected shared corpus across providers." : ""} Local Codex conversations use this provider; ChatGPT cloud Chat/Work and account-only features are not redirected. Keep Switcher running until you quit this app instance.`],
12720
13237
  cleanup: async () => {
12721
13238
  try {
12722
13239
  await native.cleanup?.();
@@ -12735,14 +13252,14 @@ exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
12735
13252
  import { createHash as createHash13 } from "crypto";
12736
13253
  import { execFile as execFile5 } from "child_process";
12737
13254
  import { access as access5, rm as rm5, writeFile as writeFile16 } from "fs/promises";
12738
- import { homedir as homedir9, userInfo as userInfo2 } from "os";
12739
- import { join as join18 } from "path";
13255
+ import { homedir as homedir10, userInfo as userInfo2 } from "os";
13256
+ import { join as join19 } from "path";
12740
13257
  import { promisify as promisify5 } from "util";
12741
13258
  var execute4 = promisify5(execFile5);
12742
13259
  var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
12743
- var claudeDesktopDataDirectory = () => join18(homedir9(), "Library/Application Support/Claude-3p");
13260
+ var claudeDesktopDataDirectory = () => join19(homedir10(), "Library/Application Support/Claude-3p");
12744
13261
  async function assertAvailable(userData) {
12745
- for (const path of [join18("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
13262
+ for (const path of [join19("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
12746
13263
  if (await access5(path).then(() => true, () => false))
12747
13264
  throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
12748
13265
  let openFiles;
@@ -12766,6 +13283,8 @@ function metadata(text) {
12766
13283
  async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
12767
13284
  if (input.harness !== "claude")
12768
13285
  throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
13286
+ if (input.sharedState && input.sharedState.tool !== "claude")
13287
+ throw new Fault(422, "native_state_tool", "Claude desktop requires the canonical Claude corpus.");
12769
13288
  validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
12770
13289
  if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
12771
13290
  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.");
@@ -12776,15 +13295,15 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
12776
13295
  const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
12777
13296
  await check2();
12778
13297
  await privateDirectory(userData);
12779
- const library = join18(userData, "configLibrary");
13298
+ const library = join19(userData, "configLibrary");
12780
13299
  await privateDirectory(library);
12781
- const release = await desktopLease(join18(library, ".switcher-lease.sqlite"));
12782
- const metaPath = join18(library, "_meta.json"), receiptPath = join18(library, ".switcher-selection.json");
13300
+ const release = await desktopLease(join19(library, ".switcher-lease.sqlite"));
13301
+ const metaPath = join19(library, "_meta.json"), receiptPath = join19(library, ".switcher-selection.json");
12783
13302
  let receipt, gateway, closed = false;
12784
13303
  const restore = async (record3) => {
12785
13304
  if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
12786
13305
  throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
12787
- const configPath = join18(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
13306
+ const configPath = join19(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
12788
13307
  if (current !== undefined && hash2(current) !== record3.configHash)
12789
13308
  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.");
12790
13309
  const currentMeta = await safeDesktopRead(metaPath);
@@ -12813,10 +13332,12 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
12813
13332
  const recovery = await safeDesktopRead(receiptPath);
12814
13333
  if (recovery)
12815
13334
  await restore(JSON.parse(recovery));
12816
- const localConfig = await safeDesktopRead(join18(userData, "claude_desktop_config.json"));
13335
+ const localConfig = await safeDesktopRead(join19(userData, "claude_desktop_config.json"));
12817
13336
  if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
12818
13337
  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.");
12819
13338
  await privateDirectory(sessionDir);
13339
+ if (input.sharedState)
13340
+ await projectNativeState(input.sharedState, sessionDir);
12820
13341
  const roles2 = input.modelPolicy?.roles;
12821
13342
  const targets = { sonnet: input.model, opus: roles2?.planning ?? input.model, haiku: roles2?.fast ?? input.model };
12822
13343
  const aliases = Object.fromEntries(Object.entries(targets).map(([tier, model3]) => ["switcher/" + tier, model3]));
@@ -12824,10 +13345,10 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
12824
13345
  if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
12825
13346
  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.");
12826
13347
  const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
12827
- const catalogPath = join18(input.stateDir, "claude-desktop-policy.json");
13348
+ const catalogPath = join19(input.stateDir, "claude-desktop-policy.json");
12828
13349
  await writeFile16(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
12829
13350
  gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
12830
- const id2 = crypto.randomUUID(), configPath = join18(library, id2 + ".json");
13351
+ const id2 = crypto.randomUUID(), configPath = join19(library, id2 + ".json");
12831
13352
  const config = JSON.stringify({
12832
13353
  inferenceProvider: "gateway",
12833
13354
  inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
@@ -12846,7 +13367,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
12846
13367
  return {
12847
13368
  executable: app.executable,
12848
13369
  args: [],
12849
- env: { CLAUDE_CONFIG_DIR: sessionDir },
13370
+ env: { ...input.sharedState ? nativeStateEnvironment(input.sharedState) : {}, CLAUDE_CONFIG_DIR: sessionDir },
12850
13371
  configPaths: [catalogPath, configPath],
12851
13372
  beforeLaunch: check2,
12852
13373
  cleanup,
@@ -12860,10 +13381,212 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
12860
13381
  }
12861
13382
  }
12862
13383
 
13384
+ // src/codex-session-discovery.ts
13385
+ import { spawn as spawn3 } from "child_process";
13386
+ import { createInterface as createInterface2 } from "readline/promises";
13387
+ import { basename as basename3, resolve as resolve10 } from "path";
13388
+ var object6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
13389
+ var unavailable = () => new Fault(422, "codex_session_discovery", "Native Codex session discovery failed. No conversation was started. Retry discovery or provide an exact session ID.");
13390
+ async function listCodexSessions(prepared, cwd, query) {
13391
+ if (!Number.isSafeInteger(query.limit) || query.limit < 1 || query.limit > 100 || query.cursor !== undefined && query.cursor.length > 4096 || query.searchTerm !== undefined && query.searchTerm.length > 1024 || cwd.length > 32768 || query.cwd !== undefined && query.cwd.length > 32768)
13392
+ throw unavailable();
13393
+ const nativeStateEnv = Object.fromEntries(Object.entries(prepared.env).filter(([name]) => ["CODEX_HOME", "CODEX_SQLITE_HOME"].includes(name)));
13394
+ const child = spawn3(prepared.executable, [...prepared.args, "app-server"], {
13395
+ cwd,
13396
+ env: { ...childEnvironment(), ...nativeStateEnv, SWITCHER_HARNESS_API_KEY: "switcher-metadata-no-auth" },
13397
+ stdio: ["pipe", "pipe", "ignore"]
13398
+ });
13399
+ let done = false, initialized = false, pending = Buffer.alloc(0), responseBytes = 0;
13400
+ let killTimer;
13401
+ let resolvePage, rejectPage;
13402
+ const result = new Promise((resolve11, reject2) => {
13403
+ resolvePage = resolve11;
13404
+ rejectPage = reject2;
13405
+ });
13406
+ const closed = new Promise((resolve11) => child.once("close", () => resolve11()));
13407
+ const stop = () => {
13408
+ child.stdin.destroy();
13409
+ child.kill("SIGTERM");
13410
+ killTimer ??= setTimeout(() => child.kill("SIGKILL"), 2000);
13411
+ killTimer.unref();
13412
+ };
13413
+ const fail = (error = unavailable()) => {
13414
+ if (!done) {
13415
+ done = true;
13416
+ rejectPage(error);
13417
+ }
13418
+ stop();
13419
+ };
13420
+ const interrupt = () => fail(new CommandInterrupted(130, "Session discovery was cancelled; no conversation was started."));
13421
+ const terminate = () => fail(new CommandInterrupted(143, "Session discovery was interrupted; no conversation was started."));
13422
+ process.once("SIGINT", interrupt);
13423
+ process.once("SIGTERM", terminate);
13424
+ process.once("SIGHUP", terminate);
13425
+ const timer = setTimeout(() => fail(), 1e4);
13426
+ child.once("error", () => fail());
13427
+ child.stdin.on("error", () => fail());
13428
+ child.once("close", () => {
13429
+ if (!done)
13430
+ fail();
13431
+ });
13432
+ const send = (message) => child.stdin.write(JSON.stringify(message) + `
13433
+ `);
13434
+ child.stdout.on("data", (chunk) => {
13435
+ if (done)
13436
+ return;
13437
+ try {
13438
+ responseBytes += chunk.length;
13439
+ if (responseBytes > 16 * 1024 * 1024 || pending.length + chunk.length > 8 * 1024 * 1024)
13440
+ throw unavailable();
13441
+ pending = Buffer.concat([pending, chunk]);
13442
+ let end;
13443
+ while ((end = pending.indexOf(10)) >= 0) {
13444
+ const line = pending.subarray(0, end);
13445
+ pending = pending.subarray(end + 1);
13446
+ if (!line.length)
13447
+ continue;
13448
+ const message = JSON.parse(line.toString("utf8"));
13449
+ if (!object6(message))
13450
+ throw unavailable();
13451
+ if (message.id === 1) {
13452
+ if (initialized || message.error || !object6(message.result))
13453
+ throw unavailable();
13454
+ initialized = true;
13455
+ send({ method: "initialized" });
13456
+ send({ id: 2, method: "thread/list", params: { ...query, modelProviders: [], useStateDbOnly: false, sortKey: "updated_at", sortDirection: "desc" } });
13457
+ } else if (message.id === 2) {
13458
+ const page = message.result;
13459
+ if (!initialized || message.error || !object6(page) || !Array.isArray(page.data) || page.data.length > query.limit || !(page.nextCursor === null || typeof page.nextCursor === "string") || typeof page.nextCursor === "string" && page.nextCursor.length > 4096)
13460
+ throw unavailable();
13461
+ const data2 = page.data.map((thread) => {
13462
+ if (!object6(thread) || typeof thread.id !== "string" || !/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(thread.id) || typeof thread.cwd !== "string" || thread.cwd.length > 32768 || thread.name != null && typeof thread.name !== "string" || thread.preview !== undefined && typeof thread.preview !== "string")
13463
+ throw unavailable();
13464
+ return { id: thread.id, cwd: thread.cwd, name: thread.name, preview: thread.preview };
13465
+ });
13466
+ done = true;
13467
+ resolvePage({ data: data2, nextCursor: page.nextCursor });
13468
+ stop();
13469
+ return;
13470
+ }
13471
+ }
13472
+ } catch {
13473
+ fail();
13474
+ }
13475
+ });
13476
+ send({ id: 1, method: "initialize", params: { clientInfo: { name: "switcher_session_discovery", version: "1" }, capabilities: { experimentalApi: true } } });
13477
+ try {
13478
+ return await result;
13479
+ } finally {
13480
+ clearTimeout(timer);
13481
+ stop();
13482
+ await closed;
13483
+ if (killTimer)
13484
+ clearTimeout(killTimer);
13485
+ process.off("SIGINT", interrupt);
13486
+ process.off("SIGTERM", terminate);
13487
+ process.off("SIGHUP", terminate);
13488
+ }
13489
+ }
13490
+ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = listCodexSessions) {
13491
+ const command = codexCommandIndex(nativeArgs);
13492
+ if (command < 0 || nativeArgs[command] !== "resume")
13493
+ return nativeArgs;
13494
+ let last = false, all2 = false, positional = false;
13495
+ let effectiveCwd = cwd;
13496
+ const remove = new Set;
13497
+ for (let i = 0;i < nativeArgs.length; i++) {
13498
+ if (i === command)
13499
+ continue;
13500
+ if (nativeArgs[i] === "--") {
13501
+ positional ||= i > command && Boolean(nativeArgs[i + 1]);
13502
+ break;
13503
+ }
13504
+ if (nativeArgs[i].startsWith("--cd="))
13505
+ effectiveCwd = resolve10(cwd, nativeArgs[i].slice(5));
13506
+ else if (nativeArgs[i].startsWith("-C") && nativeArgs[i].length > 2)
13507
+ effectiveCwd = resolve10(cwd, nativeArgs[i].slice(2));
13508
+ if (codexOptionRequestsHelp(nativeArgs[i]))
13509
+ return nativeArgs;
13510
+ if (codexOptionTakesValue(nativeArgs[i])) {
13511
+ if (nativeArgs[i] === "--cd" || nativeArgs[i] === "-C") {
13512
+ if (!nativeArgs[i + 1])
13513
+ throw unavailable();
13514
+ effectiveCwd = resolve10(cwd, nativeArgs[i + 1]);
13515
+ }
13516
+ i++;
13517
+ continue;
13518
+ }
13519
+ if (i > command && nativeArgs[i] === "--last") {
13520
+ last = true;
13521
+ remove.add(i);
13522
+ }
13523
+ if (i > command && nativeArgs[i] === "--all") {
13524
+ all2 = true;
13525
+ remove.add(i);
13526
+ }
13527
+ if (i > command && !nativeArgs[i].startsWith("-"))
13528
+ positional = true;
13529
+ }
13530
+ if (positional && !last)
13531
+ return nativeArgs;
13532
+ const query = { limit: last ? 1 : 30, ...all2 ? {} : { cwd: effectiveCwd } };
13533
+ if (!last && (!process.stdin.isTTY || !process.stderr.isTTY))
13534
+ throw new Fault(400, "codex_session_required", "Provide an exact session ID or use resume --last in noninteractive mode.");
13535
+ const finish = (id2) => [...nativeArgs.slice(0, command), "resume", id2, ...nativeArgs.slice(command + 1).filter((_arg, i) => !remove.has(i + command + 1))];
13536
+ let page = await list(prepared, effectiveCwd, query);
13537
+ if (last) {
13538
+ if (!page.data[0])
13539
+ throw new Fault(404, "codex_session_missing", "No Codex conversations match this workspace. Use resume --all to include other workspaces.");
13540
+ return finish(page.data[0].id);
13541
+ }
13542
+ const reader = createInterface2({ input: process.stdin, output: process.stderr });
13543
+ const controller = new AbortController;
13544
+ const cancel = () => controller.abort(new CommandInterrupted(130, "Session selection was cancelled."));
13545
+ const terminate = () => controller.abort(new CommandInterrupted(143, "Session selection was interrupted."));
13546
+ const hangup = () => controller.abort(new CommandInterrupted(129, "Session selection ended after terminal hangup."));
13547
+ reader.on("SIGINT", cancel);
13548
+ reader.on("close", cancel);
13549
+ process.on("SIGINT", cancel);
13550
+ process.on("SIGTERM", terminate);
13551
+ process.on("SIGHUP", hangup);
13552
+ const display = (value) => value.replace(/[\x00-\x1f\x7f-\x9f]/g, "").slice(0, 180);
13553
+ try {
13554
+ for (;; ) {
13555
+ console.error("Codex conversations across providers:");
13556
+ page.data.forEach((thread, i) => console.error(` ${i + 1}. ${display(thread.name ?? thread.id)} \u2014 workspace ${display(basename3(thread.cwd) || "unknown")}`));
13557
+ const answer = (await reader.question("Number, search text, or n for next page (Ctrl-C cancels): ", { signal: controller.signal }).catch((error) => {
13558
+ throw controller.signal.aborted ? controller.signal.reason : error;
13559
+ })).trim();
13560
+ if (answer.length > 1024)
13561
+ throw new Fault(400, "codex_session_search_limit", "Codex session search text must be at most 1024 characters.");
13562
+ if (/^[1-9]\d*$/.test(answer) && page.data[Number(answer) - 1])
13563
+ return finish(page.data[Number(answer) - 1].id);
13564
+ if (answer === "n") {
13565
+ if (!page.nextCursor) {
13566
+ console.error("No next page.");
13567
+ continue;
13568
+ }
13569
+ query.cursor = page.nextCursor;
13570
+ } else {
13571
+ delete query.cursor;
13572
+ query.searchTerm = answer;
13573
+ }
13574
+ page = await list(prepared, effectiveCwd, query);
13575
+ }
13576
+ } finally {
13577
+ reader.off("SIGINT", cancel);
13578
+ reader.off("close", cancel);
13579
+ process.off("SIGINT", cancel);
13580
+ process.off("SIGTERM", terminate);
13581
+ process.off("SIGHUP", hangup);
13582
+ reader.close();
13583
+ }
13584
+ }
13585
+
12863
13586
  // src/launcher.ts
12864
13587
  var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
12865
13588
  async function writeOriCodexCatalog(stateDir, models) {
12866
- const path = join19(stateDir, "ori-codex-models.json");
13589
+ const path = join20(stateDir, "ori-codex-models.json");
12867
13590
  const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
12868
13591
  await writeFile17(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
12869
13592
  `, { mode: 384, flag: "wx" });
@@ -12903,7 +13626,7 @@ async function oriRequestForPlan(plan, options = {}) {
12903
13626
  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.");
12904
13627
  if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
12905
13628
  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.");
12906
- const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve9(options.cwd) : undefined });
13629
+ const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve11(options.cwd) : undefined });
12907
13630
  const native = requireOriHarness(contract, target);
12908
13631
  if (!native.path)
12909
13632
  throw new Error("Ori did not report the native harness executable path.");
@@ -12951,13 +13674,14 @@ async function prepareOriForPlan(plan, options) {
12951
13674
  executable: detection.executable,
12952
13675
  version: detection.version,
12953
13676
  stateDir: options.stateDir,
12954
- cwd: resolve9(options.cwd ?? process.cwd()),
12955
- args: options.args ?? []
13677
+ cwd: resolve11(options.cwd ?? process.cwd()),
13678
+ args: options.args ?? [],
13679
+ sharedState: options.sharedState
12956
13680
  });
12957
13681
  try {
12958
13682
  const shim = prepareOriModelPolicy(request.target, native);
12959
- const dir = join19(options.stateDir, "ori-bin"), path = join19(dir, shim.name);
12960
- await mkdir11(dir, { mode: 448 });
13683
+ const dir = join20(options.stateDir, "ori-bin"), path = join20(dir, shim.name);
13684
+ await mkdir12(dir, { mode: 448 });
12961
13685
  await writeFile17(path, shim.script, { mode: 448, flag: "wx" });
12962
13686
  return { contract, prepared: {
12963
13687
  ...ori,
@@ -12980,7 +13704,7 @@ async function launch(client, profileId, options = {}) {
12980
13704
  assertHarnessArguments(profile.harness, options.args ?? []);
12981
13705
  if (profile.harness === "gemini" || profile.harness === "antigravity")
12982
13706
  validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
12983
- await validateHarnessConfiguration(profile.harness, resolve9(options.cwd ?? process.cwd()), options.args);
13707
+ await validateHarnessConfiguration(profile.harness, resolve11(options.cwd ?? process.cwd()), options.args);
12984
13708
  if (profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((process.env.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
12985
13709
  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.");
12986
13710
  if (profile.harness === "grok" && process.env.GROK_FORCE_LOGIN_TEAM_ID?.trim())
@@ -12989,7 +13713,7 @@ async function launch(client, profileId, options = {}) {
12989
13713
  await client.refreshModels(profile.providerId);
12990
13714
  const plan = await client.launchPlan(profileId);
12991
13715
  assertHarnessArguments(plan.profile.harness, options.args ?? []);
12992
- await validateHarnessConfiguration(plan.profile.harness, resolve9(options.cwd ?? process.cwd()), options.args);
13716
+ await validateHarnessConfiguration(plan.profile.harness, resolve11(options.cwd ?? process.cwd()), options.args);
12993
13717
  if (options.credentialPreflight && providerCredentialFingerprint(plan.provider) !== options.credentialPreflight)
12994
13718
  throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
12995
13719
  const backend = options.backend ?? "direct";
@@ -13011,9 +13735,9 @@ async function launch(client, profileId, options = {}) {
13011
13735
  validateHarnessVersion("gemini", detection?.version);
13012
13736
  if (backend === "direct" && plan.profile.harness === "aider")
13013
13737
  validateHarnessVersion(plan.profile.harness, detection?.version);
13014
- const root = resolve9(options.stateDir ?? join19(switcherHome(), "state"));
13738
+ const root = resolve11(options.stateDir ?? join20(switcherHome(), "state"));
13015
13739
  await privateDirectory(root);
13016
- const stateDir = await mkdtemp(join19(root, "launch-"));
13740
+ const stateDir = await mkdtemp(join20(root, "launch-"));
13017
13741
  let credential;
13018
13742
  if (backend === "direct") {
13019
13743
  try {
@@ -13057,6 +13781,27 @@ async function launch(client, profileId, options = {}) {
13057
13781
  return;
13058
13782
  });
13059
13783
  try {
13784
+ if (options.shareNativeState && plan.profile.harness !== "codex" && plan.profile.harness !== "claude")
13785
+ throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
13786
+ const shareRequested = (plan.profile.harness === "codex" || plan.profile.harness === "claude") && nativeStateRequested(plan.profile.harness, process.env, Boolean(options.shareNativeState));
13787
+ if (shareRequested && backend !== "direct")
13788
+ throw new Fault(400, "native_state_backend", "Shared native state currently requires the directly verified native adapter; Ori state/resume integration is not yet accepted.");
13789
+ if (shareRequested && plan.profile.harness === "codex") {
13790
+ assertHarnessArguments("codex", options.args ?? [], { reservedCodexRoots: ["sqlite_home"] });
13791
+ validateNativeStateVersion("codex", detection?.version);
13792
+ }
13793
+ const sharedState = shareRequested ? await resolveNativeState(plan.profile.harness) : undefined;
13794
+ const desktopState = profileId;
13795
+ const stateWarnings = sharedState ? ["Shared native state is explicitly enabled. Resumed conversation history uses this launch's selected provider and model; Switcher does not infer unverified original-provider provenance.", ...await legacyNativeStateWarnings(root, sharedState)] : [];
13796
+ let nativeHome2;
13797
+ if (sharedState && !options.desktop && !options.claudeDesktop) {
13798
+ const variable = sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
13799
+ const configured = process.env[variable] ? resolve11(process.env[variable]) : undefined;
13800
+ nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join20(root, "native-claude", profileId) : configured ?? sharedState.home;
13801
+ await privateDirectory(nativeHome2);
13802
+ await assertNativeInstructionOverlay(sharedState, nativeHome2);
13803
+ await projectNativeState(sharedState, nativeHome2);
13804
+ }
13060
13805
  const input = {
13061
13806
  harness: plan.profile.harness,
13062
13807
  baseUrl: plan.provider.baseUrl,
@@ -13069,9 +13814,10 @@ async function launch(client, profileId, options = {}) {
13069
13814
  onRoutingEvent,
13070
13815
  credential,
13071
13816
  stateDir,
13072
- cwd: resolve9(options.cwd ?? process.cwd())
13817
+ cwd: resolve11(options.cwd ?? process.cwd()),
13818
+ sharedState
13073
13819
  };
13074
- let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join19(root, "desktop-claude", profileId)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent })).prepared : await prepareHarnessLaunch({
13820
+ let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join20(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
13075
13821
  harness: plan.profile.harness,
13076
13822
  baseUrl: plan.provider.baseUrl,
13077
13823
  protocol: plan.provider.protocol,
@@ -13087,13 +13833,26 @@ async function launch(client, profileId, options = {}) {
13087
13833
  executable: nativeExecutable ?? detection?.executable,
13088
13834
  args: options.args ?? [],
13089
13835
  stateDir,
13090
- cwd: resolve9(options.cwd ?? process.cwd()),
13836
+ cwd: resolve11(options.cwd ?? process.cwd()),
13091
13837
  version: detection?.version,
13092
- ...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie"].includes(plan.profile.harness) ? { sessionDir: join19(root, "sessions", plan.profile.harness, profileId) } : {}
13838
+ sharedState,
13839
+ ...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie"].includes(plan.profile.harness) ? { sessionDir: join20(root, "sessions", plan.profile.harness, profileId) } : {}
13093
13840
  });
13094
13841
  cleanup = prepared.cleanup;
13842
+ prepared = { ...prepared, warnings: [...prepared.warnings, ...stateWarnings] };
13843
+ if (sharedState)
13844
+ prepared = { ...prepared, env: {
13845
+ ...prepared.env,
13846
+ ...nativeStateEnvironment(sharedState),
13847
+ ...nativeHome2 ? { [sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"]: nativeHome2 } : {}
13848
+ } };
13849
+ if (sharedState?.tool === "codex" && !options.desktop && backend === "direct" && options.args?.length) {
13850
+ const baseArgs = prepared.args.slice(0, prepared.args.length - options.args.length);
13851
+ const resumedArgs = await resolveCodexResumeArguments({ ...prepared, args: baseArgs }, options.args, input.cwd);
13852
+ prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
13853
+ }
13095
13854
  if (options.desktop) {
13096
- prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join19(root, "desktop", profileId));
13855
+ prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join20(root, "desktop", desktopState), sharedState);
13097
13856
  cleanup = prepared.cleanup;
13098
13857
  }
13099
13858
  for (const warning of [...plan.warnings, ...prepared.warnings])
@@ -13170,7 +13929,7 @@ async function launch(client, profileId, options = {}) {
13170
13929
  interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
13171
13930
  throw preparationSignal;
13172
13931
  }
13173
- const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve9(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
13932
+ const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve11(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
13174
13933
  await cleanup?.();
13175
13934
  cleanup = undefined;
13176
13935
  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}.`);
@@ -13187,8 +13946,8 @@ async function launch(client, profileId, options = {}) {
13187
13946
  } finally {
13188
13947
  if (lateCreateRunFinalization) {
13189
13948
  let finalizationTimer;
13190
- const finalizationTimeout = new Promise((resolve10) => {
13191
- finalizationTimer = setTimeout(resolve10, LATE_RUN_FINALIZATION_TIMEOUT_MS);
13949
+ const finalizationTimeout = new Promise((resolve12) => {
13950
+ finalizationTimer = setTimeout(resolve12, LATE_RUN_FINALIZATION_TIMEOUT_MS);
13192
13951
  });
13193
13952
  try {
13194
13953
  await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
@@ -13208,7 +13967,7 @@ async function launch(client, profileId, options = {}) {
13208
13967
 
13209
13968
  // src/direct-launch.ts
13210
13969
  import { createHash as createHash14 } from "crypto";
13211
- import { createInterface as createInterface2 } from "readline/promises";
13970
+ import { createInterface as createInterface3 } from "readline/promises";
13212
13971
  var absent2 = (error) => error instanceof SwitcherError && error.status === 404;
13213
13972
  async function resolveLaunchProvider(client, selector, options = {}) {
13214
13973
  let existing;
@@ -13253,7 +14012,7 @@ async function selectModel(models, query = "", harness) {
13253
14012
  const eligible = models.filter((m) => harness ? harnessEligible(m, harness) : codingEligible(m));
13254
14013
  if (!eligible.length)
13255
14014
  throw new Fault(422, "model_missing", "This provider has no models eligible for coding in its current catalog.");
13256
- const reader = createInterface2({ input: process.stdin, output: process.stderr });
14015
+ const reader = createInterface3({ input: process.stdin, output: process.stderr });
13257
14016
  const cancellation = new AbortController;
13258
14017
  const cancel = () => cancellation.abort(new CommandInterrupted(130, "Model selection was cancelled; no harness was started."));
13259
14018
  const terminate = () => cancellation.abort(new CommandInterrupted(143, "Model selection was interrupted; no harness was started."));
@@ -13311,14 +14070,343 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
13311
14070
  return existing;
13312
14071
  }
13313
14072
 
14073
+ // src/native-state-import.ts
14074
+ import { createHash as createHash15 } from "crypto";
14075
+ import { constants as constants8 } from "fs";
14076
+ import { lstat as lstat9, open as open5, opendir as opendir2, link as link2, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
14077
+ import { basename as basename4, dirname as dirname10, isAbsolute as isAbsolute17, join as join21, relative as relative6, resolve as resolve12 } from "path";
14078
+ var MAX_FILES = 1e5;
14079
+ var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
14080
+ 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.");
14081
+ async function info2(path) {
14082
+ try {
14083
+ return await lstat9(path);
14084
+ } catch (error) {
14085
+ if (error.code === "ENOENT")
14086
+ return;
14087
+ throw error;
14088
+ }
14089
+ }
14090
+ var identity = (s) => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs, ctimeMs: s.ctimeMs });
14091
+ var same = (a, b) => JSON.stringify(identity(a)) === JSON.stringify(identity(b));
14092
+ var inside3 = (parent, child) => {
14093
+ const path = relative6(parent, child);
14094
+ return path !== ".." && !path.startsWith("../") && !isAbsolute17(path);
14095
+ };
14096
+ var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
14097
+ async function sessionId(path, expected) {
14098
+ const nameId = basename4(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
14099
+ const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
14100
+ try {
14101
+ const before = await handle.stat();
14102
+ if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
14103
+ throw refused();
14104
+ const buffer = Buffer.alloc(Math.min(before.size, 1024 * 1024));
14105
+ let length = 0, newline = -1;
14106
+ while (length < buffer.length && newline < 0) {
14107
+ const read = await handle.read(buffer, length, buffer.length - length, null);
14108
+ if (!read.bytesRead)
14109
+ break;
14110
+ length += read.bytesRead;
14111
+ newline = buffer.indexOf(10, 0);
14112
+ }
14113
+ const after = await handle.stat(), named = await lstat9(path);
14114
+ if (!same(before, after) || !same(after, named) || after.nlink !== 1 || named.nlink !== 1 || named.isSymbolicLink())
14115
+ throw refused();
14116
+ if (newline < 0 && before.size > buffer.length)
14117
+ throw refused();
14118
+ let row;
14119
+ try {
14120
+ row = JSON.parse(buffer.subarray(0, newline < 0 ? length : newline).toString("utf8"));
14121
+ } catch {
14122
+ return nameId;
14123
+ }
14124
+ if (row && typeof row === "object" && "type" in row && row.type === "session_meta") {
14125
+ const value = row.payload?.id;
14126
+ if (typeof value !== "string" || !SESSION_ID.test(value) || nameId && value.toLowerCase() !== nameId)
14127
+ throw refused();
14128
+ return value.toLowerCase();
14129
+ }
14130
+ return nameId;
14131
+ } finally {
14132
+ await handle.close();
14133
+ }
14134
+ }
14135
+ async function checkSessionIdentities(plan) {
14136
+ if (plan.state.tool !== "codex")
14137
+ return;
14138
+ const ids = new Map;
14139
+ for (const file of plan.files) {
14140
+ if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
14141
+ continue;
14142
+ file.sessionId = await sessionId(join21(plan.source, file.path), file.source);
14143
+ if (!file.sessionId)
14144
+ continue;
14145
+ const previous = ids.get(file.sessionId);
14146
+ if (previous?.some((other) => other.sha256 !== file.sha256))
14147
+ throw refused();
14148
+ if (previous) {
14149
+ file.existing = true;
14150
+ previous.push(file);
14151
+ } else
14152
+ ids.set(file.sessionId, [file]);
14153
+ }
14154
+ if (!ids.size)
14155
+ return;
14156
+ let seen = 0;
14157
+ async function scan(directory, depth = 0) {
14158
+ if (++seen > MAX_FILES || depth > 32)
14159
+ throw refused();
14160
+ if (!await info2(directory))
14161
+ return;
14162
+ await assertNativeStateDirectory(directory);
14163
+ for await (const entry of await opendir2(directory)) {
14164
+ if (++seen > MAX_FILES || entry.isSymbolicLink())
14165
+ throw refused();
14166
+ const path = join21(directory, entry.name);
14167
+ if (entry.isDirectory()) {
14168
+ await scan(path, depth + 1);
14169
+ continue;
14170
+ }
14171
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl"))
14172
+ continue;
14173
+ const id2 = await sessionId(path);
14174
+ if (!id2 || !ids.has(id2))
14175
+ continue;
14176
+ const existing = await fingerprint2(path), importing = ids.get(id2);
14177
+ if (importing.some((file) => file.sha256 !== existing.sha256))
14178
+ throw refused();
14179
+ for (const file of importing)
14180
+ file.existing = true;
14181
+ }
14182
+ }
14183
+ await scan(join21(plan.state.home, "sessions"));
14184
+ await scan(join21(plan.state.home, "archived_sessions"));
14185
+ }
14186
+ async function fingerprint2(path, copyTo) {
14187
+ const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
14188
+ let output, complete = false;
14189
+ try {
14190
+ const before = await handle.stat();
14191
+ if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
14192
+ throw refused();
14193
+ if (copyTo)
14194
+ output = await open5(copyTo, "wx", 384);
14195
+ const hash3 = createHash15("sha256"), buffer = Buffer.alloc(64 * 1024);
14196
+ let bytes = 0;
14197
+ for (;; ) {
14198
+ const read = await handle.read(buffer, 0, buffer.length, null);
14199
+ if (!read.bytesRead)
14200
+ break;
14201
+ bytes += read.bytesRead;
14202
+ if (bytes > MAX_BYTES2)
14203
+ throw refused();
14204
+ const chunk = buffer.subarray(0, read.bytesRead);
14205
+ hash3.update(chunk);
14206
+ if (output) {
14207
+ let offset = 0;
14208
+ while (offset < chunk.length)
14209
+ offset += (await output.write(chunk, offset, chunk.length - offset)).bytesWritten;
14210
+ }
14211
+ }
14212
+ const after = await handle.stat(), named = await lstat9(path);
14213
+ if (named.isSymbolicLink() || after.nlink !== 1 || named.nlink !== 1 || bytes !== before.size || !same(before, after) || !same(after, named))
14214
+ throw refused();
14215
+ await output?.sync();
14216
+ complete = true;
14217
+ return { bytes, sha256: hash3.digest("hex"), source: identity(before) };
14218
+ } finally {
14219
+ await output?.close();
14220
+ await handle.close();
14221
+ if (copyTo && !complete)
14222
+ await unlink3(copyTo).catch(() => {
14223
+ return;
14224
+ });
14225
+ }
14226
+ }
14227
+ async function planNativeStateImport(state, source, selection) {
14228
+ if (!isAbsolute17(source) || source.includes("\x00"))
14229
+ throw refused();
14230
+ source = resolve12(source);
14231
+ if (inside3(source, state.home) || inside3(state.home, source))
14232
+ throw refused();
14233
+ await assertNativeStateDirectory(source);
14234
+ await ensureNativeStateDirectory(state.home, false);
14235
+ const allowed = NATIVE_STATE_ENTRIES[state.tool].filter((entry) => entry.name !== "thread-writer-locks");
14236
+ const entries = selection?.length ? [...new Set(selection)] : allowed.map((entry) => entry.name);
14237
+ if (entries.some((name) => !allowed.some((entry) => entry.name === name)))
14238
+ throw refused();
14239
+ const plan = { state, source, entries, files: [], directories: [], bytes: 0 };
14240
+ let seen = 0;
14241
+ async function visit(path, kind) {
14242
+ if (++seen > MAX_FILES || path.split("/").length > 32)
14243
+ throw refused();
14244
+ await ensureNativeStateDirectory(dirname10(join21(source, path)), false);
14245
+ await ensureNativeStateDirectory(dirname10(join21(state.home, path)), false);
14246
+ const from = join21(source, path), to = join21(state.home, path), entry = await info2(from), target = await info2(to);
14247
+ if (!entry)
14248
+ return;
14249
+ if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
14250
+ throw refused();
14251
+ if (kind === "directory") {
14252
+ await assertNativeStateDirectory(from);
14253
+ if (target)
14254
+ await assertNativeStateDirectory(to);
14255
+ plan.directories.push(path);
14256
+ const directory = await opendir2(from);
14257
+ const children = [];
14258
+ for await (const child of directory) {
14259
+ if (children.length + seen >= MAX_FILES || child.isSymbolicLink() || !(child.isDirectory() || child.isFile()))
14260
+ throw refused();
14261
+ children.push({ name: child.name, kind: child.isDirectory() ? "directory" : "file" });
14262
+ }
14263
+ children.sort((a, b) => a.name.localeCompare(b.name));
14264
+ for (const child of children)
14265
+ await visit(join21(path, child.name), child.kind);
14266
+ } else {
14267
+ const value = await fingerprint2(from);
14268
+ plan.bytes += value.bytes;
14269
+ if (plan.bytes > MAX_BYTES2)
14270
+ throw refused();
14271
+ if (target && (target.isSymbolicLink() || !target.isFile()))
14272
+ throw refused();
14273
+ if (target) {
14274
+ const existing = await fingerprint2(to);
14275
+ if (existing.bytes !== value.bytes || existing.sha256 !== value.sha256)
14276
+ throw refused();
14277
+ }
14278
+ plan.files.push({ path, ...value, existing: Boolean(target) });
14279
+ }
14280
+ }
14281
+ for (const name of entries)
14282
+ await visit(name, allowed.find((entry) => entry.name === name).kind);
14283
+ await checkSessionIdentities(plan);
14284
+ return plan;
14285
+ }
14286
+ function nativeStateImportDigest(plan) {
14287
+ return createHash15("sha256").update(JSON.stringify({
14288
+ tool: plan.state.tool,
14289
+ source: plan.source,
14290
+ destination: plan.state.home,
14291
+ entries: plan.entries,
14292
+ directories: plan.directories,
14293
+ files: plan.files.map((file) => ({ path: file.path, bytes: file.bytes, sha256: file.sha256, source: file.source, existing: file.existing, sessionId: file.sessionId }))
14294
+ })).digest("hex");
14295
+ }
14296
+ function nativeStateImportSummary(plan, applied) {
14297
+ const newFiles = plan.files.filter((file) => !file.existing).length;
14298
+ return {
14299
+ mode: applied ? "staged-snapshot" : "dry-run",
14300
+ tool: plan.state.tool,
14301
+ entries: plan.entries,
14302
+ planDigest: nativeStateImportDigest(plan),
14303
+ files: plan.files.length,
14304
+ newFiles,
14305
+ publishedFiles: applied ? newFiles : 0,
14306
+ bytes: plan.bytes,
14307
+ originalsPreserved: true,
14308
+ cutoverComplete: false,
14309
+ sqliteCopied: false,
14310
+ notice: "The original can still receive writes. This copy is not a completed migration. Legacy SQLite/index metadata and login data remain in the original directory; Codex discovery repairs the catalog from copied transcripts."
14311
+ };
14312
+ }
14313
+ async function applyNativeStateImportUnlocked(plan) {
14314
+ const fresh = await planNativeStateImport(plan.state, plan.source, plan.entries);
14315
+ if (JSON.stringify(fresh) !== JSON.stringify(plan))
14316
+ throw refused();
14317
+ const requiredDirectories = new Set([plan.state.home]);
14318
+ for (const path of plan.directories) {
14319
+ for (let directory = join21(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname10(directory)) {
14320
+ requiredDirectories.add(directory);
14321
+ if (directory === plan.state.home)
14322
+ break;
14323
+ }
14324
+ }
14325
+ for (const file of plan.files.filter((file2) => !file2.existing)) {
14326
+ for (let directory = dirname10(join21(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname10(directory)) {
14327
+ requiredDirectories.add(directory);
14328
+ if (directory === plan.state.home)
14329
+ break;
14330
+ }
14331
+ }
14332
+ const directories = [...requiredDirectories].sort((a, b) => a.length - b.length), createdDirectories = [];
14333
+ const staged = [];
14334
+ let published = 0;
14335
+ let committed = false, cleanupFailed = false;
14336
+ try {
14337
+ for (const directory of directories) {
14338
+ if (!await info2(directory)) {
14339
+ await ensureNativeStateDirectory(directory);
14340
+ createdDirectories.push(directory);
14341
+ } else
14342
+ await assertNativeStateDirectory(directory);
14343
+ }
14344
+ for (const file of plan.files) {
14345
+ if (file.existing)
14346
+ continue;
14347
+ const target = join21(plan.state.home, file.path), temporary = join21(dirname10(target), `.switcher-import-${crypto.randomUUID()}`);
14348
+ staged.push({ temporary, target });
14349
+ const copied = await fingerprint2(join21(plan.source, file.path), temporary);
14350
+ if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
14351
+ throw refused();
14352
+ }
14353
+ for (const item2 of staged) {
14354
+ try {
14355
+ await link2(item2.temporary, item2.target);
14356
+ published++;
14357
+ } catch (error) {
14358
+ if (published)
14359
+ throw new Fault(409, "native_state_import_partial", `Native state import published ${published} reviewed file(s) before a racing destination appeared. Existing and published data was preserved. Run a new dry-run to reconcile the remainder.`);
14360
+ throw error;
14361
+ }
14362
+ }
14363
+ committed = true;
14364
+ } finally {
14365
+ for (const item2 of staged) {
14366
+ try {
14367
+ await unlink3(item2.temporary);
14368
+ } catch (error) {
14369
+ if (error.code !== "ENOENT")
14370
+ cleanupFailed = true;
14371
+ }
14372
+ }
14373
+ if (!committed && published === 0) {
14374
+ for (const directory of createdDirectories.sort((a, b) => b.length - a.length)) {
14375
+ try {
14376
+ await rmdir2(directory);
14377
+ } catch (error) {
14378
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
14379
+ cleanupFailed = true;
14380
+ }
14381
+ }
14382
+ }
14383
+ if (cleanupFailed)
14384
+ throw new Fault(500, "native_state_import_recovery", "Native state import cleanup was incomplete. Existing data was not intentionally replaced; inspect the destination for .switcher-import files before retrying.");
14385
+ }
14386
+ }
14387
+ async function applyNativeStateImport(plan) {
14388
+ const existed = Boolean(await info2(plan.state.home));
14389
+ await ensureNativeStateDirectory(plan.state.home);
14390
+ try {
14391
+ return await withNativeStateLock(plan.state, () => applyNativeStateImportUnlocked(plan));
14392
+ } catch (error) {
14393
+ if (!existed)
14394
+ await rmdir2(plan.state.home).catch(() => {
14395
+ return;
14396
+ });
14397
+ throw error;
14398
+ }
14399
+ }
14400
+
13314
14401
  // src/cli.ts
13315
14402
  var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your provider and model
13316
14403
 
13317
14404
  switcher launch chatgpt --provider PROVIDER --model MODEL [--reasoning EFFORT]
13318
- [--dangerously-bypass-approvals-and-sandbox] [--app-path /absolute/ChatGPT.app]
14405
+ [--dangerously-bypass-approvals-and-sandbox] [--share-native-state]
14406
+ [--app-path /absolute/ChatGPT.app]
13319
14407
  [--dry-run] [--cwd DIR] [--timeout SECONDS]
13320
14408
  switcher launch claude-desktop --provider PROVIDER --model MODEL
13321
- [--app-path /absolute/Claude.app] [--dry-run]
14409
+ [--share-native-state] [--app-path /absolute/Claude.app] [--dry-run]
13322
14410
  switcher providers presets [ID]
13323
14411
  switcher providers list [--search TEXT] [--limit N] [--offset N]
13324
14412
  switcher providers add ID --url URL --protocol PROTOCOL [--credential-env NAME]
@@ -13336,8 +14424,8 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
13336
14424
  switcher profiles add ID --provider ID --harness HARNESS --model MODEL [--model-policy-file FILE] [--role-model ROLE=MODEL]
13337
14425
  switcher profiles update ID --file profile.json --version N
13338
14426
  switcher profiles delete ID --version N
13339
- switcher launch HARNESS --provider PROVIDER [--model MODEL] [--dry-run]
13340
- switcher launch PROFILE [--backend direct|ori] [--cwd DIR] [--executable PATH]
14427
+ switcher launch HARNESS --provider PROVIDER [--model MODEL] [--share-native-state] [--dry-run]
14428
+ switcher launch PROFILE [--backend direct|ori] [--share-native-state] [--cwd DIR] [--executable PATH]
13341
14429
  [--ori-executable PATH] [--state-dir DIR]
13342
14430
  [--timeout SECONDS] -- [native harness arguments]
13343
14431
  switcher runs list|get [ID]
@@ -13348,9 +14436,11 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
13348
14436
  switcher credentials repair-executable PRESET_OR_REFERENCE --sha256 EXPECTED
13349
14437
  switcher credentials repair-executable --vault-cli PATH --sha256 EXPECTED
13350
14438
  switcher doctor
14439
+ switcher state import codex|claude --from LEGACY_NATIVE_HOME [--entry NAME]... [--dry-run | --apply --plan-digest SHA256]
13351
14440
 
13352
14441
  HARNESS: claude, codex, grok, opencode, opencode2, pi, omp, dsh, cline, hermes, prime-agent, gemini, antigravity, junie, aider, kilo
13353
- chatgpt launches the installed macOS desktop app in an isolated provider profile.
14442
+ chatgpt launches the installed macOS desktop app with private login data.
14443
+ Use --share-native-state to project the canonical noncredential Codex/Claude corpus.
13354
14444
  Its local Codex conversations use the selected Responses-compatible provider.
13355
14445
  claude-desktop launches Claude in its separate Claude-3p gateway profile with a
13356
14446
  Messages-compatible provider. Quit that instance before switching providers.
@@ -13436,6 +14526,11 @@ async function main(args = process.argv.slice(2)) {
13436
14526
  "app-path": { type: "string" },
13437
14527
  reasoning: { type: "string" },
13438
14528
  "dangerously-bypass-approvals-and-sandbox": { type: "boolean" },
14529
+ "share-native-state": { type: "boolean" },
14530
+ from: { type: "string" },
14531
+ entry: { type: "string", multiple: true },
14532
+ apply: { type: "boolean" },
14533
+ "plan-digest": { type: "string" },
13439
14534
  protocol: { type: "string" },
13440
14535
  preset: { type: "string" },
13441
14536
  name: { type: "string" },
@@ -13481,12 +14576,30 @@ async function main(args = process.argv.slice(2)) {
13481
14576
  }
13482
14577
  const [command, action2, id2] = positionals;
13483
14578
  const output = (value) => console.log(JSON.stringify(value, null, 2));
14579
+ if (command === "state") {
14580
+ if (action2 !== "import" || !["codex", "claude"].includes(id2) || !values2.from || positionals.length !== 3 || nativeArgs.length || Object.keys(values2).some((key) => !["from", "entry", "apply", "plan-digest", "dry-run", "json"].includes(key)) || values2.apply && values2["dry-run"] || Boolean(values2.apply) !== Boolean(values2["plan-digest"]) || values2["plan-digest"] !== undefined && !/^[a-f0-9]{64}$/.test(values2["plan-digest"]))
14581
+ throw new Fault(400, "invalid_request", "Use switcher state import codex|claude --from LEGACY_NATIVE_HOME [--entry NAME]... [--dry-run | --apply --plan-digest SHA256]. The default is a read-only dry run.");
14582
+ const state = await resolveNativeState(id2, process.env, { create: false });
14583
+ const plan = await planNativeStateImport(state, values2.from, values2.entry);
14584
+ if (values2.apply && values2["plan-digest"] !== nativeStateImportDigest(plan))
14585
+ throw new Fault(409, "native_state_plan_mismatch", "The reviewed native-state plan no longer matches this source, destination or selection. Run a new dry-run and review its plan digest.");
14586
+ if (values2.apply)
14587
+ await applyNativeStateImport(plan);
14588
+ output(nativeStateImportSummary(plan, Boolean(values2.apply)));
14589
+ return;
14590
+ }
14591
+ if (values2.from !== undefined || values2.entry !== undefined || values2.apply !== undefined || values2["plan-digest"] !== undefined)
14592
+ throw new Fault(400, "conflicting_options", "--from, --entry, --plan-digest, --dry-run and --apply belong to switcher state import.");
14593
+ if (values2["share-native-state"] && command !== "launch")
14594
+ throw new Fault(400, "conflicting_options", "--share-native-state belongs to a Codex, ChatGPT, Claude CLI or Claude desktop launch.");
13484
14595
  const reasoning = values2.reasoning === undefined ? undefined : parse2(reasoningEffortSchema, values2.reasoning);
13485
14596
  const dangerouslyBypassApprovalsAndSandbox = values2["dangerously-bypass-approvals-and-sandbox"];
13486
14597
  if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" || values2.provider && !["chatgpt", "codex"].includes(action2) || values2.backend && values2.backend !== "direct"))
13487
14598
  throw new Fault(400, "conflicting_options", "--reasoning and --dangerously-bypass-approvals-and-sandbox require a direct Codex or ChatGPT launch.");
13488
14599
  const chatgpt = command === "launch" && action2 === "chatgpt" && values2.provider !== undefined;
13489
14600
  const claudeDesktop = command === "launch" && action2 === "claude-desktop" && values2.provider !== undefined;
14601
+ if (values2["share-native-state"] && values2.provider !== undefined && !["codex", "claude", "chatgpt", "claude-desktop"].includes(action2))
14602
+ throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
13490
14603
  if (values2["app-path"] !== undefined && !chatgpt && !claudeDesktop)
13491
14604
  throw new Fault(400, "conflicting_options", "--app-path belongs to launch chatgpt or claude-desktop --provider PROVIDER --model MODEL.");
13492
14605
  if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 || values2.executable !== undefined || values2.backend !== undefined || values2["ori-executable"] !== undefined))
@@ -13692,6 +14805,8 @@ async function main(args = process.argv.slice(2)) {
13692
14805
  if (values2.model || values2.protocol || values2.url || values2["credential-env"] || values2["model-policy-file"] || values2["role-model"])
13693
14806
  throw new Error("Use --provider PROVIDER for a direct launch, or update the saved profile explicitly.");
13694
14807
  const profile = await client.getProfile(profileId);
14808
+ if (values2["share-native-state"] && !["codex", "claude"].includes(profile.harness))
14809
+ throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
13695
14810
  assertHarnessArguments(profile.harness, nativeArgs);
13696
14811
  await validateHarnessConfiguration(profile.harness, values2.cwd ?? process.cwd(), nativeArgs);
13697
14812
  const provider = await client.getProvider(profile.providerId);
@@ -13718,14 +14833,24 @@ async function main(args = process.argv.slice(2)) {
13718
14833
  codexReasoning(model3, plan.provider.baseUrl, reasoning);
13719
14834
  }
13720
14835
  assertHarnessArguments(plan.profile.harness, nativeArgs);
14836
+ if (values2["share-native-state"] && !["codex", "claude"].includes(plan.profile.harness))
14837
+ throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
14838
+ const sharedNativeState = ["codex", "claude"].includes(plan.profile.harness) && nativeStateRequested(plan.profile.harness, process.env, Boolean(values2["share-native-state"]));
14839
+ if (sharedNativeState) {
14840
+ if (plan.profile.harness === "codex")
14841
+ assertHarnessArguments("codex", nativeArgs, { reservedCodexRoots: ["sqlite_home"] });
14842
+ await resolveNativeState(plan.profile.harness, process.env, { create: false });
14843
+ }
13721
14844
  if (backend === "ori") {
14845
+ if (sharedNativeState)
14846
+ throw new Fault(400, "native_state_backend", "Shared native state currently requires the directly verified native adapter; Ori state/resume integration is not yet accepted.");
13722
14847
  const { contract, warnings } = await validateOriForPlan(plan, { oriExecutable: values2["ori-executable"], args: nativeArgs, cwd: values2.cwd });
13723
- output({ ...plan, backend: { kind: "ori", executable: contract.executable, version: contract.version, target: plan.profile.harness, provider: "openrouter", model: plan.profile.model, warnings: [...plan.warnings, ...warnings] } });
14848
+ output({ ...plan, backend: { kind: "ori", executable: contract.executable, version: contract.version, target: plan.profile.harness, provider: "openrouter", model: plan.profile.model, warnings: [...plan.warnings, ...warnings] }, ...sharedNativeState ? { nativeState: { shared: true, consent: values2["share-native-state"] ? "command" : "environment" } } : {} });
13724
14849
  } else
13725
- output({ ...plan, ...desktop ? { desktop: { ...desktop, mode: "isolated-provider", sessionProfile: profileId } } : {}, ...claudeApp ? { desktop: { ...claudeApp, mode: "claude-3p-gateway", sessionProfile: profileId } } : {}, ...reasoning ? { reasoning } : {}, ...dangerouslyBypassApprovalsAndSandbox ? { permissions: { approvalPolicy: "never", sandboxMode: "danger-full-access" } } : {} });
14850
+ output({ ...plan, ...desktop ? { desktop: { ...desktop, mode: sharedNativeState ? "shared-state-private-auth" : "isolated-provider", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...claudeApp ? { desktop: { ...claudeApp, mode: "claude-3p-gateway", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...sharedNativeState ? { nativeState: { shared: true, consent: values2["share-native-state"] ? "command" : "environment" } } : {}, ...reasoning ? { reasoning } : {}, ...dangerouslyBypassApprovalsAndSandbox ? { permissions: { approvalPolicy: "never", sandboxMode: "danger-full-access" } } : {} });
13726
14851
  return;
13727
14852
  }
13728
- process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)) });
14853
+ process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, shareNativeState: Boolean(values2["share-native-state"]), reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)) });
13729
14854
  return;
13730
14855
  }
13731
14856
  if (editingModel) {