@hasna/switcher 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -514,7 +514,7 @@ function canonicalPolicyJSON(value) {
514
514
  }
515
515
 
516
516
  // src/domain.ts
517
- var VERSION = "0.2.2";
517
+ var VERSION = "0.2.4";
518
518
  var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
519
519
  var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
520
520
  var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
@@ -617,6 +617,7 @@ var runUpdateSchema = z4.object({
617
617
  routingEvents: routingEventsSchema.optional(),
618
618
  routingEventsDropped: z4.number().int().min(0).max(1e6).optional()
619
619
  }).strict();
620
+ var catalogSchema = z4.object({ models: z4.array(modelSchema).max(1e4), refreshedAt: z4.string().datetime(), source: z4.enum(["remote", "manual"]) }).strict();
620
621
 
621
622
  class Fault extends Error {
622
623
  status;
@@ -1482,6 +1483,9 @@ class SwitcherClient {
1482
1483
  refreshModels(id, idempotencyKey) {
1483
1484
  return this.request("POST", `/v1/providers/${encodeURIComponent(id)}/refresh`, {}, { idempotencyKey });
1484
1485
  }
1486
+ saveCatalog(id, providerVersion, catalog, idempotencyKey) {
1487
+ return this.request("PUT", `/v1/providers/${encodeURIComponent(id)}/catalog`, catalog, { version: providerVersion, idempotencyKey });
1488
+ }
1485
1489
  listModels(id, options = {}) {
1486
1490
  return this.request("GET", `/v1/providers/${encodeURIComponent(id)}/models?${this.query(options)}`);
1487
1491
  }
@@ -1788,6 +1792,10 @@ import { isAbsolute as isAbsolute4, join as join4, resolve as resolve3 } from "p
1788
1792
  var {SQL } = globalThis.Bun;
1789
1793
  import { chmod, mkdir as mkdir3 } from "fs/promises";
1790
1794
  import { dirname as dirname2, resolve as resolve2 } from "path";
1795
+ import { createHash as createHash2 } from "crypto";
1796
+ import { apiKeyMigrations } from "@hasna/contracts/auth";
1797
+ var authMigrationPlan = () => apiKeyMigrations().map((migration) => ({ ...migration, checksum: createHash2("sha256").update(migration.sql).digest("hex") }));
1798
+
1791
1799
  class Store {
1792
1800
  tail = Promise.resolve();
1793
1801
  async exclusive(action) {
@@ -1825,7 +1833,10 @@ class Store {
1825
1833
  await chmod(file, 384);
1826
1834
  }
1827
1835
  const store = new Store(sql, engine);
1828
- await store.migrate();
1836
+ if (config.migrate === false)
1837
+ await store.verifySchema();
1838
+ else
1839
+ await store.migrate();
1829
1840
  return store;
1830
1841
  } catch (error) {
1831
1842
  await sql?.close().catch(() => {});
@@ -1844,23 +1855,66 @@ class Store {
1844
1855
  await tx.unsafe("SELECT pg_advisory_xact_lock(782034215)");
1845
1856
  await tx.unsafe("CREATE TABLE IF NOT EXISTS switcher_migrations (version INTEGER PRIMARY KEY)");
1846
1857
  const versions = await tx.unsafe("SELECT version FROM switcher_migrations ORDER BY version");
1847
- if (versions.some((v) => v.version > 1))
1858
+ if (versions.some((v) => v.version > 2))
1848
1859
  throw new Error("Newer database schema");
1849
- if (versions.length)
1850
- return;
1851
- await tx.unsafe("CREATE TABLE switcher_providers (id TEXT PRIMARY KEY, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
1852
- 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)");
1853
- 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)");
1854
- 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)");
1855
- await tx.unsafe("CREATE TABLE switcher_idempotency (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, created_at TEXT NOT NULL)");
1856
- await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (1)");
1860
+ const applied = new Set(versions.map((v) => Number(v.version)));
1861
+ if (!applied.has(1)) {
1862
+ await tx.unsafe("CREATE TABLE switcher_providers (id TEXT PRIMARY KEY, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
1863
+ 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)");
1864
+ 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)");
1865
+ 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)");
1866
+ await tx.unsafe("CREATE TABLE switcher_idempotency (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, created_at TEXT NOT NULL)");
1867
+ await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (1)");
1868
+ }
1869
+ if (this.engine === "postgresql") {
1870
+ await tx.unsafe("CREATE TABLE IF NOT EXISTS switcher_auth_migrations (id TEXT PRIMARY KEY, checksum TEXT NOT NULL)");
1871
+ const migrations = authMigrationPlan();
1872
+ const authRows = await tx.unsafe("SELECT id, checksum FROM switcher_auth_migrations ORDER BY id");
1873
+ const known = new Map(migrations.map((migration) => [migration.id, migration.checksum]));
1874
+ for (const row of authRows) {
1875
+ if (known.get(String(row.id)) !== String(row.checksum))
1876
+ throw new Error("Unknown or changed API-key migration");
1877
+ }
1878
+ const completed = new Set(authRows.map((row) => String(row.id)));
1879
+ for (const migration of migrations)
1880
+ if (!completed.has(migration.id)) {
1881
+ await tx.unsafe(migration.sql);
1882
+ await tx.unsafe("INSERT INTO switcher_auth_migrations(id,checksum) VALUES ($1,$2)", [migration.id, migration.checksum]);
1883
+ }
1884
+ if (!applied.has(2))
1885
+ await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (2)");
1886
+ }
1857
1887
  });
1858
1888
  }
1889
+ async verifySchema() {
1890
+ const versions = await this.sql.unsafe("SELECT version FROM switcher_migrations ORDER BY version");
1891
+ const applied = new Set(versions.map((row) => Number(row.version)));
1892
+ if (!applied.has(1) || this.engine === "postgresql" && !applied.has(2) || versions.some((row) => Number(row.version) > 2))
1893
+ throw new Error("Unsupported database schema");
1894
+ if (this.engine === "postgresql") {
1895
+ const expected = authMigrationPlan(), rows = await this.sql.unsafe("SELECT id, checksum FROM switcher_auth_migrations ORDER BY id");
1896
+ const actual = new Map(rows.map((row) => [String(row.id), String(row.checksum)]));
1897
+ if (actual.size !== expected.length || expected.some((migration) => actual.get(migration.id) !== migration.checksum))
1898
+ throw new Error("Unsupported API-key schema");
1899
+ 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");
1900
+ }
1901
+ }
1859
1902
  async ready() {
1860
1903
  await this.exclusive(async () => {
1861
1904
  await this.sql.unsafe("SELECT 1");
1862
1905
  });
1863
1906
  }
