@hasna/switcher 0.2.9 → 0.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -514,7 +514,7 @@ function canonicalPolicyJSON(value) {
514
514
  return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
515
515
  }
516
516
  // package.json
517
- var version = "0.2.9";
517
+ var version = "0.2.11";
518
518
 
519
519
  // src/version.ts
520
520
  var VERSION = version;
@@ -1109,6 +1109,7 @@ function assertHarnessArguments(harness, args, options = {}) {
1109
1109
 
1110
1110
  // src/cli.ts
1111
1111
  import { parseArgs } from "util";
1112
+ import { join as join23, resolve as resolve14 } from "path";
1112
1113
 
1113
1114
  // src/http.ts
1114
1115
  var MAX_BYTES = 16 * 1024 * 1024;
@@ -1371,9 +1372,14 @@ async function detectChatGPTApp(appPath, system = host) {
1371
1372
  const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
1372
1373
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
1373
1374
  continue;
1374
- const executable = join3(path, "Contents/MacOS", name), codexExecutable = join3(path, "Contents/Resources/codex");
1375
- if (await system.executable(executable) && await system.executable(codexExecutable))
1376
- return { path, executable, codexExecutable, bundleId, version: version2 };
1375
+ const executable = join3(path, "Contents/MacOS", name);
1376
+ if (!await system.executable(executable))
1377
+ continue;
1378
+ for (const relative2 of ["Contents/Resources/codex", "Contents/Resources/codex-cli/CodexCLI.app/Contents/MacOS/codex"]) {
1379
+ const codexExecutable = join3(path, relative2);
1380
+ if (await system.executable(codexExecutable))
1381
+ return { path, executable, codexExecutable, bundleId, version: version2 };
1382
+ }
1377
1383
  } catch {}
1378
1384
  }
1379
1385
  throw new Fault(404, "app_not_installed", "Install the current ChatGPT/Codex macOS app or use --app-path with its absolute .app path. Legacy ChatGPT Classic cannot run custom Codex providers.");
@@ -2543,7 +2549,7 @@ var openapi_default = {
2543
2549
  openapi: "3.0.3",
2544
2550
  info: {
2545
2551
  title: "Switcher API",
2546
- version: "0.2.9",
2552
+ version: "0.2.11",
2547
2553
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2548
2554
  },
2549
2555
  security: [
@@ -11323,16 +11329,66 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
11323
11329
  }
11324
11330
 
11325
11331
  // src/launcher.ts
11326
- import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile17 } from "fs/promises";
11327
- import { join as join20, resolve as resolve11 } from "path";
11332
+ import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile18 } from "fs/promises";
11333
+ import { join as join21, resolve as resolve12 } from "path";
11328
11334
 
11329
11335
  // src/provider-credential-onboarding.ts
11330
- import { z as z8 } from "zod";
11336
+ import { z as z9 } from "zod";
11331
11337
  import { createHash as createHash11 } from "crypto";
11332
11338
  import { createInterface } from "readline/promises";
11333
11339
 
11334
- // src/credentials.ts
11340
+ // src/opencode-authentication.ts
11335
11341
  import { z as z7 } from "zod";
11342
+ var endpoint3 = "https://opencode.ai/zen/v1/systemone";
11343
+ var body = JSON.stringify({
11344
+ model: "jev-1.13-free",
11345
+ state: "The fixed test number is 7.",
11346
+ questions: { match: { type: "noul", instructions: "Is the fixed test number 7?" } }
11347
+ });
11348
+ var responseSchema = z7.object({
11349
+ model: z7.enum(["jev-1.13", "jev-1.13.0", "jev-1.13-free"]),
11350
+ answers: z7.object({ match: z7.object({ type: z7.literal("noul"), noul: z7.number().finite().min(0).max(1) }) }),
11351
+ usage: z7.object({ input_tokens: z7.number().int().nonnegative(), output_tokens: z7.number().int().nonnegative() })
11352
+ });
11353
+ var authErrorSchema = z7.object({ error: z7.object({ type: z7.enum(["AuthError", "server_error"]) }) });
11354
+ var unavailable = () => new Fault(502, "provider_auth_unavailable", "OpenCode authentication could not be verified with its free check. The selected credential was preserved; no paid model was requested.");
11355
+ function supportsOpenCodeAuthentication(provider) {
11356
+ return provider.credentialEnv === "SWITCHER_PROVIDER_OPENCODE" && ["https://opencode.ai/zen/v1", "https://opencode.ai/zen/v1/"].includes(provider.baseUrl) && (["openai-chat", "openai-responses"].includes(provider.protocol) ? (provider.authStyle ?? "bearer") === "bearer" : provider.protocol === "anthropic-messages" && provider.authStyle === "x-api-key");
11357
+ }
11358
+ async function verifyOpenCodeAuthentication(credential, fetchImpl) {
11359
+ if (!credential || /[\s\x00-\x1f\x7f]/u.test(credential) || credential.toLowerCase() === "public")
11360
+ return { authenticated: false, status: 401 };
11361
+ const signal = AbortSignal.timeout(1e4);
11362
+ const request = async (value) => {
11363
+ try {
11364
+ const response = await fetchImpl(endpoint3, {
11365
+ method: "POST",
11366
+ redirect: "manual",
11367
+ cache: "no-store",
11368
+ signal,
11369
+ body,
11370
+ headers: { accept: "application/json", "content-type": "application/json", "user-agent": "hasna-switcher/credential-check", authorization: `Bearer ${value}` }
11371
+ });
11372
+ return { status: response.status, data: await boundedJson(response, 16 * 1024) };
11373
+ } catch {
11374
+ throw unavailable();
11375
+ }
11376
+ };
11377
+ for (const invalid3 of ["hasna-switcher-invalid-credential", "oc_sk_invalid"]) {
11378
+ const control = await request(invalid3);
11379
+ if (control.status !== 401 || !authErrorSchema.safeParse(control.data).success)
11380
+ throw unavailable();
11381
+ }
11382
+ const result = await request(credential);
11383
+ if ((result.status === 401 || result.status === 403) && authErrorSchema.safeParse(result.data).success)
11384
+ return { authenticated: false, status: result.status };
11385
+ if (result.status !== 200 || !responseSchema.safeParse(result.data).success)
11386
+ throw unavailable();
11387
+ return { authenticated: true, status: 200 };
11388
+ }
11389
+
11390
+ // src/credentials.ts
11391
+ import { z as z8 } from "zod";
11336
11392
  import { ExecutableTrustError, repairExecutablePermissions, validateExecutable } from "@hasna/contracts/executable-trust";
11337
11393
  import { constants as constants5 } from "fs";
11338
11394
  import { open as open3, readdir as readdir5, unlink, link, lstat as lstat6 } from "fs/promises";
@@ -11342,27 +11398,27 @@ import { execFile as execFile3, spawn } from "child_process";
11342
11398
  import { promisify as promisify3 } from "util";
11343
11399
  import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
11344
11400
  var execute3 = promisify3(execFile3);
