@hasna/switcher 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -0
- package/dist/catalog.d.ts +1 -0
- package/dist/claude-context.d.ts +5 -0
- package/dist/cli/index.js +542 -218
- package/dist/domain.d.ts +103 -1
- package/dist/generated/api.d.ts +47 -0
- package/dist/index.js +13 -2
- package/dist/mcp/index.js +8 -2
- package/dist/presets.d.ts +14 -0
- package/dist/provider-error.d.ts +2 -0
- package/dist/provider-stream.d.ts +17 -0
- package/dist/sdk.d.ts +74 -0
- package/dist/sdk.js +13 -2
- package/dist/serve/index.js +311 -20
- package/openapi.json +268 -2
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -499,7 +499,7 @@ function canonicalPolicyJSON(value) {
|
|
|
499
499
|
}
|
|
500
500
|
|
|
501
501
|
// src/domain.ts
|
|
502
|
-
var VERSION = "0.1.
|
|
502
|
+
var VERSION = "0.1.6";
|
|
503
503
|
var harnessSchema = z3.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
504
504
|
var protocolSchema = z3.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
505
505
|
var idSchema = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
@@ -524,11 +524,16 @@ var urlSchema = z3.string().max(2000).superRefine((v, ctx) => {
|
|
|
524
524
|
ctx.addIssue({ code: "custom", message: "Invalid endpoint URL" });
|
|
525
525
|
}
|
|
526
526
|
}).transform(endpoint);
|
|
527
|
+
var expiresOnSchema = z3.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
|
|
528
|
+
const day = new Date(`${value}T00:00:00.000Z`);
|
|
529
|
+
return Number.isFinite(day.getTime()) && day.toISOString().slice(0, 10) === value;
|
|
530
|
+
}, "Use a real calendar date in YYYY-MM-DD format.");
|
|
527
531
|
var modelSchema = z3.object({
|
|
528
532
|
id: z3.string().min(1).max(300),
|
|
529
533
|
name: label,
|
|
530
534
|
description: z3.string().max(8000).optional(),
|
|
531
535
|
available: z3.boolean().optional(),
|
|
536
|
+
expiresOn: expiresOnSchema.optional(),
|
|
532
537
|
contextWindow: z3.number().int().positive().optional(),
|
|
533
538
|
maxOutputTokens: z3.number().int().positive().optional(),
|
|
534
539
|
inputModalities: z3.array(z3.string().max(50)).max(20).optional(),
|
|
@@ -549,7 +554,8 @@ var providerInputSchema = z3.object({
|
|
|
549
554
|
catalogCredentialEnv: envRef.optional(),
|
|
550
555
|
catalogAccountId: z3.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).optional(),
|
|
551
556
|
modelsPath: z3.string().regex(/^[a-zA-Z0-9_/-]+$/).max(200).default("models"),
|
|
552
|
-
manualModels: z3.array(modelSchema).max(1e4).default([])
|
|
557
|
+
manualModels: z3.array(modelSchema).max(1e4).default([]),
|
|
558
|
+
additionalModels: z3.array(modelSchema).max(1e4).optional()
|
|
553
559
|
}).strict().refine((p) => !p.modelsPath.split("/").includes("..") && !p.modelsPath.startsWith("/"), "modelsPath must be relative");
|
|
554
560
|
var providerPresetSchema = z3.object({
|
|
555
561
|
id: idSchema,
|
|
@@ -632,11 +638,14 @@ function validateHarnessProvider(harness, provider) {
|
|
|
632
638
|
if (harness === "gemini" && provider.authStyle !== "x-api-key")
|
|
633
639
|
throw new Fault(422, "auth_mismatch", "Gemini CLI requires x-api-key authentication for its native generateContent protocol.");
|
|
634
640
|
}
|
|
641
|
+
function modelExpired(model, now = new Date) {
|
|
642
|
+
return model.expiresOn !== undefined && now.toISOString().slice(0, 10) > model.expiresOn;
|
|
643
|
+
}
|
|
635
644
|
function codingEligible(model) {
|
|
636
|
-
return model.available !== false && (!model.supportedGenerationMethods || model.supportedGenerationMethods.includes("generateContent")) && (!model.outputModalities || model.outputModalities.includes("text")) && (!model.supportedParameters || model.supportedParameters.includes("tools"));
|
|
645
|
+
return !modelExpired(model) && model.available !== false && (!model.supportedGenerationMethods || model.supportedGenerationMethods.includes("generateContent")) && (!model.outputModalities || model.outputModalities.includes("text")) && (!model.supportedParameters || model.supportedParameters.includes("tools"));
|
|
637
646
|
}
|
|
638
647
|
function harnessEligible(model, harness) {
|
|
639
|
-
return harness === "aider" ? model.available !== false && (!model.supportedGenerationMethods || model.supportedGenerationMethods.includes("generateContent")) && (!model.inputModalities || model.inputModalities.includes("text")) && (!model.outputModalities || model.outputModalities.includes("text")) : codingEligible(model);
|
|
648
|
+
return !modelExpired(model) && (harness === "aider" ? model.available !== false && (!model.supportedGenerationMethods || model.supportedGenerationMethods.includes("generateContent")) && (!model.inputModalities || model.inputModalities.includes("text")) && (!model.outputModalities || model.outputModalities.includes("text")) : codingEligible(model));
|
|
640
649
|
}
|
|
641
650
|
|
|
642
651
|
// src/kilo.ts
|
|
@@ -1155,7 +1164,12 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
1155
1164
|
catalogAuthStyle: options.catalogAuthStyle ?? selected.catalogAuthStyle,
|
|
1156
1165
|
catalogFormat: options.catalogFormat ?? selected.catalogFormat,
|
|
1157
1166
|
catalogAccountId: options.catalogAccountId,
|
|
1158
|
-
modelsPath: options.modelsPath ?? selected.modelsPath
|
|
1167
|
+
modelsPath: options.modelsPath ?? selected.modelsPath,
|
|
1168
|
+
additionalModels: presetId === "deepseek" && new URL(baseUrl).origin === "https://api.deepseek.com" ? [{
|
|
1169
|
+
id: "deepseek-v4.1-flash-expires-on-0910",
|
|
1170
|
+
name: "DeepSeek V4.1 Flash preview",
|
|
1171
|
+
expiresOn: "2026-09-10"
|
|
1172
|
+
}] : []
|
|
1159
1173
|
});
|
|
1160
1174
|
}
|
|
1161
1175
|
function providerCredential(provider, env = process.env) {
|
|
@@ -1358,6 +1372,133 @@ function clientFromEnv(env = process.env, options = {}) {
|
|
|
1358
1372
|
return SwitcherClient.fromEnvironment(env, options);
|
|
1359
1373
|
}
|
|
1360
1374
|
|
|
1375
|
+
// src/provider-stream.ts
|
|
1376
|
+
function terminalEventObserver(protocol, contentType) {
|
|
1377
|
+
const enabled = contentType?.split(";", 1)[0].trim().toLowerCase() === "text/event-stream";
|
|
1378
|
+
const decoder = new TextDecoder;
|
|
1379
|
+
let line = "", data = [], size = 0, overflow = false, afterCR = false, complete = false;
|
|
1380
|
+
const dispatchLine = () => {
|
|
1381
|
+
if (!line) {
|
|
1382
|
+
if (!overflow && data.length) {
|
|
1383
|
+
const payload = data.join(`
|
|
1384
|
+
`);
|
|
1385
|
+
if (protocol === "openai-chat")
|
|
1386
|
+
complete ||= payload === "[DONE]";
|
|
1387
|
+
else
|
|
1388
|
+
try {
|
|
1389
|
+
const value = JSON.parse(payload);
|
|
1390
|
+
complete ||= protocol === "anthropic-messages" ? value?.type === "message_stop" : protocol === "openai-responses" && ["response.completed", "response.failed", "response.incomplete"].includes(value?.type);
|
|
1391
|
+
} catch {}
|
|
1392
|
+
}
|
|
1393
|
+
data = [];
|
|
1394
|
+
size = 0;
|
|
1395
|
+
overflow = false;
|
|
1396
|
+
} else if (!overflow && line.startsWith("data:"))
|
|
1397
|
+
data.push(line.slice(5).replace(/^ /, ""));
|
|
1398
|
+
line = "";
|
|
1399
|
+
};
|
|
1400
|
+
return (chunk) => {
|
|
1401
|
+
if (!enabled || protocol === "gemini-generate-content")
|
|
1402
|
+
return false;
|
|
1403
|
+
for (const char of decoder.decode(chunk, { stream: true })) {
|
|
1404
|
+
if (afterCR && char === `
|
|
1405
|
+
`) {
|
|
1406
|
+
afterCR = false;
|
|
1407
|
+
continue;
|
|
1408
|
+
}
|
|
1409
|
+
afterCR = char === "\r";
|
|
1410
|
+
if (char === "\r" || char === `
|
|
1411
|
+
`)
|
|
1412
|
+
dispatchLine();
|
|
1413
|
+
else if (++size <= 131072)
|
|
1414
|
+
line += char;
|
|
1415
|
+
else {
|
|
1416
|
+
overflow = true;
|
|
1417
|
+
line = "oversized";
|
|
1418
|
+
}
|
|
1419
|
+
}
|
|
1420
|
+
return complete;
|
|
1421
|
+
};
|
|
1422
|
+
}
|
|
1423
|
+
function proxyProviderStream(input) {
|
|
1424
|
+
const reader = input.response.body.getReader();
|
|
1425
|
+
const terminal = terminalEventObserver(input.protocol, input.response.headers.get("content-type"));
|
|
1426
|
+
let ended = false, output;
|
|
1427
|
+
const end = (error) => {
|
|
1428
|
+
if (ended)
|
|
1429
|
+
return;
|
|
1430
|
+
ended = true;
|
|
1431
|
+
try {
|
|
1432
|
+
if (error)
|
|
1433
|
+
output.error(error);
|
|
1434
|
+
else
|
|
1435
|
+
output.close();
|
|
1436
|
+
} catch {}
|
|
1437
|
+
input.release();
|
|
1438
|
+
};
|
|
1439
|
+
const cancelReader = async () => {
|
|
1440
|
+
input.abort.abort();
|
|
1441
|
+
try {
|
|
1442
|
+
await reader.cancel();
|
|
1443
|
+
} catch {}
|
|
1444
|
+
};
|
|
1445
|
+
const stream = new ReadableStream({
|
|
1446
|
+
start(controller) {
|
|
1447
|
+
output = controller;
|
|
1448
|
+
},
|
|
1449
|
+
async pull(controller) {
|
|
1450
|
+
try {
|
|
1451
|
+
const chunk = await reader.read();
|
|
1452
|
+
if (ended)
|
|
1453
|
+
return;
|
|
1454
|
+
if (chunk.done) {
|
|
1455
|
+
input.inspect?.(new Uint8Array, true);
|
|
1456
|
+
end();
|
|
1457
|
+
return;
|
|
1458
|
+
}
|
|
1459
|
+
input.inspect?.(chunk.value);
|
|
1460
|
+
const complete = terminal(chunk.value);
|
|
1461
|
+
controller.enqueue(chunk.value);
|
|
1462
|
+
if (complete) {
|
|
1463
|
+
end();
|
|
1464
|
+
await cancelReader();
|
|
1465
|
+
}
|
|
1466
|
+
} catch {
|
|
1467
|
+
if (ended)
|
|
1468
|
+
return;
|
|
1469
|
+
if (input.requestSignal.aborted || input.abort.signal.aborted || input.closing())
|
|
1470
|
+
end();
|
|
1471
|
+
else {
|
|
1472
|
+
input.interrupted?.();
|
|
1473
|
+
end(new Error("Provider stream ended unexpectedly"));
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
},
|
|
1477
|
+
async cancel() {
|
|
1478
|
+
if (!ended) {
|
|
1479
|
+
ended = true;
|
|
1480
|
+
input.release();
|
|
1481
|
+
}
|
|
1482
|
+
await cancelReader();
|
|
1483
|
+
}
|
|
1484
|
+
});
|
|
1485
|
+
return { stream, cancel: async () => {
|
|
1486
|
+
end();
|
|
1487
|
+
await cancelReader();
|
|
1488
|
+
} };
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
// src/claude-context.ts
|
|
1492
|
+
function claudeContextEnvironment(providerBaseUrl, environment = process.env) {
|
|
1493
|
+
const explicit = environment.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
|
|
1494
|
+
if (explicit !== undefined)
|
|
1495
|
+
return { CLAUDE_CODE_AUTO_COMPACT_WINDOW: explicit };
|
|
1496
|
+
const provider = new URL(providerBaseUrl);
|
|
1497
|
+
if (provider.origin === "https://api.deepseek.com" && /^\/anthropic(?:\/v1)?\/?$/.test(provider.pathname))
|
|
1498
|
+
return { CLAUDE_CODE_AUTO_COMPACT_WINDOW: "786432" };
|
|
1499
|
+
return {};
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1361
1502
|
// src/opencode-model-policy.ts
|
|
1362
1503
|
var routeForAgent = (agent) => {
|
|
1363
1504
|
const name = agent.name.toLowerCase();
|
|
@@ -1677,7 +1818,7 @@ async function fetchCatalogPage(url, headers, deadline) {
|
|
|
1677
1818
|
await waitForCatalogRetry(delay ?? 100 * 2 ** retry, deadline);
|
|
1678
1819
|
}
|
|
1679
1820
|
}
|
|
1680
|
-
async function
|
|
1821
|
+
async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
1681
1822
|
const refreshedAt = new Date().toISOString();
|
|
1682
1823
|
if (provider.manualModels.length)
|
|
1683
1824
|
return { models: provider.manualModels, source: "manual", refreshedAt };
|
|
@@ -1735,6 +1876,7 @@ async function discover(provider, env = process.env, resolveCredential) {
|
|
|
1735
1876
|
id,
|
|
1736
1877
|
name: row.displayName ?? row.name ?? row.display_name ?? id,
|
|
1737
1878
|
available: provider.catalogFormat === "mistral" && typeof row.archived === "boolean" ? !row.archived : undefined,
|
|
1879
|
+
expiresOn: row.expiresOn ?? row.expires_on,
|
|
1738
1880
|
description: typeof row.description === "string" ? row.description.slice(0, 8000) : undefined,
|
|
1739
1881
|
contextWindow: positive(row.context_length ?? row.context_window ?? row.contextLength ?? row.inputTokenLimit ?? row.model_info?.context_window ?? (provider.catalogFormat === "mistral" ? row.max_context_length : undefined)),
|
|
1740
1882
|
maxOutputTokens: positive(row.top_provider?.max_completion_tokens ?? row.max_output_tokens ?? row.outputTokenLimit ?? row.model_info?.max_output_tokens),
|
|
@@ -1861,6 +2003,15 @@ async function discover(provider, env = process.env, resolveCredential) {
|
|
|
1861
2003
|
}
|
|
1862
2004
|
throw new Fault(502, "catalog_too_large", "Provider catalog pagination exceeded 100 pages.");
|
|
1863
2005
|
}
|
|
2006
|
+
async function discover(provider, env = process.env, resolveCredential) {
|
|
2007
|
+
const catalog = await discoverBase(provider, env, resolveCredential);
|
|
2008
|
+
const models = new Map(catalog.models.map((model) => [model.id, model]));
|
|
2009
|
+
for (const additional of provider.additionalModels ?? [])
|
|
2010
|
+
models.set(additional.id, { ...models.get(additional.id), ...additional });
|
|
2011
|
+
if (models.size > 1e4)
|
|
2012
|
+
throw new Fault(502, "catalog_too_large", "Combined catalog exceeds 10,000 models.");
|
|
2013
|
+
return { ...catalog, models: [...models.values()] };
|
|
2014
|
+
}
|
|
1864
2015
|
|
|
1865
2016
|
// src/model-policy.ts
|
|
1866
2017
|
import { createHash as createHash2 } from "crypto";
|
|
@@ -1876,9 +2027,15 @@ function stable(value) {
|
|
|
1876
2027
|
}
|
|
1877
2028
|
function compileModelPolicy(model, catalog, policy) {
|
|
1878
2029
|
const selected = id(model, "model");
|
|
1879
|
-
const available = new Set(catalog.filter((m) => m.available !== false).map((m) => m.id));
|
|
1880
|
-
|
|
1881
|
-
|
|
2030
|
+
const available = new Set(catalog.filter((m) => m.available !== false && !modelExpired(m)).map((m) => m.id));
|
|
2031
|
+
const expired = new Set(catalog.filter((m) => modelExpired(m)).map((m) => m.id));
|
|
2032
|
+
const requireAvailable = (value, message) => {
|
|
2033
|
+
if (expired.has(value))
|
|
2034
|
+
throw new Fault(422, "model_expired", "A selected model has passed its configured expiry date. Select an unexpired model.");
|
|
2035
|
+
if (!available.has(value))
|
|
2036
|
+
throw new Fault(422, "model_unavailable", message);
|
|
2037
|
+
};
|
|
2038
|
+
requireAvailable(selected, "Selected model is not present in the eligible catalog.");
|
|
1882
2039
|
if (policy && policy.version !== undefined && policy.version !== 1)
|
|
1883
2040
|
throw new Fault(400, "invalid_model_policy", "Unsupported model policy version.");
|
|
1884
2041
|
const p = parse2(modelPolicySchema, policy ?? {});
|
|
@@ -1887,14 +2044,12 @@ function compileModelPolicy(model, catalog, policy) {
|
|
|
1887
2044
|
throw new Fault(400, "invalid_model_policy", "Unknown model policy role.");
|
|
1888
2045
|
const compiledRoles = Object.fromEntries(roles.map((role) => [role, id(roleInput[role] ?? selected, `roles.${role}`)]));
|
|
1889
2046
|
for (const value of Object.values(compiledRoles))
|
|
1890
|
-
|
|
1891
|
-
throw new Fault(422, "model_unavailable", "A model policy role is not present in the eligible catalog.");
|
|
2047
|
+
requireAvailable(value, "A model policy role is not present in the eligible catalog.");
|
|
1892
2048
|
const explicitAllowed = (p.allowedModels ?? []).map((v, i) => id(v, `allowedModels[${i}]`));
|
|
1893
2049
|
if (explicitAllowed.length > 500)
|
|
1894
2050
|
throw new Fault(400, "invalid_model_policy", "Model policy allowedModels is too large.");
|
|
1895
2051
|
for (const value of explicitAllowed)
|
|
1896
|
-
|
|
1897
|
-
throw new Fault(422, "model_unavailable", "An allowed model is not present in the eligible catalog.");
|
|
2052
|
+
requireAvailable(value, "An allowed model is not present in the eligible catalog.");
|
|
1898
2053
|
const aliases = Object.create(null);
|
|
1899
2054
|
for (const [name, target] of Object.entries(p.aliases ?? {})) {
|
|
1900
2055
|
if (Object.keys(aliases).length >= 200 || !/^[A-Za-z0-9._/-]{1,120}$/.test(name) || ["__proto__", "prototype", "constructor"].includes(name))
|
|
@@ -1902,8 +2057,7 @@ function compileModelPolicy(model, catalog, policy) {
|
|
|
1902
2057
|
const canonical = id(target, `aliases.${name}`);
|
|
1903
2058
|
if (available.has(name) && name !== canonical)
|
|
1904
2059
|
throw new Fault(400, "invalid_model_policy", "A model alias cannot shadow a real model ID.");
|
|
1905
|
-
|
|
1906
|
-
throw new Fault(422, "model_unavailable", "A model alias target is not present in the eligible catalog.");
|
|
2060
|
+
requireAvailable(canonical, "A model alias target is not present in the eligible catalog.");
|
|
1907
2061
|
aliases[name] = canonical;
|
|
1908
2062
|
}
|
|
1909
2063
|
const fallbacks = Object.create(null);
|
|
@@ -1912,8 +2066,8 @@ function compileModelPolicy(model, catalog, policy) {
|
|
|
1912
2066
|
if (!allowedSources.has(source) || !available.has(source) || !Array.isArray(targets) || Object.keys(fallbacks).length >= 200 || targets.length > 20)
|
|
1913
2067
|
throw new Fault(400, "invalid_model_policy", "Fallback source or list is invalid.");
|
|
1914
2068
|
const values2 = targets.map((v, i) => id(v, `fallbacks.${source}[${i}]`));
|
|
1915
|
-
|
|
1916
|
-
|
|
2069
|
+
for (const value of values2)
|
|
2070
|
+
requireAvailable(value, "A fallback model is not present in the eligible catalog.");
|
|
1917
2071
|
if (values2.includes(source))
|
|
1918
2072
|
throw new Fault(400, "invalid_model_policy", "A model cannot fall back to itself.");
|
|
1919
2073
|
fallbacks[source] = uniq(values2);
|
|
@@ -2024,7 +2178,7 @@ var openapi_default = {
|
|
|
2024
2178
|
openapi: "3.0.3",
|
|
2025
2179
|
info: {
|
|
2026
2180
|
title: "Switcher API",
|
|
2027
|
-
version: "0.1.
|
|
2181
|
+
version: "0.1.6",
|
|
2028
2182
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2029
2183
|
},
|
|
2030
2184
|
security: [
|
|
@@ -3425,6 +3579,10 @@ var openapi_default = {
|
|
|
3425
3579
|
available: {
|
|
3426
3580
|
type: "boolean"
|
|
3427
3581
|
},
|
|
3582
|
+
expiresOn: {
|
|
3583
|
+
type: "string",
|
|
3584
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
|
|
3585
|
+
},
|
|
3428
3586
|
contextWindow: {
|
|
3429
3587
|
type: "integer",
|
|
3430
3588
|
exclusiveMinimum: true,
|
|
@@ -3477,6 +3635,84 @@ var openapi_default = {
|
|
|
3477
3635
|
},
|
|
3478
3636
|
maxItems: 1e4,
|
|
3479
3637
|
default: []
|
|
3638
|
+
},
|
|
3639
|
+
additionalModels: {
|
|
3640
|
+
type: "array",
|
|
3641
|
+
items: {
|
|
3642
|
+
type: "object",
|
|
3643
|
+
properties: {
|
|
3644
|
+
id: {
|
|
3645
|
+
type: "string",
|
|
3646
|
+
minLength: 1,
|
|
3647
|
+
maxLength: 300
|
|
3648
|
+
},
|
|
3649
|
+
name: {
|
|
3650
|
+
type: "string",
|
|
3651
|
+
minLength: 1,
|
|
3652
|
+
maxLength: 200
|
|
3653
|
+
},
|
|
3654
|
+
description: {
|
|
3655
|
+
type: "string",
|
|
3656
|
+
maxLength: 8000
|
|
3657
|
+
},
|
|
3658
|
+
available: {
|
|
3659
|
+
type: "boolean"
|
|
3660
|
+
},
|
|
3661
|
+
expiresOn: {
|
|
3662
|
+
type: "string",
|
|
3663
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
|
|
3664
|
+
},
|
|
3665
|
+
contextWindow: {
|
|
3666
|
+
type: "integer",
|
|
3667
|
+
exclusiveMinimum: true,
|
|
3668
|
+
minimum: 0
|
|
3669
|
+
},
|
|
3670
|
+
maxOutputTokens: {
|
|
3671
|
+
type: "integer",
|
|
3672
|
+
exclusiveMinimum: true,
|
|
3673
|
+
minimum: 0
|
|
3674
|
+
},
|
|
3675
|
+
inputModalities: {
|
|
3676
|
+
type: "array",
|
|
3677
|
+
items: {
|
|
3678
|
+
type: "string",
|
|
3679
|
+
maxLength: 50
|
|
3680
|
+
},
|
|
3681
|
+
maxItems: 20
|
|
3682
|
+
},
|
|
3683
|
+
outputModalities: {
|
|
3684
|
+
type: "array",
|
|
3685
|
+
items: {
|
|
3686
|
+
type: "string",
|
|
3687
|
+
maxLength: 50
|
|
3688
|
+
},
|
|
3689
|
+
maxItems: 20
|
|
3690
|
+
},
|
|
3691
|
+
supportedParameters: {
|
|
3692
|
+
type: "array",
|
|
3693
|
+
items: {
|
|
3694
|
+
type: "string",
|
|
3695
|
+
maxLength: 100
|
|
3696
|
+
},
|
|
3697
|
+
maxItems: 100
|
|
3698
|
+
},
|
|
3699
|
+
supportedGenerationMethods: {
|
|
3700
|
+
type: "array",
|
|
3701
|
+
items: {
|
|
3702
|
+
type: "string",
|
|
3703
|
+
minLength: 1,
|
|
3704
|
+
maxLength: 100
|
|
3705
|
+
},
|
|
3706
|
+
maxItems: 100
|
|
3707
|
+
}
|
|
3708
|
+
},
|
|
3709
|
+
required: [
|
|
3710
|
+
"id",
|
|
3711
|
+
"name"
|
|
3712
|
+
],
|
|
3713
|
+
additionalProperties: false
|
|
3714
|
+
},
|
|
3715
|
+
maxItems: 1e4
|
|
3480
3716
|
}
|
|
3481
3717
|
},
|
|
3482
3718
|
required: [
|
|
@@ -3587,6 +3823,10 @@ var openapi_default = {
|
|
|
3587
3823
|
available: {
|
|
3588
3824
|
type: "boolean"
|
|
3589
3825
|
},
|
|
3826
|
+
expiresOn: {
|
|
3827
|
+
type: "string",
|
|
3828
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
|
|
3829
|
+
},
|
|
3590
3830
|
contextWindow: {
|
|
3591
3831
|
type: "integer",
|
|
3592
3832
|
exclusiveMinimum: true,
|
|
@@ -3640,6 +3880,84 @@ var openapi_default = {
|
|
|
3640
3880
|
maxItems: 1e4,
|
|
3641
3881
|
default: []
|
|
3642
3882
|
},
|
|
3883
|
+
additionalModels: {
|
|
3884
|
+
type: "array",
|
|
3885
|
+
items: {
|
|
3886
|
+
type: "object",
|
|
3887
|
+
properties: {
|
|
3888
|
+
id: {
|
|
3889
|
+
type: "string",
|
|
3890
|
+
minLength: 1,
|
|
3891
|
+
maxLength: 300
|
|
3892
|
+
},
|
|
3893
|
+
name: {
|
|
3894
|
+
type: "string",
|
|
3895
|
+
minLength: 1,
|
|
3896
|
+
maxLength: 200
|
|
3897
|
+
},
|
|
3898
|
+
description: {
|
|
3899
|
+
type: "string",
|
|
3900
|
+
maxLength: 8000
|
|
3901
|
+
},
|
|
3902
|
+
available: {
|
|
3903
|
+
type: "boolean"
|
|
3904
|
+
},
|
|
3905
|
+
expiresOn: {
|
|
3906
|
+
type: "string",
|
|
3907
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
|
|
3908
|
+
},
|
|
3909
|
+
contextWindow: {
|
|
3910
|
+
type: "integer",
|
|
3911
|
+
exclusiveMinimum: true,
|
|
3912
|
+
minimum: 0
|
|
3913
|
+
},
|
|
3914
|
+
maxOutputTokens: {
|
|
3915
|
+
type: "integer",
|
|
3916
|
+
exclusiveMinimum: true,
|
|
3917
|
+
minimum: 0
|
|
3918
|
+
},
|
|
3919
|
+
inputModalities: {
|
|
3920
|
+
type: "array",
|
|
3921
|
+
items: {
|
|
3922
|
+
type: "string",
|
|
3923
|
+
maxLength: 50
|
|
3924
|
+
},
|
|
3925
|
+
maxItems: 20
|
|
3926
|
+
},
|
|
3927
|
+
outputModalities: {
|
|
3928
|
+
type: "array",
|
|
3929
|
+
items: {
|
|
3930
|
+
type: "string",
|
|
3931
|
+
maxLength: 50
|
|
3932
|
+
},
|
|
3933
|
+
maxItems: 20
|
|
3934
|
+
},
|
|
3935
|
+
supportedParameters: {
|
|
3936
|
+
type: "array",
|
|
3937
|
+
items: {
|
|
3938
|
+
type: "string",
|
|
3939
|
+
maxLength: 100
|
|
3940
|
+
},
|
|
3941
|
+
maxItems: 100
|
|
3942
|
+
},
|
|
3943
|
+
supportedGenerationMethods: {
|
|
3944
|
+
type: "array",
|
|
3945
|
+
items: {
|
|
3946
|
+
type: "string",
|
|
3947
|
+
minLength: 1,
|
|
3948
|
+
maxLength: 100
|
|
3949
|
+
},
|
|
3950
|
+
maxItems: 100
|
|
3951
|
+
}
|
|
3952
|
+
},
|
|
3953
|
+
required: [
|
|
3954
|
+
"id",
|
|
3955
|
+
"name"
|
|
3956
|
+
],
|
|
3957
|
+
additionalProperties: false
|
|
3958
|
+
},
|
|
3959
|
+
maxItems: 1e4
|
|
3960
|
+
},
|
|
3643
3961
|
version: {
|
|
3644
3962
|
type: "integer",
|
|
3645
3963
|
exclusiveMinimum: true,
|
|
@@ -3987,6 +4305,10 @@ var openapi_default = {
|
|
|
3987
4305
|
available: {
|
|
3988
4306
|
type: "boolean"
|
|
3989
4307
|
},
|
|
4308
|
+
expiresOn: {
|
|
4309
|
+
type: "string",
|
|
4310
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
|
|
4311
|
+
},
|
|
3990
4312
|
contextWindow: {
|
|
3991
4313
|
type: "integer",
|
|
3992
4314
|
exclusiveMinimum: true,
|
|
@@ -4231,6 +4553,10 @@ var openapi_default = {
|
|
|
4231
4553
|
available: {
|
|
4232
4554
|
type: "boolean"
|
|
4233
4555
|
},
|
|
4556
|
+
expiresOn: {
|
|
4557
|
+
type: "string",
|
|
4558
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
|
|
4559
|
+
},
|
|
4234
4560
|
contextWindow: {
|
|
4235
4561
|
type: "integer",
|
|
4236
4562
|
exclusiveMinimum: true,
|
|
@@ -4276,12 +4602,16 @@ var openapi_default = {
|
|
|
4276
4602
|
},
|
|
4277
4603
|
codingEligible: {
|
|
4278
4604
|
type: "boolean"
|
|
4605
|
+
},
|
|
4606
|
+
expired: {
|
|
4607
|
+
type: "boolean"
|
|
4279
4608
|
}
|
|
4280
4609
|
},
|
|
4281
4610
|
required: [
|
|
4282
4611
|
"id",
|
|
4283
4612
|
"name",
|
|
4284
|
-
"codingEligible"
|
|
4613
|
+
"codingEligible",
|
|
4614
|
+
"expired"
|
|
4285
4615
|
],
|
|
4286
4616
|
additionalProperties: false
|
|
4287
4617
|
}
|
|
@@ -4341,6 +4671,10 @@ var openapi_default = {
|
|
|
4341
4671
|
available: {
|
|
4342
4672
|
type: "boolean"
|
|
4343
4673
|
},
|
|
4674
|
+
expiresOn: {
|
|
4675
|
+
type: "string",
|
|
4676
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
|
|
4677
|
+
},
|
|
4344
4678
|
contextWindow: {
|
|
4345
4679
|
type: "integer",
|
|
4346
4680
|
exclusiveMinimum: true,
|
|
@@ -4513,6 +4847,10 @@ var openapi_default = {
|
|
|
4513
4847
|
available: {
|
|
4514
4848
|
type: "boolean"
|
|
4515
4849
|
},
|
|
4850
|
+
expiresOn: {
|
|
4851
|
+
type: "string",
|
|
4852
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
|
|
4853
|
+
},
|
|
4516
4854
|
contextWindow: {
|
|
4517
4855
|
type: "integer",
|
|
4518
4856
|
exclusiveMinimum: true,
|
|
@@ -4566,6 +4904,84 @@ var openapi_default = {
|
|
|
4566
4904
|
maxItems: 1e4,
|
|
4567
4905
|
default: []
|
|
4568
4906
|
},
|
|
4907
|
+
additionalModels: {
|
|
4908
|
+
type: "array",
|
|
4909
|
+
items: {
|
|
4910
|
+
type: "object",
|
|
4911
|
+
properties: {
|
|
4912
|
+
id: {
|
|
4913
|
+
type: "string",
|
|
4914
|
+
minLength: 1,
|
|
4915
|
+
maxLength: 300
|
|
4916
|
+
},
|
|
4917
|
+
name: {
|
|
4918
|
+
type: "string",
|
|
4919
|
+
minLength: 1,
|
|
4920
|
+
maxLength: 200
|
|
4921
|
+
},
|
|
4922
|
+
description: {
|
|
4923
|
+
type: "string",
|
|
4924
|
+
maxLength: 8000
|
|
4925
|
+
},
|
|
4926
|
+
available: {
|
|
4927
|
+
type: "boolean"
|
|
4928
|
+
},
|
|
4929
|
+
expiresOn: {
|
|
4930
|
+
type: "string",
|
|
4931
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
|
|
4932
|
+
},
|
|
4933
|
+
contextWindow: {
|
|
4934
|
+
type: "integer",
|
|
4935
|
+
exclusiveMinimum: true,
|
|
4936
|
+
minimum: 0
|
|
4937
|
+
},
|
|
4938
|
+
maxOutputTokens: {
|
|
4939
|
+
type: "integer",
|
|
4940
|
+
exclusiveMinimum: true,
|
|
4941
|
+
minimum: 0
|
|
4942
|
+
},
|
|
4943
|
+
inputModalities: {
|
|
4944
|
+
type: "array",
|
|
4945
|
+
items: {
|
|
4946
|
+
type: "string",
|
|
4947
|
+
maxLength: 50
|
|
4948
|
+
},
|
|
4949
|
+
maxItems: 20
|
|
4950
|
+
},
|
|
4951
|
+
outputModalities: {
|
|
4952
|
+
type: "array",
|
|
4953
|
+
items: {
|
|
4954
|
+
type: "string",
|
|
4955
|
+
maxLength: 50
|
|
4956
|
+
},
|
|
4957
|
+
maxItems: 20
|
|
4958
|
+
},
|
|
4959
|
+
supportedParameters: {
|
|
4960
|
+
type: "array",
|
|
4961
|
+
items: {
|
|
4962
|
+
type: "string",
|
|
4963
|
+
maxLength: 100
|
|
4964
|
+
},
|
|
4965
|
+
maxItems: 100
|
|
4966
|
+
},
|
|
4967
|
+
supportedGenerationMethods: {
|
|
4968
|
+
type: "array",
|
|
4969
|
+
items: {
|
|
4970
|
+
type: "string",
|
|
4971
|
+
minLength: 1,
|
|
4972
|
+
maxLength: 100
|
|
4973
|
+
},
|
|
4974
|
+
maxItems: 100
|
|
4975
|
+
}
|
|
4976
|
+
},
|
|
4977
|
+
required: [
|
|
4978
|
+
"id",
|
|
4979
|
+
"name"
|
|
4980
|
+
],
|
|
4981
|
+
additionalProperties: false
|
|
4982
|
+
},
|
|
4983
|
+
maxItems: 1e4
|
|
4984
|
+
},
|
|
4569
4985
|
version: {
|
|
4570
4986
|
type: "integer",
|
|
4571
4987
|
exclusiveMinimum: true,
|
|
@@ -4769,6 +5185,10 @@ var openapi_default = {
|
|
|
4769
5185
|
available: {
|
|
4770
5186
|
type: "boolean"
|
|
4771
5187
|
},
|
|
5188
|
+
expiresOn: {
|
|
5189
|
+
type: "string",
|
|
5190
|
+
pattern: "^\\d{4}-\\d{2}-\\d{2}$"
|
|
5191
|
+
},
|
|
4772
5192
|
contextWindow: {
|
|
4773
5193
|
type: "integer",
|
|
4774
5194
|
exclusiveMinimum: true,
|
|
@@ -5548,7 +5968,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5548
5968
|
const catalog = await store.get("catalogs", id2);
|
|
5549
5969
|
const p = page();
|
|
5550
5970
|
const filtered = catalog.models.filter((m) => [m.id, m.name].some((s) => s.toLowerCase().includes(p.search.toLowerCase())));
|
|
5551
|
-
return json({ ...catalog, models: undefined, data: filtered.slice(p.offset, p.offset + p.limit).map((m) => ({ ...m, codingEligible: codingEligible(m) })), total: filtered.length, ...p });
|
|
5971
|
+
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 });
|
|
5552
5972
|
}
|
|
5553
5973
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
5554
5974
|
}
|
|
@@ -5634,9 +6054,11 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5634
6054
|
const selected = catalog.models.find((m) => m.id === profile.model);
|
|
5635
6055
|
if (!selected)
|
|
5636
6056
|
throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
|
|
6057
|
+
if (modelExpired(selected))
|
|
6058
|
+
throw new Fault(422, "model_expired", "Selected model has passed its configured expiry date. Select an unexpired model.");
|
|
5637
6059
|
if (!harnessEligible(selected, profile.harness))
|
|
5638
6060
|
throw new Fault(422, "model_ineligible", "Selected model is unavailable or explicitly lacks a required generation method, text output or tool support.");
|
|
5639
|
-
compileModelPolicy(profile.model, catalog.models.filter((model) => harnessEligible(model, profile.harness)), profile.modelPolicy);
|
|
6061
|
+
compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
|
|
5640
6062
|
const warnings = [];
|
|
5641
6063
|
if (profile.harness !== "aider" && !selected.supportedParameters)
|
|
5642
6064
|
warnings.push("Provider does not declare tool capabilities; execution compatibility is unverified.");
|
|
@@ -5668,6 +6090,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5668
6090
|
}
|
|
5669
6091
|
if (profile.harness !== input.harness || profile.model !== input.model || canonicalPolicyJSON(profile.modelPolicy ?? null) !== canonicalPolicyJSON(input.modelPolicy ?? profile.modelPolicy ?? null) || snapshot(profile, provider, catalog) !== input.planToken)
|
|
5670
6092
|
throw new Fault(409, "plan_changed", "Provider, profile, model policy or catalog changed; request a fresh launch plan.");
|
|
6093
|
+
compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
|
|
5671
6094
|
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);
|
|
5672
6095
|
}
|
|
5673
6096
|
if (resource === "runs" && id2 && request.method === "PATCH" && parts.length === 3) {
|
|
@@ -6107,55 +6530,8 @@ function geminiBridge(input) {
|
|
|
6107
6530
|
release();
|
|
6108
6531
|
return new Response(null, { status: response.status });
|
|
6109
6532
|
}
|
|
6110
|
-
const
|
|
6111
|
-
|
|
6112
|
-
const end = (error) => {
|
|
6113
|
-
if (ended)
|
|
6114
|
-
return;
|
|
6115
|
-
ended = true;
|
|
6116
|
-
try {
|
|
6117
|
-
if (error && !closing)
|
|
6118
|
-
output.error(error);
|
|
6119
|
-
else
|
|
6120
|
-
output.close();
|
|
6121
|
-
} catch {}
|
|
6122
|
-
release();
|
|
6123
|
-
};
|
|
6124
|
-
const stream = new ReadableStream({
|
|
6125
|
-
start(controller) {
|
|
6126
|
-
output = controller;
|
|
6127
|
-
},
|
|
6128
|
-
async pull(controller) {
|
|
6129
|
-
try {
|
|
6130
|
-
const chunk = await reader.read();
|
|
6131
|
-
if (ended)
|
|
6132
|
-
return;
|
|
6133
|
-
if (chunk.done)
|
|
6134
|
-
end();
|
|
6135
|
-
else
|
|
6136
|
-
controller.enqueue(chunk.value);
|
|
6137
|
-
} catch {
|
|
6138
|
-
end(new Error("Provider stream ended unexpectedly"));
|
|
6139
|
-
}
|
|
6140
|
-
},
|
|
6141
|
-
async cancel() {
|
|
6142
|
-
ended = true;
|
|
6143
|
-
record2.abort.abort();
|
|
6144
|
-
try {
|
|
6145
|
-
await reader.cancel();
|
|
6146
|
-
} finally {
|
|
6147
|
-
release();
|
|
6148
|
-
}
|
|
6149
|
-
}
|
|
6150
|
-
});
|
|
6151
|
-
record2.cancel = async () => {
|
|
6152
|
-
record2.abort.abort();
|
|
6153
|
-
try {
|
|
6154
|
-
await reader.cancel();
|
|
6155
|
-
} catch {} finally {
|
|
6156
|
-
end();
|
|
6157
|
-
}
|
|
6158
|
-
};
|
|
6533
|
+
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record2.abort, closing: () => closing, release });
|
|
6534
|
+
record2.cancel = cancel;
|
|
6159
6535
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
6160
6536
|
} catch {
|
|
6161
6537
|
release();
|
|
@@ -6258,6 +6634,51 @@ function compileNativeModelPolicy(input) {
|
|
|
6258
6634
|
return { harness: input.harness, env, config, unsupportedRoles };
|
|
6259
6635
|
}
|
|
6260
6636
|
|
|
6637
|
+
// src/provider-error.ts
|
|
6638
|
+
var MAX_ERROR_BYTES = 16 * 1024;
|
|
6639
|
+
var ERROR_READ_TIMEOUT_MS = 1000;
|
|
6640
|
+
var contextCodes = new Set(["context_length_exceeded", "context_window_exceeded", "prompt_too_long"]);
|
|
6641
|
+
async function isContextOverflow(response) {
|
|
6642
|
+
if (![400, 413, 422].includes(response.status) || !response.body) {
|
|
6643
|
+
response.body?.cancel().catch(() => {
|
|
6644
|
+
return;
|
|
6645
|
+
});
|
|
6646
|
+
return false;
|
|
6647
|
+
}
|
|
6648
|
+
const reader = response.body.getReader();
|
|
6649
|
+
let timer;
|
|
6650
|
+
try {
|
|
6651
|
+
const timeout = new Promise((_, reject) => {
|
|
6652
|
+
timer = setTimeout(() => reject(new Error("provider_error_timeout")), ERROR_READ_TIMEOUT_MS);
|
|
6653
|
+
});
|
|
6654
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
6655
|
+
let bytes = 0, text = "";
|
|
6656
|
+
while (true) {
|
|
6657
|
+
const { done, value } = await Promise.race([reader.read(), timeout]);
|
|
6658
|
+
if (done)
|
|
6659
|
+
break;
|
|
6660
|
+
bytes += value.byteLength;
|
|
6661
|
+
if (bytes > MAX_ERROR_BYTES)
|
|
6662
|
+
return false;
|
|
6663
|
+
text += decoder.decode(value, { stream: true });
|
|
6664
|
+
}
|
|
6665
|
+
text += decoder.decode();
|
|
6666
|
+
const error = JSON.parse(text)?.error;
|
|
6667
|
+
if (!error || typeof error !== "object" || Array.isArray(error))
|
|
6668
|
+
return false;
|
|
6669
|
+
if ([error.code, error.type].some((code) => typeof code === "string" && contextCodes.has(code)))
|
|
6670
|
+
return true;
|
|
6671
|
+
return typeof error.message === "string" && /^(?:prompt is too long\b|(?:this model['\u2019]s )?maximum context length (?:is|has been exceeded)\b|(?:input|prompt) tokens? (?:exceed|exceeds|exceeded) (?:the )?(?:maximum|model['\u2019]s) context (?:length|window)\b)/i.test(error.message.trim());
|
|
6672
|
+
} catch {
|
|
6673
|
+
return false;
|
|
6674
|
+
} finally {
|
|
6675
|
+
clearTimeout(timer);
|
|
6676
|
+
reader.cancel().catch(() => {
|
|
6677
|
+
return;
|
|
6678
|
+
});
|
|
6679
|
+
}
|
|
6680
|
+
}
|
|
6681
|
+
|
|
6261
6682
|
// src/inference-gateway.ts
|
|
6262
6683
|
import { createHash as createHash5, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
6263
6684
|
var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
|
|
@@ -6278,7 +6699,7 @@ function createInferenceGateway(input) {
|
|
|
6278
6699
|
return fail(401, "unauthorized");
|
|
6279
6700
|
const url = new URL(request.url);
|
|
6280
6701
|
if (request.method === "GET" && url.pathname === "/v1/models" && !url.search)
|
|
6281
|
-
return Response.json({ object: "list", data: input.models.map((m) => ({ ...m, object: "model" })) });
|
|
6702
|
+
return Response.json({ object: "list", data: input.models.filter((m) => !modelExpired(m)).map((m) => ({ ...m, object: "model" })) });
|
|
6282
6703
|
const gemini = input.protocol === "gemini-generate-content";
|
|
6283
6704
|
const match = gemini ? /^\/v1beta\/models\/([^/]+):(generateContent|streamGenerateContent|countTokens)$/.exec(url.pathname) : null;
|
|
6284
6705
|
const prefix = input.protocol === "anthropic-messages" ? "/messages" : input.protocol === "openai-responses" ? "/responses" : "/chat/completions";
|
|
@@ -6315,6 +6736,8 @@ function createInferenceGateway(input) {
|
|
|
6315
6736
|
if (typeof requested !== "string")
|
|
6316
6737
|
throw new Fault(400, "model_required", "A model is required.");
|
|
6317
6738
|
resolved = resolvePolicyModel(policy, requested);
|
|
6739
|
+
if (input.models.some((model) => model.id === resolved && modelExpired(model)))
|
|
6740
|
+
throw new Fault(422, "model_expired", "Selected model has expired.");
|
|
6318
6741
|
if (gemini) {
|
|
6319
6742
|
for (const declared of [body.model, body.generateContentRequest?.model])
|
|
6320
6743
|
if (declared !== undefined && declared !== requested && declared !== `models/${requested}`)
|
|
@@ -6363,6 +6786,8 @@ function createInferenceGateway(input) {
|
|
|
6363
6786
|
if (signal.aborted)
|
|
6364
6787
|
throw new Error("aborted");
|
|
6365
6788
|
const model = candidates[attempt];
|
|
6789
|
+
if (input.models.some((entry) => entry.id === model && modelExpired(entry)))
|
|
6790
|
+
throw new Fault(422, "model_expired", "Selected model has expired.");
|
|
6366
6791
|
if (attempt) {
|
|
6367
6792
|
flush();
|
|
6368
6793
|
current = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), resolvedModel: model, decision: "fallback", reason: "explicit_transient_fallback" };
|
|
@@ -6397,17 +6822,21 @@ function createInferenceGateway(input) {
|
|
|
6397
6822
|
if (!response)
|
|
6398
6823
|
throw new Error("provider_request_failed");
|
|
6399
6824
|
if (!response.ok) {
|
|
6400
|
-
await response
|
|
6825
|
+
const overflow = await isContextOverflow(response);
|
|
6826
|
+
if (overflow)
|
|
6827
|
+
current.reason = "context_length_exceeded";
|
|
6401
6828
|
release();
|
|
6829
|
+
if (overflow)
|
|
6830
|
+
return Response.json({ type: "error", error: { type: "invalid_request_error", code: "context_length_exceeded", message: "prompt is too long: the provider context window was exceeded. Compact the conversation or start a new session." } }, { status: 400 });
|
|
6402
6831
|
return fail(response.status >= 300 && response.status < 400 ? 502 : response.status, `upstream_http_${response.status}`);
|
|
6403
6832
|
}
|
|
6404
6833
|
if (!response.body) {
|
|
6405
6834
|
release();
|
|
6406
6835
|
return new Response(null, { status: response.status });
|
|
6407
6836
|
}
|
|
6408
|
-
const
|
|
6837
|
+
const decoder = new TextDecoder;
|
|
6409
6838
|
const sse = response.headers.get("content-type")?.includes("text/event-stream");
|
|
6410
|
-
let buffer = ""
|
|
6839
|
+
let buffer = "";
|
|
6411
6840
|
const observe = (text) => {
|
|
6412
6841
|
try {
|
|
6413
6842
|
const value = JSON.parse(text);
|
|
@@ -6422,14 +6851,14 @@ function createInferenceGateway(input) {
|
|
|
6422
6851
|
const inspect = (chunk, done = false) => {
|
|
6423
6852
|
buffer += decoder.decode(chunk, { stream: !done });
|
|
6424
6853
|
if (sse) {
|
|
6425
|
-
let
|
|
6854
|
+
let end = buffer.indexOf(`
|
|
6426
6855
|
`);
|
|
6427
|
-
while (
|
|
6428
|
-
const line = buffer.slice(0,
|
|
6429
|
-
buffer = buffer.slice(
|
|
6856
|
+
while (end >= 0) {
|
|
6857
|
+
const line = buffer.slice(0, end).trim();
|
|
6858
|
+
buffer = buffer.slice(end + 1);
|
|
6430
6859
|
if (line.startsWith("data:"))
|
|
6431
6860
|
observe(line.slice(5).trim());
|
|
6432
|
-
|
|
6861
|
+
end = buffer.indexOf(`
|
|
6433
6862
|
`);
|
|
6434
6863
|
}
|
|
6435
6864
|
if (buffer.length > 131072)
|
|
@@ -6439,53 +6868,10 @@ function createInferenceGateway(input) {
|
|
|
6439
6868
|
if (done && buffer)
|
|
6440
6869
|
observe(buffer);
|
|
6441
6870
|
};
|
|
6442
|
-
const
|
|
6443
|
-
|
|
6444
|
-
return;
|
|
6445
|
-
ended = true;
|
|
6446
|
-
try {
|
|
6447
|
-
if (error && !closing)
|
|
6448
|
-
output.error(error);
|
|
6449
|
-
else
|
|
6450
|
-
output.close();
|
|
6451
|
-
} catch {}
|
|
6452
|
-
release();
|
|
6453
|
-
};
|
|
6454
|
-
const stream = new ReadableStream({ start(controller) {
|
|
6455
|
-
output = controller;
|
|
6456
|
-
}, async pull(controller) {
|
|
6457
|
-
try {
|
|
6458
|
-
const chunk = await reader.read();
|
|
6459
|
-
if (ended)
|
|
6460
|
-
return;
|
|
6461
|
-
if (chunk.done) {
|
|
6462
|
-
inspect(new Uint8Array, true);
|
|
6463
|
-
end();
|
|
6464
|
-
} else {
|
|
6465
|
-
inspect(chunk.value);
|
|
6466
|
-
controller.enqueue(chunk.value);
|
|
6467
|
-
}
|
|
6468
|
-
} catch {
|
|
6469
|
-
current.reason = "stream_interrupted";
|
|
6470
|
-
end(new Error("Provider stream ended unexpectedly"));
|
|
6471
|
-
}
|
|
6472
|
-
}, async cancel() {
|
|
6473
|
-
ended = true;
|
|
6474
|
-
abort.abort();
|
|
6475
|
-
try {
|
|
6476
|
-
await reader.cancel();
|
|
6477
|
-
} finally {
|
|
6478
|
-
release();
|
|
6479
|
-
}
|
|
6871
|
+
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort, closing: () => closing, release, inspect, interrupted: () => {
|
|
6872
|
+
current.reason = "stream_interrupted";
|
|
6480
6873
|
} });
|
|
6481
|
-
record2.cancel =
|
|
6482
|
-
abort.abort();
|
|
6483
|
-
try {
|
|
6484
|
-
await reader.cancel();
|
|
6485
|
-
} catch {} finally {
|
|
6486
|
-
end();
|
|
6487
|
-
}
|
|
6488
|
-
};
|
|
6874
|
+
record2.cancel = cancel;
|
|
6489
6875
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
6490
6876
|
} catch (error) {
|
|
6491
6877
|
if (error instanceof Fault)
|
|
@@ -7875,45 +8261,8 @@ function createHermesBridge(input) {
|
|
|
7875
8261
|
release();
|
|
7876
8262
|
return new Response(null, { status: upstream.status });
|
|
7877
8263
|
}
|
|
7878
|
-
const
|
|
7879
|
-
|
|
7880
|
-
const end = () => {
|
|
7881
|
-
if (ended)
|
|
7882
|
-
return;
|
|
7883
|
-
ended = true;
|
|
7884
|
-
release();
|
|
7885
|
-
};
|
|
7886
|
-
const stream = new ReadableStream({
|
|
7887
|
-
async pull(controller) {
|
|
7888
|
-
try {
|
|
7889
|
-
const chunk = await reader.read();
|
|
7890
|
-
if (chunk.done) {
|
|
7891
|
-
end();
|
|
7892
|
-
controller.close();
|
|
7893
|
-
} else
|
|
7894
|
-
controller.enqueue(chunk.value);
|
|
7895
|
-
} catch {
|
|
7896
|
-
end();
|
|
7897
|
-
controller.error(new Error("Provider stream ended unexpectedly"));
|
|
7898
|
-
}
|
|
7899
|
-
},
|
|
7900
|
-
async cancel() {
|
|
7901
|
-
ended = true;
|
|
7902
|
-
abortController.abort();
|
|
7903
|
-
try {
|
|
7904
|
-
await reader.cancel();
|
|
7905
|
-
} finally {
|
|
7906
|
-
release();
|
|
7907
|
-
}
|
|
7908
|
-
}
|
|
7909
|
-
});
|
|
7910
|
-
record3.cancel = async () => {
|
|
7911
|
-
abortController.abort();
|
|
7912
|
-
try {
|
|
7913
|
-
await reader.cancel();
|
|
7914
|
-
} catch {}
|
|
7915
|
-
end();
|
|
7916
|
-
};
|
|
8264
|
+
const { stream, cancel } = proxyProviderStream({ response: upstream, protocol: input.protocol, requestSignal: request.signal, abort: abortController, closing: () => closing, release });
|
|
8265
|
+
record3.cancel = cancel;
|
|
7917
8266
|
return new Response(stream, {
|
|
7918
8267
|
status: upstream.status,
|
|
7919
8268
|
headers: {
|
|
@@ -8589,56 +8938,8 @@ function grokBridge(input) {
|
|
|
8589
8938
|
release();
|
|
8590
8939
|
return new Response(null, { status: response.status });
|
|
8591
8940
|
}
|
|
8592
|
-
const
|
|
8593
|
-
|
|
8594
|
-
let output;
|
|
8595
|
-
const end = (error) => {
|
|
8596
|
-
if (ended)
|
|
8597
|
-
return;
|
|
8598
|
-
ended = true;
|
|
8599
|
-
try {
|
|
8600
|
-
if (error && !closing)
|
|
8601
|
-
output.error(error);
|
|
8602
|
-
else
|
|
8603
|
-
output.close();
|
|
8604
|
-
} catch {}
|
|
8605
|
-
release();
|
|
8606
|
-
};
|
|
8607
|
-
const stream = new ReadableStream({
|
|
8608
|
-
start(controller) {
|
|
8609
|
-
output = controller;
|
|
8610
|
-
},
|
|
8611
|
-
async pull(controller) {
|
|
8612
|
-
try {
|
|
8613
|
-
const chunk = await reader.read();
|
|
8614
|
-
if (ended)
|
|
8615
|
-
return;
|
|
8616
|
-
if (chunk.done)
|
|
8617
|
-
end();
|
|
8618
|
-
else
|
|
8619
|
-
controller.enqueue(chunk.value);
|
|
8620
|
-
} catch {
|
|
8621
|
-
end(new Error("Provider stream ended unexpectedly"));
|
|
8622
|
-
}
|
|
8623
|
-
},
|
|
8624
|
-
async cancel() {
|
|
8625
|
-
ended = true;
|
|
8626
|
-
record3.abort.abort();
|
|
8627
|
-
try {
|
|
8628
|
-
await reader.cancel();
|
|
8629
|
-
} finally {
|
|
8630
|
-
release();
|
|
8631
|
-
}
|
|
8632
|
-
}
|
|
8633
|
-
});
|
|
8634
|
-
record3.cancel = async () => {
|
|
8635
|
-
record3.abort.abort();
|
|
8636
|
-
try {
|
|
8637
|
-
await reader.cancel();
|
|
8638
|
-
} catch {} finally {
|
|
8639
|
-
end();
|
|
8640
|
-
}
|
|
8641
|
-
};
|
|
8941
|
+
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record3.abort, closing: () => closing, release });
|
|
8942
|
+
record3.cancel = cancel;
|
|
8642
8943
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
8643
8944
|
} catch {
|
|
8644
8945
|
release();
|
|
@@ -8920,6 +9221,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
8920
9221
|
if (input.harness === "claude") {
|
|
8921
9222
|
env.ANTHROPIC_BASE_URL = input.baseUrl.replace(/\/v1$/, "");
|
|
8922
9223
|
Object.assign(env, input.nativePolicy?.env);
|
|
9224
|
+
Object.assign(env, claudeContextEnvironment(providerBaseUrl));
|
|
8923
9225
|
env.ANTHROPIC_MODEL = input.model;
|
|
8924
9226
|
env.ANTHROPIC_DEFAULT_MODEL = input.model;
|
|
8925
9227
|
env.CLAUDE_CODE_SUBAGENT_MODEL = input.compiledPolicy?.roles.subagent ?? input.model;
|
|
@@ -9266,6 +9568,7 @@ async function prepareHarnessLaunch(input) {
|
|
|
9266
9568
|
if (!isAbsolute10(input.stateDir) || !isAbsolute10(input.cwd))
|
|
9267
9569
|
throw new Error("Launch state and working directories must be absolute.");
|
|
9268
9570
|
const compiledPolicy = compileModelPolicy(input.model, input.models, input.modelPolicy);
|
|
9571
|
+
input = { ...input, models: input.models.filter((model3) => !modelExpired(model3)) };
|
|
9269
9572
|
const nativePolicy = compileNativeModelPolicy({ harness: input.harness, mainModel: input.model, roles: compiledPolicy.roles, version: input.version });
|
|
9270
9573
|
const specialized = new Set(["opencode", "opencode2", "gemini", "hermes"]);
|
|
9271
9574
|
const unsupported2 = specialized.has(input.harness) ? [] : nativePolicy.unsupportedRoles.filter((role) => role !== "main" && compiledPolicy.roles[role] !== input.model);
|
|
@@ -9927,7 +10230,7 @@ async function prepareOriForPlan(plan, options) {
|
|
|
9927
10230
|
protocol: plan.provider.protocol,
|
|
9928
10231
|
authStyle: plan.provider.authStyle,
|
|
9929
10232
|
model: plan.profile.model,
|
|
9930
|
-
models: plan.catalog.models.filter((m) => harnessEligible(m, plan.profile.harness)),
|
|
10233
|
+
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
9931
10234
|
modelPolicy: plan.profile.modelPolicy,
|
|
9932
10235
|
providerId: plan.provider.id,
|
|
9933
10236
|
onRoutingEvent: options.onRoutingEvent,
|
|
@@ -10037,7 +10340,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
10037
10340
|
baseUrl: plan.provider.baseUrl,
|
|
10038
10341
|
protocol: plan.provider.protocol,
|
|
10039
10342
|
model: plan.profile.model,
|
|
10040
|
-
models: plan.catalog.models.filter((m) => harnessEligible(m, plan.profile.harness)),
|
|
10343
|
+
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
10041
10344
|
modelPolicy: plan.profile.modelPolicy,
|
|
10042
10345
|
providerId: plan.provider.id,
|
|
10043
10346
|
onRoutingEvent,
|
|
@@ -10195,7 +10498,9 @@ async function resolveLaunchProvider(client, selector, options = {}) {
|
|
|
10195
10498
|
}
|
|
10196
10499
|
}
|
|
10197
10500
|
const { version, updatedAt, ...input } = existing;
|
|
10198
|
-
|
|
10501
|
+
const { additionalModels: _savedAdditions, ...savedSettings } = parse2(providerInputSchema, input);
|
|
10502
|
+
const { additionalModels: _presetAdditions, ...presetSettings } = desired;
|
|
10503
|
+
if (JSON.stringify(savedSettings) !== JSON.stringify(presetSettings))
|
|
10199
10504
|
throw new Fault(409, "provider_conflict", "A saved provider with this preset ID has different settings. Select its ID directly or update it explicitly.");
|
|
10200
10505
|
return existing;
|
|
10201
10506
|
}
|
|
@@ -10219,7 +10524,7 @@ async function selectModel(models, query = "", harness) {
|
|
|
10219
10524
|
const matching = eligible.filter((m) => `${m.id} ${m.name}`.toLowerCase().includes(query.toLowerCase()));
|
|
10220
10525
|
const visible = matching.slice(0, 30);
|
|
10221
10526
|
console.error(`Models: ${matching.length} match${matching.length === 1 ? "" : "es"}${matching.length > 30 ? " (first 30 shown; type to narrow)" : ""}.`);
|
|
10222
|
-
visible.forEach((m, i) => console.error(` ${i + 1}. ${display(m.id)} \u2014 ${display(m.name)}`));
|
|
10527
|
+
visible.forEach((m, i) => console.error(` ${i + 1}. ${display(m.id)} \u2014 ${display(m.name)}${m.expiresOn ? ` (expires ${m.expiresOn}, inclusive UTC)` : ""}`));
|
|
10223
10528
|
const answer = (await reader.question("Model number, exact model ID, or search text (Ctrl-C cancels): ", { signal: cancellation.signal }).catch((error) => {
|
|
10224
10529
|
throw cancellation.signal.aborted ? cancellation.signal.reason : error;
|
|
10225
10530
|
})).trim();
|
|
@@ -10715,6 +11020,7 @@ var HELP = `switcher \u2014 launch a coding harness with a provider and its mode
|
|
|
10715
11020
|
switcher providers update ID --file provider.json --version N
|
|
10716
11021
|
switcher providers delete ID --version N
|
|
10717
11022
|
switcher models PROVIDER [--refresh] [--search TEXT] [--limit N]
|
|
11023
|
+
switcher models add PROVIDER MODEL [--name NAME] [--expires-on YYYY-MM-DD]
|
|
10718
11024
|
switcher profiles list|get [ID]
|
|
10719
11025
|
switcher profiles add ID --provider ID --harness HARNESS --model MODEL [--model-policy-file FILE] [--role-model ROLE=MODEL]
|
|
10720
11026
|
switcher profiles update ID --file profile.json --version N
|
|
@@ -10808,6 +11114,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
10808
11114
|
offset: { type: "string" },
|
|
10809
11115
|
"model-policy-file": { type: "string" },
|
|
10810
11116
|
"role-model": { type: "string", multiple: true },
|
|
11117
|
+
"expires-on": { type: "string" },
|
|
10811
11118
|
refresh: { type: "boolean" },
|
|
10812
11119
|
backend: { type: "string" },
|
|
10813
11120
|
cwd: { type: "string" },
|
|
@@ -10834,6 +11141,12 @@ async function main(args = process.argv.slice(2)) {
|
|
|
10834
11141
|
throw new Error("Unknown command. Run switcher --help.");
|
|
10835
11142
|
const providerFlags = ["url", "protocol", "preset", "credential-env", "auth-style", "catalog-url", "catalog-format", "catalog-auth-style", "catalog-credential-env", "catalog-account-id", "models-path"];
|
|
10836
11143
|
const provided = (names) => names.some((name) => values2[name] !== undefined);
|
|
11144
|
+
const addingModel = command === "models" && action2 === "add";
|
|
11145
|
+
if (values2["expires-on"] !== undefined && !addingModel)
|
|
11146
|
+
throw new Fault(400, "conflicting_options", "--expires-on belongs to models add.");
|
|
11147
|
+
if (addingModel && (positionals.length !== 4 || nativeArgs.length || Object.keys(values2).some((name) => !["name", "expires-on", "json"].includes(name))))
|
|
11148
|
+
throw new Fault(400, "invalid_request", "Use models add PROVIDER MODEL with optional --name and --expires-on.");
|
|
11149
|
+
const modelAddition = addingModel ? parse2(modelSchema, { id: positionals[3], name: values2.name ?? positionals[3], expiresOn: values2["expires-on"] }) : undefined;
|
|
10837
11150
|
const credentialFlags = ["vault-key", "vault-url", "vault-cli", "vault-account", "vault-operator", "keychain-service", "keychain-account", "origin"];
|
|
10838
11151
|
const credentials = new CredentialResolver;
|
|
10839
11152
|
if (command === "credentials") {
|
|
@@ -10954,6 +11267,8 @@ async function main(args = process.argv.slice(2)) {
|
|
|
10954
11267
|
const selected = catalog.models.find((m) => m.id === model3);
|
|
10955
11268
|
if (!selected)
|
|
10956
11269
|
throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
|
|
11270
|
+
if (modelExpired(selected))
|
|
11271
|
+
throw new Fault(422, "model_expired", "Selected model has passed its configured expiry date. Select an unexpired model.");
|
|
10957
11272
|
if (!harnessEligible(selected, harness))
|
|
10958
11273
|
throw new Fault(422, "model_ineligible", "Selected model explicitly lacks text output or tool support.");
|
|
10959
11274
|
profileId = (await ensureLaunchProfile(client, provider, harness, model3, modelPolicy)).id;
|
|
@@ -10980,6 +11295,15 @@ async function main(args = process.argv.slice(2)) {
|
|
|
10980
11295
|
process.exitCode = await launch(client, profileId, { backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, resolveCredential: (provider) => credentials.resolve(provider) });
|
|
10981
11296
|
return;
|
|
10982
11297
|
}
|
|
11298
|
+
if (modelAddition) {
|
|
11299
|
+
const provider = await client.getProvider(id2);
|
|
11300
|
+
const { version, updatedAt, ...input } = provider;
|
|
11301
|
+
if ((provider.additionalModels ?? []).some((model3) => model3.id === modelAddition.id))
|
|
11302
|
+
throw new Fault(409, "model_exists", "This additional model already exists. Use providers update --file to edit its metadata.");
|
|
11303
|
+
await client.updateProvider({ ...input, additionalModels: [...provider.additionalModels ?? [], modelAddition] }, version);
|
|
11304
|
+
output({ providerId: provider.id, model: modelAddition, expired: modelExpired(modelAddition) });
|
|
11305
|
+
return;
|
|
11306
|
+
}
|
|
10983
11307
|
if (command === "models" && action2) {
|
|
10984
11308
|
const provider = await resolveLaunchProvider(client, action2, presetOptions());
|
|
10985
11309
|
if (values2.refresh)
|