@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/index.js CHANGED
@@ -429,12 +429,12 @@ async function detectChatGPTApp(appPath, system = host) {
429
429
  const bundleId = await field("CFBundleIdentifier");
430
430
  if (bundleId !== "com.openai.codex")
431
431
  continue;
432
- const name = await field("CFBundleExecutable"), version = await field("CFBundleShortVersionString");
432
+ const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
433
433
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
434
434
  continue;
435
435
  const executable = join(path, "Contents/MacOS", name), codexExecutable = join(path, "Contents/Resources/codex");
436
436
  if (await system.executable(executable) && await system.executable(codexExecutable))
437
- return { path, executable, codexExecutable, bundleId, version };
437
+ return { path, executable, codexExecutable, bundleId, version: version2 };
438
438
  } catch {}
439
439
  }
440
440
  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.");
@@ -457,12 +457,12 @@ async function detectClaudeDesktopApp(appPath, system = host) {
457
457
  const bundleId = await field("CFBundleIdentifier");
458
458
  if (bundleId !== "com.anthropic.claudefordesktop")
459
459
  continue;
460
- const name = await field("CFBundleExecutable"), version = await field("CFBundleShortVersionString");
460
+ const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
461
461
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
462
462
  continue;
463
463
  const executable = join(path, "Contents/MacOS", name);
464
464
  if (await system.executable(executable))
465
- return { path, executable, bundleId, version };
465
+ return { path, executable, bundleId, version: version2 };
466
466
  } catch {}
467
467
  }
468
468
  throw new Fault(404, "app_not_installed", "Install the current Claude macOS desktop app or supply its absolute .app path with --app-path.");
