@hasna/switcher 0.2.7 → 0.2.9

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
@@ -513,9 +513,13 @@ var routingEventsSchema = z3.array(routingEventSchema).max(1000);
513
513
  function canonicalPolicyJSON(value) {
514
514
  return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
515
515
  }
516
+ // package.json
517
+ var version = "0.2.9";
518
+
519
+ // src/version.ts
520
+ var VERSION = version;
516
521
 
517
522
  // src/domain.ts
518
- var VERSION = "0.2.7";
519
523
  var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "antigravity", "junie", "aider", "kilo"]);
520
524
  var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
521
525
  var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
@@ -911,7 +915,66 @@ var short = {
911
915
  "prime-agent": { required: "p", optional: "", boolean: "hv" },
912
916
  gemini: { required: "mpieo", optional: "rw", boolean: "shvydl" }
913
917
  };
914
- var providerKeys = new Set(["model", "model_provider", "model_providers", "model_catalog_json", "review_model", "agents", "memories"]);
918
+ var providerKeys = new Set(["model", "model_provider", "provider", "model_providers", "model_catalog_json", "review_model", "agents", "memories"]);
919
+ function codexOptionTakesValue(option) {
920
+ return values.codex.includes(option) || option.length === 2 && option[0] === "-" && short.codex.required.includes(option[1]);
921
+ }
922
+ function codexOptionRequestsHelp(option) {
923
+ if (["--help", "--version", "-h", "-V"].includes(option))
924
+ return true;
925
+ if (!/^-[^-]/.test(option))
926
+ return false;
927
+ for (let index = 1;index < option.length; index++) {
928
+ const name = option[index];
929
+ if (name === "h" || name === "V")
930
+ return true;
931
+ if (short.codex.required.includes(name))
932
+ return false;
933
+ }
934
+ return false;
935
+ }
936
+ function codexConfigPath(key) {
937
+ if (key.length > 4096 || /[\r\n\0]/.test(key))
938
+ throw new Error("Invalid Codex configuration key.");
939
+ let value = Bun.TOML.parse(`${key} = 0`);
940
+ const path = [];
941
+ while (value !== 0) {
942
+ if (value === null || typeof value !== "object" || Array.isArray(value))
943
+ throw new Error("Invalid Codex configuration key.");
944
+ const entries = Object.entries(value);
945
+ if (entries.length !== 1)
946
+ throw new Error("Ambiguous Codex configuration key.");
947
+ path.push(entries[0][0]);
948
+ value = entries[0][1];
949
+ }
950
+ if (!path.length)
951
+ throw new Error("Invalid Codex configuration key.");
952
+ return path;
953
+ }
954
+ function codexConfigRoots(key) {
955
+ return [codexConfigPath(key)[0]];
956
+ }
957
+ function codexCommandIndex(args) {
958
+ for (let i = 0;i < args.length; i++) {
959
+ const arg = args[i];
960
+ if (arg === "--")
961
+ return -1;
962
+ if (!arg.startsWith("-"))
963
+ return i;
964
+ if (arg.startsWith("--")) {
965
+ if (!arg.includes("=") && values.codex.includes(arg))
966
+ i++;
967
+ continue;
968
+ }
969
+ for (let j = 1;j < arg.length; j++)
970
+ if (short.codex.required.includes(arg[j])) {
971
+ if (j === arg.length - 1)
972
+ i++;
973
+ break;
974
+ }
975
+ }
976
+ return -1;
977
+ }
915
978
  function geminiPolicyArguments(input, originalHome) {
916
979
  const args = [...input], expand = (value) => value.split(",").map((part) => {
917
980
  const path = part.trim();
@@ -944,9 +1007,9 @@ function geminiPolicyArguments(input, originalHome) {
944
1007
  function codexProviderOverride(value) {
945
1008
  const key = value.slice(0, value.indexOf("=") < 0 ? value.length : value.indexOf("=")).trim();
946
1009
  try {
947
- return Object.keys(Bun.TOML.parse(`${key} = 0`)).some((root) => providerKeys.has(root));
1010
+ return codexConfigRoots(key).some((root) => providerKeys.has(root));
948
1011
  } catch {
949
- return /^(model|model_provider|model_providers|model_catalog_json|review_model|agents|memories)(?:\s*\.|\s*$)/.test(key);
1012
+ return /^(model|model_provider|provider|model_providers|model_catalog_json|review_model|agents|memories)(?:\s*\.|\s*$)/.test(key);
950
1013
  }
951
1014
  }
952
1015
  function assertHarnessArguments(harness, args, options = {}) {
@@ -977,7 +1040,16 @@ function assertHarnessArguments(harness, args, options = {}) {
977
1040
  }
978
1041
  }
979
1042
  const config = (value) => {
980
- if (harness === "codex" && (options.reserveCodexConfig || codexProviderOverride(value)))
1043
+ if (harness !== "codex")
1044
+ return;
1045
+ const key = value.slice(0, value.indexOf("=") < 0 ? value.length : value.indexOf("=")).trim();
1046
+ let reserved3 = false;
1047
+ try {
1048
+ reserved3 = codexConfigRoots(key).some((root) => options.reservedCodexRoots?.includes(root));
1049
+ } catch {
1050
+ reserved3 = Boolean(options.reservedCodexRoots?.some((root) => new RegExp(`^${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s*\\.|\\s*$)`).test(key)));
1051
+ }
1052
+ if (options.reserveCodexConfig || codexProviderOverride(value) || reserved3)
981
1053
  reject();
982
1054
  };
983
1055
  let hermesChat = false;
@@ -1296,12 +1368,12 @@ async function detectChatGPTApp(appPath, system = host) {
1296
1368
  const bundleId = await field("CFBundleIdentifier");
1297
1369
  if (bundleId !== "com.openai.codex")
1298
1370
  continue;
1299
- const name = await field("CFBundleExecutable"), version = await field("CFBundleShortVersionString");
1371
+ const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
1300
1372
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
1301
1373
  continue;
1302
1374
  const executable = join3(path, "Contents/MacOS", name), codexExecutable = join3(path, "Contents/Resources/codex");
1303
1375
  if (await system.executable(executable) && await system.executable(codexExecutable))
1304
- return { path, executable, codexExecutable, bundleId, version };
1376
+ return { path, executable, codexExecutable, bundleId, version: version2 };
1305
1377
  } catch {}
1306
1378
  }
1307
1379
  throw new Fault(404, "app_not_installed", "Install the current ChatGPT/Codex macOS app or use --app-path with its absolute .app path. Legacy ChatGPT Classic cannot run custom Codex providers.");
@@ -1324,12 +1396,12 @@ async function detectClaudeDesktopApp(appPath, system = host) {
1324
1396
  const bundleId = await field("CFBundleIdentifier");
1325
1397
  if (bundleId !== "com.anthropic.claudefordesktop")
1326
1398
  continue;
1327
- const name = await field("CFBundleExecutable"), version = await field("CFBundleShortVersionString");
1399
+ const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
1328
1400
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
1329
1401
  continue;
1330
1402
  const executable = join3(path, "Contents/MacOS", name);
1331
1403
  if (await system.executable(executable))
1332
- return { path, executable, bundleId, version };
1404
+ return { path, executable, bundleId, version: version2 };
1333
1405
  } catch {}
1334
1406
  }
1335
1407
  throw new Fault(404, "app_not_installed", "Install the current Claude macOS desktop app or supply its absolute .app path with --app-path.");
@@ -1475,17 +1547,17 @@ class SwitcherClient {
1475
1547
  createProvider(input, idempotencyKey) {
1476
1548
  return this.request("POST", "/v1/providers", input, { idempotencyKey });
1477
1549
  }
1478
- updateProvider(input, version, idempotencyKey) {
1479
- return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
1550
+ updateProvider(input, version2, idempotencyKey) {
1551
+ return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
1480
1552
  }
1481
- deleteProvider(id, version, idempotencyKey) {
1482
- return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
1553
+ deleteProvider(id, version2, idempotencyKey) {
1554
+ return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
1483
1555
  }
1484
1556
  async editModel(providerId, operation, value) {
1485
1557
  const model = typeof value === "string" ? undefined : parse2(modelSchema, value);
1486
1558
  const id = model?.id ?? parse2(modelSchema.shape.id, value);
1487
1559
  const provider = await this.getProvider(providerId);
1488
- const { version, updatedAt, ...input } = provider;
1560
+ const { version: version2, updatedAt, ...input } = provider;
1489
1561
  const manual = provider.manualModels.some((item) => item.id === id);
1490
1562
  const additional = (provider.additionalModels ?? []).some((item) => item.id === id);
1491
1563
  if (operation === "add" && (manual || additional))
@@ -1497,7 +1569,7 @@ class SwitcherClient {
1497
1569
  const additionalModels = (provider.additionalModels ?? []).filter((item) => item.id !== id);
1498
1570
  if (operation !== "remove")
1499
1571
  (useManual ? manualModels : additionalModels).push(model);
1500
- return this.updateProvider({ ...input, manualModels, additionalModels }, version);
1572
+ return this.updateProvider({ ...input, manualModels, additionalModels }, version2);
1501
1573
  }
1502
1574
  addModel(providerId, model) {
1503
1575
  return this.editModel(providerId, "add", model);
@@ -1526,11 +1598,11 @@ class SwitcherClient {
1526
1598
  createProfile(input, idempotencyKey) {
1527
1599
  return this.request("POST", "/v1/profiles", input, { idempotencyKey });
1528
1600
  }
1529
- updateProfile(input, version, idempotencyKey) {
1530
- return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
1601
+ updateProfile(input, version2, idempotencyKey) {
1602
+ return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
1531
1603
  }
1532
- deleteProfile(id, version, idempotencyKey) {
1533
- return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
1604
+ deleteProfile(id, version2, idempotencyKey) {
1605
+ return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
1534
1606
  }
1535
1607
  launchPlan(profileId, idempotencyKey) {
1536
1608
  return this.request("POST", "/v1/launch-plans", { profileId }, { idempotencyKey });
@@ -1544,8 +1616,8 @@ class SwitcherClient {
1544
1616
  createRun(input, idempotencyKey) {
1545
1617
  return this.request("POST", "/v1/runs", { ...input, modelPolicyVersion: 1 }, { idempotencyKey });
1546
1618
  }
1547
- finishRun(id, version, input, idempotencyKey) {
1548
- return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version, idempotencyKey });
1619
+ finishRun(id, version2, input, idempotencyKey) {
1620
+ return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version: version2, idempotencyKey });
1549
1621
  }
1550
1622
  }
1551
1623
  function clientFromEnv(env = process.env, options = {}) {
@@ -1983,8 +2055,8 @@ class Store {
1983
2055
  }
1984
2056
  return value;
1985
2057
  }
1986
- async remove(kind, id, version, db) {
1987
- const rows = await db.unsafe(`DELETE FROM switcher_${kind} WHERE id = $1 AND version = $2 RETURNING id`, [id, version]);
2058
+ async remove(kind, id, version2, db) {
2059
+ const rows = await db.unsafe(`DELETE FROM switcher_${kind} WHERE id = $1 AND version = $2 RETURNING id`, [id, version2]);
1988
2060
  if (!rows.length)
1989
2061
  throw new Fault(409, "version_conflict", "Entry changed or is missing; reload before retrying.");
1990
2062
  return { deleted: id };
@@ -2471,7 +2543,7 @@ var openapi_default = {
2471
2543
  openapi: "3.0.3",
2472
2544
  info: {
2473
2545
  title: "Switcher API",
2474
- version: "0.2.7",
2546
+ version: "0.2.9",
2475
2547
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2476
2548
  },
2477
2549
  security: [
@@ -6783,7 +6855,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
6783
6855
  }
6784
6856
  }
6785
6857
  const fingerprint = hash(JSON.stringify([request.method, route2, body, request.headers.get("if-match")])).toString("hex");
6786
- const version = () => {
6858
+ const version2 = () => {
6787
6859
  const v = request.headers.get("if-match");
6788
6860
  if (!v || !/^[1-9]\d*$/.test(v))
6789
6861
  throw new Fault(428, "version_required", "Supply the current numeric version in If-Match.");
@@ -6803,7 +6875,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
6803
6875
  const result = await store.mutate(key, fingerprint, async (db) => {
6804
6876
  if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
6805
6877
  if (request.method === "DELETE" && id2)
6806
- return store.remove(resource, id2, version(), db);
6878
+ return store.remove(resource, id2, version2(), db);
6807
6879
  if (request.method === "POST" && !id2 || request.method === "PUT" && id2) {
6808
6880
  const value = resource === "providers" ? parse2(providerInputSchema, body) : parse2(profileInputSchema, body);
6809
6881
  if (id2 && value.id !== id2)
@@ -6813,7 +6885,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
6813
6885
  const provider = await store.get("providers", profile.providerId, db);
6814
6886
  validateHarnessProvider(profile.harness, provider);
6815
6887
  }
6816
- const saved = await store.put(resource, value, id2 ? version() : undefined, db);
6888
+ const saved = await store.put(resource, value, id2 ? version2() : undefined, db);
6817
6889
  if (resource === "providers" && id2)
6818
6890
  await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id2]);
6819
6891
  return saved;
@@ -6840,7 +6912,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
6840
6912
  if (store.engine === "postgresql")
6841
6913
  await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR UPDATE", [id2]);
6842
6914
  const provider = await store.get("providers", id2, db);
6843
- if (provider.version !== version())
6915
+ if (provider.version !== version2())
6844
6916
  throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
6845
6917
  const catalog = parse2(catalogSchema, body);
6846
6918
  const expectedSource = provider.manualModels.length ? "manual" : "remote";
@@ -6920,7 +6992,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
6920
6992
  const run = await store.get("runs", id2, db);
6921
6993
  if (run.status !== "running")
6922
6994
  throw new Fault(409, "run_finished", "Run has already finished.");
6923
- return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
6995
+ return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version2(), db);
6924
6996
  }
6925
6997
  throw new Fault(404, "not_found", "Route was not found.");
6926
6998
  });
@@ -8491,7 +8563,7 @@ import { execFileSync as execFileSync2 } from "child_process";
8491
8563
  import { createHash as createHash7 } from "crypto";
8492
8564
  var dict = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
8493
8565
  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"]);
8566
+ 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
8567
  var codexTransportKeys = new Set(["mcp_servers", "mcp_server", "transport", "transports", "plugins"]);
8496
8568
  function codexAgentsFromEffectiveConfig(config, trustedProject = true, baseDir) {
8497
8569
  const raw = config.agents;
@@ -8554,7 +8626,7 @@ function scanNested(value, path) {
8554
8626
  if (!dict(value))
8555
8627
  return value;
8556
8628
  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")
8629
+ 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
8630
  reject(`${path}.${key}`);
8559
8631
  if (key === "agents" && dict(item)) {
8560
8632
  for (const [name, role] of Object.entries(item))
@@ -10127,41 +10199,41 @@ var versionAtLeast2 = (raw, minimum) => {
10127
10199
  }
10128
10200
  return true;
10129
10201
  };
10130
- function validateHarnessVersion(harness, version) {
10131
- if (harness === "antigravity" && version?.trim() !== "1.2.5")
10202
+ function validateHarnessVersion(harness, version2) {
10203
+ if (harness === "antigravity" && version2?.trim() !== "1.2.5")
10132
10204
  throw new Error("Antigravity CLI 1.2.5 is required by the verified native adapter.");
10133
- if (harness === "junie" && !/\b3196\.5\b/.test(version ?? ""))
10205
+ if (harness === "junie" && !/\b3196\.5\b/.test(version2 ?? ""))
10134
10206
  throw new Error("Junie build 3196.5 is required by the verified custom model adapter.");
10135
- if (harness === "kilo" && !versionAtLeast2(version, [7, 5, 15]))
10207
+ if (harness === "kilo" && !versionAtLeast2(version2, [7, 5, 15]))
10136
10208
  throw new Error("Kilo >=7.5.15 is required by this scoped provider bridge.");
10137
- if (harness === "omp" && !versionAtLeast2(version, [18, 1, 11]))
10209
+ if (harness === "omp" && !versionAtLeast2(version2, [18, 1, 11]))
10138
10210
  throw new Error("OMP >=18.1.11 is required for the native catalog and persistent session adapter.");
10139
- if (harness === "dsh" && (!versionAtLeast2(version, [0, 1, 2]) || /\b0\.1\.2-/.test(version ?? "") && !/\b0\.1\.2-rc\.[1-9]\d*(?:\b|$)/.test(version ?? "")))
10211
+ if (harness === "dsh" && (!versionAtLeast2(version2, [0, 1, 2]) || /\b0\.1\.2-/.test(version2 ?? "") && !/\b0\.1\.2-rc\.[1-9]\d*(?:\b|$)/.test(version2 ?? "")))
10140
10212
  throw new Error("DeepSeek Harness (dsh) >=0.1.2-rc.1 is required for the native profile adapter.");
10141
- if (harness === "aider" && !/^(?:aider\s+)?0\.86\.2(?:\s|$)/i.test(version ?? ""))
10213
+ if (harness === "aider" && !/^(?:aider\s+)?0\.86\.2(?:\s|$)/i.test(version2 ?? ""))
10142
10214
  throw new Error("Aider 0.86.2 is required by the verified native configuration adapter.");
10143
- if (harness === "claude" && !versionAtLeast2(version, [2, 1, 257]))
10215
+ if (harness === "claude" && !versionAtLeast2(version2, [2, 1, 257]))
10144
10216
  throw new Error("Claude Code >=2.1.257 is required for a full native modelPicker.");
10145
- if (harness === "pi" && !versionAtLeast2(version, [0, 85, 1]))
10217
+ if (harness === "pi" && !versionAtLeast2(version2, [0, 85, 1]))
10146
10218
  throw new Error("Pi >=0.85.1 is required by this catalog adapter.");
10147
- if (harness === "codex" && !versionAtLeast2(version, [0, 153, 0]))
10219
+ if (harness === "codex" && !versionAtLeast2(version2, [0, 153, 0]))
10148
10220
  throw new Error("Codex >=0.153.0 is required by this catalog adapter.");
10149
- if (harness === "grok" && !versionAtLeast2(version, [1, 0, 13]))
10221
+ if (harness === "grok" && !versionAtLeast2(version2, [1, 0, 13]))
10150
10222
  throw new Error("Grok Build >=1.0.13 is required by this remote catalog adapter.");
10151
- if (harness === "cline" && !versionAtLeast2(version, [3, 0, 61]))
10223
+ if (harness === "cline" && !versionAtLeast2(version2, [3, 0, 61]))
10152
10224
  throw new Error("Cline >=3.0.61 is required by this native provider adapter.");
10153
- if (harness === "prime-agent" && !versionAtLeast2(version, [0, 9, 2]))
10225
+ if (harness === "prime-agent" && !versionAtLeast2(version2, [0, 9, 2]))
10154
10226
  throw new Error("Prime Agent >=0.9.2 is required by this catalog adapter.");
10155
- if (harness === "opencode" && !versionAtLeast2(version, [1, 18, 0]))
10227
+ if (harness === "opencode" && !versionAtLeast2(version2, [1, 18, 0]))
10156
10228
  throw new Error("Legacy OpenCode >=1.18.0 is required by this catalog adapter.");
10157
10229
  if (harness === "opencode2") {
10158
- const preview = version?.match(/opencode2.*beta-(\d+)/i);
10159
- if (!(preview && Number(preview[1]) >= 19157) && !versionAtLeast2(version, [2, 0, 0]))
10230
+ const preview = version2?.match(/opencode2.*beta-(\d+)/i);
10231
+ if (!(preview && Number(preview[1]) >= 19157) && !versionAtLeast2(version2, [2, 0, 0]))
10160
10232
  throw new Error("OpenCode 2 beta-19157 or newer is required for isolated provider configuration; legacy OpenCode is not supported by this adapter.");
10161
10233
  }
10162
- if (harness === "hermes" && !versionAtLeast2(version, [0, 21, 0]))
10234
+ if (harness === "hermes" && !versionAtLeast2(version2, [0, 21, 0]))
10163
10235
  throw new Error("Hermes Agent >=0.21.0 is required by this provider and session adapter.");
10164
- if (harness === "gemini" && !/^0\.58\.0$/.test(version?.trim() ?? ""))
10236
+ if (harness === "gemini" && !/^0\.58\.0$/.test(version2?.trim() ?? ""))
10165
10237
  throw new Error("Gemini CLI 0.58.0 is required by the verified native settings and argument contract.");
10166
10238
  }
10167
10239
  async function jsonFile(dir, name, value) {
@@ -10850,7 +10922,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
10850
10922
  return { executable, args: ["--settings", file2, "--model", input.model, ...args], env, configPaths, warnings };
10851
10923
  }
10852
10924
  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 });
10925
+ 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
10926
  const selectableModels = input.models.filter((model3) => input.compiledPolicy?.allowedModels.includes(model3.id) ?? true);
10855
10927
  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
10928
  configPaths.push(file2);
@@ -10871,6 +10943,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
10871
10943
  overrides.push("-c", `agents.${name}.config_file=${quote(path)}`);
10872
10944
  }
10873
10945
  overrides.push("-c", `memories.extract_model=${quote(input.model)}`, "-c", `memories.consolidation_model=${quote(input.model)}`);
10946
+ if (input.sharedState?.sqliteHome)
10947
+ overrides.push("-c", `sqlite_home=${quote(input.sharedState.sqliteHome)}`);
10874
10948
  if (input.reasoning)
10875
10949
  overrides.push("-c", `model_reasoning_effort=${quote(input.reasoning)}`);
10876
10950
  if (input.dangerouslyBypassApprovalsAndSandbox)
@@ -11119,7 +11193,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
11119
11193
  return { executable, args: native, env, configPaths, warnings };
11120
11194
  }
11121
11195
  async function prepareTransportLaunch(input) {
11122
- assertHarnessArguments(input.harness, input.args ?? []);
11196
+ assertHarnessArguments(input.harness, input.args ?? [], input.sharedState?.tool === "codex" ? { reservedCodexRoots: ["sqlite_home"] } : {});
11123
11197
  if (input.harness === "kilo") {
11124
11198
  await validateKiloConfiguration(input.cwd, [...input.args ?? []]);
11125
11199
  if (input.protocol === "gemini-generate-content")
@@ -11184,7 +11258,7 @@ async function prepareTransportLaunch(input) {
11184
11258
  }
11185
11259
  }
11186
11260
  async function prepareHarnessLaunch(input) {
11187
- assertHarnessArguments(input.harness, input.args ?? []);
11261
+ assertHarnessArguments(input.harness, input.args ?? [], input.sharedState?.tool === "codex" ? { reservedCodexRoots: ["sqlite_home"] } : {});
11188
11262
  if (input.harness === "gemini" && input.authStyle !== "x-api-key")
11189
11263
  throw new Error("Gemini CLI requires x-api-key authentication.");
11190
11264
  validateHarnessVersion(input.harness, input.version);
@@ -11249,8 +11323,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
11249
11323
  }
11250
11324
 
11251
11325
  // 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";
11326
+ import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile17 } from "fs/promises";
11327
+ import { join as join20, resolve as resolve11 } from "path";
11254
11328
 
11255
11329
  // src/provider-credential-onboarding.ts
11256
11330
  import { z as z8 } from "zod";
@@ -11259,9 +11333,10 @@ import { createInterface } from "readline/promises";
11259
11333
 
11260
11334
  // src/credentials.ts
11261
11335
  import { z as z7 } from "zod";
11336
+ import { ExecutableTrustError, repairExecutablePermissions, validateExecutable } from "@hasna/contracts/executable-trust";
11262
11337
  import { constants as constants5 } from "fs";
11263
- import { open as open3, readdir as readdir5, unlink, link, lstat as lstat6, access as access4, stat as stat6, realpath as realpath6, readlink, rename as rename2 } from "fs/promises";
11264
- import { join as join16, isAbsolute as isAbsolute15, dirname as dirname8, parse as pathParts, resolve as resolvePath, sep as sep2 } from "path";
11338
+ import { open as open3, readdir as readdir5, unlink, link, lstat as lstat6 } from "fs/promises";
11339
+ import { join as join16, isAbsolute as isAbsolute15 } from "path";
11265
11340
  import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
11266
11341
  import { execFile as execFile3, spawn } from "child_process";
11267
11342
  import { promisify as promisify3 } from "util";
@@ -11416,131 +11491,37 @@ function credentialReference(selector) {
11416
11491
  throw new Fault(400, "credential_reference_required", "Use the explicit SWITCHER_PROVIDER_ reference for this provider.");
11417
11492
  return parse2(reference, name);
11418
11493
  }
11419
- async function inspectVaultExecutable(path, permitWritableFile = false) {
11420
- let info, resolved;
11421
- try {
11422
- resolved = await realpath6(path);
11423
- await access4(resolved, constants5.X_OK);
11424
- info = await stat6(resolved);
11425
- if (!info.isFile())
11426
- throw new Error;
11427
- } catch {
11428
- throw new Fault(422, "vault_exec_unavailable", "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.");
11429
- }
11430
- if (process.platform !== "win32" && (!permitWritableFile && info.mode & 18 || info.uid !== 0 && info.uid !== process.getuid?.()))
11431
- throw new Fault(422, "vault_exec_permissions", "The secrets executable must be owned by this user or root and not writable by other users. Choose a trusted installation, or use credentials repair-executable REFERENCE --sha256 EXPECTED with the executable digest from a verified package artifact. Launch never repairs permissions automatically.");
11432
- if (process.platform !== "win32") {
11433
- const seen = new Set;
11434
- const inspect = async (candidate) => {
11435
- let prefix = pathParts(candidate).root;
11436
- for (const part of candidate.slice(prefix.length).split(sep2)) {
11437
- if (!part)
11438
- continue;
11439
- prefix = join16(prefix, part);
11440
- if (seen.has(prefix))
11441
- continue;
11442
- seen.add(prefix);
11443
- if (seen.size > 256)
11444
- throw new Fault(422, "vault_exec_permissions", "The secrets executable path has too many symlink components.");
11445
- const entry = await lstat6(prefix);
11446
- const permittedFile = permitWritableFile && prefix === resolved && entry.isFile();
11447
- if (entry.uid !== 0 && entry.uid !== process.getuid?.() || !entry.isSymbolicLink() && !permittedFile && entry.mode & 18)
11448
- throw new Fault(422, "vault_exec_permissions", "The secrets executable and its ancestor directories must not be replaceable by other users. Choose an installation owned by this user or root without group/public write permissions.");
11449
- if (entry.isSymbolicLink())
11450
- await inspect(resolvePath(dirname8(prefix), await readlink(prefix)));
11451
- }
11452
- };
11453
- try {
11454
- await inspect(path);
11455
- await inspect(resolved);
11456
- } catch (error) {
11457
- if (error instanceof Fault)
11458
- throw error;
11459
- throw new Fault(422, "vault_exec_unavailable", "The secrets executable path changed or could not be verified. Retry with a trusted installation.");
11460
- }
11461
- }
11462
- return resolved;
11494
+ function vaultExecutableFault(error) {
11495
+ if (!(error instanceof ExecutableTrustError))
11496
+ throw error;
11497
+ const codes = {
11498
+ invalid_request: "invalid_request",
11499
+ executable_unavailable: "vault_exec_unavailable",
11500
+ executable_permissions: "vault_exec_permissions",
11501
+ executable_repair_unsafe: "vault_exec_repair_unsafe",
11502
+ executable_digest_mismatch: "vault_exec_digest_mismatch"
11503
+ };
11504
+ const messages = {
11505
+ invalid_request: error.message,
11506
+ executable_unavailable: "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.",
11507
+ executable_permissions: "The secrets executable and its ancestor directories must be owned by this user or root and not writable by other users. Use credentials repair-executable REFERENCE --sha256 EXPECTED with the executable digest from a verified package artifact. Launch never repairs permissions automatically.",
11508
+ executable_repair_unsafe: error.message,
11509
+ executable_digest_mismatch: "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed."
11510
+ };
11511
+ throw new Fault(error.status, codes[error.code], messages[error.code]);
11463
11512
  }
11464
11513
  async function validateVaultExecutable(path) {
11465
- return inspectVaultExecutable(path);
11514
+ try {
11515
+ return await validateExecutable(path);
11516
+ } catch (error) {
11517
+ return vaultExecutableFault(error);
11518
+ }
11466
11519
  }
11467
11520
  async function repairVaultExecutablePermissions(path, expectedSha256) {
11468
- if (!/^[a-f0-9]{64}$/.test(expectedSha256))
11469
- throw new Fault(400, "invalid_request", "--sha256 requires the SHA256 of the executable member from a verified package artifact.");
11470
- if (!isAbsolute15(path) || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path))
11471
- throw new Fault(400, "invalid_request", "Secrets executable must be an absolute path without control characters.");
11472
- if (process.platform === "win32")
11473
- throw new Fault(422, "vault_exec_repair_unsafe", "Executable permission repair requires POSIX file permissions.");
11474
- const resolved = await inspectVaultExecutable(path, true);
11475
- const file = await open3(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
11476
- const unsafe = () => new Fault(422, "vault_exec_repair_unsafe", "Executable ownership, type, links or contents changed; no trusted repair can be confirmed.");
11477
- let temporary;
11478
11521
  try {
11479
- const before = await file.stat();
11480
- const limit = 256 * 1024 * 1024;
11481
- if (!before.isFile() || before.uid !== process.getuid?.() || before.size > limit || before.mode & 3584)
11482
- throw unsafe();
11483
- const sameFile = (info) => info.dev === before.dev && info.ino === before.ino && info.size === before.size && info.uid === before.uid && info.nlink === before.nlink && info.mode === before.mode && info.mtimeMs === before.mtimeMs && info.ctimeMs === before.ctimeMs;
11484
- const hash2 = async (target) => {
11485
- const digest = createHash10("sha256");
11486
- const buffer = Buffer.alloc(1024 * 1024);
11487
- let position = 0;
11488
- while (true) {
11489
- const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
11490
- if (!bytesRead)
11491
- break;
11492
- position += bytesRead;
11493
- if (position > limit)
11494
- throw unsafe();
11495
- const bytes = buffer.subarray(0, bytesRead);
11496
- digest.update(bytes);
11497
- if (target)
11498
- await target.writeFile(bytes);
11499
- }
11500
- if (position !== before.size || !sameFile(await file.stat()))
11501
- throw unsafe();
11502
- if (digest.digest("hex") !== expectedSha256)
11503
- throw new Fault(422, "vault_exec_digest_mismatch", "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed.");
11504
- };
11505
- await hash2();
11506
- const mode = before.mode & 511 & ~18;
11507
- const changed = mode !== (before.mode & 511);
11508
- if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat6(resolved)))
11509
- throw unsafe();
11510
- if (!changed) {
11511
- await validateVaultExecutable(path);
11512
- return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
11513
- }
11514
- temporary = join16(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
11515
- const replacement = await open3(temporary, "wx", 384);
11516
- try {
11517
- await hash2(replacement);
11518
- await replacement.chmod(mode);
11519
- await replacement.sync();
11520
- const ready = await replacement.stat();
11521
- if (!ready.isFile() || ready.nlink !== 1 || ready.uid !== before.uid || ready.size !== before.size)
11522
- throw unsafe();
11523
- if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat6(resolved)))
11524
- throw unsafe();
11525
- await rename2(temporary, resolved);
11526
- temporary = undefined;
11527
- const installed = await lstat6(resolved);
11528
- if (installed.dev !== ready.dev || installed.ino !== ready.ino || await validateVaultExecutable(path) !== resolved)
11529
- throw unsafe();
11530
- const directory = await open3(dirname8(resolved), constants5.O_RDONLY | constants5.O_DIRECTORY | constants5.O_NOFOLLOW);
11531
- try {
11532
- await directory.sync();
11533
- } finally {
11534
- await directory.close();
11535
- }
11536
- } finally {
11537
- await replacement.close();
11538
- }
11539
- return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
11540
- } finally {
11541
- await file.close();
11542
- if (temporary)
11543
- await unlink(temporary);
11522
+ return await repairExecutablePermissions(path, expectedSha256);
11523
+ } catch (error) {
11524
+ return vaultExecutableFault(error);
11544
11525
  }
11545
11526
  }
11546
11527
  function bindingTarget(selector, override, allowedOrigins) {
@@ -11801,6 +11782,7 @@ async function deliverVaultCredential() {
11801
11782
 
11802
11783
  // src/provider-credential-onboarding.ts
11803
11784
  var absent = (error) => error instanceof SwitcherError && error.status === 404;
11785
+ var MAX_CREDENTIAL_MATCHES = 256;
11804
11786
  var secretMetadataSchema = z8.object({
11805
11787
  key: vaultKeySchema,
11806
11788
  type: z8.enum(["api_key", "password", "token", "credential", "other"]),
@@ -11840,7 +11822,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
11840
11822
  const operator2 = await resolveVaultOperatorEnvironment(provisional, env);
11841
11823
  const entries = new Map;
11842
11824
  for (const query of searchTerms(provider)) {
11843
- const output = await runVaultCommand(provisional, ["search", query, "--json"], env, {}, {
11825
+ const output = await runVaultCommand(provisional, ["search", query, "--json", "--full", "--limit", String(MAX_CREDENTIAL_MATCHES + 1)], env, {}, {
11844
11826
  captureBytes: 256 * 1024,
11845
11827
  oversizeCode: "vault_metadata_oversized",
11846
11828
  oversizeMessage: "Secrets returned too much credential metadata; narrow the vault naming or bind an exact key explicitly.",
@@ -11854,12 +11836,14 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
11854
11836
  } catch {
11855
11837
  throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned invalid credential metadata JSON.");
11856
11838
  }
11857
- const result = secretMetadataSchema.array().max(1000).safeParse(parsed);
11839
+ if (Array.isArray(parsed) && parsed.length > MAX_CREDENTIAL_MATCHES)
11840
+ throw new Fault(422, "credential_matches_too_many", "More than 256 credential metadata rows matched. Bind an exact vault key explicitly.");
11841
+ const result = secretMetadataSchema.array().max(MAX_CREDENTIAL_MATCHES).safeParse(parsed);
11858
11842
  if (!result.success)
11859
11843
  throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned an unsupported credential metadata shape.");
11860
11844
  for (const entry of result.data)
11861
11845
  entries.set(entry.key, entry);
11862
- if (entries.size > 256)
11846
+ if (entries.size > MAX_CREDENTIAL_MATCHES)
11863
11847
  throw new Fault(422, "credential_matches_too_many", "More than 256 credential references matched. Bind an exact vault key explicitly.");
11864
11848
  }
11865
11849
  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 } }));
@@ -12462,13 +12446,13 @@ async function inspectOri(options = {}) {
12462
12446
  const versionResult = await readOnly(executable, ["--version"], environment, options.cwd);
12463
12447
  if (versionResult.code !== 0)
12464
12448
  throw new OriBackendError("ori_unavailable", "Ori could not report its version; install it or pass an explicit executable.");
12465
- const version = parseVersion(versionResult.stdout);
12466
- if (!version)
12449
+ const version2 = parseVersion(versionResult.stdout);
12450
+ if (!version2)
12467
12451
  throw new OriBackendError("invalid_contract", "Ori --version did not report a version.");
12468
12452
  const inventoryResult = await readOnly(executable, ["harness", "list", "--json"], environment, options.cwd);
12469
12453
  if (inventoryResult.code !== 0)
12470
12454
  throw new OriBackendError("ori_unavailable", "Ori could not report its harness inventory.");
12471
- return { executable, version, harnesses: parseHarnesses(inventoryResult.stdout) };
12455
+ return { executable, version: version2, harnesses: parseHarnesses(inventoryResult.stdout) };
12472
12456
  }
12473
12457
  function assertSupportedOriVersion(contract) {
12474
12458
  if (!/^0\.12\./.test(contract.version))
@@ -12583,11 +12567,12 @@ function oriLaunchWarnings(target) {
12583
12567
  // src/chatgpt-launch.ts
12584
12568
  import { createHash as createHash12 } from "crypto";
12585
12569
  import { writeFile as writeFile15, rm as rm4 } from "fs/promises";
12586
- import { join as join17 } from "path";
12570
+ import { join as join18 } from "path";
12571
+ import { fileURLToPath } from "url";
12587
12572
 
12588
12573
  // src/desktop-state.ts
12589
12574
  import { Database as Database3 } from "bun:sqlite";
12590
- import { readFile as readFile7, writeFile as writeFile14, rm as rm3, lstat as lstat7, rename as rename3, chmod as chmod2 } from "fs/promises";
12575
+ import { readFile as readFile7, writeFile as writeFile14, rm as rm3, lstat as lstat7, rename as rename2, chmod as chmod2 } from "fs/promises";
12591
12576
  async function safeDesktopRead(path) {
12592
12577
  try {
12593
12578
  const info = await lstat7(path);
@@ -12604,7 +12589,7 @@ async function writeDesktopPrivate(path, text) {
12604
12589
  const temporary = path + "." + crypto.randomUUID() + ".tmp";
12605
12590
  try {
12606
12591
  await writeFile14(temporary, text, { mode: 384, flag: "wx" });
12607
- await rename3(temporary, path);
12592
+ await rename2(temporary, path);
12608
12593
  } finally {
12609
12594
  await rm3(temporary, { force: true });
12610
12595
  }
@@ -12635,6 +12620,401 @@ async function desktopLease(path) {
12635
12620
  };
12636
12621
  }
12637
12622
 
12623
+ // src/native-state.ts
12624
+ import { lstat as lstat8, mkdir as mkdir11, open as open4, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
12625
+ import { constants as constants7 } from "fs";
12626
+ import { homedir as homedir9 } from "os";
12627
+ import { dirname as dirname8, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve9 } from "path";
12628
+ function nativeStateRequested(tool, environment = process.env, explicit = false) {
12629
+ const suffix = tool.toUpperCase();
12630
+ return explicit || environment[`HASNA_${suffix}_STATE_HOME`] !== undefined || environment[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
12631
+ }
12632
+ function validateNativeStateVersion(tool, version2) {
12633
+ if (tool !== "codex")
12634
+ return;
12635
+ const match = version2?.match(/(\d+)\.(\d+)\.(\d+)/), actual = match?.slice(1).map(Number);
12636
+ if (!actual || actual[0] !== 0 || actual[1] < 154)
12637
+ 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.");
12638
+ }
12639
+ var CODEX_INSTRUCTION_KEYS = [
12640
+ "instructions",
12641
+ "developer_instructions",
12642
+ "model_instructions_file",
12643
+ "compact_prompt",
12644
+ "experimental_compact_prompt_file",
12645
+ "include_permissions_instructions",
12646
+ "include_apps_instructions",
12647
+ "include_collaboration_mode_instructions",
12648
+ "include_environment_context",
12649
+ "project_doc_max_bytes",
12650
+ "project_doc_fallback_filenames"
12651
+ ];
12652
+ var NATIVE_STATE_ENTRIES = {
12653
+ codex: [
12654
+ ...["sessions", "archived_sessions", "thread-writer-locks", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12655
+ ...["history.jsonl", "AGENTS.md", "AGENTS.override.md"].map((name) => ({ name, kind: "file" }))
12656
+ ],
12657
+ claude: [
12658
+ ...["projects", "todos", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12659
+ ...["history.jsonl", "CLAUDE.md"].map((name) => ({ name, kind: "file" }))
12660
+ ]
12661
+ };
12662
+ async function info(path) {
12663
+ try {
12664
+ return await lstat8(path);
12665
+ } catch (error) {
12666
+ if (error.code === "ENOENT")
12667
+ return;
12668
+ throw error;
12669
+ }
12670
+ }
12671
+ function absolute(value) {
12672
+ if (!isAbsolute16(value) || value.includes("\x00"))
12673
+ throw new Fault(422, "native_state_path", "The shared native state directory must be an absolute path.");
12674
+ return resolve9(value);
12675
+ }
12676
+ function credentialOverlay(path) {
12677
+ return /(?:^|\/)subscriptions\/profiles\//.test(path) || /(?:^|\/)switcher\/state\/(?:desktop|desktop-claude|launch-[^/]+)\//.test(path);
12678
+ }
12679
+ async function assertSafeAncestors(path) {
12680
+ for (let parent = path;; parent = dirname8(parent)) {
12681
+ const ancestor = await lstat8(parent);
12682
+ const stickyRoot = ancestor.uid === 0 && (ancestor.mode & 512) !== 0;
12683
+ if (!ancestor.isDirectory() || ancestor.isSymbolicLink() || ![0, process.getuid?.()].includes(ancestor.uid) || (ancestor.mode & 18) !== 0 && !stickyRoot)
12684
+ throw new Fault(422, "native_state_permissions", "Shared native state has an unsafe ancestor directory.");
12685
+ if (parent === dirname8(parent))
12686
+ break;
12687
+ }
12688
+ }
12689
+ async function assertNativeStateDirectory(path) {
12690
+ const entry = await info(path);
12691
+ if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || await realpath6(path) !== path)
12692
+ throw new Fault(422, "native_state_permissions", "Shared native state must be an owned directory without writable or symbolic-link redirection.");
12693
+ await assertSafeAncestors(dirname8(path));
12694
+ }
12695
+ async function ensureNativeStateDirectory(path, create = true) {
12696
+ if (await info(path))
12697
+ return assertNativeStateDirectory(path);
12698
+ await ensureNativeStateDirectory(dirname8(path), create);
12699
+ if (!create)
12700
+ return;
12701
+ await mkdir11(path, { mode: 448 }).catch((error) => {
12702
+ if (error.code !== "EEXIST")
12703
+ throw error;
12704
+ });
12705
+ await assertNativeStateDirectory(path);
12706
+ }
12707
+ async function withNativeStateLock(state, operation) {
12708
+ await ensureNativeStateDirectory(state.home);
12709
+ const path = join17(state.home, ".switcher-shared-state.lock");
12710
+ let handle;
12711
+ try {
12712
+ handle = await open4(path, "wx", 384);
12713
+ } catch (error) {
12714
+ if (error.code !== "EEXIST")
12715
+ throw error;
12716
+ const entry = await info(path);
12717
+ if (!entry?.isFile() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 63) !== 0)
12718
+ throw new Fault(422, "native_state_lock", "The shared-state lock has unsafe ownership, permissions or type.");
12719
+ 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.");
12720
+ }
12721
+ const identity = await handle.stat();
12722
+ try {
12723
+ return await operation();
12724
+ } finally {
12725
+ await handle.close();
12726
+ try {
12727
+ const entry = await lstat8(path);
12728
+ if (entry.dev === identity.dev && entry.ino === identity.ino)
12729
+ await unlink2(path);
12730
+ } catch (error) {
12731
+ if (error.code !== "ENOENT")
12732
+ throw error;
12733
+ }
12734
+ }
12735
+ }
12736
+ async function assertShareableTree(path, budget = { entries: 0 }, depth = 0) {
12737
+ if (depth > 32)
12738
+ throw new Fault(422, "native_state_inventory_limit", "The shared native corpus exceeds the safe projection inventory limit.");
12739
+ if (depth === 0)
12740
+ await assertNativeStateDirectory(path);
12741
+ for await (const child of await opendir(path)) {
12742
+ if (++budget.entries > 1e5 || child.isSymbolicLink())
12743
+ throw new Fault(422, "native_state_entry", "A shared native state tree contains an unsupported link or exceeds the safe inventory limit.");
12744
+ const nested = join17(path, child.name), entry = await lstat8(nested);
12745
+ if (entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0)
12746
+ throw new Fault(422, "native_state_entry", "A shared native state entry has unsafe ownership or writable permissions.");
12747
+ if (child.isDirectory()) {
12748
+ if (!entry.isDirectory())
12749
+ throw new Fault(422, "native_state_entry", "A shared native state directory changed during inspection.");
12750
+ await assertShareableTree(nested, budget, depth + 1);
12751
+ continue;
12752
+ }
12753
+ if (!child.isFile() || !entry.isFile() || entry.nlink !== 1)
12754
+ throw new Fault(422, "native_state_entry", "A shared native state tree contains an unsupported file type or hardlink.");
12755
+ }
12756
+ }
12757
+ async function readCodexStateConfig(home) {
12758
+ const path = join17(home, "config.toml"), entry = await info(path);
12759
+ if (!entry)
12760
+ return {};
12761
+ if (!entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
12762
+ throw new Fault(422, "native_state_config", "The Codex instruction configuration cannot be read safely.");
12763
+ const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
12764
+ let config;
12765
+ try {
12766
+ const opened = await handle.stat();
12767
+ if (opened.ino !== entry.ino || opened.dev !== entry.dev || opened.nlink !== 1 || opened.size > 1024 * 1024)
12768
+ throw new Fault(409, "native_state_config", "The Codex instruction configuration changed during preparation.");
12769
+ config = Bun.TOML.parse(await handle.readFile("utf8"));
12770
+ } catch (error) {
12771
+ if (error instanceof Fault)
12772
+ throw error;
12773
+ throw new Fault(422, "native_state_config", "The Codex instruction configuration is invalid.");
12774
+ } finally {
12775
+ await handle.close();
12776
+ }
12777
+ if (config.profile !== undefined || config.include !== undefined)
12778
+ 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.");
12779
+ return config;
12780
+ }
12781
+ var CODEX_INSTRUCTION_FILE_KEYS = new Set(["model_instructions_file", "experimental_compact_prompt_file"]);
12782
+ async function codexInstructionProjection(home, config, allowedExternalFiles = {}) {
12783
+ const instructions = {};
12784
+ for (const key of CODEX_INSTRUCTION_KEYS) {
12785
+ const value = config[key];
12786
+ if (value === undefined)
12787
+ continue;
12788
+ 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");
12789
+ if (!valid)
12790
+ throw new Fault(422, "native_state_instructions", "Codex instruction configuration has an unsupported value.");
12791
+ if (CODEX_INSTRUCTION_FILE_KEYS.has(key)) {
12792
+ const path = resolve9(home, value), entry = await info(path);
12793
+ const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute16(relativePath);
12794
+ if (!contained && path !== allowedExternalFiles[key] || !entry || !entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || ![0, process.getuid?.()].includes(entry.uid) || (entry.mode & 18) !== 0 || await realpath6(path) !== path)
12795
+ throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
12796
+ await assertSafeAncestors(dirname8(path));
12797
+ const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW).catch(() => {
12798
+ throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
12799
+ });
12800
+ try {
12801
+ const opened = await handle.stat();
12802
+ if (opened.ino !== entry.ino || opened.dev !== entry.dev || opened.nlink !== 1)
12803
+ throw new Fault(409, "native_state_instructions", "The configured instruction file changed during preparation.");
12804
+ } finally {
12805
+ await handle.close();
12806
+ }
12807
+ instructions[key] = path;
12808
+ } else
12809
+ instructions[key] = value;
12810
+ }
12811
+ return instructions;
12812
+ }
12813
+ async function assertNativeInstructionOverlay(state, overlayHome) {
12814
+ if (state.tool !== "codex" || absolute(overlayHome) === state.home)
12815
+ return;
12816
+ await assertNativeStateDirectory(overlayHome);
12817
+ const config = await readCodexStateConfig(overlayHome);
12818
+ if (config.profiles !== undefined || config.include !== undefined)
12819
+ throw new Fault(422, "native_state_instruction_overlay", "Private Codex profile/include instruction overlays are not supported. Resolve their effective canonical instructions before launching.");
12820
+ const expected = state.instructions ?? {};
12821
+ const allowedExternalFiles = Object.fromEntries([...CODEX_INSTRUCTION_FILE_KEYS].flatMap((key) => typeof expected[key] === "string" ? [[key, expected[key]]] : []));
12822
+ const actual = await codexInstructionProjection(overlayHome, config, allowedExternalFiles);
12823
+ if (CODEX_INSTRUCTION_KEYS.some((key) => JSON.stringify(actual[key]) !== JSON.stringify(expected[key])))
12824
+ 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.");
12825
+ }
12826
+ async function resolveNativeState(tool, environment = process.env, options = {}) {
12827
+ if (process.platform === "win32")
12828
+ throw new Fault(422, "unsupported_platform", "Shared native state currently requires POSIX ownership, no-follow and symlink semantics on Linux or macOS.");
12829
+ const suffix = tool.toUpperCase();
12830
+ const marker = `HASNA_${suffix}_STATE_HOME`, legacyMarker = `SUBSCRIPTIONS_SHARED_HOME_${suffix}`;
12831
+ const primary = environment[marker], legacy = environment[legacyMarker];
12832
+ if (primary !== undefined && legacy !== undefined && absolute(primary) !== absolute(legacy))
12833
+ throw new Fault(409, "native_state_identity_conflict", `The ${marker} and ${legacyMarker} corpus identities disagree. Select one exact shared native state directory before launching.`);
12834
+ const userHome = absolute(environment.HOME ?? homedir9());
12835
+ const selected = primary !== undefined ? absolute(primary) : legacy !== undefined ? absolute(legacy) : join17(userHome, `.${tool}`);
12836
+ if (credentialOverlay(selected))
12837
+ throw new Fault(422, "native_state_overlay", "An authentication profile cannot be the shared native state directory. Select its original native state directory.");
12838
+ await ensureNativeStateDirectory(selected, options.create !== false);
12839
+ if (tool === "claude")
12840
+ return { tool, home: selected, marker };
12841
+ const config = await readCodexStateConfig(selected);
12842
+ let sqliteHome = selected;
12843
+ if (config.sqlite_home !== undefined) {
12844
+ if (typeof config.sqlite_home !== "string")
12845
+ throw new Fault(422, "native_state_config", "Codex sqlite_home must be an absolute directory.");
12846
+ sqliteHome = absolute(config.sqlite_home);
12847
+ if (credentialOverlay(sqliteHome))
12848
+ throw new Fault(422, "native_state_overlay", "Codex SQLite state cannot belong to an authentication profile.");
12849
+ await ensureNativeStateDirectory(sqliteHome, options.create !== false);
12850
+ }
12851
+ const instructions = await codexInstructionProjection(selected, config);
12852
+ return { tool, home: selected, sqliteHome, marker, instructions };
12853
+ }
12854
+ function nativeStateEnvironment(state) {
12855
+ return state.tool === "codex" && state.sqliteHome ? { CODEX_SQLITE_HOME: state.sqliteHome } : {};
12856
+ }
12857
+ async function assertCodexDatabaseRedirectSafe(state, overlayHome) {
12858
+ if (state.tool !== "codex")
12859
+ return;
12860
+ const config = await readCodexStateConfig(overlayHome);
12861
+ const previous = config.sqlite_home;
12862
+ if (previous !== undefined && typeof previous !== "string")
12863
+ throw new Fault(422, "native_state_config", "The previous Codex sqlite_home must be an absolute directory.");
12864
+ const roots = new Set([overlayHome, ...typeof previous === "string" ? [absolute(previous)] : []]);
12865
+ for (const root of roots) {
12866
+ if (root === (state.sqliteHome ?? state.home) || !await info(root))
12867
+ continue;
12868
+ await assertNativeStateDirectory(root);
12869
+ const before = await lstat8(root);
12870
+ let inspected = 0;
12871
+ for await (const entry of await opendir(root)) {
12872
+ if (++inspected > 1e4)
12873
+ throw new Fault(409, "native_state_inventory_limit", "Native database inventory exceeded its bounded limit; no state was projected.");
12874
+ if (/^(?:state|logs|goals|memories|queue|thread_history)_\d+\.sqlite(?:-(?:wal|shm))?$/.test(entry.name))
12875
+ throw new Fault(409, "native_state_migration_required", "This profile retains native database metadata. Reconcile its catalog and history before redirecting shared state.");
12876
+ }
12877
+ const after = await lstat8(root);
12878
+ if (after.isSymbolicLink() || before.dev !== after.dev || before.ino !== after.ino || before.mtimeMs !== after.mtimeMs)
12879
+ throw new Fault(409, "native_state_inventory_changed", "Native database inventory changed; no state was projected.");
12880
+ }
12881
+ }
12882
+ async function directoryHasEntries(path) {
12883
+ const directory = await opendir(path);
12884
+ try {
12885
+ return Boolean(await directory.read());
12886
+ } finally {
12887
+ await directory.close();
12888
+ }
12889
+ }
12890
+ async function legacyNativeStateWarnings(root, state) {
12891
+ const directory = join17(root, state.tool === "codex" ? "desktop" : "desktop-claude");
12892
+ if (!await info(directory))
12893
+ return [];
12894
+ await assertNativeStateDirectory(directory);
12895
+ const pending = [];
12896
+ let inspected = 0;
12897
+ for await (const entry of await opendir(directory)) {
12898
+ if (++inspected > 1000)
12899
+ throw new Fault(409, "native_state_inventory_limit", "Too many legacy desktop profiles to inspect safely.");
12900
+ if (!entry.isDirectory() || entry.isSymbolicLink())
12901
+ continue;
12902
+ const home = join17(directory, entry.name, ...state.tool === "codex" ? ["codex"] : []);
12903
+ if (!await info(home))
12904
+ continue;
12905
+ await assertNativeStateDirectory(home);
12906
+ for (const name of [...NATIVE_STATE_ENTRIES[state.tool].map((item2) => item2.name), ...state.tool === "codex" ? ["state_5.sqlite", "session_index.jsonl"] : []]) {
12907
+ const path = join17(home, name), item2 = await info(path);
12908
+ if (!item2 || item2.isSymbolicLink())
12909
+ continue;
12910
+ if (item2.isFile() && item2.size > 0 || item2.isDirectory() && await directoryHasEntries(path)) {
12911
+ pending.push(home);
12912
+ break;
12913
+ }
12914
+ }
12915
+ }
12916
+ const display = (path) => {
12917
+ 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")}`);
12918
+ return value.length > 768 ? `${value.slice(0, 384)}...${value.slice(-381)}` : value;
12919
+ };
12920
+ 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.`);
12921
+ if (pending.length > warnings.length)
12922
+ warnings.push(`${pending.length - warnings.length} additional legacy ${state.tool} state directories are pending migration; inspect the Switcher state root before launch.`);
12923
+ return warnings;
12924
+ }
12925
+ async function createTrackedDirectory(path, created) {
12926
+ try {
12927
+ await mkdir11(path, { mode: 448 });
12928
+ created.push(path);
12929
+ } catch (error) {
12930
+ if (error.code !== "EEXIST")
12931
+ throw error;
12932
+ await assertNativeStateDirectory(path);
12933
+ }
12934
+ }
12935
+ async function projectNativeStateUnlocked(state, overlayHome) {
12936
+ overlayHome = absolute(overlayHome);
12937
+ await assertNativeStateDirectory(state.home);
12938
+ await assertNativeStateDirectory(overlayHome);
12939
+ if (overlayHome === state.home)
12940
+ return;
12941
+ const contains = (parent, child) => {
12942
+ const suffix = relative5(parent, child);
12943
+ return suffix !== ".." && !suffix.startsWith("../") && !isAbsolute16(suffix);
12944
+ };
12945
+ if (contains(state.home, overlayHome) || contains(overlayHome, state.home))
12946
+ throw new Fault(422, "native_state_overlap", "The shared corpus and authentication overlay must be separate directories.");
12947
+ await assertCodexDatabaseRedirectSafe(state, overlayHome);
12948
+ for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
12949
+ const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
12950
+ await ensureNativeStateDirectory(dirname8(target), false);
12951
+ await ensureNativeStateDirectory(dirname8(destination), false);
12952
+ const source = await info(target), existing = await info(destination);
12953
+ if (source && (source.isSymbolicLink() || source.uid !== process.getuid?.() || (source.mode & 18) !== 0 || source.isFile() && source.nlink !== 1 || (entry.kind === "directory" ? !source.isDirectory() : !source.isFile())))
12954
+ throw new Fault(422, "native_state_entry", "A shared native state entry has an unsupported type, owner or permissions.");
12955
+ if (source?.isDirectory())
12956
+ await assertShareableTree(target);
12957
+ if (existing && (!existing.isSymbolicLink() || resolve9(dirname8(destination), await readlink(destination)) !== target))
12958
+ 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.");
12959
+ }
12960
+ const createdLinks = [];
12961
+ const createdFiles = [], createdDirectories = [];
12962
+ try {
12963
+ for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
12964
+ const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
12965
+ const targetParent = dirname8(target), destinationParent = dirname8(destination);
12966
+ if (!await info(targetParent))
12967
+ await createTrackedDirectory(targetParent, createdDirectories);
12968
+ else
12969
+ await assertNativeStateDirectory(targetParent);
12970
+ if (!await info(destinationParent))
12971
+ await createTrackedDirectory(destinationParent, createdDirectories);
12972
+ else
12973
+ await assertNativeStateDirectory(destinationParent);
12974
+ if (entry.kind === "file" && !await info(target))
12975
+ continue;
12976
+ if (!await info(target)) {
12977
+ if (entry.kind === "directory")
12978
+ await createTrackedDirectory(target, createdDirectories);
12979
+ else {
12980
+ const file = await open4(target, "wx", 384);
12981
+ await file.close();
12982
+ createdFiles.push(target);
12983
+ }
12984
+ }
12985
+ if (!await info(destination)) {
12986
+ await symlink4(target, destination, entry.kind === "directory" ? "dir" : "file");
12987
+ createdLinks.push({ destination, target });
12988
+ }
12989
+ }
12990
+ } catch (error) {
12991
+ for (const item2 of createdLinks.reverse()) {
12992
+ try {
12993
+ if ((await info(item2.destination))?.isSymbolicLink() && resolve9(dirname8(item2.destination), await readlink(item2.destination)) === item2.target)
12994
+ await unlink2(item2.destination);
12995
+ } catch {}
12996
+ }
12997
+ for (const path of createdFiles.reverse()) {
12998
+ try {
12999
+ const entry = await info(path);
13000
+ if (entry?.isFile() && entry.nlink === 1 && entry.size === 0)
13001
+ await unlink2(path);
13002
+ } catch {}
13003
+ }
13004
+ for (const path of [...new Set(createdDirectories)].sort((a, b) => b.length - a.length)) {
13005
+ try {
13006
+ await rmdir(path);
13007
+ } catch {}
13008
+ }
13009
+ throw error;
13010
+ }
13011
+ }
13012
+ async function projectNativeState(state, overlayHome) {
13013
+ if (absolute(overlayHome) === state.home)
13014
+ return;
13015
+ return withNativeStateLock(state, () => projectNativeStateUnlocked(state, overlayHome));
13016
+ }
13017
+
12638
13018
  // src/chatgpt-launch.ts
12639
13019
  var object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
12640
13020
  function merge2(base, overlay) {
@@ -12643,16 +13023,41 @@ function merge2(base, overlay) {
12643
13023
  result[key] = object5(value) && object5(result[key]) ? merge2(result[key], value) : value;
12644
13024
  return result;
12645
13025
  }
13026
+ function clearSwitcherModelState(config) {
13027
+ for (const key of [...codexRoutingKeys, "review_model", "sqlite_home", "model_reasoning_effort", "cli_auth_credentials_store", "forced_login_method", ...CODEX_INSTRUCTION_KEYS])
13028
+ delete config[key];
13029
+ if (object5(config.agents)) {
13030
+ for (const key of ["default_subagent_model", "default_subagent_reasoning_effort", "default_subagent_reasoning_summary"])
13031
+ delete config.agents[key];
13032
+ for (const [name, value] of Object.entries(config.agents))
13033
+ if (object5(value)) {
13034
+ for (const key of ["model", "model_provider", "provider", "config_file"])
13035
+ delete value[key];
13036
+ if (!Object.keys(value).length)
13037
+ delete config.agents[name];
13038
+ }
13039
+ if (!Object.keys(config.agents).length)
13040
+ delete config.agents;
13041
+ }
13042
+ if (object5(config.memories)) {
13043
+ delete config.memories.extract_model;
13044
+ delete config.memories.consolidation_model;
13045
+ if (!Object.keys(config.memories).length)
13046
+ delete config.memories;
13047
+ }
13048
+ }
12646
13049
  var digest = (value) => createHash12("sha256").update(value).digest("hex");
12647
13050
  var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
12648
- async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
13051
+ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedState) {
13052
+ if (sharedState && sharedState.tool !== "codex")
13053
+ throw new Fault(422, "native_state_tool", "ChatGPT requires the canonical Codex corpus.");
12649
13054
  await privateDirectory(sessionDir);
12650
- const home = join17(sessionDir, "codex"), userData = join17(sessionDir, "electron");
13055
+ const home = join18(sessionDir, "codex"), userData = join18(sessionDir, "electron");
12651
13056
  await privateDirectory(home);
12652
13057
  await privateDirectory(userData);
12653
- const release = await desktopLease(join17(sessionDir, "launch.sqlite"));
13058
+ const release = await desktopLease(join18(sessionDir, "launch.sqlite"));
12654
13059
  let released = false, authText;
12655
- const authPath = join17(home, "auth.json"), receiptPath = join17(home, ".switcher-auth.sha256");
13060
+ const authPath = join18(home, "auth.json"), receiptPath = join18(home, ".switcher-auth.sha256");
12656
13061
  const cleanup = async () => {
12657
13062
  if (released)
12658
13063
  return;
@@ -12667,18 +13072,23 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
12667
13072
  }
12668
13073
  };
12669
13074
  try {
13075
+ if (sharedState)
13076
+ await projectNativeState(sharedState, home);
12670
13077
  const settings2 = [];
12671
13078
  for (let i = 0;i < native.args.length; i += 2) {
12672
13079
  if (native.args[i] !== "-c" || typeof native.args[i + 1] !== "string")
12673
13080
  throw new Fault(400, "desktop_arguments", "Desktop launches accept provider/model settings, not native CLI commands.");
12674
- settings2.push(native.args[i + 1]);
13081
+ if (!sharedState?.sqliteHome || !native.args[i + 1].startsWith("sqlite_home="))
13082
+ settings2.push(native.args[i + 1]);
12675
13083
  }
12676
13084
  settings2.push('cli_auth_credentials_store="file"', 'forced_login_method="api"');
13085
+ if (sharedState?.sqliteHome)
13086
+ settings2.push(`sqlite_home=${JSON.stringify(sharedState.sqliteHome)}`);
12677
13087
  if (!settings2.some((setting) => setting.startsWith("approval_policy=")))
12678
13088
  settings2.push('approval_policy="on-request"');
12679
13089
  if (!settings2.some((setting) => setting.startsWith("sandbox_mode=")))
12680
13090
  settings2.push('sandbox_mode="workspace-write"');
12681
- const configPath = join17(home, "config.toml");
13091
+ const configPath = join18(home, "config.toml");
12682
13092
  const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
12683
13093
  if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
12684
13094
  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 +13099,12 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
12689
13099
  if (error.code !== "ENOENT")
12690
13100
  throw new Fault(422, "desktop_config_invalid", "The desktop profile config cannot be read safely.");
12691
13101
  }
13102
+ if (sharedState) {
13103
+ if (["profile", "profiles", "include"].some((key2) => existing[key2] !== undefined))
13104
+ 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.");
13105
+ clearSwitcherModelState(existing);
13106
+ Object.assign(existing, sharedState.instructions);
13107
+ }
12692
13108
  const config = merge2(existing, Bun.TOML.parse(settings2.join(`
12693
13109
  `)));
12694
13110
  await writeDesktopPrivate(configPath, renderCodexAgentToml(config));
@@ -12699,8 +13115,20 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
12699
13115
  `;
12700
13116
  await writeDesktopPrivate(receiptPath, digest(authText));
12701
13117
  await writeDesktopPrivate(authPath, authText);
12702
- const wrapper = join17(stateDir, "chatgpt-codex");
13118
+ const wrapper = join18(stateDir, "chatgpt-codex");
12703
13119
  const overrides = settings2.flatMap((setting) => ["-c", setting]);
13120
+ let bridge = "";
13121
+ if (sharedState) {
13122
+ const entry = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./codex-state-bridge.ts" : "../codex-state-bridge.js", import.meta.url));
13123
+ const ownedKeys = new Set(["model_provider", "model_providers", "model_catalog_json", "review_model", "agents", "memories", "sqlite_home"]);
13124
+ const routing3 = Object.fromEntries(Object.entries(config).filter(([key2]) => ownedKeys.has(key2)));
13125
+ if (typeof config.model !== "string")
13126
+ throw new Fault(500, "desktop_model_missing", "Desktop preparation did not receive its selected model.");
13127
+ bridge = `if [ "\${1-}" = app-server ]; then
13128
+ exec ${[process.execPath, entry, app.codexExecutable, config.model, JSON.stringify(routing3)].map(quote2).join(" ")} "$@" ${overrides.map(quote2).join(" ")}
13129
+ fi
13130
+ `;
13131
+ }
12704
13132
  await writeFile15(wrapper, `#!/bin/sh
12705
13133
  set -eu
12706
13134
  unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
@@ -12708,15 +13136,15 @@ export CODEX_HOME=${quote2(home)}
12708
13136
  if [ "\${1-}" = sandbox ]; then
12709
13137
  exec ${quote2(app.codexExecutable)} "$@"
12710
13138
  fi
12711
- exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
13139
+ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
12712
13140
  `, { mode: 448, flag: "wx" });
12713
13141
  return {
12714
13142
  ...native,
12715
13143
  executable: app.executable,
12716
13144
  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" },
13145
+ 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
13146
  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.`],
13147
+ 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
13148
  cleanup: async () => {
12721
13149
  try {
12722
13150
  await native.cleanup?.();
@@ -12734,16 +13162,16 @@ exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
12734
13162
  // src/claude-desktop-launch.ts
12735
13163
  import { createHash as createHash13 } from "crypto";
12736
13164
  import { execFile as execFile5 } from "child_process";
12737
- 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";
13165
+ import { access as access4, rm as rm5, writeFile as writeFile16 } from "fs/promises";
13166
+ import { homedir as homedir10, userInfo as userInfo2 } from "os";
13167
+ import { join as join19 } from "path";
12740
13168
  import { promisify as promisify5 } from "util";
12741
13169
  var execute4 = promisify5(execFile5);
12742
13170
  var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
12743
- var claudeDesktopDataDirectory = () => join18(homedir9(), "Library/Application Support/Claude-3p");
13171
+ var claudeDesktopDataDirectory = () => join19(homedir10(), "Library/Application Support/Claude-3p");
12744
13172
  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"])
12746
- if (await access5(path).then(() => true, () => false))
13173
+ for (const path of [join19("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
13174
+ if (await access4(path).then(() => true, () => false))
12747
13175
  throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
12748
13176
  let openFiles;
12749
13177
  try {
@@ -12766,25 +13194,27 @@ function metadata(text) {
12766
13194
  async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
12767
13195
  if (input.harness !== "claude")
12768
13196
  throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
13197
+ if (input.sharedState && input.sharedState.tool !== "claude")
13198
+ throw new Fault(422, "native_state_tool", "Claude desktop requires the canonical Claude corpus.");
12769
13199
  validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
12770
13200
  if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
12771
13201
  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.");
12772
- const version = app.version.split(".").map(Number);
12773
- if (version.length < 3 || version.some((n) => !Number.isSafeInteger(n)) || version[0] < 1 || version[0] === 1 && version[1] < 52386)
13202
+ const version2 = app.version.split(".").map(Number);
13203
+ if (version2.length < 3 || version2.some((n) => !Number.isSafeInteger(n)) || version2[0] < 1 || version2[0] === 1 && version2[1] < 52386)
12774
13204
  throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
12775
13205
  const userData = system?.userData ?? claudeDesktopDataDirectory();
12776
13206
  const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
12777
13207
  await check2();
12778
13208
  await privateDirectory(userData);
12779
- const library = join18(userData, "configLibrary");
13209
+ const library = join19(userData, "configLibrary");
12780
13210
  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");
13211
+ const release = await desktopLease(join19(library, ".switcher-lease.sqlite"));
13212
+ const metaPath = join19(library, "_meta.json"), receiptPath = join19(library, ".switcher-selection.json");
12783
13213
  let receipt, gateway, closed = false;
12784
13214
  const restore = async (record3) => {
12785
13215
  if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
12786
13216
  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);
13217
+ const configPath = join19(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
12788
13218
  if (current !== undefined && hash2(current) !== record3.configHash)
12789
13219
  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
13220
  const currentMeta = await safeDesktopRead(metaPath);
@@ -12813,10 +13243,12 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
12813
13243
  const recovery = await safeDesktopRead(receiptPath);
12814
13244
  if (recovery)
12815
13245
  await restore(JSON.parse(recovery));
12816
- const localConfig = await safeDesktopRead(join18(userData, "claude_desktop_config.json"));
13246
+ const localConfig = await safeDesktopRead(join19(userData, "claude_desktop_config.json"));
12817
13247
  if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
12818
13248
  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
13249
  await privateDirectory(sessionDir);
13250
+ if (input.sharedState)
13251
+ await projectNativeState(input.sharedState, sessionDir);
12820
13252
  const roles2 = input.modelPolicy?.roles;
12821
13253
  const targets = { sonnet: input.model, opus: roles2?.planning ?? input.model, haiku: roles2?.fast ?? input.model };
12822
13254
  const aliases = Object.fromEntries(Object.entries(targets).map(([tier, model3]) => ["switcher/" + tier, model3]));
@@ -12824,10 +13256,10 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
12824
13256
  if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
12825
13257
  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
13258
  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");
13259
+ const catalogPath = join19(input.stateDir, "claude-desktop-policy.json");
12828
13260
  await writeFile16(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
12829
13261
  gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
12830
- const id2 = crypto.randomUUID(), configPath = join18(library, id2 + ".json");
13262
+ const id2 = crypto.randomUUID(), configPath = join19(library, id2 + ".json");
12831
13263
  const config = JSON.stringify({
12832
13264
  inferenceProvider: "gateway",
12833
13265
  inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
@@ -12846,7 +13278,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
12846
13278
  return {
12847
13279
  executable: app.executable,
12848
13280
  args: [],
12849
- env: { CLAUDE_CONFIG_DIR: sessionDir },
13281
+ env: { ...input.sharedState ? nativeStateEnvironment(input.sharedState) : {}, CLAUDE_CONFIG_DIR: sessionDir },
12850
13282
  configPaths: [catalogPath, configPath],
12851
13283
  beforeLaunch: check2,
12852
13284
  cleanup,
@@ -12860,10 +13292,212 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
12860
13292
  }
12861
13293
  }
12862
13294
 
13295
+ // src/codex-session-discovery.ts
13296
+ import { spawn as spawn3 } from "child_process";
13297
+ import { createInterface as createInterface2 } from "readline/promises";
13298
+ import { basename as basename3, resolve as resolve10 } from "path";
13299
+ var object6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
13300
+ 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.");
13301
+ async function listCodexSessions(prepared, cwd, query) {
13302
+ 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)
13303
+ throw unavailable();
13304
+ const nativeStateEnv = Object.fromEntries(Object.entries(prepared.env).filter(([name]) => ["CODEX_HOME", "CODEX_SQLITE_HOME"].includes(name)));
13305
+ const child = spawn3(prepared.executable, [...prepared.args, "app-server"], {
13306
+ cwd,
13307
+ env: { ...childEnvironment(), ...nativeStateEnv, SWITCHER_HARNESS_API_KEY: "switcher-metadata-no-auth" },
13308
+ stdio: ["pipe", "pipe", "ignore"]
13309
+ });
13310
+ let done = false, initialized = false, pending = Buffer.alloc(0), responseBytes = 0;
13311
+ let killTimer;
13312
+ let resolvePage, rejectPage;
13313
+ const result = new Promise((resolve11, reject2) => {
13314
+ resolvePage = resolve11;
13315
+ rejectPage = reject2;
13316
+ });
13317
+ const closed = new Promise((resolve11) => child.once("close", () => resolve11()));
13318
+ const stop = () => {
13319
+ child.stdin.destroy();
13320
+ child.kill("SIGTERM");
13321
+ killTimer ??= setTimeout(() => child.kill("SIGKILL"), 2000);
13322
+ killTimer.unref();
13323
+ };
13324
+ const fail = (error = unavailable()) => {
13325
+ if (!done) {
13326
+ done = true;
13327
+ rejectPage(error);
13328
+ }
13329
+ stop();
13330
+ };
13331
+ const interrupt = () => fail(new CommandInterrupted(130, "Session discovery was cancelled; no conversation was started."));
13332
+ const terminate = () => fail(new CommandInterrupted(143, "Session discovery was interrupted; no conversation was started."));
13333
+ process.once("SIGINT", interrupt);
13334
+ process.once("SIGTERM", terminate);
13335
+ process.once("SIGHUP", terminate);
13336
+ const timer = setTimeout(() => fail(), 1e4);
13337
+ child.once("error", () => fail());
13338
+ child.stdin.on("error", () => fail());
13339
+ child.once("close", () => {
13340
+ if (!done)
13341
+ fail();
13342
+ });
13343
+ const send = (message) => child.stdin.write(JSON.stringify(message) + `
13344
+ `);
13345
+ child.stdout.on("data", (chunk) => {
13346
+ if (done)
13347
+ return;
13348
+ try {
13349
+ responseBytes += chunk.length;
13350
+ if (responseBytes > 16 * 1024 * 1024 || pending.length + chunk.length > 8 * 1024 * 1024)
13351
+ throw unavailable();
13352
+ pending = Buffer.concat([pending, chunk]);
13353
+ let end;
13354
+ while ((end = pending.indexOf(10)) >= 0) {
13355
+ const line = pending.subarray(0, end);
13356
+ pending = pending.subarray(end + 1);
13357
+ if (!line.length)
13358
+ continue;
13359
+ const message = JSON.parse(line.toString("utf8"));
13360
+ if (!object6(message))
13361
+ throw unavailable();
13362
+ if (message.id === 1) {
13363
+ if (initialized || message.error || !object6(message.result))
13364
+ throw unavailable();
13365
+ initialized = true;
13366
+ send({ method: "initialized" });
13367
+ send({ id: 2, method: "thread/list", params: { ...query, modelProviders: [], useStateDbOnly: false, sortKey: "updated_at", sortDirection: "desc" } });
13368
+ } else if (message.id === 2) {
13369
+ const page = message.result;
13370
+ 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)
13371
+ throw unavailable();
13372
+ const data2 = page.data.map((thread) => {
13373
+ 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")
13374
+ throw unavailable();
13375
+ return { id: thread.id, cwd: thread.cwd, name: thread.name, preview: thread.preview };
13376
+ });
13377
+ done = true;
13378
+ resolvePage({ data: data2, nextCursor: page.nextCursor });
13379
+ stop();
13380
+ return;
13381
+ }
13382
+ }
13383
+ } catch {
13384
+ fail();
13385
+ }
13386
+ });
13387
+ send({ id: 1, method: "initialize", params: { clientInfo: { name: "switcher_session_discovery", version: "1" }, capabilities: { experimentalApi: true } } });
13388
+ try {
13389
+ return await result;
13390
+ } finally {
13391
+ clearTimeout(timer);
13392
+ stop();
13393
+ await closed;
13394
+ if (killTimer)
13395
+ clearTimeout(killTimer);
13396
+ process.off("SIGINT", interrupt);
13397
+ process.off("SIGTERM", terminate);
13398
+ process.off("SIGHUP", terminate);
13399
+ }
13400
+ }
13401
+ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = listCodexSessions) {
13402
+ const command = codexCommandIndex(nativeArgs);
13403
+ if (command < 0 || nativeArgs[command] !== "resume")
13404
+ return nativeArgs;
13405
+ let last = false, all2 = false, positional = false;
13406
+ let effectiveCwd = cwd;
13407
+ const remove = new Set;
13408
+ for (let i = 0;i < nativeArgs.length; i++) {
13409
+ if (i === command)
13410
+ continue;
13411
+ if (nativeArgs[i] === "--") {
13412
+ positional ||= i > command && Boolean(nativeArgs[i + 1]);
13413
+ break;
13414
+ }
13415
+ if (nativeArgs[i].startsWith("--cd="))
13416
+ effectiveCwd = resolve10(cwd, nativeArgs[i].slice(5));
13417
+ else if (nativeArgs[i].startsWith("-C") && nativeArgs[i].length > 2)
13418
+ effectiveCwd = resolve10(cwd, nativeArgs[i].slice(2));
13419
+ if (codexOptionRequestsHelp(nativeArgs[i]))
13420
+ return nativeArgs;
13421
+ if (codexOptionTakesValue(nativeArgs[i])) {
13422
+ if (nativeArgs[i] === "--cd" || nativeArgs[i] === "-C") {
13423
+ if (!nativeArgs[i + 1])
13424
+ throw unavailable();
13425
+ effectiveCwd = resolve10(cwd, nativeArgs[i + 1]);
13426
+ }
13427
+ i++;
13428
+ continue;
13429
+ }
13430
+ if (i > command && nativeArgs[i] === "--last") {
13431
+ last = true;
13432
+ remove.add(i);
13433
+ }
13434
+ if (i > command && nativeArgs[i] === "--all") {
13435
+ all2 = true;
13436
+ remove.add(i);
13437
+ }
13438
+ if (i > command && !nativeArgs[i].startsWith("-"))
13439
+ positional = true;
13440
+ }
13441
+ if (positional && !last)
13442
+ return nativeArgs;
13443
+ const query = { limit: last ? 1 : 30, ...all2 ? {} : { cwd: effectiveCwd } };
13444
+ if (!last && (!process.stdin.isTTY || !process.stderr.isTTY))
13445
+ throw new Fault(400, "codex_session_required", "Provide an exact session ID or use resume --last in noninteractive mode.");
13446
+ const finish = (id2) => [...nativeArgs.slice(0, command), "resume", id2, ...nativeArgs.slice(command + 1).filter((_arg, i) => !remove.has(i + command + 1))];
13447
+ let page = await list(prepared, effectiveCwd, query);
13448
+ if (last) {
13449
+ if (!page.data[0])
13450
+ throw new Fault(404, "codex_session_missing", "No Codex conversations match this workspace. Use resume --all to include other workspaces.");
13451
+ return finish(page.data[0].id);
13452
+ }
13453
+ const reader = createInterface2({ input: process.stdin, output: process.stderr });
13454
+ const controller = new AbortController;
13455
+ const cancel = () => controller.abort(new CommandInterrupted(130, "Session selection was cancelled."));
13456
+ const terminate = () => controller.abort(new CommandInterrupted(143, "Session selection was interrupted."));
13457
+ const hangup = () => controller.abort(new CommandInterrupted(129, "Session selection ended after terminal hangup."));
13458
+ reader.on("SIGINT", cancel);
13459
+ reader.on("close", cancel);
13460
+ process.on("SIGINT", cancel);
13461
+ process.on("SIGTERM", terminate);
13462
+ process.on("SIGHUP", hangup);
13463
+ const display = (value) => value.replace(/[\x00-\x1f\x7f-\x9f]/g, "").slice(0, 180);
13464
+ try {
13465
+ for (;; ) {
13466
+ console.error("Codex conversations across providers:");
13467
+ page.data.forEach((thread, i) => console.error(` ${i + 1}. ${display(thread.name ?? thread.id)} \u2014 workspace ${display(basename3(thread.cwd) || "unknown")}`));
13468
+ const answer = (await reader.question("Number, search text, or n for next page (Ctrl-C cancels): ", { signal: controller.signal }).catch((error) => {
13469
+ throw controller.signal.aborted ? controller.signal.reason : error;
13470
+ })).trim();
13471
+ if (answer.length > 1024)
13472
+ throw new Fault(400, "codex_session_search_limit", "Codex session search text must be at most 1024 characters.");
13473
+ if (/^[1-9]\d*$/.test(answer) && page.data[Number(answer) - 1])
13474
+ return finish(page.data[Number(answer) - 1].id);
13475
+ if (answer === "n") {
13476
+ if (!page.nextCursor) {
13477
+ console.error("No next page.");
13478
+ continue;
13479
+ }
13480
+ query.cursor = page.nextCursor;
13481
+ } else {
13482
+ delete query.cursor;
13483
+ query.searchTerm = answer;
13484
+ }
13485
+ page = await list(prepared, effectiveCwd, query);
13486
+ }
13487
+ } finally {
13488
+ reader.off("SIGINT", cancel);
13489
+ reader.off("close", cancel);
13490
+ process.off("SIGINT", cancel);
13491
+ process.off("SIGTERM", terminate);
13492
+ process.off("SIGHUP", hangup);
13493
+ reader.close();
13494
+ }
13495
+ }
13496
+
12863
13497
  // src/launcher.ts
12864
13498
  var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
12865
13499
  async function writeOriCodexCatalog(stateDir, models) {
12866
- const path = join19(stateDir, "ori-codex-models.json");
13500
+ const path = join20(stateDir, "ori-codex-models.json");
12867
13501
  const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
12868
13502
  await writeFile17(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
12869
13503
  `, { mode: 384, flag: "wx" });
@@ -12903,7 +13537,7 @@ async function oriRequestForPlan(plan, options = {}) {
12903
13537
  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
13538
  if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
12905
13539
  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 });
13540
+ const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve11(options.cwd) : undefined });
12907
13541
  const native = requireOriHarness(contract, target);
12908
13542
  if (!native.path)
12909
13543
  throw new Error("Ori did not report the native harness executable path.");
@@ -12951,13 +13585,14 @@ async function prepareOriForPlan(plan, options) {
12951
13585
  executable: detection.executable,
12952
13586
  version: detection.version,
12953
13587
  stateDir: options.stateDir,
12954
- cwd: resolve9(options.cwd ?? process.cwd()),
12955
- args: options.args ?? []
13588
+ cwd: resolve11(options.cwd ?? process.cwd()),
13589
+ args: options.args ?? [],
13590
+ sharedState: options.sharedState
12956
13591
  });
12957
13592
  try {
12958
13593
  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 });
13594
+ const dir = join20(options.stateDir, "ori-bin"), path = join20(dir, shim.name);
13595
+ await mkdir12(dir, { mode: 448 });
12961
13596
  await writeFile17(path, shim.script, { mode: 448, flag: "wx" });
12962
13597
  return { contract, prepared: {
12963
13598
  ...ori,
@@ -12980,7 +13615,7 @@ async function launch(client, profileId, options = {}) {
12980
13615
  assertHarnessArguments(profile.harness, options.args ?? []);
12981
13616
  if (profile.harness === "gemini" || profile.harness === "antigravity")
12982
13617
  validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
12983
- await validateHarnessConfiguration(profile.harness, resolve9(options.cwd ?? process.cwd()), options.args);
13618
+ await validateHarnessConfiguration(profile.harness, resolve11(options.cwd ?? process.cwd()), options.args);
12984
13619
  if (profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((process.env.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
12985
13620
  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
13621
  if (profile.harness === "grok" && process.env.GROK_FORCE_LOGIN_TEAM_ID?.trim())
@@ -12989,7 +13624,7 @@ async function launch(client, profileId, options = {}) {
12989
13624
  await client.refreshModels(profile.providerId);
12990
13625
  const plan = await client.launchPlan(profileId);
12991
13626
  assertHarnessArguments(plan.profile.harness, options.args ?? []);
12992
- await validateHarnessConfiguration(plan.profile.harness, resolve9(options.cwd ?? process.cwd()), options.args);
13627
+ await validateHarnessConfiguration(plan.profile.harness, resolve11(options.cwd ?? process.cwd()), options.args);
12993
13628
  if (options.credentialPreflight && providerCredentialFingerprint(plan.provider) !== options.credentialPreflight)
12994
13629
  throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
12995
13630
  const backend = options.backend ?? "direct";
@@ -13011,9 +13646,9 @@ async function launch(client, profileId, options = {}) {
13011
13646
  validateHarnessVersion("gemini", detection?.version);
13012
13647
  if (backend === "direct" && plan.profile.harness === "aider")
13013
13648
  validateHarnessVersion(plan.profile.harness, detection?.version);
13014
- const root = resolve9(options.stateDir ?? join19(switcherHome(), "state"));
13649
+ const root = resolve11(options.stateDir ?? join20(switcherHome(), "state"));
13015
13650
  await privateDirectory(root);
13016
- const stateDir = await mkdtemp(join19(root, "launch-"));
13651
+ const stateDir = await mkdtemp(join20(root, "launch-"));
13017
13652
  let credential;
13018
13653
  if (backend === "direct") {
13019
13654
  try {
@@ -13057,6 +13692,27 @@ async function launch(client, profileId, options = {}) {
13057
13692
  return;
13058
13693
  });
13059
13694
  try {
13695
+ if (options.shareNativeState && plan.profile.harness !== "codex" && plan.profile.harness !== "claude")
13696
+ throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
13697
+ const shareRequested = (plan.profile.harness === "codex" || plan.profile.harness === "claude") && nativeStateRequested(plan.profile.harness, process.env, Boolean(options.shareNativeState));
13698
+ if (shareRequested && backend !== "direct")
13699
+ 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.");
13700
+ if (shareRequested && plan.profile.harness === "codex") {
13701
+ assertHarnessArguments("codex", options.args ?? [], { reservedCodexRoots: ["sqlite_home"] });
13702
+ validateNativeStateVersion("codex", detection?.version);
13703
+ }
13704
+ const sharedState = shareRequested ? await resolveNativeState(plan.profile.harness) : undefined;
13705
+ const desktopState = profileId;
13706
+ 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)] : [];
13707
+ let nativeHome2;
13708
+ if (sharedState && !options.desktop && !options.claudeDesktop) {
13709
+ const variable = sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
13710
+ const configured = process.env[variable] ? resolve11(process.env[variable]) : undefined;
13711
+ nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join20(root, "native-claude", profileId) : configured ?? sharedState.home;
13712
+ await privateDirectory(nativeHome2);
13713
+ await assertNativeInstructionOverlay(sharedState, nativeHome2);
13714
+ await projectNativeState(sharedState, nativeHome2);
13715
+ }
13060
13716
  const input = {
13061
13717
  harness: plan.profile.harness,
13062
13718
  baseUrl: plan.provider.baseUrl,
@@ -13069,9 +13725,10 @@ async function launch(client, profileId, options = {}) {
13069
13725
  onRoutingEvent,
13070
13726
  credential,
13071
13727
  stateDir,
13072
- cwd: resolve9(options.cwd ?? process.cwd())
13728
+ cwd: resolve11(options.cwd ?? process.cwd()),
13729
+ sharedState
13073
13730
  };
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({
13731
+ 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
13732
  harness: plan.profile.harness,
13076
13733
  baseUrl: plan.provider.baseUrl,
13077
13734
  protocol: plan.provider.protocol,
@@ -13087,13 +13744,26 @@ async function launch(client, profileId, options = {}) {
13087
13744
  executable: nativeExecutable ?? detection?.executable,
13088
13745
  args: options.args ?? [],
13089
13746
  stateDir,
13090
- cwd: resolve9(options.cwd ?? process.cwd()),
13747
+ cwd: resolve11(options.cwd ?? process.cwd()),
13091
13748
  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) } : {}
13749
+ sharedState,
13750
+ ...["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
13751
  });
13094
13752
  cleanup = prepared.cleanup;
13753
+ prepared = { ...prepared, warnings: [...prepared.warnings, ...stateWarnings] };
13754
+ if (sharedState)
13755
+ prepared = { ...prepared, env: {
13756
+ ...prepared.env,
13757
+ ...nativeStateEnvironment(sharedState),
13758
+ ...nativeHome2 ? { [sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"]: nativeHome2 } : {}
13759
+ } };
13760
+ if (sharedState?.tool === "codex" && !options.desktop && backend === "direct" && options.args?.length) {
13761
+ const baseArgs = prepared.args.slice(0, prepared.args.length - options.args.length);
13762
+ const resumedArgs = await resolveCodexResumeArguments({ ...prepared, args: baseArgs }, options.args, input.cwd);
13763
+ prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
13764
+ }
13095
13765
  if (options.desktop) {
13096
- prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join19(root, "desktop", profileId));
13766
+ prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join20(root, "desktop", desktopState), sharedState);
13097
13767
  cleanup = prepared.cleanup;
13098
13768
  }
13099
13769
  for (const warning of [...plan.warnings, ...prepared.warnings])
@@ -13170,7 +13840,7 @@ async function launch(client, profileId, options = {}) {
13170
13840
  interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
13171
13841
  throw preparationSignal;
13172
13842
  }
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 });
13843
+ 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
13844
  await cleanup?.();
13175
13845
  cleanup = undefined;
13176
13846
  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 +13857,8 @@ async function launch(client, profileId, options = {}) {
13187
13857
  } finally {
13188
13858
  if (lateCreateRunFinalization) {
13189
13859
  let finalizationTimer;
13190
- const finalizationTimeout = new Promise((resolve10) => {
13191
- finalizationTimer = setTimeout(resolve10, LATE_RUN_FINALIZATION_TIMEOUT_MS);
13860
+ const finalizationTimeout = new Promise((resolve12) => {
13861
+ finalizationTimer = setTimeout(resolve12, LATE_RUN_FINALIZATION_TIMEOUT_MS);
13192
13862
  });
13193
13863
  try {
13194
13864
  await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
@@ -13208,7 +13878,7 @@ async function launch(client, profileId, options = {}) {
13208
13878
 
13209
13879
  // src/direct-launch.ts
13210
13880
  import { createHash as createHash14 } from "crypto";
13211
- import { createInterface as createInterface2 } from "readline/promises";
13881
+ import { createInterface as createInterface3 } from "readline/promises";
13212
13882
  var absent2 = (error) => error instanceof SwitcherError && error.status === 404;
13213
13883
  async function resolveLaunchProvider(client, selector, options = {}) {
13214
13884
  let existing;
@@ -13239,7 +13909,7 @@ async function resolveLaunchProvider(client, selector, options = {}) {
13239
13909
  existing = await client.getProvider(desired.id);
13240
13910
  }
13241
13911
  }
13242
- const { version, updatedAt, ...input } = existing;
13912
+ const { version: version2, updatedAt, ...input } = existing;
13243
13913
  const { additionalModels: _savedAdditions, credentialCheck: savedCredentialCheck, ...savedSettings } = parse2(providerInputSchema, input);
13244
13914
  const { additionalModels: _presetAdditions, credentialCheck: presetCredentialCheck, ...presetSettings } = desired;
13245
13915
  if (JSON.stringify(savedSettings) !== JSON.stringify(presetSettings) || savedCredentialCheck !== undefined && JSON.stringify(savedCredentialCheck) !== JSON.stringify(presetCredentialCheck))
@@ -13253,7 +13923,7 @@ async function selectModel(models, query = "", harness) {
13253
13923
  const eligible = models.filter((m) => harness ? harnessEligible(m, harness) : codingEligible(m));
13254
13924
  if (!eligible.length)
13255
13925
  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 });
13926
+ const reader = createInterface3({ input: process.stdin, output: process.stderr });
13257
13927
  const cancellation = new AbortController;
13258
13928
  const cancel = () => cancellation.abort(new CommandInterrupted(130, "Model selection was cancelled; no harness was started."));
13259
13929
  const terminate = () => cancellation.abort(new CommandInterrupted(143, "Model selection was interrupted; no harness was started."));
@@ -13311,14 +13981,343 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
13311
13981
  return existing;
13312
13982
  }
13313
13983
 
13984
+ // src/native-state-import.ts
13985
+ import { createHash as createHash15 } from "crypto";
13986
+ import { constants as constants8 } from "fs";
13987
+ import { lstat as lstat9, open as open5, opendir as opendir2, link as link2, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
13988
+ import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join21, relative as relative6, resolve as resolve12 } from "path";
13989
+ var MAX_FILES = 1e5;
13990
+ var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
13991
+ 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.");
13992
+ async function info2(path) {
13993
+ try {
13994
+ return await lstat9(path);
13995
+ } catch (error) {
13996
+ if (error.code === "ENOENT")
13997
+ return;
13998
+ throw error;
13999
+ }
14000
+ }
14001
+ var identity = (s) => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs, ctimeMs: s.ctimeMs });
14002
+ var same = (a, b) => JSON.stringify(identity(a)) === JSON.stringify(identity(b));
14003
+ var inside3 = (parent, child) => {
14004
+ const path = relative6(parent, child);
14005
+ return path !== ".." && !path.startsWith("../") && !isAbsolute17(path);
14006
+ };
14007
+ var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
14008
+ async function sessionId(path, expected) {
14009
+ const nameId = basename4(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
14010
+ const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
14011
+ try {
14012
+ const before = await handle.stat();
14013
+ if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
14014
+ throw refused();
14015
+ const buffer = Buffer.alloc(Math.min(before.size, 1024 * 1024));
14016
+ let length = 0, newline = -1;
14017
+ while (length < buffer.length && newline < 0) {
14018
+ const read = await handle.read(buffer, length, buffer.length - length, null);
14019
+ if (!read.bytesRead)
14020
+ break;
14021
+ length += read.bytesRead;
14022
+ newline = buffer.indexOf(10, 0);
14023
+ }
14024
+ const after = await handle.stat(), named = await lstat9(path);
14025
+ if (!same(before, after) || !same(after, named) || after.nlink !== 1 || named.nlink !== 1 || named.isSymbolicLink())
14026
+ throw refused();
14027
+ if (newline < 0 && before.size > buffer.length)
14028
+ throw refused();
14029
+ let row;
14030
+ try {
14031
+ row = JSON.parse(buffer.subarray(0, newline < 0 ? length : newline).toString("utf8"));
14032
+ } catch {
14033
+ return nameId;
14034
+ }
14035
+ if (row && typeof row === "object" && "type" in row && row.type === "session_meta") {
14036
+ const value = row.payload?.id;
14037
+ if (typeof value !== "string" || !SESSION_ID.test(value) || nameId && value.toLowerCase() !== nameId)
14038
+ throw refused();
14039
+ return value.toLowerCase();
14040
+ }
14041
+ return nameId;
14042
+ } finally {
14043
+ await handle.close();
14044
+ }
14045
+ }
14046
+ async function checkSessionIdentities(plan) {
14047
+ if (plan.state.tool !== "codex")
14048
+ return;
14049
+ const ids = new Map;
14050
+ for (const file of plan.files) {
14051
+ if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
14052
+ continue;
14053
+ file.sessionId = await sessionId(join21(plan.source, file.path), file.source);
14054
+ if (!file.sessionId)
14055
+ continue;
14056
+ const previous = ids.get(file.sessionId);
14057
+ if (previous?.some((other) => other.sha256 !== file.sha256))
14058
+ throw refused();
14059
+ if (previous) {
14060
+ file.existing = true;
14061
+ previous.push(file);
14062
+ } else
14063
+ ids.set(file.sessionId, [file]);
14064
+ }
14065
+ if (!ids.size)
14066
+ return;
14067
+ let seen = 0;
14068
+ async function scan(directory, depth = 0) {
14069
+ if (++seen > MAX_FILES || depth > 32)
14070
+ throw refused();
14071
+ if (!await info2(directory))
14072
+ return;
14073
+ await assertNativeStateDirectory(directory);
14074
+ for await (const entry of await opendir2(directory)) {
14075
+ if (++seen > MAX_FILES || entry.isSymbolicLink())
14076
+ throw refused();
14077
+ const path = join21(directory, entry.name);
14078
+ if (entry.isDirectory()) {
14079
+ await scan(path, depth + 1);
14080
+ continue;
14081
+ }
14082
+ if (!entry.isFile() || !entry.name.endsWith(".jsonl"))
14083
+ continue;
14084
+ const id2 = await sessionId(path);
14085
+ if (!id2 || !ids.has(id2))
14086
+ continue;
14087
+ const existing = await fingerprint2(path), importing = ids.get(id2);
14088
+ if (importing.some((file) => file.sha256 !== existing.sha256))
14089
+ throw refused();
14090
+ for (const file of importing)
14091
+ file.existing = true;
14092
+ }
14093
+ }
14094
+ await scan(join21(plan.state.home, "sessions"));
14095
+ await scan(join21(plan.state.home, "archived_sessions"));
14096
+ }
14097
+ async function fingerprint2(path, copyTo) {
14098
+ const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
14099
+ let output, complete = false;
14100
+ try {
14101
+ const before = await handle.stat();
14102
+ if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
14103
+ throw refused();
14104
+ if (copyTo)
14105
+ output = await open5(copyTo, "wx", 384);
14106
+ const hash3 = createHash15("sha256"), buffer = Buffer.alloc(64 * 1024);
14107
+ let bytes = 0;
14108
+ for (;; ) {
14109
+ const read = await handle.read(buffer, 0, buffer.length, null);
14110
+ if (!read.bytesRead)
14111
+ break;
14112
+ bytes += read.bytesRead;
14113
+ if (bytes > MAX_BYTES2)
14114
+ throw refused();
14115
+ const chunk = buffer.subarray(0, read.bytesRead);
14116
+ hash3.update(chunk);
14117
+ if (output) {
14118
+ let offset = 0;
14119
+ while (offset < chunk.length)
14120
+ offset += (await output.write(chunk, offset, chunk.length - offset)).bytesWritten;
14121
+ }
14122
+ }
14123
+ const after = await handle.stat(), named = await lstat9(path);
14124
+ if (named.isSymbolicLink() || after.nlink !== 1 || named.nlink !== 1 || bytes !== before.size || !same(before, after) || !same(after, named))
14125
+ throw refused();
14126
+ await output?.sync();
14127
+ complete = true;
14128
+ return { bytes, sha256: hash3.digest("hex"), source: identity(before) };
14129
+ } finally {
14130
+ await output?.close();
14131
+ await handle.close();
14132
+ if (copyTo && !complete)
14133
+ await unlink3(copyTo).catch(() => {
14134
+ return;
14135
+ });
14136
+ }
14137
+ }
14138
+ async function planNativeStateImport(state, source, selection) {
14139
+ if (!isAbsolute17(source) || source.includes("\x00"))
14140
+ throw refused();
14141
+ source = resolve12(source);
14142
+ if (inside3(source, state.home) || inside3(state.home, source))
14143
+ throw refused();
14144
+ await assertNativeStateDirectory(source);
14145
+ await ensureNativeStateDirectory(state.home, false);
14146
+ const allowed = NATIVE_STATE_ENTRIES[state.tool].filter((entry) => entry.name !== "thread-writer-locks");
14147
+ const entries = selection?.length ? [...new Set(selection)] : allowed.map((entry) => entry.name);
14148
+ if (entries.some((name) => !allowed.some((entry) => entry.name === name)))
14149
+ throw refused();
14150
+ const plan = { state, source, entries, files: [], directories: [], bytes: 0 };
14151
+ let seen = 0;
14152
+ async function visit(path, kind) {
14153
+ if (++seen > MAX_FILES || path.split("/").length > 32)
14154
+ throw refused();
14155
+ await ensureNativeStateDirectory(dirname9(join21(source, path)), false);
14156
+ await ensureNativeStateDirectory(dirname9(join21(state.home, path)), false);
14157
+ const from = join21(source, path), to = join21(state.home, path), entry = await info2(from), target = await info2(to);
14158
+ if (!entry)
14159
+ return;
14160
+ if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
14161
+ throw refused();
14162
+ if (kind === "directory") {
14163
+ await assertNativeStateDirectory(from);
14164
+ if (target)
14165
+ await assertNativeStateDirectory(to);
14166
+ plan.directories.push(path);
14167
+ const directory = await opendir2(from);
14168
+ const children = [];
14169
+ for await (const child of directory) {
14170
+ if (children.length + seen >= MAX_FILES || child.isSymbolicLink() || !(child.isDirectory() || child.isFile()))
14171
+ throw refused();
14172
+ children.push({ name: child.name, kind: child.isDirectory() ? "directory" : "file" });
14173
+ }
14174
+ children.sort((a, b) => a.name.localeCompare(b.name));
14175
+ for (const child of children)
14176
+ await visit(join21(path, child.name), child.kind);
14177
+ } else {
14178
+ const value = await fingerprint2(from);
14179
+ plan.bytes += value.bytes;
14180
+ if (plan.bytes > MAX_BYTES2)
14181
+ throw refused();
14182
+ if (target && (target.isSymbolicLink() || !target.isFile()))
14183
+ throw refused();
14184
+ if (target) {
14185
+ const existing = await fingerprint2(to);
14186
+ if (existing.bytes !== value.bytes || existing.sha256 !== value.sha256)
14187
+ throw refused();
14188
+ }
14189
+ plan.files.push({ path, ...value, existing: Boolean(target) });
14190
+ }
14191
+ }
14192
+ for (const name of entries)
14193
+ await visit(name, allowed.find((entry) => entry.name === name).kind);
14194
+ await checkSessionIdentities(plan);
14195
+ return plan;
14196
+ }
14197
+ function nativeStateImportDigest(plan) {
14198
+ return createHash15("sha256").update(JSON.stringify({
14199
+ tool: plan.state.tool,
14200
+ source: plan.source,
14201
+ destination: plan.state.home,
14202
+ entries: plan.entries,
14203
+ directories: plan.directories,
14204
+ files: plan.files.map((file) => ({ path: file.path, bytes: file.bytes, sha256: file.sha256, source: file.source, existing: file.existing, sessionId: file.sessionId }))
14205
+ })).digest("hex");
14206
+ }
14207
+ function nativeStateImportSummary(plan, applied) {
14208
+ const newFiles = plan.files.filter((file) => !file.existing).length;
14209
+ return {
14210
+ mode: applied ? "staged-snapshot" : "dry-run",
14211
+ tool: plan.state.tool,
14212
+ entries: plan.entries,
14213
+ planDigest: nativeStateImportDigest(plan),
14214
+ files: plan.files.length,
14215
+ newFiles,
14216
+ publishedFiles: applied ? newFiles : 0,
14217
+ bytes: plan.bytes,
14218
+ originalsPreserved: true,
14219
+ cutoverComplete: false,
14220
+ sqliteCopied: false,
14221
+ 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."
14222
+ };
14223
+ }
14224
+ async function applyNativeStateImportUnlocked(plan) {
14225
+ const fresh = await planNativeStateImport(plan.state, plan.source, plan.entries);
14226
+ if (JSON.stringify(fresh) !== JSON.stringify(plan))
14227
+ throw refused();
14228
+ const requiredDirectories = new Set([plan.state.home]);
14229
+ for (const path of plan.directories) {
14230
+ for (let directory = join21(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname9(directory)) {
14231
+ requiredDirectories.add(directory);
14232
+ if (directory === plan.state.home)
14233
+ break;
14234
+ }
14235
+ }
14236
+ for (const file of plan.files.filter((file2) => !file2.existing)) {
14237
+ for (let directory = dirname9(join21(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname9(directory)) {
14238
+ requiredDirectories.add(directory);
14239
+ if (directory === plan.state.home)
14240
+ break;
14241
+ }
14242
+ }
14243
+ const directories = [...requiredDirectories].sort((a, b) => a.length - b.length), createdDirectories = [];
14244
+ const staged = [];
14245
+ let published = 0;
14246
+ let committed = false, cleanupFailed = false;
14247
+ try {
14248
+ for (const directory of directories) {
14249
+ if (!await info2(directory)) {
14250
+ await ensureNativeStateDirectory(directory);
14251
+ createdDirectories.push(directory);
14252
+ } else
14253
+ await assertNativeStateDirectory(directory);
14254
+ }
14255
+ for (const file of plan.files) {
14256
+ if (file.existing)
14257
+ continue;
14258
+ const target = join21(plan.state.home, file.path), temporary = join21(dirname9(target), `.switcher-import-${crypto.randomUUID()}`);
14259
+ staged.push({ temporary, target });
14260
+ const copied = await fingerprint2(join21(plan.source, file.path), temporary);
14261
+ if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
14262
+ throw refused();
14263
+ }
14264
+ for (const item2 of staged) {
14265
+ try {
14266
+ await link2(item2.temporary, item2.target);
14267
+ published++;
14268
+ } catch (error) {
14269
+ if (published)
14270
+ 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.`);
14271
+ throw error;
14272
+ }
14273
+ }
14274
+ committed = true;
14275
+ } finally {
14276
+ for (const item2 of staged) {
14277
+ try {
14278
+ await unlink3(item2.temporary);
14279
+ } catch (error) {
14280
+ if (error.code !== "ENOENT")
14281
+ cleanupFailed = true;
14282
+ }
14283
+ }
14284
+ if (!committed && published === 0) {
14285
+ for (const directory of createdDirectories.sort((a, b) => b.length - a.length)) {
14286
+ try {
14287
+ await rmdir2(directory);
14288
+ } catch (error) {
14289
+ if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
14290
+ cleanupFailed = true;
14291
+ }
14292
+ }
14293
+ }
14294
+ if (cleanupFailed)
14295
+ 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.");
14296
+ }
14297
+ }
14298
+ async function applyNativeStateImport(plan) {
14299
+ const existed = Boolean(await info2(plan.state.home));
14300
+ await ensureNativeStateDirectory(plan.state.home);
14301
+ try {
14302
+ return await withNativeStateLock(plan.state, () => applyNativeStateImportUnlocked(plan));
14303
+ } catch (error) {
14304
+ if (!existed)
14305
+ await rmdir2(plan.state.home).catch(() => {
14306
+ return;
14307
+ });
14308
+ throw error;
14309
+ }
14310
+ }
14311
+
13314
14312
  // src/cli.ts
13315
14313
  var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your provider and model
13316
14314
 
13317
14315
  switcher launch chatgpt --provider PROVIDER --model MODEL [--reasoning EFFORT]
13318
- [--dangerously-bypass-approvals-and-sandbox] [--app-path /absolute/ChatGPT.app]
14316
+ [--dangerously-bypass-approvals-and-sandbox] [--share-native-state]
14317
+ [--app-path /absolute/ChatGPT.app]
13319
14318
  [--dry-run] [--cwd DIR] [--timeout SECONDS]
13320
14319
  switcher launch claude-desktop --provider PROVIDER --model MODEL
13321
- [--app-path /absolute/Claude.app] [--dry-run]
14320
+ [--share-native-state] [--app-path /absolute/Claude.app] [--dry-run]
13322
14321
  switcher providers presets [ID]
13323
14322
  switcher providers list [--search TEXT] [--limit N] [--offset N]
13324
14323
  switcher providers add ID --url URL --protocol PROTOCOL [--credential-env NAME]
@@ -13336,8 +14335,8 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
13336
14335
  switcher profiles add ID --provider ID --harness HARNESS --model MODEL [--model-policy-file FILE] [--role-model ROLE=MODEL]
13337
14336
  switcher profiles update ID --file profile.json --version N
13338
14337
  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]
14338
+ switcher launch HARNESS --provider PROVIDER [--model MODEL] [--share-native-state] [--dry-run]
14339
+ switcher launch PROFILE [--backend direct|ori] [--share-native-state] [--cwd DIR] [--executable PATH]
13341
14340
  [--ori-executable PATH] [--state-dir DIR]
13342
14341
  [--timeout SECONDS] -- [native harness arguments]
13343
14342
  switcher runs list|get [ID]
@@ -13348,9 +14347,11 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
13348
14347
  switcher credentials repair-executable PRESET_OR_REFERENCE --sha256 EXPECTED
13349
14348
  switcher credentials repair-executable --vault-cli PATH --sha256 EXPECTED
13350
14349
  switcher doctor
14350
+ switcher state import codex|claude --from LEGACY_NATIVE_HOME [--entry NAME]... [--dry-run | --apply --plan-digest SHA256]
13351
14351
 
13352
14352
  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.
14353
+ chatgpt launches the installed macOS desktop app with private login data.
14354
+ Use --share-native-state to project the canonical noncredential Codex/Claude corpus.
13354
14355
  Its local Codex conversations use the selected Responses-compatible provider.
13355
14356
  claude-desktop launches Claude in its separate Claude-3p gateway profile with a
13356
14357
  Messages-compatible provider. Quit that instance before switching providers.
@@ -13436,6 +14437,11 @@ async function main(args = process.argv.slice(2)) {
13436
14437
  "app-path": { type: "string" },
13437
14438
  reasoning: { type: "string" },
13438
14439
  "dangerously-bypass-approvals-and-sandbox": { type: "boolean" },
14440
+ "share-native-state": { type: "boolean" },
14441
+ from: { type: "string" },
14442
+ entry: { type: "string", multiple: true },
14443
+ apply: { type: "boolean" },
14444
+ "plan-digest": { type: "string" },
13439
14445
  protocol: { type: "string" },
13440
14446
  preset: { type: "string" },
13441
14447
  name: { type: "string" },
@@ -13481,12 +14487,30 @@ async function main(args = process.argv.slice(2)) {
13481
14487
  }
13482
14488
  const [command, action2, id2] = positionals;
13483
14489
  const output = (value) => console.log(JSON.stringify(value, null, 2));
14490
+ if (command === "state") {
14491
+ 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"]))
14492
+ 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.");
14493
+ const state = await resolveNativeState(id2, process.env, { create: false });
14494
+ const plan = await planNativeStateImport(state, values2.from, values2.entry);
14495
+ if (values2.apply && values2["plan-digest"] !== nativeStateImportDigest(plan))
14496
+ 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.");
14497
+ if (values2.apply)
14498
+ await applyNativeStateImport(plan);
14499
+ output(nativeStateImportSummary(plan, Boolean(values2.apply)));
14500
+ return;
14501
+ }
14502
+ if (values2.from !== undefined || values2.entry !== undefined || values2.apply !== undefined || values2["plan-digest"] !== undefined)
14503
+ throw new Fault(400, "conflicting_options", "--from, --entry, --plan-digest, --dry-run and --apply belong to switcher state import.");
14504
+ if (values2["share-native-state"] && command !== "launch")
14505
+ throw new Fault(400, "conflicting_options", "--share-native-state belongs to a Codex, ChatGPT, Claude CLI or Claude desktop launch.");
13484
14506
  const reasoning = values2.reasoning === undefined ? undefined : parse2(reasoningEffortSchema, values2.reasoning);
13485
14507
  const dangerouslyBypassApprovalsAndSandbox = values2["dangerously-bypass-approvals-and-sandbox"];
13486
14508
  if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" || values2.provider && !["chatgpt", "codex"].includes(action2) || values2.backend && values2.backend !== "direct"))
13487
14509
  throw new Fault(400, "conflicting_options", "--reasoning and --dangerously-bypass-approvals-and-sandbox require a direct Codex or ChatGPT launch.");
13488
14510
  const chatgpt = command === "launch" && action2 === "chatgpt" && values2.provider !== undefined;
13489
14511
  const claudeDesktop = command === "launch" && action2 === "claude-desktop" && values2.provider !== undefined;
14512
+ if (values2["share-native-state"] && values2.provider !== undefined && !["codex", "claude", "chatgpt", "claude-desktop"].includes(action2))
14513
+ throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
13490
14514
  if (values2["app-path"] !== undefined && !chatgpt && !claudeDesktop)
13491
14515
  throw new Fault(400, "conflicting_options", "--app-path belongs to launch chatgpt or claude-desktop --provider PROVIDER --model MODEL.");
13492
14516
  if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 || values2.executable !== undefined || values2.backend !== undefined || values2["ori-executable"] !== undefined))
@@ -13692,6 +14716,8 @@ async function main(args = process.argv.slice(2)) {
13692
14716
  if (values2.model || values2.protocol || values2.url || values2["credential-env"] || values2["model-policy-file"] || values2["role-model"])
13693
14717
  throw new Error("Use --provider PROVIDER for a direct launch, or update the saved profile explicitly.");
13694
14718
  const profile = await client.getProfile(profileId);
14719
+ if (values2["share-native-state"] && !["codex", "claude"].includes(profile.harness))
14720
+ throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
13695
14721
  assertHarnessArguments(profile.harness, nativeArgs);
13696
14722
  await validateHarnessConfiguration(profile.harness, values2.cwd ?? process.cwd(), nativeArgs);
13697
14723
  const provider = await client.getProvider(profile.providerId);
@@ -13718,14 +14744,24 @@ async function main(args = process.argv.slice(2)) {
13718
14744
  codexReasoning(model3, plan.provider.baseUrl, reasoning);
13719
14745
  }
13720
14746
  assertHarnessArguments(plan.profile.harness, nativeArgs);
14747
+ if (values2["share-native-state"] && !["codex", "claude"].includes(plan.profile.harness))
14748
+ throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
14749
+ const sharedNativeState = ["codex", "claude"].includes(plan.profile.harness) && nativeStateRequested(plan.profile.harness, process.env, Boolean(values2["share-native-state"]));
14750
+ if (sharedNativeState) {
14751
+ if (plan.profile.harness === "codex")
14752
+ assertHarnessArguments("codex", nativeArgs, { reservedCodexRoots: ["sqlite_home"] });
14753
+ await resolveNativeState(plan.profile.harness, process.env, { create: false });
14754
+ }
13721
14755
  if (backend === "ori") {
14756
+ if (sharedNativeState)
14757
+ 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
14758
  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] } });
14759
+ 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
14760
  } 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" } } : {} });
14761
+ 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
14762
  return;
13727
14763
  }
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)) });
14764
+ 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
14765
  return;
13730
14766
  }
13731
14767
  if (editingModel) {