1907
+ authQueryClient() {
1908
+ if (this.engine !== "postgresql")
1909
+ throw new Fault(500, "auth_config", "Signed API keys require the PostgreSQL backend.");
1910
+ return {
1911
+ many: async (sql, params = []) => await this.sql.unsafe(sql, [...params]),
1912
+ get: async (sql, params = []) => (await this.sql.unsafe(sql, [...params]))[0] ?? null,
1913
+ execute: async (sql, params = []) => {
1914
+ await this.sql.unsafe(sql, [...params]);
1915
+ }
1916
+ };
1917
+ }
1864
1918
  async close() {
1865
1919
  await this.tail;
1866
1920
  await this.sql.close();
@@ -1946,7 +2000,8 @@ class Store {
1946
2000
  }
1947
2001
 
1948
2002
  // src/service.ts
1949
- import { createHash as createHash3, timingSafeEqual } from "crypto";
2003
+ import { createHash as createHash4, timingSafeEqual } from "crypto";
2004
+ import { verifyApiKey } from "@hasna/contracts/auth";
1950
2005
  import { z as z5 } from "zod";
1951
2006
 
1952
2007
  // src/auth.ts
@@ -2221,7 +2276,7 @@ async function discover(provider, env = process.env, resolveCredential) {
2221
2276
  }
2222
2277
 
2223
2278
  // src/model-policy.ts
2224
- import { createHash as createHash2 } from "crypto";
2279
+ import { createHash as createHash3 } from "crypto";
2225
2280
  var roles = ["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"];
2226
2281
  var id = (v, label2) => {
2227
2282
  if (typeof v !== "string" || !v || v.length > 300 || /[\u0000-\u001f\u007f]/.test(v))
@@ -2283,7 +2338,7 @@ function compileModelPolicy(model, catalog, policy) {
2283
2338
  if (Object.values(aliases).some((value) => !allowedModels.includes(value)))
2284
2339
  throw new Fault(422, "model_not_allowed", "A model alias target must be explicitly allowed by the launch policy.");
2285
2340
  const result = { version: 1, model: selected, roles: compiledRoles, allowedModels, aliases, fallbacks };
2286
- return { ...result, digest: createHash2("sha256").update(stable(result)).digest("hex") };
2341
+ return { ...result, digest: createHash3("sha256").update(stable(result)).digest("hex") };
2287
2342
  }
2288
2343
  function resolvePolicyModel(compiled, requested) {
2289
2344
  const value = id(requested, "requested model");
@@ -2385,10 +2440,13 @@ var openapi_default = {
2385
2440
  openapi: "3.0.3",
2386
2441
  info: {
2387
2442
  title: "Switcher API",
2388
- version: "0.2.2",
2443
+ version: "0.2.4",
2389
2444
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2390
2445
  },
2391
2446
  security: [
2447
+ {
2448
+ apiKeyAuth: []
2449
+ },
2392
2450
  {
2393
2451
  bearerAuth: []
2394
2452
  }
@@ -3142,6 +3200,73 @@ var openapi_default = {
3142
3200
  }
3143
3201
  }
3144
3202
  },
3203
+ responses: {
3204
+ "200": {
3205
+ description: "Success",
3206
+ content: {
3207
+ "application/json": {
3208
+ schema: {
3209
+ $ref: "#/components/schemas/Catalog"
3210
+ }
3211
+ }
3212
+ }
3213
+ },
3214
+ default: {
3215
+ description: "Structured error",
3216
+ content: {
3217
+ "application/json": {
3218
+ schema: {
3219
+ $ref: "#/components/schemas/Error"
3220
+ }
3221
+ }
3222
+ }
3223
+ }
3224
+ },
3225
+ description: "Self-hosted/local server refresh. Hosted clients discover locally and commit catalog metadata through the version-checked catalog endpoint."
3226
+ }
3227
+ },
3228
+ "/v1/providers/{id}/catalog": {
3229
+ put: {
3230
+ operationId: "saveCatalog",
3231
+ parameters: [
3232
+ {
3233
+ name: "id",
3234
+ in: "path",
3235
+ required: true,
3236
+ schema: {
3237
+ type: "string"
3238
+ }
3239
+ },
3240
+ {
3241
+ name: "Idempotency-Key",
3242
+ in: "header",
3243
+ required: true,
3244
+ schema: {
3245
+ type: "string",
3246
+ minLength: 8,
3247
+ maxLength: 128
3248
+ }
3249
+ },
3250
+ {
3251
+ name: "If-Match",
3252
+ in: "header",
3253
+ required: true,
3254
+ schema: {
3255
+ type: "integer",
3256
+ minimum: 1
3257
+ }
3258
+ }
3259
+ ],
3260
+ requestBody: {
3261
+ required: true,
3262
+ content: {
3263
+ "application/json": {
3264
+ schema: {
3265
+ $ref: "#/components/schemas/Catalog"
3266
+ }
3267
+ }
3268
+ }
3269
+ },
3145
3270
  responses: {
3146
3271
  "200": {
3147
3272
  description: "Success",
@@ -3529,6 +3654,36 @@ var openapi_default = {
3529
3654
  }
3530
3655
  },
3531
3656
  "/v1/openapi.json": {
3657
+ get: {
3658
+ operationId: "openApiV1",
3659
+ parameters: [],
3660
+ responses: {
3661
+ "200": {
3662
+ description: "Success",
3663
+ content: {
3664
+ "application/json": {
3665
+ schema: {
3666
+ type: "object",
3667
+ additionalProperties: true
3668
+ }
3669
+ }
3670
+ }
3671
+ },
3672
+ default: {
3673
+ description: "Structured error",
3674
+ content: {
3675
+ "application/json": {
3676
+ schema: {
3677
+ $ref: "#/components/schemas/Error"
3678
+ }
3679
+ }
3680
+ }
3681
+ }
3682
+ },
3683
+ security: []
3684
+ }
3685
+ },
3686
+ "/openapi.json": {
3532
3687
  get: {
3533
3688
  operationId: "openApi",
3534
3689
  parameters: [],
@@ -3554,12 +3709,18 @@ var openapi_default = {
3554
3709
  }
3555
3710
  }
3556
3711
  }
3557
- }
3712
+ },
3713
+ security: []
3558
3714
  }
3559
3715
  }
3560
3716
  },
3561
3717
  components: {
3562
3718
  securitySchemes: {
3719
+ apiKeyAuth: {
3720
+ type: "apiKey",
3721
+ in: "header",
3722
+ name: "x-api-key"
3723
+ },
3563
3724
  bearerAuth: {
3564
3725
  type: "http",
3565
3726
  scheme: "bearer"
@@ -5132,10 +5293,12 @@ var openapi_default = {
5132
5293
  "name"
5133
5294
  ],
5134
5295
  additionalProperties: false
5135
- }
5296
+ },
5297
+ maxItems: 1e4
5136
5298
  },
5137
5299
  refreshedAt: {
5138
- type: "string"
5300
+ type: "string",
5301
+ format: "date-time"
5139
5302
  },
5140
5303
  source: {
5141
5304
  type: "string",
@@ -5720,10 +5883,12 @@ var openapi_default = {
5720
5883
  "name"
5721
5884
  ],
5722
5885
  additionalProperties: false
5723
- }
5886
+ },
5887
+ maxItems: 1e4
5724
5888
  },
5725
5889
  refreshedAt: {
5726
- type: "string"
5890
+ type: "string",
5891
+ format: "date-time"
5727
5892
  },