11345
- var reference = z7.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
11346
- var item = z7.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
11347
- var vaultKeySchema = z7.string().max(500).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*)*$/, "Use a vault key path, not an option or secret value");
11348
- var keychain = z7.object({ kind: z7.literal("keychain"), service: item, account: item }).strict();
11349
- var credentialTier = z7.enum(["argument", "override", "pointer", "profile", "keychain", "disk", "env"]);
11350
- var operator = z7.discriminatedUnion("kind", [
11351
- z7.object({ kind: z7.literal("contracts"), expectedSource: item.optional(), expectedTier: credentialTier.optional() }).strict(),
11352
- z7.object({ kind: z7.literal("env") }).strict(),
11353
- z7.object({ kind: z7.literal("keychain"), account: item.refine((value) => value.trim().length > 0 && value === value.trim(), "Vault account must be nonblank without surrounding whitespace") }).strict()
11401
+ var reference = z8.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
11402
+ var item = z8.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
11403
+ var vaultKeySchema = z8.string().max(500).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*)*$/, "Use a vault key path, not an option or secret value");
11404
+ var keychain = z8.object({ kind: z8.literal("keychain"), service: item, account: item }).strict();
11405
+ var credentialTier = z8.enum(["argument", "override", "pointer", "profile", "keychain", "disk", "env"]);
11406
+ var operator = z8.discriminatedUnion("kind", [
11407
+ z8.object({ kind: z8.literal("contracts"), expectedSource: item.optional(), expectedTier: credentialTier.optional() }).strict(),
11408
+ z8.object({ kind: z8.literal("env") }).strict(),
11409
+ z8.object({ kind: z8.literal("keychain"), account: item.refine((value) => value.trim().length > 0 && value === value.trim(), "Vault account must be nonblank without surrounding whitespace") }).strict()
11354
11410
  ]);
