@hasna/switcher 0.2.8 → 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/README.md CHANGED
@@ -456,7 +456,7 @@ switcher credentials repair-executable deepseek --sha256 EXPECTED_EXECUTABLE_SHA
456
456
 
457
457
  For a fresh installation whose unsafe executable prevents creating a binding, use `switcher credentials repair-executable --vault-cli /absolute/path/to/secrets --sha256 EXPECTED_EXECUTABLE_SHA256` first, then bind normally. Select either a binding reference or an explicit path.
458
458
 
459
- The digest is a release-artifact checksum, not a credential. Do not substitute the installed file's own hash: that would trust any altered bytes. Repair checks the exact bytes, file owner/type and every path ancestor, then creates an identical private copy and atomically replaces the writable executable with group/public write permission removed. Cache hardlinks and already-open writers retain the old inode and cannot change the repaired executable. It then runs the ordinary launch checks again. Safe files are unchanged; digest mismatches, unsafe ancestors and unowned files are refused. The command never starts Secrets, contacts the vault, changes bindings, or repairs permissions automatically during launch. Run this explicit step after each affected installation; a later Bun install can reset bin modes again. Reinstall a verified package if its bytes differ.
459
+ The digest is a release-artifact checksum, not a credential. Do not substitute the installed file's own hash: that would trust any altered bytes. Repair checks the exact bytes, file owner/type and every path ancestor, then creates an identical private copy and atomically replaces a writable or hardlinked executable with group/public write permission removed. Cache hardlinks and already-open writers retain the old inode and cannot change the repaired executable. It then runs the ordinary launch checks again. Safe files with a private inode are unchanged; digest mismatches, unsafe ancestors and unowned files are refused. The command never starts Secrets, contacts the vault, changes bindings, or repairs permissions automatically during launch. Run this explicit step after each affected installation; a later Bun install can reset bin modes again. Reinstall a verified package if its bytes differ.
460
460
 
461
461
  For provider keys already stored in macOS Keychain, use `--keychain-service SERVICE --keychain-account ACCOUNT` instead of vault options. Bindings contain only references and authorized origins under `~/.hasna/switcher/config/credential-bindings`, in owner-only files. They remain local even when Switcher uses a remote API. A configured binding takes precedence over environment aliases; an unavailable binding never falls back to another account.
462
462
 
package/dist/cli/index.js CHANGED
@@ -513,9 +513,13 @@ var routingEventsSchema = z3.array(routingEventSchema).max(1000);
513
513
  function canonicalPolicyJSON(value) {
514
514
  return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
515
515
  }
516
+ // package.json
517
+ var version = "0.2.9";
518
+
519
+ // src/version.ts
520
+ var VERSION = version;
516
521
 
517
522
  // src/domain.ts
518
- var VERSION = "0.2.7";
519
523
  var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "antigravity", "junie", "aider", "kilo"]);
520
524
  var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
521
525
  var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
@@ -1364,12 +1368,12 @@ async function detectChatGPTApp(appPath, system = host) {
1364
1368
  const bundleId = await field("CFBundleIdentifier");
1365
1369
  if (bundleId !== "com.openai.codex")
1366
1370
  continue;
1367
- const name = await field("CFBundleExecutable"), version = await field("CFBundleShortVersionString");
1371
+ const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
1368
1372
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
1369
1373
  continue;
1370
1374
  const executable = join3(path, "Contents/MacOS", name), codexExecutable = join3(path, "Contents/Resources/codex");
1371
1375
  if (await system.executable(executable) && await system.executable(codexExecutable))
1372
- return { path, executable, codexExecutable, bundleId, version };
1376
+ return { path, executable, codexExecutable, bundleId, version: version2 };
1373
1377
  } catch {}
1374
1378
  }
1375
1379
  throw new Fault(404, "app_not_installed", "Install the current ChatGPT/Codex macOS app or use --app-path with its absolute .app path. Legacy ChatGPT Classic cannot run custom Codex providers.");
@@ -1392,12 +1396,12 @@ async function detectClaudeDesktopApp(appPath, system = host) {
1392
1396
  const bundleId = await field("CFBundleIdentifier");
1393
1397
  if (bundleId !== "com.anthropic.claudefordesktop")
1394
1398
  continue;
1395
- const name = await field("CFBundleExecutable"), version = await field("CFBundleShortVersionString");
1399
+ const name = await field("CFBundleExecutable"), version2 = await field("CFBundleShortVersionString");
1396
1400
  if (!/^[A-Za-z0-9 _-]+$/.test(name))
1397
1401
  continue;
1398
1402
  const executable = join3(path, "Contents/MacOS", name);
1399
1403
  if (await system.executable(executable))
1400
- return { path, executable, bundleId, version };
1404
+ return { path, executable, bundleId, version: version2 };
1401
1405
  } catch {}
1402
1406
  }
1403
1407
  throw new Fault(404, "app_not_installed", "Install the current Claude macOS desktop app or supply its absolute .app path with --app-path.");