5728
5893
  source: {
5729
5894
  type: "string",
@@ -6349,15 +6514,31 @@ var openapi_default = {
6349
6514
  Ready: {
6350
6515
  type: "object",
6351
6516
  properties: {
6352
- ready: {
6353
- type: "boolean"
6517
+ status: {
6518
+ type: "string",
6519
+ enum: [
6520
+ "ready",
6521
+ "unavailable"
6522
+ ]
6523
+ },
6524
+ version: {
6525
+ type: "string"
6526
+ },
6527
+ backend: {
6528
+ type: "string",
6529
+ enum: [
6530
+ "sqlite",
6531
+ "postgresql"
6532
+ ]
6354
6533
  },
6355
6534
  reason: {
6356
6535
  type: "string"
6357
6536
  }
6358
6537
  },
6359
6538
  required: [
6360
- "ready"
6539
+ "status",
6540
+ "version",
6541
+ "backend"
6361
6542
  ],
6362
6543
  additionalProperties: false
6363
6544
  },
@@ -6425,12 +6606,27 @@ var openapi_default = {
6425
6606
  };
6426
6607
 
6427
6608
  // src/service.ts
6428
- var snapshot = (profile, provider, catalog) => createHash3("sha256").update(JSON.stringify([profile, provider, { models: catalog.models, source: catalog.source }])).digest("hex");
6429
- var hash = (s) => createHash3("sha256").update(s).digest();
6430
- function createHandler(store, apiKey, providerEnv = process.env, resolveCredential) {
6431
- if (!apiKey || apiKey.length < 24)
6609
+ var providerCatalogFingerprint = (provider) => createHash4("sha256").update(JSON.stringify(provider)).digest("hex");
6610
+ var snapshot = (profile, provider, catalog) => createHash4("sha256").update(JSON.stringify([profile, provider, { models: catalog.models, source: catalog.source }])).digest("hex");
6611
+ var hash = (s) => createHash4("sha256").update(s).digest();
6612
+ function localApiKey(headers) {
6613
+ const direct = headers.get("x-api-key");
6614
+ if (direct)
6615
+ return direct;
6616
+ const authorization = headers.get("authorization") ?? "";
6617
+ return authorization.startsWith("Bearer ") ? authorization.slice("Bearer ".length) : "";
6618
+ }
6619
+ function createHandler(store, authentication, providerEnv = process.env, resolveCredential) {
6620
+ const localToken = typeof authentication === "string" ? authentication : undefined;
6621
+ if (localToken !== undefined && (localToken.length < 24 || /[\r\n]/.test(localToken)))
6432
6622
  throw new Fault(500, "auth_config", "Set HASNA_SWITCHER_API_KEY to a random token of at least 24 characters.");
6433
- const expected = hash(`Bearer ${apiKey}`);
6623
+ const expected = localToken === undefined ? undefined : hash(localToken);
6624
+ const verifier = typeof authentication === "string" ? undefined : verifyApiKey({
6625
+ app: "switcher",
6626
+ signingSecret: authentication.signingSecret,
6627
+ keyStatus: authentication.keyStatus,
6628
+ ...authentication.audit ? { audit: authentication.audit } : {}
6629
+ });
6434
6630
  return async (request) => {
6435
6631
  const requestId = crypto.randomUUID();
6436
6632
  const json = (body, status = 200) => Response.json(body, { status, headers: { "x-request-id": requestId, "cache-control": "no-store", "x-content-type-options": "nosniff" } });
@@ -6444,15 +6640,23 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
6444
6640
  if (request.method === "GET" && route2 === "/ready") {
6445
6641
  try {
6446
6642
  await store.ready();
6447
- return json({ ready: true });
6643
+ return json({ status: "ready", version: VERSION, backend: store.engine });
6448
6644
  } catch {
6449
- return json({ ready: false, reason: "Storage is unavailable." }, 503);
6645
+ return json({ status: "unavailable", version: VERSION, backend: store.engine, reason: "Storage is unavailable." }, 503);
6450
6646
  }
6451
6647
  }
6452
- if (!timingSafeEqual(expected, hash(request.headers.get("authorization") ?? "")))
6453
- throw new Fault(401, "unauthorized", "A valid API bearer token is required.");
6454
6648
  if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route2))
6455
6649
  return json(openapi_default);
6650
+ if (expected) {
6651
+ const presented = hash(localApiKey(request.headers));
6652
+ if (!timingSafeEqual(expected, presented))
6653
+ throw new Fault(401, "unauthorized", "A valid API key is required.");
6654
+ } else {
6655
+ const requiredScopes = [request.method === "GET" || request.method === "HEAD" ? "switcher:read" : "switcher:write"];
6656
+ const decision = await verifier.authenticate(request.headers, { method: request.method, path: route2, requiredScopes });
6657
+ if (!decision.ok)
6658
+ throw new Fault(decision.status, `auth_${decision.reason}`, decision.message);
6659
+ }
6456
6660
  const parts = route2.split("/").filter(Boolean);
6457
6661
  if (parts[0] !== "v1")
6458
6662
  throw new Fault(404, "not_found", "Route was not found.");
@@ -6476,7 +6680,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
6476
6680
  const catalog = await store.get("catalogs", id2);
6477
6681
  const p = page();
6478
6682
  const filtered = catalog.models.filter((m) => [m.id, m.name].some((s) => s.toLowerCase().includes(p.search.toLowerCase())));
6479
- 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 });
6683
+ 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 });
6480
6684
  }
6481
6685
  throw new Fault(404, "not_found", "Route was not found.");
6482
6686
  }
@@ -6506,6 +6710,8 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
6506
6710
  if (replay.found)
6507
6711
  return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
6508
6712
  let refreshed;
6713
+ if (!expected && resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST")
6714
+ 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.");
6509
6715
  if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
6510
6716
  parse2(z5.object({}).strict(), body);
6511
6717
  const provider = await store.get("providers", id2);
@@ -6544,7 +6750,29 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
6544
6750
  if (!(e instanceof Fault && e.status === 404))
6545
6751
  throw e;
6546
6752
  }
6547
- return store.put("catalogs", { id: id2, ...catalog }, old?.version, db);
6753
+ const saved = await store.put("catalogs", { id: id2, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
6754
+ return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
6755
+ }
6756
+ if (resource === "providers" && id2 && parts[3] === "catalog" && parts.length === 4 && request.method === "PUT") {
6757
+ if (store.engine === "postgresql")
6758
+ await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id2]);
6759
+ const provider = await store.get("providers", id2, db);
6760
+ if (provider.version !== version())
6761
+ throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
6762
+ const catalog = parse2(catalogSchema, body);
6763
+ const expectedSource = provider.manualModels.length ? "manual" : "remote";
6764
+ if (catalog.source !== expectedSource)
6765
+ throw new Fault(422, "catalog_source_mismatch", "Catalog provenance does not match the current provider configuration.");
6766
+ catalog.refreshedAt = new Date().toISOString();
6767
+ let old;
6768
+ try {
6769
+ old = await store.get("catalogs", id2, db);
6770
+ } catch (error) {
6771
+ if (!(error instanceof Fault && error.status === 404))
6772
+ throw error;
6773
+ }
6774
+ const saved = await store.put("catalogs", { id: id2, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
6775
+ return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
6548
6776
  }
6549
6777
  if (resource === "launch-plans" && !id2 && request.method === "POST") {
6550
6778
  const { profileId } = parse2(z5.object({ profileId: idSchema }).strict(), body);
@@ -6559,6 +6787,9 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
6559
6787
  throw new Fault(422, "catalog_missing", "Refresh the provider catalog before launching.");
6560
6788
  throw e;
6561
6789
  }
6790
+ const stored = catalog;
6791
+ if (stored.providerVersion !== undefined && stored.providerVersion !== provider.version || stored.providerFingerprint !== undefined && stored.providerFingerprint !== providerCatalogFingerprint(provider))
6792
+ throw new Fault(409, "catalog_provider_changed", "Catalog metadata belongs to an older provider configuration; refresh locally before launching.");
6562
6793
  const selected = catalog.models.find((m) => m.id === profile.model);
6563
6794
  if (!selected)
6564
6795
  throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
@@ -6619,21 +6850,35 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
6619
6850
  }
6620
6851
 
6621
6852
  // src/server.ts