11355
- var origin = z7.string().transform((value) => new URL(endpoint(value)).origin);
11356
- var credentialBindingSchema = z7.object({
11357
- schema: z7.literal(1),
11411
+ var origin = z8.string().transform((value) => new URL(endpoint(value)).origin);
11412
+ var credentialBindingSchema = z8.object({
11413
+ schema: z8.literal(1),
11358
11414
  credentialEnv: reference,
11359
- origins: z7.array(origin).min(1).max(30),
11360
- requireProviderAuthentication: z7.literal(true).optional(),
11361
- source: z7.discriminatedUnion("kind", [keychain, z7.object({
11362
- kind: z7.literal("vault"),
11415
+ origins: z8.array(origin).min(1).max(30),
11416
+ requireProviderAuthentication: z8.literal(true).optional(),
11417
+ source: z8.discriminatedUnion("kind", [keychain, z8.object({
11418
+ kind: z8.literal("vault"),
11363
11419
  key: vaultKeySchema,
11364
- url: z7.string().max(2000).transform(endpoint).optional(),
11365
- executable: z7.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute15, "Secrets executable must be an absolute path"),
11420
+ url: z8.string().max(2000).transform(endpoint).optional(),
11421
+ executable: z8.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute15, "Secrets executable must be an absolute path"),
11366
11422
  operator
11367
11423
  }).strict()])
11368
11424
  }).strict().superRefine((binding, ctx) => {
@@ -11783,13 +11839,13 @@ async function deliverVaultCredential() {
11783
11839
  // src/provider-credential-onboarding.ts
11784
11840
  var absent = (error) => error instanceof SwitcherError && error.status === 404;
11785
11841
  var MAX_CREDENTIAL_MATCHES = 256;
11786
- var secretMetadataSchema = z8.object({
11842
+ var secretMetadataSchema = z9.object({
11787
11843
  key: vaultKeySchema,
11788
- type: z8.enum(["api_key", "password", "token", "credential", "other"]),
11789
- label: z8.string().max(1000).nullable().optional(),
11790
- expires_at: z8.string().max(200).nullable().optional(),
11791
- created_at: z8.string().max(200),
11792
- updated_at: z8.string().max(200)
11844
+ type: z9.enum(["api_key", "password", "token", "credential", "other"]),
11845
+ label: z9.string().max(1000).nullable().optional(),
11846
+ expires_at: z9.string().max(200).nullable().optional(),
11847
+ created_at: z9.string().max(200),
11848
+ updated_at: z9.string().max(200)
11793
11849
  }).strict();
11794
11850
  var cleanDisplay = (value) => value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, "").slice(0, 500);
11795
11851
  var credentialOrigins = (provider) => {
@@ -11898,6 +11954,8 @@ function authenticationProbe(provider) {
11898
11954
  return;
11899
11955
  }
11900
11956
  async function verifyProviderAuthentication({ provider, credential, fetch: fetchImpl = fetch }) {
11957
+ if (!provider.credentialCheck && supportsOpenCodeAuthentication(provider))
11958
+ return verifyOpenCodeAuthentication(credential, fetchImpl);
11901
11959
  const probe = authenticationProbe(provider);
11902
11960
  if (!probe)
11903
11961
  return { authenticated: false, unsupported: true };
@@ -12625,9 +12683,11 @@ import { lstat as lstat8, mkdir as mkdir11, open as open4, opendir, readlink, re
12625
12683
  import { constants as constants7 } from "fs";
12626
12684
  import { homedir as homedir9 } from "os";
12627
12685
  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) {
12686
+ function nativeStateRequested(tool, environment = process.env, explicit) {
12687
+ if (explicit !== undefined)
12688
+ return explicit;
12629
12689
  const suffix = tool.toUpperCase();
12630
- return explicit || environment[`HASNA_${suffix}_STATE_HOME`] !== undefined || environment[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
12690
+ return tool === "claude" || environment[`HASNA_${suffix}_STATE_HOME`] !== undefined || environment[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
12631
12691
  }
12632
12692
  function validateNativeStateVersion(tool, version2) {
12633
12693
  if (tool !== "codex")
@@ -12651,11 +12711,11 @@ var CODEX_INSTRUCTION_KEYS = [
12651
12711
  ];
12652
12712
  var NATIVE_STATE_ENTRIES = {
12653
12713
  codex: [
12654
- ...["sessions", "archived_sessions", "thread-writer-locks", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12714
+ ...["sessions", "archived_sessions", "thread-writer-locks", "skills", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12655
12715
  ...["history.jsonl", "AGENTS.md", "AGENTS.override.md"].map((name) => ({ name, kind: "file" }))
12656
12716
  ],
12657
12717
  claude: [
12658
- ...["projects", "todos", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12718
+ ...["projects", "todos", "skills", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
12659
12719
  ...["history.jsonl", "CLAUDE.md"].map((name) => ({ name, kind: "file" }))
12660
12720
  ]
12661
12721
  };
@@ -12704,6 +12764,30 @@ async function ensureNativeStateDirectory(path, create = true) {
12704
12764
  });
12705
12765
  await assertNativeStateDirectory(path);
12706
12766
  }
12767
+ async function assertNativeStateIsolation(tool, home, environment = process.env) {
12768
+ home = absolute(home);
12769
+ const canonical = await resolveNativeState(tool, environment, { create: false });
12770
+ const roots = [canonical.home, canonical.sqliteHome, join17(absolute(environment.HOME ?? homedir9()), `.${tool}`)];
12771
+ const contains = (parent, child) => {
12772
+ const path = relative5(parent, child);
12773
+ return path !== ".." && !path.startsWith("../") && !isAbsolute16(path);
12774
+ };
12775
+ if (roots.some((root) => root && (contains(root, home) || contains(home, root))))
12776
+ throw new Fault(409, "native_state_isolation_conflict", "The isolated home overlaps a canonical native corpus or database. Select a distinct private home; Switcher will not alter existing state.");
12777
+ if (!await info(home))
12778
+ return;
12779
+ await assertNativeStateDirectory(home);
12780
+ for (const { name } of NATIVE_STATE_ENTRIES[tool]) {
12781
+ await ensureNativeStateDirectory(dirname8(join17(home, name)), false);
12782
+ if ((await info(join17(home, name)))?.isSymbolicLink())
12783
+ throw new Fault(409, "native_state_isolation_conflict", "This profile already links native state. Select a separate isolated profile; Switcher will not remove its existing shared links.");
12784
+ }
12785
+ if (tool === "codex") {
12786
+ const config = await readCodexStateConfig(home);
12787
+ if (config.sqlite_home !== undefined && (typeof config.sqlite_home !== "string" || absolute(config.sqlite_home) !== home))
12788
+ throw new Fault(409, "native_state_isolation_conflict", "This profile redirects its native database. Select a separate isolated profile; Switcher will not rewrite its existing configuration.");
12789
+ }
12790
+ }
12707
12791
  async function withNativeStateLock(state, operation) {
12708
12792
  await ensureNativeStateDirectory(state.home);
12709
12793
  const path = join17(state.home, ".switcher-shared-state.lock");
@@ -13162,15 +13246,119 @@ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join("
13162
13246
  // src/claude-desktop-launch.ts
13163
13247
  import { createHash as createHash13 } from "crypto";
13164
13248
  import { execFile as execFile5 } from "child_process";
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";
13249
+ import { access as access4, rm as rm5, writeFile as writeFile17 } from "fs/promises";
13250
+ import { homedir as homedir11, userInfo as userInfo2 } from "os";
13251
+ import { join as join20 } from "path";
13168
13252
  import { promisify as promisify5 } from "util";
13253
+
13254
+ // src/claude-user-settings.ts
13255
+ import { constants as constants8 } from "fs";
13256
+ import { lstat as lstat9, open as open5, writeFile as writeFile16 } from "fs/promises";
13257
+ import { homedir as homedir10 } from "os";
13258
+ import { join as join19, resolve as resolve10 } from "path";
13259
+ var preferences = new Set([
13260
+ "$schema",
13261
+ "permissions",
13262
+ "sandbox",
13263
+ "language",
13264
+ "outputStyle",
13265
+ "alwaysThinkingEnabled",
13266
+ "effortLevel",
13267
+ "cleanupPeriodDays",
13268
+ "autoUpdatesChannel",
13269
+ "includeCoAuthoredBy",
13270
+ "attribution",
13271
+ "respectGitignore",
13272
+ "spinnerTipsEnabled",
13273
+ "spinnerVerbs",
13274
+ "spinnerTipsOverride",
13275
+ "terminalProgressBarEnabled",
13276
+ "prefersReducedMotion",
13277
+ "showTurnDuration",
13278
+ "showClearContextOnPlanAccept",
13279
+ "showCompactionHistory",
13280
+ "teammateMode"
13281
+ ]);
13282
+ var routing3 = new Set(["model", "modelPicker", "fallbackModel"]);
13283
+ var invalid3 = () => new Fault(422, "claude_user_settings", "Claude user settings cannot be safely projected. Use a regular owned JSON settings file with supported preferences and permission policy.");
13284
+ async function readSettings(home) {
13285
+ await ensureNativeStateDirectory(home, false);
13286
+ const path = join19(home, "settings.json");
13287
+ const entry = await lstat9(path).catch((error) => {
13288
+ if (error.code === "ENOENT")
13289
+ return;
13290
+ throw error;
13291
+ });
13292
+ if (!entry)
13293
+ return;
13294
+ if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1 || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
13295
+ throw invalid3();
13296
+ const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
13297
+ try {
13298
+ const opened = await handle.stat();
13299
+ if (opened.dev !== entry.dev || opened.ino !== entry.ino || opened.nlink !== 1 || opened.size > 1024 * 1024)
13300
+ throw invalid3();
13301
+ const value = JSON.parse(await handle.readFile("utf8"));
13302
+ if (!value || typeof value !== "object" || Array.isArray(value))
13303
+ throw invalid3();
13304
+ return value;
13305
+ } catch (error) {
13306
+ if (error instanceof Fault)
13307
+ throw error;
13308
+ throw invalid3();
13309
+ } finally {
13310
+ await handle.close();
13311
+ }
13312
+ }
13313
+ function project(settings2, existing) {
13314
+ const result = {};
13315
+ for (const [key, value] of Object.entries(settings2)) {
13316
+ if (routing3.has(key)) {
13317
+ if (existing && key === "fallbackModel")
13318
+ throw new Fault(409, "claude_settings_routing", "The private Claude settings select a fallback model. Resolve that conflict with the Switcher profile before launching.");
13319
+ continue;
13320
+ }
13321
+ if (key === "env" && value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0)
13322
+ continue;
13323
+ if (!preferences.has(key))
13324
+ throw new Fault(422, "claude_settings_unsupported", "Claude user settings contain an unsupported environment, helper or capability setting. Keep credentials and provider routing in the selected profile; resolve this settings projection explicitly before launching.");
13325
+ result[key] = value;
13326
+ }
13327
+ return result;
13328
+ }
13329
+ async function prepareClaudeUserSettings(overlayHome, environment = process.env) {
13330
+ overlayHome = resolve10(overlayHome);
13331
+ const existing = await readSettings(overlayHome);
13332
+ if (existing !== undefined) {
13333
+ project(existing, true);
13334
+ return;
13335
+ }
13336
+ const sourceHome = resolve10(environment.CLAUDE_CONFIG_DIR ?? join19(environment.HOME ?? homedir10(), ".claude"));
13337
+ if (sourceHome === overlayHome)
13338
+ return;
13339
+ const source = await readSettings(sourceHome);
13340
+ if (source === undefined)
13341
+ return;
13342
+ const settings2 = project(source, false);
13343
+ await ensureNativeStateDirectory(overlayHome);
13344
+ try {
13345
+ await writeFile16(join19(overlayHome, "settings.json"), JSON.stringify(settings2, null, 2) + `
13346
+ `, { mode: 384, flag: "wx" });
13347
+ } catch (error) {
13348
+ if (error.code !== "EEXIST")
13349
+ throw error;
13350
+ const concurrent = await readSettings(overlayHome);
13351
+ if (concurrent === undefined || JSON.stringify(project(concurrent, true)) !== JSON.stringify(settings2))
13352
+ throw new Fault(409, "claude_user_settings_changed", "The private Claude settings changed during preparation. Existing settings were preserved; retry after resolving the concurrent launch.");
13353
+ }
13354
+ }
13355
+
13356
+ // src/claude-desktop-launch.ts
13169
13357
  var execute4 = promisify5(execFile5);
13170
13358
  var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
13171
- var claudeDesktopDataDirectory = () => join19(homedir10(), "Library/Application Support/Claude-3p");
13359
+ var claudeDesktopDataDirectory = () => join20(homedir11(), "Library/Application Support/Claude-3p");
13172
13360
  async function assertAvailable(userData) {
13173
- for (const path of [join19("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
13361
+ for (const path of [join20("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
13174
13362
  if (await access4(path).then(() => true, () => false))
13175
13363
  throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
13176
13364
  let openFiles;
@@ -13206,15 +13394,15 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13206
13394
  const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
13207
13395
  await check2();
13208
13396
  await privateDirectory(userData);
13209
- const library = join19(userData, "configLibrary");
13397
+ const library = join20(userData, "configLibrary");
13210
13398
  await privateDirectory(library);
13211
- const release = await desktopLease(join19(library, ".switcher-lease.sqlite"));
13212
- const metaPath = join19(library, "_meta.json"), receiptPath = join19(library, ".switcher-selection.json");
13399
+ const release = await desktopLease(join20(library, ".switcher-lease.sqlite"));
13400
+ const metaPath = join20(library, "_meta.json"), receiptPath = join20(library, ".switcher-selection.json");
13213
13401
  let receipt, gateway, closed = false;
13214
13402
  const restore = async (record3) => {
13215
13403
  if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
13216
13404
  throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
13217
- const configPath = join19(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
13405
+ const configPath = join20(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
13218
13406
  if (current !== undefined && hash2(current) !== record3.configHash)
13219
13407
  throw new Fault(409, "desktop_config_changed", "The Switcher Claude configuration was edited outside this launch. Switcher will preserve it; review the configuration library before relaunching.");
13220
13408
  const currentMeta = await safeDesktopRead(metaPath);
@@ -13243,9 +13431,11 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13243
13431
  const recovery = await safeDesktopRead(receiptPath);
13244
13432
  if (recovery)
13245
13433
  await restore(JSON.parse(recovery));
13246
- const localConfig = await safeDesktopRead(join19(userData, "claude_desktop_config.json"));
13434
+ const localConfig = await safeDesktopRead(join20(userData, "claude_desktop_config.json"));
13247
13435
  if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
13248
13436
  throw new Fault(409, "desktop_mode", "Claude's third-party profile is set to standard account mode. Select third-party mode in Claude before launching this gateway.");
13437
+ if (input.sharedState)
13438
+ await prepareClaudeUserSettings(sessionDir);
13249
13439
  await privateDirectory(sessionDir);
13250
13440
  if (input.sharedState)
13251
13441
  await projectNativeState(input.sharedState, sessionDir);
@@ -13256,10 +13446,10 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13256
13446
  if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
13257
13447
  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.");
13258
13448
  const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
13259
- const catalogPath = join19(input.stateDir, "claude-desktop-policy.json");
13260
- await writeFile16(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
13449
+ const catalogPath = join20(input.stateDir, "claude-desktop-policy.json");
13450
+ await writeFile17(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
13261
13451
  gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
13262
- const id2 = crypto.randomUUID(), configPath = join19(library, id2 + ".json");
13452
+ const id2 = crypto.randomUUID(), configPath = join20(library, id2 + ".json");
13263
13453
  const config = JSON.stringify({
13264
13454
  inferenceProvider: "gateway",
13265
13455
  inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
@@ -13295,12 +13485,12 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13295
13485
  // src/codex-session-discovery.ts
13296
13486
  import { spawn as spawn3 } from "child_process";
13297
13487
  import { createInterface as createInterface2 } from "readline/promises";
13298
- import { basename as basename3, resolve as resolve10 } from "path";
13488
+ import { basename as basename3, resolve as resolve11 } from "path";
13299
13489
  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.");
13490
+ var unavailable2 = () => new Fault(422, "codex_session_discovery", "Native Codex session discovery failed. No conversation was started. Retry discovery or provide an exact session ID.");
13301
13491
  async function listCodexSessions(prepared, cwd, query) {
13302
13492
  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();
13493
+ throw unavailable2();
13304
13494
  const nativeStateEnv = Object.fromEntries(Object.entries(prepared.env).filter(([name]) => ["CODEX_HOME", "CODEX_SQLITE_HOME"].includes(name)));
13305
13495
  const child = spawn3(prepared.executable, [...prepared.args, "app-server"], {
13306
13496
  cwd,
@@ -13310,18 +13500,18 @@ async function listCodexSessions(prepared, cwd, query) {
13310
13500
  let done = false, initialized = false, pending = Buffer.alloc(0), responseBytes = 0;
13311
13501
  let killTimer;
13312
13502
  let resolvePage, rejectPage;
13313
- const result = new Promise((resolve11, reject2) => {
13314
- resolvePage = resolve11;
13503
+ const result = new Promise((resolve12, reject2) => {
13504
+ resolvePage = resolve12;
13315
13505
  rejectPage = reject2;
13316
13506
  });
13317
- const closed = new Promise((resolve11) => child.once("close", () => resolve11()));
13507
+ const closed = new Promise((resolve12) => child.once("close", () => resolve12()));
13318
13508
  const stop = () => {
13319
13509
  child.stdin.destroy();
13320
13510
  child.kill("SIGTERM");
13321
13511
  killTimer ??= setTimeout(() => child.kill("SIGKILL"), 2000);
13322
13512
  killTimer.unref();
13323
13513
  };
13324
- const fail = (error = unavailable()) => {
13514
+ const fail = (error = unavailable2()) => {
13325
13515
  if (!done) {
13326
13516
  done = true;
13327
13517
  rejectPage(error);
@@ -13348,7 +13538,7 @@ async function listCodexSessions(prepared, cwd, query) {
13348
13538
  try {
13349
13539
  responseBytes += chunk.length;
13350
13540
  if (responseBytes > 16 * 1024 * 1024 || pending.length + chunk.length > 8 * 1024 * 1024)
13351
- throw unavailable();
13541
+ throw unavailable2();
13352
13542
  pending = Buffer.concat([pending, chunk]);
13353
13543
  let end;
13354
13544
  while ((end = pending.indexOf(10)) >= 0) {
@@ -13358,20 +13548,20 @@ async function listCodexSessions(prepared, cwd, query) {
13358
13548
  continue;
13359
13549
  const message = JSON.parse(line.toString("utf8"));
13360
13550
  if (!object6(message))
13361
- throw unavailable();
13551
+ throw unavailable2();
13362
13552
  if (message.id === 1) {
13363
13553
  if (initialized || message.error || !object6(message.result))
13364
- throw unavailable();
13554
+ throw unavailable2();
13365
13555
  initialized = true;
13366
13556
  send({ method: "initialized" });
13367
13557
  send({ id: 2, method: "thread/list", params: { ...query, modelProviders: [], useStateDbOnly: false, sortKey: "updated_at", sortDirection: "desc" } });
13368
13558
  } else if (message.id === 2) {
13369
13559
  const page = message.result;
13370
13560
  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();
13561
+ throw unavailable2();
13372
13562
  const data2 = page.data.map((thread) => {
13373
13563
  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();
13564
+ throw unavailable2();
13375
13565
  return { id: thread.id, cwd: thread.cwd, name: thread.name, preview: thread.preview };
13376
13566
  });
13377
13567
  done = true;
@@ -13413,16 +13603,16 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
13413
13603
  break;
13414
13604
  }
13415
13605
  if (nativeArgs[i].startsWith("--cd="))
13416
- effectiveCwd = resolve10(cwd, nativeArgs[i].slice(5));
13606
+ effectiveCwd = resolve11(cwd, nativeArgs[i].slice(5));
13417
13607
  else if (nativeArgs[i].startsWith("-C") && nativeArgs[i].length > 2)
13418
- effectiveCwd = resolve10(cwd, nativeArgs[i].slice(2));
13608
+ effectiveCwd = resolve11(cwd, nativeArgs[i].slice(2));
13419
13609
  if (codexOptionRequestsHelp(nativeArgs[i]))
13420
13610
  return nativeArgs;
13421
13611
  if (codexOptionTakesValue(nativeArgs[i])) {
13422
13612
  if (nativeArgs[i] === "--cd" || nativeArgs[i] === "-C") {
13423
13613
  if (!nativeArgs[i + 1])
13424
- throw unavailable();
13425
- effectiveCwd = resolve10(cwd, nativeArgs[i + 1]);
13614
+ throw unavailable2();
13615
+ effectiveCwd = resolve11(cwd, nativeArgs[i + 1]);
13426
13616
  }
13427
13617
  i++;
13428
13618
  continue;
@@ -13497,9 +13687,9 @@ async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = lis
13497
13687
  // src/launcher.ts
13498
13688
  var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
13499
13689
  async function writeOriCodexCatalog(stateDir, models) {
13500
- const path = join20(stateDir, "ori-codex-models.json");
13690
+ const path = join21(stateDir, "ori-codex-models.json");
13501
13691
  const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
13502
- await writeFile17(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
13692
+ await writeFile18(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
13503
13693
  `, { mode: 384, flag: "wx" });
13504
13694
  return path;
13505
13695
  }
@@ -13537,7 +13727,7 @@ async function oriRequestForPlan(plan, options = {}) {
13537
13727
  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.");
13538
13728
  if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
13539
13729
  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.");
13540
- const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve11(options.cwd) : undefined });
13730
+ const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve12(options.cwd) : undefined });
13541
13731
  const native = requireOriHarness(contract, target);
13542
13732
  if (!native.path)
13543
13733
  throw new Error("Ori did not report the native harness executable path.");
@@ -13585,15 +13775,15 @@ async function prepareOriForPlan(plan, options) {
13585
13775
  executable: detection.executable,
13586
13776
  version: detection.version,
13587
13777
  stateDir: options.stateDir,
13588
- cwd: resolve11(options.cwd ?? process.cwd()),
13778
+ cwd: resolve12(options.cwd ?? process.cwd()),
13589
13779
  args: options.args ?? [],
13590
13780
  sharedState: options.sharedState
13591
13781
  });
13592
13782
  try {
13593
13783
  const shim = prepareOriModelPolicy(request.target, native);
13594
- const dir = join20(options.stateDir, "ori-bin"), path = join20(dir, shim.name);
13784
+ const dir = join21(options.stateDir, "ori-bin"), path = join21(dir, shim.name);
13595
13785
  await mkdir12(dir, { mode: 448 });
13596
- await writeFile17(path, shim.script, { mode: 448, flag: "wx" });
13786
+ await writeFile18(path, shim.script, { mode: 448, flag: "wx" });
13597
13787
  return { contract, prepared: {
13598
13788
  ...ori,
13599
13789
  env: { ...ori.env, ...shim.env, PATH: `${dir}:${ori.env.PATH ?? process.env.PATH ?? ""}` },
@@ -13608,6 +13798,8 @@ async function prepareOriForPlan(plan, options) {
13608
13798
  }
13609
13799
  }
13610
13800
  async function launch(client, profileId, options = {}) {
13801
+ if (options.backend === "ori" && options.shareNativeState === false)
13802
+ throw new Fault(400, "native_state_backend", "Explicit native-state isolation requires the direct adapter; Ori isolation is not yet verified.");
13611
13803
  const launchDeadline = options.timeoutMs === undefined ? undefined : Date.now() + options.timeoutMs;
13612
13804
  const profile = await client.getProfile(profileId);
13613
13805
  if ((options.reasoning || options.dangerouslyBypassApprovalsAndSandbox) && (profile.harness !== "codex" || (options.backend ?? "direct") !== "direct"))
@@ -13615,7 +13807,7 @@ async function launch(client, profileId, options = {}) {
13615
13807
  assertHarnessArguments(profile.harness, options.args ?? []);
13616
13808
  if (profile.harness === "gemini" || profile.harness === "antigravity")
13617
13809
  validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
13618
- await validateHarnessConfiguration(profile.harness, resolve11(options.cwd ?? process.cwd()), options.args);
13810
+ await validateHarnessConfiguration(profile.harness, resolve12(options.cwd ?? process.cwd()), options.args);
13619
13811
  if (profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((process.env.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
13620
13812
  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.");
13621
13813
  if (profile.harness === "grok" && process.env.GROK_FORCE_LOGIN_TEAM_ID?.trim())
@@ -13624,7 +13816,7 @@ async function launch(client, profileId, options = {}) {
13624
13816
  await client.refreshModels(profile.providerId);
13625
13817
  const plan = await client.launchPlan(profileId);
13626
13818
  assertHarnessArguments(plan.profile.harness, options.args ?? []);
13627
- await validateHarnessConfiguration(plan.profile.harness, resolve11(options.cwd ?? process.cwd()), options.args);
13819
+ await validateHarnessConfiguration(plan.profile.harness, resolve12(options.cwd ?? process.cwd()), options.args);
13628
13820
  if (options.credentialPreflight && providerCredentialFingerprint(plan.provider) !== options.credentialPreflight)
13629
13821
  throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
13630
13822
  const backend = options.backend ?? "direct";
@@ -13646,9 +13838,9 @@ async function launch(client, profileId, options = {}) {
13646
13838
  validateHarnessVersion("gemini", detection?.version);
13647
13839
  if (backend === "direct" && plan.profile.harness === "aider")
13648
13840
  validateHarnessVersion(plan.profile.harness, detection?.version);
13649
- const root = resolve11(options.stateDir ?? join20(switcherHome(), "state"));
13841
+ const root = resolve12(options.stateDir ?? join21(switcherHome(), "state"));
13650
13842
  await privateDirectory(root);
13651
- const stateDir = await mkdtemp(join20(root, "launch-"));
13843
+ const stateDir = await mkdtemp(join21(root, "launch-"));
13652
13844
  let credential;
13653
13845
  if (backend === "direct") {
13654
13846
  try {
@@ -13678,11 +13870,11 @@ async function launch(client, profileId, options = {}) {
13678
13870
  } else
13679
13871
  routingEventsDropped = Math.min(1e6, routingEventsDropped + 1);
13680
13872
  };
13681
- const finishRunOnce = async (candidate, body, message) => {
13873
+ const finishRunOnce = async (candidate, body2, message) => {
13682
13874
  if (runFinalized)
13683
13875
  return;
13684
13876
  runFinalized = true;
13685
- await client.finishRun(candidate.id, candidate.version, { ...body, routingEvents, routingEventsDropped }, crypto.randomUUID()).catch(() => console.error(message));
13877
+ await client.finishRun(candidate.id, candidate.version, { ...body2, routingEvents, routingEventsDropped }, crypto.randomUUID()).catch(() => console.error(message));
13686
13878
  };
13687
13879
  let cancelPreparation;
13688
13880
  const preparationCancellation = new Promise((_, reject2) => {
@@ -13692,27 +13884,42 @@ async function launch(client, profileId, options = {}) {
13692
13884
  return;
13693
13885
  });
13694
13886
  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));
13887
+ if (options.shareNativeState !== undefined && plan.profile.harness !== "codex" && plan.profile.harness !== "claude")
13888
+ throw new Fault(400, "native_state_harness", "Native-state options are supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
13889
+ const shareRequested = (plan.profile.harness === "codex" || plan.profile.harness === "claude") && nativeStateRequested(plan.profile.harness, process.env, options.shareNativeState);
13698
13890
  if (shareRequested && backend !== "direct")
13699
13891
  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") {
13892
+ if ((shareRequested || options.shareNativeState === false) && plan.profile.harness === "codex")
13701
13893
  assertHarnessArguments("codex", options.args ?? [], { reservedCodexRoots: ["sqlite_home"] });
13894
+ if (shareRequested && plan.profile.harness === "codex")
13702
13895
  validateNativeStateVersion("codex", detection?.version);
13703
- }
13704
13896
  const sharedState = shareRequested ? await resolveNativeState(plan.profile.harness) : undefined;
13705
13897
  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)] : [];
13898
+ const stateWarnings = sharedState ? ["Shared native state is enabled. Resumed conversation history uses this launch's selected provider and model; Switcher does not infer unverified original-provider provenance.", ...await legacyNativeStateWarnings(root, sharedState)] : [];
13707
13899
  let nativeHome2;
13708
13900
  if (sharedState && !options.desktop && !options.claudeDesktop) {
13709
13901
  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;
13902
+ const configured = process.env[variable] ? resolve12(process.env[variable]) : undefined;
13903
+ nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join21(root, "native-claude", profileId) : configured ?? sharedState.home;
13904
+ if (sharedState.tool === "claude")
13905
+ await prepareClaudeUserSettings(nativeHome2);
13712
13906
  await privateDirectory(nativeHome2);
13713
13907
  await assertNativeInstructionOverlay(sharedState, nativeHome2);
13714
13908
  await projectNativeState(sharedState, nativeHome2);
13715
13909
  }
13910
+ if (options.shareNativeState === false && backend === "direct") {
13911
+ const tool = plan.profile.harness;
13912
+ if (options.desktop)
13913
+ await assertNativeStateIsolation(tool, join21(root, "desktop", desktopState, "codex"));
13914
+ else if (options.claudeDesktop)
13915
+ await assertNativeStateIsolation(tool, join21(root, "desktop-claude", desktopState));
13916
+ else {
13917
+ const variable = tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
13918
+ nativeHome2 = process.env[variable] ? resolve12(process.env[variable]) : join21(root, `native-${tool}`, profileId);
13919
+ await assertNativeStateIsolation(tool, nativeHome2);
13920
+ await privateDirectory(nativeHome2);
13921
+ }
13922
+ }
13716
13923
  const input = {
13717
13924
  harness: plan.profile.harness,
13718
13925
  baseUrl: plan.provider.baseUrl,
@@ -13725,10 +13932,10 @@ async function launch(client, profileId, options = {}) {
13725
13932
  onRoutingEvent,
13726
13933
  credential,
13727
13934
  stateDir,
13728
- cwd: resolve11(options.cwd ?? process.cwd()),
13935
+ cwd: resolve12(options.cwd ?? process.cwd()),
13729
13936
  sharedState
13730
13937
  };
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({
13938
+ let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join21(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
13732
13939
  harness: plan.profile.harness,
13733
13940
  baseUrl: plan.provider.baseUrl,
13734
13941
  protocol: plan.provider.protocol,
@@ -13744,18 +13951,19 @@ async function launch(client, profileId, options = {}) {
13744
13951
  executable: nativeExecutable ?? detection?.executable,
13745
13952
  args: options.args ?? [],
13746
13953
  stateDir,
13747
- cwd: resolve11(options.cwd ?? process.cwd()),
13954
+ cwd: resolve12(options.cwd ?? process.cwd()),
13748
13955
  version: detection?.version,
13749
13956
  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) } : {}
13957
+ ...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie"].includes(plan.profile.harness) ? { sessionDir: join21(root, "sessions", plan.profile.harness, profileId) } : {}
13751
13958
  });
13752
13959
  cleanup = prepared.cleanup;
13753
13960
  prepared = { ...prepared, warnings: [...prepared.warnings, ...stateWarnings] };
13754
- if (sharedState)
13961
+ if (sharedState || nativeHome2)
13755
13962
  prepared = { ...prepared, env: {
13756
13963
  ...prepared.env,
13757
- ...nativeStateEnvironment(sharedState),
13758
- ...nativeHome2 ? { [sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"]: nativeHome2 } : {}
13964
+ ...sharedState ? nativeStateEnvironment(sharedState) : {},
13965
+ ...nativeHome2 ? { [plan.profile.harness === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"]: nativeHome2 } : {},
13966
+ ...nativeHome2 && options.shareNativeState === false && plan.profile.harness === "codex" ? { CODEX_SQLITE_HOME: nativeHome2 } : {}
13759
13967
  } };
13760
13968
  if (sharedState?.tool === "codex" && !options.desktop && backend === "direct" && options.args?.length) {
13761
13969
  const baseArgs = prepared.args.slice(0, prepared.args.length - options.args.length);
@@ -13763,7 +13971,7 @@ async function launch(client, profileId, options = {}) {
13763
13971
  prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
13764
13972
  }
13765
13973
  if (options.desktop) {
13766
- prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join20(root, "desktop", desktopState), sharedState);
13974
+ prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join21(root, "desktop", desktopState), sharedState);
13767
13975
  cleanup = prepared.cleanup;
13768
13976
  }
13769
13977
  for (const warning of [...plan.warnings, ...prepared.warnings])
@@ -13840,7 +14048,7 @@ async function launch(client, profileId, options = {}) {
13840
14048
  interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
13841
14049
  throw preparationSignal;
13842
14050
  }
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 });
14051
+ const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve12(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
13844
14052
  await cleanup?.();
13845
14053
  cleanup = undefined;
13846
14054
  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}.`);
@@ -13857,8 +14065,8 @@ async function launch(client, profileId, options = {}) {
13857
14065
  } finally {
13858
14066
  if (lateCreateRunFinalization) {
13859
14067
  let finalizationTimer;
13860
- const finalizationTimeout = new Promise((resolve12) => {
13861
- finalizationTimer = setTimeout(resolve12, LATE_RUN_FINALIZATION_TIMEOUT_MS);
14068
+ const finalizationTimeout = new Promise((resolve13) => {
14069
+ finalizationTimer = setTimeout(resolve13, LATE_RUN_FINALIZATION_TIMEOUT_MS);
13862
14070
  });
13863
14071
  try {
13864
14072
  await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
@@ -13983,15 +14191,15 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
13983
14191
 
13984
14192
  // src/native-state-import.ts
13985
14193
  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";
14194
+ import { constants as constants9 } from "fs";
14195
+ import { lstat as lstat10, open as open6, opendir as opendir2, link as link2, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
14196
+ import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join22, relative as relative6, resolve as resolve13 } from "path";
13989
14197
  var MAX_FILES = 1e5;
13990
14198
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
13991
14199
  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
14200
  async function info2(path) {
13993
14201
  try {
13994
- return await lstat9(path);
14202
+ return await lstat10(path);
13995
14203
  } catch (error) {
13996
14204
  if (error.code === "ENOENT")
13997
14205
  return;
@@ -14007,7 +14215,7 @@ var inside3 = (parent, child) => {
14007
14215
  var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
14008
14216
  async function sessionId(path, expected) {
14009
14217
  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);
14218
+ const handle = await open6(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
14011
14219
  try {
14012
14220
  const before = await handle.stat();
14013
14221
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
@@ -14021,7 +14229,7 @@ async function sessionId(path, expected) {
14021
14229
  length += read.bytesRead;
14022
14230
  newline = buffer.indexOf(10, 0);
14023
14231
  }
14024
- const after = await handle.stat(), named = await lstat9(path);
14232
+ const after = await handle.stat(), named = await lstat10(path);
14025
14233
  if (!same(before, after) || !same(after, named) || after.nlink !== 1 || named.nlink !== 1 || named.isSymbolicLink())
14026
14234
  throw refused();
14027
14235
  if (newline < 0 && before.size > buffer.length)
@@ -14050,7 +14258,7 @@ async function checkSessionIdentities(plan) {
14050
14258
  for (const file of plan.files) {
14051
14259
  if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
14052
14260
  continue;
14053
- file.sessionId = await sessionId(join21(plan.source, file.path), file.source);
14261
+ file.sessionId = await sessionId(join22(plan.source, file.path), file.source);
14054
14262
  if (!file.sessionId)
14055
14263
  continue;
14056
14264
  const previous = ids.get(file.sessionId);
@@ -14074,7 +14282,7 @@ async function checkSessionIdentities(plan) {
14074
14282
  for await (const entry of await opendir2(directory)) {
14075
14283
  if (++seen > MAX_FILES || entry.isSymbolicLink())
14076
14284
  throw refused();
14077
- const path = join21(directory, entry.name);
14285
+ const path = join22(directory, entry.name);
14078
14286
  if (entry.isDirectory()) {
14079
14287
  await scan(path, depth + 1);
14080
14288
  continue;
@@ -14091,18 +14299,18 @@ async function checkSessionIdentities(plan) {
14091
14299
  file.existing = true;
14092
14300
  }
14093
14301
  }
14094
- await scan(join21(plan.state.home, "sessions"));
14095
- await scan(join21(plan.state.home, "archived_sessions"));
14302
+ await scan(join22(plan.state.home, "sessions"));
14303
+ await scan(join22(plan.state.home, "archived_sessions"));
14096
14304
  }
14097
14305
  async function fingerprint2(path, copyTo) {
14098
- const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
14306
+ const handle = await open6(path, constants9.O_RDONLY | constants9.O_NOFOLLOW);
14099
14307
  let output, complete = false;
14100
14308
  try {
14101
14309
  const before = await handle.stat();
14102
14310
  if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
14103
14311
  throw refused();
14104
14312
  if (copyTo)
14105
- output = await open5(copyTo, "wx", 384);
14313
+ output = await open6(copyTo, "wx", 384);
14106
14314
  const hash3 = createHash15("sha256"), buffer = Buffer.alloc(64 * 1024);
14107
14315
  let bytes = 0;
14108
14316
  for (;; ) {
@@ -14120,7 +14328,7 @@ async function fingerprint2(path, copyTo) {
14120
14328
  offset += (await output.write(chunk, offset, chunk.length - offset)).bytesWritten;
14121
14329
  }
14122
14330
  }
14123
- const after = await handle.stat(), named = await lstat9(path);
14331
+ const after = await handle.stat(), named = await lstat10(path);
14124
14332
  if (named.isSymbolicLink() || after.nlink !== 1 || named.nlink !== 1 || bytes !== before.size || !same(before, after) || !same(after, named))
14125
14333
  throw refused();
14126
14334
  await output?.sync();
@@ -14138,12 +14346,12 @@ async function fingerprint2(path, copyTo) {
14138
14346
  async function planNativeStateImport(state, source, selection) {
14139
14347
  if (!isAbsolute17(source) || source.includes("\x00"))
14140
14348
  throw refused();
14141
- source = resolve12(source);
14349
+ source = resolve13(source);
14142
14350
  if (inside3(source, state.home) || inside3(state.home, source))
14143
14351
  throw refused();
14144
14352
  await assertNativeStateDirectory(source);
14145
14353
  await ensureNativeStateDirectory(state.home, false);
14146
- const allowed = NATIVE_STATE_ENTRIES[state.tool].filter((entry) => entry.name !== "thread-writer-locks");
14354
+ const allowed = NATIVE_STATE_ENTRIES[state.tool].filter((entry) => !["thread-writer-locks", "skills"].includes(entry.name));
14147
14355
  const entries = selection?.length ? [...new Set(selection)] : allowed.map((entry) => entry.name);
14148
14356
  if (entries.some((name) => !allowed.some((entry) => entry.name === name)))
14149
14357
  throw refused();
@@ -14152,9 +14360,9 @@ async function planNativeStateImport(state, source, selection) {
14152
14360
  async function visit(path, kind) {
14153
14361
  if (++seen > MAX_FILES || path.split("/").length > 32)
14154
14362
  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);
14363
+ await ensureNativeStateDirectory(dirname9(join22(source, path)), false);
14364
+ await ensureNativeStateDirectory(dirname9(join22(state.home, path)), false);
14365
+ const from = join22(source, path), to = join22(state.home, path), entry = await info2(from), target = await info2(to);
14158
14366
  if (!entry)
14159
14367
  return;
14160
14368
  if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
@@ -14173,7 +14381,7 @@ async function planNativeStateImport(state, source, selection) {
14173
14381
  }
14174
14382
  children.sort((a, b) => a.name.localeCompare(b.name));
14175
14383
  for (const child of children)
14176
- await visit(join21(path, child.name), child.kind);
14384
+ await visit(join22(path, child.name), child.kind);
14177
14385
  } else {
14178
14386
  const value = await fingerprint2(from);
14179
14387
  plan.bytes += value.bytes;
@@ -14227,14 +14435,14 @@ async function applyNativeStateImportUnlocked(plan) {
14227
14435
  throw refused();
14228
14436
  const requiredDirectories = new Set([plan.state.home]);
14229
14437
  for (const path of plan.directories) {
14230
- for (let directory = join21(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname9(directory)) {
14438
+ for (let directory = join22(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname9(directory)) {
14231
14439
  requiredDirectories.add(directory);
14232
14440
  if (directory === plan.state.home)
14233
14441
  break;
14234
14442
  }
14235
14443
  }
14236
14444
  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)) {
14445
+ for (let directory = dirname9(join22(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname9(directory)) {
14238
14446
  requiredDirectories.add(directory);
14239
14447
  if (directory === plan.state.home)
14240
14448
  break;
@@ -14255,9 +14463,9 @@ async function applyNativeStateImportUnlocked(plan) {
14255
14463
  for (const file of plan.files) {
14256
14464
  if (file.existing)
14257
14465
  continue;
14258
- const target = join21(plan.state.home, file.path), temporary = join21(dirname9(target), `.switcher-import-${crypto.randomUUID()}`);
14466
+ const target = join22(plan.state.home, file.path), temporary = join22(dirname9(target), `.switcher-import-${crypto.randomUUID()}`);
14259
14467
  staged.push({ temporary, target });
14260
- const copied = await fingerprint2(join21(plan.source, file.path), temporary);
14468
+ const copied = await fingerprint2(join22(plan.source, file.path), temporary);
14261
14469
  if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
14262
14470
  throw refused();
14263
14471
  }
@@ -14313,11 +14521,11 @@ async function applyNativeStateImport(plan) {
14313
14521
  var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your provider and model
14314
14522
 
14315
14523
  switcher launch chatgpt --provider PROVIDER --model MODEL [--reasoning EFFORT]
14316
- [--dangerously-bypass-approvals-and-sandbox] [--share-native-state]
14524
+ [--dangerously-bypass-approvals-and-sandbox] [--share-native-state | --no-share-native-state]
14317
14525
  [--app-path /absolute/ChatGPT.app]
14318
14526
  [--dry-run] [--cwd DIR] [--timeout SECONDS]
14319
14527
  switcher launch claude-desktop --provider PROVIDER --model MODEL
14320
- [--share-native-state] [--app-path /absolute/Claude.app] [--dry-run]
14528
+ [--share-native-state | --no-share-native-state] [--app-path /absolute/Claude.app] [--dry-run]
14321
14529
  switcher providers presets [ID]
14322
14530
  switcher providers list [--search TEXT] [--limit N] [--offset N]
14323
14531
  switcher providers add ID --url URL --protocol PROTOCOL [--credential-env NAME]
@@ -14335,8 +14543,8 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
14335
14543
  switcher profiles add ID --provider ID --harness HARNESS --model MODEL [--model-policy-file FILE] [--role-model ROLE=MODEL]
14336
14544
  switcher profiles update ID --file profile.json --version N
14337
14545
  switcher profiles delete ID --version N
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]
14546
+ switcher launch HARNESS --provider PROVIDER [--model MODEL] [--share-native-state | --no-share-native-state] [--dry-run]
14547
+ switcher launch PROFILE [--backend direct|ori] [--share-native-state | --no-share-native-state] [--cwd DIR] [--executable PATH]
14340
14548
  [--ori-executable PATH] [--state-dir DIR]
14341
14549
  [--timeout SECONDS] -- [native harness arguments]
14342
14550
  switcher runs list|get [ID]
@@ -14351,7 +14559,9 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
14351
14559
 
14352
14560
  HARNESS: claude, codex, grok, opencode, opencode2, pi, omp, dsh, cline, hermes, prime-agent, gemini, antigravity, junie, aider, kilo
14353
14561
  chatgpt launches the installed macOS desktop app with private login data.
14354
- Use --share-native-state to project the canonical noncredential Codex/Claude corpus.
14562
+ Claude shares canonical sessions, skills and instructions by default.
14563
+ Use --no-share-native-state for isolation. Codex currently requires
14564
+ --share-native-state or a canonical state marker.
14355
14565
  Its local Codex conversations use the selected Responses-compatible provider.
14356
14566
  claude-desktop launches Claude in its separate Claude-3p gateway profile with a
14357
14567
  Messages-compatible provider. Quit that instance before switching providers.
@@ -14438,6 +14648,7 @@ async function main(args = process.argv.slice(2)) {
14438
14648
  reasoning: { type: "string" },
14439
14649
  "dangerously-bypass-approvals-and-sandbox": { type: "boolean" },
14440
14650
  "share-native-state": { type: "boolean" },
14651
+ "no-share-native-state": { type: "boolean" },
14441
14652
  from: { type: "string" },
14442
14653
  entry: { type: "string", multiple: true },
14443
14654
  apply: { type: "boolean" },
@@ -14501,16 +14712,19 @@ async function main(args = process.argv.slice(2)) {
14501
14712
  }
14502
14713
  if (values2.from !== undefined || values2.entry !== undefined || values2.apply !== undefined || values2["plan-digest"] !== undefined)
14503
14714
  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.");
14715
+ if (values2["share-native-state"] && values2["no-share-native-state"])
14716
+ throw new Fault(400, "conflicting_options", "Use only one of --share-native-state and --no-share-native-state.");
14717
+ const shareNativeState = values2["no-share-native-state"] ? false : values2["share-native-state"];
14718
+ if (shareNativeState !== undefined && command !== "launch")
14719
+ throw new Fault(400, "conflicting_options", "--share-native-state and --no-share-native-state belong to a Codex, ChatGPT, Claude CLI or Claude desktop launch.");
14506
14720
  const reasoning = values2.reasoning === undefined ? undefined : parse2(reasoningEffortSchema, values2.reasoning);
14507
14721
  const dangerouslyBypassApprovalsAndSandbox = values2["dangerously-bypass-approvals-and-sandbox"];
14508
14722
  if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" || values2.provider && !["chatgpt", "codex"].includes(action2) || values2.backend && values2.backend !== "direct"))
14509
14723
  throw new Fault(400, "conflicting_options", "--reasoning and --dangerously-bypass-approvals-and-sandbox require a direct Codex or ChatGPT launch.");
14510
14724
  const chatgpt = command === "launch" && action2 === "chatgpt" && values2.provider !== undefined;
14511
14725
  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.");
14726
+ if (shareNativeState !== undefined && values2.provider !== undefined && !["codex", "claude", "chatgpt", "claude-desktop"].includes(action2))
14727
+ throw new Fault(400, "native_state_harness", "Native-state options are supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
14514
14728
  if (values2["app-path"] !== undefined && !chatgpt && !claudeDesktop)
14515
14729
  throw new Fault(400, "conflicting_options", "--app-path belongs to launch chatgpt or claude-desktop --provider PROVIDER --model MODEL.");
14516
14730
  if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 || values2.executable !== undefined || values2.backend !== undefined || values2["ori-executable"] !== undefined))
@@ -14613,6 +14827,8 @@ async function main(args = process.argv.slice(2)) {
14613
14827
  const backend = values2.backend ?? "direct";
14614
14828
  if (backend !== "direct" && backend !== "ori")
14615
14829
  throw new Fault(400, "invalid_backend", "Use --backend direct or --backend ori.");
14830
+ if (command === "launch" && backend === "ori" && values2["no-share-native-state"])
14831
+ throw new Fault(400, "native_state_backend", "Explicit native-state isolation requires the direct adapter; Ori isolation is not yet verified.");
14616
14832
  if (command !== "launch" && (values2.backend !== undefined || values2["ori-executable"] !== undefined))
14617
14833
  throw new Fault(400, "conflicting_options", "--backend and --ori-executable belong to launch.");
14618
14834
  if (command === "launch" && backend === "ori" && values2.executable !== undefined)
@@ -14716,8 +14932,8 @@ async function main(args = process.argv.slice(2)) {
14716
14932
  if (values2.model || values2.protocol || values2.url || values2["credential-env"] || values2["model-policy-file"] || values2["role-model"])
14717
14933
  throw new Error("Use --provider PROVIDER for a direct launch, or update the saved profile explicitly.");
14718
14934
  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.");
14935
+ if (shareNativeState !== undefined && !["codex", "claude"].includes(profile.harness))
14936
+ throw new Fault(400, "native_state_harness", "Native-state options are supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
14721
14937
  assertHarnessArguments(profile.harness, nativeArgs);
14722
14938
  await validateHarnessConfiguration(profile.harness, values2.cwd ?? process.cwd(), nativeArgs);
14723
14939
  const provider = await client.getProvider(profile.providerId);
@@ -14744,24 +14960,32 @@ async function main(args = process.argv.slice(2)) {
14744
14960
  codexReasoning(model3, plan.provider.baseUrl, reasoning);
14745
14961
  }
14746
14962
  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"] });
14963
+ if (shareNativeState !== undefined && !["codex", "claude"].includes(plan.profile.harness))
14964
+ throw new Fault(400, "native_state_harness", "Native-state options are supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
14965
+ const sharedNativeState = ["codex", "claude"].includes(plan.profile.harness) && nativeStateRequested(plan.profile.harness, process.env, shareNativeState);
14966
+ const suffix = plan.profile.harness.toUpperCase();
14967
+ const marked = process.env[`HASNA_${suffix}_STATE_HOME`] !== undefined || process.env[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
14968
+ const nativeState = sharedNativeState ? { shared: true, consent: shareNativeState === true ? "command" : marked ? "environment" : "default" } : shareNativeState === false ? { shared: false, consent: "command" } : undefined;
14969
+ if ((sharedNativeState || shareNativeState === false) && plan.profile.harness === "codex")
14970
+ assertHarnessArguments("codex", nativeArgs, { reservedCodexRoots: ["sqlite_home"] });
14971
+ if (sharedNativeState)
14753
14972
  await resolveNativeState(plan.profile.harness, process.env, { create: false });
14973
+ if (shareNativeState === false) {
14974
+ const tool = plan.profile.harness, root = resolve14(values2["state-dir"] ?? join23(switcherHome(), "state"));
14975
+ const configured = process.env[tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"];
14976
+ const home = desktop ? join23(root, "desktop", profileId, "codex") : claudeApp ? join23(root, "desktop-claude", profileId) : configured ? resolve14(configured) : join23(root, `native-${tool}`, profileId);
14977
+ await assertNativeStateIsolation(tool, home);
14754
14978
  }
14755
14979
  if (backend === "ori") {
14756
14980
  if (sharedNativeState)
14757
14981
  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.");
14758
14982
  const { contract, warnings } = await validateOriForPlan(plan, { oriExecutable: values2["ori-executable"], args: nativeArgs, cwd: values2.cwd });
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" } } : {} });
14983
+ output({ ...plan, backend: { kind: "ori", executable: contract.executable, version: contract.version, target: plan.profile.harness, provider: "openrouter", model: plan.profile.model, warnings: [...plan.warnings, ...warnings] }, ...nativeState ? { nativeState } : {} });
14760
14984
  } else
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" } } : {} });
14985
+ output({ ...plan, ...desktop ? { desktop: { ...desktop, mode: sharedNativeState ? "shared-state-private-auth" : "isolated-provider", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...claudeApp ? { desktop: { ...claudeApp, mode: "claude-3p-gateway", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...nativeState ? { nativeState } : {}, ...reasoning ? { reasoning } : {}, ...dangerouslyBypassApprovalsAndSandbox ? { permissions: { approvalPolicy: "never", sandboxMode: "danger-full-access" } } : {} });
14762
14986
  return;
14763
14987
  }
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)) });
14988
+ process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, shareNativeState, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)) });
14765
14989
  return;
14766
14990
  }
14767
14991
  if (editingModel) {