@hasna/switcher 0.2.1 → 0.2.3

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/mcp/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // src/mcp.ts
5
5
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
6
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
- import { z as z5 } from "zod";
7
+ import { z as z7 } from "zod";
8
8
 
9
9
  // src/runtime.ts
10
10
  import { randomBytes } from "crypto";
@@ -69,7 +69,7 @@ function canonicalPolicyJSON(value) {
69
69
  }
70
70
 
71
71
  // src/domain.ts
72
- var VERSION = "0.2.1";
72
+ var VERSION = "0.2.3";
73
73
  var harnessSchema = z3.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
74
74
  var protocolSchema = z3.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
75
75
  var idSchema = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
@@ -94,6 +94,8 @@ var urlSchema = z3.string().max(2000).superRefine((v, ctx) => {
94
94
  ctx.addIssue({ code: "custom", message: "Invalid endpoint URL" });
95
95
  }
96
96
  }).transform(endpoint);
97
+ var credentialCheckPath = z3.string().min(1).max(200).regex(/^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$/).refine((value) => !value.startsWith("/") && !value.split("/").some((part) => part === "." || part === ".."), "credentialCheck.path must be relative without dot segments");
98
+ var credentialCheckSchema = z3.object({ method: z3.enum(["GET", "HEAD"]).default("GET"), path: credentialCheckPath }).strict();
97
99
  var expiresOnSchema = z3.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
98
100
  const day = new Date(`${value}T00:00:00.000Z`);
99
101
  return Number.isFinite(day.getTime()) && day.toISOString().slice(0, 10) === value;
@@ -119,6 +121,7 @@ var providerInputSchema = z3.object({
119
121
  protocol: protocolSchema,
120
122
  credentialEnv: envRef.optional(),
121
123
  authStyle: z3.enum(["bearer", "x-api-key", "api-key"]).default("bearer"),
124
+ credentialCheck: credentialCheckSchema.optional(),
122
125
  catalogBaseUrl: urlSchema.optional(),
123
126
  catalogFormat: z3.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]).optional(),
124
127
  catalogAuthStyle: z3.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
@@ -137,6 +140,7 @@ var providerPresetSchema = z3.object({
137
140
  protocol: protocolSchema,
138
141
  baseUrl: urlSchema.optional(),
139
142
  authStyle: z3.enum(["bearer", "x-api-key", "api-key"]),
143
+ credentialCheck: credentialCheckSchema.optional(),
140
144
  catalogBaseUrl: urlSchema.optional(),
141
145
  catalogFormat: z3.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]),
142
146
  catalogAuthStyle: z3.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
@@ -168,6 +172,7 @@ var runUpdateSchema = z3.object({
168
172
  routingEvents: routingEventsSchema.optional(),
169
173
  routingEventsDropped: z3.number().int().min(0).max(1e6).optional()
170
174
  }).strict();
175
+ var catalogSchema = z3.object({ models: z3.array(modelSchema).max(1e4), refreshedAt: z3.string().datetime(), source: z3.enum(["remote", "manual"]) }).strict();
171
176
 
172
177
  class Fault extends Error {
173
178
  status;
@@ -178,6 +183,14 @@ class Fault extends Error {
178
183
  this.code = code;
179
184
  }
180
185
  }
186
+
187
+ class CommandInterrupted extends Fault {
188
+ exitCode;
189
+ constructor(exitCode, message) {
190
+ super(499, "interrupted", message);
191
+ this.exitCode = exitCode;
192
+ }
193
+ }
181
194
  function parse(schema, value) {
182
195
  const result = schema.safeParse(value);
183
196
  if (!result.success)
@@ -278,7 +291,7 @@ var providerPresets = [
278
291
  route("openai-responses", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
279
292
  route("anthropic-messages", "https://api.deepseek.com/anthropic/v1", { catalogBaseUrl: "https://api.deepseek.com" })
280
293
  ], ["https://api-docs.deepseek.com/guides/anthropic_api", "https://api-docs.deepseek.com/api/list-models", "https://api-docs.deepseek.com/updates/", "https://api-docs.deepseek.com/guides/responses_api/"], "DEEPSEEK_API_KEY"),
281
- preset("openrouter", "OpenRouter", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, "https://openrouter.ai/api/v1", { catalogAuthStyle: "none" })), ["https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties", "https://openrouter.ai/docs/guides/overview"], "OPENROUTER_API_KEY"),
294
+ preset("openrouter", "OpenRouter", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, "https://openrouter.ai/api/v1", { catalogAuthStyle: "none", credentialCheck: { method: "GET", path: "key" } })), ["https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties", "https://openrouter.ai/docs/guides/overview"], "OPENROUTER_API_KEY"),
282
295
  preset("anthropic", "Anthropic", [route("anthropic-messages", "https://api.anthropic.com/v1", { authStyle: "x-api-key" })], ["https://platform.claude.com/docs/en/api/overview", "https://platform.claude.com/docs/en/api/models/list"], "ANTHROPIC_API_KEY"),