@@ -1543,17 +1547,17 @@ class SwitcherClient {
1543
1547
  createProvider(input, idempotencyKey) {
1544
1548
  return this.request("POST", "/v1/providers", input, { idempotencyKey });
1545
1549
  }
1546
- updateProvider(input, version, idempotencyKey) {
1547
- return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
1550
+ updateProvider(input, version2, idempotencyKey) {
1551
+ return this.request("PUT", `/v1/providers/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
1548
1552
  }
1549
- deleteProvider(id, version, idempotencyKey) {
1550
- return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
1553
+ deleteProvider(id, version2, idempotencyKey) {
1554
+ return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
1551
1555
  }
1552
1556
  async editModel(providerId, operation, value) {
1553
1557
  const model = typeof value === "string" ? undefined : parse2(modelSchema, value);
1554
1558
  const id = model?.id ?? parse2(modelSchema.shape.id, value);
1555
1559
  const provider = await this.getProvider(providerId);
1556
- const { version, updatedAt, ...input } = provider;
1560
+ const { version: version2, updatedAt, ...input } = provider;
1557
1561
  const manual = provider.manualModels.some((item) => item.id === id);
1558
1562
  const additional = (provider.additionalModels ?? []).some((item) => item.id === id);
1559
1563
  if (operation === "add" && (manual || additional))
@@ -1565,7 +1569,7 @@ class SwitcherClient {
1565
1569
  const additionalModels = (provider.additionalModels ?? []).filter((item) => item.id !== id);
1566
1570
  if (operation !== "remove")
1567
1571
  (useManual ? manualModels : additionalModels).push(model);
1568
- return this.updateProvider({ ...input, manualModels, additionalModels }, version);
1572
+ return this.updateProvider({ ...input, manualModels, additionalModels }, version2);
1569
1573
  }
1570
1574
  addModel(providerId, model) {
1571
1575
  return this.editModel(providerId, "add", model);
@@ -1594,11 +1598,11 @@ class SwitcherClient {
1594
1598
  createProfile(input, idempotencyKey) {
1595
1599
  return this.request("POST", "/v1/profiles", input, { idempotencyKey });
1596
1600
  }
1597
- updateProfile(input, version, idempotencyKey) {
1598
- return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version, idempotencyKey });
1601
+ updateProfile(input, version2, idempotencyKey) {
1602
+ return this.request("PUT", `/v1/profiles/${encodeURIComponent(input.id)}`, input, { version: version2, idempotencyKey });
1599
1603
  }
1600
- deleteProfile(id, version, idempotencyKey) {
1601
- return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
1604
+ deleteProfile(id, version2, idempotencyKey) {
1605
+ return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version: version2, idempotencyKey });
1602
1606
  }
1603
1607
  launchPlan(profileId, idempotencyKey) {
1604
1608
  return this.request("POST", "/v1/launch-plans", { profileId }, { idempotencyKey });
@@ -1612,8 +1616,8 @@ class SwitcherClient {
1612
1616
  createRun(input, idempotencyKey) {
1613
1617
  return this.request("POST", "/v1/runs", { ...input, modelPolicyVersion: 1 }, { idempotencyKey });
1614
1618
  }
1615
- finishRun(id, version, input, idempotencyKey) {
1616
- return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version, idempotencyKey });
1619
+ finishRun(id, version2, input, idempotencyKey) {
1620
+ return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input, { version: version2, idempotencyKey });
1617
1621
  }
1618
1622
  }
1619
1623
  function clientFromEnv(env = process.env, options = {}) {
@@ -2051,8 +2055,8 @@ class Store {
2051
2055
  }
2052
2056
  return value;
2053
2057
  }
2054
- async remove(kind, id, version, db) {
2055
- const rows = await db.unsafe(`DELETE FROM switcher_${kind} WHERE id = $1 AND version = $2 RETURNING id`, [id, version]);
2058
+ async remove(kind, id, version2, db) {
2059
+ const rows = await db.unsafe(`DELETE FROM switcher_${kind} WHERE id = $1 AND version = $2 RETURNING id`, [id, version2]);
2056
2060
  if (!rows.length)
2057
2061
  throw new Fault(409, "version_conflict", "Entry changed or is missing; reload before retrying.");
2058
2062
  return { deleted: id };
@@ -2539,7 +2543,7 @@ var openapi_default = {
2539
2543
  openapi: "3.0.3",
2540
2544
  info: {
2541
2545
  title: "Switcher API",
2542
- version: "0.2.7",
2546
+ version: "0.2.9",
2543
2547
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2544
2548
  },
2545
2549
  security: [
@@ -6851,7 +6855,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
6851
6855
  }
6852
6856
  }
6853
6857
  const fingerprint = hash(JSON.stringify([request.method, route2, body, request.headers.get("if-match")])).toString("hex");
6854
- const version = () => {
6858
+ const version2 = () => {
6855
6859
  const v = request.headers.get("if-match");
6856
6860
  if (!v || !/^[1-9]\d*$/.test(v))
6857
6861
  throw new Fault(428, "version_required", "Supply the current numeric version in If-Match.");
@@ -6871,7 +6875,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
6871
6875
  const result = await store.mutate(key, fingerprint, async (db) => {
6872
6876
  if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
6873
6877
  if (request.method === "DELETE" && id2)
6874
- return store.remove(resource, id2, version(), db);
6878
+ return store.remove(resource, id2, version2(), db);
6875
6879
  if (request.method === "POST" && !id2 || request.method === "PUT" && id2) {
6876
6880
  const value = resource === "providers" ? parse2(providerInputSchema, body) : parse2(profileInputSchema, body);
6877
6881
  if (id2 && value.id !== id2)
@@ -6881,7 +6885,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
6881
6885
  const provider = await store.get("providers", profile.providerId, db);
6882
6886
  validateHarnessProvider(profile.harness, provider);
6883
6887
  }
6884
- const saved = await store.put(resource, value, id2 ? version() : undefined, db);
6888
+ const saved = await store.put(resource, value, id2 ? version2() : undefined, db);
6885
6889
  if (resource === "providers" && id2)
6886
6890
  await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id2]);
6887
6891
  return saved;
@@ -6908,7 +6912,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
6908
6912
  if (store.engine === "postgresql")
6909
6913
  await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR UPDATE", [id2]);
6910
6914
  const provider = await store.get("providers", id2, db);
6911
- if (provider.version !== version())
6915
+ if (provider.version !== version2())
6912
6916
  throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
6913
6917
  const catalog = parse2(catalogSchema, body);
6914
6918
  const expectedSource = provider.manualModels.length ? "manual" : "remote";
@@ -6988,7 +6992,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
6988
6992
  const run = await store.get("runs", id2, db);
6989
6993
  if (run.status !== "running")
6990
6994
  throw new Fault(409, "run_finished", "Run has already finished.");
6991
- return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
6995
+ return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version2(), db);
6992
6996
  }
6993
6997
  throw new Fault(404, "not_found", "Route was not found.");
6994
6998
  });
@@ -10195,41 +10199,41 @@ var versionAtLeast2 = (raw, minimum) => {
10195
10199
  }
10196
10200
  return true;
10197
10201
  };
10198
- function validateHarnessVersion(harness, version) {
10199
- if (harness === "antigravity" && version?.trim() !== "1.2.5")
10202
+ function validateHarnessVersion(harness, version2) {
10203
+ if (harness === "antigravity" && version2?.trim() !== "1.2.5")
10200
10204
  throw new Error("Antigravity CLI 1.2.5 is required by the verified native adapter.");
10201
- if (harness === "junie" && !/\b3196\.5\b/.test(version ?? ""))
10205
+ if (harness === "junie" && !/\b3196\.5\b/.test(version2 ?? ""))
10202
10206
  throw new Error("Junie build 3196.5 is required by the verified custom model adapter.");
10203
- if (harness === "kilo" && !versionAtLeast2(version, [7, 5, 15]))
10207
+ if (harness === "kilo" && !versionAtLeast2(version2, [7, 5, 15]))
10204
10208
  throw new Error("Kilo >=7.5.15 is required by this scoped provider bridge.");
10205
- if (harness === "omp" && !versionAtLeast2(version, [18, 1, 11]))
10209
+ if (harness === "omp" && !versionAtLeast2(version2, [18, 1, 11]))
10206
10210
  throw new Error("OMP >=18.1.11 is required for the native catalog and persistent session adapter.");
10207
- if (harness === "dsh" && (!versionAtLeast2(version, [0, 1, 2]) || /\b0\.1\.2-/.test(version ?? "") && !/\b0\.1\.2-rc\.[1-9]\d*(?:\b|$)/.test(version ?? "")))
10211
+ if (harness === "dsh" && (!versionAtLeast2(version2, [0, 1, 2]) || /\b0\.1\.2-/.test(version2 ?? "") && !/\b0\.1\.2-rc\.[1-9]\d*(?:\b|$)/.test(version2 ?? "")))
10208
10212
  throw new Error("DeepSeek Harness (dsh) >=0.1.2-rc.1 is required for the native profile adapter.");
10209
- if (harness === "aider" && !/^(?:aider\s+)?0\.86\.2(?:\s|$)/i.test(version ?? ""))
10213
+ if (harness === "aider" && !/^(?:aider\s+)?0\.86\.2(?:\s|$)/i.test(version2 ?? ""))
10210
10214
  throw new Error("Aider 0.86.2 is required by the verified native configuration adapter.");
10211
- if (harness === "claude" && !versionAtLeast2(version, [2, 1, 257]))
10215
+ if (harness === "claude" && !versionAtLeast2(version2, [2, 1, 257]))
10212
10216
  throw new Error("Claude Code >=2.1.257 is required for a full native modelPicker.");
10213
- if (harness === "pi" && !versionAtLeast2(version, [0, 85, 1]))
10217
+ if (harness === "pi" && !versionAtLeast2(version2, [0, 85, 1]))
10214
10218
  throw new Error("Pi >=0.85.1 is required by this catalog adapter.");
10215
- if (harness === "codex" && !versionAtLeast2(version, [0, 153, 0]))
10219
+ if (harness === "codex" && !versionAtLeast2(version2, [0, 153, 0]))
10216
10220
  throw new Error("Codex >=0.153.0 is required by this catalog adapter.");
10217
- if (harness === "grok" && !versionAtLeast2(version, [1, 0, 13]))
10221
+ if (harness === "grok" && !versionAtLeast2(version2, [1, 0, 13]))
10218
10222
  throw new Error("Grok Build >=1.0.13 is required by this remote catalog adapter.");
10219
- if (harness === "cline" && !versionAtLeast2(version, [3, 0, 61]))
10223
+ if (harness === "cline" && !versionAtLeast2(version2, [3, 0, 61]))
10220
10224
  throw new Error("Cline >=3.0.61 is required by this native provider adapter.");
10221
- if (harness === "prime-agent" && !versionAtLeast2(version, [0, 9, 2]))
10225
+ if (harness === "prime-agent" && !versionAtLeast2(version2, [0, 9, 2]))
10222
10226
  throw new Error("Prime Agent >=0.9.2 is required by this catalog adapter.");
10223
- if (harness === "opencode" && !versionAtLeast2(version, [1, 18, 0]))
10227
+ if (harness === "opencode" && !versionAtLeast2(version2, [1, 18, 0]))
10224
10228
  throw new Error("Legacy OpenCode >=1.18.0 is required by this catalog adapter.");
10225
10229
  if (harness === "opencode2") {
10226
- const preview = version?.match(/opencode2.*beta-(\d+)/i);
10227
- if (!(preview && Number(preview[1]) >= 19157) && !versionAtLeast2(version, [2, 0, 0]))
10230
+ const preview = version2?.match(/opencode2.*beta-(\d+)/i);
10231
+ if (!(preview && Number(preview[1]) >= 19157) && !versionAtLeast2(version2, [2, 0, 0]))
10228
10232
  throw new Error("OpenCode 2 beta-19157 or newer is required for isolated provider configuration; legacy OpenCode is not supported by this adapter.");
10229
10233
  }
10230
- if (harness === "hermes" && !versionAtLeast2(version, [0, 21, 0]))
10234
+ if (harness === "hermes" && !versionAtLeast2(version2, [0, 21, 0]))
10231
10235
  throw new Error("Hermes Agent >=0.21.0 is required by this provider and session adapter.");
10232
- if (harness === "gemini" && !/^0\.58\.0$/.test(version?.trim() ?? ""))
10236
+ if (harness === "gemini" && !/^0\.58\.0$/.test(version2?.trim() ?? ""))
10233
10237
  throw new Error("Gemini CLI 0.58.0 is required by the verified native settings and argument contract.");
10234
10238
  }
10235
10239
  async function jsonFile(dir, name, value) {
@@ -11329,9 +11333,10 @@ import { createInterface } from "readline/promises";
11329
11333
 
11330
11334
  // src/credentials.ts
11331
11335
  import { z as z7 } from "zod";
11336
+ import { ExecutableTrustError, repairExecutablePermissions, validateExecutable } from "@hasna/contracts/executable-trust";
11332
11337
  import { constants as constants5 } from "fs";
11333
- import { open as open3, readdir as readdir5, unlink, link, lstat as lstat6, access as access4, stat as stat6, realpath as realpath6, readlink, rename as rename2 } from "fs/promises";
11334
- import { join as join16, isAbsolute as isAbsolute15, dirname as dirname8, parse as pathParts, resolve as resolvePath, sep as sep2 } from "path";
11338
+ import { open as open3, readdir as readdir5, unlink, link, lstat as lstat6 } from "fs/promises";
11339
+ import { join as join16, isAbsolute as isAbsolute15 } from "path";
11335
11340
  import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
11336
11341
  import { execFile as execFile3, spawn } from "child_process";
11337
11342
  import { promisify as promisify3 } from "util";
@@ -11486,131 +11491,37 @@ function credentialReference(selector) {
11486
11491
  throw new Fault(400, "credential_reference_required", "Use the explicit SWITCHER_PROVIDER_ reference for this provider.");
11487
11492
  return parse2(reference, name);
11488
11493
  }
11489
- async function inspectVaultExecutable(path, permitWritableFile = false) {
11490
- let info, resolved;
11491
- try {
11492
- resolved = await realpath6(path);
11493
- await access4(resolved, constants5.X_OK);
11494
- info = await stat6(resolved);
11495
- if (!info.isFile())
11496
- throw new Error;
11497
- } catch {
11498
- throw new Fault(422, "vault_exec_unavailable", "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.");
11499
- }
11500
- if (process.platform !== "win32" && (!permitWritableFile && info.mode & 18 || info.uid !== 0 && info.uid !== process.getuid?.()))
11501
- 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.");
11502
- if (process.platform !== "win32") {
11503
- const seen = new Set;
11504
- const inspect = async (candidate) => {
11505
- let prefix = pathParts(candidate).root;
11506
- for (const part of candidate.slice(prefix.length).split(sep2)) {
11507
- if (!part)
11508
- continue;
11509
- prefix = join16(prefix, part);
11510
- if (seen.has(prefix))
11511
- continue;
11512
- seen.add(prefix);
11513
- if (seen.size > 256)
11514
- throw new Fault(422, "vault_exec_permissions", "The secrets executable path has too many symlink components.");
11515
- const entry = await lstat6(prefix);
11516
- const permittedFile = permitWritableFile && prefix === resolved && entry.isFile();
11517
- if (entry.uid !== 0 && entry.uid !== process.getuid?.() || !entry.isSymbolicLink() && !permittedFile && entry.mode & 18)
11518
- 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.");
11519
- if (entry.isSymbolicLink())
11520
- await inspect(resolvePath(dirname8(prefix), await readlink(prefix)));
11521
- }
11522
- };
11523
- try {
11524
- await inspect(path);
11525
- await inspect(resolved);
11526
- } catch (error) {
11527
- if (error instanceof Fault)
11528
- throw error;
11529
- throw new Fault(422, "vault_exec_unavailable", "The secrets executable path changed or could not be verified. Retry with a trusted installation.");
11530
- }
11531
- }
11532
- return resolved;
11494
+ function vaultExecutableFault(error) {
11495
+ if (!(error instanceof ExecutableTrustError))
11496
+ throw error;
11497
+ const codes = {
11498
+ invalid_request: "invalid_request",
11499
+ executable_unavailable: "vault_exec_unavailable",
11500
+ executable_permissions: "vault_exec_permissions",
11501
+ executable_repair_unsafe: "vault_exec_repair_unsafe",
11502
+ executable_digest_mismatch: "vault_exec_digest_mismatch"
11503
+ };
11504
+ const messages = {
11505
+ invalid_request: error.message,
11506
+ executable_unavailable: "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.",
11507
+ executable_permissions: "The secrets executable and its ancestor directories must be owned by this user or root and not writable by other users. Use credentials repair-executable REFERENCE --sha256 EXPECTED with the executable digest from a verified package artifact. Launch never repairs permissions automatically.",
11508
+ executable_repair_unsafe: error.message,
11509
+ executable_digest_mismatch: "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed."
11510
+ };
11511
+ throw new Fault(error.status, codes[error.code], messages[error.code]);
11533
11512
  }
11534
11513
  async function validateVaultExecutable(path) {
11535
- return inspectVaultExecutable(path);
11514
+ try {
11515
+ return await validateExecutable(path);
11516
+ } catch (error) {
11517
+ return vaultExecutableFault(error);
11518
+ }
11536
11519
  }
11537
11520
  async function repairVaultExecutablePermissions(path, expectedSha256) {
11538
- if (!/^[a-f0-9]{64}$/.test(expectedSha256))
11539
- throw new Fault(400, "invalid_request", "--sha256 requires the SHA256 of the executable member from a verified package artifact.");
11540
- if (!isAbsolute15(path) || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path))
11541
- throw new Fault(400, "invalid_request", "Secrets executable must be an absolute path without control characters.");
11542
- if (process.platform === "win32")
11543
- throw new Fault(422, "vault_exec_repair_unsafe", "Executable permission repair requires POSIX file permissions.");
11544
- const resolved = await inspectVaultExecutable(path, true);
11545
- const file = await open3(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
11546
- const unsafe = () => new Fault(422, "vault_exec_repair_unsafe", "Executable ownership, type, links or contents changed; no trusted repair can be confirmed.");
11547
- let temporary;
11548
11521
  try {
11549
- const before = await file.stat();
11550
- const limit = 256 * 1024 * 1024;
11551
- if (!before.isFile() || before.uid !== process.getuid?.() || before.size > limit || before.mode & 3584)
11552
- throw unsafe();
11553
- const sameFile = (info) => info.dev === before.dev && info.ino === before.ino && info.size === before.size && info.uid === before.uid && info.nlink === before.nlink && info.mode === before.mode && info.mtimeMs === before.mtimeMs && info.ctimeMs === before.ctimeMs;
11554
- const hash2 = async (target) => {
11555
- const digest = createHash10("sha256");
11556
- const buffer = Buffer.alloc(1024 * 1024);
11557
- let position = 0;
11558
- while (true) {
11559
- const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
11560
- if (!bytesRead)
11561
- break;
11562
- position += bytesRead;
11563
- if (position > limit)
11564
- throw unsafe();
11565
- const bytes = buffer.subarray(0, bytesRead);
11566
- digest.update(bytes);
11567
- if (target)
11568
- await target.writeFile(bytes);
11569
- }
11570
- if (position !== before.size || !sameFile(await file.stat()))
11571
- throw unsafe();
11572
- if (digest.digest("hex") !== expectedSha256)
11573
- throw new Fault(422, "vault_exec_digest_mismatch", "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed.");
11574
- };
11575
- await hash2();
11576
- const mode = before.mode & 511 & ~18;
11577
- const changed = mode !== (before.mode & 511);
11578
- if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat6(resolved)))
11579
- throw unsafe();
11580
- if (!changed) {
11581
- await validateVaultExecutable(path);
11582
- return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
11583
- }
11584
- temporary = join16(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
11585
- const replacement = await open3(temporary, "wx", 384);
11586
- try {
11587
- await hash2(replacement);
11588
- await replacement.chmod(mode);
11589
- await replacement.sync();
11590
- const ready = await replacement.stat();
11591
- if (!ready.isFile() || ready.nlink !== 1 || ready.uid !== before.uid || ready.size !== before.size)
11592
- throw unsafe();
11593
- if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat6(resolved)))
11594
- throw unsafe();
11595
- await rename2(temporary, resolved);
11596
- temporary = undefined;
11597
- const installed = await lstat6(resolved);
11598
- if (installed.dev !== ready.dev || installed.ino !== ready.ino || await validateVaultExecutable(path) !== resolved)
11599
- throw unsafe();
11600
- const directory = await open3(dirname8(resolved), constants5.O_RDONLY | constants5.O_DIRECTORY | constants5.O_NOFOLLOW);
11601
- try {
11602
- await directory.sync();
11603
- } finally {
11604
- await directory.close();
11605
- }
11606
- } finally {
11607
- await replacement.close();
11608
- }
11609
- return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
11610
- } finally {
11611
- await file.close();
11612
- if (temporary)
11613
- await unlink(temporary);
11522
+ return await repairExecutablePermissions(path, expectedSha256);
11523
+ } catch (error) {
11524
+ return vaultExecutableFault(error);
11614
11525
  }
11615
11526
  }
11616
11527
  function bindingTarget(selector, override, allowedOrigins) {
@@ -12535,13 +12446,13 @@ async function inspectOri(options = {}) {
12535
12446
  const versionResult = await readOnly(executable, ["--version"], environment, options.cwd);
12536
12447
  if (versionResult.code !== 0)
12537
12448
  throw new OriBackendError("ori_unavailable", "Ori could not report its version; install it or pass an explicit executable.");
12538
- const version = parseVersion(versionResult.stdout);
12539
- if (!version)
12449
+ const version2 = parseVersion(versionResult.stdout);
12450
+ if (!version2)
12540
12451
  throw new OriBackendError("invalid_contract", "Ori --version did not report a version.");
12541
12452
  const inventoryResult = await readOnly(executable, ["harness", "list", "--json"], environment, options.cwd);
12542
12453
  if (inventoryResult.code !== 0)
12543
12454
  throw new OriBackendError("ori_unavailable", "Ori could not report its harness inventory.");
12544
- return { executable, version, harnesses: parseHarnesses(inventoryResult.stdout) };
12455
+ return { executable, version: version2, harnesses: parseHarnesses(inventoryResult.stdout) };
12545
12456
  }
12546
12457
  function assertSupportedOriVersion(contract) {
12547
12458
  if (!/^0\.12\./.test(contract.version))
@@ -12661,7 +12572,7 @@ import { fileURLToPath } from "url";
12661
12572
 
12662
12573
  // src/desktop-state.ts
12663
12574
  import { Database as Database3 } from "bun:sqlite";
12664
- import { readFile as readFile7, writeFile as writeFile14, rm as rm3, lstat as lstat7, rename as rename3, chmod as chmod2 } from "fs/promises";
12575
+ import { readFile as readFile7, writeFile as writeFile14, rm as rm3, lstat as lstat7, rename as rename2, chmod as chmod2 } from "fs/promises";
12665
12576
  async function safeDesktopRead(path) {
12666
12577
  try {
12667
12578
  const info = await lstat7(path);
@@ -12678,7 +12589,7 @@ async function writeDesktopPrivate(path, text) {
12678
12589
  const temporary = path + "." + crypto.randomUUID() + ".tmp";
12679
12590
  try {
12680
12591
  await writeFile14(temporary, text, { mode: 384, flag: "wx" });
12681
- await rename3(temporary, path);
12592
+ await rename2(temporary, path);
12682
12593
  } finally {
12683
12594
  await rm3(temporary, { force: true });
12684
12595
  }
@@ -12710,18 +12621,18 @@ async function desktopLease(path) {
12710
12621
  }
12711
12622
 
12712
12623
  // src/native-state.ts
12713
- import { lstat as lstat8, mkdir as mkdir11, open as open4, opendir, readlink as readlink2, realpath as realpath7, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
12624
+ import { lstat as lstat8, mkdir as mkdir11, open as open4, opendir, readlink, realpath as realpath6, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
12714
12625
  import { constants as constants7 } from "fs";
12715
12626
  import { homedir as homedir9 } from "os";
12716
- import { dirname as dirname9, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve9 } from "path";
12627
+ import { dirname as dirname8, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve9 } from "path";
12717
12628
  function nativeStateRequested(tool, environment = process.env, explicit = false) {
12718
12629
  const suffix = tool.toUpperCase();
12719
12630
  return explicit || environment[`HASNA_${suffix}_STATE_HOME`] !== undefined || environment[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
12720
12631
  }
12721
- function validateNativeStateVersion(tool, version) {
12632
+ function validateNativeStateVersion(tool, version2) {
12722
12633
  if (tool !== "codex")
12723
12634
  return;
12724
- const match = version?.match(/(\d+)\.(\d+)\.(\d+)/), actual = match?.slice(1).map(Number);
12635
+ const match = version2?.match(/(\d+)\.(\d+)\.(\d+)/), actual = match?.slice(1).map(Number);
12725
12636
  if (!actual || actual[0] !== 0 || actual[1] < 154)
12726
12637
  throw new Fault(422, "native_state_version", "Shared Codex state requires Codex 0.154.0 or newer, whose metadata and resume protocol has been acceptance-tested by Switcher.");
12727
12638
  }
@@ -12766,25 +12677,25 @@ function credentialOverlay(path) {
12766
12677
  return /(?:^|\/)subscriptions\/profiles\//.test(path) || /(?:^|\/)switcher\/state\/(?:desktop|desktop-claude|launch-[^/]+)\//.test(path);
12767
12678
  }
12768
12679
  async function assertSafeAncestors(path) {
12769
- for (let parent = path;; parent = dirname9(parent)) {
12680
+ for (let parent = path;; parent = dirname8(parent)) {
12770
12681
  const ancestor = await lstat8(parent);
12771
12682
  const stickyRoot = ancestor.uid === 0 && (ancestor.mode & 512) !== 0;
12772
12683
  if (!ancestor.isDirectory() || ancestor.isSymbolicLink() || ![0, process.getuid?.()].includes(ancestor.uid) || (ancestor.mode & 18) !== 0 && !stickyRoot)
12773
12684
  throw new Fault(422, "native_state_permissions", "Shared native state has an unsafe ancestor directory.");
12774
- if (parent === dirname9(parent))
12685
+ if (parent === dirname8(parent))
12775
12686
  break;
12776
12687
  }
12777
12688
  }
12778
12689
  async function assertNativeStateDirectory(path) {
12779
12690
  const entry = await info(path);
12780
- if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || await realpath7(path) !== path)
12691
+ if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || await realpath6(path) !== path)
12781
12692
  throw new Fault(422, "native_state_permissions", "Shared native state must be an owned directory without writable or symbolic-link redirection.");
12782
- await assertSafeAncestors(dirname9(path));
12693
+ await assertSafeAncestors(dirname8(path));
12783
12694
  }
12784
12695
  async function ensureNativeStateDirectory(path, create = true) {
12785
12696
  if (await info(path))
12786
12697
  return assertNativeStateDirectory(path);
12787
- await ensureNativeStateDirectory(dirname9(path), create);
12698
+ await ensureNativeStateDirectory(dirname8(path), create);
12788
12699
  if (!create)
12789
12700
  return;
12790
12701
  await mkdir11(path, { mode: 448 }).catch((error) => {
@@ -12880,9 +12791,9 @@ async function codexInstructionProjection(home, config, allowedExternalFiles = {
12880
12791
  if (CODEX_INSTRUCTION_FILE_KEYS.has(key)) {
12881
12792
  const path = resolve9(home, value), entry = await info(path);
12882
12793
  const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute16(relativePath);
12883
- if (!contained && path !== allowedExternalFiles[key] || !entry || !entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || ![0, process.getuid?.()].includes(entry.uid) || (entry.mode & 18) !== 0 || await realpath7(path) !== path)
12794
+ if (!contained && path !== allowedExternalFiles[key] || !entry || !entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || ![0, process.getuid?.()].includes(entry.uid) || (entry.mode & 18) !== 0 || await realpath6(path) !== path)
12884
12795
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
12885
- await assertSafeAncestors(dirname9(path));
12796
+ await assertSafeAncestors(dirname8(path));
12886
12797
  const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW).catch(() => {
12887
12798
  throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
12888
12799
  });
@@ -13036,14 +12947,14 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13036
12947
  await assertCodexDatabaseRedirectSafe(state, overlayHome);
13037
12948
  for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
13038
12949
  const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
13039
- await ensureNativeStateDirectory(dirname9(target), false);
13040
- await ensureNativeStateDirectory(dirname9(destination), false);
12950
+ await ensureNativeStateDirectory(dirname8(target), false);
12951
+ await ensureNativeStateDirectory(dirname8(destination), false);
13041
12952
  const source = await info(target), existing = await info(destination);
13042
12953
  if (source && (source.isSymbolicLink() || source.uid !== process.getuid?.() || (source.mode & 18) !== 0 || source.isFile() && source.nlink !== 1 || (entry.kind === "directory" ? !source.isDirectory() : !source.isFile())))
13043
12954
  throw new Fault(422, "native_state_entry", "A shared native state entry has an unsupported type, owner or permissions.");
13044
12955
  if (source?.isDirectory())
13045
12956
  await assertShareableTree(target);
13046
- if (existing && (!existing.isSymbolicLink() || resolve9(dirname9(destination), await readlink2(destination)) !== target))
12957
+ if (existing && (!existing.isSymbolicLink() || resolve9(dirname8(destination), await readlink(destination)) !== target))
13047
12958
  throw new Fault(409, "native_state_migration_required", "This launch profile already contains native state. Preserve and migrate its noncredential state before linking the shared corpus.");
13048
12959
  }
13049
12960
  const createdLinks = [];
@@ -13051,7 +12962,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13051
12962
  try {
13052
12963
  for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
13053
12964
  const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
13054
- const targetParent = dirname9(target), destinationParent = dirname9(destination);
12965
+ const targetParent = dirname8(target), destinationParent = dirname8(destination);
13055
12966
  if (!await info(targetParent))
13056
12967
  await createTrackedDirectory(targetParent, createdDirectories);
13057
12968
  else
@@ -13079,7 +12990,7 @@ async function projectNativeStateUnlocked(state, overlayHome) {
13079
12990
  } catch (error) {
13080
12991
  for (const item2 of createdLinks.reverse()) {
13081
12992
  try {
13082
- if ((await info(item2.destination))?.isSymbolicLink() && resolve9(dirname9(item2.destination), await readlink2(item2.destination)) === item2.target)
12993
+ if ((await info(item2.destination))?.isSymbolicLink() && resolve9(dirname8(item2.destination), await readlink(item2.destination)) === item2.target)
13083
12994
  await unlink2(item2.destination);
13084
12995
  } catch {}
13085
12996
  }
@@ -13251,7 +13162,7 @@ ${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join("
13251
13162
  // src/claude-desktop-launch.ts
13252
13163
  import { createHash as createHash13 } from "crypto";
13253
13164
  import { execFile as execFile5 } from "child_process";
13254
- import { access as access5, rm as rm5, writeFile as writeFile16 } from "fs/promises";
13165
+ import { access as access4, rm as rm5, writeFile as writeFile16 } from "fs/promises";
13255
13166
  import { homedir as homedir10, userInfo as userInfo2 } from "os";
13256
13167
  import { join as join19 } from "path";
13257
13168
  import { promisify as promisify5 } from "util";
@@ -13260,7 +13171,7 @@ var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
13260
13171
  var claudeDesktopDataDirectory = () => join19(homedir10(), "Library/Application Support/Claude-3p");
13261
13172
  async function assertAvailable(userData) {
13262
13173
  for (const path of [join19("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
13263
- if (await access5(path).then(() => true, () => false))
13174
+ if (await access4(path).then(() => true, () => false))
13264
13175
  throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
13265
13176
  let openFiles;
13266
13177
  try {
@@ -13288,8 +13199,8 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
13288
13199
  validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
13289
13200
  if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
13290
13201
  throw new Fault(400, "desktop_arguments", "Claude desktop uses its own effort and permission controls; native CLI arguments and Codex-only launch controls are not accepted.");
13291
- const version = app.version.split(".").map(Number);
13292
- if (version.length < 3 || version.some((n) => !Number.isSafeInteger(n)) || version[0] < 1 || version[0] === 1 && version[1] < 52386)
13202
+ const version2 = app.version.split(".").map(Number);
13203
+ if (version2.length < 3 || version2.some((n) => !Number.isSafeInteger(n)) || version2[0] < 1 || version2[0] === 1 && version2[1] < 52386)
13293
13204
  throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
13294
13205
  const userData = system?.userData ?? claudeDesktopDataDirectory();
13295
13206
  const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
@@ -13998,7 +13909,7 @@ async function resolveLaunchProvider(client, selector, options = {}) {
13998
13909
  existing = await client.getProvider(desired.id);
13999
13910
  }
14000
13911
  }
14001
- const { version, updatedAt, ...input } = existing;
13912
+ const { version: version2, updatedAt, ...input } = existing;
14002
13913
  const { additionalModels: _savedAdditions, credentialCheck: savedCredentialCheck, ...savedSettings } = parse2(providerInputSchema, input);
14003
13914
  const { additionalModels: _presetAdditions, credentialCheck: presetCredentialCheck, ...presetSettings } = desired;
14004
13915
  if (JSON.stringify(savedSettings) !== JSON.stringify(presetSettings) || savedCredentialCheck !== undefined && JSON.stringify(savedCredentialCheck) !== JSON.stringify(presetCredentialCheck))
@@ -14074,7 +13985,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
14074
13985
  import { createHash as createHash15 } from "crypto";
14075
13986
  import { constants as constants8 } from "fs";
14076
13987
  import { lstat as lstat9, open as open5, opendir as opendir2, link as link2, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
14077
- import { basename as basename4, dirname as dirname10, isAbsolute as isAbsolute17, join as join21, relative as relative6, resolve as resolve12 } from "path";
13988
+ import { basename as basename4, dirname as dirname9, isAbsolute as isAbsolute17, join as join21, relative as relative6, resolve as resolve12 } from "path";
14078
13989
  var MAX_FILES = 1e5;
14079
13990
  var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
14080
13991
  var refused = () => new Fault(409, "native_state_import_conflict", "Native state import found changed, unsafe or divergent data. No existing file will be replaced. Keep the original directory and resolve the conflict explicitly.");
@@ -14241,8 +14152,8 @@ async function planNativeStateImport(state, source, selection) {
14241
14152
  async function visit(path, kind) {
14242
14153
  if (++seen > MAX_FILES || path.split("/").length > 32)
14243
14154
  throw refused();
14244
- await ensureNativeStateDirectory(dirname10(join21(source, path)), false);
14245
- await ensureNativeStateDirectory(dirname10(join21(state.home, path)), false);
14155
+ await ensureNativeStateDirectory(dirname9(join21(source, path)), false);
14156
+ await ensureNativeStateDirectory(dirname9(join21(state.home, path)), false);
14246
14157
  const from = join21(source, path), to = join21(state.home, path), entry = await info2(from), target = await info2(to);
14247
14158
  if (!entry)
14248
14159
  return;
@@ -14316,14 +14227,14 @@ async function applyNativeStateImportUnlocked(plan) {
14316
14227
  throw refused();
14317
14228
  const requiredDirectories = new Set([plan.state.home]);
14318
14229
  for (const path of plan.directories) {
14319
- for (let directory = join21(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname10(directory)) {
14230
+ for (let directory = join21(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname9(directory)) {
14320
14231
  requiredDirectories.add(directory);
14321
14232
  if (directory === plan.state.home)
14322
14233
  break;
14323
14234
  }
14324
14235
  }
14325
14236
  for (const file of plan.files.filter((file2) => !file2.existing)) {
14326
- for (let directory = dirname10(join21(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname10(directory)) {
14237
+ for (let directory = dirname9(join21(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname9(directory)) {
14327
14238
  requiredDirectories.add(directory);
14328
14239
  if (directory === plan.state.home)
14329
14240
  break;
@@ -14344,7 +14255,7 @@ async function applyNativeStateImportUnlocked(plan) {
14344
14255
  for (const file of plan.files) {
14345
14256
  if (file.existing)
14346
14257
  continue;
14347
- const target = join21(plan.state.home, file.path), temporary = join21(dirname10(target), `.switcher-import-${crypto.randomUUID()}`);
14258
+ const target = join21(plan.state.home, file.path), temporary = join21(dirname9(target), `.switcher-import-${crypto.randomUUID()}`);
14348
14259
  staged.push({ temporary, target });
14349
14260
  const copied = await fingerprint2(join21(plan.source, file.path), temporary);
14350
14261
  if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
@@ -239,18 +239,8 @@ export declare class CredentialBindings {
239
239
  }
240
240
  export declare function credentialReference(selector: string): string;
241
241
  export declare function validateVaultExecutable(path: string): Promise<string>;
242
- /** Explicit install finalization. The caller supplies a digest from a verified
243
- * artifact, never a digest computed from the currently installed executable.
244
- * No credential is resolved and the executable is never started. */
245
- export declare function repairVaultExecutablePermissions(path: string, expectedSha256: string): Promise<{
246
- changed: false;
247
- mode: string;
248
- sha256: string;
249
- } | {
250
- changed: true;
251
- mode: string;
252
- sha256: string;
253
- }>;
242
+ /** Explicit, digest-verified finalization. Never resolves a credential or starts the executable. */
243
+ export declare function repairVaultExecutablePermissions(path: string, expectedSha256: string): Promise<import("@hasna/contracts/executable-trust").ExecutableRepairResult>;
254
244
  export declare function bindingTarget(selector: string, override?: string, allowedOrigins?: string[]): {
255
245
  credentialEnv: string;
256
246
  origins: string[];
package/dist/domain.d.ts CHANGED
@@ -3,7 +3,7 @@ import { type RoutingEvent } from "./model-policy-schema";
3
3
  export { modelPolicySchema, routingEventSchema, routingEventsSchema } from "./model-policy-schema";
4
4
  export type { ModelPolicy, RoutingEvent } from "./model-policy-schema";
5
5
  export type { AuthStyle } from "./auth";
6
- export declare const VERSION = "0.2.7";
6
+ export { VERSION } from "./version";
7
7
  export declare const harnessSchema: z.ZodEnum<["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "antigravity", "junie", "aider", "kilo"]>;
8
8
  export declare const protocolSchema: z.ZodEnum<["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]>;
9
9
  export declare const idSchema: z.ZodString;
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 = {}) {
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")
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",
package/openapi.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "openapi": "3.0.3",
3
3
  "info": {
4
4
  "title": "Switcher API",
5
- "version": "0.2.7",
5
+ "version": "0.2.9",
6
6
  "description": "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
7
7
  },
8
8
  "security": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hasna/switcher",
3
- "version": "0.2.8",
3
+ "version": "0.2.9",
4
4
  "type": "module",
5
5
  "description": "Universal provider and model switcher for coding harnesses with an API, SDK and self-hosted storage",
6
6
  "license": "Apache-2.0",
@@ -72,7 +72,7 @@
72
72
  "@types/pg": "8.23.1"
73
73
  },
74
74
  "dependencies": {
75
- "@hasna/contracts": "1.0.2",
75
+ "@hasna/contracts": "1.3.0",
76
76
  "@modelcontextprotocol/sdk": "^1.29.0",
77
77
  "jsonc-parser": "3.3.1",
78
78
  "yaml": "2.9.0",