6853
+ import { ApiKeyStore } from "@hasna/contracts/auth";
6622
6854
  async function startServer(options) {
6623
6855
  const port = options.port ?? 0;
6624
6856
  if (!Number.isInteger(port) || port < 0 || port > 65535)
6625
6857
  throw new Fault(400, "invalid_port", "Port must be an integer between 0 and 65535.");
6626
- if (options.apiKey.length < 24 || /[\r\n]/.test(options.apiKey))
6858
+ if (Boolean(options.apiKey) === Boolean(options.signingSecret))
6859
+ throw new Fault(500, "auth_config", "Configure exactly one local API token or hosted API signing secret.");
6860
+ if (options.apiKey && (options.apiKey.length < 24 || /[\r\n]/.test(options.apiKey)))
6627
6861
  throw new Fault(500, "auth_config", "Use a random operator token of at least 24 characters.");
6628
- const store = await Store.open({ databaseUrl: options.databaseUrl, sqlitePath: options.sqlitePath });
6862
+ if (options.signingSecret && (options.signingSecret.length < 32 || /[\r\n]/.test(options.signingSecret)))
6863
+ throw new Fault(500, "auth_config", "Use an API signing secret of at least 32 characters.");
6864
+ if (options.signingSecret && !options.databaseUrl)
6865
+ throw new Fault(500, "storage_config", "Hosted signed-key authentication requires PostgreSQL; configure HASNA_SWITCHER_DATABASE_URL.");
6866
+ const store = await Store.open({ databaseUrl: options.databaseUrl, sqlitePath: options.sqlitePath, migrate: !options.signingSecret });
6629
6867
  let server;
6630
6868
  try {
6869
+ const authentication = options.apiKey ?? (() => {
6870
+ const keyStore = new ApiKeyStore(store.authQueryClient());
6871
+ return { kind: "signed-api-key", signingSecret: options.signingSecret, keyStatus: keyStore.keyStatus, audit: (event) => {
6872
+ if (event.outcome === "deny")
6873
+ console.error(`api_auth deny kid=${event.kid ?? "-"} reason=${event.reason ?? "-"} ${event.method ?? "-"} ${event.path ?? "-"}`);
6874
+ } };
6875
+ })();
6631
6876
  server = Bun.serve({
6632
6877
  hostname: options.hostname ?? "127.0.0.1",
6633
6878
  port,
6634
6879
  maxRequestBodySize: 1024 * 1024,
6635
6880
  idleTimeout: 60,
6636
- fetch: createHandler(store, options.apiKey, options.providerEnv, options.resolveCredential)
6881
+ fetch: createHandler(store, authentication, options.providerEnv, options.resolveCredential)
6637
6882
  });
6638
6883
  await store.ready();
6639
6884
  } catch (error) {
@@ -6673,7 +6918,19 @@ var SWITCHER_LOCAL_OPT_IN_ENV_KEYS = ["HASNA_SWITCHER_LOCAL", "SWITCHER_LOCAL"];
6673
6918
  var SWITCHER_KEYCHAIN_ITEM = "hasna.credentials.switcher.api-key";
6674
6919
  var SWITCHER_CREDENTIALS_FILE = "~/.hasna/switcher/config/credentials";
6675
6920
  function isSwitcherLocalOptIn(env = process.env) {
6676
- return SWITCHER_LOCAL_OPT_IN_ENV_KEYS.some((key) => (env[key] ?? "").trim() !== "");
6921
+ let selected;
6922
+ for (const key of SWITCHER_LOCAL_OPT_IN_ENV_KEYS) {
6923
+ if (env[key] === undefined)
6924
+ continue;
6925
+ const value = env[key].trim().toLowerCase();
6926
+ const decision = !value || ["0", "false", "no", "off"].includes(value) ? false : ["1", "true", "yes", "on"].includes(value) ? true : undefined;
6927
+ if (decision === undefined)
6928
+ throw new Fault(400, "invalid_local_opt_in", `${key} must be one of 1, true, yes, on, 0, false, no, or off.`);
6929
+ if (selected !== undefined && selected !== decision)
6930
+ throw new Fault(400, "conflicting_local_opt_in", "HASNA_SWITCHER_LOCAL and SWITCHER_LOCAL must not disagree.");
6931
+ selected = decision;
6932
+ }
6933
+ return selected ?? false;
6677
6934
  }
6678
6935
  function switcherAuthorityEnvKeys() {
6679
6936
  const keys = clientTransportEnvKeys("switcher");
@@ -7033,9 +7290,9 @@ async function prepareGemini(input) {
7033
7290
  }
7034
7291
 
7035
7292
  // src/gemini-bridge.ts
7036
- import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "crypto";
7293
+ import { createHash as createHash5, timingSafeEqual as timingSafeEqual2 } from "crypto";
7037
7294
  function geminiBridge(input, timing = {}) {
7038
- const token = crypto.randomUUID() + crypto.randomUUID(), digest = (value) => createHash4("sha256").update(value).digest(), expected = digest(token);
7295
+ const token = crypto.randomUUID() + crypto.randomUUID(), digest = (value) => createHash5("sha256").update(value).digest(), expected = digest(token);
7039
7296
  const models = new Set(input.models.map((model) => model.id));
7040
7297
  let closing = false, stopped;
7041
7298
  const active = new Set;
@@ -7723,20 +7980,28 @@ function prepareOpenCodeMessages(baseUrl, body, suffix, credential, state = new
7723
7980
  }
7724
7981
 
7725
7982
  // src/inference-gateway.ts
7726
- import { createHash as createHash5, timingSafeEqual as timingSafeEqual3 } from "crypto";
7983
+ import { createHash as createHash6, timingSafeEqual as timingSafeEqual3 } from "crypto";
7727
7984
  var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
7985
+ var MIN_REQUEST_BODY_BYTES = 4 * 1024 * 1024;
7986
+ var MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024;
7987
+ var REQUEST_BYTES_PER_CONTEXT_TOKEN = 16;
7988
+ function requestBodyLimit(models, policy) {
7989
+ const allowed = new Set(policy.allowedModels);
7990
+ const contextWindow = Math.max(0, ...models.filter((model) => allowed.has(model.id)).map((model) => Number.isSafeInteger(model.contextWindow) && model.contextWindow > 0 ? model.contextWindow : 0));
7991
+ return Math.min(MAX_REQUEST_BODY_BYTES, Math.max(MIN_REQUEST_BODY_BYTES, contextWindow * REQUEST_BYTES_PER_CONTEXT_TOKEN));
7992
+ }
7728
7993
  function createInferenceGateway(input, timing = {}) {
7729
7994
  const token = crypto.randomUUID() + crypto.randomUUID();
7730
7995
  const openCodeSession = crypto.randomUUID();
7731
7996
  const openCodeState = new Map;
7732
- const digest = (value) => createHash5("sha256").update(value).digest();
7997
+ const digest = (value) => createHash6("sha256").update(value).digest();
7733
7998
  const expected = digest(token), policy = input.compiledPolicy;
7734
7999
  const known = new Set(input.models.map((m) => m.id));
7735
8000
  const safeModel = (value) => typeof value === "string" && value !== input.credential && (known.has(value) || Object.hasOwn(policy.aliases, value)) ? value : "<unrecognized>";
7736
8001
  const fail = (status, code, message) => Response.json({ error: { type: "switcher_model_policy", code, message: message ?? (code === "model_not_allowed" ? "This model is outside the launch policy. Select it with switcher launch --model or explicitly assign an allowed role model." : `Switcher inference gateway: ${code}.`) } }, { status });
7737
8002
  let closing = false, stopped;
7738
8003
  const active = new Set;
7739
- const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
8004
+ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: requestBodyLimit(input.models, input.compiledPolicy), idleTimeout: 255, async fetch(request, server2) {
7740
8005
  if (closing)
7741
8006
  return fail(503, "closing");
7742
8007
  const credential = request.headers.get("x-goog-api-key") ?? request.headers.get("x-api-key") ?? request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
@@ -7869,8 +8134,6 @@ function createInferenceGateway(input, timing = {}) {
7869
8134
  response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers: upstreamHeaders, body: JSON.stringify(translated?.body ?? outgoing), redirect: "manual", ...activity.fetchOptions }));
7870
8135
  } catch {
7871
8136
  current.reason = activity.timedOut() ? "provider_idle_timeout" : signal.aborted ? "request_cancelled" : "network_error";
7872
- if (!signal.aborted && attempt + 1 < candidates.length)
7873
- continue;
7874
8137
  throw new Error("provider_request_failed");
7875
8138
  }
7876
8139
  current.upstreamStatus = response.status;
@@ -7948,8 +8211,9 @@ function createInferenceGateway(input, timing = {}) {
7948
8211
  current.reason = error.code;
7949
8212
  else if (activity.timedOut())
7950
8213
  current.reason = "provider_idle_timeout";
8214
+ const networkError = !(error instanceof Fault) && current.reason === "network_error";
7951
8215
  release();
7952
- return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : "provider_request_failed", error instanceof Fault && error.code === "opencode_translation_unsupported" ? error.message : undefined);
8216
+ return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : networkError ? "provider_network_error" : "provider_request_failed", error instanceof Fault && error.code === "opencode_translation_unsupported" ? error.message : networkError ? "The upstream provider connection ended before response headers. Switcher did not attempt a fallback because delivery is uncertain." : undefined);
7953
8217
  }
7954
8218
  } });
