@hasna/switcher 0.2.3 → 0.2.5
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/Dockerfile +2 -3
- 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/serve/index.js
CHANGED
|
@@ -68,7 +68,7 @@ function canonicalPolicyJSON(value) {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
// src/domain.ts
|
|
71
|
-
var VERSION = "0.2.
|
|
71
|
+
var VERSION = "0.2.5";
|
|
72
72
|
var harnessSchema = z3.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
73
73
|
var protocolSchema = z3.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
74
74
|
var idSchema = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
@@ -265,7 +265,7 @@ class Store {
|
|
|
265
265
|
await sql?.close().catch(() => {});
|
|
266
266
|
const code = error?.code;
|
|
267
267
|
if (engine === "sqlite" && ["SQLITE_BUSY", "SQLITE_BUSY_SNAPSHOT", "SQLITE_LOCKED"].includes(code ?? "") && Date.now() < deadline) {
|
|
268
|
-
await new Promise((
|
|
268
|
+
await new Promise((resolve2) => setTimeout(resolve2, Math.min(200, 20 * (attempt + 1))));
|
|
269
269
|
continue;
|
|
270
270
|
}
|
|
271
271
|
throw new Fault(500, "storage_unavailable", "Database startup failed; check configuration, permissions and other database users.");
|
|
@@ -506,7 +506,7 @@ async function waitForCatalogRetry(delayMs, deadline) {
|
|
|
506
506
|
if (Date.now() + delayMs > deadline)
|
|
507
507
|
throw catalogDeadlineFault();
|
|
508
508
|
if (delayMs > 0)
|
|
509
|
-
await new Promise((
|
|
509
|
+
await new Promise((resolve2) => setTimeout(resolve2, delayMs));
|
|
510
510
|
}
|
|
511
511
|
async function fetchCatalogPage(url, headers, deadline) {
|
|
512
512
|
for (let retry = 0;; retry++) {
|
|
@@ -614,8 +614,8 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
614
614
|
candidate.outputModalities = capabilities.completion_chat ? ["text"] : [];
|
|
615
615
|
}
|
|
616
616
|
if (provider.catalogFormat === "together") {
|
|
617
|
-
const
|
|
618
|
-
candidate.outputModalities =
|
|
617
|
+
const modalities2 = { chat: ["text"], language: ["text"], code: ["text"], image: ["image"], audio: ["audio"], video: ["video"], embedding: ["embedding"], rerank: ["rerank"], moderation: ["classification"] };
|
|
618
|
+
candidate.outputModalities = modalities2[row.type];
|
|
619
619
|
}
|
|
620
620
|
if (provider.catalogFormat === "fireworks") {
|
|
621
621
|
if (row.supportsImageInput === true)
|
|
@@ -735,9 +735,9 @@ async function discover(provider, env = process.env, resolveCredential) {
|
|
|
735
735
|
// src/model-policy.ts
|
|
736
736
|
import { createHash as createHash2 } from "crypto";
|
|
737
737
|
var roles = ["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"];
|
|
738
|
-
var id = (v,
|
|
738
|
+
var id = (v, label2) => {
|
|
739
739
|
if (typeof v !== "string" || !v || v.length > 300 || /[\u0000-\u001f\u007f]/.test(v))
|
|
740
|
-
throw new Fault(400, "invalid_model_policy", `${
|
|
740
|
+
throw new Fault(400, "invalid_model_policy", `${label2} is invalid.`);
|
|
741
741
|
return v;
|
|
742
742
|
};
|
|
743
743
|
var uniq = (xs) => [...new Set(xs)];
|
|
@@ -808,17 +808,17 @@ var route = (protocol, baseUrl, options = {}) => ({
|
|
|
808
808
|
notes: [],
|
|
809
809
|
...options
|
|
810
810
|
});
|
|
811
|
-
var preset = (
|
|
812
|
-
id,
|
|
811
|
+
var preset = (id2, name, protocols, sources, alias) => parse(providerPresetSchema, {
|
|
812
|
+
id: id2,
|
|
813
813
|
name,
|
|
814
814
|
protocols,
|
|
815
815
|
sources,
|
|
816
816
|
credentialAliases: alias ? [alias] : [],
|
|
817
|
-
credentialEnv: alias ? `SWITCHER_PROVIDER_${
|
|
817
|
+
credentialEnv: alias ? `SWITCHER_PROVIDER_${id2.toUpperCase().replace(/-/g, "_")}` : undefined,
|
|
818
818
|
verification: "documented"
|
|
819
819
|
});
|
|
820
820
|
var providerPresets = [
|
|
821
|
-
...["opencode", "opencode-go"].map((
|
|
821
|
+
...["opencode", "opencode-go"].map((id2) => preset(id2, id2 === "opencode" ? "OpenCode Zen" : "OpenCode Go", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, id2 === "opencode" ? "https://opencode.ai/zen/v1" : "https://opencode.ai/zen/go/v1", {
|
|
822
822
|
authStyle: protocol === "anthropic-messages" ? "x-api-key" : "bearer",
|
|
823
823
|
catalogAuthStyle: "none",
|
|
824
824
|
notes: ["Discovers the full live catalog. Claude requests are adapted to each model's documented native endpoint. Other harnesses require models compatible with their selected protocol. Go requires an active subscription and coding-agent session headers."]
|
|
@@ -888,8 +888,8 @@ var providerPresets = [
|
|
|
888
888
|
preset("siliconflow", "SiliconFlow", [route("openai-chat", "https://api.siliconflow.cn/v1", { catalogBaseUrl: "https://api.siliconflow.cn/v1", catalogFormat: "openai", notes: ["The official SiliconCloud OpenAPI contract defines GET /models with Bearer auth and data[] model rows; optional type and sub_type filters are available at the upstream endpoint."] })], ["https://github.com/siliconflow/siliconcloud/blob/main/openapi.yaml", "https://docs.siliconflow.cn/docs/userguide/quickstart", "https://docs.siliconflow.cn/docs/api/chat-completions-post"], "SILICONFLOW_API_KEY"),
|
|
889
889
|
...["anthropic-messages", "openai-responses", "openai-chat"].map((protocol) => preset(`generic-${protocol}`, `Custom ${protocol}`, [route(protocol)], []))
|
|
890
890
|
];
|
|
891
|
-
function getProviderPreset(
|
|
892
|
-
const entry = providerPresets.find((p) => p.id ===
|
|
891
|
+
function getProviderPreset(id2) {
|
|
892
|
+
const entry = providerPresets.find((p) => p.id === id2);
|
|
893
893
|
if (!entry)
|
|
894
894
|
throw new Fault(404, "preset_not_found", "Unknown provider preset. Use switcher providers presets to list available presets.");
|
|
895
895
|
return structuredClone(entry);
|
|
@@ -899,7 +899,7 @@ var openapi_default = {
|
|
|
899
899
|
openapi: "3.0.3",
|
|
900
900
|
info: {
|
|
901
901
|
title: "Switcher API",
|
|
902
|
-
version: "0.2.
|
|
902
|
+
version: "0.2.5",
|
|
903
903
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
904
904
|
},
|
|
905
905
|
security: [
|
|
@@ -5091,12 +5091,12 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5091
5091
|
const json = (body, status = 200) => Response.json(body, { status, headers: { "x-request-id": requestId, "cache-control": "no-store", "x-content-type-options": "nosniff" } });
|
|
5092
5092
|
try {
|
|
5093
5093
|
const url = new URL(request.url);
|
|
5094
|
-
const
|
|
5095
|
-
if (request.method === "GET" &&
|
|
5094
|
+
const route2 = url.pathname.replace(/\/$/, "");
|
|
5095
|
+
if (request.method === "GET" && route2 === "/health")
|
|
5096
5096
|
return json({ status: "ok", version: VERSION, backend: store.engine });
|
|
5097
|
-
if (request.method === "GET" &&
|
|
5097
|
+
if (request.method === "GET" && route2 === "/version")
|
|
5098
5098
|
return json({ version: VERSION });
|
|
5099
|
-
if (request.method === "GET" &&
|
|
5099
|
+
if (request.method === "GET" && route2 === "/ready") {
|
|
5100
5100
|
try {
|
|
5101
5101
|
await store.ready();
|
|
5102
5102
|
return json({ status: "ready", version: VERSION, backend: store.engine });
|
|
@@ -5104,7 +5104,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5104
5104
|
return json({ status: "unavailable", version: VERSION, backend: store.engine, reason: "Storage is unavailable." }, 503);
|
|
5105
5105
|
}
|
|
5106
5106
|
}
|
|
5107
|
-
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(
|
|
5107
|
+
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route2))
|
|
5108
5108
|
return json(openapi_default);
|
|
5109
5109
|
if (expected) {
|
|
5110
5110
|
const presented = hash(localApiKey(request.headers));
|
|
@@ -5112,17 +5112,17 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5112
5112
|
throw new Fault(401, "unauthorized", "A valid API key is required.");
|
|
5113
5113
|
} else {
|
|
5114
5114
|
const requiredScopes = [request.method === "GET" || request.method === "HEAD" ? "switcher:read" : "switcher:write"];
|
|
5115
|
-
const decision = await verifier.authenticate(request.headers, { method: request.method, path:
|
|
5115
|
+
const decision = await verifier.authenticate(request.headers, { method: request.method, path: route2, requiredScopes });
|
|
5116
5116
|
if (!decision.ok)
|
|
5117
5117
|
throw new Fault(decision.status, `auth_${decision.reason}`, decision.message);
|
|
5118
5118
|
}
|
|
5119
|
-
const parts =
|
|
5119
|
+
const parts = route2.split("/").filter(Boolean);
|
|
5120
5120
|
if (parts[0] !== "v1")
|
|
5121
5121
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
5122
5122
|
const resource = parts[1];
|
|
5123
|
-
const
|
|
5124
|
-
if (
|
|
5125
|
-
parse(idSchema,
|
|
5123
|
+
const id2 = parts[2];
|
|
5124
|
+
if (id2)
|
|
5125
|
+
parse(idSchema, id2);
|
|
5126
5126
|
const page = () => parse(z4.object({
|
|
5127
5127
|
limit: z4.coerce.number().int().min(1).max(1000).default(100),
|
|
5128
5128
|
offset: z4.coerce.number().int().min(0).max(1e6).default(0),
|
|
@@ -5130,13 +5130,13 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5130
5130
|
}).strict(), Object.fromEntries(url.searchParams));
|
|
5131
5131
|
if (request.method === "GET") {
|
|
5132
5132
|
if (resource === "provider-presets" && parts.length <= 3)
|
|
5133
|
-
return json(
|
|
5133
|
+
return json(id2 ? getProviderPreset(id2) : { data: providerPresets });
|
|
5134
5134
|
if (["providers", "profiles", "runs"].includes(resource) && parts.length <= 3) {
|
|
5135
5135
|
const kind = resource;
|
|
5136
|
-
return json(
|
|
5136
|
+
return json(id2 ? await store.get(kind, id2) : await store.list(kind, page()));
|
|
5137
5137
|
}
|
|
5138
|
-
if (resource === "providers" &&
|
|
5139
|
-
const catalog = await store.get("catalogs",
|
|
5138
|
+
if (resource === "providers" && id2 && parts[3] === "models" && parts.length === 4) {
|
|
5139
|
+
const catalog = await store.get("catalogs", id2);
|
|
5140
5140
|
const p = page();
|
|
5141
5141
|
const filtered = catalog.models.filter((m) => [m.id, m.name].some((s) => s.toLowerCase().includes(p.search.toLowerCase())));
|
|
5142
5142
|
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 });
|
|
@@ -5158,7 +5158,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5158
5158
|
throw new Fault(400, "invalid_json", "Request must contain valid JSON under 1 MiB.");
|
|
5159
5159
|
}
|
|
5160
5160
|
}
|
|
5161
|
-
const fingerprint = hash(JSON.stringify([request.method,
|
|
5161
|
+
const fingerprint = hash(JSON.stringify([request.method, route2, body, request.headers.get("if-match")])).toString("hex");
|
|
5162
5162
|
const version = () => {
|
|
5163
5163
|
const v = request.headers.get("if-match");
|
|
5164
5164
|
if (!v || !/^[1-9]\d*$/.test(v))
|
|
@@ -5167,55 +5167,55 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5167
5167
|
};
|
|
5168
5168
|
const replay = await store.replay(key, fingerprint);
|
|
5169
5169
|
if (replay.found)
|
|
5170
|
-
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
5170
|
+
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
|
|
5171
5171
|
let refreshed;
|
|
5172
|
-
if (!expected && resource === "providers" &&
|
|
5172
|
+
if (!expected && resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST")
|
|
5173
5173
|
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.");
|
|
5174
|
-
if (resource === "providers" &&
|
|
5174
|
+
if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
5175
5175
|
parse(z4.object({}).strict(), body);
|
|
5176
|
-
const provider = await store.get("providers",
|
|
5176
|
+
const provider = await store.get("providers", id2);
|
|
5177
5177
|
refreshed = { provider, catalog: await discover(provider, providerEnv, resolveCredential) };
|
|
5178
5178
|
}
|
|
5179
5179
|
const result = await store.mutate(key, fingerprint, async (db) => {
|
|
5180
5180
|
if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
|
|
5181
|
-
if (request.method === "DELETE" &&
|
|
5182
|
-
return store.remove(resource,
|
|
5183
|
-
if (request.method === "POST" && !
|
|
5181
|
+
if (request.method === "DELETE" && id2)
|
|
5182
|
+
return store.remove(resource, id2, version(), db);
|
|
5183
|
+
if (request.method === "POST" && !id2 || request.method === "PUT" && id2) {
|
|
5184
5184
|
const value = resource === "providers" ? parse(providerInputSchema, body) : parse(profileInputSchema, body);
|
|
5185
|
-
if (
|
|
5185
|
+
if (id2 && value.id !== id2)
|
|
5186
5186
|
throw new Fault(400, "id_mismatch", "Path and body IDs must match.");
|
|
5187
5187
|
if (resource === "profiles") {
|
|
5188
5188
|
const profile = value;
|
|
5189
5189
|
const provider = await store.get("providers", profile.providerId, db);
|
|
5190
5190
|
validateHarnessProvider(profile.harness, provider);
|
|
5191
5191
|
}
|
|
5192
|
-
const saved = await store.put(resource, value,
|
|
5193
|
-
if (resource === "providers" &&
|
|
5194
|
-
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [
|
|
5192
|
+
const saved = await store.put(resource, value, id2 ? version() : undefined, db);
|
|
5193
|
+
if (resource === "providers" && id2)
|
|
5194
|
+
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id2]);
|
|
5195
5195
|
return saved;
|
|
5196
5196
|
}
|
|
5197
5197
|
}
|
|
5198
|
-
if (resource === "providers" &&
|
|
5198
|
+
if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
5199
5199
|
if (store.engine === "postgresql")
|
|
5200
|
-
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [
|
|
5201
|
-
const provider = await store.get("providers",
|
|
5200
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id2]);
|
|
5201
|
+
const provider = await store.get("providers", id2, db);
|
|
5202
5202
|
if (!refreshed || provider.version !== refreshed.provider.version)
|
|
5203
5203
|
throw new Fault(409, "provider_changed", "Provider changed during discovery; refresh again.");
|
|
5204
5204
|
const catalog = refreshed.catalog;
|
|
5205
5205
|
let old;
|
|
5206
5206
|
try {
|
|
5207
|
-
old = await store.get("catalogs",
|
|
5207
|
+
old = await store.get("catalogs", id2, db);
|
|
5208
5208
|
} catch (e) {
|
|
5209
5209
|
if (!(e instanceof Fault && e.status === 404))
|
|
5210
5210
|
throw e;
|
|
5211
5211
|
}
|
|
5212
|
-
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5212
|
+
const saved = await store.put("catalogs", { id: id2, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5213
5213
|
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
5214
5214
|
}
|
|
5215
|
-
if (resource === "providers" &&
|
|
5215
|
+
if (resource === "providers" && id2 && parts[3] === "catalog" && parts.length === 4 && request.method === "PUT") {
|
|
5216
5216
|
if (store.engine === "postgresql")
|
|
5217
|
-
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [
|
|
5218
|
-
const provider = await store.get("providers",
|
|
5217
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id2]);
|
|
5218
|
+
const provider = await store.get("providers", id2, db);
|
|
5219
5219
|
if (provider.version !== version())
|
|
5220
5220
|
throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
|
|
5221
5221
|
const catalog = parse(catalogSchema, body);
|
|
@@ -5225,15 +5225,15 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5225
5225
|
catalog.refreshedAt = new Date().toISOString();
|
|
5226
5226
|
let old;
|
|
5227
5227
|
try {
|
|
5228
|
-
old = await store.get("catalogs",
|
|
5228
|
+
old = await store.get("catalogs", id2, db);
|
|
5229
5229
|
} catch (error) {
|
|
5230
5230
|
if (!(error instanceof Fault && error.status === 404))
|
|
5231
5231
|
throw error;
|
|
5232
5232
|
}
|
|
5233
|
-
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5233
|
+
const saved = await store.put("catalogs", { id: id2, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
5234
5234
|
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
5235
5235
|
}
|
|
5236
|
-
if (resource === "launch-plans" && !
|
|
5236
|
+
if (resource === "launch-plans" && !id2 && request.method === "POST") {
|
|
5237
5237
|
const { profileId } = parse(z4.object({ profileId: idSchema }).strict(), body);
|
|
5238
5238
|
const profile = await store.get("profiles", profileId, db);
|
|
5239
5239
|
const provider = await store.get("providers", profile.providerId, db);
|
|
@@ -5266,7 +5266,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5266
5266
|
warnings.push("Catalog snapshot is older than five minutes; refresh before launching.");
|
|
5267
5267
|
return { profile, provider, catalog, warnings, planToken: snapshot(profile, provider, catalog) };
|
|
5268
5268
|
}
|
|
5269
|
-
if (resource === "runs" && !
|
|
5269
|
+
if (resource === "runs" && !id2 && request.method === "POST") {
|
|
5270
5270
|
if (body?.modelPolicyVersion !== 1)
|
|
5271
5271
|
throw new Fault(409, "launcher_upgrade_required", "This API requires a launcher with automatic model policy version 1; upgrade the Switcher CLI/SDK.");
|
|
5272
5272
|
const input = parse(runInputSchema, body);
|
|
@@ -5291,16 +5291,16 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
5291
5291
|
compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
|
|
5292
5292
|
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);
|
|
5293
5293
|
}
|
|
5294
|
-
if (resource === "runs" &&
|
|
5294
|
+
if (resource === "runs" && id2 && request.method === "PATCH" && parts.length === 3) {
|
|
5295
5295
|
const input = parse(runUpdateSchema, body);
|
|
5296
|
-
const run = await store.get("runs",
|
|
5296
|
+
const run = await store.get("runs", id2, db);
|
|
5297
5297
|
if (run.status !== "running")
|
|
5298
5298
|
throw new Fault(409, "run_finished", "Run has already finished.");
|
|
5299
5299
|
return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
|
|
5300
5300
|
}
|
|
5301
5301
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
5302
5302
|
});
|
|
5303
|
-
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
5303
|
+
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
|
|
5304
5304
|
} catch (error) {
|
|
5305
5305
|
const safe = error instanceof Fault ? error : new Fault(500, "internal_error", "Request failed.");
|
|
5306
5306
|
return json({ error: { code: safe.code, message: safe.message, requestId } }, safe.status);
|
package/openapi.json
CHANGED
package/package.json
CHANGED