283
296
  preset("gemini", "Google Gemini", [route("gemini-generate-content", "https://generativelanguage.googleapis.com/v1beta", {
284
297
  authStyle: "x-api-key",
@@ -344,6 +357,18 @@ function getProviderPreset(id) {
344
357
  throw new Fault(404, "preset_not_found", "Unknown provider preset. Use switcher providers presets to list available presets.");
345
358
  return structuredClone(entry);
346
359
  }
360
+ function providerCredential(provider, env = process.env) {
361
+ if (!provider.credentialEnv)
362
+ return;
363
+ let value = env[provider.credentialEnv];
364
+ if (!value) {
365
+ const preset = providerPresets.find((p) => p.credentialEnv === provider.credentialEnv && p.protocols.some((route) => route.protocol === provider.protocol && (route.baseUrl ? new URL(route.baseUrl).origin === new URL(provider.baseUrl).origin : p.id === "azure-openai")));
366
+ value = preset?.credentialAliases.map((name) => env[name]).find(Boolean);
367
+ }
368
+ if (value && /[\r\n]/.test(value))
369
+ throw new Fault(422, "credential_invalid", "Provider credential contains invalid header characters.");
370
+ return value;
371
+ }
347
372
  // src/desktop-apps.ts
348
373
  import { execFile } from "child_process";
349
374
  import { access, stat } from "fs/promises";
@@ -551,6 +576,9 @@ class SwitcherClient {
551
576
  refreshModels(id, idempotencyKey) {
552
577
  return this.request("POST", `/v1/providers/${encodeURIComponent(id)}/refresh`, {}, { idempotencyKey });
553
578
  }
579
+ saveCatalog(id, providerVersion, catalog, idempotencyKey) {
580
+ return this.request("PUT", `/v1/providers/${encodeURIComponent(id)}/catalog`, catalog, { version: providerVersion, idempotencyKey });
581
+ }
554
582
  listModels(id, options = {}) {
555
583
  return this.request("GET", `/v1/providers/${encodeURIComponent(id)}/models?${this.query(options)}`);
556
584
  }
@@ -593,6 +621,10 @@ function clientFromEnv(env = process.env, options = {}) {
593
621
  var {SQL } = globalThis.Bun;
594
622
  import { chmod, mkdir } from "fs/promises";
595
623
  import { dirname, resolve } from "path";
624
+ import { createHash } from "crypto";
625
+ import { apiKeyMigrations } from "@hasna/contracts/auth";
626
+ var authMigrationPlan = () => apiKeyMigrations().map((migration) => ({ ...migration, checksum: createHash("sha256").update(migration.sql).digest("hex") }));
627
+
596
628
  class Store {
597
629
  tail = Promise.resolve();
598
630
  async exclusive(action) {
@@ -630,13 +662,16 @@ class Store {
630
662
  await chmod(file, 384);
631
663
  }
632
664
  const store = new Store(sql, engine);
633
- await store.migrate();
665
+ if (config.migrate === false)
666
+ await store.verifySchema();
667
+ else
668
+ await store.migrate();
634
669
  return store;
635
670
  } catch (error) {
636
671
  await sql?.close().catch(() => {});
637
672
  const code = error?.code;
638
673
  if (engine === "sqlite" && ["SQLITE_BUSY", "SQLITE_BUSY_SNAPSHOT", "SQLITE_LOCKED"].includes(code ?? "") && Date.now() < deadline) {
639
- await new Promise((resolve2) => setTimeout(resolve2, Math.min(200, 20 * (attempt + 1))));
674
+ await new Promise((resolve) => setTimeout(resolve, Math.min(200, 20 * (attempt + 1))));
640
675
  continue;
641
676
  }
642
677
  throw new Fault(500, "storage_unavailable", "Database startup failed; check configuration, permissions and other database users.");
@@ -649,23 +684,66 @@ class Store {
649
684
  await tx.unsafe("SELECT pg_advisory_xact_lock(782034215)");
650
685
  await tx.unsafe("CREATE TABLE IF NOT EXISTS switcher_migrations (version INTEGER PRIMARY KEY)");
651
686
  const versions = await tx.unsafe("SELECT version FROM switcher_migrations ORDER BY version");
652
- if (versions.some((v) => v.version > 1))
687
+ if (versions.some((v) => v.version > 2))
653
688
  throw new Error("Newer database schema");
654
- if (versions.length)
655
- return;
656
- await tx.unsafe("CREATE TABLE switcher_providers (id TEXT PRIMARY KEY, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
657
- await tx.unsafe("CREATE TABLE switcher_profiles (id TEXT PRIMARY KEY, provider_id TEXT NOT NULL REFERENCES switcher_providers(id), version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
658
- await tx.unsafe("CREATE TABLE switcher_catalogs (id TEXT PRIMARY KEY REFERENCES switcher_providers(id) ON DELETE CASCADE, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
659
- await tx.unsafe("CREATE TABLE switcher_runs (id TEXT PRIMARY KEY, profile_id TEXT NOT NULL REFERENCES switcher_profiles(id), version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
660
- await tx.unsafe("CREATE TABLE switcher_idempotency (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, created_at TEXT NOT NULL)");
661
- await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (1)");
689
+ const applied = new Set(versions.map((v) => Number(v.version)));
690
+ if (!applied.has(1)) {
691
+ await tx.unsafe("CREATE TABLE switcher_providers (id TEXT PRIMARY KEY, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
692
+ await tx.unsafe("CREATE TABLE switcher_profiles (id TEXT PRIMARY KEY, provider_id TEXT NOT NULL REFERENCES switcher_providers(id), version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
693
+ await tx.unsafe("CREATE TABLE switcher_catalogs (id TEXT PRIMARY KEY REFERENCES switcher_providers(id) ON DELETE CASCADE, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
694
+ await tx.unsafe("CREATE TABLE switcher_runs (id TEXT PRIMARY KEY, profile_id TEXT NOT NULL REFERENCES switcher_profiles(id), version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
695
+ await tx.unsafe("CREATE TABLE switcher_idempotency (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, created_at TEXT NOT NULL)");
696
+ await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (1)");
697
+ }
698
+ if (this.engine === "postgresql") {
699
+ await tx.unsafe("CREATE TABLE IF NOT EXISTS switcher_auth_migrations (id TEXT PRIMARY KEY, checksum TEXT NOT NULL)");
700
+ const migrations = authMigrationPlan();
701
+ const authRows = await tx.unsafe("SELECT id, checksum FROM switcher_auth_migrations ORDER BY id");
702
+ const known = new Map(migrations.map((migration) => [migration.id, migration.checksum]));
703
+ for (const row of authRows) {
704
+ if (known.get(String(row.id)) !== String(row.checksum))
705
+ throw new Error("Unknown or changed API-key migration");
706
+ }
707
+ const completed = new Set(authRows.map((row) => String(row.id)));
708
+ for (const migration of migrations)
709
+ if (!completed.has(migration.id)) {
710
+ await tx.unsafe(migration.sql);
711
+ await tx.unsafe("INSERT INTO switcher_auth_migrations(id,checksum) VALUES ($1,$2)", [migration.id, migration.checksum]);
712
+ }
713
+ if (!applied.has(2))
714
+ await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (2)");
715
+ }
662
716
  });
663
717
  }
718
+ async verifySchema() {
719
+ const versions = await this.sql.unsafe("SELECT version FROM switcher_migrations ORDER BY version");
720
+ const applied = new Set(versions.map((row) => Number(row.version)));
721
+ if (!applied.has(1) || this.engine === "postgresql" && !applied.has(2) || versions.some((row) => Number(row.version) > 2))
722
+ throw new Error("Unsupported database schema");
723
+ if (this.engine === "postgresql") {
724
+ const expected = authMigrationPlan(), rows = await this.sql.unsafe("SELECT id, checksum FROM switcher_auth_migrations ORDER BY id");
725
+ const actual = new Map(rows.map((row) => [String(row.id), String(row.checksum)]));
726
+ if (actual.size !== expected.length || expected.some((migration) => actual.get(migration.id) !== migration.checksum))
727
+ throw new Error("Unsupported API-key schema");
728
+ await this.sql.unsafe("SELECT kid, app, agent, tid, scopes, token_hash, issued_at, expires_at, revoked_at, revoked_reason, last_used_at, created_by FROM api_keys LIMIT 0");
729
+ }
730
+ }
664
731
  async ready() {
665
732
  await this.exclusive(async () => {
666
733
  await this.sql.unsafe("SELECT 1");
667
734
  });
668
735
  }
736
+ authQueryClient() {
737
+ if (this.engine !== "postgresql")
738
+ throw new Fault(500, "auth_config", "Signed API keys require the PostgreSQL backend.");
739
+ return {
740
+ many: async (sql, params = []) => await this.sql.unsafe(sql, [...params]),
741
+ get: async (sql, params = []) => (await this.sql.unsafe(sql, [...params]))[0] ?? null,
742
+ execute: async (sql, params = []) => {
743
+ await this.sql.unsafe(sql, [...params]);
744
+ }
745
+ };
746
+ }
669
747
  async close() {
670
748
  await this.tail;
671
749
  await this.sql.close();
@@ -751,7 +829,8 @@ class Store {
751
829
  }
752
830
 
753
831
  // src/service.ts
754
- import { createHash as createHash2, timingSafeEqual } from "crypto";
832
+ import { createHash as createHash3, timingSafeEqual } from "crypto";
833
+ import { verifyApiKey } from "@hasna/contracts/auth";
755
834
  import { z as z4 } from "zod";
756
835
 
757
836
  // src/auth.ts
@@ -799,7 +878,7 @@ async function waitForCatalogRetry(delayMs, deadline) {
799
878
  if (Date.now() + delayMs > deadline)
800
879
  throw catalogDeadlineFault();
801
880
  if (delayMs > 0)
802
- await new Promise((resolve2) => setTimeout(resolve2, delayMs));
881
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
803
882
  }
804
883
  async function fetchCatalogPage(url, headers, deadline) {
805
884
  for (let retry = 0;; retry++) {
@@ -907,8 +986,8 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
907
986
  candidate.outputModalities = capabilities.completion_chat ? ["text"] : [];
908
987
  }
909
988
  if (provider.catalogFormat === "together") {
910
- const modalities2 = { chat: ["text"], language: ["text"], code: ["text"], image: ["image"], audio: ["audio"], video: ["video"], embedding: ["embedding"], rerank: ["rerank"], moderation: ["classification"] };
911
- candidate.outputModalities = modalities2[row.type];
989
+ const modalities = { chat: ["text"], language: ["text"], code: ["text"], image: ["image"], audio: ["audio"], video: ["video"], embedding: ["embedding"], rerank: ["rerank"], moderation: ["classification"] };
990
+ candidate.outputModalities = modalities[row.type];
912
991
  }
913
992
  if (provider.catalogFormat === "fireworks") {
914
993
  if (row.supportsImageInput === true)
@@ -1026,11 +1105,11 @@ async function discover(provider, env = process.env, resolveCredential) {
1026
1105
  }
1027
1106
 
1028
1107
  // src/model-policy.ts
1029
- import { createHash } from "crypto";
1108
+ import { createHash as createHash2 } from "crypto";
1030
1109
  var roles = ["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"];
1031
- var id = (v, label2) => {
1110
+ var id = (v, label) => {
1032
1111
  if (typeof v !== "string" || !v || v.length > 300 || /[\u0000-\u001f\u007f]/.test(v))
1033
- throw new Fault(400, "invalid_model_policy", `${label2} is invalid.`);
1112
+ throw new Fault(400, "invalid_model_policy", `${label} is invalid.`);
1034
1113
  return v;
1035
1114
  };
1036
1115
  var uniq = (xs) => [...new Set(xs)];
@@ -1088,17 +1167,20 @@ function compileModelPolicy(model, catalog, policy) {
1088
1167
  if (Object.values(aliases).some((value) => !allowedModels.includes(value)))
1089
1168
  throw new Fault(422, "model_not_allowed", "A model alias target must be explicitly allowed by the launch policy.");
1090
1169
  const result = { version: 1, model: selected, roles: compiledRoles, allowedModels, aliases, fallbacks };
1091
- return { ...result, digest: createHash("sha256").update(stable(result)).digest("hex") };
1170
+ return { ...result, digest: createHash2("sha256").update(stable(result)).digest("hex") };
1092
1171
  }
1093
1172
  // openapi.json
1094
1173
  var openapi_default = {
1095
1174
  openapi: "3.0.3",
1096
1175
  info: {
1097
1176
  title: "Switcher API",
1098
- version: "0.2.1",
1177
+ version: "0.2.3",
1099
1178
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
1100
1179
  },
1101
1180
  security: [
1181
+ {
1182
+ apiKeyAuth: []
1183
+ },
1102
1184
  {
1103
1185
  bearerAuth: []
1104
1186
  }
@@ -1852,6 +1934,73 @@ var openapi_default = {
1852
1934
  }
1853
1935
  }
1854
1936
  },
1937
+ responses: {
1938
+ "200": {
1939
+ description: "Success",
1940
+ content: {
1941
+ "application/json": {
1942
+ schema: {
1943
+ $ref: "#/components/schemas/Catalog"
1944
+ }
1945
+ }
1946
+ }
1947
+ },
1948
+ default: {
1949
+ description: "Structured error",
1950
+ content: {
1951
+ "application/json": {
1952
+ schema: {
1953
+ $ref: "#/components/schemas/Error"
1954
+ }
1955
+ }
1956
+ }
1957
+ }
1958
+ },
1959
+ description: "Self-hosted/local server refresh. Hosted clients discover locally and commit catalog metadata through the version-checked catalog endpoint."
1960
+ }
1961
+ },
1962
+ "/v1/providers/{id}/catalog": {
1963
+ put: {
1964
+ operationId: "saveCatalog",
1965
+ parameters: [
1966
+ {
1967
+ name: "id",
1968
+ in: "path",
1969
+ required: true,
1970
+ schema: {
1971
+ type: "string"
1972
+ }
1973
+ },
1974
+ {
1975
+ name: "Idempotency-Key",
1976
+ in: "header",
1977
+ required: true,
1978
+ schema: {
1979
+ type: "string",
1980
+ minLength: 8,
1981
+ maxLength: 128
1982
+ }
1983
+ },
1984
+ {
1985
+ name: "If-Match",
1986
+ in: "header",
1987
+ required: true,
1988
+ schema: {
1989
+ type: "integer",
1990
+ minimum: 1
1991
+ }
1992
+ }
1993
+ ],
1994
+ requestBody: {
1995
+ required: true,
1996
+ content: {
1997
+ "application/json": {
1998
+ schema: {
1999
+ $ref: "#/components/schemas/Catalog"
2000
+ }
2001
+ }
2002
+ }
2003
+ },
1855
2004
  responses: {
1856
2005
  "200": {
1857
2006
  description: "Success",
@@ -2239,6 +2388,36 @@ var openapi_default = {
2239
2388
  }
2240
2389
  },
2241
2390
  "/v1/openapi.json": {
2391
+ get: {
2392
+ operationId: "openApiV1",
2393
+ parameters: [],
2394
+ responses: {
2395
+ "200": {
2396
+ description: "Success",
2397
+ content: {
2398
+ "application/json": {
2399
+ schema: {
2400
+ type: "object",
2401
+ additionalProperties: true
2402
+ }
2403
+ }
2404
+ }
2405
+ },
2406
+ default: {
2407
+ description: "Structured error",
2408
+ content: {
2409
+ "application/json": {
2410
+ schema: {
2411
+ $ref: "#/components/schemas/Error"
2412
+ }
2413
+ }
2414
+ }
2415
+ }
2416
+ },
2417
+ security: []
2418
+ }
2419
+ },
2420
+ "/openapi.json": {
2242
2421
  get: {
2243
2422
  operationId: "openApi",
2244
2423
  parameters: [],
@@ -2264,12 +2443,18 @@ var openapi_default = {
2264
2443
  }
2265
2444
  }
2266
2445
  }
2267
- }
2446
+ },
2447
+ security: []
2268
2448
  }
2269
2449
  }
2270
2450
  },
2271
2451
  components: {
2272
2452
  securitySchemes: {
2453
+ apiKeyAuth: {
2454
+ type: "apiKey",
2455
+ in: "header",
2456
+ name: "x-api-key"
2457
+ },
2273
2458
  bearerAuth: {
2274
2459
  type: "http",
2275
2460
  scheme: "bearer"
@@ -2325,6 +2510,29 @@ var openapi_default = {
2325
2510
  "api-key"
2326
2511
  ]
2327
2512
  },
2513
+ credentialCheck: {
2514
+ type: "object",
2515
+ properties: {
2516
+ method: {
2517
+ type: "string",
2518
+ enum: [
2519
+ "GET",
2520
+ "HEAD"
2521
+ ],
2522
+ default: "GET"
2523
+ },
2524
+ path: {
2525
+ type: "string",
2526
+ minLength: 1,
2527
+ maxLength: 200,
2528
+ pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
2529
+ }
2530
+ },
2531
+ required: [
2532
+ "path"
2533
+ ],
2534
+ additionalProperties: false
2535
+ },
2328
2536
  catalogBaseUrl: {
2329
2537
  type: "string",
2330
2538
  maxLength: 2000
@@ -2434,6 +2642,29 @@ var openapi_default = {
2434
2642
  ],
2435
2643
  default: "bearer"
2436
2644
  },
2645
+ credentialCheck: {
2646
+ type: "object",
2647
+ properties: {
2648
+ method: {
2649
+ type: "string",
2650
+ enum: [
2651
+ "GET",
2652
+ "HEAD"
2653
+ ],
2654
+ default: "GET"
2655
+ },
2656
+ path: {
2657
+ type: "string",
2658
+ minLength: 1,
2659
+ maxLength: 200,
2660
+ pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
2661
+ }
2662
+ },
2663
+ required: [
2664
+ "path"
2665
+ ],
2666
+ additionalProperties: false
2667
+ },
2437
2668
  catalogBaseUrl: {
2438
2669
  type: "string",
2439
2670
  maxLength: 2000
@@ -2712,6 +2943,29 @@ var openapi_default = {
2712
2943
  ],
2713
2944
  default: "bearer"
2714
2945
  },
2946
+ credentialCheck: {
2947
+ type: "object",
2948
+ properties: {
2949
+ method: {
2950
+ type: "string",
2951
+ enum: [
2952
+ "GET",
2953
+ "HEAD"
2954
+ ],
2955
+ default: "GET"
2956
+ },
2957
+ path: {
2958
+ type: "string",
2959
+ minLength: 1,
2960
+ maxLength: 200,
2961
+ pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
2962
+ }
2963
+ },
2964
+ required: [
2965
+ "path"
2966
+ ],
2967
+ additionalProperties: false
2968
+ },
2715
2969
  catalogBaseUrl: {
2716
2970
  type: "string",
2717
2971
  maxLength: 2000
@@ -3773,10 +4027,12 @@ var openapi_default = {
3773
4027
  "name"
3774
4028
  ],
3775
4029
  additionalProperties: false
3776
- }
4030
+ },
4031
+ maxItems: 1e4
3777
4032
  },
3778
4033
  refreshedAt: {
3779
- type: "string"
4034
+ type: "string",
4035
+ format: "date-time"
3780
4036
  },
3781
4037
  source: {
3782
4038
  type: "string",
@@ -3834,6 +4090,29 @@ var openapi_default = {
3834
4090
  ],
3835
4091
  default: "bearer"
3836
4092
  },
4093
+ credentialCheck: {
4094
+ type: "object",
4095
+ properties: {
4096
+ method: {
4097
+ type: "string",
4098
+ enum: [
4099
+ "GET",
4100
+ "HEAD"
4101
+ ],
4102
+ default: "GET"
4103
+ },
4104
+ path: {
4105
+ type: "string",
4106
+ minLength: 1,
4107
+ maxLength: 200,
4108
+ pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
4109
+ }
4110
+ },
4111
+ required: [
4112
+ "path"
4113
+ ],
4114
+ additionalProperties: false
4115
+ },
3837
4116
  catalogBaseUrl: {
3838
4117
  type: "string",
3839
4118
  maxLength: 2000
@@ -4338,10 +4617,12 @@ var openapi_default = {
4338
4617
  "name"
4339
4618
  ],
4340
4619
  additionalProperties: false
4341
- }
4620
+ },
4621
+ maxItems: 1e4
4342
4622
  },
4343
4623
  refreshedAt: {
4344
- type: "string"
4624
+ type: "string",
4625
+ format: "date-time"
4345
4626
  },
4346
4627
  source: {
4347
4628
  type: "string",
@@ -4967,15 +5248,31 @@ var openapi_default = {
4967
5248
  Ready: {
4968
5249
  type: "object",
4969
5250
  properties: {
4970
- ready: {
4971
- type: "boolean"
5251
+ status: {
5252
+ type: "string",
5253
+ enum: [
5254
+ "ready",
5255
+ "unavailable"
5256
+ ]
5257
+ },
5258
+ version: {
5259
+ type: "string"
5260
+ },
5261
+ backend: {
5262
+ type: "string",
5263
+ enum: [
5264
+ "sqlite",
5265
+ "postgresql"
5266
+ ]
4972
5267
  },
4973
5268
  reason: {
4974
5269
  type: "string"
4975
5270
  }
4976
5271
  },
4977
5272
  required: [
4978
- "ready"
5273
+ "status",
5274
+ "version",
5275
+ "backend"
4979
5276
  ],
4980
5277
  additionalProperties: false
4981
5278
  },
@@ -5043,41 +5340,64 @@ var openapi_default = {
5043
5340
  };
5044
5341
 
5045
5342
  // src/service.ts
5046
- var snapshot = (profile, provider, catalog) => createHash2("sha256").update(JSON.stringify([profile, provider, { models: catalog.models, source: catalog.source }])).digest("hex");
5047
- var hash = (s) => createHash2("sha256").update(s).digest();
5048
- function createHandler(store, apiKey, providerEnv = process.env, resolveCredential) {
5049
- if (!apiKey || apiKey.length < 24)
5343
+ var providerCatalogFingerprint = (provider) => createHash3("sha256").update(JSON.stringify(provider)).digest("hex");
5344
+ var snapshot = (profile, provider, catalog) => createHash3("sha256").update(JSON.stringify([profile, provider, { models: catalog.models, source: catalog.source }])).digest("hex");
5345
+ var hash = (s) => createHash3("sha256").update(s).digest();
5346
+ function localApiKey(headers) {
5347
+ const direct = headers.get("x-api-key");
5348
+ if (direct)
5349
+ return direct;
5350
+ const authorization = headers.get("authorization") ?? "";
5351
+ return authorization.startsWith("Bearer ") ? authorization.slice("Bearer ".length) : "";
5352
+ }
5353
+ function createHandler(store, authentication, providerEnv = process.env, resolveCredential) {
5354
+ const localToken = typeof authentication === "string" ? authentication : undefined;
5355
+ if (localToken !== undefined && (localToken.length < 24 || /[\r\n]/.test(localToken)))
5050
5356
  throw new Fault(500, "auth_config", "Set HASNA_SWITCHER_API_KEY to a random token of at least 24 characters.");
5051
- const expected = hash(`Bearer ${apiKey}`);
5357
+ const expected = localToken === undefined ? undefined : hash(localToken);
5358
+ const verifier = typeof authentication === "string" ? undefined : verifyApiKey({
5359
+ app: "switcher",
5360
+ signingSecret: authentication.signingSecret,
5361
+ keyStatus: authentication.keyStatus,
5362
+ ...authentication.audit ? { audit: authentication.audit } : {}
5363
+ });
5052
5364
  return async (request) => {
5053
5365
  const requestId = crypto.randomUUID();
5054
5366
  const json = (body, status = 200) => Response.json(body, { status, headers: { "x-request-id": requestId, "cache-control": "no-store", "x-content-type-options": "nosniff" } });
5055
5367
  try {
5056
5368
  const url = new URL(request.url);
5057
- const route2 = url.pathname.replace(/\/$/, "");
5058
- if (request.method === "GET" && route2 === "/health")
5369
+ const route = url.pathname.replace(/\/$/, "");
5370
+ if (request.method === "GET" && route === "/health")
5059
5371
  return json({ status: "ok", version: VERSION, backend: store.engine });
5060
- if (request.method === "GET" && route2 === "/version")
5372
+ if (request.method === "GET" && route === "/version")
5061
5373
  return json({ version: VERSION });
5062
- if (request.method === "GET" && route2 === "/ready") {
5374
+ if (request.method === "GET" && route === "/ready") {
5063
5375
  try {
5064
5376
  await store.ready();
5065
- return json({ ready: true });
5377
+ return json({ status: "ready", version: VERSION, backend: store.engine });
5066
5378
  } catch {
5067
- return json({ ready: false, reason: "Storage is unavailable." }, 503);
5379
+ return json({ status: "unavailable", version: VERSION, backend: store.engine, reason: "Storage is unavailable." }, 503);
5068
5380
  }
5069
5381
  }
5070
- if (!timingSafeEqual(expected, hash(request.headers.get("authorization") ?? "")))
5071
- throw new Fault(401, "unauthorized", "A valid API bearer token is required.");
5072
- if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route2))
5382
+ if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route))
5073
5383
  return json(openapi_default);
5074
- const parts = route2.split("/").filter(Boolean);
5384
+ if (expected) {
5385
+ const presented = hash(localApiKey(request.headers));
5386
+ if (!timingSafeEqual(expected, presented))
5387
+ throw new Fault(401, "unauthorized", "A valid API key is required.");
5388
+ } else {
5389
+ const requiredScopes = [request.method === "GET" || request.method === "HEAD" ? "switcher:read" : "switcher:write"];
5390
+ const decision = await verifier.authenticate(request.headers, { method: request.method, path: route, requiredScopes });
5391
+ if (!decision.ok)
5392
+ throw new Fault(decision.status, `auth_${decision.reason}`, decision.message);
5393
+ }
5394
+ const parts = route.split("/").filter(Boolean);
5075
5395
  if (parts[0] !== "v1")
5076
5396
  throw new Fault(404, "not_found", "Route was not found.");
5077
5397
  const resource = parts[1];
5078
- const id2 = parts[2];
5079
- if (id2)
5080
- parse(idSchema, id2);
5398
+ const id = parts[2];
5399
+ if (id)
5400
+ parse(idSchema, id);
5081
5401
  const page = () => parse(z4.object({
5082
5402
  limit: z4.coerce.number().int().min(1).max(1000).default(100),
5083
5403
  offset: z4.coerce.number().int().min(0).max(1e6).default(0),
@@ -5085,16 +5405,16 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5085
5405
  }).strict(), Object.fromEntries(url.searchParams));
5086
5406
  if (request.method === "GET") {
5087
5407
  if (resource === "provider-presets" && parts.length <= 3)
5088
- return json(id2 ? getProviderPreset(id2) : { data: providerPresets });
5408
+ return json(id ? getProviderPreset(id) : { data: providerPresets });
5089
5409
  if (["providers", "profiles", "runs"].includes(resource) && parts.length <= 3) {
5090
5410
  const kind = resource;
5091
- return json(id2 ? await store.get(kind, id2) : await store.list(kind, page()));
5411
+ return json(id ? await store.get(kind, id) : await store.list(kind, page()));
5092
5412
  }
5093
- if (resource === "providers" && id2 && parts[3] === "models" && parts.length === 4) {
5094
- const catalog = await store.get("catalogs", id2);
5413
+ if (resource === "providers" && id && parts[3] === "models" && parts.length === 4) {
5414
+ const catalog = await store.get("catalogs", id);
5095
5415
  const p = page();
5096
5416
  const filtered = catalog.models.filter((m) => [m.id, m.name].some((s) => s.toLowerCase().includes(p.search.toLowerCase())));
5097
- return json({ ...catalog, models: undefined, data: filtered.slice(p.offset, p.offset + p.limit).map((m) => ({ ...m, codingEligible: codingEligible(m), expired: modelExpired(m) })), total: filtered.length, ...p });
5417
+ return json({ ...catalog, providerVersion: undefined, providerFingerprint: undefined, models: undefined, data: filtered.slice(p.offset, p.offset + p.limit).map((m) => ({ ...m, codingEligible: codingEligible(m), expired: modelExpired(m) })), total: filtered.length, ...p });
5098
5418
  }
5099
5419
  throw new Fault(404, "not_found", "Route was not found.");
5100
5420
  }
@@ -5113,7 +5433,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5113
5433
  throw new Fault(400, "invalid_json", "Request must contain valid JSON under 1 MiB.");
5114
5434
  }
5115
5435
  }
5116
- const fingerprint = hash(JSON.stringify([request.method, route2, body, request.headers.get("if-match")])).toString("hex");
5436
+ const fingerprint = hash(JSON.stringify([request.method, route, body, request.headers.get("if-match")])).toString("hex");
5117
5437
  const version = () => {
5118
5438
  const v = request.headers.get("if-match");
5119
5439
  if (!v || !/^[1-9]\d*$/.test(v))
@@ -5122,49 +5442,73 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5122
5442
  };
5123
5443
  const replay = await store.replay(key, fingerprint);
5124
5444
  if (replay.found)
5125
- return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
5445
+ return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id ? 201 : 200);
5126
5446
  let refreshed;
5127
- if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
5447
+ if (!expected && resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST")
5448
+ throw new Fault(422, "local_catalog_refresh_required", "Hosted Switcher never contacts provider URLs. Refresh with the local CLI or MCP client, which authenticates locally and commits catalog metadata only.");
5449
+ if (resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
5128
5450
  parse(z4.object({}).strict(), body);
5129
- const provider = await store.get("providers", id2);
5451
+ const provider = await store.get("providers", id);
5130
5452
  refreshed = { provider, catalog: await discover(provider, providerEnv, resolveCredential) };
5131
5453
  }
5132
5454
  const result = await store.mutate(key, fingerprint, async (db) => {
5133
5455
  if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
5134
- if (request.method === "DELETE" && id2)
5135
- return store.remove(resource, id2, version(), db);
5136
- if (request.method === "POST" && !id2 || request.method === "PUT" && id2) {
5456
+ if (request.method === "DELETE" && id)
5457
+ return store.remove(resource, id, version(), db);
5458
+ if (request.method === "POST" && !id || request.method === "PUT" && id) {
5137
5459
  const value = resource === "providers" ? parse(providerInputSchema, body) : parse(profileInputSchema, body);
5138
- if (id2 && value.id !== id2)
5460
+ if (id && value.id !== id)
5139
5461
  throw new Fault(400, "id_mismatch", "Path and body IDs must match.");
5140
5462
  if (resource === "profiles") {
5141
5463
  const profile = value;
5142
5464
  const provider = await store.get("providers", profile.providerId, db);
5143
5465
  validateHarnessProvider(profile.harness, provider);
5144
5466
  }
5145
- const saved = await store.put(resource, value, id2 ? version() : undefined, db);
5146
- if (resource === "providers" && id2)
5147
- await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id2]);
5467
+ const saved = await store.put(resource, value, id ? version() : undefined, db);
5468
+ if (resource === "providers" && id)
5469
+ await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id]);
5148
5470
  return saved;
5149
5471
  }
5150
5472
  }
5151
- if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
5473
+ if (resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
5152
5474
  if (store.engine === "postgresql")
5153
- await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id2]);
5154
- const provider = await store.get("providers", id2, db);
5475
+ await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id]);
5476
+ const provider = await store.get("providers", id, db);
5155
5477
  if (!refreshed || provider.version !== refreshed.provider.version)
5156
5478
  throw new Fault(409, "provider_changed", "Provider changed during discovery; refresh again.");
5157
5479
  const catalog = refreshed.catalog;
5158
5480
  let old;
5159
5481
  try {
5160
- old = await store.get("catalogs", id2, db);
5482
+ old = await store.get("catalogs", id, db);
5161
5483
  } catch (e) {
5162
5484
  if (!(e instanceof Fault && e.status === 404))
5163
5485
  throw e;
5164
5486
  }
5165
- return store.put("catalogs", { id: id2, ...catalog }, old?.version, db);
5487
+ const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
5488
+ return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
5489
+ }
5490
+ if (resource === "providers" && id && parts[3] === "catalog" && parts.length === 4 && request.method === "PUT") {
5491
+ if (store.engine === "postgresql")
5492
+ await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id]);
5493
+ const provider = await store.get("providers", id, db);
5494
+ if (provider.version !== version())
5495
+ throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
5496
+ const catalog = parse(catalogSchema, body);
5497
+ const expectedSource = provider.manualModels.length ? "manual" : "remote";
5498
+ if (catalog.source !== expectedSource)
5499
+ throw new Fault(422, "catalog_source_mismatch", "Catalog provenance does not match the current provider configuration.");
5500
+ catalog.refreshedAt = new Date().toISOString();
5501
+ let old;
5502
+ try {
5503
+ old = await store.get("catalogs", id, db);
5504
+ } catch (error) {
5505
+ if (!(error instanceof Fault && error.status === 404))
5506
+ throw error;
5507
+ }
5508
+ const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
5509
+ return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
5166
5510
  }
5167
- if (resource === "launch-plans" && !id2 && request.method === "POST") {
5511
+ if (resource === "launch-plans" && !id && request.method === "POST") {
5168
5512
  const { profileId } = parse(z4.object({ profileId: idSchema }).strict(), body);
5169
5513
  const profile = await store.get("profiles", profileId, db);
5170
5514
  const provider = await store.get("providers", profile.providerId, db);
@@ -5177,6 +5521,9 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5177
5521
  throw new Fault(422, "catalog_missing", "Refresh the provider catalog before launching.");
5178
5522
  throw e;
5179
5523
  }
5524
+ const stored = catalog;
5525
+ if (stored.providerVersion !== undefined && stored.providerVersion !== provider.version || stored.providerFingerprint !== undefined && stored.providerFingerprint !== providerCatalogFingerprint(provider))
5526
+ throw new Fault(409, "catalog_provider_changed", "Catalog metadata belongs to an older provider configuration; refresh locally before launching.");
5180
5527
  const selected = catalog.models.find((m) => m.id === profile.model);
5181
5528
  if (!selected)
5182
5529
  throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
@@ -5194,7 +5541,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5194
5541
  warnings.push("Catalog snapshot is older than five minutes; refresh before launching.");
5195
5542
  return { profile, provider, catalog, warnings, planToken: snapshot(profile, provider, catalog) };
5196
5543
  }
5197
- if (resource === "runs" && !id2 && request.method === "POST") {
5544
+ if (resource === "runs" && !id && request.method === "POST") {
5198
5545
  if (body?.modelPolicyVersion !== 1)
5199
5546
  throw new Fault(409, "launcher_upgrade_required", "This API requires a launcher with automatic model policy version 1; upgrade the Switcher CLI/SDK.");
5200
5547
  const input = parse(runInputSchema, body);
@@ -5219,16 +5566,16 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5219
5566
  compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
5220
5567
  return store.put("runs", { ...input, modelPolicy: profile.modelPolicy, providerId: provider.id, providerVersion: provider.version, profileVersion: profile.version, id: crypto.randomUUID(), status: "running", startedAt: new Date().toISOString() }, undefined, db);
5221
5568
  }
5222
- if (resource === "runs" && id2 && request.method === "PATCH" && parts.length === 3) {
5569
+ if (resource === "runs" && id && request.method === "PATCH" && parts.length === 3) {
5223
5570
  const input = parse(runUpdateSchema, body);
5224
- const run = await store.get("runs", id2, db);
5571
+ const run = await store.get("runs", id, db);
5225
5572
  if (run.status !== "running")
5226
5573
  throw new Fault(409, "run_finished", "Run has already finished.");
5227
5574
  return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
5228
5575
  }
5229
5576
  throw new Fault(404, "not_found", "Route was not found.");
5230
5577
  });
5231
- return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
5578
+ return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id ? 201 : 200);
5232
5579
  } catch (error) {
5233
5580
  const safe = error instanceof Fault ? error : new Fault(500, "internal_error", "Request failed.");
5234
5581
  return json({ error: { code: safe.code, message: safe.message, requestId } }, safe.status);
@@ -5237,21 +5584,35 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5237
5584
  }
5238
5585
 
5239
5586
  // src/server.ts
5587
+ import { ApiKeyStore } from "@hasna/contracts/auth";
5240
5588
  async function startServer(options) {
5241
5589
  const port = options.port ?? 0;
5242
5590
  if (!Number.isInteger(port) || port < 0 || port > 65535)
5243
5591
  throw new Fault(400, "invalid_port", "Port must be an integer between 0 and 65535.");
5244
- if (options.apiKey.length < 24 || /[\r\n]/.test(options.apiKey))
5592
+ if (Boolean(options.apiKey) === Boolean(options.signingSecret))
5593
+ throw new Fault(500, "auth_config", "Configure exactly one local API token or hosted API signing secret.");
5594
+ if (options.apiKey && (options.apiKey.length < 24 || /[\r\n]/.test(options.apiKey)))
5245
5595
  throw new Fault(500, "auth_config", "Use a random operator token of at least 24 characters.");
5246
- const store = await Store.open({ databaseUrl: options.databaseUrl, sqlitePath: options.sqlitePath });
5596
+ if (options.signingSecret && (options.signingSecret.length < 32 || /[\r\n]/.test(options.signingSecret)))
5597
+ throw new Fault(500, "auth_config", "Use an API signing secret of at least 32 characters.");
5598
+ if (options.signingSecret && !options.databaseUrl)
5599
+ throw new Fault(500, "storage_config", "Hosted signed-key authentication requires PostgreSQL; configure HASNA_SWITCHER_DATABASE_URL.");
5600
+ const store = await Store.open({ databaseUrl: options.databaseUrl, sqlitePath: options.sqlitePath, migrate: !options.signingSecret });
5247
5601
  let server;
5248
5602
  try {
5603
+ const authentication = options.apiKey ?? (() => {
5604
+ const keyStore = new ApiKeyStore(store.authQueryClient());
5605
+ return { kind: "signed-api-key", signingSecret: options.signingSecret, keyStatus: keyStore.keyStatus, audit: (event) => {
5606
+ if (event.outcome === "deny")
5607
+ console.error(`api_auth deny kid=${event.kid ?? "-"} reason=${event.reason ?? "-"} ${event.method ?? "-"} ${event.path ?? "-"}`);
5608
+ } };
5609
+ })();
5249
5610
  server = Bun.serve({
5250
5611
  hostname: options.hostname ?? "127.0.0.1",
5251
5612
  port,
5252
5613
  maxRequestBodySize: 1024 * 1024,
5253
5614
  idleTimeout: 60,
5254
- fetch: createHandler(store, options.apiKey, options.providerEnv, options.resolveCredential)
5615
+ fetch: createHandler(store, authentication, options.providerEnv, options.resolveCredential)
5255
5616
  });
5256
5617
  await store.ready();
5257
5618
  } catch (error) {
@@ -5291,7 +5652,19 @@ var SWITCHER_LOCAL_OPT_IN_ENV_KEYS = ["HASNA_SWITCHER_LOCAL", "SWITCHER_LOCAL"];
5291
5652
  var SWITCHER_KEYCHAIN_ITEM = "hasna.credentials.switcher.api-key";
5292
5653
  var SWITCHER_CREDENTIALS_FILE = "~/.hasna/switcher/config/credentials";
5293
5654
  function isSwitcherLocalOptIn(env = process.env) {
5294
- return SWITCHER_LOCAL_OPT_IN_ENV_KEYS.some((key) => (env[key] ?? "").trim() !== "");
5655
+ let selected;
5656
+ for (const key of SWITCHER_LOCAL_OPT_IN_ENV_KEYS) {
5657
+ if (env[key] === undefined)
5658
+ continue;
5659
+ const value = env[key].trim().toLowerCase();
5660
+ const decision = !value || ["0", "false", "no", "off"].includes(value) ? false : ["1", "true", "yes", "on"].includes(value) ? true : undefined;
5661
+ if (decision === undefined)
5662
+ throw new Fault(400, "invalid_local_opt_in", `${key} must be one of 1, true, yes, on, 0, false, no, or off.`);
5663
+ if (selected !== undefined && selected !== decision)
5664
+ throw new Fault(400, "conflicting_local_opt_in", "HASNA_SWITCHER_LOCAL and SWITCHER_LOCAL must not disagree.");
5665
+ selected = decision;
5666
+ }
5667
+ return selected ?? false;
5295
5668
  }
5296
5669
  function switcherAuthorityEnvKeys() {
5297
5670
  const keys = clientTransportEnvKeys("switcher");
@@ -5370,15 +5743,691 @@ async function openCliRuntime(env = process.env, resolveCredential) {
5370
5743
  return { client: new SwitcherClient({ baseUrl: service.url, apiKey }), mode: "local", providerEnv, close: service.close };
5371
5744
  }
5372
5745
 
5746
+ // src/credentials.ts
5747
+ import { z as z5 } from "zod";
5748
+ import { constants as constants2 } from "fs";
5749
+ import { open, readdir, unlink, link, lstat as lstat2, access as access2, stat as stat2, realpath, readlink, rename } from "fs/promises";
5750
+ import { join as join2, isAbsolute as isAbsolute2, dirname as dirname2, parse as pathParts, resolve as resolvePath, sep } from "path";
5751
+ import { createHash as createHash4, randomUUID } from "crypto";
5752
+ import { execFile as execFile2, spawn } from "child_process";
5753
+ import { promisify as promisify2 } from "util";
5754
+ import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
5755
+ var execute2 = promisify2(execFile2);
5756
+ var reference = z5.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
5757
+ var item = z5.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
5758
+ var vaultKeySchema = z5.string().max(500).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*)*$/, "Use a vault key path, not an option or secret value");
5759
+ var keychain = z5.object({ kind: z5.literal("keychain"), service: item, account: item }).strict();
5760
+ var credentialTier = z5.enum(["argument", "override", "pointer", "profile", "keychain", "disk", "env"]);
5761
+ var operator = z5.discriminatedUnion("kind", [
5762
+ z5.object({ kind: z5.literal("contracts"), expectedSource: item.optional(), expectedTier: credentialTier.optional() }).strict(),
5763
+ z5.object({ kind: z5.literal("env") }).strict(),
5764
+ z5.object({ kind: z5.literal("keychain"), account: item.refine((value) => value.trim().length > 0 && value === value.trim(), "Vault account must be nonblank without surrounding whitespace") }).strict()
5765
+ ]);
5766
+ var origin = z5.string().transform((value) => new URL(endpoint(value)).origin);
5767
+ var credentialBindingSchema = z5.object({
5768
+ schema: z5.literal(1),
5769
+ credentialEnv: reference,
5770
+ origins: z5.array(origin).min(1).max(30),
5771
+ requireProviderAuthentication: z5.literal(true).optional(),
5772
+ source: z5.discriminatedUnion("kind", [keychain, z5.object({
5773
+ kind: z5.literal("vault"),
5774
+ key: vaultKeySchema,
5775
+ url: z5.string().max(2000).transform(endpoint).optional(),
5776
+ executable: z5.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute2, "Secrets executable must be an absolute path"),
5777
+ operator
5778
+ }).strict()])
5779
+ }).strict().superRefine((binding, ctx) => {
5780
+ if (binding.source.kind === "vault" && binding.source.operator.kind !== "contracts" && !binding.source.url)
5781
+ ctx.addIssue({ code: "custom", path: ["source", "url"], message: "An explicit env or Keychain operator binding requires a vault URL." });
5782
+ if (binding.source.kind === "vault" && binding.source.operator.kind === "contracts" && Boolean(binding.source.operator.expectedSource) !== Boolean(binding.source.operator.expectedTier))
5783
+ ctx.addIssue({ code: "custom", path: ["source", "operator"], message: "A pinned Contracts operator requires both expectedSource and expectedTier." });
5784
+ });
5785
+ var fingerprint = (binding) => createHash4("sha256").update(JSON.stringify(binding)).digest("hex");
5786
+
5787
+ class CredentialBindings {
5788
+ env;
5789
+ directory;
5790
+ constructor(env = process.env) {
5791
+ this.env = env;
5792
+ this.directory = join2(switcherHome(env), "config", "credential-bindings");
5793
+ }
5794
+ path(name) {
5795
+ return join2(this.directory, parse(reference, name) + ".json");
5796
+ }
5797
+ async readableDirectory() {
5798
+ for (const path of [switcherHome(this.env), join2(switcherHome(this.env), "config"), this.directory]) {
5799
+ let info;
5800
+ try {
5801
+ info = await lstat2(path);
5802
+ } catch (error) {
5803
+ if (error.code === "ENOENT")
5804
+ return false;
5805
+ throw error;
5806
+ }
5807
+ if (!info.isDirectory() || info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid?.()))
5808
+ throw new Fault(500, "credential_binding_permissions", "Credential binding directories must be real, owner-only directories (mode 0700).");
5809
+ }
5810
+ return true;
5811
+ }
5812
+ async get(name) {
5813
+ const path = this.path(name);
5814
+ if (!await this.readableDirectory())
5815
+ return;
5816
+ let file;
5817
+ try {
5818
+ file = await open(path, constants2.O_RDONLY | constants2.O_NOFOLLOW | constants2.O_NONBLOCK);
5819
+ } catch (error) {
5820
+ if (error.code === "ENOENT")
5821
+ return;
5822
+ throw new Fault(500, "credential_binding_unreadable", "Cannot safely open the local credential binding.");
5823
+ }
5824
+ try {
5825
+ const info = await file.stat();
5826
+ if (!info.isFile() || info.size > 32768 || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid?.()))
5827
+ throw new Fault(500, "credential_binding_permissions", "Credential binding must be an owner-only regular file (mode 0600).");
5828
+ let value;
5829
+ try {
5830
+ value = JSON.parse(await file.readFile("utf8"));
5831
+ } catch {
5832
+ throw new Fault(500, "credential_binding_invalid", "Credential binding must contain valid JSON.");
5833
+ }
5834
+ const binding = parse(credentialBindingSchema, value);
5835
+ if (binding.credentialEnv !== name)
5836
+ throw new Fault(500, "credential_binding_invalid", "Credential binding reference does not match its filename.");
5837
+ return binding;
5838
+ } finally {
5839
+ await file.close();
5840
+ }
5841
+ }
5842
+ async list() {
5843
+ if (!await this.readableDirectory())
5844
+ return [];
5845
+ let entries;
5846
+ try {
5847
+ entries = await readdir(this.directory);
5848
+ } catch (error) {
5849
+ if (error.code === "ENOENT")
5850
+ return [];
5851
+ throw error;
5852
+ }
5853
+ const result = [];
5854
+ for (const name of entries.sort())
5855
+ if (/^SWITCHER_PROVIDER_[A-Z0-9_]+\.json$/.test(name)) {
5856
+ const binding = await this.get(name.slice(0, -5));
5857
+ if (binding)
5858
+ result.push(binding);
5859
+ }
5860
+ return result;
5861
+ }
5862
+ async bind(input) {
5863
+ const binding = parse(credentialBindingSchema, input);
5864
+ if (binding.source.kind === "vault")
5865
+ await validateVaultExecutable(binding.source.executable);
5866
+ await privateDirectory(switcherHome(this.env));
5867
+ await privateDirectory(join2(switcherHome(this.env), "config"));
5868
+ await privateDirectory(this.directory);
5869
+ const temporary = join2(this.directory, `.binding-${randomUUID()}`);
5870
+ const file = await open(temporary, "wx", 384);
5871
+ try {
5872
+ await file.writeFile(JSON.stringify(binding, null, 2) + `
5873
+ `);
5874
+ await file.sync();
5875
+ try {
5876
+ await link(temporary, this.path(binding.credentialEnv));
5877
+ } catch (error) {
5878
+ if (error.code !== "EEXIST")
5879
+ throw error;
5880
+ const existing = await this.get(binding.credentialEnv);
5881
+ if (existing && fingerprint(existing) === fingerprint(binding))
5882
+ return existing;
5883
+ throw new Fault(409, "credential_binding_exists", "A different binding already exists. Remove it explicitly before binding another credential account.");
5884
+ }
5885
+ } finally {
5886
+ await file.close();
5887
+ await unlink(temporary);
5888
+ }
5889
+ return binding;
5890
+ }
5891
+ async remove(name) {
5892
+ const binding = await this.get(name);
5893
+ if (!binding)
5894
+ throw new Fault(404, "credential_binding_missing", "No local credential binding exists for this reference.");
5895
+ await unlink(this.path(name));
5896
+ return { removed: name };
5897
+ }
5898
+ }
5899
+ async function inspectVaultExecutable(path, permitWritableFile = false) {
5900
+ let info, resolved;
5901
+ try {
5902
+ resolved = await realpath(path);
5903
+ await access2(resolved, constants2.X_OK);
5904
+ info = await stat2(resolved);
5905
+ if (!info.isFile())
5906
+ throw new Error;
5907
+ } catch {
5908
+ throw new Fault(422, "vault_exec_unavailable", "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.");
5909
+ }
5910
+ if (process.platform !== "win32" && (!permitWritableFile && info.mode & 18 || info.uid !== 0 && info.uid !== process.getuid?.()))
5911
+ 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.");
5912
+ if (process.platform !== "win32") {
5913
+ const seen = new Set;
5914
+ const inspect = async (candidate) => {
5915
+ let prefix = pathParts(candidate).root;
5916
+ for (const part of candidate.slice(prefix.length).split(sep)) {
5917
+ if (!part)
5918
+ continue;
5919
+ prefix = join2(prefix, part);
5920
+ if (seen.has(prefix))
5921
+ continue;
5922
+ seen.add(prefix);
5923
+ if (seen.size > 256)
5924
+ throw new Fault(422, "vault_exec_permissions", "The secrets executable path has too many symlink components.");
5925
+ const entry = await lstat2(prefix);
5926
+ const permittedFile = permitWritableFile && prefix === resolved && entry.isFile();
5927
+ if (entry.uid !== 0 && entry.uid !== process.getuid?.() || !entry.isSymbolicLink() && !permittedFile && entry.mode & 18)
5928
+ 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.");
5929
+ if (entry.isSymbolicLink())
5930
+ await inspect(resolvePath(dirname2(prefix), await readlink(prefix)));
5931
+ }
5932
+ };
5933
+ try {
5934
+ await inspect(path);
5935
+ await inspect(resolved);
5936
+ } catch (error) {
5937
+ if (error instanceof Fault)
5938
+ throw error;
5939
+ throw new Fault(422, "vault_exec_unavailable", "The secrets executable path changed or could not be verified. Retry with a trusted installation.");
5940
+ }
5941
+ }
5942
+ return resolved;
5943
+ }
5944
+ async function validateVaultExecutable(path) {
5945
+ return inspectVaultExecutable(path);
5946
+ }
5947
+ async function readKeychain(source) {
5948
+ if (process.platform !== "darwin")
5949
+ throw new Fault(422, "keychain_unavailable", "This binding requires macOS Keychain. Use a supported vault binding or runtime environment on this station.");
5950
+ let stdout;
5951
+ try {
5952
+ ({ stdout } = await execute2("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 }));
5953
+ } catch (error) {
5954
+ const status = error.code;
5955
+ if (status === 44)
5956
+ throw new Fault(422, "keychain_item_missing", "The configured Keychain item does not exist for that service and account; no alternate credential was selected.");
5957
+ throw new Fault(422, "keychain_unavailable", `The configured Keychain item could not be read (security exited ${typeof status === "number" ? status : "without a status"}); it is locked or inaccessible. No alternate credential was selected.`);
5958
+ }
5959
+ const value = stdout.replace(/\r?\n$/, "");
5960
+ if (!value || /[\x00-\x1f\x7f]/.test(value))
5961
+ throw new Fault(422, "keychain_item_invalid", "The configured Keychain item holds an unusable value; no alternate credential was selected.");
5962
+ return value;
5963
+ }
5964
+
5965
+ class CredentialResolver {
5966
+ env;
5967
+ keychainRead;
5968
+ bindings;
5969
+ constructor(env = process.env, keychainRead = readKeychain) {
5970
+ this.env = env;
5971
+ this.keychainRead = keychainRead;
5972
+ this.bindings = new CredentialBindings(env);
5973
+ }
5974
+ async resolve(provider) {
5975
+ if (!provider.credentialEnv)
5976
+ return;
5977
+ const binding = await this.bindings.get(provider.credentialEnv);
5978
+ if (!binding)
5979
+ return providerCredential(provider, this.env);
5980
+ if (!binding.origins.includes(new URL(provider.baseUrl).origin))
5981
+ throw new Fault(422, "credential_authority", "The local credential binding does not authorize this provider origin. Update the binding explicitly; no key was sent.");
5982
+ if (binding.source.kind === "keychain")
5983
+ return this.keychainRead(binding.source);
5984
+ return fetchVaultCredential(binding, this.env);
5985
+ }
5986
+ async check(name) {
5987
+ const binding = await this.bindings.get(name);
5988
+ if (!binding)
5989
+ throw new Fault(404, "credential_binding_missing", "No local credential binding exists for this reference.");
5990
+ if (binding.source.kind === "vault") {
5991
+ const output = await runVaultCommand(binding, ["get", binding.source.key, "--check"], this.env, {}, {
5992
+ captureBytes: 4096,
5993
+ oversizeCode: "vault_check_failed",
5994
+ oversizeMessage: "The secrets CLI returned an oversized check result."
5995
+ });
5996
+ const match = /^key=\S+ length=(\d+) sha256=([a-f0-9]{64})\s*$/.exec(output);
5997
+ if (!match)
5998
+ throw new Fault(422, "vault_check_failed", "The secrets CLI did not return a supported credential check result.");
5999
+ return { credentialEnv: name, source: "vault", available: true, length: Number(match[1]), sha256: match[2], providerAuthentication: "not tested" };
6000
+ }
6001
+ const value = await this.keychainRead(binding.source);
6002
+ return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash4("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
6003
+ }
6004
+ }
6005
+ var DELIVERY_URL = "SWITCHER_CREDENTIAL_DELIVERY_URL";
6006
+ var DELIVERY_NONCE = "SWITCHER_CREDENTIAL_DELIVERY_NONCE";
6007
+ var DELIVERY_VALUE = "SWITCHER_CREDENTIAL_DELIVERY_VALUE";
6008
+
6009
+ class CredentialInterrupted extends CommandInterrupted {
6010
+ constructor(exitCode) {
6011
+ super(exitCode, "Credential lookup was interrupted; no harness was started.");
6012
+ }
6013
+ }
6014
+ async function resolveVaultOperatorEnvironment(binding, env, options = {}) {
6015
+ if (binding.source.kind !== "vault")
6016
+ throw new Fault(500, "credential_resolution", "Unexpected credential source.");
6017
+ const source = binding.source;
6018
+ let credential, url = source.url;
6019
+ try {
6020
+ if (source.operator.kind === "contracts") {
6021
+ const pair = () => {
6022
+ const keys = clientTransportEnvKeys3("secrets");
6023
+ const configuredUrl = keys.apiUrlKeys.map((name) => env[name]).find((value) => value !== undefined) ?? keychainConfigValue2("secrets", env, options.keychain)?.value ?? appConfigDiskValue2("secrets", env, keys.apiUrlKeys)?.value;
6024
+ const resolution = resolveClientTransport("secrets", env, { credentials: options });
6025
+ const key = resolveCredential("secrets", env, options);
6026
+ if (key?.tier === "pointer")
6027
+ throw new Fault(422, "vault_operator_pointer", "A Secrets operator cannot bootstrap itself through HASNA_SECRETS_API_KEY_REF. Configure its operator in Keychain, canonical config/credentials, or an explicit key override.");
6028
+ if (!key?.apiKey || key.source !== resolution.apiKeySource || key.tier !== resolution.apiKeyTier)
6029
+ throw new Fault(422, "vault_operator_changed", "The vault operator changed during resolution; no credential was sent. Retry after configuration is stable.");
6030
+ const boundUrl = source.url ? toV1BaseUrl(source.url) : resolution.baseUrl;
6031
+ if (resolution.apiUrlSource !== "default" && boundUrl !== resolution.baseUrl)
6032
+ throw new Fault(422, "vault_operator_authority", "The binding vault URL conflicts with the canonical Secrets API URL; no credential was sent.");
6033
+ if (configuredUrl !== undefined && toV1BaseUrl(configuredUrl) !== resolution.baseUrl)
6034
+ throw new Fault(422, "vault_operator_changed", "The vault authority changed during resolution; no credential was sent.");
6035
+ return { key, url: configuredUrl?.trim() ?? source.url ?? boundUrl.replace(/\/v1$/, "") };
6036
+ };
6037
+ const first = pair(), second = pair();
6038
+ if (first.key.apiKey !== second.key.apiKey || first.key.source !== second.key.source || first.key.tier !== second.key.tier || first.url !== second.url)
6039
+ throw new Fault(422, "vault_operator_changed", "The vault operator or authority changed during resolution; no credential was sent. Retry after configuration is stable.");
6040
+ if (source.operator.expectedSource && (second.key.source !== source.operator.expectedSource || second.key.tier !== source.operator.expectedTier))
6041
+ throw new Fault(422, "vault_operator_changed", `The selected Secrets account/source changed from ${source.operator.expectedSource}; no alternate account was selected. Restore that source or rebind explicitly.`);
6042
+ credential = second.key;
6043
+ url = second.url;
6044
+ } else {
6045
+ credential = source.operator.kind === "keychain" ? resolveCredential("secrets", { HASNA_STATION: source.operator.account }, { keychain: { ...options.keychain, enabled: true } }) : resolveCredential("secrets", Object.fromEntries(Object.entries(env).filter(([name]) => name === "HASNA_SECRETS_API_KEY")), { keychain: { enabled: false } });
6046
+ }
6047
+ } catch (error) {
6048
+ if (error instanceof Fault)
6049
+ throw error;
6050
+ const kind = error instanceof Error ? error.name : "";
6051
+ const detail = error instanceof Error ? error.message : "";
6052
+ const reason = /keychain|security exited/i.test(detail) ? "selected Secrets Keychain source is locked or inaccessible" : kind === "CredentialFileUnsafeError" ? "unsafe canonical config/credentials file" : kind === "ClientTransportConfigurationError" ? "invalid or missing canonical API URL/key" : source.operator.kind === "keychain" ? "unavailable pinned Keychain account" : "credential selection refused by Contracts (Keychain, canonical file, profile, or environment)";
6053
+ throw new Fault(422, "vault_operator_unavailable", `Cannot resolve the Secrets vault operator: ${reason}. Check the selected source in this terminal session; no alternate account was selected.`);
6054
+ }
6055
+ if (!credential?.apiKey)
6056
+ throw new Fault(422, "vault_operator_missing", "The selected vault operator has no credential. Use a canonical Contracts binding, restore its named Keychain account, or inject HASNA_SECRETS_API_KEY for an explicit env binding.");
6057
+ const allowed = /^(PATH|HOME|USER|LOGNAME|SHELL|LANG|LC_[A-Z_]+|TMPDIR|TEMP|TMP|HASNA_HOME|HASNA_CONFIG_HOME|HASNA_SECRETS_HOME|HASNA_STATION)$/;
6058
+ const next = Object.fromEntries(Object.entries(env).filter(([name]) => allowed.test(name)));
6059
+ next.HASNA_SECRETS_API_URL = url;
6060
+ next.HASNA_SECRETS_API_KEY = credential.apiKey;
6061
+ next.HASNA_SECRETS_API_KEY_OVERRIDE = credential.apiKey;
6062
+ if (binding.source.operator.kind === "keychain")
6063
+ next.HASNA_STATION = binding.source.operator.account;
6064
+ return { environment: next, source: credential.source, tier: credential.tier, url };
6065
+ }
6066
+ async function runVaultCommand(binding, args, env, delivery = {}, options = {}) {
6067
+ if (binding.source.kind !== "vault")
6068
+ throw new Fault(500, "credential_resolution", "Unexpected credential source.");
6069
+ if (process.platform === "win32")
6070
+ throw new Fault(422, "vault_exec_unavailable", "Vault CLI bindings currently require POSIX process groups; use runtime environment injection on Windows.");
6071
+ const executable = await validateVaultExecutable(binding.source.executable);
6072
+ const operator = options.operator ?? await resolveVaultOperatorEnvironment(binding, env);
6073
+ const childEnv = { ...operator.environment, ...delivery };
6074
+ return new Promise((resolveResult, reject) => {
6075
+ const child = spawn(executable, args, { env: childEnv, stdio: ["ignore", options.captureBytes ? "pipe" : "ignore", "ignore"], detached: true, shell: false });
6076
+ let failure;
6077
+ let output = "";
6078
+ let outputBytes = 0;
6079
+ let cleaned = false;
6080
+ const kill = () => {
6081
+ if (child.pid) {
6082
+ try {
6083
+ process.kill(-child.pid, "SIGKILL");
6084
+ } catch {}
6085
+ }
6086
+ };
6087
+ const interrupt = (signal) => {
6088
+ failure = new CredentialInterrupted(signal === "SIGINT" ? 130 : 143);
6089
+ process.exitCode = signal === "SIGINT" ? 130 : 143;
6090
+ kill();
6091
+ };
6092
+ const onInt = () => interrupt("SIGINT");
6093
+ const onTerm = () => interrupt("SIGTERM");
6094
+ process.on("SIGINT", onInt);
6095
+ process.on("SIGTERM", onTerm);
6096
+ const timeout = setTimeout(() => {
6097
+ failure = new Fault(504, "vault_timeout", "Credential lookup exceeded 20 seconds; no alternate credential was selected.");
6098
+ kill();
6099
+ }, 20000);
6100
+ const cleanup = () => {
6101
+ if (cleaned)
6102
+ return;
6103
+ cleaned = true;
6104
+ clearTimeout(timeout);
6105
+ process.off("SIGINT", onInt);
6106
+ process.off("SIGTERM", onTerm);
6107
+ kill();
6108
+ };
6109
+ child.stdout?.on("data", (chunk) => {
6110
+ outputBytes += chunk.length;
6111
+ if (outputBytes > (options.captureBytes ?? 0)) {
6112
+ failure = new Fault(422, options.oversizeCode ?? "vault_check_failed", options.oversizeMessage ?? "The secrets CLI returned an oversized result.");
6113
+ kill();
6114
+ } else
6115
+ output += chunk.toString("utf8");
6116
+ });
6117
+ child.once("error", () => {
6118
+ cleanup();
6119
+ reject(new Fault(422, "vault_exec_failed", "The configured secrets CLI could not start; check its executable and permissions."));
6120
+ });
6121
+ child.once("exit", cleanup);
6122
+ child.once("close", (code) => {
6123
+ if (failure)
6124
+ reject(failure);
6125
+ else if (code !== 0)
6126
+ reject(new Fault(422, options.lookupCode ?? "vault_lookup_failed", options.lookupMessage ?? "The secrets CLI could not read the configured key. Check vault access and conflicting local vault URL settings; no alternate account was selected."));
6127
+ else
6128
+ resolveResult(output);
6129
+ });
6130
+ });
6131
+ }
6132
+ async function fetchVaultCredential(binding, env) {
6133
+ if (binding.source.kind !== "vault")
6134
+ throw new Fault(500, "credential_resolution", "Unexpected credential source.");
6135
+ const nonce = crypto.randomUUID() + crypto.randomUUID();
6136
+ let value;
6137
+ const broker = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 65536, async fetch(request) {
6138
+ if (request.method !== "POST" || new URL(request.url).pathname !== "/credential" || request.headers.get("authorization") !== `Bearer ${nonce}` || value !== undefined)
6139
+ return new Response(null, { status: 404 });
6140
+ let candidate;
6141
+ try {
6142
+ candidate = await request.json();
6143
+ } catch {
6144
+ return new Response(null, { status: 400 });
6145
+ }
6146
+ if (typeof candidate !== "string" || !candidate || candidate.length > 64000 || /[\x00-\x1f\x7f]/.test(candidate))
6147
+ return new Response(null, { status: 400 });
6148
+ value = candidate;
6149
+ return new Response(null, { status: 204 });
6150
+ } });
6151
+ try {
6152
+ await runVaultCommand(binding, ["exec", binding.source.key, "--as", DELIVERY_VALUE, "--", process.execPath, process.argv[1], "__credential-delivery"], env, {
6153
+ [DELIVERY_URL]: broker.url.origin + "/credential",
6154
+ [DELIVERY_NONCE]: nonce
6155
+ });
6156
+ if (!value)
6157
+ throw new Fault(422, "vault_delivery_failed", "The secrets CLI completed without a valid credential handoff.");
6158
+ return value;
6159
+ } finally {
6160
+ await broker.stop(true);
6161
+ }
6162
+ }
6163
+
6164
+ // src/provider-credential-onboarding.ts
6165
+ import { z as z6 } from "zod";
6166
+ import { createHash as createHash5 } from "crypto";
6167
+ import { createInterface } from "readline/promises";
6168
+ var absent = (error) => error instanceof SwitcherError && error.status === 404;
6169
+ var secretMetadataSchema = z6.object({
6170
+ key: vaultKeySchema,
6171
+ type: z6.enum(["api_key", "password", "token", "credential", "other"]),
6172
+ label: z6.string().max(1000).nullable().optional(),
6173
+ expires_at: z6.string().max(200).nullable().optional(),
6174
+ created_at: z6.string().max(200),
6175
+ updated_at: z6.string().max(200)
6176
+ }).strict();
6177
+ var cleanDisplay = (value) => value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, "").slice(0, 500);
6178
+ var credentialOrigins = (provider) => {
6179
+ const origins = new Set([new URL(provider.baseUrl).origin]);
6180
+ const catalogAuthStyle = provider.catalogAuthStyle ?? provider.authStyle ?? "bearer";
6181
+ const catalogCredentialEnv = provider.catalogCredentialEnv ?? provider.credentialEnv;
6182
+ if (catalogAuthStyle !== "none" && provider.catalogBaseUrl && catalogCredentialEnv === provider.credentialEnv)
6183
+ origins.add(new URL(provider.catalogBaseUrl).origin);
6184
+ return [...origins];
6185
+ };
6186
+ var providerCredentialSetupCommand = (provider) => {
6187
+ if (!provider.credentialEnv)
6188
+ return "";
6189
+ const origins = credentialOrigins(provider).map((value) => ` --origin ${value}`).join("");
6190
+ return `switcher credentials bind ${provider.credentialEnv}${origins} --vault-key <vault-key>`;
6191
+ };
6192
+ var searchTerms = (provider) => {
6193
+ const fromReference = provider.credentialEnv?.replace(/^SWITCHER_PROVIDER_/, "").replace(/_API_KEY$/, "").toLowerCase().replace(/_/g, "-");
6194
+ const raw = [fromReference, provider.name.toLowerCase().replace(/[^a-z0-9]+/g, "-"), provider.id.toLowerCase()];
6195
+ return [...new Set(raw.flatMap((value) => value ? [value, ...value.split("-")] : []).filter((value) => value.length >= 3 && !new Set(["api", "key", "provider", "responses", "response", "messages", "message", "chat", "custom"]).has(value)))].slice(0, 4);
6196
+ };
6197
+ async function discoverVaultReferences(provider, env = process.env, vaultExecutable = Bun.which("secrets") ?? "") {
6198
+ if (!provider.credentialEnv)
6199
+ return [];
6200
+ if (!vaultExecutable)
6201
+ throw new Fault(422, "vault_exec_unavailable", "Hasna Secrets is not installed in this launcher process. Install it or run the exact credentials bind command with --vault-cli /absolute/path.");
6202
+ await validateVaultExecutable(vaultExecutable);
6203
+ const source = { kind: "vault", key: "switcher/provider-credential-discovery", executable: vaultExecutable, operator: { kind: "contracts" } };
6204
+ const provisional = parse(credentialBindingSchema, { schema: 1, credentialEnv: provider.credentialEnv, origins: credentialOrigins(provider), source });
6205
+ const operator = await resolveVaultOperatorEnvironment(provisional, env);
6206
+ const entries = new Map;
6207
+ for (const query of searchTerms(provider)) {
6208
+ const output = await runVaultCommand(provisional, ["search", query, "--json"], env, {}, {
6209
+ captureBytes: 256 * 1024,
6210
+ oversizeCode: "vault_metadata_oversized",
6211
+ oversizeMessage: "Secrets returned too much credential metadata; narrow the vault naming or bind an exact key explicitly.",
6212
+ lookupCode: "vault_search_failed",
6213
+ lookupMessage: "Hasna Secrets could not search credential metadata. Check the selected vault/Keychain source; no alternate account was selected.",
6214
+ operator
6215
+ });
6216
+ let parsed;
6217
+ try {
6218
+ parsed = JSON.parse(output);
6219
+ } catch {
6220
+ throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned invalid credential metadata JSON.");
6221
+ }
6222
+ const result = secretMetadataSchema.array().max(1000).safeParse(parsed);
6223
+ if (!result.success)
6224
+ throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned an unsupported credential metadata shape.");
6225
+ for (const entry of result.data)
6226
+ entries.set(entry.key, entry);
6227
+ if (entries.size > 256)
6228
+ throw new Fault(422, "credential_matches_too_many", "More than 256 credential references matched. Bind an exact vault key explicitly.");
6229
+ }
6230
+ return [...entries.values()].sort((a, b) => a.key.localeCompare(b.key)).map((entry) => ({ account: operator.source, key: entry.key, url: operator.url, executable: vaultExecutable, operator: { kind: "contracts", expectedSource: operator.source, expectedTier: operator.tier } }));
6231
+ }
6232
+ async function selectVaultReference({ provider, matches }) {
6233
+ if (!process.stdin.isTTY || !process.stderr.isTTY)
6234
+ return;
6235
+ console.error(`Secrets account/source: ${cleanDisplay(matches[0]?.account ?? "unknown")}`);
6236
+ console.error(`Credential references matching ${cleanDisplay(provider.name)}:`);
6237
+ matches.forEach((match, index) => console.error(` ${index + 1}. ${cleanDisplay(match.key)}${match.account === matches[0]?.account ? "" : ` (account/source: ${cleanDisplay(match.account)})`}`));
6238
+ const reader = createInterface({ input: process.stdin, output: process.stderr });
6239
+ const cancellation = new AbortController;
6240
+ const cancel = () => cancellation.abort(new CommandInterrupted(130, "Credential setup was cancelled; no binding was saved and no harness was started."));
6241
+ const terminate = () => cancellation.abort(new CommandInterrupted(143, "Credential setup was interrupted; no binding was saved and no harness was started."));
6242
+ reader.on("SIGINT", cancel);
6243
+ reader.on("close", cancel);
6244
+ process.on("SIGINT", cancel);
6245
+ process.on("SIGTERM", terminate);
6246
+ try {
6247
+ for (;; ) {
6248
+ const answer = (await reader.question("Credential number (Ctrl-C cancels): ", { signal: cancellation.signal }).catch((error) => {
6249
+ throw cancellation.signal.aborted ? cancellation.signal.reason : error;
6250
+ })).trim();
6251
+ if (!answer || /^(q|quit|cancel)$/i.test(answer))
6252
+ return;
6253
+ if (/^[1-9]\d*$/.test(answer) && matches[Number(answer) - 1])
6254
+ return matches[Number(answer) - 1];
6255
+ console.error(`Enter a number from 1 to ${matches.length}, or q to cancel.`);
6256
+ }
6257
+ } finally {
6258
+ reader.off("SIGINT", cancel);
6259
+ reader.off("close", cancel);
6260
+ process.off("SIGINT", cancel);
6261
+ process.off("SIGTERM", terminate);
6262
+ reader.close();
6263
+ }
6264
+ }
6265
+ function authenticationProbe(provider) {
6266
+ if (provider.credentialCheck) {
6267
+ const root = provider.baseUrl.endsWith("/") ? provider.baseUrl : `${provider.baseUrl}/`;
6268
+ const url = new URL(provider.credentialCheck.path, root);
6269
+ if (url.origin !== new URL(provider.baseUrl).origin || !url.href.startsWith(root))
6270
+ throw new Fault(422, "provider_auth_check_invalid", "Provider authentication check must remain below its inference endpoint.");
6271
+ return { url, method: provider.credentialCheck.method ?? "GET", authStyle: provider.authStyle ?? "bearer" };
6272
+ }
6273
+ const base = new URL(provider.baseUrl);
6274
+ if (provider.credentialEnv === "SWITCHER_PROVIDER_OPENROUTER" && base.origin === "https://openrouter.ai" && base.pathname.replace(/\/+$/, "") === "/api/v1")
6275
+ return { url: new URL("https://openrouter.ai/api/v1/key"), method: "GET", authStyle: provider.authStyle ?? "bearer" };
6276
+ return;
6277
+ }
6278
+ async function verifyProviderAuthentication({ provider, credential, fetch: fetchImpl = fetch }) {
6279
+ const probe = authenticationProbe(provider);
6280
+ if (!probe)
6281
+ return { authenticated: false, unsupported: true };
6282
+ const [header, value] = authHeader(probe.authStyle, credential);
6283
+ const headers = { accept: "application/json", "user-agent": "hasna-switcher/credential-check" };
6284
+ headers[provider.catalogFormat === "gemini" && header === "x-api-key" ? "x-goog-api-key" : header] = value;
6285
+ if (provider.protocol === "anthropic-messages" && probe.url.hostname !== "openrouter.ai")
6286
+ headers["anthropic-version"] = "2023-06-01";
6287
+ let response;
6288
+ try {
6289
+ response = await fetchImpl(probe.url, { method: probe.method, headers, redirect: "manual", signal: AbortSignal.timeout(1e4) });
6290
+ } catch {
6291
+ throw new Fault(502, "provider_auth_unavailable", "Provider authentication check could not reach the configured authority. Retry without changing accounts.");
6292
+ }
6293
+ const status = response.status;
6294
+ await response.body?.cancel().catch(() => {});
6295
+ if (status >= 200 && status < 300)
6296
+ return { authenticated: true, status };
6297
+ if (status === 401 || status === 403)
6298
+ return { authenticated: false, status };
6299
+ if (status >= 300 && status < 400)
6300
+ throw new Fault(502, "provider_auth_unavailable", "Provider authentication check returned a redirect; credentials were not forwarded.");
6301
+ throw new Fault(502, "provider_auth_unavailable", `Provider authentication check returned HTTP ${status}; the selected credential was not replaced.`);
6302
+ }
6303
+ function providerCredentialFingerprint(provider) {
6304
+ return createHash5("sha256").update(JSON.stringify({
6305
+ id: provider.id,
6306
+ baseUrl: provider.baseUrl,
6307
+ protocol: provider.protocol,
6308
+ authStyle: provider.authStyle ?? "bearer",
6309
+ credentialEnv: provider.credentialEnv ?? null,
6310
+ credentialCheck: provider.credentialCheck ?? null
6311
+ })).digest("hex");
6312
+ }
6313
+ function preparedProviderCredential(provider, credential, fields) {
6314
+ const providerFingerprint = providerCredentialFingerprint(provider);
6315
+ const prepared = { ...fields, providerFingerprint };
6316
+ Object.defineProperty(prepared, "resolveCredential", { enumerable: false, configurable: false, writable: false, value: async (candidate) => {
6317
+ if (providerCredentialFingerprint(candidate) !== providerFingerprint)
6318
+ throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
6319
+ return credential;
6320
+ } });
6321
+ return Object.freeze(prepared);
6322
+ }
6323
+ async function ensureProviderCredential(provider, options = {}) {
6324
+ if (!provider.credentialEnv)
6325
+ return preparedProviderCredential(provider, undefined, { source: "not-required", configured: false, verified: false });
6326
+ const resolver = options.resolver ?? new CredentialResolver(options.env ?? process.env);
6327
+ const existing = await resolver.bindings.get(provider.credentialEnv);
6328
+ let credential = await resolver.resolve(provider);
6329
+ if (existing && !credential)
6330
+ throw new Fault(422, "credential_binding_unavailable", "The selected credential binding did not provide a usable value; no alternate account was selected.");
6331
+ let configured = false;
6332
+ if (!credential) {
6333
+ if (!(options.interactive ?? (process.stdin.isTTY && process.stderr.isTTY)))
6334
+ throw new Fault(400, "credential_setup_required", `Provider credential setup is required. Run: ${providerCredentialSetupCommand(provider)}. Or provide ${provider.credentialEnv} in this launch process.`);
6335
+ const discover = options.discoverVaultReferences ?? ((request) => discoverVaultReferences(request.provider, options.env ?? process.env, options.vaultExecutable));
6336
+ let matches;
6337
+ try {
6338
+ matches = await discover({ provider, credentialEnv: provider.credentialEnv });
6339
+ } catch (error) {
6340
+ if (error instanceof Fault && error.code === "vault_exec_unavailable")
6341
+ throw new Fault(error.status, error.code, `${error.message} Run: ${providerCredentialSetupCommand(provider)} --vault-cli /absolute/path/to/secrets.`);
6342
+ throw error;
6343
+ }
6344
+ if (!matches.length)
6345
+ throw new Fault(404, "credential_match_missing", `No matching Hasna Secrets credential reference was found for ${provider.name}. Run: ${providerCredentialSetupCommand(provider)}.`);
6346
+ const select = options.selectVaultReference ?? selectVaultReference;
6347
+ const candidate = await select({ provider, matches });
6348
+ if (!candidate)
6349
+ throw new CommandInterrupted(130, "Credential setup was cancelled; no binding was saved and no harness was started.");
6350
+ const selected = matches.find((match) => match.account === candidate.account && match.key === candidate.key && match.executable === candidate.executable && JSON.stringify(match.operator) === JSON.stringify(candidate.operator));
6351
+ if (!selected)
6352
+ throw new Fault(400, "credential_selection_invalid", "Choose one of the displayed credential references.");
6353
+ const source = { kind: "vault", key: selected.key, ...selected.url ? { url: selected.url } : {}, executable: selected.executable, operator: selected.operator };
6354
+ await resolver.bindings.bind(parse(credentialBindingSchema, { schema: 1, credentialEnv: provider.credentialEnv, origins: credentialOrigins(provider), requireProviderAuthentication: true, source }));
6355
+ configured = true;
6356
+ credential = await resolver.resolve(provider);
6357
+ if (!credential)
6358
+ throw new Fault(422, "vault_delivery_failed", "The selected credential reference did not provide a usable value; no alternate account was selected.");
6359
+ }
6360
+ const verify = options.verifyProviderAuthentication ?? ((request) => verifyProviderAuthentication(request));
6361
+ const result = await verify({ provider, credential });
6362
+ if (result.unsupported) {
6363
+ if (configured || existing?.requireProviderAuthentication)
6364
+ throw new Fault(422, "provider_auth_check_unsupported", `This provider has no configured non-inference authentication check.${configured ? " The selected binding was preserved." : ""} Configure credentialCheck before launch; no unverified credential was sent.`);
6365
+ return preparedProviderCredential(provider, credential, { source: existing ? "binding" : "environment", configured, verified: false });
6366
+ }
6367
+ if (!result.authenticated)
6368
+ throw new Fault(401, "provider_credential_rejected", `The provider rejected the selected credential${result.status ? ` with HTTP ${result.status}` : ""}. No alternate account was selected.${existing || configured ? ` To choose a different reference, run: switcher credentials remove ${provider.credentialEnv}.` : ""}`);
6369
+ return preparedProviderCredential(provider, credential, { source: existing || configured ? "binding" : "environment", configured, verified: true });
6370
+ }
6371
+ function catalogRequiresCredential(provider) {
6372
+ if (provider.manualModels.length)
6373
+ return false;
6374
+ return (provider.catalogAuthStyle ?? provider.authStyle) !== "none" && Boolean(provider.catalogCredentialEnv ?? provider.credentialEnv);
6375
+ }
6376
+ async function launchCatalog(client, provider, dryRun = false, options = {}) {
6377
+ if (!dryRun && options.clientSide) {
6378
+ const origins = credentialOrigins(provider);
6379
+ const resolve = async (candidate) => {
6380
+ if (options.credential && candidate.credentialEnv === provider.credentialEnv && origins.includes(new URL(candidate.baseUrl).origin))
6381
+ return options.credential;
6382
+ return options.resolveCredential?.(candidate);
6383
+ };
6384
+ const catalog = await discover(provider, {}, resolve);
6385
+ return client.saveCatalog(provider.id, provider.version, catalog);
6386
+ }
6387
+ if (!dryRun || !catalogRequiresCredential(provider))
6388
+ return client.refreshModels(provider.id);
6389
+ const models = [];
6390
+ let offset = 0, refreshedAt, source, total;
6391
+ for (let pageNumber = 0;pageNumber < 10; pageNumber++) {
6392
+ let page;
6393
+ try {
6394
+ page = await client.listModels(provider.id, { limit: 1000, offset });
6395
+ } catch (error) {
6396
+ if (absent(error))
6397
+ throw new Fault(400, "dry_run_catalog_unavailable", `Dry-run will not retrieve provider credentials. Refresh ${provider.id} explicitly with switcher models ${provider.id} --refresh, then rerun the plan.`);
6398
+ throw error;
6399
+ }
6400
+ if (total === undefined) {
6401
+ total = page.total;
6402
+ refreshedAt = page.refreshedAt;
6403
+ source = page.source;
6404
+ } else if (total !== page.total || refreshedAt !== page.refreshedAt || source !== page.source)
6405
+ throw new Fault(409, "catalog_changed", "The cached catalog changed while the dry-run plan was being read; retry.");
6406
+ for (const row of page.data) {
6407
+ const { codingEligible: _codingEligible, expired: _expired, ...model } = row;
6408
+ models.push(model);
6409
+ }
6410
+ offset += page.data.length;
6411
+ if (offset >= page.total)
6412
+ break;
6413
+ if (!page.data.length)
6414
+ throw new Fault(502, "invalid_catalog", "The cached catalog page did not advance.");
6415
+ }
6416
+ if (total === undefined || models.length !== total || !refreshedAt || !source)
6417
+ throw new Fault(502, "invalid_catalog", "The cached catalog exceeds the bounded dry-run reader or is incomplete.");
6418
+ return { models, refreshedAt, source };
6419
+ }
6420
+
5373
6421
  // src/mcp.ts
5374
6422
  var server = new McpServer({ name: "switcher", version: VERSION });
5375
6423
  var runtime;
6424
+ var credentials = new CredentialResolver;
5376
6425
  var clientFromEnv2 = () => {
5377
6426
  if (!runtime)
5378
6427
  throw new Fault(503, "unavailable", "Switcher API runtime is not open.");
5379
6428
  return runtime.client;
5380
6429
  };
5381
- var page = { limit: z5.number().int().min(1).max(1000).optional(), offset: z5.number().int().nonnegative().optional(), search: z5.string().optional() };
6430
+ var page = { limit: z7.number().int().min(1).max(1000).optional(), offset: z7.number().int().nonnegative().optional(), search: z7.string().optional() };
5382
6431
  function tool(name, description, schema, run) {
5383
6432
  server.tool(name, description, schema, async (input) => {
5384
6433
  try {
@@ -5389,33 +6438,40 @@ function tool(name, description, schema, run) {
5389
6438
  });
5390
6439
  }
5391
6440
  tool("providers_list", "List provider profiles.", page, (p) => clientFromEnv2().listProviders(p));
5392
- tool("providers_get", "Get a provider.", { id: z5.string() }, (p) => clientFromEnv2().getProvider(p.id));
6441
+ tool("providers_get", "Get a provider.", { id: z7.string() }, (p) => clientFromEnv2().getProvider(p.id));
5393
6442
  tool("providers_create", "Create a provider using credential environment references only.", providerInputSchema.innerType().shape, (p) => clientFromEnv2().createProvider(p));
5394
- tool("providers_update", "Replace a provider at its current version.", { provider: providerInputSchema, version: z5.number().int() }, (p) => clientFromEnv2().updateProvider(p.provider, p.version));
5395
- tool("providers_delete", "Delete an unreferenced provider.", { id: z5.string(), version: z5.number().int() }, (p) => clientFromEnv2().deleteProvider(p.id, p.version));
5396
- tool("models_list", "List catalog with capability information.", { id: z5.string(), ...page }, (p) => {
5397
- const { id: id2, ...rest } = p;
5398
- return clientFromEnv2().listModels(id2, rest);
6443
+ tool("providers_update", "Replace a provider at its current version.", { provider: providerInputSchema, version: z7.number().int() }, (p) => clientFromEnv2().updateProvider(p.provider, p.version));
6444
+ tool("providers_delete", "Delete an unreferenced provider.", { id: z7.string(), version: z7.number().int() }, (p) => clientFromEnv2().deleteProvider(p.id, p.version));
6445
+ tool("models_list", "List catalog with capability information.", { id: z7.string(), ...page }, (p) => {
6446
+ const { id, ...rest } = p;
6447
+ return clientFromEnv2().listModels(id, rest);
6448
+ });
6449
+ tool("models_add", "Add saved model metadata; discovery stays active unless the provider uses a manual catalog.", { providerId: z7.string(), model: modelSchema }, (p) => clientFromEnv2().addModel(p.providerId, p.model));
6450
+ tool("models_update", "Replace all saved metadata for a configured model.", { providerId: z7.string(), model: modelSchema }, (p) => clientFromEnv2().updateModel(p.providerId, p.model));
6451
+ tool("models_remove", "Remove saved model metadata; upstream catalog entries remain.", { providerId: z7.string(), modelId: modelSchema.shape.id }, (p) => clientFromEnv2().removeModel(p.providerId, p.modelId));
6452
+ tool("models_refresh", "Discover provider models.", { id: z7.string() }, async (p) => {
6453
+ const client = clientFromEnv2(), provider = await client.getProvider(p.id);
6454
+ if (runtime?.mode !== "remote")
6455
+ return client.refreshModels(provider.id);
6456
+ const prepared = await ensureProviderCredential(provider, { interactive: false, resolver: credentials });
6457
+ const credential = await prepared.resolveCredential(provider);
6458
+ return launchCatalog(client, provider, false, { clientSide: true, credential, resolveCredential: (candidate) => credentials.resolve(candidate) });
5399
6459
  });
5400
- tool("models_add", "Add saved model metadata; discovery stays active unless the provider uses a manual catalog.", { providerId: z5.string(), model: modelSchema }, (p) => clientFromEnv2().addModel(p.providerId, p.model));
5401
- tool("models_update", "Replace all saved metadata for a configured model.", { providerId: z5.string(), model: modelSchema }, (p) => clientFromEnv2().updateModel(p.providerId, p.model));
5402
- tool("models_remove", "Remove saved model metadata; upstream catalog entries remain.", { providerId: z5.string(), modelId: modelSchema.shape.id }, (p) => clientFromEnv2().removeModel(p.providerId, p.modelId));
5403
- tool("models_refresh", "Discover provider models.", { id: z5.string() }, (p) => clientFromEnv2().refreshModels(p.id));
5404
6460
  tool("profiles_list", "List harness launch profiles.", page, (p) => clientFromEnv2().listProfiles(p));
5405
- tool("profiles_get", "Get a harness profile.", { id: z5.string() }, (p) => clientFromEnv2().getProfile(p.id));
6461
+ tool("profiles_get", "Get a harness profile.", { id: z7.string() }, (p) => clientFromEnv2().getProfile(p.id));
5406
6462
  tool("profiles_create", "Create a harness launch profile.", profileInputSchema.shape, (p) => clientFromEnv2().createProfile(p));
5407
- tool("profiles_update", "Replace a harness profile at its version.", { profile: profileInputSchema, version: z5.number().int() }, (p) => clientFromEnv2().updateProfile(p.profile, p.version));
5408
- tool("profiles_delete", "Delete a profile without run history.", { id: z5.string(), version: z5.number().int() }, (p) => clientFromEnv2().deleteProfile(p.id, p.version));
5409
- tool("launch_plan", "Validate a local launch plan; does not execute a remote process.", { profileId: z5.string() }, (p) => clientFromEnv2().launchPlan(p.profileId));
6463
+ tool("profiles_update", "Replace a harness profile at its version.", { profile: profileInputSchema, version: z7.number().int() }, (p) => clientFromEnv2().updateProfile(p.profile, p.version));
6464
+ tool("profiles_delete", "Delete a profile without run history.", { id: z7.string(), version: z7.number().int() }, (p) => clientFromEnv2().deleteProfile(p.id, p.version));
6465
+ tool("launch_plan", "Validate a local launch plan; does not execute a remote process.", { profileId: z7.string() }, (p) => clientFromEnv2().launchPlan(p.profileId));
5410
6466
  tool("runs_list", "List launch metadata.", page, (p) => clientFromEnv2().listRuns(p));
5411
- tool("runs_get", "Get launch metadata.", { id: z5.string() }, (p) => clientFromEnv2().getRun(p.id));
6467
+ tool("runs_get", "Get launch metadata.", { id: z7.string() }, (p) => clientFromEnv2().getRun(p.id));
5412
6468
  if (process.argv.includes("--version"))
5413
6469
  console.log(VERSION);
5414
6470
  else if (process.argv.includes("--help"))
5415
6471
  console.log("switcher-mcp: authenticated Switcher API tools over MCP stdio. Resolves API URL/key through @hasna/contracts (Keychain, canonical config/credentials, or environment). With nothing configured it exits 1 before answering initialize and names those sources; HASNA_SWITCHER_LOCAL=1 deliberately serves the on-box store instead.");
5416
6472
  else {
5417
6473
  try {
5418
- runtime = await openCliRuntime(process.env);
6474
+ runtime = await openCliRuntime(process.env, (provider) => credentials.resolve(provider));
5419
6475
  } catch (error) {
5420
6476
  const code = error instanceof Fault ? error.code : "remote_api_config_error";
5421
6477
  console.error(`${code.toUpperCase()}: ${error instanceof Error ? error.message : "Switcher API configuration could not be resolved."}`);