@hasna/switcher 0.2.3 → 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 +589 -581
- package/dist/domain.d.ts +1 -1
- package/dist/index.js +11 -11
- package/dist/mcp/index.js +62 -62
- package/dist/sdk.js +11 -11
- package/dist/serve/index.js +55 -55
- package/openapi.json +1 -1
- package/package.json +1 -1
package/dist/domain.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { type RoutingEvent } from "./model-policy-schema";
|
|
|
3
3
|
export { modelPolicySchema, routingEventSchema, routingEventsSchema } from "./model-policy-schema";
|
|
4
4
|
export type { ModelPolicy, RoutingEvent } from "./model-policy-schema";
|
|
5
5
|
export type { AuthStyle } from "./auth";
|
|
6
|
-
export declare const VERSION = "0.2.
|
|
6
|
+
export declare const VERSION = "0.2.4";
|
|
7
7
|
export declare const harnessSchema: z.ZodEnum<["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]>;
|
|
8
8
|
export declare const protocolSchema: z.ZodEnum<["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]>;
|
|
9
9
|
export declare const idSchema: z.ZodString;
|
package/dist/index.js
CHANGED
|
@@ -316,8 +316,8 @@ function getProviderPreset(id) {
|
|
|
316
316
|
return structuredClone(entry);
|
|
317
317
|
}
|
|
318
318
|
function providerFromPreset(presetId, options = {}) {
|
|
319
|
-
const
|
|
320
|
-
const selected =
|
|
319
|
+
const preset2 = getProviderPreset(presetId);
|
|
320
|
+
const selected = preset2.protocols.find((p) => (!options.protocol || p.protocol === options.protocol) && (!options.harness || compatible(options.harness, p.protocol)));
|
|
321
321
|
if (!selected)
|
|
322
322
|
throw new Fault(422, "protocol_mismatch", "This provider preset has no native protocol compatible with the requested harness. Choose an explicitly compatible gateway.");
|
|
323
323
|
const baseUrl = options.baseUrl ?? selected.baseUrl;
|
|
@@ -325,7 +325,7 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
325
325
|
throw new Fault(400, "endpoint_required", "This preset requires an explicit --url for its inference endpoint.");
|
|
326
326
|
if (presetId === "azure-openai" && !/\/openai\/v1$/.test(endpoint(baseUrl)))
|
|
327
327
|
throw new Fault(400, "invalid_url", "Azure OpenAI v1 requires an explicit endpoint ending in /openai/v1; deployment and api-version URLs are unsupported.");
|
|
328
|
-
if (options.baseUrl && selected.baseUrl && new URL(endpoint(options.baseUrl)).origin !== new URL(selected.baseUrl).origin &&
|
|
328
|
+
if (options.baseUrl && selected.baseUrl && new URL(endpoint(options.baseUrl)).origin !== new URL(selected.baseUrl).origin && preset2.credentialEnv && !options.credentialEnv)
|
|
329
329
|
throw new Fault(422, "credential_authority", "An endpoint on another origin requires an explicit --credential-env reference.");
|
|
330
330
|
const suffix = selected.protocol === "anthropic-messages" ? "messages" : selected.protocol === "openai-responses" ? "responses" : "chat";
|
|
331
331
|
if (presetId === "fireworks" && !options.catalogBaseUrl && !options.catalogAccountId)
|
|
@@ -334,11 +334,11 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
334
334
|
throw new Fault(400, "catalog_url_required", "This preset requires an explicit --catalog-url when enabling a catalog parser.");
|
|
335
335
|
const catalogBaseUrl = options.catalogBaseUrl ?? (presetId === "fireworks" && options.catalogAccountId ? `https://api.fireworks.ai/v1/accounts/${encodeURIComponent(options.catalogAccountId)}` : options.baseUrl ? undefined : selected.catalogBaseUrl);
|
|
336
336
|
return parse(providerInputSchema, {
|
|
337
|
-
id: options.id ?? `${
|
|
338
|
-
name:
|
|
337
|
+
id: options.id ?? `${preset2.id}-${suffix}`,
|
|
338
|
+
name: preset2.name,
|
|
339
339
|
baseUrl,
|
|
340
340
|
protocol: selected.protocol,
|
|
341
|
-
credentialEnv: options.credentialEnv ??
|
|
341
|
+
credentialEnv: options.credentialEnv ?? preset2.credentialEnv,
|
|
342
342
|
authStyle: options.authStyle ?? selected.authStyle,
|
|
343
343
|
credentialCheck: selected.credentialCheck,
|
|
344
344
|
catalogBaseUrl,
|
|
@@ -666,10 +666,10 @@ function clientFromEnv(env = process.env, options = {}) {
|
|
|
666
666
|
return SwitcherClient.fromEnvironment(env, options);
|
|
667
667
|
}
|
|
668
668
|
export {
|
|
669
|
-
|
|
670
|
-
SwitcherError,
|
|
671
|
-
clientFromEnv,
|
|
672
|
-
detectChatGPTApp,
|
|
669
|
+
providerFromPreset,
|
|
673
670
|
detectClaudeDesktopApp,
|
|
674
|
-
|
|
671
|
+
detectChatGPTApp,
|
|
672
|
+
clientFromEnv,
|
|
673
|
+
SwitcherError,
|
|
674
|
+
SwitcherClient
|
|
675
675
|
};
|
package/dist/mcp/index.js
CHANGED
|
@@ -69,7 +69,7 @@ function canonicalPolicyJSON(value) {
|
|
|
69
69
|
}
|
|
70
70
|
|
|
71
71
|
// src/domain.ts
|
|
72
|
-
var VERSION = "0.2.
|
|
72
|
+
var VERSION = "0.2.4";
|
|
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}$/);
|
|
@@ -362,8 +362,8 @@ function providerCredential(provider, env = process.env) {
|
|
|
362
362
|
return;
|
|
363
363
|
let value = env[provider.credentialEnv];
|
|
364
364
|
if (!value) {
|
|
365
|
-
const
|
|
366
|
-
value =
|
|
365
|
+
const preset2 = providerPresets.find((p) => p.credentialEnv === provider.credentialEnv && p.protocols.some((route2) => route2.protocol === provider.protocol && (route2.baseUrl ? new URL(route2.baseUrl).origin === new URL(provider.baseUrl).origin : p.id === "azure-openai")));
|
|
366
|
+
value = preset2?.credentialAliases.map((name) => env[name]).find(Boolean);
|
|
367
367
|
}
|
|
368
368
|
if (value && /[\r\n]/.test(value))
|
|
369
369
|
throw new Fault(422, "credential_invalid", "Provider credential contains invalid header characters.");
|
|
@@ -671,7 +671,7 @@ class Store {
|
|
|
671
671
|
await sql?.close().catch(() => {});
|
|
672
672
|
const code = error?.code;
|
|
673
673
|
if (engine === "sqlite" && ["SQLITE_BUSY", "SQLITE_BUSY_SNAPSHOT", "SQLITE_LOCKED"].includes(code ?? "") && Date.now() < deadline) {
|
|
674
|
-
await new Promise((
|
|
674
|
+
await new Promise((resolve2) => setTimeout(resolve2, Math.min(200, 20 * (attempt + 1))));
|
|
675
675
|
continue;
|
|
676
676
|
}
|
|
677
677
|
throw new Fault(500, "storage_unavailable", "Database startup failed; check configuration, permissions and other database users.");
|
|
@@ -878,7 +878,7 @@ async function waitForCatalogRetry(delayMs, deadline) {
|
|
|
878
878
|
if (Date.now() + delayMs > deadline)
|
|
879
879
|
throw catalogDeadlineFault();
|
|
880
880
|
if (delayMs > 0)
|
|
881
|
-
await new Promise((
|
|
881
|
+
await new Promise((resolve2) => setTimeout(resolve2, delayMs));
|
|
882
882
|
}
|
|
883
883
|
async function fetchCatalogPage(url, headers, deadline) {
|
|
884
884
|
for (let retry = 0;; retry++) {
|
|
@@ -986,8 +986,8 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
986
986
|
candidate.outputModalities = capabilities.completion_chat ? ["text"] : [];
|
|
987
987
|
}
|
|
988
988
|
if (provider.catalogFormat === "together") {
|
|
989
|
-
const
|
|
990
|
-
candidate.outputModalities =
|
|
989
|
+
const modalities2 = { chat: ["text"], language: ["text"], code: ["text"], image: ["image"], audio: ["audio"], video: ["video"], embedding: ["embedding"], rerank: ["rerank"], moderation: ["classification"] };
|
|
990
|
+
candidate.outputModalities = modalities2[row.type];
|
|
991
991
|
}
|
|
992
992
|
if (provider.catalogFormat === "fireworks") {
|
|
993
993
|
if (row.supportsImageInput === true)
|
|
@@ -1107,9 +1107,9 @@ async function discover(provider, env = process.env, resolveCredential) {
|
|
|
1107
1107
|
// src/model-policy.ts
|
|
1108
1108
|
import { createHash as createHash2 } from "crypto";
|
|
1109
1109
|
var roles = ["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"];
|
|
1110
|
-
var id = (v,
|
|
1110
|
+
var id = (v, label2) => {
|
|
1111
1111
|
if (typeof v !== "string" || !v || v.length > 300 || /[\u0000-\u001f\u007f]/.test(v))
|
|
1112
|
-
throw new Fault(400, "invalid_model_policy", `${
|
|
1112
|
+
throw new Fault(400, "invalid_model_policy", `${label2} is invalid.`);
|
|
1113
1113
|
return v;
|
|
1114
1114
|
};
|
|
1115
1115
|
var uniq = (xs) => [...new Set(xs)];
|
|
@@ -1174,7 +1174,7 @@ var openapi_default = {
|
|
|
1174
1174
|
openapi: "3.0.3",
|
|
1175
1175
|
info: {
|
|
1176
1176
|
title: "Switcher API",
|
|
1177
|
-
version: "0.2.
|
|
1177
|
+
version: "0.2.4",
|
|
1178
1178
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
1179
1179
|
},
|
|
1180
1180
|
security: [
|
|
@@ -5366,12 +5366,12 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5366
5366
|
const json = (body, status = 200) => Response.json(body, { status, headers: { "x-request-id": requestId, "cache-control": "no-store", "x-content-type-options": "nosniff" } });
|
|
5367
5367
|
try {
|
|
5368
5368
|
const url = new URL(request.url);
|
|
5369
|
-
const
|
|
5370
|
-
if (request.method === "GET" &&
|
|
5369
|
+
const route2 = url.pathname.replace(/\/$/, "");
|
|
5370
|
+
if (request.method === "GET" && route2 === "/health")
|
|
5371
5371
|
return json({ status: "ok", version: VERSION, backend: store.engine });
|
|
5372
|
-
if (request.method === "GET" &&
|
|
5372
|
+
if (request.method === "GET" && route2 === "/version")
|
|
5373
5373
|
return json({ version: VERSION });
|
|
5374
|
-
if (request.method === "GET" &&
|
|
5374
|
+
if (request.method === "GET" && route2 === "/ready") {
|
|
5375
5375
|
try {
|
|
5376
5376
|
await store.ready();
|
|
5377
5377
|
return json({ status: "ready", version: VERSION, backend: store.engine });
|
|
@@ -5379,7 +5379,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5379
5379
|
return json({ status: "unavailable", version: VERSION, backend: store.engine, reason: "Storage is unavailable." }, 503);
|
|
5380
5380
|
}
|
|
5381
5381
|
}
|
|
5382
|
-
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(
|
|
5382
|
+
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route2))
|
|
5383
5383
|
return json(openapi_default);
|
|
5384
5384
|
if (expected) {
|
|
5385
5385
|
const presented = hash(localApiKey(request.headers));
|
|
@@ -5387,17 +5387,17 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5387
5387
|
throw new Fault(401, "unauthorized", "A valid API key is required.");
|
|
5388
5388
|
} else {
|
|
5389
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:
|
|
5390
|
+
const decision = await verifier.authenticate(request.headers, { method: request.method, path: route2, requiredScopes });
|
|
5391
5391
|
if (!decision.ok)
|
|
5392
5392
|
throw new Fault(decision.status, `auth_${decision.reason}`, decision.message);
|
|
5393
5393
|
}
|
|
5394
|
-
const parts =
|
|
5394
|
+
const parts = route2.split("/").filter(Boolean);
|
|
5395
5395
|
if (parts[0] !== "v1")
|
|
5396
5396
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
5397
5397
|
const resource = parts[1];
|
|
5398
|
-
const
|
|
5399
|
-
if (
|
|
5400
|
-
parse(idSchema,
|
|
5398
|
+
const id2 = parts[2];
|
|
5399
|
+
if (id2)
|
|
5400
|
+
parse(idSchema, id2);
|
|
5401
5401
|
const page = () => parse(z4.object({
|
|
5402
5402
|
limit: z4.coerce.number().int().min(1).max(1000).default(100),
|
|
5403
5403
|
offset: z4.coerce.number().int().min(0).max(1e6).default(0),
|
|
@@ -5405,13 +5405,13 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5405
5405
|
}).strict(), Object.fromEntries(url.searchParams));
|
|
5406
5406
|
if (request.method === "GET") {
|
|
5407
5407
|
if (resource === "provider-presets" && parts.length <= 3)
|
|
5408
|
-
return json(
|
|
5408
|
+
return json(id2 ? getProviderPreset(id2) : { data: providerPresets });
|
|
5409
5409
|
if (["providers", "profiles", "runs"].includes(resource) && parts.length <= 3) {
|
|
5410
5410
|
const kind = resource;
|
|
5411
|
-
return json(
|
|
5411
|
+
return json(id2 ? await store.get(kind, id2) : await store.list(kind, page()));
|
|
5412
5412
|
}
|
|
5413
|
-
if (resource === "providers" &&
|
|
5414
|
-
const catalog = await store.get("catalogs",
|
|
5413
|
+
if (resource === "providers" && id2 && parts[3] === "models" && parts.length === 4) {
|
|
5414
|
+
const catalog = await store.get("catalogs", id2);
|
|
5415
5415
|
const p = page();
|
|
5416
5416
|
const filtered = catalog.models.filter((m) => [m.id, m.name].some((s) => s.toLowerCase().includes(p.search.toLowerCase())));
|
|
5417
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 });
|
|
@@ -5433,7 +5433,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5433
5433
|
throw new Fault(400, "invalid_json", "Request must contain valid JSON under 1 MiB.");
|
|
5434
5434
|
}
|
|
5435
5435
|
}
|
|
5436
|
-
const fingerprint = hash(JSON.stringify([request.method,
|
|
5436
|
+
const fingerprint = hash(JSON.stringify([request.method, route2, body, request.headers.get("if-match")])).toString("hex");
|
|
5437
5437
|
const version = () => {
|
|
5438
5438
|
const v = request.headers.get("if-match");
|
|
5439
5439
|
if (!v || !/^[1-9]\d*$/.test(v))
|
|
@@ -5442,55 +5442,55 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5442
5442
|
};
|
|
5443
5443
|
const replay = await store.replay(key, fingerprint);
|
|
5444
5444
|
if (replay.found)
|
|
5445
|
-
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
5445
|
+
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
|
|
5446
5446
|
let refreshed;
|
|
5447
|
-
if (!expected && resource === "providers" &&
|
|
5447
|
+
if (!expected && resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST")
|
|
5448
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" &&
|
|
5449
|
+
if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
5450
5450
|
parse(z4.object({}).strict(), body);
|
|
5451
|
-
const provider = await store.get("providers",
|
|
5451
|
+
const provider = await store.get("providers", id2);
|
|
5452
5452
|
refreshed = { provider, catalog: await discover(provider, providerEnv, resolveCredential) };
|
|
5453
5453
|
}
|
|
5454
5454
|
const result = await store.mutate(key, fingerprint, async (db) => {
|
|
5455
5455
|
if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
|
|
5456
|
-
if (request.method === "DELETE" &&
|
|
5457
|
-
return store.remove(resource,
|
|
5458
|
-
if (request.method === "POST" && !
|
|
5456
|
+
if (request.method === "DELETE" && id2)
|
|
5457
|
+
return store.remove(resource, id2, version(), db);
|
|
5458
|
+
if (request.method === "POST" && !id2 || request.method === "PUT" && id2) {
|
|
5459
5459
|
const value = resource === "providers" ? parse(providerInputSchema, body) : parse(profileInputSchema, body);
|
|
5460
|
-
if (
|
|
5460
|
+
if (id2 && value.id !== id2)
|
|
5461
5461
|
throw new Fault(400, "id_mismatch", "Path and body IDs must match.");
|
|
5462
5462
|
if (resource === "profiles") {
|
|
5463
5463
|
const profile = value;
|
|
5464
5464
|
const provider = await store.get("providers", profile.providerId, db);
|
|
5465
5465
|
validateHarnessProvider(profile.harness, provider);
|
|
5466
5466
|
}
|
|
5467
|
-
const saved = await store.put(resource, value,
|
|
5468
|
-
if (resource === "providers" &&
|
|
5469
|
-
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [
|
|
5467
|
+
const saved = await store.put(resource, value, id2 ? version() : undefined, db);
|
|
5468
|
+
if (resource === "providers" && id2)
|
|
5469
|
+
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id2]);
|
|
5470
5470
|
return saved;
|
|
5471
5471
|
}
|
|
5472
5472
|
}
|
|
5473
|
-
if (resource === "providers" &&
|
|
5473
|
+
if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
5474
5474
|
if (store.engine === "postgresql")
|
|
5475
|
-
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [
|
|
5476
|
-
const provider = await store.get("providers",
|
|
5475
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id2]);
|
|
5476
|
+
const provider = await store.get("providers", id2, db);
|
|
5477
5477
|
if (!refreshed || provider.version !== refreshed.provider.version)
|
|
5478
5478
|
throw new Fault(409, "provider_changed", "Provider changed during discovery; refresh again.");
|
|
5479
5479
|
const catalog = refreshed.catalog;
|
|
5480
5480
|
let old;
|
|
5481
5481
|
try {
|
|
5482
|
-
old = await store.get("catalogs",
|
|
5482
|
+
old = await store.get("catalogs", id2, db);
|
|
5483
5483
|
} catch (e) {
|
|
5484
5484
|
if (!(e instanceof Fault && e.status === 404))
|
|
5485
5485
|
throw e;
|
|
5486
5486
|
}
|
|
5487
|
-
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5487
|
+
const saved = await store.put("catalogs", { id: id2, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5488
5488
|
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
5489
5489
|
}
|
|
5490
|
-
if (resource === "providers" &&
|
|
5490
|
+
if (resource === "providers" && id2 && parts[3] === "catalog" && parts.length === 4 && request.method === "PUT") {
|
|
5491
5491
|
if (store.engine === "postgresql")
|
|
5492
|
-
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [
|
|
5493
|
-
const provider = await store.get("providers",
|
|
5492
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id2]);
|
|
5493
|
+
const provider = await store.get("providers", id2, db);
|
|
5494
5494
|
if (provider.version !== version())
|
|
5495
5495
|
throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
|
|
5496
5496
|
const catalog = parse(catalogSchema, body);
|
|
@@ -5500,15 +5500,15 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5500
5500
|
catalog.refreshedAt = new Date().toISOString();
|
|
5501
5501
|
let old;
|
|
5502
5502
|
try {
|
|
5503
|
-
old = await store.get("catalogs",
|
|
5503
|
+
old = await store.get("catalogs", id2, db);
|
|
5504
5504
|
} catch (error) {
|
|
5505
5505
|
if (!(error instanceof Fault && error.status === 404))
|
|
5506
5506
|
throw error;
|
|
5507
5507
|
}
|
|
5508
|
-
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5508
|
+
const saved = await store.put("catalogs", { id: id2, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5509
5509
|
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
5510
5510
|
}
|
|
5511
|
-
if (resource === "launch-plans" && !
|
|
5511
|
+
if (resource === "launch-plans" && !id2 && request.method === "POST") {
|
|
5512
5512
|
const { profileId } = parse(z4.object({ profileId: idSchema }).strict(), body);
|
|
5513
5513
|
const profile = await store.get("profiles", profileId, db);
|
|
5514
5514
|
const provider = await store.get("providers", profile.providerId, db);
|
|
@@ -5541,7 +5541,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5541
5541
|
warnings.push("Catalog snapshot is older than five minutes; refresh before launching.");
|
|
5542
5542
|
return { profile, provider, catalog, warnings, planToken: snapshot(profile, provider, catalog) };
|
|
5543
5543
|
}
|
|
5544
|
-
if (resource === "runs" && !
|
|
5544
|
+
if (resource === "runs" && !id2 && request.method === "POST") {
|
|
5545
5545
|
if (body?.modelPolicyVersion !== 1)
|
|
5546
5546
|
throw new Fault(409, "launcher_upgrade_required", "This API requires a launcher with automatic model policy version 1; upgrade the Switcher CLI/SDK.");
|
|
5547
5547
|
const input = parse(runInputSchema, body);
|
|
@@ -5566,16 +5566,16 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5566
5566
|
compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
|
|
5567
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);
|
|
5568
5568
|
}
|
|
5569
|
-
if (resource === "runs" &&
|
|
5569
|
+
if (resource === "runs" && id2 && request.method === "PATCH" && parts.length === 3) {
|
|
5570
5570
|
const input = parse(runUpdateSchema, body);
|
|
5571
|
-
const run = await store.get("runs",
|
|
5571
|
+
const run = await store.get("runs", id2, db);
|
|
5572
5572
|
if (run.status !== "running")
|
|
5573
5573
|
throw new Fault(409, "run_finished", "Run has already finished.");
|
|
5574
5574
|
return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
|
|
5575
5575
|
}
|
|
5576
5576
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
5577
5577
|
});
|
|
5578
|
-
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
5578
|
+
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
|
|
5579
5579
|
} catch (error) {
|
|
5580
5580
|
const safe = error instanceof Fault ? error : new Fault(500, "internal_error", "Request failed.");
|
|
5581
5581
|
return json({ error: { code: safe.code, message: safe.message, requestId } }, safe.status);
|
|
@@ -6069,8 +6069,8 @@ async function runVaultCommand(binding, args, env, delivery = {}, options = {})
|
|
|
6069
6069
|
if (process.platform === "win32")
|
|
6070
6070
|
throw new Fault(422, "vault_exec_unavailable", "Vault CLI bindings currently require POSIX process groups; use runtime environment injection on Windows.");
|
|
6071
6071
|
const executable = await validateVaultExecutable(binding.source.executable);
|
|
6072
|
-
const
|
|
6073
|
-
const childEnv = { ...
|
|
6072
|
+
const operator2 = options.operator ?? await resolveVaultOperatorEnvironment(binding, env);
|
|
6073
|
+
const childEnv = { ...operator2.environment, ...delivery };
|
|
6074
6074
|
return new Promise((resolveResult, reject) => {
|
|
6075
6075
|
const child = spawn(executable, args, { env: childEnv, stdio: ["ignore", options.captureBytes ? "pipe" : "ignore", "ignore"], detached: true, shell: false });
|
|
6076
6076
|
let failure;
|
|
@@ -6202,7 +6202,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
|
|
|
6202
6202
|
await validateVaultExecutable(vaultExecutable);
|
|
6203
6203
|
const source = { kind: "vault", key: "switcher/provider-credential-discovery", executable: vaultExecutable, operator: { kind: "contracts" } };
|
|
6204
6204
|
const provisional = parse(credentialBindingSchema, { schema: 1, credentialEnv: provider.credentialEnv, origins: credentialOrigins(provider), source });
|
|
6205
|
-
const
|
|
6205
|
+
const operator2 = await resolveVaultOperatorEnvironment(provisional, env);
|
|
6206
6206
|
const entries = new Map;
|
|
6207
6207
|
for (const query of searchTerms(provider)) {
|
|
6208
6208
|
const output = await runVaultCommand(provisional, ["search", query, "--json"], env, {}, {
|
|
@@ -6211,7 +6211,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
|
|
|
6211
6211
|
oversizeMessage: "Secrets returned too much credential metadata; narrow the vault naming or bind an exact key explicitly.",
|
|
6212
6212
|
lookupCode: "vault_search_failed",
|
|
6213
6213
|
lookupMessage: "Hasna Secrets could not search credential metadata. Check the selected vault/Keychain source; no alternate account was selected.",
|
|
6214
|
-
operator
|
|
6214
|
+
operator: operator2
|
|
6215
6215
|
});
|
|
6216
6216
|
let parsed;
|
|
6217
6217
|
try {
|
|
@@ -6227,7 +6227,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
|
|
|
6227
6227
|
if (entries.size > 256)
|
|
6228
6228
|
throw new Fault(422, "credential_matches_too_many", "More than 256 credential references matched. Bind an exact vault key explicitly.");
|
|
6229
6229
|
}
|
|
6230
|
-
return [...entries.values()].sort((a, b) => a.key.localeCompare(b.key)).map((entry) => ({ account:
|
|
6230
|
+
return [...entries.values()].sort((a, b) => a.key.localeCompare(b.key)).map((entry) => ({ account: operator2.source, key: entry.key, url: operator2.url, executable: vaultExecutable, operator: { kind: "contracts", expectedSource: operator2.source, expectedTier: operator2.tier } }));
|
|
6231
6231
|
}
|
|
6232
6232
|
async function selectVaultReference({ provider, matches }) {
|
|
6233
6233
|
if (!process.stdin.isTTY || !process.stderr.isTTY)
|
|
@@ -6332,10 +6332,10 @@ async function ensureProviderCredential(provider, options = {}) {
|
|
|
6332
6332
|
if (!credential) {
|
|
6333
6333
|
if (!(options.interactive ?? (process.stdin.isTTY && process.stderr.isTTY)))
|
|
6334
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
|
|
6335
|
+
const discover2 = options.discoverVaultReferences ?? ((request) => discoverVaultReferences(request.provider, options.env ?? process.env, options.vaultExecutable));
|
|
6336
6336
|
let matches;
|
|
6337
6337
|
try {
|
|
6338
|
-
matches = await
|
|
6338
|
+
matches = await discover2({ provider, credentialEnv: provider.credentialEnv });
|
|
6339
6339
|
} catch (error) {
|
|
6340
6340
|
if (error instanceof Fault && error.code === "vault_exec_unavailable")
|
|
6341
6341
|
throw new Fault(error.status, error.code, `${error.message} Run: ${providerCredentialSetupCommand(provider)} --vault-cli /absolute/path/to/secrets.`);
|
|
@@ -6376,12 +6376,12 @@ function catalogRequiresCredential(provider) {
|
|
|
6376
6376
|
async function launchCatalog(client, provider, dryRun = false, options = {}) {
|
|
6377
6377
|
if (!dryRun && options.clientSide) {
|
|
6378
6378
|
const origins = credentialOrigins(provider);
|
|
6379
|
-
const
|
|
6379
|
+
const resolve3 = async (candidate) => {
|
|
6380
6380
|
if (options.credential && candidate.credentialEnv === provider.credentialEnv && origins.includes(new URL(candidate.baseUrl).origin))
|
|
6381
6381
|
return options.credential;
|
|
6382
6382
|
return options.resolveCredential?.(candidate);
|
|
6383
6383
|
};
|
|
6384
|
-
const catalog = await discover(provider, {},
|
|
6384
|
+
const catalog = await discover(provider, {}, resolve3);
|
|
6385
6385
|
return client.saveCatalog(provider.id, provider.version, catalog);
|
|
6386
6386
|
}
|
|
6387
6387
|
if (!dryRun || !catalogRequiresCredential(provider))
|
|
@@ -6443,8 +6443,8 @@ tool("providers_create", "Create a provider using credential environment referen
|
|
|
6443
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
6444
|
tool("providers_delete", "Delete an unreferenced provider.", { id: z7.string(), version: z7.number().int() }, (p) => clientFromEnv2().deleteProvider(p.id, p.version));
|
|
6445
6445
|
tool("models_list", "List catalog with capability information.", { id: z7.string(), ...page }, (p) => {
|
|
6446
|
-
const { id, ...rest } = p;
|
|
6447
|
-
return clientFromEnv2().listModels(
|
|
6446
|
+
const { id: id2, ...rest } = p;
|
|
6447
|
+
return clientFromEnv2().listModels(id2, rest);
|
|
6448
6448
|
});
|
|
6449
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
6450
|
tool("models_update", "Replace all saved metadata for a configured model.", { providerId: z7.string(), model: modelSchema }, (p) => clientFromEnv2().updateModel(p.providerId, p.model));
|
package/dist/sdk.js
CHANGED
|
@@ -316,8 +316,8 @@ function getProviderPreset(id) {
|
|
|
316
316
|
return structuredClone(entry);
|
|
317
317
|
}
|
|
318
318
|
function providerFromPreset(presetId, options = {}) {
|
|
319
|
-
const
|
|
320
|
-
const selected =
|
|
319
|
+
const preset2 = getProviderPreset(presetId);
|
|
320
|
+
const selected = preset2.protocols.find((p) => (!options.protocol || p.protocol === options.protocol) && (!options.harness || compatible(options.harness, p.protocol)));
|
|
321
321
|
if (!selected)
|
|
322
322
|
throw new Fault(422, "protocol_mismatch", "This provider preset has no native protocol compatible with the requested harness. Choose an explicitly compatible gateway.");
|
|
323
323
|
const baseUrl = options.baseUrl ?? selected.baseUrl;
|
|
@@ -325,7 +325,7 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
325
325
|
throw new Fault(400, "endpoint_required", "This preset requires an explicit --url for its inference endpoint.");
|
|
326
326
|
if (presetId === "azure-openai" && !/\/openai\/v1$/.test(endpoint(baseUrl)))
|
|
327
327
|
throw new Fault(400, "invalid_url", "Azure OpenAI v1 requires an explicit endpoint ending in /openai/v1; deployment and api-version URLs are unsupported.");
|
|
328
|
-
if (options.baseUrl && selected.baseUrl && new URL(endpoint(options.baseUrl)).origin !== new URL(selected.baseUrl).origin &&
|
|
328
|
+
if (options.baseUrl && selected.baseUrl && new URL(endpoint(options.baseUrl)).origin !== new URL(selected.baseUrl).origin && preset2.credentialEnv && !options.credentialEnv)
|
|
329
329
|
throw new Fault(422, "credential_authority", "An endpoint on another origin requires an explicit --credential-env reference.");
|
|
330
330
|
const suffix = selected.protocol === "anthropic-messages" ? "messages" : selected.protocol === "openai-responses" ? "responses" : "chat";
|
|
331
331
|
if (presetId === "fireworks" && !options.catalogBaseUrl && !options.catalogAccountId)
|
|
@@ -334,11 +334,11 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
334
334
|
throw new Fault(400, "catalog_url_required", "This preset requires an explicit --catalog-url when enabling a catalog parser.");
|
|
335
335
|
const catalogBaseUrl = options.catalogBaseUrl ?? (presetId === "fireworks" && options.catalogAccountId ? `https://api.fireworks.ai/v1/accounts/${encodeURIComponent(options.catalogAccountId)}` : options.baseUrl ? undefined : selected.catalogBaseUrl);
|
|
336
336
|
return parse(providerInputSchema, {
|
|
337
|
-
id: options.id ?? `${
|
|
338
|
-
name:
|
|
337
|
+
id: options.id ?? `${preset2.id}-${suffix}`,
|
|
338
|
+
name: preset2.name,
|
|
339
339
|
baseUrl,
|
|
340
340
|
protocol: selected.protocol,
|
|
341
|
-
credentialEnv: options.credentialEnv ??
|
|
341
|
+
credentialEnv: options.credentialEnv ?? preset2.credentialEnv,
|
|
342
342
|
authStyle: options.authStyle ?? selected.authStyle,
|
|
343
343
|
credentialCheck: selected.credentialCheck,
|
|
344
344
|
catalogBaseUrl,
|
|
@@ -666,10 +666,10 @@ function clientFromEnv(env = process.env, options = {}) {
|
|
|
666
666
|
return SwitcherClient.fromEnvironment(env, options);
|
|
667
667
|
}
|
|
668
668
|
export {
|
|
669
|
-
|
|
670
|
-
SwitcherError,
|
|
671
|
-
clientFromEnv,
|
|
672
|
-
detectChatGPTApp,
|
|
669
|
+
providerFromPreset,
|
|
673
670
|
detectClaudeDesktopApp,
|
|
674
|
-
|
|
671
|
+
detectChatGPTApp,
|
|
672
|
+
clientFromEnv,
|
|
673
|
+
SwitcherError,
|
|
674
|
+
SwitcherClient
|
|
675
675
|
};
|