@@ -608,17 +608,17 @@ class SwitcherClient {
608
608
  createProvider(input, idempotencyKey) {
609
609
  return this.request("POST", "/v1/providers", input, { idempotencyKey });
610
610
  }
611
- updateProvider(input, version, idempotencyKey) {
612
- return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
611
+ updateProvider(input, version2, idempotencyKey) {
612
+ return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
613
613
  }
614
- deleteProvider(id, version, idempotencyKey) {
615
- return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
614
+ deleteProvider(id, version2, idempotencyKey) {
615
+ return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
616
616
  }
617
617
  async editModel(providerId, operation, value) {
618
618
  const model = typeof value === "string" ? undefined : parse(modelSchema, value);
619
619
  const id = model?.id ?? parse(modelSchema.shape.id, value);
620
620
  const provider = await this.getProvider(providerId);
621
- const { version, updatedAt, ...input } = provider;
621
+ const { version: version2, updatedAt, ...input } = provider;
622
622
  const manual = provider.manualModels.some((item) => item.id === id);
623
623
  const additional = (provider.additionalModels ?? []).some((item) => item.id === id);
624
624
  if (operation === "add" && (manual || additional))
@@ -630,7 +630,7 @@ class SwitcherClient {
630
630
  const additionalModels = (provider.additionalModels ?? []).filter((item) => item.id !== id);
631
631
  if (operation !== "remove")
632
632
  (useManual ? manualModels : additionalModels).push(model);
633
- return this.updateProvider({ ...input, manualModels, additionalModels }, version);
633
+ return this.updateProvider({ ...input, manualModels, additionalModels }, version2);
634
634
  }
635
635
  addModel(providerId, model) {
636
636
  return this.editModel(providerId, "add", model);
@@ -659,11 +659,11 @@ class SwitcherClient {
659
659
  createProfile(input, idempotencyKey) {
660
660
  return this.request("POST", "/v1/profiles", input, { idempotencyKey });
661
661
  }
662
- updateProfile(input, version, idempotencyKey) {
663
- return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
662
+ updateProfile(input, version2, idempotencyKey) {
663
+ return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
664
664
  }
665
- deleteProfile(id, version, idempotencyKey) {
666
- return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
665
+ deleteProfile(id, version2, idempotencyKey) {
666
+ return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
667
667
  }
668
668
  launchPlan(profileId, idempotencyKey) {
669
669
  return this.request("POST", "/v1/launch-plans", { profileId }, { idempotencyKey });
@@ -677,8 +677,8 @@ class SwitcherClient {
677
677
  createRun(input, idempotencyKey) {
678
678
  return this.request("POST", "/v1/runs", { ...input, modelPolicyVersion: 1 }, { idempotencyKey });
679
679
  }
680
- finishRun(id, version, input, idempotencyKey) {
681
- return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version, idempotencyKey });
680
+ finishRun(id, version2, input, idempotencyKey) {
681
+ return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version: version2, idempotencyKey });
682
682
  }
683
683
  }
684
684
  function clientFromEnv(env = process.env, options = {}) {
@@ -4,12 +4,14 @@ import { type LaunchPlan, type ProviderInput } from "./domain";
4
4
  import { type OriContract } from "./ori-backend";
5
5
  import type { ChatGPTInstallation, ClaudeDesktopInstallation } from "./desktop-apps";
6
6
  import type { ReasoningEffort } from "./reasoning";
7
+ import { type NativeState } from "./native-state";
7
8
  import type { RoutingEvent } from "./inference-gateway";
8
9
  export { childEnvironment } from "./harness-environment";
9
10
  export type LaunchBackend = "direct" | "ori";
10
11
  export type LaunchOptions = {
11
12
  desktop?: ChatGPTInstallation;
12
13
  claudeDesktop?: ClaudeDesktopInstallation;
14
+ shareNativeState?: boolean;
13
15
  reasoning?: ReasoningEffort;
14
16
  dangerouslyBypassApprovalsAndSandbox?: boolean;
15
17
  backend?: LaunchBackend;
@@ -28,6 +30,7 @@ type OriPreparationOptions = Pick<LaunchOptions, "oriExecutable" | "args" | "res
28
30
  stateDir?: string;
29
31
  cwd?: string;
30
32
  onRoutingEvent?: (event: RoutingEvent) => void;
33
+ sharedState?: NativeState;
31
34
  };
32
35
  type OriSupportedHarness = Exclude<LaunchPlan["profile"]["harness"], "omp" | "cline" | "hermes" | "prime-agent" | "gemini" | "aider" | "opencode" | "kilo" | "antigravity" | "junie">;
33
36
  export declare function validateOriForPlan(plan: LaunchPlan, options?: Pick<OriPreparationOptions, "oriExecutable" | "args" | "credentialEnv" | "cwd">): Promise<{
package/dist/mcp/index.js CHANGED
@@ -68,9 +68,13 @@ var routingEventsSchema = z2.array(routingEventSchema).max(1000);
68
68
  function canonicalPolicyJSON(value) {
69
69
  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);
70
70
  }
71
+ // package.json
72
+ var version = "0.2.9";
73
+
74
+ // src/version.ts
75
+ var VERSION = version;
71
76
 
72
77
  // src/domain.ts
73
- var VERSION = "0.2.7";
74
78
  var harnessSchema = z3.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "antigravity", "junie", "aider", "kilo"]);
75
79
  var protocolSchema = z3.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
76
80
  var idSchema = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
@@ -556,17 +560,17 @@ class SwitcherClient {
556
560
  createProvider(input, idempotencyKey) {
557
561
  return this.request("POST", "/v1/providers", input, { idempotencyKey });
558
562
  }
559
- updateProvider(input, version, idempotencyKey) {
560
- return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
563
+ updateProvider(input, version2, idempotencyKey) {
564
+ return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
561
565
  }
562
- deleteProvider(id, version, idempotencyKey) {
563
- return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
566
+ deleteProvider(id, version2, idempotencyKey) {
567
+ return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
564
568
  }
565
569
  async editModel(providerId, operation, value) {
566
570
  const model = typeof value === "string" ? undefined : parse(modelSchema, value);
567
571
  const id = model?.id ?? parse(modelSchema.shape.id, value);
568
572
  const provider = await this.getProvider(providerId);
569
- const { version, updatedAt, ...input } = provider;
573
+ const { version: version2, updatedAt, ...input } = provider;
570
574
  const manual = provider.manualModels.some((item) => item.id === id);
571
575
  const additional = (provider.additionalModels ?? []).some((item) => item.id === id);
572
576
  if (operation === "add" && (manual || additional))
@@ -578,7 +582,7 @@ class SwitcherClient {
578
582
  const additionalModels = (provider.additionalModels ?? []).filter((item) => item.id !== id);
579
583
  if (operation !== "remove")
580
584
  (useManual ? manualModels : additionalModels).push(model);
581
- return this.updateProvider({ ...input, manualModels, additionalModels }, version);
585
+ return this.updateProvider({ ...input, manualModels, additionalModels }, version2);
582
586
  }
583
587
  addModel(providerId, model) {
584
588
  return this.editModel(providerId, "add", model);
@@ -607,11 +611,11 @@ class SwitcherClient {
607
611
  createProfile(input, idempotencyKey) {
608
612
  return this.request("POST", "/v1/profiles", input, { idempotencyKey });
609
613
  }
610
- updateProfile(input, version, idempotencyKey) {
611
- return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
614
+ updateProfile(input, version2, idempotencyKey) {
615
+ return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
612
616
  }
613
- deleteProfile(id, version, idempotencyKey) {
614
- return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
617
+ deleteProfile(id, version2, idempotencyKey) {
618
+ return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
615
619
  }
616
620
  launchPlan(profileId, idempotencyKey) {
617
621
  return this.request("POST", "/v1/launch-plans", { profileId }, { idempotencyKey });
@@ -625,8 +629,8 @@ class SwitcherClient {
625
629
  createRun(input, idempotencyKey) {
626
630
  return this.request("POST", "/v1/runs", { ...input, modelPolicyVersion: 1 }, { idempotencyKey });
627
631
  }
628
- finishRun(id, version, input, idempotencyKey) {
629
- return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version, idempotencyKey });
632
+ finishRun(id, version2, input, idempotencyKey) {
633
+ return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version: version2, idempotencyKey });
630
634
  }
631
635
  }
632
636
  function clientFromEnv(env = process.env, options = {}) {
@@ -800,8 +804,8 @@ class Store {
800
804
  }
801
805
  return value;
802
806
  }
803
- async remove(kind, id, version, db) {
804
- const rows = await db.unsafe(`DELETE FROM switcher_${kind} WHERE id = $1 AND version = $2 RETURNING id`, [id, version]);
807
+ async remove(kind, id, version2, db) {
808
+ const rows = await db.unsafe(`DELETE FROM switcher_${kind} WHERE id = $1 AND version = $2 RETURNING id`, [id, version2]);
805
809
  if (!rows.length)
806
810
  throw new Fault(409, "version_conflict", "Entry changed or is missing; reload before retrying.");
807
811
  return { deleted: id };
@@ -1193,7 +1197,7 @@ var openapi_default = {
1193
1197
  openapi: "3.0.3",
1194
1198
  info: {
1195
1199
  title: "Switcher API",
1196
- version: "0.2.7",
1200
+ version: "0.2.9",
1197
1201
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
1198
1202
  },
1199
1203
  security: [
@@ -5505,7 +5509,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
5505
5509
  }
5506
5510
  }
5507
5511
  const fingerprint = hash(JSON.stringify([request.method, route2, body, request.headers.get("if-match")])).toString("hex");
5508
- const version = () => {
5512
+ const version2 = () => {
5509
5513
  const v = request.headers.get("if-match");
5510
5514
  if (!v || !/^[1-9]\d*$/.test(v))
5511
5515
  throw new Fault(428, "version_required", "Supply the current numeric version in If-Match.");
@@ -5525,7 +5529,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
5525
5529
  const result = await store.mutate(key, fingerprint, async (db) => {
5526
5530
  if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
5527
5531
  if (request.method === "DELETE" && id2)
5528
- return store.remove(resource, id2, version(), db);
5532
+ return store.remove(resource, id2, version2(), db);
5529
5533
  if (request.method === "POST" && !id2 || request.method === "PUT" && id2) {
5530
5534
  const value = resource === "providers" ? parse(providerInputSchema, body) : parse(profileInputSchema, body);
5531
5535
  if (id2 && value.id !== id2)
@@ -5535,7 +5539,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
5535
5539
  const provider = await store.get("providers", profile.providerId, db);
5536
5540
  validateHarnessProvider(profile.harness, provider);
5537
5541
  }
5538
- const saved = await store.put(resource, value, id2 ? version() : undefined, db);
5542
+ const saved = await store.put(resource, value, id2 ? version2() : undefined, db);
5539
5543
  if (resource === "providers" && id2)
5540
5544
  await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id2]);
5541
5545
  return saved;
@@ -5562,7 +5566,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
5562
5566
  if (store.engine === "postgresql")
5563
5567
  await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR UPDATE", [id2]);
5564
5568
  const provider = await store.get("providers", id2, db);
5565
- if (provider.version !== version())
5569
+ if (provider.version !== version2())
5566
5570
  throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
5567
5571
  const catalog = parse(catalogSchema, body);
5568
5572
  const expectedSource = provider.manualModels.length ? "manual" : "remote";
@@ -5642,7 +5646,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
5642
5646
  const run = await store.get("runs", id2, db);
5643
5647
  if (run.status !== "running")
5644
5648
  throw new Fault(409, "run_finished", "Run has already finished.");
5645
- return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
5649
+ return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version2(), db);
5646
5650
  }
5647
5651
  throw new Fault(404, "not_found", "Route was not found.");
5648
5652
  });
@@ -5816,9 +5820,10 @@ async function openCliRuntime(env = process.env, resolveCredential) {
5816
5820
 
5817
5821
  // src/credentials.ts
5818
5822
  import { z as z5 } from "zod";
5823
+ import { ExecutableTrustError, repairExecutablePermissions, validateExecutable } from "@hasna/contracts/executable-trust";
5819
5824
  import { constants as constants2 } from "fs";
5820
- import { open, readdir, unlink, link, lstat as lstat2, access as access2, stat as stat2, realpath, readlink, rename } from "fs/promises";
5821
- import { join as join2, isAbsolute as isAbsolute2, dirname as dirname2, parse as pathParts, resolve as resolvePath, sep } from "path";
5825
+ import { open, readdir, unlink, link, lstat as lstat2 } from "fs/promises";
5826
+ import { join as join2, isAbsolute as isAbsolute2 } from "path";
5822
5827
  import { createHash as createHash4, randomUUID } from "crypto";
5823
5828
  import { execFile as execFile2, spawn } from "child_process";
5824
5829
  import { promisify as promisify2 } from "util";
@@ -5967,53 +5972,31 @@ class CredentialBindings {
5967
5972
  return { removed: name };
5968
5973
  }
5969
5974
  }
5970
- async function inspectVaultExecutable(path, permitWritableFile = false) {
5971
- let info, resolved;
5972
- try {
5973
- resolved = await realpath(path);
5974
- await access2(resolved, constants2.X_OK);
5975
- info = await stat2(resolved);
5976
- if (!info.isFile())
5977
- throw new Error;
5978
- } catch {
5979
- throw new Fault(422, "vault_exec_unavailable", "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.");
5980
- }
5981
- if (process.platform !== "win32" && (!permitWritableFile && info.mode & 18 || info.uid !== 0 && info.uid !== process.getuid?.()))
5982
- 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.");
5983
- if (process.platform !== "win32") {
5984
- const seen = new Set;
5985
- const inspect = async (candidate) => {
5986
- let prefix = pathParts(candidate).root;
5987
- for (const part of candidate.slice(prefix.length).split(sep)) {
5988
- if (!part)
5989
- continue;
5990
- prefix = join2(prefix, part);
5991
- if (seen.has(prefix))
5992
- continue;
5993
- seen.add(prefix);
5994
- if (seen.size > 256)
5995
- throw new Fault(422, "vault_exec_permissions", "The secrets executable path has too many symlink components.");
5996
- const entry = await lstat2(prefix);
5997
- const permittedFile = permitWritableFile && prefix === resolved && entry.isFile();
5998
- if (entry.uid !== 0 && entry.uid !== process.getuid?.() || !entry.isSymbolicLink() && !permittedFile && entry.mode & 18)
5999
- 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.");
6000
- if (entry.isSymbolicLink())
6001
- await inspect(resolvePath(dirname2(prefix), await readlink(prefix)));
6002
- }
6003
- };
6004
- try {
6005
- await inspect(path);
6006
- await inspect(resolved);
6007
- } catch (error) {
6008
- if (error instanceof Fault)
6009
- throw error;
6010
- throw new Fault(422, "vault_exec_unavailable", "The secrets executable path changed or could not be verified. Retry with a trusted installation.");
6011
- }
6012
- }
6013
- return resolved;
5975
+ function vaultExecutableFault(error) {
5976
+ if (!(error instanceof ExecutableTrustError))
5977
+ throw error;
5978
+ const codes = {
5979
+ invalid_request: "invalid_request",
5980
+ executable_unavailable: "vault_exec_unavailable",
5981
+ executable_permissions: "vault_exec_permissions",
5982
+ executable_repair_unsafe: "vault_exec_repair_unsafe",
5983
+ executable_digest_mismatch: "vault_exec_digest_mismatch"
5984
+ };
5985
+ const messages = {
5986
+ invalid_request: error.message,
5987
+ executable_unavailable: "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.",
5988
+ 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.",
5989
+ executable_repair_unsafe: error.message,
5990
+ executable_digest_mismatch: "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed."
5991
+ };
5992
+ throw new Fault(error.status, codes[error.code], messages[error.code]);
6014
5993
  }
6015
5994
  async function validateVaultExecutable(path) {
6016
- return inspectVaultExecutable(path);
5995
+ try {
5996
+ return await validateExecutable(path);
5997
+ } catch (error) {
5998
+ return vaultExecutableFault(error);
5999
+ }
6017
6000
  }
6018
6001
  async function readKeychain(source) {
6019
6002
  if (process.platform !== "darwin")
@@ -6237,6 +6220,7 @@ import { z as z6 } from "zod";
6237
6220
  import { createHash as createHash5 } from "crypto";
6238
6221
  import { createInterface } from "readline/promises";
6239
6222
  var absent = (error) => error instanceof SwitcherError && error.status === 404;
6223
+ var MAX_CREDENTIAL_MATCHES = 256;
6240
6224
  var secretMetadataSchema = z6.object({
6241
6225
  key: vaultKeySchema,
6242
6226
  type: z6.enum(["api_key", "password", "token", "credential", "other"]),
@@ -6276,7 +6260,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
6276
6260
  const operator2 = await resolveVaultOperatorEnvironment(provisional, env);
6277
6261
  const entries = new Map;
6278
6262
  for (const query of searchTerms(provider)) {
6279
- const output = await runVaultCommand(provisional, ["search", query, "--json"], env, {}, {
6263
+ const output = await runVaultCommand(provisional, ["search", query, "--json", "--full", "--limit", String(MAX_CREDENTIAL_MATCHES + 1)], env, {}, {
6280
6264
  captureBytes: 256 * 1024,
6281
6265
  oversizeCode: "vault_metadata_oversized",
6282
6266
  oversizeMessage: "Secrets returned too much credential metadata; narrow the vault naming or bind an exact key explicitly.",
@@ -6290,12 +6274,14 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
6290
6274
  } catch {
6291
6275
  throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned invalid credential metadata JSON.");
6292
6276
  }
6293
- const result = secretMetadataSchema.array().max(1000).safeParse(parsed);
6277
+ if (Array.isArray(parsed) && parsed.length > MAX_CREDENTIAL_MATCHES)
6278
+ throw new Fault(422, "credential_matches_too_many", "More than 256 credential metadata rows matched. Bind an exact vault key explicitly.");
6279
+ const result = secretMetadataSchema.array().max(MAX_CREDENTIAL_MATCHES).safeParse(parsed);
6294
6280
  if (!result.success)
6295
6281
  throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned an unsupported credential metadata shape.");
6296
6282
  for (const entry of result.data)
6297
6283
  entries.set(entry.key, entry);
6298
- if (entries.size > 256)
6284
+ if (entries.size > MAX_CREDENTIAL_MATCHES)
6299
6285
  throw new Fault(422, "credential_matches_too_many", "More than 256 credential references matched. Bind an exact vault key explicitly.");
6300
6286
  }
6301
6287
  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 } }));
@@ -0,0 +1,44 @@
1
+ import { type NativeState } from "./native-state";
2
+ type Identity = {
3
+ dev: number;
4
+ ino: number;
5
+ size: number;
6
+ mtimeMs: number;
7
+ ctimeMs: number;
8
+ };
9
+ type File = {
10
+ path: string;
11
+ bytes: number;
12
+ sha256: string;
13
+ source: Identity;
14
+ existing: boolean;
15
+ sessionId?: string;
16
+ };
17
+ export type NativeStateImport = {
18
+ state: NativeState;
19
+ source: string;
20
+ entries: string[];
21
+ directories: string[];
22
+ files: File[];
23
+ bytes: number;
24
+ };
25
+ /** Entire import is checked before writes. Account/auth/config/SQLite files
26
+ * cannot be selected, including through links. This is a snapshot, not cutover. */
27
+ export declare function planNativeStateImport(state: NativeState, source: string, selection?: string[]): Promise<NativeStateImport>;
28
+ export declare function nativeStateImportDigest(plan: NativeStateImport): string;
29
+ export declare function nativeStateImportSummary(plan: NativeStateImport, applied: boolean): {
30
+ mode: string;
31
+ tool: import("./native-state").SharedNativeTool;
32
+ entries: string[];
33
+ planDigest: string;
34
+ files: number;
35
+ newFiles: number;
36
+ publishedFiles: number;
37
+ bytes: number;
38
+ originalsPreserved: boolean;
39
+ cutoverComplete: boolean;
40
+ sqliteCopied: boolean;
41
+ notice: string;
42
+ };
43
+ export declare function applyNativeStateImport(plan: NativeStateImport): Promise<void>;
44
+ export {};
@@ -0,0 +1,32 @@
1
+ export type SharedNativeTool = "codex" | "claude";
2
+ export type NativeState = {
3
+ tool: SharedNativeTool;
4
+ home: string;
5
+ sqliteHome?: string;
6
+ marker: string;
7
+ instructions?: Record<string, unknown>;
8
+ };
9
+ export declare function nativeStateRequested(tool: SharedNativeTool, environment?: NodeJS.ProcessEnv, explicit?: boolean): boolean;
10
+ export declare function validateNativeStateVersion(tool: SharedNativeTool, version: string | undefined): void;
11
+ export declare const CODEX_INSTRUCTION_KEYS: readonly ["instructions", "developer_instructions", "model_instructions_file", "compact_prompt", "experimental_compact_prompt_file", "include_permissions_instructions", "include_apps_instructions", "include_collaboration_mode_instructions", "include_environment_context", "project_doc_max_bytes", "project_doc_fallback_filenames"];
12
+ type Entry = {
13
+ name: string;
14
+ kind: "directory" | "file";
15
+ };
16
+ export declare const NATIVE_STATE_ENTRIES: Record<SharedNativeTool, readonly Entry[]>;
17
+ export declare function assertNativeStateDirectory(path: string): Promise<void>;
18
+ export declare function ensureNativeStateDirectory(path: string, create?: boolean): Promise<void>;
19
+ export declare function withNativeStateLock<T>(state: NativeState, operation: () => Promise<T>): Promise<T>;
20
+ /** A nested CLI keeps its authentication home. Refuse conflicting instruction
21
+ * overlays rather than rewriting account config or exposing instructions in argv. */
22
+ export declare function assertNativeInstructionOverlay(state: NativeState, overlayHome: string): Promise<void>;
23
+ /** This marker identifies the corpus, never the selected authentication home. */
24
+ export declare function resolveNativeState(tool: SharedNativeTool, environment?: NodeJS.ProcessEnv, options?: {
25
+ create?: boolean;
26
+ }): Promise<NativeState>;
27
+ export declare function nativeStateEnvironment(state: NativeState): Record<string, string>;
28
+ /** Metadata only. Old data remains visible as pending migration; normal launch
29
+ * never treats starting a fresh shared overlay as completed legacy migration. */
30
+ export declare function legacyNativeStateWarnings(root: string, state: NativeState): Promise<string[]>;
31
+ export declare function projectNativeState(state: NativeState, overlayHome: string): Promise<void>;
32
+ export {};
package/dist/sdk.js CHANGED
@@ -429,12 +429,12 @@ async function detectChatGPTApp(appPath, system = host) {
429
429
  const bundleId = await field("CFBundleIdentifier");
430
430
  if (bundleId !== "com.openai.codex")
431
431
  continue;
432
- const name = await field("CFBundleExecutable"), version = await field("CFBundleShortVersionString");
432
+ const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
433
433
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
434
434
  continue;
435
435
  const executable = join(path, "Contents/MacOS", name), codexExecutable = join(path, "Contents/Resources/codex");
436
436
  if (await system.executable(executable) && await system.executable(codexExecutable))
437
- return { path, executable, codexExecutable, bundleId, version };
437
+ return { path, executable, codexExecutable, bundleId, version: version2 };
438
438
  } catch {}
439
439
  }
440
440
  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.");
@@ -457,12 +457,12 @@ async function detectClaudeDesktopApp(appPath, system = host) {
457
457
  const bundleId = await field("CFBundleIdentifier");
458
458
  if (bundleId !== "com.anthropic.claudefordesktop")
459
459
  continue;
460
- const name = await field("CFBundleExecutable"), version = await field("CFBundleShortVersionString");
460
+ const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
461
461
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
462
462
  continue;
463
463
  const executable = join(path, "Contents/MacOS", name);
464
464
  if (await system.executable(executable))
465
- return { path, executable, bundleId, version };
465
+ return { path, executable, bundleId, version: version2 };
466
466
  } catch {}
467
467
  }
468
468
  throw new Fault(404, "app_not_installed", "Install the current Claude macOS desktop app or supply its absolute .app path with --app-path.");
@@ -608,17 +608,17 @@ class SwitcherClient {
608
608
  createProvider(input, idempotencyKey) {
609
609
  return this.request("POST", "/v1/providers", input, { idempotencyKey });
610
610
  }
611
- updateProvider(input, version, idempotencyKey) {
612
- return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
611
+ updateProvider(input, version2, idempotencyKey) {
612
+ return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
613
613
  }
614
- deleteProvider(id, version, idempotencyKey) {
615
- return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
614
+ deleteProvider(id, version2, idempotencyKey) {
615
+ return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
616
616
  }
617
617
  async editModel(providerId, operation, value) {
618
618
  const model = typeof value === "string" ? undefined : parse(modelSchema, value);
619
619
  const id = model?.id ?? parse(modelSchema.shape.id, value);
620
620
  const provider = await this.getProvider(providerId);
621
- const { version, updatedAt, ...input } = provider;
621
+ const { version: version2, updatedAt, ...input } = provider;
622
622
  const manual = provider.manualModels.some((item) => item.id === id);
623
623
  const additional = (provider.additionalModels ?? []).some((item) => item.id === id);
624
624
  if (operation === "add" && (manual || additional))
@@ -630,7 +630,7 @@ class SwitcherClient {
630
630
  const additionalModels = (provider.additionalModels ?? []).filter((item) => item.id !== id);
631
631
  if (operation !== "remove")
632
632
  (useManual ? manualModels : additionalModels).push(model);
633
- return this.updateProvider({ ...input, manualModels, additionalModels }, version);
633
+ return this.updateProvider({ ...input, manualModels, additionalModels }, version2);
634
634
  }
635
635
  addModel(providerId, model) {
636
636
  return this.editModel(providerId, "add", model);
@@ -659,11 +659,11 @@ class SwitcherClient {
659
659
  createProfile(input, idempotencyKey) {
660
660
  return this.request("POST", "/v1/profiles", input, { idempotencyKey });
661
661
  }
662
- updateProfile(input, version, idempotencyKey) {
663
- return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
662
+ updateProfile(input, version2, idempotencyKey) {
663
+ return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
664
664
  }
665
- deleteProfile(id, version, idempotencyKey) {
666
- return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
665
+ deleteProfile(id, version2, idempotencyKey) {
666
+ return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
667
667
  }
668
668
  launchPlan(profileId, idempotencyKey) {
669
669
  return this.request("POST", "/v1/launch-plans", { profileId }, { idempotencyKey });
@@ -677,8 +677,8 @@ class SwitcherClient {
677
677
  createRun(input, idempotencyKey) {
678
678
  return this.request("POST", "/v1/runs", { ...input, modelPolicyVersion: 1 }, { idempotencyKey });
679
679
  }
680
- finishRun(id, version, input, idempotencyKey) {
681
- return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version, idempotencyKey });
680
+ finishRun(id, version2, input, idempotencyKey) {
681
+ return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version: version2, idempotencyKey });
682
682
  }
683
683
  }
684
684
  function clientFromEnv(env = process.env, options = {}) {
@@ -67,9 +67,13 @@ var routingEventsSchema = z2.array(routingEventSchema).max(1000);
67
67
  function canonicalPolicyJSON(value) {
68
68
  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);
69
69
  }
70
+ // package.json
71
+ var version = "0.2.9";
72
+
73
+ // src/version.ts
74
+ var VERSION = version;
70
75
 
71
76
  // src/domain.ts
72
- var VERSION = "0.2.7";
73
77
  var harnessSchema = z3.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "antigravity", "junie", "aider", "kilo"]);
74
78
  var protocolSchema = z3.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
75
79
  var idSchema = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
@@ -379,8 +383,8 @@ class Store {
379
383
  }
380
384
  return value;
381
385
  }
382
- async remove(kind, id, version, db) {
383
- const rows = await db.unsafe(`DELETE FROM switcher_${kind} WHERE id = $1 AND version = $2 RETURNING id`, [id, version]);
386
+ async remove(kind, id, version2, db) {
387
+ const rows = await db.unsafe(`DELETE FROM switcher_${kind} WHERE id = $1 AND version = $2 RETURNING id`, [id, version2]);
384
388
  if (!rows.length)
385
389
  throw new Fault(409, "version_conflict", "Entry changed or is missing; reload before retrying.");
386
390
  return { deleted: id };
@@ -918,7 +922,7 @@ var openapi_default = {
918
922
  openapi: "3.0.3",
919
923
  info: {
920
924
  title: "Switcher API",
921
- version: "0.2.7",
925
+ version: "0.2.9",
922
926
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
923
927
  },
924
928
  security: [
@@ -5230,7 +5234,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
5230
5234
  }
5231
5235
  }
5232
5236
  const fingerprint = hash(JSON.stringify([request.method, route2, body, request.headers.get("if-match")])).toString("hex");
5233
- const version = () => {
5237
+ const version2 = () => {
5234
5238
  const v = request.headers.get("if-match");
5235
5239
  if (!v || !/^[1-9]\d*$/.test(v))
5236
5240
  throw new Fault(428, "version_required", "Supply the current numeric version in If-Match.");
@@ -5250,7 +5254,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
5250
5254
  const result = await store.mutate(key, fingerprint, async (db) => {
5251
5255
  if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
5252
5256
  if (request.method === "DELETE" && id2)
5253
- return store.remove(resource, id2, version(), db);
5257
+ return store.remove(resource, id2, version2(), db);
5254
5258
  if (request.method === "POST" && !id2 || request.method === "PUT" && id2) {
5255
5259
  const value = resource === "providers" ? parse(providerInputSchema, body) : parse(profileInputSchema, body);
5256
5260
  if (id2 && value.id !== id2)
@@ -5260,7 +5264,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
5260
5264
  const provider = await store.get("providers", profile.providerId, db);
5261
5265
  validateHarnessProvider(profile.harness, provider);
5262
5266
  }
5263
- const saved = await store.put(resource, value, id2 ? version() : undefined, db);
5267
+ const saved = await store.put(resource, value, id2 ? version2() : undefined, db);
5264
5268
  if (resource === "providers" && id2)
5265
5269
  await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id2]);
5266
5270
  return saved;
@@ -5287,7 +5291,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
5287
5291
  if (store.engine === "postgresql")
5288
5292
  await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR UPDATE", [id2]);
5289
5293
  const provider = await store.get("providers", id2, db);
5290
- if (provider.version !== version())
5294
+ if (provider.version !== version2())
5291
5295
  throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
5292
5296
  const catalog = parse(catalogSchema, body);
5293
5297
  const expectedSource = provider.manualModels.length ? "manual" : "remote";
@@ -5367,7 +5371,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
5367
5371
  const run = await store.get("runs", id2, db);
5368
5372
  if (run.status !== "running")
5369
5373
  throw new Fault(409, "run_finished", "Run has already finished.");
5370
- return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
5374
+ return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version2(), db);
5371
5375
  }
5372
5376
  throw new Fault(404, "not_found", "Route was not found.");
5373
5377
  });
@@ -0,0 +1 @@
1
+ export declare const VERSION: string;
@@ -4,7 +4,7 @@
4
4
  "name": "switcher",
5
5
  "class": "cli-with-store",
6
6
  "contractVersion": "v1",
7
- "kitVersion": "1.0.2",
7
+ "kitVersion": "1.3.0",
8
8
  "description": "Universal provider and model switcher with API-first local and hosted operation. CLI, MCP and SDK resolve one authenticated HTTP authority through @hasna/contracts and fail closed when hosted configuration is missing or invalid. HASNA_SWITCHER_LOCAL=1 deliberately selects an owned loopback API backed by SQLite; hosted https://api.hasna.com/switcher uses PostgreSQL and signed revocable API keys. Provider credentials remain local to the launcher and are never stored or returned by the service.",
9
9
  "bins": [
10
10
  "switcher",