7955
8219
  return { baseUrl: new URL(input.protocol === "gemini-generate-content" ? "v1beta" : "v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
@@ -7969,7 +8233,7 @@ function createInferenceGateway(input, timing = {}) {
7969
8233
  import { mkdir as mkdir5, readFile as readFile2, realpath as realpath3, stat as stat4, writeFile as writeFile4 } from "fs/promises";
7970
8234
  import { dirname as dirname4, isAbsolute as isAbsolute6, join as join6, resolve as resolve5 } from "path";
7971
8235
  import { execFileSync as execFileSync2 } from "child_process";
7972
- import { createHash as createHash6 } from "crypto";
8236
+ import { createHash as createHash7 } from "crypto";
7973
8237
  var dict = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
7974
8238
  var model = (v) => JSON.stringify(v);
7975
8239
  var codexRoutingKeys = new Set(["model", "model_provider", "model_providers", "model_catalog_json", "base_url", "wire_api", "env_key", "env_http_headers", "http_headers", "auth_command", "include"]);
@@ -8115,7 +8379,7 @@ async function writeCodexAgentOverrides(result, stateDir) {
8115
8379
  await mkdir5(root, { recursive: true });
8116
8380
  const paths = {};
8117
8381
  for (const agent of result.agents) {
8118
- const digest = createHash6("sha256").update(agent.name).digest("hex").slice(0, 16);
8382
+ const digest = createHash7("sha256").update(agent.name).digest("hex").slice(0, 16);
8119
8383
  const path = join6(root, `agent-${digest}.toml`);
8120
8384
  await writeFile4(path, renderCodexAgentToml(agent.config), { encoding: "utf8", mode: 384, flag: "wx" });
8121
8385
  paths[agent.name] = path;
@@ -8236,7 +8500,7 @@ async function readCodexAgentConfig(path) {
8236
8500
  import { access as access3, mkdir as mkdir10, readFile as readFile4, readdir as readdir4, writeFile as writeFile10, rm as rm2 } from "fs/promises";
8237
8501
  import { basename as basename2, dirname as dirname7, join as join12, isAbsolute as isAbsolute11, resolve as resolve8 } from "path";
8238
8502
  import { homedir as homedir7, tmpdir } from "os";
8239
- import { createHash as createHash8, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual5 } from "crypto";
8503
+ import { createHash as createHash9, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual5 } from "crypto";
8240
8504
  import { execFile as execFile2 } from "child_process";
8241
8505
  import { promisify as promisify2 } from "util";
8242
8506
  import { createConnection } from "net";
@@ -9224,7 +9488,7 @@ function compileHermesModelPolicy(currentModel, roles2, baseUrl, apiMode = "chat
9224
9488
  }
9225
9489
 
9226
9490
  // src/hermes-backend.ts
9227
- import { createHash as createHash7, timingSafeEqual as timingSafeEqual4 } from "crypto";
9491
+ import { createHash as createHash8, timingSafeEqual as timingSafeEqual4 } from "crypto";
9228
9492
  import { mkdir as mkdir9, symlink as symlink2, writeFile as writeFile9 } from "fs/promises";
9229
9493
  import { isAbsolute as isAbsolute10, join as join11 } from "path";
9230
9494
  var hermesApiMode = {
@@ -9257,8 +9521,8 @@ function createHermesBridge(input, timing = {}) {
9257
9521
  const nativeHeader = protocol === "anthropic-messages" ? "x-api-key" : "authorization";
9258
9522
  const nativeCredential = request.headers.get(nativeHeader) ?? "";
9259
9523
  const expectedCredential = nativeHeader === "x-api-key" ? token : `Bearer ${token}`;
9260
- const actual = createHash7("sha256").update(nativeCredential).digest();
9261
- const expectedHeader = createHash7("sha256").update(expectedCredential).digest();
9524
+ const actual = createHash8("sha256").update(nativeCredential).digest();
9525
+ const expectedHeader = createHash8("sha256").update(expectedCredential).digest();
9262
9526
  if (actual.length !== expectedHeader.length || !timingSafeEqual4(actual, expectedHeader))
9263
9527
  return Response.json({ error: { message: "Unauthorized" } }, { status: 401 });
9264
9528
  const path = new URL(request.url).pathname;
@@ -9944,7 +10208,7 @@ function codexModel(model3, priority, baseUrl = "https://provider.invalid", sele
9944
10208
  }
9945
10209
  function grokBridge(input, timing = {}) {
9946
10210
  const token = crypto.randomUUID() + crypto.randomUUID();
9947
- const expected = createHash8("sha256").update(`Bearer ${token}`).digest();
10211
+ const expected = createHash9("sha256").update(`Bearer ${token}`).digest();
9948
10212
  const models = new Map(input.models.flatMap((m) => [[m.id, m.id], [grokAlias(input, m.id), m.id]]));
9949
10213
  let server;
9950
10214
  let closing = false;
@@ -9956,7 +10220,7 @@ function grokBridge(input, timing = {}) {
9956
10220
  if (closing)
9957
10221
  return Response.json({ error: { message: "Bridge is closing" } }, { status: 503 });
9958
10222
  const auth = request.headers.get("authorization") ?? (request.headers.has("x-api-key") ? `Bearer ${request.headers.get("x-api-key")}` : "");
9959
- if (!timingSafeEqual5(expected, createHash8("sha256").update(auth).digest()))
10223
+ if (!timingSafeEqual5(expected, createHash9("sha256").update(auth).digest()))
9960
10224
  return Response.json({ error: { message: "Unauthorized" } }, { status: 401 });
9961
10225
  const path = new URL(request.url).pathname;
9962
10226
  if (request.method === "GET" && path === "/v1/api-key")
@@ -10042,10 +10306,10 @@ function grokBridge(input, timing = {}) {
10042
10306
  })() };
10043
10307
  }
10044
10308
  function grokAlias(input, model3) {
10045
- return "switcher-" + createHash8("sha256").update(JSON.stringify([input.providerBaseUrl ?? input.baseUrl, input.protocol])).digest("hex").slice(0, 12) + "/" + model3;
10309
+ return "switcher-" + createHash9("sha256").update(JSON.stringify([input.providerBaseUrl ?? input.baseUrl, input.protocol])).digest("hex").slice(0, 12) + "/" + model3;
10046
10310
  }
10047
10311
  function piProviderId(input, providerBaseUrl) {
10048
- return "switcher-" + createHash8("sha256").update(JSON.stringify([endpoint(providerBaseUrl), input.protocol])).digest("hex").slice(0, 12);
10312
+ return "switcher-" + createHash9("sha256").update(JSON.stringify([endpoint(providerBaseUrl), input.protocol])).digest("hex").slice(0, 12);
10049
10313
  }
10050
10314
  function piModel(input, api) {
10051
10315
  return input.models.map((model3) => ({
@@ -10059,7 +10323,7 @@ function piModel(input, api) {
10059
10323
  }));
10060
10324
  }
10061
10325
  function primeProviderId(input, providerBaseUrl) {
10062
- return "switcher-" + createHash8("sha256").update(JSON.stringify([endpoint(providerBaseUrl), input.protocol])).digest("hex").slice(0, 12);
10326
+ return "switcher-" + createHash9("sha256").update(JSON.stringify([endpoint(providerBaseUrl), input.protocol])).digest("hex").slice(0, 12);
10063
10327
  }
10064
10328
  var PRIME_UNIX_SOCKET_LIMIT = 100;
10065
10329
  var PRIME_DAEMON_STARTUP_TIMEOUT_MS = 30000;
@@ -10069,7 +10333,7 @@ function primeSocketPaths(runtimeDir) {
10069
10333
  const daemonSocket = join12(runtimeDir, basename3);
10070
10334
  const uid = typeof process.getuid === "function" ? String(process.getuid()) : "user";
10071
10335
  const workerDir = join12(runtimeDir, `prime-agent-${uid}`);
10072
- const workerKey = createHash8("sha256").update(daemonSocket).digest("hex").slice(0, 12);
10336
+ const workerKey = createHash9("sha256").update(daemonSocket).digest("hex").slice(0, 12);
10073
10337
  const workerSocket = join12(workerDir, `worker-${workerKey}-${"x".repeat(12)}.sock`);
10074
10338
  const overlong = [daemonSocket, workerSocket].find((path) => Buffer.byteLength(path, "utf8") > PRIME_UNIX_SOCKET_LIMIT);
10075
10339
  return { daemonSocket, runtimeDir, workerDir, workerPrefix: join12(workerDir, `worker-${workerKey}-`), overlong };
@@ -10514,7 +10778,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
10514
10778
  return { executable: executable2, args: ["--daemon-socket", daemonSocket, "--provider", providerId, "--model", input.model, "--models", `${providerId}/**`, ...args], env, configPaths, warnings, beforeLaunch, cleanup };
10515
10779
  }
10516
10780
  if (input.harness === "opencode") {
10517
- const providerID2 = "switcher-" + createHash8("sha256").update(endpoint(providerBaseUrl) + input.protocol).digest("hex").slice(0, 12);
10781
+ const providerID2 = "switcher-" + createHash9("sha256").update(endpoint(providerBaseUrl) + input.protocol).digest("hex").slice(0, 12);
10518
10782
  const packageName2 = { "anthropic-messages": "@ai-sdk/anthropic", "openai-responses": "@ai-sdk/openai", "openai-chat": "@ai-sdk/openai-compatible" }[input.protocol];
10519
10783
  const modelConfig = Object.fromEntries(input.models.map((model3) => [model3.id, {
10520
10784
  name: model3.name,
@@ -10556,7 +10820,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
10556
10820
  warnings.push("Legacy OpenCode uses the documented singular provider configuration and an isolated XDG data root for durable sessions; it is separate from OpenCode 2.");
10557
10821
  return { executable, args: native2, env, configPaths, warnings };
10558
10822
  }
10559
- const providerID = "switcher-" + createHash8("sha256").update(endpoint(providerBaseUrl) + input.protocol).digest("hex").slice(0, 12);
10823
+ const providerID = "switcher-" + createHash9("sha256").update(endpoint(providerBaseUrl) + input.protocol).digest("hex").slice(0, 12);
10560
10824
  const packageName = { "anthropic-messages": "anthropic", "openai-responses": "openai/responses", "openai-chat": "openai-compatible", "gemini-generate-content": "gemini" }[input.protocol];
10561
10825
  const models = Object.fromEntries(input.models.map((m) => [m.id, {
10562
10826
  modelID: m.id,
@@ -10716,20 +10980,24 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
10716
10980
  import { mkdir as mkdir11, mkdtemp, rm as rm6, writeFile as writeFile14 } from "fs/promises";
10717
10981
  import { join as join16, resolve as resolve9 } from "path";
10718
10982
 
10983
+ // src/provider-credential-onboarding.ts
10984
+ import { z as z8 } from "zod";
10985
+ import { createHash as createHash11 } from "crypto";
10986
+ import { createInterface } from "readline/promises";
10987
+
10719
10988
  // src/credentials.ts
10720
10989
  import { z as z7 } from "zod";
10721
10990
  import { constants as constants5 } from "fs";
10722
10991
  import { open as open3, readdir as readdir5, unlink, link, lstat as lstat4, access as access4, stat as stat6, realpath as realpath6, readlink, rename as rename2 } from "fs/promises";
10723
10992
  import { join as join13, isAbsolute as isAbsolute13, dirname as dirname8, parse as pathParts, resolve as resolvePath, sep as sep2 } from "path";
10724
- import { createHash as createHash9, randomUUID as randomUUID5 } from "crypto";
10993
+ import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
10725
10994
  import { execFile as execFile3, spawn } from "child_process";
10726
10995
  import { promisify as promisify3 } from "util";
10727
- import { createInterface } from "readline/promises";
10728
10996
  import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
10729
10997
  var execute3 = promisify3(execFile3);
10730
10998
  var reference = z7.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
10731
10999
  var item = z7.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
10732
- var vaultKey = z7.string().max(500).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*)*$/, "Use a vault key path, not an option or secret value");
11000
+ var vaultKeySchema = z7.string().max(500).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*)*$/, "Use a vault key path, not an option or secret value");
10733
11001
  var keychain = z7.object({ kind: z7.literal("keychain"), service: item, account: item }).strict();
10734
11002
  var credentialTier = z7.enum(["argument", "override", "pointer", "profile", "keychain", "disk", "env"]);
10735
11003
  var operator = z7.discriminatedUnion("kind", [
@@ -10745,7 +11013,7 @@ var credentialBindingSchema = z7.object({
10745
11013
  requireProviderAuthentication: z7.literal(true).optional(),
10746
11014
  source: z7.discriminatedUnion("kind", [keychain, z7.object({
10747
11015
  kind: z7.literal("vault"),
10748
- key: vaultKey,
11016
+ key: vaultKeySchema,
10749
11017
  url: z7.string().max(2000).transform(endpoint).optional(),
10750
11018
  executable: z7.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute13, "Secrets executable must be an absolute path"),
10751
11019
  operator
@@ -10756,7 +11024,7 @@ var credentialBindingSchema = z7.object({
10756
11024
  if (binding.source.kind === "vault" && binding.source.operator.kind === "contracts" && Boolean(binding.source.operator.expectedSource) !== Boolean(binding.source.operator.expectedTier))
10757
11025
  ctx.addIssue({ code: "custom", path: ["source", "operator"], message: "A pinned Contracts operator requires both expectedSource and expectedTier." });
10758
11026
  });
10759
- var fingerprint = (binding) => createHash9("sha256").update(JSON.stringify(binding)).digest("hex");
11027
+ var fingerprint = (binding) => createHash10("sha256").update(JSON.stringify(binding)).digest("hex");
10760
11028
 
10761
11029
  class CredentialBindings {
10762
11030
  env;
@@ -10942,7 +11210,7 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
10942
11210
  throw unsafe();
10943
11211
  const sameFile = (info) => info.dev === before.dev && info.ino === before.ino && info.size === before.size && info.uid === before.uid && info.nlink === before.nlink && info.mode === before.mode && info.mtimeMs === before.mtimeMs && info.ctimeMs === before.ctimeMs;
10944
11212
  const hash2 = async (target) => {
10945
- const digest = createHash9("sha256");
11213
+ const digest = createHash10("sha256");
10946
11214
  const buffer = Buffer.alloc(1024 * 1024);
10947
11215
  let position = 0;
10948
11216
  while (true) {
@@ -11075,7 +11343,7 @@ class CredentialResolver {
11075
11343
  return { credentialEnv: name, source: "vault", available: true, length: Number(match[1]), sha256: match[2], providerAuthentication: "not tested" };
11076
11344
  }
11077
11345
  const value = await this.keychainRead(binding.source);
11078
- return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash9("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
11346
+ return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash10("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
11079
11347
  }
11080
11348
  }
11081
11349
  var DELIVERY_URL = "SWITCHER_CREDENTIAL_DELIVERY_URL";
@@ -11236,13 +11504,38 @@ async function fetchVaultCredential(binding, env) {
11236
11504
  await broker.stop(true);
11237
11505
  }
11238
11506
  }
11239
- var secretMetadataSchema = z7.object({
11240
- key: vaultKey,
11241
- type: z7.enum(["api_key", "password", "token", "credential", "other"]),
11242
- label: z7.string().max(1000).nullable().optional(),
11243
- expires_at: z7.string().max(200).nullable().optional(),
11244
- created_at: z7.string().max(200),
11245
- updated_at: z7.string().max(200)
11507
+ async function deliverVaultCredential() {
11508
+ const address = process.env[DELIVERY_URL];
11509
+ const nonce = process.env[DELIVERY_NONCE];
11510
+ const value = process.env[DELIVERY_VALUE];
11511
+ if (!address || !nonce || !value)
11512
+ throw new Fault(400, "credential_delivery_invalid", "Credential delivery requires an owned vault lookup.");
11513
+ let url;
11514
+ try {
11515
+ url = new URL(address);
11516
+ } catch {
11517
+ throw new Fault(400, "credential_delivery_invalid", "Invalid credential delivery address.");
11518
+ }
11519
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.pathname !== "/credential" || url.username || url.password || url.search || url.hash)
11520
+ throw new Fault(400, "credential_delivery_invalid", "Credential delivery is restricted to the owned loopback receiver.");
11521
+ try {
11522
+ const response = await fetch(url, { method: "POST", headers: { authorization: `Bearer ${nonce}`, "content-type": "application/json" }, body: JSON.stringify(value), redirect: "error", signal: AbortSignal.timeout(5000) });
11523
+ if (response.status !== 204)
11524
+ throw new Error;
11525
+ } catch {
11526
+ throw new Fault(422, "credential_delivery_failed", "The owned credential receiver was unavailable.");
11527
+ }
11528
+ }
11529
+
11530
+ // src/provider-credential-onboarding.ts
11531
+ var absent = (error) => error instanceof SwitcherError && error.status === 404;
11532
+ var secretMetadataSchema = z8.object({
11533
+ key: vaultKeySchema,
11534
+ type: z8.enum(["api_key", "password", "token", "credential", "other"]),
11535
+ label: z8.string().max(1000).nullable().optional(),
11536
+ expires_at: z8.string().max(200).nullable().optional(),
11537
+ created_at: z8.string().max(200),
11538
+ updated_at: z8.string().max(200)
11246
11539
  }).strict();
11247
11540
  var cleanDisplay = (value) => value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, "").slice(0, 500);
11248
11541
  var credentialOrigins = (provider) => {
@@ -11371,7 +11664,7 @@ async function verifyProviderAuthentication({ provider, credential, fetch: fetch
11371
11664
  throw new Fault(502, "provider_auth_unavailable", `Provider authentication check returned HTTP ${status}; the selected credential was not replaced.`);
11372
11665
  }
11373
11666
  function providerCredentialFingerprint(provider) {
11374
- return createHash9("sha256").update(JSON.stringify({
11667
+ return createHash11("sha256").update(JSON.stringify({
11375
11668
  id: provider.id,
11376
11669
  baseUrl: provider.baseUrl,
11377
11670
  protocol: provider.protocol,
@@ -11435,30 +11728,57 @@ async function ensureProviderCredential(provider, options = {}) {
11435
11728
  return preparedProviderCredential(provider, credential, { source: existing ? "binding" : "environment", configured, verified: false });
11436
11729
  }
11437
11730
  if (!result.authenticated)
11438
- throw new Fault(401, "provider_credential_rejected", `The provider rejected the selected credential${result.status ? ` with HTTP ${result.status}` : ""}. No alternate account was selected.${configured ? ` To choose a different reference, run: switcher credentials remove ${provider.credentialEnv}.` : ""}`);
11731
+ 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}.` : ""}`);
11439
11732
  return preparedProviderCredential(provider, credential, { source: existing || configured ? "binding" : "environment", configured, verified: true });
11440
11733
  }
11441
- async function deliverVaultCredential() {
11442
- const address = process.env[DELIVERY_URL];
11443
- const nonce = process.env[DELIVERY_NONCE];
11444
- const value = process.env[DELIVERY_VALUE];
11445
- if (!address || !nonce || !value)
11446
- throw new Fault(400, "credential_delivery_invalid", "Credential delivery requires an owned vault lookup.");
11447
- let url;
11448
- try {
11449
- url = new URL(address);
11450
- } catch {
11451
- throw new Fault(400, "credential_delivery_invalid", "Invalid credential delivery address.");
11734
+ function catalogRequiresCredential(provider) {
11735
+ if (provider.manualModels.length)
11736
+ return false;
11737
+ return (provider.catalogAuthStyle ?? provider.authStyle) !== "none" && Boolean(provider.catalogCredentialEnv ?? provider.credentialEnv);
11738
+ }
11739
+ async function launchCatalog(client, provider, dryRun = false, options = {}) {
11740
+ if (!dryRun && options.clientSide) {
11741
+ const origins = credentialOrigins(provider);
11742
+ const resolve9 = async (candidate) => {
11743
+ if (options.credential && candidate.credentialEnv === provider.credentialEnv && origins.includes(new URL(candidate.baseUrl).origin))
11744
+ return options.credential;
11745
+ return options.resolveCredential?.(candidate);
11746
+ };
11747
+ const catalog = await discover(provider, {}, resolve9);
11748
+ return client.saveCatalog(provider.id, provider.version, catalog);
11452
11749
  }
11453
- if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.pathname !== "/credential" || url.username || url.password || url.search || url.hash)
11454
- throw new Fault(400, "credential_delivery_invalid", "Credential delivery is restricted to the owned loopback receiver.");
11455
- try {
11456
- const response = await fetch(url, { method: "POST", headers: { authorization: `Bearer ${nonce}`, "content-type": "application/json" }, body: JSON.stringify(value), redirect: "error", signal: AbortSignal.timeout(5000) });
11457
- if (response.status !== 204)
11458
- throw new Error;
11459
- } catch {
11460
- throw new Fault(422, "credential_delivery_failed", "The owned credential receiver was unavailable.");
11750
+ if (!dryRun || !catalogRequiresCredential(provider))
11751
+ return client.refreshModels(provider.id);
11752
+ const models = [];
11753
+ let offset = 0, refreshedAt, source, total;
11754
+ for (let pageNumber = 0;pageNumber < 10; pageNumber++) {
11755
+ let page;
11756
+ try {
11757
+ page = await client.listModels(provider.id, { limit: 1000, offset });
11758
+ } catch (error) {
11759
+ if (absent(error))
11760
+ 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.`);
11761
+ throw error;
11762
+ }
11763
+ if (total === undefined) {
11764
+ total = page.total;
11765
+ refreshedAt = page.refreshedAt;
11766
+ source = page.source;
11767
+ } else if (total !== page.total || refreshedAt !== page.refreshedAt || source !== page.source)
11768
+ throw new Fault(409, "catalog_changed", "The cached catalog changed while the dry-run plan was being read; retry.");
11769
+ for (const row of page.data) {
11770
+ const { codingEligible: _codingEligible, expired: _expired, ...model3 } = row;
11771
+ models.push(model3);
11772
+ }
11773
+ offset += page.data.length;
11774
+ if (offset >= page.total)
11775
+ break;
11776
+ if (!page.data.length)
11777
+ throw new Fault(502, "invalid_catalog", "The cached catalog page did not advance.");
11461
11778
  }
11779
+ if (total === undefined || models.length !== total || !refreshedAt || !source)
11780
+ throw new Fault(502, "invalid_catalog", "The cached catalog exceeds the bounded dry-run reader or is incomplete.");
11781
+ return { models, refreshedAt, source };
11462
11782
  }
11463
11783
 
11464
11784
  // src/harness-process.ts
@@ -11986,7 +12306,7 @@ function oriLaunchWarnings(target) {
11986
12306
  }
11987
12307
 
11988
12308
  // src/chatgpt-launch.ts
11989
- import { createHash as createHash10 } from "crypto";
12309
+ import { createHash as createHash12 } from "crypto";
11990
12310
  import { writeFile as writeFile12, rm as rm4 } from "fs/promises";
11991
12311
  import { join as join14 } from "path";
11992
12312
 
@@ -12048,7 +12368,7 @@ function merge2(base, overlay) {
12048
12368
  result[key] = object5(value) && object5(result[key]) ? merge2(result[key], value) : value;
12049
12369
  return result;
12050
12370
  }
12051
- var digest = (value) => createHash10("sha256").update(value).digest("hex");
12371
+ var digest = (value) => createHash12("sha256").update(value).digest("hex");
12052
12372
  var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
12053
12373
  async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
12054
12374
  await privateDirectory(sessionDir);
@@ -12137,14 +12457,14 @@ exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
12137
12457
  }
12138
12458
 
12139
12459
  // src/claude-desktop-launch.ts
12140
- import { createHash as createHash11 } from "crypto";
12460
+ import { createHash as createHash13 } from "crypto";
12141
12461
  import { execFile as execFile5 } from "child_process";
12142
12462
  import { access as access5, rm as rm5, writeFile as writeFile13 } from "fs/promises";
12143
12463
  import { homedir as homedir8, userInfo as userInfo2 } from "os";
12144
12464
  import { join as join15 } from "path";
12145
12465
  import { promisify as promisify5 } from "util";
12146
12466
  var execute4 = promisify5(execFile5);
12147
- var hash2 = (text) => createHash11("sha256").update(text).digest("hex");
12467
+ var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
12148
12468
  var claudeDesktopDataDirectory = () => join15(homedir8(), "Library/Application Support/Claude-3p");
12149
12469
  async function assertAvailable(userData) {
12150
12470
  for (const path of [join15("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
@@ -12610,15 +12930,15 @@ async function launch(client, profileId, options = {}) {
12610
12930
  }
12611
12931
 
12612
12932
  // src/direct-launch.ts
12613
- import { createHash as createHash12 } from "crypto";
12933
+ import { createHash as createHash14 } from "crypto";
12614
12934
  import { createInterface as createInterface2 } from "readline/promises";
12615
- var absent = (error) => error instanceof SwitcherError && error.status === 404;
12935
+ var absent2 = (error) => error instanceof SwitcherError && error.status === 404;
12616
12936
  async function resolveLaunchProvider(client, selector, options = {}) {
12617
12937
  let existing;
12618
12938
  try {
12619
12939
  existing = await client.getProvider(selector);
12620
12940
  } catch (error) {
12621
- if (!absent(error))
12941
+ if (!absent2(error))
12622
12942
  throw error;
12623
12943
  }
12624
12944
  if (existing) {
@@ -12630,7 +12950,7 @@ async function resolveLaunchProvider(client, selector, options = {}) {
12630
12950
  try {
12631
12951
  existing = await client.getProvider(desired.id);
12632
12952
  } catch (error) {
12633
- if (!absent(error))
12953
+ if (!absent2(error))
12634
12954
  throw error;
12635
12955
  }
12636
12956
  if (!existing) {
@@ -12649,45 +12969,6 @@ async function resolveLaunchProvider(client, selector, options = {}) {
12649
12969
  throw new Fault(409, "provider_conflict", "A saved provider with this preset ID has different settings. Select its ID directly or update it explicitly.");
12650
12970
  return existing;
12651
12971
  }
12652
- function catalogRequiresCredential(provider) {
12653
- if (provider.manualModels.length)
12654
- return false;
12655
- return (provider.catalogAuthStyle ?? provider.authStyle) !== "none" && Boolean(provider.catalogCredentialEnv ?? provider.credentialEnv);
12656
- }
12657
- async function launchCatalog(client, provider, dryRun = false) {
12658
- if (!dryRun || !catalogRequiresCredential(provider))
12659
- return client.refreshModels(provider.id);
12660
- const models = [];
12661
- let offset = 0, refreshedAt, source, total;
12662
- for (let pageNumber = 0;pageNumber < 10; pageNumber++) {
12663
- let page;
12664
- try {
12665
- page = await client.listModels(provider.id, { limit: 1000, offset });
12666
- } catch (error) {
12667
- if (absent(error))
12668
- 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.`);
12669
- throw error;
12670
- }
12671
- if (total === undefined) {
12672
- total = page.total;
12673
- refreshedAt = page.refreshedAt;
12674
- source = page.source;
12675
- } else if (total !== page.total || refreshedAt !== page.refreshedAt || source !== page.source)
12676
- throw new Fault(409, "catalog_changed", "The cached catalog changed while the dry-run plan was being read; retry.");
12677
- for (const row of page.data) {
12678
- const { codingEligible: _codingEligible, expired: _expired, ...model3 } = row;
12679
- models.push(model3);
12680
- }
12681
- offset += page.data.length;
12682
- if (offset >= page.total)
12683
- break;
12684
- if (!page.data.length)
12685
- throw new Fault(502, "invalid_catalog", "The cached catalog page did not advance.");
12686
- }
12687
- if (total === undefined || models.length !== total || !refreshedAt || !source)
12688
- throw new Fault(502, "invalid_catalog", "The cached catalog exceeds the bounded dry-run reader or is incomplete.");
12689
- return { models, refreshedAt, source };
12690
- }
12691
12972
  var display = (value) => value.replace(/[\x00-\x1f\x7f-\x9f]/g, "");
12692
12973
  async function selectModel(models, query = "", harness) {
12693
12974
  if (!process.stdin.isTTY || !process.stderr.isTTY)
@@ -12729,13 +13010,13 @@ async function selectModel(models, query = "", harness) {
12729
13010
  async function ensureLaunchProfile(client, provider, harness, model3, modelPolicy) {
12730
13011
  const normalizedPolicy = modelPolicy === undefined ? undefined : parse2(modelPolicySchema, modelPolicy);
12731
13012
  const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
12732
- const hash3 = createHash12("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
13013
+ const hash3 = createHash14("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
12733
13014
  const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
12734
13015
  let existing;
12735
13016
  try {
12736
13017
  existing = await client.getProfile(desired.id);
12737
13018
  } catch (error) {
12738
- if (!absent(error))
13019
+ if (!absent2(error))
12739
13020
  throw error;
12740
13021
  }
12741
13022
  if (!existing) {
@@ -13058,6 +13339,13 @@ async function main(args = process.argv.slice(2)) {
13058
13339
  const runtimeEnvironment = dryLaunch ? Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("SWITCHER_PROVIDER_"))) : process.env;
13059
13340
  const runtime = await openCliRuntime(runtimeEnvironment, dryLaunch ? undefined : (provider) => credentials.resolve(provider));
13060
13341
  const client = runtime.client;
13342
+ const refreshCatalog = async (provider, prepared) => {
13343
+ if (runtime.mode !== "remote")
13344
+ return client.refreshModels(provider.id);
13345
+ const checked = prepared ?? await ensureProviderCredential(provider, { resolver: credentials });
13346
+ const credential = await checked.resolveCredential(provider);
13347
+ return launchCatalog(client, provider, false, { clientSide: true, credential, resolveCredential: (candidate) => credentials.resolve(candidate) });
13348
+ };
13061
13349
  try {
13062
13350
  const presetOptions = () => ({
13063
13351
  protocol: values2.protocol ? parse2(protocolSchema, values2.protocol) : undefined,
@@ -13104,12 +13392,13 @@ async function main(args = process.argv.slice(2)) {
13104
13392
  const modelPolicy = await readModelPolicy(values2["model-policy-file"], values2["role-model"]);
13105
13393
  const provider = await resolveLaunchProvider(client, values2.provider, { ...presetOptions(), harness });
13106
13394
  validateHarnessProvider(harness, provider);
13395
+ let prepared;
13107
13396
  if (!values2["dry-run"]) {
13108
- const prepared = await ensureProviderCredential(provider, { resolver: credentials });
13397
+ prepared = await ensureProviderCredential(provider, { resolver: credentials });
13109
13398
  credentialPreflight = prepared.providerFingerprint;
13110
13399
  resolvePreparedCredential = prepared.resolveCredential;
13111
13400
  }
13112
- const catalog = await launchCatalog(client, provider, Boolean(values2["dry-run"]));
13401
+ const catalog = values2["dry-run"] ? await launchCatalog(client, provider, true) : await refreshCatalog(provider, prepared);
13113
13402
  const model3 = values2.model ?? await selectModel(catalog.models, values2.search, harness);
13114
13403
  const selected = catalog.models.find((m) => m.id === model3);
13115
13404
  if (!selected)
@@ -13130,12 +13419,16 @@ async function main(args = process.argv.slice(2)) {
13130
13419
  const provider = await client.getProvider(profile.providerId);
13131
13420
  if (profile.harness === "gemini")
13132
13421
  validateHarnessProvider(profile.harness, provider);
13422
+ let prepared;
13133
13423
  if (!values2["dry-run"]) {
13134
- const prepared = await ensureProviderCredential(provider, { resolver: credentials });
13424
+ prepared = await ensureProviderCredential(provider, { resolver: credentials });
13135
13425
  credentialPreflight = prepared.providerFingerprint;
13136
13426
  resolvePreparedCredential = prepared.resolveCredential;
13137
13427
  }
13138
- await launchCatalog(client, provider, Boolean(values2["dry-run"]));
13428
+ if (values2["dry-run"])
13429
+ await launchCatalog(client, provider, true);
13430
+ else
13431
+ await refreshCatalog(provider, prepared);
13139
13432
  }
13140
13433
  if (values2["dry-run"]) {
13141
13434
  const plan = await client.launchPlan(profileId);
@@ -13170,13 +13463,13 @@ async function main(args = process.argv.slice(2)) {
13170
13463
  if (command === "models" && action2) {
13171
13464
  const provider = await resolveLaunchProvider(client, listingModels ? id2 : action2, presetOptions());
13172
13465
  if (values2.refresh)
13173
- await client.refreshModels(provider.id);
13466
+ await refreshCatalog(provider);
13174
13467
  try {
13175
13468
  output(await client.listModels(provider.id, page));
13176
13469
  } catch (error) {
13177
13470
  if (!(error instanceof SwitcherError && error.status === 404))
13178
13471
  throw error;
13179
- await client.refreshModels(provider.id);
13472
+ await refreshCatalog(provider);
13180
13473
  output(await client.listModels(provider.id, page));
13181
13474
  }
13182
13475
  return;
@@ -13201,7 +13494,8 @@ async function main(args = process.argv.slice(2)) {
13201
13494
  return;
13202
13495
  }
13203
13496
  if (action2 === "refresh" && id2) {
13204
- output(await client.refreshModels(id2));
13497
+ const provider = await client.getProvider(id2);
13498
+ output(await refreshCatalog(provider));
13205
13499
  return;
13206
13500
  }
13207
13501
  if (action2 === "delete" && id2) {