@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/cli/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
+
var __require = import.meta.require;
|
|
3
4
|
|
|
4
5
|
// src/kilo.ts
|
|
5
6
|
import { createHash } from "crypto";
|
|
@@ -187,8 +188,8 @@ async function kiloSettings(cwd, stateDir, env = process.env, options = {}) {
|
|
|
187
188
|
const out = {};
|
|
188
189
|
if (own(v, "tools")) {
|
|
189
190
|
const tools = record(v.tools, path, "tools permission");
|
|
190
|
-
for (const
|
|
191
|
-
if (typeof
|
|
191
|
+
for (const enabled2 of Object.values(tools))
|
|
192
|
+
if (typeof enabled2 !== "boolean")
|
|
192
193
|
invalid(path, "tools permission");
|
|
193
194
|
out.tools = tools;
|
|
194
195
|
}
|
|
@@ -513,7 +514,7 @@ function canonicalPolicyJSON(value) {
|
|
|
513
514
|
}
|
|
514
515
|
|
|
515
516
|
// src/domain.ts
|
|
516
|
-
var VERSION = "0.2.
|
|
517
|
+
var VERSION = "0.2.4";
|
|
517
518
|
var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
518
519
|
var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
519
520
|
var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
@@ -995,8 +996,8 @@ function assertHarnessArguments(harness, args, options = {}) {
|
|
|
995
996
|
if (arg.startsWith("--") || !short[harness]) {
|
|
996
997
|
if (harness === "codex" && flag === "--config")
|
|
997
998
|
config(equals < 0 ? args[i + 1] ?? "" : arg.slice(equals + 1));
|
|
998
|
-
const
|
|
999
|
-
if (equals < 0 && (
|
|
999
|
+
const required2 = values[harness].includes(flag) && !(harness === "hermes" && hermesChat && flag === "--oneshot") && !(harness === "opencode" && args[i + 1]?.startsWith("-"));
|
|
1000
|
+
if (equals < 0 && (required2 || optionalValues[harness]?.includes(flag) && args[i + 1] !== undefined && !args[i + 1].startsWith("-")))
|
|
1000
1001
|
i++;
|
|
1001
1002
|
continue;
|
|
1002
1003
|
}
|
|
@@ -1161,8 +1162,8 @@ function getProviderPreset(id) {
|
|
|
1161
1162
|
return structuredClone(entry);
|
|
1162
1163
|
}
|
|
1163
1164
|
function providerFromPreset(presetId, options = {}) {
|
|
1164
|
-
const
|
|
1165
|
-
const selected =
|
|
1165
|
+
const preset2 = getProviderPreset(presetId);
|
|
1166
|
+
const selected = preset2.protocols.find((p) => (!options.protocol || p.protocol === options.protocol) && (!options.harness || compatible(options.harness, p.protocol)));
|
|
1166
1167
|
if (!selected)
|
|
1167
1168
|
throw new Fault(422, "protocol_mismatch", "This provider preset has no native protocol compatible with the requested harness. Choose an explicitly compatible gateway.");
|
|
1168
1169
|
const baseUrl = options.baseUrl ?? selected.baseUrl;
|
|
@@ -1170,7 +1171,7 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
1170
1171
|
throw new Fault(400, "endpoint_required", "This preset requires an explicit --url for its inference endpoint.");
|
|
1171
1172
|
if (presetId === "azure-openai" && !/\/openai\/v1$/.test(endpoint(baseUrl)))
|
|
1172
1173
|
throw new Fault(400, "invalid_url", "Azure OpenAI v1 requires an explicit endpoint ending in /openai/v1; deployment and api-version URLs are unsupported.");
|
|
1173
|
-
if (options.baseUrl && selected.baseUrl && new URL(endpoint(options.baseUrl)).origin !== new URL(selected.baseUrl).origin &&
|
|
1174
|
+
if (options.baseUrl && selected.baseUrl && new URL(endpoint(options.baseUrl)).origin !== new URL(selected.baseUrl).origin && preset2.credentialEnv && !options.credentialEnv)
|
|
1174
1175
|
throw new Fault(422, "credential_authority", "An endpoint on another origin requires an explicit --credential-env reference.");
|
|
1175
1176
|
const suffix = selected.protocol === "anthropic-messages" ? "messages" : selected.protocol === "openai-responses" ? "responses" : "chat";
|
|
1176
1177
|
if (presetId === "fireworks" && !options.catalogBaseUrl && !options.catalogAccountId)
|
|
@@ -1179,11 +1180,11 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
1179
1180
|
throw new Fault(400, "catalog_url_required", "This preset requires an explicit --catalog-url when enabling a catalog parser.");
|
|
1180
1181
|
const catalogBaseUrl = options.catalogBaseUrl ?? (presetId === "fireworks" && options.catalogAccountId ? `https://api.fireworks.ai/v1/accounts/${encodeURIComponent(options.catalogAccountId)}` : options.baseUrl ? undefined : selected.catalogBaseUrl);
|
|
1181
1182
|
return parse2(providerInputSchema, {
|
|
1182
|
-
id: options.id ?? `${
|
|
1183
|
-
name:
|
|
1183
|
+
id: options.id ?? `${preset2.id}-${suffix}`,
|
|
1184
|
+
name: preset2.name,
|
|
1184
1185
|
baseUrl,
|
|
1185
1186
|
protocol: selected.protocol,
|
|
1186
|
-
credentialEnv: options.credentialEnv ??
|
|
1187
|
+
credentialEnv: options.credentialEnv ?? preset2.credentialEnv,
|
|
1187
1188
|
authStyle: options.authStyle ?? selected.authStyle,
|
|
1188
1189
|
credentialCheck: selected.credentialCheck,
|
|
1189
1190
|
catalogBaseUrl,
|
|
@@ -1206,8 +1207,8 @@ function providerCredential(provider, env = process.env) {
|
|
|
1206
1207
|
return;
|
|
1207
1208
|
let value = env[provider.credentialEnv];
|
|
1208
1209
|
if (!value) {
|
|
1209
|
-
const
|
|
1210
|
-
value =
|
|
1210
|
+
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")));
|
|
1211
|
+
value = preset2?.credentialAliases.map((name) => env[name]).find(Boolean);
|
|
1211
1212
|
}
|
|
1212
1213
|
if (value && /[\r\n]/.test(value))
|
|
1213
1214
|
throw new Fault(422, "credential_invalid", "Provider credential contains invalid header characters.");
|
|
@@ -1319,13 +1320,13 @@ class SwitcherError extends Error {
|
|
|
1319
1320
|
}
|
|
1320
1321
|
}
|
|
1321
1322
|
function apiError(status, data, apiKey) {
|
|
1322
|
-
const
|
|
1323
|
-
const error =
|
|
1323
|
+
const object2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1324
|
+
const error = object2(data) && object2(data.error) ? data.error : {};
|
|
1324
1325
|
const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1325
1326
|
const base64 = Buffer.from(apiKey, "utf8").toString("base64");
|
|
1326
|
-
const
|
|
1327
|
+
const literal2 = [apiKey, JSON.stringify(apiKey).slice(1, -1), base64, base64.replace(/=+$/, ""), Buffer.from(apiKey, "utf8").toString("base64url")];
|
|
1327
1328
|
const encoded = [encodeURIComponent(apiKey), new URLSearchParams({ key: apiKey }).toString().slice(4)];
|
|
1328
|
-
const patterns = [...new Set(
|
|
1329
|
+
const patterns = [...new Set(literal2)].sort((a, b) => b.length - a.length).map(escape);
|
|
1329
1330
|
for (const value of encoded) {
|
|
1330
1331
|
patterns.unshift(escape(value).replace(/%[0-9A-F]{2}/g, (part) => part.replace(/[A-F]/g, (letter) => `[${letter}${letter.toLowerCase()}]`)));
|
|
1331
1332
|
}
|
|
@@ -1756,7 +1757,7 @@ function compileOpenCodeModelPolicy(input) {
|
|
|
1756
1757
|
}
|
|
1757
1758
|
function openCodeInvocationModel(args, policy, defaultAgent) {
|
|
1758
1759
|
let name = defaultAgent;
|
|
1759
|
-
const
|
|
1760
|
+
const values2 = new Set(["--session", "--prompt", "--agent", "--format", "--file", "--title", "--command", "--variant", "--log-level", "--replay-limit", "--completions", "-s", "-f"]);
|
|
1760
1761
|
for (let i = 0;i < args.length; i++) {
|
|
1761
1762
|
const arg = args[i];
|
|
1762
1763
|
if (arg === "--")
|
|
@@ -1765,7 +1766,7 @@ function openCodeInvocationModel(args, policy, defaultAgent) {
|
|
|
1765
1766
|
name = arg.slice(8);
|
|
1766
1767
|
continue;
|
|
1767
1768
|
}
|
|
1768
|
-
if (
|
|
1769
|
+
if (values2.has(arg)) {
|
|
1769
1770
|
if (arg === "--agent")
|
|
1770
1771
|
name = args[i + 1];
|
|
1771
1772
|
i++;
|
|
@@ -1841,7 +1842,7 @@ class Store {
|
|
|
1841
1842
|
await sql?.close().catch(() => {});
|
|
1842
1843
|
const code = error?.code;
|
|
1843
1844
|
if (engine === "sqlite" && ["SQLITE_BUSY", "SQLITE_BUSY_SNAPSHOT", "SQLITE_LOCKED"].includes(code ?? "") && Date.now() < deadline) {
|
|
1844
|
-
await new Promise((
|
|
1845
|
+
await new Promise((resolve3) => setTimeout(resolve3, Math.min(200, 20 * (attempt + 1))));
|
|
1845
1846
|
continue;
|
|
1846
1847
|
}
|
|
1847
1848
|
throw new Fault(500, "storage_unavailable", "Database startup failed; check configuration, permissions and other database users.");
|
|
@@ -2048,7 +2049,7 @@ async function waitForCatalogRetry(delayMs, deadline) {
|
|
|
2048
2049
|
if (Date.now() + delayMs > deadline)
|
|
2049
2050
|
throw catalogDeadlineFault();
|
|
2050
2051
|
if (delayMs > 0)
|
|
2051
|
-
await new Promise((
|
|
2052
|
+
await new Promise((resolve3) => setTimeout(resolve3, delayMs));
|
|
2052
2053
|
}
|
|
2053
2054
|
async function fetchCatalogPage(url, headers, deadline) {
|
|
2054
2055
|
for (let retry = 0;; retry++) {
|
|
@@ -2156,8 +2157,8 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
2156
2157
|
candidate.outputModalities = capabilities.completion_chat ? ["text"] : [];
|
|
2157
2158
|
}
|
|
2158
2159
|
if (provider.catalogFormat === "together") {
|
|
2159
|
-
const
|
|
2160
|
-
candidate.outputModalities =
|
|
2160
|
+
const modalities2 = { chat: ["text"], language: ["text"], code: ["text"], image: ["image"], audio: ["audio"], video: ["video"], embedding: ["embedding"], rerank: ["rerank"], moderation: ["classification"] };
|
|
2161
|
+
candidate.outputModalities = modalities2[row.type];
|
|
2161
2162
|
}
|
|
2162
2163
|
if (provider.catalogFormat === "fireworks") {
|
|
2163
2164
|
if (row.supportsImageInput === true)
|
|
@@ -2277,9 +2278,9 @@ async function discover(provider, env = process.env, resolveCredential) {
|
|
|
2277
2278
|
// src/model-policy.ts
|
|
2278
2279
|
import { createHash as createHash3 } from "crypto";
|
|
2279
2280
|
var roles = ["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"];
|
|
2280
|
-
var id = (v,
|
|
2281
|
+
var id = (v, label2) => {
|
|
2281
2282
|
if (typeof v !== "string" || !v || v.length > 300 || /[\u0000-\u001f\u007f]/.test(v))
|
|
2282
|
-
throw new Fault(400, "invalid_model_policy", `${
|
|
2283
|
+
throw new Fault(400, "invalid_model_policy", `${label2} is invalid.`);
|
|
2283
2284
|
return v;
|
|
2284
2285
|
};
|
|
2285
2286
|
var uniq = (xs) => [...new Set(xs)];
|
|
@@ -2326,12 +2327,12 @@ function compileModelPolicy(model, catalog, policy) {
|
|
|
2326
2327
|
for (const [source, targets] of Object.entries(p.fallbacks ?? {})) {
|
|
2327
2328
|
if (!allowedSources.has(source) || !available.has(source) || !Array.isArray(targets) || Object.keys(fallbacks).length >= 200 || targets.length > 20)
|
|
2328
2329
|
throw new Fault(400, "invalid_model_policy", "Fallback source or list is invalid.");
|
|
2329
|
-
const
|
|
2330
|
-
for (const value of
|
|
2330
|
+
const values2 = targets.map((v, i) => id(v, `fallbacks.${source}[${i}]`));
|
|
2331
|
+
for (const value of values2)
|
|
2331
2332
|
requireAvailable(value, "A fallback model is not present in the eligible catalog.");
|
|
2332
|
-
if (
|
|
2333
|
+
if (values2.includes(source))
|
|
2333
2334
|
throw new Fault(400, "invalid_model_policy", "A model cannot fall back to itself.");
|
|
2334
|
-
fallbacks[source] = uniq(
|
|
2335
|
+
fallbacks[source] = uniq(values2);
|
|
2335
2336
|
}
|
|
2336
2337
|
const allowedModels = uniq([selected, ...Object.values(compiledRoles), ...explicitAllowed, ...Object.values(fallbacks).flat()]).sort();
|
|
2337
2338
|
if (Object.values(aliases).some((value) => !allowedModels.includes(value)))
|
|
@@ -2439,7 +2440,7 @@ var openapi_default = {
|
|
|
2439
2440
|
openapi: "3.0.3",
|
|
2440
2441
|
info: {
|
|
2441
2442
|
title: "Switcher API",
|
|
2442
|
-
version: "0.2.
|
|
2443
|
+
version: "0.2.4",
|
|
2443
2444
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2444
2445
|
},
|
|
2445
2446
|
security: [
|
|
@@ -6631,12 +6632,12 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6631
6632
|
const json = (body, status = 200) => Response.json(body, { status, headers: { "x-request-id": requestId, "cache-control": "no-store", "x-content-type-options": "nosniff" } });
|
|
6632
6633
|
try {
|
|
6633
6634
|
const url = new URL(request.url);
|
|
6634
|
-
const
|
|
6635
|
-
if (request.method === "GET" &&
|
|
6635
|
+
const route2 = url.pathname.replace(/\/$/, "");
|
|
6636
|
+
if (request.method === "GET" && route2 === "/health")
|
|
6636
6637
|
return json({ status: "ok", version: VERSION, backend: store.engine });
|
|
6637
|
-
if (request.method === "GET" &&
|
|
6638
|
+
if (request.method === "GET" && route2 === "/version")
|
|
6638
6639
|
return json({ version: VERSION });
|
|
6639
|
-
if (request.method === "GET" &&
|
|
6640
|
+
if (request.method === "GET" && route2 === "/ready") {
|
|
6640
6641
|
try {
|
|
6641
6642
|
await store.ready();
|
|
6642
6643
|
return json({ status: "ready", version: VERSION, backend: store.engine });
|
|
@@ -6644,7 +6645,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6644
6645
|
return json({ status: "unavailable", version: VERSION, backend: store.engine, reason: "Storage is unavailable." }, 503);
|
|
6645
6646
|
}
|
|
6646
6647
|
}
|
|
6647
|
-
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(
|
|
6648
|
+
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route2))
|
|
6648
6649
|
return json(openapi_default);
|
|
6649
6650
|
if (expected) {
|
|
6650
6651
|
const presented = hash(localApiKey(request.headers));
|
|
@@ -6652,17 +6653,17 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6652
6653
|
throw new Fault(401, "unauthorized", "A valid API key is required.");
|
|
6653
6654
|
} else {
|
|
6654
6655
|
const requiredScopes = [request.method === "GET" || request.method === "HEAD" ? "switcher:read" : "switcher:write"];
|
|
6655
|
-
const decision = await verifier.authenticate(request.headers, { method: request.method, path:
|
|
6656
|
+
const decision = await verifier.authenticate(request.headers, { method: request.method, path: route2, requiredScopes });
|
|
6656
6657
|
if (!decision.ok)
|
|
6657
6658
|
throw new Fault(decision.status, `auth_${decision.reason}`, decision.message);
|
|
6658
6659
|
}
|
|
6659
|
-
const parts =
|
|
6660
|
+
const parts = route2.split("/").filter(Boolean);
|
|
6660
6661
|
if (parts[0] !== "v1")
|
|
6661
6662
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
6662
6663
|
const resource = parts[1];
|
|
6663
|
-
const
|
|
6664
|
-
if (
|
|
6665
|
-
parse2(idSchema,
|
|
6664
|
+
const id2 = parts[2];
|
|
6665
|
+
if (id2)
|
|
6666
|
+
parse2(idSchema, id2);
|
|
6666
6667
|
const page = () => parse2(z5.object({
|
|
6667
6668
|
limit: z5.coerce.number().int().min(1).max(1000).default(100),
|
|
6668
6669
|
offset: z5.coerce.number().int().min(0).max(1e6).default(0),
|
|
@@ -6670,13 +6671,13 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6670
6671
|
}).strict(), Object.fromEntries(url.searchParams));
|
|
6671
6672
|
if (request.method === "GET") {
|
|
6672
6673
|
if (resource === "provider-presets" && parts.length <= 3)
|
|
6673
|
-
return json(
|
|
6674
|
+
return json(id2 ? getProviderPreset(id2) : { data: providerPresets });
|
|
6674
6675
|
if (["providers", "profiles", "runs"].includes(resource) && parts.length <= 3) {
|
|
6675
6676
|
const kind = resource;
|
|
6676
|
-
return json(
|
|
6677
|
+
return json(id2 ? await store.get(kind, id2) : await store.list(kind, page()));
|
|
6677
6678
|
}
|
|
6678
|
-
if (resource === "providers" &&
|
|
6679
|
-
const catalog = await store.get("catalogs",
|
|
6679
|
+
if (resource === "providers" && id2 && parts[3] === "models" && parts.length === 4) {
|
|
6680
|
+
const catalog = await store.get("catalogs", id2);
|
|
6680
6681
|
const p = page();
|
|
6681
6682
|
const filtered = catalog.models.filter((m) => [m.id, m.name].some((s) => s.toLowerCase().includes(p.search.toLowerCase())));
|
|
6682
6683
|
return json({ ...catalog, providerVersion: undefined, providerFingerprint: undefined, models: undefined, data: filtered.slice(p.offset, p.offset + p.limit).map((m) => ({ ...m, codingEligible: codingEligible(m), expired: modelExpired(m) })), total: filtered.length, ...p });
|
|
@@ -6698,7 +6699,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6698
6699
|
throw new Fault(400, "invalid_json", "Request must contain valid JSON under 1 MiB.");
|
|
6699
6700
|
}
|
|
6700
6701
|
}
|
|
6701
|
-
const fingerprint = hash(JSON.stringify([request.method,
|
|
6702
|
+
const fingerprint = hash(JSON.stringify([request.method, route2, body, request.headers.get("if-match")])).toString("hex");
|
|
6702
6703
|
const version = () => {
|
|
6703
6704
|
const v = request.headers.get("if-match");
|
|
6704
6705
|
if (!v || !/^[1-9]\d*$/.test(v))
|
|
@@ -6707,55 +6708,55 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6707
6708
|
};
|
|
6708
6709
|
const replay = await store.replay(key, fingerprint);
|
|
6709
6710
|
if (replay.found)
|
|
6710
|
-
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
6711
|
+
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
|
|
6711
6712
|
let refreshed;
|
|
6712
|
-
if (!expected && resource === "providers" &&
|
|
6713
|
+
if (!expected && resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST")
|
|
6713
6714
|
throw new Fault(422, "local_catalog_refresh_required", "Hosted Switcher never contacts provider URLs. Refresh with the local CLI or MCP client, which authenticates locally and commits catalog metadata only.");
|
|
6714
|
-
if (resource === "providers" &&
|
|
6715
|
+
if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
6715
6716
|
parse2(z5.object({}).strict(), body);
|
|
6716
|
-
const provider = await store.get("providers",
|
|
6717
|
+
const provider = await store.get("providers", id2);
|
|
6717
6718
|
refreshed = { provider, catalog: await discover(provider, providerEnv, resolveCredential) };
|
|
6718
6719
|
}
|
|
6719
6720
|
const result = await store.mutate(key, fingerprint, async (db) => {
|
|
6720
6721
|
if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
|
|
6721
|
-
if (request.method === "DELETE" &&
|
|
6722
|
-
return store.remove(resource,
|
|
6723
|
-
if (request.method === "POST" && !
|
|
6722
|
+
if (request.method === "DELETE" && id2)
|
|
6723
|
+
return store.remove(resource, id2, version(), db);
|
|
6724
|
+
if (request.method === "POST" && !id2 || request.method === "PUT" && id2) {
|
|
6724
6725
|
const value = resource === "providers" ? parse2(providerInputSchema, body) : parse2(profileInputSchema, body);
|
|
6725
|
-
if (
|
|
6726
|
+
if (id2 && value.id !== id2)
|
|
6726
6727
|
throw new Fault(400, "id_mismatch", "Path and body IDs must match.");
|
|
6727
6728
|
if (resource === "profiles") {
|
|
6728
6729
|
const profile = value;
|
|
6729
6730
|
const provider = await store.get("providers", profile.providerId, db);
|
|
6730
6731
|
validateHarnessProvider(profile.harness, provider);
|
|
6731
6732
|
}
|
|
6732
|
-
const saved = await store.put(resource, value,
|
|
6733
|
-
if (resource === "providers" &&
|
|
6734
|
-
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [
|
|
6733
|
+
const saved = await store.put(resource, value, id2 ? version() : undefined, db);
|
|
6734
|
+
if (resource === "providers" && id2)
|
|
6735
|
+
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id2]);
|
|
6735
6736
|
return saved;
|
|
6736
6737
|
}
|
|
6737
6738
|
}
|
|
6738
|
-
if (resource === "providers" &&
|
|
6739
|
+
if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
6739
6740
|
if (store.engine === "postgresql")
|
|
6740
|
-
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [
|
|
6741
|
-
const provider = await store.get("providers",
|
|
6741
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id2]);
|
|
6742
|
+
const provider = await store.get("providers", id2, db);
|
|
6742
6743
|
if (!refreshed || provider.version !== refreshed.provider.version)
|
|
6743
6744
|
throw new Fault(409, "provider_changed", "Provider changed during discovery; refresh again.");
|
|
6744
6745
|
const catalog = refreshed.catalog;
|
|
6745
6746
|
let old;
|
|
6746
6747
|
try {
|
|
6747
|
-
old = await store.get("catalogs",
|
|
6748
|
+
old = await store.get("catalogs", id2, db);
|
|
6748
6749
|
} catch (e) {
|
|
6749
6750
|
if (!(e instanceof Fault && e.status === 404))
|
|
6750
6751
|
throw e;
|
|
6751
6752
|
}
|
|
6752
|
-
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
6753
|
+
const saved = await store.put("catalogs", { id: id2, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
6753
6754
|
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
6754
6755
|
}
|
|
6755
|
-
if (resource === "providers" &&
|
|
6756
|
+
if (resource === "providers" && id2 && parts[3] === "catalog" && parts.length === 4 && request.method === "PUT") {
|
|
6756
6757
|
if (store.engine === "postgresql")
|
|
6757
|
-
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [
|
|
6758
|
-
const provider = await store.get("providers",
|
|
6758
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id2]);
|
|
6759
|
+
const provider = await store.get("providers", id2, db);
|
|
6759
6760
|
if (provider.version !== version())
|
|
6760
6761
|
throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
|
|
6761
6762
|
const catalog = parse2(catalogSchema, body);
|
|
@@ -6765,15 +6766,15 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6765
6766
|
catalog.refreshedAt = new Date().toISOString();
|
|
6766
6767
|
let old;
|
|
6767
6768
|
try {
|
|
6768
|
-
old = await store.get("catalogs",
|
|
6769
|
+
old = await store.get("catalogs", id2, db);
|
|
6769
6770
|
} catch (error) {
|
|
6770
6771
|
if (!(error instanceof Fault && error.status === 404))
|
|
6771
6772
|
throw error;
|
|
6772
6773
|
}
|
|
6773
|
-
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
6774
|
+
const saved = await store.put("catalogs", { id: id2, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
6774
6775
|
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
6775
6776
|
}
|
|
6776
|
-
if (resource === "launch-plans" && !
|
|
6777
|
+
if (resource === "launch-plans" && !id2 && request.method === "POST") {
|
|
6777
6778
|
const { profileId } = parse2(z5.object({ profileId: idSchema }).strict(), body);
|
|
6778
6779
|
const profile = await store.get("profiles", profileId, db);
|
|
6779
6780
|
const provider = await store.get("providers", profile.providerId, db);
|
|
@@ -6806,7 +6807,7 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6806
6807
|
warnings.push("Catalog snapshot is older than five minutes; refresh before launching.");
|
|
6807
6808
|
return { profile, provider, catalog, warnings, planToken: snapshot(profile, provider, catalog) };
|
|
6808
6809
|
}
|
|
6809
|
-
if (resource === "runs" && !
|
|
6810
|
+
if (resource === "runs" && !id2 && request.method === "POST") {
|
|
6810
6811
|
if (body?.modelPolicyVersion !== 1)
|
|
6811
6812
|
throw new Fault(409, "launcher_upgrade_required", "This API requires a launcher with automatic model policy version 1; upgrade the Switcher CLI/SDK.");
|
|
6812
6813
|
const input = parse2(runInputSchema, body);
|
|
@@ -6831,16 +6832,16 @@ function createHandler(store, authentication, providerEnv = process.env, resolve
|
|
|
6831
6832
|
compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
|
|
6832
6833
|
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);
|
|
6833
6834
|
}
|
|
6834
|
-
if (resource === "runs" &&
|
|
6835
|
+
if (resource === "runs" && id2 && request.method === "PATCH" && parts.length === 3) {
|
|
6835
6836
|
const input = parse2(runUpdateSchema, body);
|
|
6836
|
-
const run = await store.get("runs",
|
|
6837
|
+
const run = await store.get("runs", id2, db);
|
|
6837
6838
|
if (run.status !== "running")
|
|
6838
6839
|
throw new Fault(409, "run_finished", "Run has already finished.");
|
|
6839
6840
|
return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
|
|
6840
6841
|
}
|
|
6841
6842
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
6842
6843
|
});
|
|
6843
|
-
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
6844
|
+
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
|
|
6844
6845
|
} catch (error) {
|
|
6845
6846
|
const safe = error instanceof Fault ? error : new Fault(500, "internal_error", "Request failed.");
|
|
6846
6847
|
return json({ error: { code: safe.code, message: safe.message, requestId } }, safe.status);
|
|
@@ -7025,14 +7026,14 @@ var nativeUtilityAliases = ["auto", "pro", "flash", "flash-lite", "auto-gemini-3
|
|
|
7025
7026
|
function ownRecord() {
|
|
7026
7027
|
return Object.create(null);
|
|
7027
7028
|
}
|
|
7028
|
-
function safeId(value,
|
|
7029
|
+
function safeId(value, label2) {
|
|
7029
7030
|
if (typeof value !== "string" || value.length < 1 || value.length > 300 || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
7030
|
-
throw new Fault(400, "invalid_model_policy", `${
|
|
7031
|
+
throw new Fault(400, "invalid_model_policy", `${label2} is invalid.`);
|
|
7031
7032
|
}
|
|
7032
7033
|
return value;
|
|
7033
7034
|
}
|
|
7034
|
-
function compileGeminiModelPolicy(
|
|
7035
|
-
const selected = safeId(
|
|
7035
|
+
function compileGeminiModelPolicy(selectedModel2, models, compiled) {
|
|
7036
|
+
const selected = safeId(selectedModel2, "model");
|
|
7036
7037
|
if (compiled.model !== selected)
|
|
7037
7038
|
throw new Fault(400, "invalid_model_policy", "Gemini policy does not match the selected model.");
|
|
7038
7039
|
for (const role of ["planning", "review"])
|
|
@@ -7058,8 +7059,8 @@ function compileGeminiModelPolicy(selectedModel, models, compiled) {
|
|
|
7058
7059
|
const modelChains = ownRecord();
|
|
7059
7060
|
const modelDefinitions = ownRecord();
|
|
7060
7061
|
for (const model of models) {
|
|
7061
|
-
const
|
|
7062
|
-
modelDefinitions[
|
|
7062
|
+
const id2 = safeId(model.id, "catalog model");
|
|
7063
|
+
modelDefinitions[id2] = {
|
|
7063
7064
|
displayName: model.name,
|
|
7064
7065
|
tier: "custom",
|
|
7065
7066
|
family: "switcher",
|
|
@@ -7068,9 +7069,9 @@ function compileGeminiModelPolicy(selectedModel, models, compiled) {
|
|
|
7068
7069
|
features: { thinking: false, multimodalToolUse: model.inputModalities?.includes("image") ?? false }
|
|
7069
7070
|
};
|
|
7070
7071
|
}
|
|
7071
|
-
for (const
|
|
7072
|
-
safeId(
|
|
7073
|
-
modelIdResolutions[
|
|
7072
|
+
for (const id2 of [...new Set([...compiled.allowedModels, ...models.map((model) => model.id)])]) {
|
|
7073
|
+
safeId(id2, "catalog model");
|
|
7074
|
+
modelIdResolutions[id2] = { default: id2, contexts: [] };
|
|
7074
7075
|
}
|
|
7075
7076
|
for (const alias of nativeUtilityAliases) {
|
|
7076
7077
|
if (!eligible.has(alias))
|
|
@@ -7094,8 +7095,8 @@ var nativeModels = ["gemini-3.1-flash-lite", "gemini-3.1-pro-preview", "gemini-3
|
|
|
7094
7095
|
var object2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
7095
7096
|
async function regular(path, limit = 2 * 1024 * 1024) {
|
|
7096
7097
|
try {
|
|
7097
|
-
const
|
|
7098
|
-
if (!
|
|
7098
|
+
const stat4 = await lstat2(path);
|
|
7099
|
+
if (!stat4.isFile() || stat4.size > limit)
|
|
7099
7100
|
throw new Error("unsupported");
|
|
7100
7101
|
return true;
|
|
7101
7102
|
} catch (error) {
|
|
@@ -7154,17 +7155,17 @@ async function validateGeminiConfiguration(cwd, env = process.env) {
|
|
|
7154
7155
|
const systemPath = env.GEMINI_CLI_SYSTEM_SETTINGS_PATH ?? (process.platform === "darwin" ? "/Library/Application Support/GeminiCli/settings.json" : process.platform === "win32" ? "C:\\ProgramData\\gemini-cli\\settings.json" : "/etc/gemini-cli/settings.json");
|
|
7155
7156
|
const defaultsPath = env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ?? join5(dirname3(systemPath), "system-defaults.json");
|
|
7156
7157
|
const paths = [defaultsPath, join5(home, ".gemini", "settings.json"), join5(resolve4(cwd), ".gemini", "settings.json"), systemPath];
|
|
7157
|
-
const
|
|
7158
|
+
const values2 = [];
|
|
7158
7159
|
for (const path of paths) {
|
|
7159
7160
|
const value = await settings(path);
|
|
7160
7161
|
check(value, path);
|
|
7161
|
-
|
|
7162
|
+
values2.push(value);
|
|
7162
7163
|
}
|
|
7163
7164
|
for (const key of ["policyPaths", "adminPolicyPaths"])
|
|
7164
|
-
if (
|
|
7165
|
+
if (values2[2][key]?.some?.((path) => typeof path === "string" && (path === "~" || path.startsWith("~/"))))
|
|
7165
7166
|
throw new Error("Gemini project policy paths using ~ must use an absolute path so workspace trust remains authoritative under an isolated native home.");
|
|
7166
|
-
const contextNames = [...new Set(["GEMINI.md", ...
|
|
7167
|
-
return { home, defaults: originalPaths(
|
|
7167
|
+
const contextNames = [...new Set(["GEMINI.md", ...values2.flatMap((value) => [value.context?.fileName ?? []].flat())])];
|
|
7168
|
+
return { home, defaults: originalPaths(values2[0], home), user: originalPaths(values2[1], home), system: originalPaths(values2[3], home), contextNames, trustPath: env.GEMINI_CLI_TRUSTED_FOLDERS_PATH ?? join5(home, ".gemini", "trustedFolders.json") };
|
|
7168
7169
|
}
|
|
7169
7170
|
async function snapshotFile(source, destination) {
|
|
7170
7171
|
if (await regular(source))
|
|
@@ -7173,8 +7174,8 @@ async function snapshotFile(source, destination) {
|
|
|
7173
7174
|
async function snapshotPolicies(source, destination) {
|
|
7174
7175
|
let entries;
|
|
7175
7176
|
try {
|
|
7176
|
-
const
|
|
7177
|
-
if (!
|
|
7177
|
+
const stat4 = await lstat2(source);
|
|
7178
|
+
if (!stat4.isDirectory() || stat4.isSymbolicLink())
|
|
7178
7179
|
throw new Error("Unsupported Gemini policy directory");
|
|
7179
7180
|
entries = await readdir2(source, { withFileTypes: true });
|
|
7180
7181
|
} catch (error) {
|
|
@@ -7249,7 +7250,7 @@ async function prepareGemini(input) {
|
|
|
7249
7250
|
}
|
|
7250
7251
|
const defaults = join5(input.stateDir, "gemini-system-defaults.json"), system = join5(input.stateDir, "gemini-system.json"), user = join5(dir, "settings.json");
|
|
7251
7252
|
const modelPolicy = compileGeminiModelPolicy(input.model, input.models, input.compiledPolicy ?? compileModelPolicy(input.model, input.models, input.modelPolicy));
|
|
7252
|
-
const modelDefinitions = { ...Object.fromEntries(nativeModels.map((
|
|
7253
|
+
const modelDefinitions = { ...Object.fromEntries(nativeModels.map((id2) => [id2, { isVisible: false }])), ...modelPolicy.modelConfigs.modelDefinitions };
|
|
7253
7254
|
const enforced = { ...original.system, security: { ...original.system.security, auth: { ...original.system.security?.auth, selectedType: "gemini-api-key" } }, model: { ...original.system.model, name: input.model }, modelConfigs: { ...modelPolicy.modelConfigs, modelDefinitions }, agents: { ...original.system.agents, overrides: { ...original.system.agents?.overrides, ...modelPolicy.agents?.overrides } }, experimental: { ...original.system.experimental, dynamicModelConfiguration: true } };
|
|
7254
7255
|
for (const [path, value] of [[defaults, original.defaults], [user, original.user], [system, enforced]]) {
|
|
7255
7256
|
const text = JSON.stringify(value, null, 2) + `
|
|
@@ -7295,7 +7296,7 @@ function geminiBridge(input, timing = {}) {
|
|
|
7295
7296
|
const models = new Set(input.models.map((model) => model.id));
|
|
7296
7297
|
let closing = false, stopped;
|
|
7297
7298
|
const active = new Set;
|
|
7298
|
-
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request,
|
|
7299
|
+
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
|
|
7299
7300
|
const fail = (status, message) => Response.json({ error: { code: status, message } }, { status });
|
|
7300
7301
|
if (closing)
|
|
7301
7302
|
return fail(503, "Bridge is closing");
|
|
@@ -7332,17 +7333,17 @@ function geminiBridge(input, timing = {}) {
|
|
|
7332
7333
|
if (input.credential)
|
|
7333
7334
|
headers["x-goog-api-key"] = input.credential;
|
|
7334
7335
|
let complete;
|
|
7335
|
-
const
|
|
7336
|
-
complete =
|
|
7336
|
+
const record2 = { abort: new AbortController, done: new Promise((resolve5) => {
|
|
7337
|
+
complete = resolve5;
|
|
7337
7338
|
}) };
|
|
7338
|
-
const activity = createProviderRequest(request.signal,
|
|
7339
|
+
const activity = createProviderRequest(request.signal, record2.abort.signal, timing);
|
|
7339
7340
|
const release = () => {
|
|
7340
7341
|
activity.finish();
|
|
7341
|
-
active.delete(
|
|
7342
|
+
active.delete(record2);
|
|
7342
7343
|
complete();
|
|
7343
7344
|
};
|
|
7344
|
-
active.add(
|
|
7345
|
-
|
|
7345
|
+
active.add(record2);
|
|
7346
|
+
server2.timeout(request, 0);
|
|
7346
7347
|
try {
|
|
7347
7348
|
const response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
|
|
7348
7349
|
if (!response.ok) {
|
|
@@ -7356,8 +7357,8 @@ function geminiBridge(input, timing = {}) {
|
|
|
7356
7357
|
release();
|
|
7357
7358
|
return new Response(null, { status: response.status });
|
|
7358
7359
|
}
|
|
7359
|
-
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort:
|
|
7360
|
-
|
|
7360
|
+
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record2.abort, closing: () => closing, release, activity });
|
|
7361
|
+
record2.cancel = cancel;
|
|
7361
7362
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
7362
7363
|
} catch {
|
|
7363
7364
|
release();
|
|
@@ -7399,7 +7400,7 @@ function exactModels(input) {
|
|
|
7399
7400
|
throw new Error(`Native model policy role ${role} is empty.`);
|
|
7400
7401
|
return result;
|
|
7401
7402
|
}
|
|
7402
|
-
var unsupported = (...
|
|
7403
|
+
var unsupported = (...roles2) => roles2;
|
|
7403
7404
|
function compileNativeModelPolicy(input) {
|
|
7404
7405
|
const models = exactModels(input);
|
|
7405
7406
|
const env = {};
|
|
@@ -7521,13 +7522,13 @@ function normalizeCodexDelegation(body) {
|
|
|
7521
7522
|
|
|
7522
7523
|
// src/opencode.ts
|
|
7523
7524
|
function rememberGeminiTool(part, state) {
|
|
7524
|
-
const
|
|
7525
|
+
const id2 = `call_${crypto.randomUUID()}`;
|
|
7525
7526
|
if (typeof part.thoughtSignature === "string") {
|
|
7526
7527
|
if (part.thoughtSignature.length > 65536 || state.size >= 2000)
|
|
7527
7528
|
throw new Fault(502, "opencode_signature_limit", "Gemini tool continuation metadata exceeded the launch limit.");
|
|
7528
|
-
state.set(
|
|
7529
|
+
state.set(id2, part.thoughtSignature);
|
|
7529
7530
|
}
|
|
7530
|
-
return
|
|
7531
|
+
return id2;
|
|
7531
7532
|
}
|
|
7532
7533
|
function openCodeLane(baseUrl) {
|
|
7533
7534
|
const url = new URL(baseUrl);
|
|
@@ -7625,11 +7626,11 @@ function toChat(body) {
|
|
|
7625
7626
|
messages.push({ role: "assistant", content: content.length ? content : null, ...calls.length ? { tool_calls: calls } : {}, ...thinking ? { reasoning_content: thinking } : {} });
|
|
7626
7627
|
} else {
|
|
7627
7628
|
const images = [];
|
|
7628
|
-
for (const part of parts.filter((
|
|
7629
|
-
const
|
|
7630
|
-
messages.push({ role: "tool", tool_call_id: part.tool_use_id, content:
|
|
7631
|
-
if (
|
|
7632
|
-
images.push({ type: "text", text: `Images returned by tool call ${part.tool_use_id}:` }, ...
|
|
7629
|
+
for (const part of parts.filter((part2) => part2.type === "tool_result")) {
|
|
7630
|
+
const result2 = toolResult(part);
|
|
7631
|
+
messages.push({ role: "tool", tool_call_id: part.tool_use_id, content: result2.text });
|
|
7632
|
+
if (result2.images.length)
|
|
7633
|
+
images.push({ type: "text", text: `Images returned by tool call ${part.tool_use_id}:` }, ...result2.images);
|
|
7633
7634
|
}
|
|
7634
7635
|
const content = chatContent([...images, ...parts.filter((part) => part.type !== "tool_result")]);
|
|
7635
7636
|
if (content.length)
|
|
@@ -7981,6 +7982,14 @@ function prepareOpenCodeMessages(baseUrl, body, suffix, credential, state = new
|
|
|
7981
7982
|
// src/inference-gateway.ts
|
|
7982
7983
|
import { createHash as createHash6, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
7983
7984
|
var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
|
|
7985
|
+
var MIN_REQUEST_BODY_BYTES = 4 * 1024 * 1024;
|
|
7986
|
+
var MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024;
|
|
7987
|
+
var REQUEST_BYTES_PER_CONTEXT_TOKEN = 16;
|
|
7988
|
+
function requestBodyLimit(models, policy) {
|
|
7989
|
+
const allowed = new Set(policy.allowedModels);
|
|
7990
|
+
const contextWindow = Math.max(0, ...models.filter((model) => allowed.has(model.id)).map((model) => Number.isSafeInteger(model.contextWindow) && model.contextWindow > 0 ? model.contextWindow : 0));
|
|
7991
|
+
return Math.min(MAX_REQUEST_BODY_BYTES, Math.max(MIN_REQUEST_BODY_BYTES, contextWindow * REQUEST_BYTES_PER_CONTEXT_TOKEN));
|
|
7992
|
+
}
|
|
7984
7993
|
function createInferenceGateway(input, timing = {}) {
|
|
7985
7994
|
const token = crypto.randomUUID() + crypto.randomUUID();
|
|
7986
7995
|
const openCodeSession = crypto.randomUUID();
|
|
@@ -7992,7 +8001,7 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7992
8001
|
const fail = (status, code, message) => Response.json({ error: { type: "switcher_model_policy", code, message: message ?? (code === "model_not_allowed" ? "This model is outside the launch policy. Select it with switcher launch --model or explicitly assign an allowed role model." : `Switcher inference gateway: ${code}.`) } }, { status });
|
|
7993
8002
|
let closing = false, stopped;
|
|
7994
8003
|
const active = new Set;
|
|
7995
|
-
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize:
|
|
8004
|
+
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: requestBodyLimit(input.models, input.compiledPolicy), idleTimeout: 255, async fetch(request, server2) {
|
|
7996
8005
|
if (closing)
|
|
7997
8006
|
return fail(503, "closing");
|
|
7998
8007
|
const credential = request.headers.get("x-goog-api-key") ?? request.headers.get("x-api-key") ?? request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
|
|
@@ -8064,17 +8073,17 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8064
8073
|
};
|
|
8065
8074
|
const abort = new AbortController;
|
|
8066
8075
|
let complete;
|
|
8067
|
-
const
|
|
8076
|
+
const record2 = { abort, done: new Promise((r) => complete = r) };
|
|
8068
8077
|
const activity = createProviderRequest(request.signal, abort.signal, timing);
|
|
8069
8078
|
const release = () => {
|
|
8070
8079
|
activity.finish();
|
|
8071
8080
|
flush();
|
|
8072
|
-
active.delete(
|
|
8081
|
+
active.delete(record2);
|
|
8073
8082
|
complete();
|
|
8074
8083
|
};
|
|
8075
|
-
active.add(
|
|
8084
|
+
active.add(record2);
|
|
8076
8085
|
const signal = activity.fetchOptions.signal;
|
|
8077
|
-
|
|
8086
|
+
server2.timeout(request, 0);
|
|
8078
8087
|
const headers = { "content-type": "application/json" };
|
|
8079
8088
|
Object.assign(headers, openCodeHeaders(input.baseUrl, request.headers, body, openCodeSession));
|
|
8080
8089
|
if (input.credential) {
|
|
@@ -8109,8 +8118,8 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8109
8118
|
} else
|
|
8110
8119
|
payload.model = model;
|
|
8111
8120
|
const guidance = renderModelGuidance({ harness: input.harness, providerId: input.providerId, baseUrl: input.baseUrl, model, compiled: policy, catalogPath: input.catalogPath });
|
|
8112
|
-
const
|
|
8113
|
-
const outgoing = injectModelGuidance(input.protocol,
|
|
8121
|
+
const compatible2 = input.harness === "codex" && input.protocol === "openai-responses" && new URL(input.baseUrl).hostname !== "api.openai.com" ? normalizeCodexDelegation(payload) : payload;
|
|
8122
|
+
const outgoing = injectModelGuidance(input.protocol, compatible2, guidance, match?.[2]);
|
|
8114
8123
|
const translated = input.protocol === "anthropic-messages" ? prepareOpenCodeMessages(input.baseUrl, outgoing, suffix, input.credential, openCodeState) : undefined;
|
|
8115
8124
|
const path = translated?.path ?? (gemini ? `/models/${encodeURIComponent(model)}:${match[2]}${url.search}` : suffix + (betaQuery ? "?beta=true" : ""));
|
|
8116
8125
|
const upstreamHeaders = { ...headers };
|
|
@@ -8125,8 +8134,6 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8125
8134
|
response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers: upstreamHeaders, body: JSON.stringify(translated?.body ?? outgoing), redirect: "manual", ...activity.fetchOptions }));
|
|
8126
8135
|
} catch {
|
|
8127
8136
|
current.reason = activity.timedOut() ? "provider_idle_timeout" : signal.aborted ? "request_cancelled" : "network_error";
|
|
8128
|
-
if (!signal.aborted && attempt + 1 < candidates.length)
|
|
8129
|
-
continue;
|
|
8130
8137
|
throw new Error("provider_request_failed");
|
|
8131
8138
|
}
|
|
8132
8139
|
current.upstreamStatus = response.status;
|
|
@@ -8197,15 +8204,16 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8197
8204
|
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort, closing: () => closing, release, activity, inspect, interrupted: (reason) => {
|
|
8198
8205
|
current.reason = reason;
|
|
8199
8206
|
} });
|
|
8200
|
-
|
|
8207
|
+
record2.cancel = cancel;
|
|
8201
8208
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
8202
8209
|
} catch (error) {
|
|
8203
8210
|
if (error instanceof Fault)
|
|
8204
8211
|
current.reason = error.code;
|
|
8205
8212
|
else if (activity.timedOut())
|
|
8206
8213
|
current.reason = "provider_idle_timeout";
|
|
8214
|
+
const networkError = !(error instanceof Fault) && current.reason === "network_error";
|
|
8207
8215
|
release();
|
|
8208
|
-
return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : "provider_request_failed", error instanceof Fault && error.code === "opencode_translation_unsupported" ? error.message : undefined);
|
|
8216
|
+
return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : networkError ? "provider_network_error" : "provider_request_failed", error instanceof Fault && error.code === "opencode_translation_unsupported" ? error.message : networkError ? "The upstream provider connection ended before response headers. Switcher did not attempt a fallback because delivery is uncertain." : undefined);
|
|
8209
8217
|
}
|
|
8210
8218
|
} });
|
|
8211
8219
|
return { baseUrl: new URL(input.protocol === "gemini-generate-content" ? "v1beta" : "v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
|
|
@@ -8264,13 +8272,13 @@ function codexAgentsFromEffectiveConfig(config, trustedProject = true, baseDir)
|
|
|
8264
8272
|
function reject(key) {
|
|
8265
8273
|
throw new Error(`Codex policy cannot preserve ${key}; provider, transport, and include configuration are launch-owned.`);
|
|
8266
8274
|
}
|
|
8267
|
-
function cloneAgentConfig(value,
|
|
8275
|
+
function cloneAgentConfig(value, selectedModel2, provider) {
|
|
8268
8276
|
const out = {};
|
|
8269
8277
|
for (const [key, item] of Object.entries(value)) {
|
|
8270
8278
|
if (codexTransportKeys.has(key) || key === "include" || key === "model_providers")
|
|
8271
8279
|
reject(key);
|
|
8272
8280
|
if (key === "model") {
|
|
8273
|
-
out.model =
|
|
8281
|
+
out.model = selectedModel2;
|
|
8274
8282
|
continue;
|
|
8275
8283
|
}
|
|
8276
8284
|
if (key === "model_provider" || key === "provider") {
|
|
@@ -8281,7 +8289,7 @@ function cloneAgentConfig(value, selectedModel, provider) {
|
|
|
8281
8289
|
reject(key);
|
|
8282
8290
|
out[key] = scanNested(item, key);
|
|
8283
8291
|
}
|
|
8284
|
-
out.model =
|
|
8292
|
+
out.model = selectedModel2;
|
|
8285
8293
|
out.model_provider = provider;
|
|
8286
8294
|
return out;
|
|
8287
8295
|
}
|
|
@@ -8306,9 +8314,9 @@ function compileCodexModelPolicy(input) {
|
|
|
8306
8314
|
const policy = modelPolicySchema.parse(input.policy ?? {});
|
|
8307
8315
|
const subagentModel = policy.roles?.subagent ?? input.model;
|
|
8308
8316
|
const reviewModel = policy.roles?.review ?? input.model;
|
|
8309
|
-
const
|
|
8310
|
-
if (
|
|
8311
|
-
throw new Error(`Codex does not expose role controls for: ${
|
|
8317
|
+
const unsupported3 = ["fast", "planning", "summary", "compaction", "weak", "editor"].filter((role) => policy.roles?.[role] !== undefined && policy.roles?.[role] !== input.model);
|
|
8318
|
+
if (unsupported3.length)
|
|
8319
|
+
throw new Error(`Codex does not expose role controls for: ${unsupported3.join(", ")}.`);
|
|
8312
8320
|
const agents = [];
|
|
8313
8321
|
const ignoredUntrustedAgents = [];
|
|
8314
8322
|
for (const [name, definition] of Object.entries(input.agents ?? {})) {
|
|
@@ -8508,8 +8516,8 @@ var object3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
|
8508
8516
|
async function data(path) {
|
|
8509
8517
|
let text;
|
|
8510
8518
|
try {
|
|
8511
|
-
const
|
|
8512
|
-
if (!
|
|
8519
|
+
const stat5 = await lstat3(path);
|
|
8520
|
+
if (!stat5.isFile() || stat5.size > 1024 * 1024)
|
|
8513
8521
|
throw new Error("unsupported");
|
|
8514
8522
|
text = await readFile3(path, "utf8");
|
|
8515
8523
|
} catch (error) {
|
|
@@ -8595,11 +8603,11 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
8595
8603
|
}
|
|
8596
8604
|
effective = { ...effective, ...normalized };
|
|
8597
8605
|
}
|
|
8598
|
-
const
|
|
8599
|
-
if (
|
|
8600
|
-
if (!Array.isArray(
|
|
8606
|
+
const settings2 = await data(join7(root, ".aider.model.settings.yml"));
|
|
8607
|
+
if (settings2 !== undefined) {
|
|
8608
|
+
if (!Array.isArray(settings2))
|
|
8601
8609
|
throw new Error("Aider model settings must be a list.");
|
|
8602
|
-
for (const entry of
|
|
8610
|
+
for (const entry of settings2)
|
|
8603
8611
|
if (!object3(entry) || entry.extra_params !== undefined && (!object3(entry.extra_params) || Object.keys(entry.extra_params).some((key) => !safeParameters.has(key))))
|
|
8604
8612
|
throw new Error(`Aider custom transport or callback model settings cannot be preserved safely: ${join7(root, ".aider.model.settings.yml")}`);
|
|
8605
8613
|
}
|
|
@@ -8618,12 +8626,12 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
8618
8626
|
effective.read = typeof effective.read === "string" ? expandHome(effective.read, home) : effective.read.map((path) => expandHome(path, home));
|
|
8619
8627
|
return effective;
|
|
8620
8628
|
}
|
|
8621
|
-
function aiderModelName(protocol,
|
|
8622
|
-
return `${protocol === "anthropic-messages" ? "anthropic" : protocol === "openai-responses" ? "openai/responses" : "openai"}/${
|
|
8629
|
+
function aiderModelName(protocol, id2) {
|
|
8630
|
+
return `${protocol === "anthropic-messages" ? "anthropic" : protocol === "openai-responses" ? "openai/responses" : "openai"}/${id2}`;
|
|
8623
8631
|
}
|
|
8624
8632
|
async function historyFile(path) {
|
|
8625
|
-
const
|
|
8626
|
-
if (!
|
|
8633
|
+
const stat5 = await lstat3(path);
|
|
8634
|
+
if (!stat5.isFile() || stat5.isSymbolicLink() || stat5.size > 64 * 1024 * 1024 || process.platform !== "win32" && ((stat5.mode & 63) !== 0 || stat5.uid !== process.getuid?.()))
|
|
8627
8635
|
throw new Error("Aider history must be an owner-only regular file smaller than 64 MiB.");
|
|
8628
8636
|
}
|
|
8629
8637
|
async function prepareAider(input) {
|
|
@@ -8632,9 +8640,9 @@ async function prepareAider(input) {
|
|
|
8632
8640
|
if (input.protocol === "openai-responses" && input.models.some((m) => m.id.includes("responses/")))
|
|
8633
8641
|
throw new Error("Aider/LiteLLM removes responses/ segments from Responses model names; this catalog cannot be mapped exactly.");
|
|
8634
8642
|
const parsed = aiderArguments(input.args ?? []), global = await validateAiderConfiguration(input.cwd, input.args);
|
|
8635
|
-
const
|
|
8636
|
-
if (
|
|
8637
|
-
const files = parsed.args.splice(
|
|
8643
|
+
const literal2 = parsed.args.indexOf("--");
|
|
8644
|
+
if (literal2 >= 0) {
|
|
8645
|
+
const files = parsed.args.splice(literal2).slice(1);
|
|
8638
8646
|
parsed.args.push(...files.map((path) => resolve6(input.cwd, path)));
|
|
8639
8647
|
}
|
|
8640
8648
|
const sourceHome = process.env.HOME ?? homedir5();
|
|
@@ -8655,7 +8663,7 @@ async function prepareAider(input) {
|
|
|
8655
8663
|
`).join(""), { mode: 384, flag: "wx" });
|
|
8656
8664
|
const sessions = input.sessionDir ?? join7(input.stateDir, "sessions");
|
|
8657
8665
|
await privateDirectory(sessions);
|
|
8658
|
-
const
|
|
8666
|
+
const id2 = crypto.randomUUID(), history = join7(sessions, `${id2}.chat.md`), inputHistory = join7(sessions, `${id2}.input`);
|
|
8659
8667
|
if (parsed.restore) {
|
|
8660
8668
|
const latest = join7(sessions, "latest.json");
|
|
8661
8669
|
await historyFile(latest).catch(() => {
|
|
@@ -8671,12 +8679,12 @@ async function prepareAider(input) {
|
|
|
8671
8679
|
await writeFile5(history, "", { mode: 384, flag: "wx" });
|
|
8672
8680
|
const originalHistoryLength = (await readFile3(history, "utf8")).length;
|
|
8673
8681
|
await writeFile5(inputHistory, "", { mode: 384, flag: "wx" });
|
|
8674
|
-
const
|
|
8682
|
+
const model2 = aiderModelName(input.protocol, input.model);
|
|
8675
8683
|
const weakModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.weak ?? input.model), editorModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.editor ?? input.model);
|
|
8676
8684
|
const extra = { api_base: input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl, api_key: `os.environ/${KEY2}` };
|
|
8677
|
-
const
|
|
8685
|
+
const settings2 = join7(input.stateDir, "aider-model-settings.json"), metadata = join7(input.stateDir, "aider-model-metadata.json"), config = join7(input.stateDir, "aider-config.json"), empty = join7(input.stateDir, "aider-empty.env");
|
|
8678
8686
|
const definitions = input.models.map((m) => ({ name: aiderModelName(input.protocol, m.id), edit_format: "whole", use_repo_map: true, weak_model_name: weakModel, editor_model_name: editorModel, extra_params: extra }));
|
|
8679
|
-
await writeFile5(
|
|
8687
|
+
await writeFile5(settings2, JSON.stringify([...definitions, { name: "aider/extra_params", extra_params: extra }]), { mode: 384, flag: "wx" });
|
|
8680
8688
|
await writeFile5(metadata, JSON.stringify(Object.fromEntries(input.models.map((m) => [aiderModelName(input.protocol, m.id), {
|
|
8681
8689
|
...m.contextWindow ? { max_input_tokens: m.contextWindow } : {},
|
|
8682
8690
|
...m.maxOutputTokens ? { max_output_tokens: m.maxOutputTokens, max_tokens: m.maxOutputTokens } : {},
|
|
@@ -8686,15 +8694,15 @@ async function prepareAider(input) {
|
|
|
8686
8694
|
}]))), { mode: 384, flag: "wx" });
|
|
8687
8695
|
const ignored = new Set(`model weak-model editor-model openai-api-key anthropic-api-key openai-api-base openai-api-type openai-api-version openai-api-deployment-id openai-organization-id set-env api-key alias config env-file model-settings-file model-metadata-file input-history-file chat-history-file llm-history-file restore-chat-history load analytics analytics-log analytics-posthog-host analytics-posthog-project-api-key analytics-disable check-update show-release-notes`.split(" "));
|
|
8688
8696
|
const preserved = Object.fromEntries(Object.entries(global).filter(([key]) => !ignored.has(key) && !startup.includes(key)));
|
|
8689
|
-
await writeFile5(config, JSON.stringify({ ...preserved, model, "weak-model": weakModel, "editor-model": editorModel, "model-settings-file":
|
|
8697
|
+
await writeFile5(config, JSON.stringify({ ...preserved, model: model2, "weak-model": weakModel, "editor-model": editorModel, "model-settings-file": settings2, "model-metadata-file": metadata, "env-file": empty, "input-history-file": inputHistory, "chat-history-file": history, "llm-history-file": "", "restore-chat-history": parsed.restore, load: "", analytics: false, "check-update": false, "show-release-notes": false, "openai-api-key": "", "anthropic-api-key": "", "openai-api-base": input.baseUrl, "openai-api-type": "", "openai-api-version": "", "openai-api-deployment-id": "", "openai-organization-id": "" }), { mode: 384, flag: "wx" });
|
|
8690
8698
|
await writeFile5(empty, "", { mode: 384, flag: "wx" });
|
|
8691
|
-
const aliases = ["--alias", `switcher-${
|
|
8699
|
+
const aliases = ["--alias", `switcher-${id2}:${model2}`];
|
|
8692
8700
|
let cleaned = false;
|
|
8693
8701
|
return {
|
|
8694
8702
|
executable: input.executable ?? "aider",
|
|
8695
|
-
args: ["--config", config, "--model",
|
|
8703
|
+
args: ["--config", config, "--model", model2, "--weak-model", weakModel, "--editor-model", editorModel, "--set-env", "PYTHON_DOTENV_DISABLED=1", "--api-key", "SWITCHER_UNUSED=unused", ...aliases, ...parsed.args],
|
|
8696
8704
|
env: { HOME: home, XDG_CONFIG_HOME: join7(home, "config"), XDG_CACHE_HOME: join7(home, "cache"), XDG_DATA_HOME: join7(home, "data"), PYTHON_DOTENV_DISABLED: "1", LITELLM_LOCAL_MODEL_COST_MAP: "True", [KEY2]: input.credential, [input.protocol === "anthropic-messages" ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY"]: input.credential },
|
|
8697
|
-
configPaths: [config,
|
|
8705
|
+
configPaths: [config, settings2, metadata, empty, gitConfig],
|
|
8698
8706
|
warnings: [
|
|
8699
8707
|
...input.protocol === "openai-responses" ? ["Aider 0.86.2 with LiteLLM 1.81.10 uses buffered Responses requests even when native streaming is requested; incremental upstream Responses output is unavailable through this adapter."] : [],
|
|
8700
8708
|
"Aider uses native file context and whole-file edits; it does not expose an autonomous file-read function tool. The provider must follow Aider's edit format.",
|
|
@@ -8709,8 +8717,8 @@ async function prepareAider(input) {
|
|
|
8709
8717
|
await historyFile(history);
|
|
8710
8718
|
if (!/^#### /m.test((await readFile3(history, "utf8")).slice(originalHistoryLength)))
|
|
8711
8719
|
return;
|
|
8712
|
-
const pending = join7(sessions, `${
|
|
8713
|
-
await writeFile5(pending, JSON.stringify({ id }), { mode: 384, flag: "wx" });
|
|
8720
|
+
const pending = join7(sessions, `${id2}.latest.json`);
|
|
8721
|
+
await writeFile5(pending, JSON.stringify({ id: id2 }), { mode: 384, flag: "wx" });
|
|
8714
8722
|
await rename(pending, join7(sessions, "latest.json"));
|
|
8715
8723
|
}
|
|
8716
8724
|
};
|
|
@@ -8718,7 +8726,7 @@ async function prepareAider(input) {
|
|
|
8718
8726
|
|
|
8719
8727
|
// src/grok-args.ts
|
|
8720
8728
|
function validateGrokResume(args) {
|
|
8721
|
-
const
|
|
8729
|
+
const values2 = new Set([
|
|
8722
8730
|
"--cwd",
|
|
8723
8731
|
"--leader-socket",
|
|
8724
8732
|
"--debug-file",
|
|
@@ -8770,7 +8778,7 @@ function validateGrokResume(args) {
|
|
|
8770
8778
|
if (prompts.has(flag))
|
|
8771
8779
|
headless = true;
|
|
8772
8780
|
const optionalValue = ["--resume", "--worktree", "--local-workspace"].includes(flag);
|
|
8773
|
-
if (!attached && (
|
|
8781
|
+
if (!attached && (values2.has(flag) || prompts.has(flag) || flag === "--load" || optionalValue && args[i + 1] !== undefined && !args[i + 1].startsWith("-")))
|
|
8774
8782
|
i++;
|
|
8775
8783
|
} else if (arg.startsWith("-") && arg.length > 1) {
|
|
8776
8784
|
for (let j = 1;j < arg.length; j++) {
|
|
@@ -8806,17 +8814,17 @@ var PROTOCOL = {
|
|
|
8806
8814
|
"openai-responses": { protocol: "openai-responses", client: "openai", providerId: "openai-native", authStyle: "bearer" },
|
|
8807
8815
|
"openai-chat": { protocol: "openai-chat", client: "openai-compatible", providerId: "openai-compatible", authStyle: "bearer" }
|
|
8808
8816
|
};
|
|
8809
|
-
function modelEntry(
|
|
8817
|
+
function modelEntry(model2, protocol) {
|
|
8810
8818
|
return {
|
|
8811
|
-
id:
|
|
8812
|
-
name:
|
|
8813
|
-
...
|
|
8814
|
-
...
|
|
8819
|
+
id: model2.id,
|
|
8820
|
+
name: model2.name,
|
|
8821
|
+
...model2.contextWindow ? { contextWindow: model2.contextWindow } : {},
|
|
8822
|
+
...model2.maxOutputTokens ? { maxTokens: model2.maxOutputTokens } : {},
|
|
8815
8823
|
capabilities: ["streaming", "tools"],
|
|
8816
8824
|
...protocol === "openai-responses" ? { apiFormat: "openai-responses" } : {},
|
|
8817
8825
|
modalities: {
|
|
8818
|
-
input:
|
|
8819
|
-
output:
|
|
8826
|
+
input: model2.inputModalities?.filter((modality) => modality === "text" || modality === "image") ?? ["text"],
|
|
8827
|
+
output: model2.outputModalities?.filter((modality) => modality === "text") ?? ["text"]
|
|
8820
8828
|
}
|
|
8821
8829
|
};
|
|
8822
8830
|
}
|
|
@@ -8829,12 +8837,12 @@ async function prepareClineLaunch(input) {
|
|
|
8829
8837
|
if (input.protocol === "gemini-generate-content")
|
|
8830
8838
|
throw new Error("Cline does not support the Gemini generateContent protocol.");
|
|
8831
8839
|
const requestedProtocol = input.protocol;
|
|
8832
|
-
const selected = input.models.find((
|
|
8840
|
+
const selected = input.models.find((model2) => model2.id === input.model);
|
|
8833
8841
|
if (!selected)
|
|
8834
8842
|
throw new Error("Selected model is missing from the launch catalog.");
|
|
8835
|
-
if (input.models.some((
|
|
8843
|
+
if (input.models.some((model2) => !codingEligible(model2)))
|
|
8836
8844
|
throw new Error("Launch catalog contains a model explicitly ineligible for coding.");
|
|
8837
|
-
if (new Set(input.models.map((
|
|
8845
|
+
if (new Set(input.models.map((model2) => model2.id.toLowerCase())).size !== input.models.length)
|
|
8838
8846
|
throw new Error("Cline cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
8839
8847
|
const mapping = PROTOCOL[input.protocol];
|
|
8840
8848
|
if ((input.authStyle ?? "bearer") !== mapping.authStyle)
|
|
@@ -8883,7 +8891,7 @@ async function prepareClineLaunch(input) {
|
|
|
8883
8891
|
protocol: mapping.protocol,
|
|
8884
8892
|
client: mapping.client
|
|
8885
8893
|
},
|
|
8886
|
-
models: Object.fromEntries(input.models.map((
|
|
8894
|
+
models: Object.fromEntries(input.models.map((model2) => [model2.id, modelEntry(model2, requestedProtocol)]))
|
|
8887
8895
|
}
|
|
8888
8896
|
}
|
|
8889
8897
|
});
|
|
@@ -8970,8 +8978,8 @@ function permissions(value, path, home) {
|
|
|
8970
8978
|
}
|
|
8971
8979
|
if (own2(value, "permission")) {
|
|
8972
8980
|
const legacy = typeof value.permission === "string" ? { "*": value.permission } : record2(value.permission, path, "permission");
|
|
8973
|
-
for (const [name,
|
|
8974
|
-
const entries = typeof
|
|
8981
|
+
for (const [name, permission2] of Object.entries(legacy)) {
|
|
8982
|
+
const entries = typeof permission2 === "string" ? { "*": permission2 } : record2(permission2, path, "permission");
|
|
8975
8983
|
for (const [resource, item] of Object.entries(entries)) {
|
|
8976
8984
|
const parsed = effect.safeParse(item);
|
|
8977
8985
|
if (!parsed.success)
|
|
@@ -9129,9 +9137,9 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
9129
9137
|
seen.add(canonical);
|
|
9130
9138
|
documents.push({ path, value: jsonc2(text, path) });
|
|
9131
9139
|
}
|
|
9132
|
-
async function agentsDirectory(
|
|
9140
|
+
async function agentsDirectory(directory2) {
|
|
9133
9141
|
for (const source of ["agent", "agents", "mode", "modes"]) {
|
|
9134
|
-
const base = join9(
|
|
9142
|
+
const base = join9(directory2, source), entries = [];
|
|
9135
9143
|
const visited = new Set;
|
|
9136
9144
|
let examined = 0;
|
|
9137
9145
|
async function walk(dir, depth) {
|
|
@@ -9163,22 +9171,22 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
9163
9171
|
for (const path of entries.sort()) {
|
|
9164
9172
|
const text = await read(path, false);
|
|
9165
9173
|
const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
|
|
9166
|
-
let
|
|
9174
|
+
let data2 = {};
|
|
9167
9175
|
if (match) {
|
|
9168
9176
|
const parsed = parseDocument3(match[1], { uniqueKeys: true });
|
|
9169
9177
|
if (parsed.errors.length)
|
|
9170
9178
|
invalid2(path, "agent YAML frontmatter");
|
|
9171
9179
|
try {
|
|
9172
|
-
|
|
9180
|
+
data2 = record2(parsed.toJS({ maxAliasCount: 0 }), path, "agent YAML frontmatter");
|
|
9173
9181
|
} catch {
|
|
9174
9182
|
invalid2(path, "agent YAML frontmatter");
|
|
9175
9183
|
}
|
|
9176
9184
|
}
|
|
9177
9185
|
const body = text.slice(match?.[0].length ?? 0).trim();
|
|
9178
9186
|
const nativeKeys = new Set(["model", "request", "system", "description", "mode", "hidden", "color", "steps", "disabled", "permissions", "variant"]);
|
|
9179
|
-
const legacy = Object.keys(
|
|
9187
|
+
const legacy = Object.keys(data2).some((key) => !nativeKeys.has(key));
|
|
9180
9188
|
const name = relative4(base, path).replaceAll("\\", "/").replace(/\.md$/, "");
|
|
9181
|
-
const value = { ...
|
|
9189
|
+
const value = { ...data2, [legacy ? "prompt" : "system"]: body, ...source === "mode" || source === "modes" ? { mode: "primary" } : {} };
|
|
9182
9190
|
documents.push({ path, value: { [legacy ? "agent" : "agents"]: { [name]: value }, __literalAgentBody: true } });
|
|
9183
9191
|
}
|
|
9184
9192
|
}
|
|
@@ -9359,11 +9367,11 @@ var API = {
|
|
|
9359
9367
|
"openai-chat": "openai-completions"
|
|
9360
9368
|
};
|
|
9361
9369
|
function selectedModels(input) {
|
|
9362
|
-
if (!input.models.length || !input.models.some((
|
|
9370
|
+
if (!input.models.length || !input.models.some((model2) => model2.id === input.model))
|
|
9363
9371
|
throw new Error("Selected model is missing from the launch catalog.");
|
|
9364
|
-
if (input.models.some((
|
|
9372
|
+
if (input.models.some((model2) => !codingEligible(model2)))
|
|
9365
9373
|
throw new Error("Launch catalog contains a model explicitly ineligible for coding.");
|
|
9366
|
-
if (new Set(input.models.map((
|
|
9374
|
+
if (new Set(input.models.map((model2) => model2.id.toLowerCase())).size !== input.models.length)
|
|
9367
9375
|
throw new Error("OMP cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
9368
9376
|
return input.models;
|
|
9369
9377
|
}
|
|
@@ -9381,14 +9389,14 @@ async function prepareOmpLaunch(input) {
|
|
|
9381
9389
|
await mkdir8(agentDir, { recursive: true, mode: 448 });
|
|
9382
9390
|
await mkdir8(sessionDir, { recursive: true, mode: 448 });
|
|
9383
9391
|
const api = API[input.protocol];
|
|
9384
|
-
const modelDefinitions = models.map((
|
|
9385
|
-
id:
|
|
9386
|
-
name:
|
|
9392
|
+
const modelDefinitions = models.map((model2) => ({
|
|
9393
|
+
id: model2.id,
|
|
9394
|
+
name: model2.name,
|
|
9387
9395
|
api,
|
|
9388
|
-
input: (
|
|
9389
|
-
supportsTools:
|
|
9390
|
-
...
|
|
9391
|
-
...
|
|
9396
|
+
input: (model2.inputModalities ?? ["text"]).filter((value) => value === "text" || value === "image").length ? (model2.inputModalities ?? ["text"]).filter((value) => value === "text" || value === "image") : ["text"],
|
|
9397
|
+
supportsTools: model2.supportedParameters?.includes("tools") ?? true,
|
|
9398
|
+
...model2.contextWindow ? { contextWindow: model2.contextWindow } : {},
|
|
9399
|
+
...model2.maxOutputTokens ? { maxTokens: model2.maxOutputTokens } : {}
|
|
9392
9400
|
}));
|
|
9393
9401
|
const provider = {
|
|
9394
9402
|
name: "Switcher",
|
|
@@ -9448,9 +9456,9 @@ var tasks = {
|
|
|
9448
9456
|
session_search: "fast",
|
|
9449
9457
|
web_extract: "fast"
|
|
9450
9458
|
};
|
|
9451
|
-
function model2(value,
|
|
9459
|
+
function model2(value, label2) {
|
|
9452
9460
|
if (typeof value !== "string" || value.length < 1 || value.length > 300 || /[\u0000-\u001f\u007f]/.test(value))
|
|
9453
|
-
throw new Fault(400, "invalid_model_policy", `${
|
|
9461
|
+
throw new Fault(400, "invalid_model_policy", `${label2} is invalid.`);
|
|
9454
9462
|
return value;
|
|
9455
9463
|
}
|
|
9456
9464
|
function endpoint2(value) {
|
|
@@ -9467,12 +9475,12 @@ function endpoint2(value) {
|
|
|
9467
9475
|
throw new Fault(400, "invalid_url", "Hermes auxiliary endpoint must be HTTPS or loopback HTTP without credentials.");
|
|
9468
9476
|
return url.href.replace(/\/+$/, "");
|
|
9469
9477
|
}
|
|
9470
|
-
function compileHermesModelPolicy(currentModel,
|
|
9478
|
+
function compileHermesModelPolicy(currentModel, roles2, baseUrl, apiMode = "chat_completions") {
|
|
9471
9479
|
const selected = model2(currentModel, "model");
|
|
9472
|
-
if (
|
|
9480
|
+
if (roles2.editor && roles2.editor !== selected)
|
|
9473
9481
|
throw new Fault(422, "unsupported_role", "Hermes does not expose a separate editor model.");
|
|
9474
9482
|
const endpointUrl = endpoint2(baseUrl);
|
|
9475
|
-
const chosen = (role) => model2(
|
|
9483
|
+
const chosen = (role) => model2(roles2[role] ?? selected, `roles.${role}`);
|
|
9476
9484
|
const auxiliary = Object.create(null);
|
|
9477
9485
|
for (const [task, role] of Object.entries(tasks))
|
|
9478
9486
|
auxiliary[task] = { api_mode: apiMode, provider: "custom", model: chosen(role), base_url: endpointUrl, api_key_env: "SWITCHER_HERMES_AUX_API_KEY", fallback_chain: [] };
|
|
@@ -9497,7 +9505,7 @@ var apiMode = hermesApiMode;
|
|
|
9497
9505
|
function createHermesBridge(input, timing = {}) {
|
|
9498
9506
|
const protocol = input.protocol;
|
|
9499
9507
|
const token = crypto.randomUUID() + crypto.randomUUID();
|
|
9500
|
-
const modelIds = new Set(input.models.map((
|
|
9508
|
+
const modelIds = new Set(input.models.map((model3) => model3.id));
|
|
9501
9509
|
const active = new Set;
|
|
9502
9510
|
let closing = false;
|
|
9503
9511
|
let server;
|
|
@@ -9507,7 +9515,7 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9507
9515
|
port: 0,
|
|
9508
9516
|
maxRequestBodySize: 4 * 1024 * 1024,
|
|
9509
9517
|
idleTimeout: 255,
|
|
9510
|
-
async fetch(request,
|
|
9518
|
+
async fetch(request, server2) {
|
|
9511
9519
|
if (closing)
|
|
9512
9520
|
return Response.json({ error: { message: "Hermes bridge is closing" } }, { status: 503 });
|
|
9513
9521
|
const nativeHeader = protocol === "anthropic-messages" ? "x-api-key" : "authorization";
|
|
@@ -9521,13 +9529,13 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9521
9529
|
if (request.method === "GET" && path === "/v1/models") {
|
|
9522
9530
|
return Response.json({
|
|
9523
9531
|
object: "list",
|
|
9524
|
-
data: input.models.map((
|
|
9525
|
-
id:
|
|
9532
|
+
data: input.models.map((model3) => ({
|
|
9533
|
+
id: model3.id,
|
|
9526
9534
|
object: "model",
|
|
9527
|
-
name:
|
|
9535
|
+
name: model3.name,
|
|
9528
9536
|
owned_by: "switcher",
|
|
9529
|
-
context_window:
|
|
9530
|
-
max_output_tokens:
|
|
9537
|
+
context_window: model3.contextWindow,
|
|
9538
|
+
max_output_tokens: model3.maxOutputTokens
|
|
9531
9539
|
}))
|
|
9532
9540
|
});
|
|
9533
9541
|
}
|
|
@@ -9541,25 +9549,25 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9541
9549
|
}
|
|
9542
9550
|
if (!body || typeof body !== "object" || typeof body.model !== "string")
|
|
9543
9551
|
return Response.json({ error: { message: "A model is required" } }, { status: 400 });
|
|
9544
|
-
const
|
|
9545
|
-
if (!modelIds.has(
|
|
9552
|
+
const selectedModel2 = body.model;
|
|
9553
|
+
if (!modelIds.has(selectedModel2))
|
|
9546
9554
|
return Response.json({ error: { message: "Model is outside the Switcher launch catalog" } }, { status: 403 });
|
|
9547
9555
|
const abortController = new AbortController;
|
|
9548
9556
|
let complete;
|
|
9549
|
-
const
|
|
9557
|
+
const record3 = {
|
|
9550
9558
|
abort: abortController,
|
|
9551
|
-
done: new Promise((
|
|
9552
|
-
complete =
|
|
9559
|
+
done: new Promise((resolve8) => {
|
|
9560
|
+
complete = resolve8;
|
|
9553
9561
|
})
|
|
9554
9562
|
};
|
|
9555
9563
|
const activity = createProviderRequest(request.signal, abortController.signal, timing);
|
|
9556
9564
|
const release = () => {
|
|
9557
9565
|
activity.finish();
|
|
9558
|
-
active.delete(
|
|
9566
|
+
active.delete(record3);
|
|
9559
9567
|
complete();
|
|
9560
9568
|
};
|
|
9561
|
-
active.add(
|
|
9562
|
-
|
|
9569
|
+
active.add(record3);
|
|
9570
|
+
record3.cancel = async () => {
|
|
9563
9571
|
abortController.abort();
|
|
9564
9572
|
release();
|
|
9565
9573
|
};
|
|
@@ -9574,7 +9582,7 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9574
9582
|
if (beta)
|
|
9575
9583
|
headers["anthropic-beta"] = beta;
|
|
9576
9584
|
}
|
|
9577
|
-
|
|
9585
|
+
server2.timeout(request, 0);
|
|
9578
9586
|
try {
|
|
9579
9587
|
const upstream = await activity.run(() => fetch(`${input.baseUrl}${routePath[protocol].replace(/^\/v1/, "")}`, {
|
|
9580
9588
|
method: "POST",
|
|
@@ -9595,7 +9603,7 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9595
9603
|
return new Response(null, { status: upstream.status });
|
|
9596
9604
|
}
|
|
9597
9605
|
const { stream, cancel } = proxyProviderStream({ response: upstream, protocol: input.protocol, requestSignal: request.signal, abort: abortController, closing: () => closing, release, activity });
|
|
9598
|
-
|
|
9606
|
+
record3.cancel = cancel;
|
|
9599
9607
|
return new Response(stream, {
|
|
9600
9608
|
status: upstream.status,
|
|
9601
9609
|
headers: {
|
|
@@ -9615,11 +9623,11 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9615
9623
|
cleanup: () => stopped ??= (async () => {
|
|
9616
9624
|
closing = true;
|
|
9617
9625
|
const pending = [...active];
|
|
9618
|
-
for (const
|
|
9619
|
-
|
|
9620
|
-
await Promise.allSettled(pending.map(async (
|
|
9621
|
-
await
|
|
9622
|
-
await
|
|
9626
|
+
for (const record3 of pending)
|
|
9627
|
+
record3.abort.abort();
|
|
9628
|
+
await Promise.allSettled(pending.map(async (record3) => {
|
|
9629
|
+
await record3.cancel?.();
|
|
9630
|
+
await record3.done;
|
|
9623
9631
|
}));
|
|
9624
9632
|
await server.stop(true);
|
|
9625
9633
|
})()
|
|
@@ -9630,9 +9638,9 @@ async function prepareHermesLaunch(input) {
|
|
|
9630
9638
|
throw new Error("Launch state and working directories must be absolute.");
|
|
9631
9639
|
if (input.protocol !== "anthropic-messages" && input.protocol !== "openai-responses" && input.protocol !== "openai-chat")
|
|
9632
9640
|
throw new Error("Hermes does not support this provider protocol.");
|
|
9633
|
-
if (!input.models.length || !input.models.some((
|
|
9641
|
+
if (!input.models.length || !input.models.some((model3) => model3.id === input.model))
|
|
9634
9642
|
throw new Error("Selected model is missing from the launch catalog.");
|
|
9635
|
-
if (new Set(input.models.map((
|
|
9643
|
+
if (new Set(input.models.map((model3) => model3.id.toLowerCase())).size !== input.models.length)
|
|
9636
9644
|
throw new Error("Hermes cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
9637
9645
|
if (input.credential && /[\r\n]/.test(input.credential))
|
|
9638
9646
|
throw new Error("Provider credential contains invalid header characters.");
|
|
@@ -9964,20 +9972,20 @@ function toolsPermission(value, path) {
|
|
|
9964
9972
|
const tools = policyRecord(value, path);
|
|
9965
9973
|
if (tools === undefined)
|
|
9966
9974
|
return;
|
|
9967
|
-
const
|
|
9975
|
+
const permission2 = {};
|
|
9968
9976
|
for (const [name, enabled] of Object.entries(tools)) {
|
|
9969
9977
|
if (typeof enabled !== "boolean")
|
|
9970
9978
|
throw new Error(`OpenCode tools policy at ${path}.${name} must be boolean.`);
|
|
9971
|
-
|
|
9979
|
+
permission2[name === "write" || name === "edit" || name === "patch" ? "edit" : name] = enabled ? "allow" : "deny";
|
|
9972
9980
|
}
|
|
9973
|
-
return
|
|
9981
|
+
return permission2;
|
|
9974
9982
|
}
|
|
9975
9983
|
function expandHomePattern(value) {
|
|
9976
9984
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
9977
9985
|
return value;
|
|
9978
|
-
const
|
|
9986
|
+
const record3 = value;
|
|
9979
9987
|
const output = {};
|
|
9980
|
-
for (const [key, item] of Object.entries(
|
|
9988
|
+
for (const [key, item] of Object.entries(record3)) {
|
|
9981
9989
|
const expanded = key === "~" ? homedir7() : key.startsWith("~/") ? join12(homedir7(), key.slice(2)) : key;
|
|
9982
9990
|
output[expanded] = expandHomePattern(item);
|
|
9983
9991
|
}
|
|
@@ -9986,9 +9994,9 @@ function expandHomePattern(value) {
|
|
|
9986
9994
|
function policyWithExpandedPatterns(value) {
|
|
9987
9995
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
9988
9996
|
return value;
|
|
9989
|
-
const
|
|
9997
|
+
const record3 = value;
|
|
9990
9998
|
const output = {};
|
|
9991
|
-
for (const [key, item] of Object.entries(
|
|
9999
|
+
for (const [key, item] of Object.entries(record3))
|
|
9992
10000
|
output[key] = typeof item === "object" && item !== null && !Array.isArray(item) ? expandHomePattern(item) : item;
|
|
9993
10001
|
return output;
|
|
9994
10002
|
}
|
|
@@ -10002,7 +10010,7 @@ function decodePolicy(text, file) {
|
|
|
10002
10010
|
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
10003
10011
|
throw new Error(`OpenCode config at ${file} must be an object.`);
|
|
10004
10012
|
const config = parsed;
|
|
10005
|
-
const
|
|
10013
|
+
const permission2 = policyWithExpandedPatterns(policyValue(config.permission, `${file}:permission`));
|
|
10006
10014
|
const toolsValue = policyRecord(config.tools, `${file}:tools`);
|
|
10007
10015
|
const tools = {};
|
|
10008
10016
|
for (const [name, value] of Object.entries(toolsValue ?? {})) {
|
|
@@ -10029,7 +10037,7 @@ function decodePolicy(text, file) {
|
|
|
10029
10037
|
if (merged !== undefined)
|
|
10030
10038
|
mode[name] = { permission: merged };
|
|
10031
10039
|
}
|
|
10032
|
-
return { ...
|
|
10040
|
+
return { ...permission2 !== undefined ? { permission: permission2 } : {}, ...Object.keys(tools).length ? { tools } : {}, ...Object.keys(agent).length ? { agent } : {}, ...Object.keys(mode).length ? { mode } : {} };
|
|
10033
10041
|
}
|
|
10034
10042
|
async function readPolicyFile(file) {
|
|
10035
10043
|
let text;
|
|
@@ -10077,13 +10085,13 @@ async function readAgentPolicyFile(file, kind, root) {
|
|
|
10077
10085
|
throw new Error(`OpenCode ${kind} policy could not be parsed safely: ${file}`, { cause: error });
|
|
10078
10086
|
}
|
|
10079
10087
|
const frontmatter = policyRecord(parsed, `${file}:frontmatter`);
|
|
10080
|
-
const
|
|
10088
|
+
const permission2 = policyWithExpandedPatterns(policyValue(frontmatter?.permission, `${file}:permission`));
|
|
10081
10089
|
const toolPermission = toolsPermission(frontmatter?.tools, `${file}:tools`);
|
|
10082
|
-
const merged = mergePolicyValue(toolPermission,
|
|
10090
|
+
const merged = mergePolicyValue(toolPermission, permission2);
|
|
10083
10091
|
const fields = nativeAgentFields(frontmatter, file);
|
|
10084
10092
|
fields.prompt = text.slice(match[0].length).trim();
|
|
10085
|
-
const
|
|
10086
|
-
return { name:
|
|
10093
|
+
const relative5 = file.slice(root.length + 1).replaceAll("\\", "/").replace(/\.md$/i, "");
|
|
10094
|
+
return { name: relative5 || basename2(file, ".md"), ...fields, ...merged !== undefined ? { permission: merged } : {} };
|
|
10087
10095
|
}
|
|
10088
10096
|
async function preservedOpenCodePolicy(cwd) {
|
|
10089
10097
|
const result = {};
|
|
@@ -10104,8 +10112,8 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
10104
10112
|
applyLayer(layer);
|
|
10105
10113
|
};
|
|
10106
10114
|
const applyText = (text, source) => applyLayer(decodePolicy(text, source));
|
|
10107
|
-
const applyMarkdown = async (
|
|
10108
|
-
for (const entry of await agentPolicyFiles(
|
|
10115
|
+
const applyMarkdown = async (dir2, kind) => {
|
|
10116
|
+
for (const entry of await agentPolicyFiles(dir2, kind)) {
|
|
10109
10117
|
const policy = await readAgentPolicyFile(entry.file, kind, entry.root);
|
|
10110
10118
|
if (!policy)
|
|
10111
10119
|
continue;
|
|
@@ -10158,25 +10166,25 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
10158
10166
|
if (process.env.OPENCODE_CONFIG_CONTENT)
|
|
10159
10167
|
applyText(process.env.OPENCODE_CONFIG_CONTENT, "OPENCODE_CONFIG_CONTENT");
|
|
10160
10168
|
if (process.env.OPENCODE_PERMISSION) {
|
|
10161
|
-
let
|
|
10169
|
+
let permission2;
|
|
10162
10170
|
try {
|
|
10163
|
-
|
|
10171
|
+
permission2 = JSON.parse(process.env.OPENCODE_PERMISSION);
|
|
10164
10172
|
} catch (error) {
|
|
10165
10173
|
throw new Error("OpenCode permission policy could not be parsed safely: OPENCODE_PERMISSION", { cause: error });
|
|
10166
10174
|
}
|
|
10167
|
-
const value = policyWithExpandedPatterns(policyValue(
|
|
10175
|
+
const value = policyWithExpandedPatterns(policyValue(permission2, "OPENCODE_PERMISSION"));
|
|
10168
10176
|
applyLayer({ permission: value });
|
|
10169
10177
|
}
|
|
10170
10178
|
if (result.tools)
|
|
10171
10179
|
result.permission = mergePolicyValue(toolsPermission(result.tools, "OpenCode tools policy"), result.permission);
|
|
10172
10180
|
return result;
|
|
10173
10181
|
}
|
|
10174
|
-
function codexModel(
|
|
10175
|
-
const reasoning = codexReasoning(
|
|
10182
|
+
function codexModel(model3, priority, baseUrl = "https://provider.invalid", selectedReasoning) {
|
|
10183
|
+
const reasoning = codexReasoning(model3, baseUrl, selectedReasoning);
|
|
10176
10184
|
return {
|
|
10177
|
-
slug:
|
|
10178
|
-
display_name:
|
|
10179
|
-
description:
|
|
10185
|
+
slug: model3.id,
|
|
10186
|
+
display_name: model3.name,
|
|
10187
|
+
description: model3.description ?? model3.id,
|
|
10180
10188
|
shell_type: "shell_command",
|
|
10181
10189
|
visibility: "list",
|
|
10182
10190
|
supported_in_api: true,
|
|
@@ -10190,9 +10198,9 @@ function codexModel(model, priority, baseUrl = "https://provider.invalid", selec
|
|
|
10190
10198
|
apply_patch_tool_type: null,
|
|
10191
10199
|
truncation_policy: { mode: "tokens", limit: 1e4 },
|
|
10192
10200
|
experimental_supported_tools: [],
|
|
10193
|
-
context_window:
|
|
10194
|
-
max_context_window:
|
|
10195
|
-
input_modalities: (
|
|
10201
|
+
context_window: model3.contextWindow ?? null,
|
|
10202
|
+
max_context_window: model3.contextWindow ?? null,
|
|
10203
|
+
input_modalities: (model3.inputModalities ?? ["text"]).filter((m) => m === "text" || m === "image"),
|
|
10196
10204
|
prefer_websockets: false,
|
|
10197
10205
|
use_responses_lite: false,
|
|
10198
10206
|
model_messages: { instructions_template: "You are Codex, a coding assistant. Help the user with their requested work. Follow the user and developer instructions, use the available tools when appropriate, preserve unrelated changes, and report actual results and remaining limitations.", instructions_variables: null }
|
|
@@ -10208,7 +10216,7 @@ function grokBridge(input, timing = {}) {
|
|
|
10208
10216
|
const active = new Set;
|
|
10209
10217
|
const apiBackend = { "anthropic-messages": "messages", "openai-responses": "responses", "openai-chat": "chat_completions", "gemini-generate-content": "generate_content" }[input.protocol];
|
|
10210
10218
|
const apiPath = { "anthropic-messages": "/messages", "openai-responses": "/responses", "openai-chat": "/chat/completions", "gemini-generate-content": "/generateContent" }[input.protocol];
|
|
10211
|
-
server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request,
|
|
10219
|
+
server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
|
|
10212
10220
|
if (closing)
|
|
10213
10221
|
return Response.json({ error: { message: "Bridge is closing" } }, { status: 503 });
|
|
10214
10222
|
const auth = request.headers.get("authorization") ?? (request.headers.has("x-api-key") ? `Bearer ${request.headers.get("x-api-key")}` : "");
|
|
@@ -10223,7 +10231,7 @@ function grokBridge(input, timing = {}) {
|
|
|
10223
10231
|
model: m.id,
|
|
10224
10232
|
name: m.name,
|
|
10225
10233
|
description: m.description,
|
|
10226
|
-
base_url: new URL("v1",
|
|
10234
|
+
base_url: new URL("v1", server2.url).href,
|
|
10227
10235
|
context_window: m.contextWindow,
|
|
10228
10236
|
max_completion_tokens: m.maxOutputTokens,
|
|
10229
10237
|
api_backend: apiBackend,
|
|
@@ -10253,17 +10261,17 @@ function grokBridge(input, timing = {}) {
|
|
|
10253
10261
|
if (closing)
|
|
10254
10262
|
return Response.json({ error: { message: "Bridge is closing" } }, { status: 503 });
|
|
10255
10263
|
let complete;
|
|
10256
|
-
const
|
|
10257
|
-
complete =
|
|
10264
|
+
const record3 = { abort: new AbortController, done: new Promise((resolve9) => {
|
|
10265
|
+
complete = resolve9;
|
|
10258
10266
|
}) };
|
|
10259
|
-
const activity = createProviderRequest(request.signal,
|
|
10267
|
+
const activity = createProviderRequest(request.signal, record3.abort.signal, timing);
|
|
10260
10268
|
const release = () => {
|
|
10261
10269
|
activity.finish();
|
|
10262
|
-
active.delete(
|
|
10270
|
+
active.delete(record3);
|
|
10263
10271
|
complete();
|
|
10264
10272
|
};
|
|
10265
|
-
active.add(
|
|
10266
|
-
|
|
10273
|
+
active.add(record3);
|
|
10274
|
+
server2.timeout(request, 0);
|
|
10267
10275
|
try {
|
|
10268
10276
|
const response = await activity.run(() => fetch(`${input.baseUrl}${apiPath}`, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
|
|
10269
10277
|
if (!response.ok) {
|
|
@@ -10277,8 +10285,8 @@ function grokBridge(input, timing = {}) {
|
|
|
10277
10285
|
release();
|
|
10278
10286
|
return new Response(null, { status: response.status });
|
|
10279
10287
|
}
|
|
10280
|
-
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort:
|
|
10281
|
-
|
|
10288
|
+
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record3.abort, closing: () => closing, release, activity });
|
|
10289
|
+
record3.cancel = cancel;
|
|
10282
10290
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
10283
10291
|
} catch {
|
|
10284
10292
|
release();
|
|
@@ -10288,30 +10296,30 @@ function grokBridge(input, timing = {}) {
|
|
|
10288
10296
|
return { baseUrl: new URL("v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
|
|
10289
10297
|
closing = true;
|
|
10290
10298
|
const pending = [...active];
|
|
10291
|
-
for (const
|
|
10292
|
-
|
|
10293
|
-
await Promise.allSettled(pending.map(async (
|
|
10294
|
-
await
|
|
10295
|
-
await
|
|
10299
|
+
for (const record3 of pending)
|
|
10300
|
+
record3.abort.abort();
|
|
10301
|
+
await Promise.allSettled(pending.map(async (record3) => {
|
|
10302
|
+
await record3.cancel?.();
|
|
10303
|
+
await record3.done;
|
|
10296
10304
|
}));
|
|
10297
10305
|
await server.stop(true);
|
|
10298
10306
|
})() };
|
|
10299
10307
|
}
|
|
10300
|
-
function grokAlias(input,
|
|
10301
|
-
return "switcher-" + createHash9("sha256").update(JSON.stringify([input.providerBaseUrl ?? input.baseUrl, input.protocol])).digest("hex").slice(0, 12) + "/" +
|
|
10308
|
+
function grokAlias(input, model3) {
|
|
10309
|
+
return "switcher-" + createHash9("sha256").update(JSON.stringify([input.providerBaseUrl ?? input.baseUrl, input.protocol])).digest("hex").slice(0, 12) + "/" + model3;
|
|
10302
10310
|
}
|
|
10303
10311
|
function piProviderId(input, providerBaseUrl) {
|
|
10304
10312
|
return "switcher-" + createHash9("sha256").update(JSON.stringify([endpoint(providerBaseUrl), input.protocol])).digest("hex").slice(0, 12);
|
|
10305
10313
|
}
|
|
10306
10314
|
function piModel(input, api) {
|
|
10307
|
-
return input.models.map((
|
|
10308
|
-
id:
|
|
10309
|
-
name:
|
|
10315
|
+
return input.models.map((model3) => ({
|
|
10316
|
+
id: model3.id,
|
|
10317
|
+
name: model3.name,
|
|
10310
10318
|
api,
|
|
10311
|
-
...
|
|
10312
|
-
...
|
|
10313
|
-
input: (
|
|
10314
|
-
...
|
|
10319
|
+
...model3.contextWindow ? { contextWindow: model3.contextWindow } : {},
|
|
10320
|
+
...model3.maxOutputTokens ? { maxTokens: model3.maxOutputTokens } : {},
|
|
10321
|
+
input: (model3.inputModalities ?? ["text"]).filter((modality) => modality === "text" || modality === "image").length > 0 ? (model3.inputModalities ?? ["text"]).filter((modality) => modality === "text" || modality === "image") : ["text"],
|
|
10322
|
+
...model3.supportedParameters?.includes("reasoning") ? { reasoning: true } : {}
|
|
10315
10323
|
}));
|
|
10316
10324
|
}
|
|
10317
10325
|
function primeProviderId(input, providerBaseUrl) {
|
|
@@ -10321,8 +10329,8 @@ var PRIME_UNIX_SOCKET_LIMIT = 100;
|
|
|
10321
10329
|
var PRIME_DAEMON_STARTUP_TIMEOUT_MS = 30000;
|
|
10322
10330
|
var PRIME_DAEMON_SHUTDOWN_TIMEOUT_MS = 5000;
|
|
10323
10331
|
function primeSocketPaths(runtimeDir) {
|
|
10324
|
-
const
|
|
10325
|
-
const daemonSocket = join12(runtimeDir,
|
|
10332
|
+
const basename3 = `p-${randomUUID4().replaceAll("-", "").slice(0, 8)}.sock`;
|
|
10333
|
+
const daemonSocket = join12(runtimeDir, basename3);
|
|
10326
10334
|
const uid = typeof process.getuid === "function" ? String(process.getuid()) : "user";
|
|
10327
10335
|
const workerDir = join12(runtimeDir, `prime-agent-${uid}`);
|
|
10328
10336
|
const workerKey = createHash9("sha256").update(daemonSocket).digest("hex").slice(0, 12);
|
|
@@ -10355,7 +10363,7 @@ function primeSignalSupervisor(supervisor, signal) {
|
|
|
10355
10363
|
} catch {}
|
|
10356
10364
|
}
|
|
10357
10365
|
async function primeReadinessProbe(socketPath) {
|
|
10358
|
-
await new Promise((
|
|
10366
|
+
await new Promise((resolve9, reject2) => {
|
|
10359
10367
|
const socket = createConnection(socketPath);
|
|
10360
10368
|
let settled = false;
|
|
10361
10369
|
let buffer = "";
|
|
@@ -10365,7 +10373,7 @@ async function primeReadinessProbe(socketPath) {
|
|
|
10365
10373
|
settled = true;
|
|
10366
10374
|
socket.removeAllListeners();
|
|
10367
10375
|
socket.destroy();
|
|
10368
|
-
error ?
|
|
10376
|
+
error ? reject2(error) : resolve9();
|
|
10369
10377
|
};
|
|
10370
10378
|
const timer = setTimeout(() => finish(new Error("Prime Agent daemon hello timed out.")), 500);
|
|
10371
10379
|
const onLine = (line) => {
|
|
@@ -10420,12 +10428,12 @@ async function primeStartSupervisor(input, executable, socketPath, env, onSpawn)
|
|
|
10420
10428
|
await primeReadinessProbe(socketPath);
|
|
10421
10429
|
return supervisor;
|
|
10422
10430
|
} catch {}
|
|
10423
|
-
await new Promise((
|
|
10431
|
+
await new Promise((resolve9) => setTimeout(resolve9, 25));
|
|
10424
10432
|
}
|
|
10425
10433
|
throw new Error(`Prime Agent daemon did not become ready within ${PRIME_DAEMON_STARTUP_TIMEOUT_MS / 1000} seconds.`);
|
|
10426
10434
|
} catch (error) {
|
|
10427
10435
|
primeSignalSupervisor(supervisor, "SIGTERM");
|
|
10428
|
-
await Promise.race([supervisor.exited, new Promise((
|
|
10436
|
+
await Promise.race([supervisor.exited, new Promise((resolve9) => setTimeout(resolve9, 1000))]);
|
|
10429
10437
|
if (!exited)
|
|
10430
10438
|
primeSignalSupervisor(supervisor, "SIGKILL");
|
|
10431
10439
|
throw error;
|
|
@@ -10439,7 +10447,7 @@ async function primeOwnedShutdown(socketPath, workerPrefix) {
|
|
|
10439
10447
|
let responseSeen = false;
|
|
10440
10448
|
const requestId = `switcher_${randomUUID4()}`;
|
|
10441
10449
|
let requestSent = false;
|
|
10442
|
-
await new Promise((
|
|
10450
|
+
await new Promise((resolve9, reject2) => {
|
|
10443
10451
|
const socket = createConnection(socketPath);
|
|
10444
10452
|
let settled = false;
|
|
10445
10453
|
let buffer = "";
|
|
@@ -10453,9 +10461,9 @@ async function primeOwnedShutdown(socketPath, workerPrefix) {
|
|
|
10453
10461
|
socket.removeAllListeners();
|
|
10454
10462
|
socket.destroy();
|
|
10455
10463
|
if (error)
|
|
10456
|
-
|
|
10464
|
+
reject2(error);
|
|
10457
10465
|
else
|
|
10458
|
-
|
|
10466
|
+
resolve9();
|
|
10459
10467
|
};
|
|
10460
10468
|
timeout = setTimeout(() => finish(new Error(`Timed out shutting down the Prime Agent daemon on ${socketPath}.`)), 3000);
|
|
10461
10469
|
const onLine = (line) => {
|
|
@@ -10504,12 +10512,12 @@ async function primeOwnedShutdown(socketPath, workerPrefix) {
|
|
|
10504
10512
|
const [daemonExists, workers] = await Promise.all([exists(), workerEntries()]);
|
|
10505
10513
|
if (!daemonExists && !workers.length)
|
|
10506
10514
|
return;
|
|
10507
|
-
await new Promise((
|
|
10515
|
+
await new Promise((resolve9) => setTimeout(resolve9, 50));
|
|
10508
10516
|
}
|
|
10509
10517
|
throw new Error(responseSeen ? `Prime Agent owned daemon or worker sockets remained after shutdown (${socketPath}).` : `Prime Agent daemon did not acknowledge owned shutdown and remained reachable (${socketPath}).`);
|
|
10510
10518
|
}
|
|
10511
10519
|
async function primeWaitExit(supervisor, timeout) {
|
|
10512
|
-
return await Promise.race([supervisor.exited.then(() => true), new Promise((
|
|
10520
|
+
return await Promise.race([supervisor.exited.then(() => true), new Promise((resolve9) => setTimeout(() => resolve9(false), timeout))]);
|
|
10513
10521
|
}
|
|
10514
10522
|
async function primeRemainingSockets(socketPath, workerPrefix) {
|
|
10515
10523
|
const daemon = await access3(socketPath).then(() => true, () => false);
|
|
@@ -10519,14 +10527,14 @@ async function primeRemainingSockets(socketPath, workerPrefix) {
|
|
|
10519
10527
|
return [...daemon ? [socketPath] : [], ...workers.map((entry) => join12(workerDir, entry))];
|
|
10520
10528
|
}
|
|
10521
10529
|
function primeModel(input, api) {
|
|
10522
|
-
return input.models.map((
|
|
10523
|
-
id:
|
|
10524
|
-
...
|
|
10530
|
+
return input.models.map((model3) => ({
|
|
10531
|
+
id: model3.id,
|
|
10532
|
+
...model3.name ? { name: model3.name } : {},
|
|
10525
10533
|
api,
|
|
10526
|
-
reasoning:
|
|
10527
|
-
input: (
|
|
10528
|
-
...
|
|
10529
|
-
...
|
|
10534
|
+
reasoning: model3.supportedParameters?.includes("reasoning") ?? false,
|
|
10535
|
+
input: (model3.inputModalities ?? ["text"]).filter((modality) => modality === "text" || modality === "image").length > 0 ? (model3.inputModalities ?? ["text"]).filter((modality) => modality === "text" || modality === "image") : ["text"],
|
|
10536
|
+
...model3.contextWindow ? { contextWindow: model3.contextWindow } : {},
|
|
10537
|
+
...model3.maxOutputTokens ? { maxTokens: model3.maxOutputTokens } : {}
|
|
10530
10538
|
}));
|
|
10531
10539
|
}
|
|
10532
10540
|
async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUrl ?? input.baseUrl) {
|
|
@@ -10567,16 +10575,16 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10567
10575
|
env.ANTHROPIC_API_KEY = "";
|
|
10568
10576
|
env.ANTHROPIC_AUTH_TOKEN = "";
|
|
10569
10577
|
env[input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"] = input.credential ?? "switcher-local-no-auth";
|
|
10570
|
-
const
|
|
10571
|
-
configPaths.push(
|
|
10578
|
+
const file2 = await jsonFile(input.stateDir, "claude-settings.json", { modelPicker: { replaceBuiltInOptions: true, options: input.models.map((m) => ({ model: m.id, label: m.name, description: m.description?.slice(0, 300) })) } });
|
|
10579
|
+
configPaths.push(file2);
|
|
10572
10580
|
warnings.push("Claude managed settings and model allowlists can restrict the generated picker.");
|
|
10573
|
-
return { executable, args: ["--settings",
|
|
10581
|
+
return { executable, args: ["--settings", file2, "--model", input.model, ...args], env, configPaths, warnings };
|
|
10574
10582
|
}
|
|
10575
10583
|
if (input.harness === "codex") {
|
|
10576
|
-
const
|
|
10577
|
-
const
|
|
10578
|
-
configPaths.push(
|
|
10579
|
-
configPaths.push(...Object.values(
|
|
10584
|
+
const rolePolicy2 = await prepareCodexModelPolicy({ cwd: input.cwd, stateDir: input.stateDir, model: input.model, policy: input.modelPolicy ? { version: 1, ...input.modelPolicy } : undefined, switcherProvider: "switcher", switcherBaseUrl: input.baseUrl });
|
|
10585
|
+
const file2 = await jsonFile(input.stateDir, "codex-models.json", { models: input.models.map((model3, index) => codexModel(model3, index, providerBaseUrl, model3.id === input.model ? input.reasoning : undefined)) });
|
|
10586
|
+
configPaths.push(file2);
|
|
10587
|
+
configPaths.push(...Object.values(rolePolicy2.agentConfigPaths));
|
|
10580
10588
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
10581
10589
|
const provider = { name: "Switcher", base_url: input.baseUrl, wire_api: "responses", requires_openai_auth: false };
|
|
10582
10590
|
{
|
|
@@ -10586,8 +10594,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10586
10594
|
provider.env_key = KEY4;
|
|
10587
10595
|
}
|
|
10588
10596
|
const toml = Object.entries(provider).map(([k, v]) => `${k} = ${typeof v === "object" ? "{ " + Object.entries(v).map(([key, value]) => `${quote(key)} = ${quote(value)}`).join(", ") + " }" : quote(v)}`).join(", ");
|
|
10589
|
-
const overrides = ["-c", `model_provider="switcher"`, "-c", `model_providers.switcher={ ${toml} }`, "-c", `model_catalog_json=${quote(
|
|
10590
|
-
for (const [name, path] of Object.entries(
|
|
10597
|
+
const overrides = ["-c", `model_provider="switcher"`, "-c", `model_providers.switcher={ ${toml} }`, "-c", `model_catalog_json=${quote(file2)}`, "-c", `model=${quote(input.model)}`, "-c", `review_model=${quote(input.compiledPolicy?.roles.review ?? input.model)}`, "-c", `agents.default_subagent_model=${quote(input.compiledPolicy?.roles.subagent ?? input.model)}`];
|
|
10598
|
+
for (const [name, path] of Object.entries(rolePolicy2.agentConfigPaths)) {
|
|
10591
10599
|
if (!/^[A-Za-z0-9_-]+$/.test(name))
|
|
10592
10600
|
throw new Error("Codex role names containing punctuation beyond hyphens/underscores cannot be safely overridden by this native CLI.");
|
|
10593
10601
|
overrides.push("-c", `agents.${name}.config_file=${quote(path)}`);
|
|
@@ -10604,22 +10612,22 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10604
10612
|
}
|
|
10605
10613
|
if (input.harness === "grok") {
|
|
10606
10614
|
validateGrokResume(args);
|
|
10607
|
-
const
|
|
10608
|
-
configPaths.push(
|
|
10615
|
+
const file2 = await jsonFile(input.stateDir, "grok-overlay.json", { models: { default: grokAlias(input, input.model), session_summary: grokAlias(input, input.compiledPolicy?.roles.summary ?? input.model), allowed_models: input.models.map((m) => grokAlias(input, m.id)) } });
|
|
10616
|
+
configPaths.push(file2);
|
|
10609
10617
|
const bridge = grokBridge(input);
|
|
10610
10618
|
env.GROK_MODELS_BASE_URL = bridge.baseUrl;
|
|
10611
10619
|
env.GROK_MODELS_LIST_URL = bridge.baseUrl + "/models";
|
|
10612
10620
|
env.GROK_XAI_API_BASE_URL = bridge.baseUrl;
|
|
10613
10621
|
env.XAI_API_KEY = bridge.token;
|
|
10614
10622
|
env[KEY4] = bridge.token;
|
|
10615
|
-
env.GROK_CONFIG_PATH =
|
|
10623
|
+
env.GROK_CONFIG_PATH = file2;
|
|
10616
10624
|
warnings.push("Grok uses a per-launch loopback catalog/auth bridge; native managed model policies still apply.");
|
|
10617
10625
|
return { executable, args: ["--model", grokAlias(input, input.model), "--no-leader", ...args], env, configPaths, warnings, cleanup: bridge.cleanup };
|
|
10618
10626
|
}
|
|
10619
10627
|
if (input.harness === "pi") {
|
|
10620
10628
|
if (input.authStyle === "x-api-key" && input.protocol !== "anthropic-messages")
|
|
10621
10629
|
throw new Error("Pi can use x-api-key authentication only with the Anthropic Messages protocol.");
|
|
10622
|
-
if (new Set(input.models.map((
|
|
10630
|
+
if (new Set(input.models.map((model3) => model3.id.toLowerCase())).size !== input.models.length)
|
|
10623
10631
|
throw new Error("Pi cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
10624
10632
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions", "gemini-generate-content": "gemini" }[input.protocol];
|
|
10625
10633
|
const providerId = piProviderId(input, providerBaseUrl);
|
|
@@ -10628,14 +10636,14 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10628
10636
|
const piBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
|
|
10629
10637
|
await mkdir10(agentDir, { recursive: true, mode: 448 });
|
|
10630
10638
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
10631
|
-
const
|
|
10639
|
+
const file2 = await jsonFile(agentDir, "models.json", { providers: { [providerId]: {
|
|
10632
10640
|
name: "Switcher",
|
|
10633
10641
|
baseUrl: piBaseUrl,
|
|
10634
10642
|
api,
|
|
10635
10643
|
apiKey: `$${KEY4}`,
|
|
10636
10644
|
models: piModel(input, api)
|
|
10637
10645
|
} } });
|
|
10638
|
-
configPaths.push(
|
|
10646
|
+
configPaths.push(file2);
|
|
10639
10647
|
env.PI_CODING_AGENT_DIR = agentDir;
|
|
10640
10648
|
env.PI_CODING_AGENT_SESSION_DIR = sessionDir;
|
|
10641
10649
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
@@ -10655,7 +10663,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10655
10663
|
throw new Error("DSH session directory must be absolute.");
|
|
10656
10664
|
await mkdir10(home, { recursive: true, mode: 448 });
|
|
10657
10665
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
10658
|
-
const
|
|
10666
|
+
const route2 = { provider: providerId, model: input.model };
|
|
10659
10667
|
const overlay = [
|
|
10660
10668
|
{ id: "llm-deepseek", disabled: true },
|
|
10661
10669
|
{ id: "llm-pi-ai", config: { providers: { [providerId]: {
|
|
@@ -10663,21 +10671,21 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10663
10671
|
api,
|
|
10664
10672
|
apiKeyEnv: KEY4,
|
|
10665
10673
|
baseURL: input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl,
|
|
10666
|
-
models: input.models.map((
|
|
10667
|
-
id:
|
|
10668
|
-
name:
|
|
10669
|
-
...
|
|
10670
|
-
...
|
|
10671
|
-
input: (
|
|
10674
|
+
models: input.models.map((model3) => ({
|
|
10675
|
+
id: model3.id,
|
|
10676
|
+
name: model3.name,
|
|
10677
|
+
...model3.contextWindow ? { contextWindow: model3.contextWindow } : {},
|
|
10678
|
+
...model3.maxOutputTokens ? { maxTokens: model3.maxOutputTokens } : {},
|
|
10679
|
+
input: (model3.inputModalities ?? ["text"]).filter((modality) => modality === "text" || modality === "image")
|
|
10672
10680
|
}))
|
|
10673
10681
|
} } } },
|
|
10674
|
-
{ id: "agent-default-model", config:
|
|
10682
|
+
{ id: "agent-default-model", config: route2 },
|
|
10675
10683
|
{ id: "session-persistence-jsonl", config: { root: join12(sessionDir, "sessions") } },
|
|
10676
10684
|
{ id: "attachment-local", config: { dshHome: sessionDir } },
|
|
10677
|
-
...selected.profile === "acp" ? [{ id: "acp", config:
|
|
10685
|
+
...selected.profile === "acp" ? [{ id: "acp", config: route2 }] : []
|
|
10678
10686
|
];
|
|
10679
|
-
const
|
|
10680
|
-
configPaths.push(
|
|
10687
|
+
const file2 = await jsonFile(input.stateDir, "dsh-patch.json", overlay);
|
|
10688
|
+
configPaths.push(file2);
|
|
10681
10689
|
env.DSH_HOME = home;
|
|
10682
10690
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
10683
10691
|
warnings.push("DeepSeek Harness uses an isolated temporary home and its native pi-ai provider adapter. Global profiles, settings, plugins and saved credentials are not loaded; sessions and attachments persist under Switcher state per profile. Native project customization remains active.");
|
|
@@ -10685,7 +10693,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10685
10693
|
warnings.push("DSH opens its native browser UI on an allocated loopback port; use -- --no-open to print the URL without opening a browser.");
|
|
10686
10694
|
if (selected.profile === "headless")
|
|
10687
10695
|
warnings.push("DSH headless runs one fresh task; resume is available through the native web UI or ACP session/resume.");
|
|
10688
|
-
return { executable, args: ["--profile", selected.profile, "--patch",
|
|
10696
|
+
return { executable, args: ["--profile", selected.profile, "--patch", file2, ...selected.args], env, configPaths, warnings };
|
|
10689
10697
|
}
|
|
10690
10698
|
if (input.harness === "cline")
|
|
10691
10699
|
return prepareClineLaunch(input);
|
|
@@ -10694,7 +10702,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10694
10702
|
if (input.harness === "prime-agent") {
|
|
10695
10703
|
if (input.authStyle === "x-api-key" && input.protocol !== "anthropic-messages")
|
|
10696
10704
|
throw new Error("Prime Agent can use x-api-key authentication only with the Anthropic Messages protocol.");
|
|
10697
|
-
if (new Set(input.models.map((
|
|
10705
|
+
if (new Set(input.models.map((model3) => model3.id.toLowerCase())).size !== input.models.length)
|
|
10698
10706
|
throw new Error("Prime Agent cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
10699
10707
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
|
|
10700
10708
|
const providerId = primeProviderId(input, providerBaseUrl);
|
|
@@ -10705,8 +10713,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10705
10713
|
const primeBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
|
|
10706
10714
|
await mkdir10(agentDir, { recursive: true, mode: 448 });
|
|
10707
10715
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
10708
|
-
const
|
|
10709
|
-
await writeFile10(
|
|
10716
|
+
const file2 = join12(agentDir, "models.json");
|
|
10717
|
+
await writeFile10(file2, JSON.stringify({ providers: { [providerId]: {
|
|
10710
10718
|
name: "Switcher",
|
|
10711
10719
|
baseUrl: primeBaseUrl,
|
|
10712
10720
|
api,
|
|
@@ -10714,21 +10722,21 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10714
10722
|
models: primeModel(input, api)
|
|
10715
10723
|
} } }, null, 2) + `
|
|
10716
10724
|
`, { mode: 384, flag: "w" });
|
|
10717
|
-
configPaths.push(
|
|
10725
|
+
configPaths.push(file2);
|
|
10718
10726
|
env.PRIME_AGENT_CODING_AGENT_DIR = agentDir;
|
|
10719
10727
|
env.PRIME_AGENT_SESSION_DIR = sessionDir;
|
|
10720
10728
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
10721
10729
|
warnings.push("Prime Agent uses an isolated per-launch models.json catalog and session directory; built-in provider configuration and credential stores are not inherited.");
|
|
10722
10730
|
warnings.push("Prime Agent's model list diagnostic still includes built-in providers; the launch model and scoped picker are restricted to the Switcher provider.");
|
|
10723
10731
|
env.TMPDIR = runtimeDir;
|
|
10724
|
-
const
|
|
10732
|
+
const executable2 = input.executable ?? input.harness;
|
|
10725
10733
|
let supervisor;
|
|
10726
10734
|
let starting;
|
|
10727
10735
|
let ready = false;
|
|
10728
10736
|
const beforeLaunch = async () => {
|
|
10729
10737
|
if (ready)
|
|
10730
10738
|
return;
|
|
10731
|
-
starting ??= primeStartSupervisor(input,
|
|
10739
|
+
starting ??= primeStartSupervisor(input, executable2, daemonSocket, env, (child) => {
|
|
10732
10740
|
supervisor = child;
|
|
10733
10741
|
});
|
|
10734
10742
|
supervisor = await starting;
|
|
@@ -10767,36 +10775,36 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10767
10775
|
if (failure)
|
|
10768
10776
|
throw failure;
|
|
10769
10777
|
};
|
|
10770
|
-
return { executable, args: ["--daemon-socket", daemonSocket, "--provider", providerId, "--model", input.model, "--models", `${providerId}/**`, ...args], env, configPaths, warnings, beforeLaunch, cleanup };
|
|
10778
|
+
return { executable: executable2, args: ["--daemon-socket", daemonSocket, "--provider", providerId, "--model", input.model, "--models", `${providerId}/**`, ...args], env, configPaths, warnings, beforeLaunch, cleanup };
|
|
10771
10779
|
}
|
|
10772
10780
|
if (input.harness === "opencode") {
|
|
10773
|
-
const
|
|
10774
|
-
const
|
|
10775
|
-
const modelConfig = Object.fromEntries(input.models.map((
|
|
10776
|
-
name:
|
|
10777
|
-
...
|
|
10781
|
+
const providerID2 = "switcher-" + createHash9("sha256").update(endpoint(providerBaseUrl) + input.protocol).digest("hex").slice(0, 12);
|
|
10782
|
+
const packageName2 = { "anthropic-messages": "@ai-sdk/anthropic", "openai-responses": "@ai-sdk/openai", "openai-chat": "@ai-sdk/openai-compatible" }[input.protocol];
|
|
10783
|
+
const modelConfig = Object.fromEntries(input.models.map((model3) => [model3.id, {
|
|
10784
|
+
name: model3.name,
|
|
10785
|
+
...model3.contextWindow && model3.maxOutputTokens ? { limit: { context: model3.contextWindow, output: model3.maxOutputTokens } } : {}
|
|
10778
10786
|
}]));
|
|
10779
10787
|
const instructions = await projectInstructionPaths(input.cwd);
|
|
10780
10788
|
const policy = await preservedOpenCodePolicy(input.cwd);
|
|
10781
|
-
const
|
|
10782
|
-
const
|
|
10789
|
+
const rolePolicy2 = compileOpenCodeModelPolicy({ providerId: providerID2, mainModel: input.model, roles: input.compiledPolicy?.roles, format: "legacy", preservedAgents: Object.entries(policy.agent ?? {}).map(([name, agent]) => ({ ...agent, name })) });
|
|
10790
|
+
const config2 = {
|
|
10783
10791
|
$schema: "https://opencode.ai/config.json",
|
|
10784
|
-
small_model: `${
|
|
10785
|
-
enabled_providers: [
|
|
10792
|
+
small_model: `${providerID2}/${input.compiledPolicy?.roles.fast ?? input.model}`,
|
|
10793
|
+
enabled_providers: [providerID2],
|
|
10786
10794
|
...instructions.length ? { instructions } : {},
|
|
10787
10795
|
...policy.permission ? { permission: policy.permission } : {},
|
|
10788
|
-
...
|
|
10796
|
+
...rolePolicy2.config,
|
|
10789
10797
|
...policy.mode ? { mode: policy.mode } : {},
|
|
10790
|
-
provider: { [
|
|
10791
|
-
npm:
|
|
10798
|
+
provider: { [providerID2]: {
|
|
10799
|
+
npm: packageName2,
|
|
10792
10800
|
name: "Switcher",
|
|
10793
10801
|
options: { baseURL: input.baseUrl, apiKey: `{env:${KEY4}}` },
|
|
10794
10802
|
models: modelConfig
|
|
10795
10803
|
} }
|
|
10796
10804
|
};
|
|
10797
|
-
const
|
|
10798
|
-
configPaths.push(
|
|
10799
|
-
env.OPENCODE_CONFIG =
|
|
10805
|
+
const file2 = await jsonFile(input.stateDir, "opencode-legacy.json", config2);
|
|
10806
|
+
configPaths.push(file2);
|
|
10807
|
+
env.OPENCODE_CONFIG = file2;
|
|
10800
10808
|
const sessionDir = input.sessionDir ?? join12(input.stateDir, "sessions");
|
|
10801
10809
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
10802
10810
|
env.XDG_DATA_HOME = join12(sessionDir, "data");
|
|
@@ -10805,12 +10813,12 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10805
10813
|
env.XDG_STATE_HOME = join12(input.stateDir, "state");
|
|
10806
10814
|
env.HOME = join12(input.stateDir, "home");
|
|
10807
10815
|
env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";
|
|
10808
|
-
env.OPENCODE_CONFIG_CONTENT = JSON.stringify(
|
|
10816
|
+
env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config2);
|
|
10809
10817
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
10810
|
-
const
|
|
10811
|
-
const
|
|
10818
|
+
const modelRef2 = openCodeInvocationModel(args, rolePolicy2);
|
|
10819
|
+
const native2 = args[0] === "run" ? ["run", "--model", modelRef2, ...args.slice(1)] : args[0] === "models" ? ["models", ...args.slice(1)] : ["--model", modelRef2, ...args];
|
|
10812
10820
|
warnings.push("Legacy OpenCode uses the documented singular provider configuration and an isolated XDG data root for durable sessions; it is separate from OpenCode 2.");
|
|
10813
|
-
return { executable, args:
|
|
10821
|
+
return { executable, args: native2, env, configPaths, warnings };
|
|
10814
10822
|
}
|
|
10815
10823
|
const providerID = "switcher-" + createHash9("sha256").update(endpoint(providerBaseUrl) + input.protocol).digest("hex").slice(0, 12);
|
|
10816
10824
|
const packageName = { "anthropic-messages": "anthropic", "openai-responses": "openai/responses", "openai-chat": "openai-compatible", "gemini-generate-content": "gemini" }[input.protocol];
|
|
@@ -10820,13 +10828,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10820
10828
|
capabilities: { tools: m.supportedParameters?.includes("tools") ?? true, input: m.inputModalities ?? ["text"], output: m.outputModalities ?? ["text"] },
|
|
10821
10829
|
limit: { ...m.contextWindow ? { context: m.contextWindow } : {}, ...m.maxOutputTokens ? { output: m.maxOutputTokens } : {} }
|
|
10822
10830
|
}]));
|
|
10823
|
-
const
|
|
10831
|
+
const settings2 = { baseURL: input.baseUrl };
|
|
10824
10832
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
10825
|
-
|
|
10833
|
+
settings2.apiKey = `{env:${KEY4}}`;
|
|
10826
10834
|
const isolated = await isolateOpenCode2(input.cwd, input.stateDir, providerID);
|
|
10827
10835
|
const rolePolicy = compileOpenCodeModelPolicy({ providerId: providerID, mainModel: input.model, roles: input.compiledPolicy?.roles, preservedAgents: Object.entries(isolated.config.agents ?? {}).map(([name, agent]) => ({ ...agent, name })) });
|
|
10828
10836
|
const modelRef = openCodeInvocationModel(args, rolePolicy, isolated.config.default_agent);
|
|
10829
|
-
const config = { ...isolated.config, ...rolePolicy.config, providers: { [providerID]: { name: "Switcher", env: [KEY4], package: `@opencode-ai/ai/providers/${packageName}`, settings, models } } };
|
|
10837
|
+
const config = { ...isolated.config, ...rolePolicy.config, providers: { [providerID]: { name: "Switcher", env: [KEY4], package: `@opencode-ai/ai/providers/${packageName}`, settings: settings2, models } } };
|
|
10830
10838
|
const file = join12(input.stateDir, "opencode.json");
|
|
10831
10839
|
await writeFile10(file, openCode2ConfigText(config, providerID, KEY4), { mode: 384, flag: "wx" });
|
|
10832
10840
|
configPaths.push(file, isolated.instructionFile);
|
|
@@ -10847,18 +10855,18 @@ async function prepareTransportLaunch(input) {
|
|
|
10847
10855
|
if (input.protocol === "gemini-generate-content")
|
|
10848
10856
|
throw new Error("Kilo is incompatible with this protocol.");
|
|
10849
10857
|
validateHarnessVersion(input.harness, input.version);
|
|
10850
|
-
const
|
|
10858
|
+
const bridge2 = grokBridge({ ...input, baseUrl: endpoint(input.baseUrl) });
|
|
10851
10859
|
try {
|
|
10852
|
-
const prepared = await prepareKilo({ ...input, credential:
|
|
10860
|
+
const prepared = await prepareKilo({ ...input, credential: bridge2.token }, bridge2.baseUrl);
|
|
10853
10861
|
return { ...prepared, cleanup: async () => {
|
|
10854
10862
|
try {
|
|
10855
10863
|
await prepared.cleanup?.();
|
|
10856
10864
|
} finally {
|
|
10857
|
-
await
|
|
10865
|
+
await bridge2.cleanup();
|
|
10858
10866
|
}
|
|
10859
10867
|
} };
|
|
10860
10868
|
} catch (error) {
|
|
10861
|
-
await
|
|
10869
|
+
await bridge2.cleanup();
|
|
10862
10870
|
throw error;
|
|
10863
10871
|
}
|
|
10864
10872
|
}
|
|
@@ -10873,18 +10881,18 @@ async function prepareTransportLaunch(input) {
|
|
|
10873
10881
|
const configuration = await validateGeminiConfiguration(input.cwd);
|
|
10874
10882
|
if (input.credential && JSON.stringify([configuration.defaults, configuration.user, configuration.system]).includes(input.credential))
|
|
10875
10883
|
throw new Error("Gemini native configuration must not contain the upstream provider credential.");
|
|
10876
|
-
const
|
|
10884
|
+
const bridge2 = geminiBridge(input);
|
|
10877
10885
|
try {
|
|
10878
|
-
const prepared = await prepareNativeLaunch({ ...input, baseUrl:
|
|
10886
|
+
const prepared = await prepareNativeLaunch({ ...input, baseUrl: bridge2.baseUrl, credential: bridge2.token });
|
|
10879
10887
|
return { ...prepared, cleanup: async () => {
|
|
10880
10888
|
try {
|
|
10881
10889
|
await prepared.cleanup?.();
|
|
10882
10890
|
} finally {
|
|
10883
|
-
await
|
|
10891
|
+
await bridge2.cleanup();
|
|
10884
10892
|
}
|
|
10885
10893
|
} };
|
|
10886
10894
|
} catch (error) {
|
|
10887
|
-
await
|
|
10895
|
+
await bridge2.cleanup();
|
|
10888
10896
|
throw error;
|
|
10889
10897
|
}
|
|
10890
10898
|
}
|
|
@@ -10915,12 +10923,12 @@ async function prepareHarnessLaunch(input) {
|
|
|
10915
10923
|
if (!isAbsolute11(input.stateDir) || !isAbsolute11(input.cwd))
|
|
10916
10924
|
throw new Error("Launch state and working directories must be absolute.");
|
|
10917
10925
|
const compiledPolicy = compileModelPolicy(input.model, input.models, input.modelPolicy);
|
|
10918
|
-
input = { ...input, models: input.models.filter((
|
|
10926
|
+
input = { ...input, models: input.models.filter((model3) => !modelExpired(model3)) };
|
|
10919
10927
|
const nativePolicy = compileNativeModelPolicy({ harness: input.harness, mainModel: input.model, roles: compiledPolicy.roles, version: input.version });
|
|
10920
10928
|
const specialized = new Set(["opencode", "opencode2", "gemini", "hermes"]);
|
|
10921
|
-
const
|
|
10922
|
-
if (
|
|
10923
|
-
throw new Error(`${input.harness} does not expose native model controls for: ${
|
|
10929
|
+
const unsupported3 = specialized.has(input.harness) ? [] : nativePolicy.unsupportedRoles.filter((role) => role !== "main" && compiledPolicy.roles[role] !== input.model);
|
|
10930
|
+
if (unsupported3.length)
|
|
10931
|
+
throw new Error(`${input.harness} does not expose native model controls for: ${unsupported3.join(", ")}.`);
|
|
10924
10932
|
await mkdir10(input.stateDir, { recursive: true, mode: 448 });
|
|
10925
10933
|
const catalogPath = await jsonFile(input.stateDir, `switcher-model-policy-${randomUUID4()}.json`, { policy: compiledPolicy, models: input.models });
|
|
10926
10934
|
const bridge = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
@@ -10954,7 +10962,7 @@ function prepareOriModelPolicy(target, prepared) {
|
|
|
10954
10962
|
throw new Error("Invalid native environment value.");
|
|
10955
10963
|
if (prepared.args.some((arg) => arg.includes("\x00")))
|
|
10956
10964
|
throw new Error("Invalid native argument.");
|
|
10957
|
-
const
|
|
10965
|
+
const quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
10958
10966
|
const env = { SWITCHER_ORI_NATIVE_EXECUTABLE: prepared.executable };
|
|
10959
10967
|
for (const [key, value] of entries)
|
|
10960
10968
|
env[`SWITCHER_ORI_CHILD_${key}`] = value;
|
|
@@ -10964,7 +10972,7 @@ function prepareOriModelPolicy(target, prepared) {
|
|
|
10964
10972
|
set -eu
|
|
10965
10973
|
unset OPENROUTER_API_KEY OPENAI_API_KEY XAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN GROK_MODELS_BASE_URL GROK_MODELS_LIST_URL GROK_XAI_API_BASE_URL
|
|
10966
10974
|
${restore}
|
|
10967
|
-
exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(
|
|
10975
|
+
exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
|
|
10968
10976
|
` };
|
|
10969
10977
|
}
|
|
10970
10978
|
|
|
@@ -11201,7 +11209,7 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
11201
11209
|
if (!before.isFile() || before.uid !== process.getuid?.() || before.size > limit || before.mode & 3584)
|
|
11202
11210
|
throw unsafe();
|
|
11203
11211
|
const sameFile = (info) => info.dev === before.dev && info.ino === before.ino && info.size === before.size && info.uid === before.uid && info.nlink === before.nlink && info.mode === before.mode && info.mtimeMs === before.mtimeMs && info.ctimeMs === before.ctimeMs;
|
|
11204
|
-
const
|
|
11212
|
+
const hash2 = async (target) => {
|
|
11205
11213
|
const digest = createHash10("sha256");
|
|
11206
11214
|
const buffer = Buffer.alloc(1024 * 1024);
|
|
11207
11215
|
let position = 0;
|
|
@@ -11222,7 +11230,7 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
11222
11230
|
if (digest.digest("hex") !== expectedSha256)
|
|
11223
11231
|
throw new Fault(422, "vault_exec_digest_mismatch", "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed.");
|
|
11224
11232
|
};
|
|
11225
|
-
await
|
|
11233
|
+
await hash2();
|
|
11226
11234
|
const mode = before.mode & 511 & ~18;
|
|
11227
11235
|
const changed = mode !== (before.mode & 511);
|
|
11228
11236
|
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat4(resolved)))
|
|
@@ -11234,7 +11242,7 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
11234
11242
|
temporary = join13(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
|
|
11235
11243
|
const replacement = await open3(temporary, "wx", 384);
|
|
11236
11244
|
try {
|
|
11237
|
-
await
|
|
11245
|
+
await hash2(replacement);
|
|
11238
11246
|
await replacement.chmod(mode);
|
|
11239
11247
|
await replacement.sync();
|
|
11240
11248
|
const ready = await replacement.stat();
|
|
@@ -11271,11 +11279,11 @@ function bindingTarget(selector, override, allowedOrigins) {
|
|
|
11271
11279
|
throw new Fault(400, "credential_origin_required", "Use --origin URL to authorize a custom credential destination.");
|
|
11272
11280
|
return { credentialEnv: parse2(reference, selector), origins: allowedOrigins.map((value) => new URL(endpoint(value)).origin) };
|
|
11273
11281
|
}
|
|
11274
|
-
const
|
|
11275
|
-
const credentialEnv = override ??
|
|
11282
|
+
const preset2 = getProviderPreset(selector);
|
|
11283
|
+
const credentialEnv = override ?? preset2.credentialEnv;
|
|
11276
11284
|
if (!credentialEnv)
|
|
11277
11285
|
throw new Fault(400, "credential_reference_required", "Use --credential-env for a preset without a default credential reference.");
|
|
11278
|
-
const origins = allowedOrigins ?? [...new Set(
|
|
11286
|
+
const origins = allowedOrigins ?? [...new Set(preset2.protocols.flatMap((route2) => route2.baseUrl ? [new URL(route2.baseUrl).origin] : []))];
|
|
11279
11287
|
if (!origins.length)
|
|
11280
11288
|
throw new Fault(400, "credential_origin_required", "Use --origin URL for this custom preset.");
|
|
11281
11289
|
return { credentialEnv: parse2(reference, credentialEnv), origins };
|
|
@@ -11405,9 +11413,9 @@ async function runVaultCommand(binding, args, env, delivery = {}, options = {})
|
|
|
11405
11413
|
if (process.platform === "win32")
|
|
11406
11414
|
throw new Fault(422, "vault_exec_unavailable", "Vault CLI bindings currently require POSIX process groups; use runtime environment injection on Windows.");
|
|
11407
11415
|
const executable = await validateVaultExecutable(binding.source.executable);
|
|
11408
|
-
const
|
|
11409
|
-
const childEnv = { ...
|
|
11410
|
-
return new Promise((resolveResult,
|
|
11416
|
+
const operator2 = options.operator ?? await resolveVaultOperatorEnvironment(binding, env);
|
|
11417
|
+
const childEnv = { ...operator2.environment, ...delivery };
|
|
11418
|
+
return new Promise((resolveResult, reject2) => {
|
|
11411
11419
|
const child = spawn(executable, args, { env: childEnv, stdio: ["ignore", options.captureBytes ? "pipe" : "ignore", "ignore"], detached: true, shell: false });
|
|
11412
11420
|
let failure;
|
|
11413
11421
|
let output = "";
|
|
@@ -11452,14 +11460,14 @@ async function runVaultCommand(binding, args, env, delivery = {}, options = {})
|
|
|
11452
11460
|
});
|
|
11453
11461
|
child.once("error", () => {
|
|
11454
11462
|
cleanup();
|
|
11455
|
-
|
|
11463
|
+
reject2(new Fault(422, "vault_exec_failed", "The configured secrets CLI could not start; check its executable and permissions."));
|
|
11456
11464
|
});
|
|
11457
11465
|
child.once("exit", cleanup);
|
|
11458
11466
|
child.once("close", (code) => {
|
|
11459
11467
|
if (failure)
|
|
11460
|
-
|
|
11468
|
+
reject2(failure);
|
|
11461
11469
|
else if (code !== 0)
|
|
11462
|
-
|
|
11470
|
+
reject2(new Fault(422, options.lookupCode ?? "vault_lookup_failed", options.lookupMessage ?? "The secrets CLI could not read the configured key. Check vault access and conflicting local vault URL settings; no alternate account was selected."));
|
|
11463
11471
|
else
|
|
11464
11472
|
resolveResult(output);
|
|
11465
11473
|
});
|
|
@@ -11557,7 +11565,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
|
|
|
11557
11565
|
await validateVaultExecutable(vaultExecutable);
|
|
11558
11566
|
const source = { kind: "vault", key: "switcher/provider-credential-discovery", executable: vaultExecutable, operator: { kind: "contracts" } };
|
|
11559
11567
|
const provisional = parse2(credentialBindingSchema, { schema: 1, credentialEnv: provider.credentialEnv, origins: credentialOrigins(provider), source });
|
|
11560
|
-
const
|
|
11568
|
+
const operator2 = await resolveVaultOperatorEnvironment(provisional, env);
|
|
11561
11569
|
const entries = new Map;
|
|
11562
11570
|
for (const query of searchTerms(provider)) {
|
|
11563
11571
|
const output = await runVaultCommand(provisional, ["search", query, "--json"], env, {}, {
|
|
@@ -11566,7 +11574,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
|
|
|
11566
11574
|
oversizeMessage: "Secrets returned too much credential metadata; narrow the vault naming or bind an exact key explicitly.",
|
|
11567
11575
|
lookupCode: "vault_search_failed",
|
|
11568
11576
|
lookupMessage: "Hasna Secrets could not search credential metadata. Check the selected vault/Keychain source; no alternate account was selected.",
|
|
11569
|
-
operator
|
|
11577
|
+
operator: operator2
|
|
11570
11578
|
});
|
|
11571
11579
|
let parsed;
|
|
11572
11580
|
try {
|
|
@@ -11582,7 +11590,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
|
|
|
11582
11590
|
if (entries.size > 256)
|
|
11583
11591
|
throw new Fault(422, "credential_matches_too_many", "More than 256 credential references matched. Bind an exact vault key explicitly.");
|
|
11584
11592
|
}
|
|
11585
|
-
return [...entries.values()].sort((a, b) => a.key.localeCompare(b.key)).map((entry) => ({ account:
|
|
11593
|
+
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 } }));
|
|
11586
11594
|
}
|
|
11587
11595
|
async function selectVaultReference({ provider, matches }) {
|
|
11588
11596
|
if (!process.stdin.isTTY || !process.stderr.isTTY)
|
|
@@ -11687,10 +11695,10 @@ async function ensureProviderCredential(provider, options = {}) {
|
|
|
11687
11695
|
if (!credential) {
|
|
11688
11696
|
if (!(options.interactive ?? (process.stdin.isTTY && process.stderr.isTTY)))
|
|
11689
11697
|
throw new Fault(400, "credential_setup_required", `Provider credential setup is required. Run: ${providerCredentialSetupCommand(provider)}. Or provide ${provider.credentialEnv} in this launch process.`);
|
|
11690
|
-
const
|
|
11698
|
+
const discover2 = options.discoverVaultReferences ?? ((request) => discoverVaultReferences(request.provider, options.env ?? process.env, options.vaultExecutable));
|
|
11691
11699
|
let matches;
|
|
11692
11700
|
try {
|
|
11693
|
-
matches = await
|
|
11701
|
+
matches = await discover2({ provider, credentialEnv: provider.credentialEnv });
|
|
11694
11702
|
} catch (error) {
|
|
11695
11703
|
if (error instanceof Fault && error.code === "vault_exec_unavailable")
|
|
11696
11704
|
throw new Fault(error.status, error.code, `${error.message} Run: ${providerCredentialSetupCommand(provider)} --vault-cli /absolute/path/to/secrets.`);
|
|
@@ -11731,12 +11739,12 @@ function catalogRequiresCredential(provider) {
|
|
|
11731
11739
|
async function launchCatalog(client, provider, dryRun = false, options = {}) {
|
|
11732
11740
|
if (!dryRun && options.clientSide) {
|
|
11733
11741
|
const origins = credentialOrigins(provider);
|
|
11734
|
-
const
|
|
11742
|
+
const resolve9 = async (candidate) => {
|
|
11735
11743
|
if (options.credential && candidate.credentialEnv === provider.credentialEnv && origins.includes(new URL(candidate.baseUrl).origin))
|
|
11736
11744
|
return options.credential;
|
|
11737
11745
|
return options.resolveCredential?.(candidate);
|
|
11738
11746
|
};
|
|
11739
|
-
const catalog = await discover(provider, {},
|
|
11747
|
+
const catalog = await discover(provider, {}, resolve9);
|
|
11740
11748
|
return client.saveCatalog(provider.id, provider.version, catalog);
|
|
11741
11749
|
}
|
|
11742
11750
|
if (!dryRun || !catalogRequiresCredential(provider))
|
|
@@ -11759,8 +11767,8 @@ async function launchCatalog(client, provider, dryRun = false, options = {}) {
|
|
|
11759
11767
|
} else if (total !== page.total || refreshedAt !== page.refreshedAt || source !== page.source)
|
|
11760
11768
|
throw new Fault(409, "catalog_changed", "The cached catalog changed while the dry-run plan was being read; retry.");
|
|
11761
11769
|
for (const row of page.data) {
|
|
11762
|
-
const { codingEligible: _codingEligible, expired: _expired, ...
|
|
11763
|
-
models.push(
|
|
11770
|
+
const { codingEligible: _codingEligible, expired: _expired, ...model3 } = row;
|
|
11771
|
+
models.push(model3);
|
|
11764
11772
|
}
|
|
11765
11773
|
offset += page.data.length;
|
|
11766
11774
|
if (offset >= page.total)
|
|
@@ -11802,7 +11810,7 @@ async function runHarnessProcess(options) {
|
|
|
11802
11810
|
const grouped = process.platform !== "win32", interactive = !options.silent && grouped && tty.some(Boolean);
|
|
11803
11811
|
const redirects = interactive ? tty.flatMap((value, index) => value ? [] : [index]) : [];
|
|
11804
11812
|
const duplicator = redirects.length ? await terminalDescriptorDuplicator() : undefined;
|
|
11805
|
-
return new Promise((resolveResult,
|
|
11813
|
+
return new Promise((resolveResult, reject2) => {
|
|
11806
11814
|
const wasRaw = process.stdin.isRaw, wasFlowing = process.stdin.readableFlowing;
|
|
11807
11815
|
let controllingInput;
|
|
11808
11816
|
let inputTimer;
|
|
@@ -11841,12 +11849,12 @@ async function runHarnessProcess(options) {
|
|
|
11841
11849
|
cwd: options.cwd,
|
|
11842
11850
|
env: options.env,
|
|
11843
11851
|
stdio: ["inherit", "inherit", "inherit", ...duplicates],
|
|
11844
|
-
terminal: { cols, rows, name: options.env.TERM ?? "xterm-256color", data(_terminal,
|
|
11852
|
+
terminal: { cols, rows, name: options.env.TERM ?? "xterm-256color", data(_terminal, data2) {
|
|
11845
11853
|
try {
|
|
11846
11854
|
if (output)
|
|
11847
|
-
output.write(
|
|
11855
|
+
output.write(data2);
|
|
11848
11856
|
else if (controllingOutput !== undefined)
|
|
11849
|
-
writeSync(controllingOutput,
|
|
11857
|
+
writeSync(controllingOutput, data2);
|
|
11850
11858
|
} catch {
|
|
11851
11859
|
failTerminal();
|
|
11852
11860
|
}
|
|
@@ -12001,7 +12009,7 @@ async function runHarnessProcess(options) {
|
|
|
12001
12009
|
};
|
|
12002
12010
|
child.once("error", () => {
|
|
12003
12011
|
cleanup();
|
|
12004
|
-
|
|
12012
|
+
reject2(new Error("Harness process could not start; check executable and permissions."));
|
|
12005
12013
|
});
|
|
12006
12014
|
child.once("exit", async (code, signal) => {
|
|
12007
12015
|
if (timeout)
|
|
@@ -12010,13 +12018,13 @@ async function runHarnessProcess(options) {
|
|
|
12010
12018
|
signalGroup("SIGTERM");
|
|
12011
12019
|
const deadline = Date.now() + 5000;
|
|
12012
12020
|
while (groupExists() && Date.now() < deadline)
|
|
12013
|
-
await new Promise((
|
|
12021
|
+
await new Promise((resolve9) => setTimeout(resolve9, 25));
|
|
12014
12022
|
if (groupExists())
|
|
12015
12023
|
signalGroup("SIGKILL");
|
|
12016
12024
|
}
|
|
12017
12025
|
cleanup();
|
|
12018
12026
|
if (terminalFailure) {
|
|
12019
|
-
|
|
12027
|
+
reject2(terminalFailure);
|
|
12020
12028
|
return;
|
|
12021
12029
|
}
|
|
12022
12030
|
const exitCode = interruptionExitCode ?? code ?? (signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : signal === "SIGHUP" ? 129 : 137);
|
|
@@ -12153,14 +12161,14 @@ function parseHarnesses(stdout) {
|
|
|
12153
12161
|
return rows.flatMap((row) => {
|
|
12154
12162
|
if (!row || typeof row !== "object")
|
|
12155
12163
|
return [];
|
|
12156
|
-
const
|
|
12157
|
-
if (typeof
|
|
12164
|
+
const item2 = row;
|
|
12165
|
+
if (typeof item2.kind !== "string" || typeof item2.installed !== "boolean")
|
|
12158
12166
|
return [];
|
|
12159
12167
|
return [{
|
|
12160
|
-
kind:
|
|
12161
|
-
displayName: typeof
|
|
12162
|
-
installed:
|
|
12163
|
-
path: typeof
|
|
12168
|
+
kind: item2.kind,
|
|
12169
|
+
displayName: typeof item2.displayName === "string" ? item2.displayName : undefined,
|
|
12170
|
+
installed: item2.installed,
|
|
12171
|
+
path: typeof item2.path === "string" ? item2.path : undefined
|
|
12164
12172
|
}];
|
|
12165
12173
|
});
|
|
12166
12174
|
}
|
|
@@ -12208,16 +12216,16 @@ function requireOriHarness(contract, target) {
|
|
|
12208
12216
|
throw new OriBackendError("harness_unavailable", `Ori cannot launch ${target} because its native harness is not installed; no installer was started.`);
|
|
12209
12217
|
return row;
|
|
12210
12218
|
}
|
|
12211
|
-
function oriProvider(
|
|
12212
|
-
const provider = oriProviderCatalog.find((entry) => entry.id ===
|
|
12219
|
+
function oriProvider(id2) {
|
|
12220
|
+
const provider = oriProviderCatalog.find((entry) => entry.id === id2);
|
|
12213
12221
|
if (!provider)
|
|
12214
12222
|
throw new OriBackendError("provider_unsupported", "Ori supports OpenRouter only; use a direct Switcher adapter for this provider.");
|
|
12215
12223
|
return provider;
|
|
12216
12224
|
}
|
|
12217
12225
|
function assertProviderAuthority(target, provider, providerBaseUrl, protocol) {
|
|
12218
12226
|
const catalog = oriProvider("openrouter");
|
|
12219
|
-
const
|
|
12220
|
-
if (!providerBaseUrl || !protocol || !
|
|
12227
|
+
const compatible2 = target === "codex" ? protocol === "openai-responses" : target === "claude" ? protocol === "anthropic-messages" : catalog.protocols.includes(protocol);
|
|
12228
|
+
if (!providerBaseUrl || !protocol || !compatible2)
|
|
12221
12229
|
throw new OriBackendError("provider_authority", "Ori requires an explicit OpenRouter provider URL and a protocol supported by the selected Ori target.");
|
|
12222
12230
|
let url;
|
|
12223
12231
|
try {
|
|
@@ -12384,17 +12392,17 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
|
12384
12392
|
}
|
|
12385
12393
|
};
|
|
12386
12394
|
try {
|
|
12387
|
-
const
|
|
12395
|
+
const settings2 = [];
|
|
12388
12396
|
for (let i = 0;i < native.args.length; i += 2) {
|
|
12389
12397
|
if (native.args[i] !== "-c" || typeof native.args[i + 1] !== "string")
|
|
12390
12398
|
throw new Fault(400, "desktop_arguments", "Desktop launches accept provider/model settings, not native CLI commands.");
|
|
12391
|
-
|
|
12399
|
+
settings2.push(native.args[i + 1]);
|
|
12392
12400
|
}
|
|
12393
|
-
|
|
12394
|
-
if (!
|
|
12395
|
-
|
|
12396
|
-
if (!
|
|
12397
|
-
|
|
12401
|
+
settings2.push('cli_auth_credentials_store="file"', 'forced_login_method="api"');
|
|
12402
|
+
if (!settings2.some((setting) => setting.startsWith("approval_policy=")))
|
|
12403
|
+
settings2.push('approval_policy="on-request"');
|
|
12404
|
+
if (!settings2.some((setting) => setting.startsWith("sandbox_mode=")))
|
|
12405
|
+
settings2.push('sandbox_mode="workspace-write"');
|
|
12398
12406
|
const configPath = join14(home, "config.toml");
|
|
12399
12407
|
const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
|
|
12400
12408
|
if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
|
|
@@ -12406,7 +12414,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
|
12406
12414
|
if (error.code !== "ENOENT")
|
|
12407
12415
|
throw new Fault(422, "desktop_config_invalid", "The desktop profile config cannot be read safely.");
|
|
12408
12416
|
}
|
|
12409
|
-
const config = merge2(existing, Bun.TOML.parse(
|
|
12417
|
+
const config = merge2(existing, Bun.TOML.parse(settings2.join(`
|
|
12410
12418
|
`)));
|
|
12411
12419
|
await writeDesktopPrivate(configPath, renderCodexAgentToml(config));
|
|
12412
12420
|
const key = native.env.SWITCHER_HARNESS_API_KEY;
|
|
@@ -12417,7 +12425,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
|
12417
12425
|
await writeDesktopPrivate(receiptPath, digest(authText));
|
|
12418
12426
|
await writeDesktopPrivate(authPath, authText);
|
|
12419
12427
|
const wrapper = join14(stateDir, "chatgpt-codex");
|
|
12420
|
-
const overrides =
|
|
12428
|
+
const overrides = settings2.flatMap((setting) => ["-c", setting]);
|
|
12421
12429
|
await writeFile12(wrapper, `#!/bin/sh
|
|
12422
12430
|
set -eu
|
|
12423
12431
|
unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
|
|
@@ -12476,7 +12484,7 @@ async function assertAvailable(userData) {
|
|
|
12476
12484
|
}
|
|
12477
12485
|
function metadata(text) {
|
|
12478
12486
|
const value = text === undefined ? { entries: [] } : JSON.parse(text);
|
|
12479
|
-
if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((
|
|
12487
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((item2) => !item2 || typeof item2 !== "object" || Array.isArray(item2)))
|
|
12480
12488
|
throw new Fault(422, "desktop_config_invalid", "Claude's configuration library metadata is invalid.");
|
|
12481
12489
|
return value;
|
|
12482
12490
|
}
|
|
@@ -12490,27 +12498,27 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12490
12498
|
if (version.length < 3 || version.some((n) => !Number.isSafeInteger(n)) || version[0] < 1 || version[0] === 1 && version[1] < 52386)
|
|
12491
12499
|
throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
|
|
12492
12500
|
const userData = system?.userData ?? claudeDesktopDataDirectory();
|
|
12493
|
-
const
|
|
12494
|
-
await
|
|
12501
|
+
const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
|
|
12502
|
+
await check2();
|
|
12495
12503
|
await privateDirectory(userData);
|
|
12496
12504
|
const library = join15(userData, "configLibrary");
|
|
12497
12505
|
await privateDirectory(library);
|
|
12498
12506
|
const release = await desktopLease(join15(library, ".switcher-lease.sqlite"));
|
|
12499
12507
|
const metaPath = join15(library, "_meta.json"), receiptPath = join15(library, ".switcher-selection.json");
|
|
12500
12508
|
let receipt, gateway, closed = false;
|
|
12501
|
-
const restore = async (
|
|
12502
|
-
if (!/^[a-f0-9-]{36}$/.test(
|
|
12509
|
+
const restore = async (record3) => {
|
|
12510
|
+
if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
|
|
12503
12511
|
throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
|
|
12504
|
-
const configPath = join15(library,
|
|
12505
|
-
if (current !== undefined && hash2(current) !==
|
|
12512
|
+
const configPath = join15(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
|
|
12513
|
+
if (current !== undefined && hash2(current) !== record3.configHash)
|
|
12506
12514
|
throw new Fault(409, "desktop_config_changed", "The Switcher Claude configuration was edited outside this launch. Switcher will preserve it; review the configuration library before relaunching.");
|
|
12507
12515
|
const currentMeta = await safeDesktopRead(metaPath);
|
|
12508
|
-
if (currentMeta !==
|
|
12516
|
+
if (currentMeta !== record3.appliedMeta && currentMeta !== (record3.previousMeta ?? undefined))
|
|
12509
12517
|
throw new Fault(409, "desktop_config_changed", "Claude's selected configuration changed during this launch. Switcher will preserve the changed selection; review its configuration library before relaunching.");
|
|
12510
|
-
if (
|
|
12518
|
+
if (record3.previousMeta === null)
|
|
12511
12519
|
await rm5(metaPath, { force: true });
|
|
12512
12520
|
else
|
|
12513
|
-
await writeDesktopPrivate(metaPath,
|
|
12521
|
+
await writeDesktopPrivate(metaPath, record3.previousMeta);
|
|
12514
12522
|
await rm5(configPath, { force: true });
|
|
12515
12523
|
await rm5(receiptPath, { force: true });
|
|
12516
12524
|
};
|
|
@@ -12534,9 +12542,9 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12534
12542
|
if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
|
|
12535
12543
|
throw new Fault(409, "desktop_mode", "Claude's third-party profile is set to standard account mode. Select third-party mode in Claude before launching this gateway.");
|
|
12536
12544
|
await privateDirectory(sessionDir);
|
|
12537
|
-
const
|
|
12538
|
-
const targets = { sonnet: input.model, opus:
|
|
12539
|
-
const aliases = Object.fromEntries(Object.entries(targets).map(([tier,
|
|
12545
|
+
const roles2 = input.modelPolicy?.roles;
|
|
12546
|
+
const targets = { sonnet: input.model, opus: roles2?.planning ?? input.model, haiku: roles2?.fast ?? input.model };
|
|
12547
|
+
const aliases = Object.fromEntries(Object.entries(targets).map(([tier, model3]) => ["switcher/" + tier, model3]));
|
|
12540
12548
|
for (const [alias, target] of Object.entries(aliases))
|
|
12541
12549
|
if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
|
|
12542
12550
|
throw new Fault(409, "desktop_alias_conflict", "The model policy conflicts with Claude desktop's reserved switcher/sonnet, switcher/opus or switcher/haiku routing aliases.");
|
|
@@ -12544,19 +12552,19 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12544
12552
|
const catalogPath = join15(input.stateDir, "claude-desktop-policy.json");
|
|
12545
12553
|
await writeFile13(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
|
|
12546
12554
|
gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
12547
|
-
const
|
|
12555
|
+
const id2 = crypto.randomUUID(), configPath = join15(library, id2 + ".json");
|
|
12548
12556
|
const config = JSON.stringify({
|
|
12549
12557
|
inferenceProvider: "gateway",
|
|
12550
12558
|
inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
|
|
12551
12559
|
inferenceGatewayApiKey: gateway.token,
|
|
12552
12560
|
inferenceGatewayAuthScheme: "bearer",
|
|
12553
12561
|
modelDiscoveryEnabled: false,
|
|
12554
|
-
inferenceModels: Object.entries(targets).map(([tier,
|
|
12562
|
+
inferenceModels: Object.entries(targets).map(([tier, model3]) => ({ name: "switcher/" + tier, labelOverride: model3, anthropicFamilyTier: tier, isFamilyDefault: true }))
|
|
12555
12563
|
});
|
|
12556
12564
|
const previousMeta = await safeDesktopRead(metaPath);
|
|
12557
12565
|
const meta = metadata(previousMeta);
|
|
12558
|
-
const appliedMeta = JSON.stringify({ ...meta, appliedId:
|
|
12559
|
-
receipt = { id, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
|
|
12566
|
+
const appliedMeta = JSON.stringify({ ...meta, appliedId: id2, entries: [...meta.entries, { id: id2, name: `Switcher: ${input.providerId ?? "provider"} / ${input.model}` }] });
|
|
12567
|
+
receipt = { id: id2, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
|
|
12560
12568
|
await writeDesktopPrivate(configPath, config);
|
|
12561
12569
|
await writeDesktopPrivate(receiptPath, JSON.stringify(receipt));
|
|
12562
12570
|
await writeDesktopPrivate(metaPath, appliedMeta);
|
|
@@ -12565,7 +12573,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12565
12573
|
args: [],
|
|
12566
12574
|
env: { CLAUDE_CONFIG_DIR: sessionDir },
|
|
12567
12575
|
configPaths: [catalogPath, configPath],
|
|
12568
|
-
beforeLaunch:
|
|
12576
|
+
beforeLaunch: check2,
|
|
12569
12577
|
cleanup,
|
|
12570
12578
|
warnings: [`Claude desktop gateway: ${input.providerId ?? "provider"} / ${input.model}. Uses the shared Claude-3p profile, separate from the normal Claude account. Quit this instance before switching providers; keep Switcher running until then. The previous configuration selection is restored on exit. Managed settings and native permissions remain authoritative.`]
|
|
12571
12579
|
};
|
|
@@ -12581,8 +12589,8 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12581
12589
|
var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
|
|
12582
12590
|
async function writeOriCodexCatalog(stateDir, models) {
|
|
12583
12591
|
const path = join16(stateDir, "ori-codex-models.json");
|
|
12584
|
-
const
|
|
12585
|
-
await writeFile14(path, JSON.stringify({ models:
|
|
12592
|
+
const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
|
|
12593
|
+
await writeFile14(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
|
|
12586
12594
|
`, { mode: 384, flag: "wx" });
|
|
12587
12595
|
return path;
|
|
12588
12596
|
}
|
|
@@ -12642,7 +12650,7 @@ function buildOriRequest(plan, target, catalogPath, args) {
|
|
|
12642
12650
|
providerBaseUrl: plan.provider.baseUrl,
|
|
12643
12651
|
protocol: plan.provider.protocol,
|
|
12644
12652
|
model: plan.profile.model,
|
|
12645
|
-
catalog: { source: "switcher-openrouter", modelIds: plan.catalog.models.filter(codingEligible).map((
|
|
12653
|
+
catalog: { source: "switcher-openrouter", modelIds: plan.catalog.models.filter(codingEligible).map((model3) => model3.id), ...catalogPath ? { codexModelCatalogPath: catalogPath } : {} },
|
|
12646
12654
|
args
|
|
12647
12655
|
};
|
|
12648
12656
|
}
|
|
@@ -12765,8 +12773,8 @@ async function launch(client, profileId, options = {}) {
|
|
|
12765
12773
|
await client.finishRun(candidate.id, candidate.version, { ...body, routingEvents, routingEventsDropped }, crypto.randomUUID()).catch(() => console.error(message));
|
|
12766
12774
|
};
|
|
12767
12775
|
let cancelPreparation;
|
|
12768
|
-
const preparationCancellation = new Promise((_,
|
|
12769
|
-
cancelPreparation =
|
|
12776
|
+
const preparationCancellation = new Promise((_, reject2) => {
|
|
12777
|
+
cancelPreparation = reject2;
|
|
12770
12778
|
});
|
|
12771
12779
|
preparationCancellation.catch(() => {
|
|
12772
12780
|
return;
|
|
@@ -12818,8 +12826,8 @@ async function launch(client, profileId, options = {}) {
|
|
|
12818
12826
|
return;
|
|
12819
12827
|
preparationSignal = error;
|
|
12820
12828
|
createRunCancelled = true;
|
|
12821
|
-
preparationCleanup ??= cleanup?.().catch((
|
|
12822
|
-
console.error(`switcher: Could not clean up the interrupted launch: ${
|
|
12829
|
+
preparationCleanup ??= cleanup?.().catch((error2) => {
|
|
12830
|
+
console.error(`switcher: Could not clean up the interrupted launch: ${error2 instanceof Error ? error2.message : "unknown cleanup failure"}.`);
|
|
12823
12831
|
});
|
|
12824
12832
|
if (cancel)
|
|
12825
12833
|
cancelPreparation(preparationSignal);
|
|
@@ -12902,8 +12910,8 @@ async function launch(client, profileId, options = {}) {
|
|
|
12902
12910
|
} finally {
|
|
12903
12911
|
if (lateCreateRunFinalization) {
|
|
12904
12912
|
let finalizationTimer;
|
|
12905
|
-
const finalizationTimeout = new Promise((
|
|
12906
|
-
finalizationTimer = setTimeout(
|
|
12913
|
+
const finalizationTimeout = new Promise((resolve10) => {
|
|
12914
|
+
finalizationTimer = setTimeout(resolve10, LATE_RUN_FINALIZATION_TIMEOUT_MS);
|
|
12907
12915
|
});
|
|
12908
12916
|
try {
|
|
12909
12917
|
await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
|
|
@@ -12999,11 +13007,11 @@ async function selectModel(models, query = "", harness) {
|
|
|
12999
13007
|
reader.close();
|
|
13000
13008
|
}
|
|
13001
13009
|
}
|
|
13002
|
-
async function ensureLaunchProfile(client, provider, harness,
|
|
13010
|
+
async function ensureLaunchProfile(client, provider, harness, model3, modelPolicy) {
|
|
13003
13011
|
const normalizedPolicy = modelPolicy === undefined ? undefined : parse2(modelPolicySchema, modelPolicy);
|
|
13004
|
-
const identity = normalizedPolicy === undefined ? [provider.id, harness,
|
|
13005
|
-
const
|
|
13006
|
-
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${
|
|
13012
|
+
const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
|
|
13013
|
+
const hash3 = createHash14("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
|
|
13014
|
+
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
|
|
13007
13015
|
let existing;
|
|
13008
13016
|
try {
|
|
13009
13017
|
existing = await client.getProfile(desired.id);
|
|
@@ -13020,7 +13028,7 @@ async function ensureLaunchProfile(client, provider, harness, model, modelPolicy
|
|
|
13020
13028
|
existing = await client.getProfile(desired.id);
|
|
13021
13029
|
}
|
|
13022
13030
|
}
|
|
13023
|
-
if (existing.providerId !== desired.providerId || existing.harness !== harness || existing.model !==
|
|
13031
|
+
if (existing.providerId !== desired.providerId || existing.harness !== harness || existing.model !== model3 || canonicalPolicyJSON(existing.modelPolicy ?? null) !== canonicalPolicyJSON(desired.modelPolicy ?? null))
|
|
13024
13032
|
throw new Fault(409, "profile_conflict", "An existing launch profile has different settings. Select a saved profile explicitly.");
|
|
13025
13033
|
return existing;
|
|
13026
13034
|
}
|
|
@@ -13120,28 +13128,28 @@ async function readModelPolicy(file, roleValues) {
|
|
|
13120
13128
|
return parse2(modelPolicySchema, await readInput(file));
|
|
13121
13129
|
if (!roleValues?.length)
|
|
13122
13130
|
return;
|
|
13123
|
-
const
|
|
13131
|
+
const roles2 = {};
|
|
13124
13132
|
const valid = new Set(["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"]);
|
|
13125
|
-
for (const
|
|
13126
|
-
const split =
|
|
13127
|
-
if (split <= 0 || split ===
|
|
13133
|
+
for (const item2 of roleValues) {
|
|
13134
|
+
const split = item2.indexOf("=");
|
|
13135
|
+
if (split <= 0 || split === item2.length - 1)
|
|
13128
13136
|
throw new Fault(400, "invalid_request", "Each --role-model must use ROLE=MODEL.");
|
|
13129
|
-
const role =
|
|
13130
|
-
const
|
|
13137
|
+
const role = item2.slice(0, split);
|
|
13138
|
+
const model3 = item2.slice(split + 1);
|
|
13131
13139
|
if (!valid.has(role))
|
|
13132
13140
|
throw new Fault(400, "invalid_request", `Unknown model policy role: ${role}.`);
|
|
13133
|
-
if (
|
|
13141
|
+
if (roles2[role] !== undefined)
|
|
13134
13142
|
throw new Fault(400, "conflicting_options", `Duplicate model policy role: ${role}.`);
|
|
13135
|
-
|
|
13143
|
+
roles2[role] = model3;
|
|
13136
13144
|
}
|
|
13137
|
-
return parse2(modelPolicySchema, { version: 1, roles });
|
|
13145
|
+
return parse2(modelPolicySchema, { version: 1, roles: roles2 });
|
|
13138
13146
|
}
|
|
13139
13147
|
async function main(args = process.argv.slice(2)) {
|
|
13140
13148
|
if (args.length === 1 && args[0] === "__credential-delivery")
|
|
13141
13149
|
return deliverVaultCredential();
|
|
13142
13150
|
const split = args.indexOf("--");
|
|
13143
13151
|
const nativeArgs = split >= 0 ? args.slice(split + 1) : [];
|
|
13144
|
-
const { values, positionals } = parseArgs({ args: split >= 0 ? args.slice(0, split) : args, allowPositionals: true, options: {
|
|
13152
|
+
const { values: values2, positionals } = parseArgs({ args: split >= 0 ? args.slice(0, split) : args, allowPositionals: true, options: {
|
|
13145
13153
|
help: { type: "boolean" },
|
|
13146
13154
|
version: { type: "string" },
|
|
13147
13155
|
json: { type: "boolean" },
|
|
@@ -13189,145 +13197,145 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13189
13197
|
"keychain-account": { type: "string" },
|
|
13190
13198
|
origin: { type: "string", multiple: true }
|
|
13191
13199
|
} });
|
|
13192
|
-
if (
|
|
13200
|
+
if (values2.help || !positionals.length) {
|
|
13193
13201
|
console.log(HELP);
|
|
13194
13202
|
return;
|
|
13195
13203
|
}
|
|
13196
|
-
const [command,
|
|
13204
|
+
const [command, action2, id2] = positionals;
|
|
13197
13205
|
const output = (value) => console.log(JSON.stringify(value, null, 2));
|
|
13198
|
-
const reasoning =
|
|
13199
|
-
const dangerouslyBypassApprovalsAndSandbox =
|
|
13200
|
-
if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" ||
|
|
13206
|
+
const reasoning = values2.reasoning === undefined ? undefined : parse2(reasoningEffortSchema, values2.reasoning);
|
|
13207
|
+
const dangerouslyBypassApprovalsAndSandbox = values2["dangerously-bypass-approvals-and-sandbox"];
|
|
13208
|
+
if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" || values2.provider && !["chatgpt", "codex"].includes(action2) || values2.backend && values2.backend !== "direct"))
|
|
13201
13209
|
throw new Fault(400, "conflicting_options", "--reasoning and --dangerously-bypass-approvals-and-sandbox require a direct Codex or ChatGPT launch.");
|
|
13202
|
-
const chatgpt = command === "launch" &&
|
|
13203
|
-
const claudeDesktop = command === "launch" &&
|
|
13204
|
-
if (
|
|
13210
|
+
const chatgpt = command === "launch" && action2 === "chatgpt" && values2.provider !== undefined;
|
|
13211
|
+
const claudeDesktop = command === "launch" && action2 === "claude-desktop" && values2.provider !== undefined;
|
|
13212
|
+
if (values2["app-path"] !== undefined && !chatgpt && !claudeDesktop)
|
|
13205
13213
|
throw new Fault(400, "conflicting_options", "--app-path belongs to launch chatgpt or claude-desktop --provider PROVIDER --model MODEL.");
|
|
13206
|
-
if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 ||
|
|
13214
|
+
if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 || values2.executable !== undefined || values2.backend !== undefined || values2["ori-executable"] !== undefined))
|
|
13207
13215
|
throw new Fault(400, "conflicting_options", "Desktop apps use their own runtime; native CLI arguments, --executable and --backend are not accepted.");
|
|
13208
|
-
const desktop = chatgpt ? await detectChatGPTApp(
|
|
13209
|
-
const claudeApp = claudeDesktop ? await detectClaudeDesktopApp(
|
|
13216
|
+
const desktop = chatgpt ? await detectChatGPTApp(values2["app-path"]) : undefined;
|
|
13217
|
+
const claudeApp = claudeDesktop ? await detectClaudeDesktopApp(values2["app-path"]) : undefined;
|
|
13210
13218
|
if (!["doctor", "launch", "models", "runs", "providers", "profiles", "credentials"].includes(command))
|
|
13211
13219
|
throw new Error("Unknown command. Run switcher --help.");
|
|
13212
13220
|
const providerFlags = ["url", "protocol", "preset", "credential-env", "auth-style", "catalog-url", "catalog-format", "catalog-auth-style", "catalog-credential-env", "catalog-account-id", "models-path"];
|
|
13213
|
-
const provided = (names) => names.some((name) =>
|
|
13214
|
-
const editingModel = command === "models" && positionals.length > 2 && ["add", "update", "remove"].includes(
|
|
13215
|
-
const configuringModels = command === "models" && positionals.length > 2 &&
|
|
13216
|
-
const listingModels = command === "models" && positionals.length > 2 &&
|
|
13217
|
-
if (listingModels && (positionals.length !== 3 || nativeArgs.length || Object.keys(
|
|
13221
|
+
const provided = (names) => names.some((name) => values2[name] !== undefined);
|
|
13222
|
+
const editingModel = command === "models" && positionals.length > 2 && ["add", "update", "remove"].includes(action2);
|
|
13223
|
+
const configuringModels = command === "models" && positionals.length > 2 && action2 === "config";
|
|
13224
|
+
const listingModels = command === "models" && positionals.length > 2 && action2 === "list";
|
|
13225
|
+
if (listingModels && (positionals.length !== 3 || nativeArgs.length || Object.keys(values2).some((name) => !["refresh", "search", "limit", "offset", "json"].includes(name))))
|
|
13218
13226
|
throw new Fault(400, "invalid_request", "Use models list PROVIDER with optional --refresh, --search, --limit and --offset.");
|
|
13219
|
-
if (
|
|
13227
|
+
if (values2["expires-on"] !== undefined && (!editingModel || action2 === "remove"))
|
|
13220
13228
|
throw new Fault(400, "conflicting_options", "--expires-on belongs to models add/update.");
|
|
13221
|
-
if (editingModel && (positionals.length !== 4 || nativeArgs.length || Object.keys(
|
|
13229
|
+
if (editingModel && (positionals.length !== 4 || nativeArgs.length || Object.keys(values2).some((name) => !(action2 === "remove" ? ["json"] : ["name", "expires-on", "file", "json"]).includes(name))))
|
|
13222
13230
|
throw new Fault(400, "invalid_request", "Use models add/update PROVIDER MODEL with --file or --name/--expires-on; models remove accepts only PROVIDER MODEL.");
|
|
13223
|
-
if (configuringModels && (positionals.length !== 3 || nativeArgs.length || Object.keys(
|
|
13231
|
+
if (configuringModels && (positionals.length !== 3 || nativeArgs.length || Object.keys(values2).some((name) => name !== "json")))
|
|
13224
13232
|
throw new Fault(400, "invalid_request", "Use models config PROVIDER without other settings.");
|
|
13225
|
-
if (editingModel &&
|
|
13233
|
+
if (editingModel && values2.file !== undefined && (values2.name !== undefined || values2["expires-on"] !== undefined))
|
|
13226
13234
|
throw new Fault(400, "conflicting_options", "Use --file by itself for model metadata.");
|
|
13227
|
-
const modelInput = editingModel &&
|
|
13235
|
+
const modelInput = editingModel && action2 !== "remove" ? parse2(modelSchema, values2.file !== undefined ? await readInput(values2.file) : { id: positionals[3], name: values2.name ?? positionals[3], expiresOn: values2["expires-on"] }) : undefined;
|
|
13228
13236
|
if (modelInput && modelInput.id !== positionals[3])
|
|
13229
13237
|
throw new Fault(400, "id_mismatch", "Model file id must match the command model ID.");
|
|
13230
|
-
if (editingModel &&
|
|
13238
|
+
if (editingModel && action2 === "remove")
|
|
13231
13239
|
parse2(modelSchema.shape.id, positionals[3]);
|
|
13232
|
-
const seedingProvider = command === "providers" &&
|
|
13233
|
-
if (
|
|
13240
|
+
const seedingProvider = command === "providers" && action2 === "add";
|
|
13241
|
+
if (values2["models-file"] !== undefined && !seedingProvider)
|
|
13234
13242
|
throw new Fault(400, "conflicting_options", "--models-file belongs to providers add.");
|
|
13235
|
-
if (command === "providers" &&
|
|
13243
|
+
if (command === "providers" && values2.model !== undefined && !seedingProvider)
|
|
13236
13244
|
throw new Fault(400, "conflicting_options", "Provider --model belongs to providers add. Use models add/update/remove for saved providers.");
|
|
13237
|
-
if (seedingProvider &&
|
|
13245
|
+
if (seedingProvider && values2["models-file"] !== undefined && values2.model !== undefined)
|
|
13238
13246
|
throw new Fault(400, "conflicting_options", "Use --model or --models-file, not both.");
|
|
13239
13247
|
let starterModels;
|
|
13240
|
-
if (seedingProvider && (
|
|
13241
|
-
starterModels = parse2(modelSchema.array().min(1).max(1e4),
|
|
13242
|
-
if (new Set(starterModels.map((
|
|
13248
|
+
if (seedingProvider && (values2.model !== undefined || values2["models-file"] !== undefined)) {
|
|
13249
|
+
starterModels = parse2(modelSchema.array().min(1).max(1e4), values2["models-file"] !== undefined ? await readInput(values2["models-file"]) : [{ id: values2.model, name: values2.model }]);
|
|
13250
|
+
if (new Set(starterModels.map((model3) => model3.id)).size !== starterModels.length)
|
|
13243
13251
|
throw new Fault(400, "duplicate_model", "Model IDs must be unique.");
|
|
13244
13252
|
}
|
|
13245
13253
|
const credentialFlags = ["vault-key", "vault-url", "vault-cli", "vault-account", "vault-operator", "keychain-service", "keychain-account", "origin"];
|
|
13246
13254
|
const credentials = new CredentialResolver;
|
|
13247
|
-
if (
|
|
13255
|
+
if (values2.sha256 !== undefined && !(command === "credentials" && action2 === "repair-executable"))
|
|
13248
13256
|
throw new Fault(400, "conflicting_options", "--sha256 belongs to credentials repair-executable.");
|
|
13249
13257
|
if (command === "credentials") {
|
|
13250
|
-
if (
|
|
13251
|
-
const explicitPath =
|
|
13252
|
-
if (Boolean(
|
|
13258
|
+
if (action2 === "repair-executable") {
|
|
13259
|
+
const explicitPath = values2["vault-cli"];
|
|
13260
|
+
if (Boolean(id2) === (explicitPath !== undefined) || positionals.length !== (id2 ? 3 : 2) || nativeArgs.length || Object.keys(values2).some((name) => !["sha256", "json", "vault-cli"].includes(name)) || !/^[a-f0-9]{64}$/.test(values2.sha256 ?? ""))
|
|
13253
13261
|
throw new Fault(400, "invalid_request", "Use credentials repair-executable PRESET_OR_REFERENCE (or --vault-cli PATH) --sha256 EXPECTED, with the executable digest from a verified package artifact.");
|
|
13254
13262
|
let executable = explicitPath;
|
|
13255
|
-
if (
|
|
13256
|
-
const binding = await credentials.bindings.get(credentialReference(
|
|
13263
|
+
if (id2) {
|
|
13264
|
+
const binding = await credentials.bindings.get(credentialReference(id2));
|
|
13257
13265
|
if (!binding || binding.source.kind !== "vault")
|
|
13258
13266
|
throw new Fault(422, "vault_binding_required", "Choose an existing vault credential binding to repair its configured executable.");
|
|
13259
13267
|
executable = binding.source.executable;
|
|
13260
13268
|
}
|
|
13261
|
-
output(await repairVaultExecutablePermissions(executable,
|
|
13269
|
+
output(await repairVaultExecutablePermissions(executable, values2.sha256));
|
|
13262
13270
|
return;
|
|
13263
13271
|
}
|
|
13264
13272
|
const bindingFlags = [...credentialFlags, "credential-env"];
|
|
13265
|
-
if (nativeArgs.length || positionals.length > 3 || Object.keys(
|
|
13273
|
+
if (nativeArgs.length || positionals.length > 3 || Object.keys(values2).some((name) => name !== "json" && !bindingFlags.includes(name)))
|
|
13266
13274
|
throw new Fault(400, "conflicting_options", "Credentials accepts only binding options; no API, profile or harness settings.");
|
|
13267
|
-
if (
|
|
13275
|
+
if (action2 !== "bind" && provided(bindingFlags))
|
|
13268
13276
|
throw new Fault(400, "conflicting_options", "Credential source and origin options belong to credentials bind.");
|
|
13269
|
-
if (
|
|
13277
|
+
if (action2 === "list" && !id2) {
|
|
13270
13278
|
output(await credentials.bindings.list());
|
|
13271
13279
|
return;
|
|
13272
13280
|
}
|
|
13273
|
-
if (
|
|
13274
|
-
output(await credentials.bindings.remove(credentialReference(
|
|
13281
|
+
if (action2 === "remove" && id2) {
|
|
13282
|
+
output(await credentials.bindings.remove(credentialReference(id2)));
|
|
13275
13283
|
return;
|
|
13276
13284
|
}
|
|
13277
|
-
if (
|
|
13278
|
-
output(await credentials.check(credentialReference(
|
|
13285
|
+
if (action2 === "check" && id2) {
|
|
13286
|
+
output(await credentials.check(credentialReference(id2)));
|
|
13279
13287
|
return;
|
|
13280
13288
|
}
|
|
13281
|
-
if (
|
|
13289
|
+
if (action2 !== "bind" || !id2)
|
|
13282
13290
|
throw new Fault(400, "invalid_request", "Use credentials bind PRESET, list, check PRESET_OR_REFERENCE, or remove PRESET_OR_REFERENCE.");
|
|
13283
13291
|
const hasVault = provided(["vault-key", "vault-url", "vault-cli", "vault-account", "vault-operator"]);
|
|
13284
13292
|
const hasKeychain = provided(["keychain-service", "keychain-account"]);
|
|
13285
13293
|
if (hasVault === hasKeychain)
|
|
13286
13294
|
throw new Fault(400, "conflicting_options", "Choose one credential source: vault or Keychain.");
|
|
13287
|
-
if (
|
|
13295
|
+
if (values2["vault-operator"] !== undefined && !["contracts", "env"].includes(values2["vault-operator"]))
|
|
13288
13296
|
throw new Fault(400, "invalid_request", "Use --vault-operator contracts or env.");
|
|
13289
|
-
if (
|
|
13297
|
+
if (values2["vault-account"] !== undefined && values2["vault-operator"] !== undefined)
|
|
13290
13298
|
throw new Fault(400, "conflicting_options", "Use either --vault-account or --vault-operator.");
|
|
13291
13299
|
const source = hasVault ? {
|
|
13292
13300
|
kind: "vault",
|
|
13293
|
-
key:
|
|
13294
|
-
url:
|
|
13295
|
-
executable:
|
|
13296
|
-
operator:
|
|
13297
|
-
} : { kind: "keychain", service:
|
|
13298
|
-
output(await credentials.bindings.bind(parse2(credentialBindingSchema, { schema: 1, ...bindingTarget(
|
|
13301
|
+
key: values2["vault-key"],
|
|
13302
|
+
url: values2["vault-url"],
|
|
13303
|
+
executable: values2["vault-cli"] ?? Bun.which("secrets"),
|
|
13304
|
+
operator: values2["vault-account"] !== undefined ? { kind: "keychain", account: values2["vault-account"] } : { kind: values2["vault-operator"] ?? "contracts" }
|
|
13305
|
+
} : { kind: "keychain", service: values2["keychain-service"], account: values2["keychain-account"] };
|
|
13306
|
+
output(await credentials.bindings.bind(parse2(credentialBindingSchema, { schema: 1, ...bindingTarget(id2, values2["credential-env"], values2.origin), source })));
|
|
13299
13307
|
return;
|
|
13300
13308
|
}
|
|
13301
13309
|
if (provided(credentialFlags))
|
|
13302
13310
|
throw new Fault(400, "conflicting_options", "Credential source and origin options belong to credentials bind.");
|
|
13303
|
-
const backend =
|
|
13311
|
+
const backend = values2.backend ?? "direct";
|
|
13304
13312
|
if (backend !== "direct" && backend !== "ori")
|
|
13305
13313
|
throw new Fault(400, "invalid_backend", "Use --backend direct or --backend ori.");
|
|
13306
|
-
if (command !== "launch" && (
|
|
13314
|
+
if (command !== "launch" && (values2.backend !== undefined || values2["ori-executable"] !== undefined))
|
|
13307
13315
|
throw new Fault(400, "conflicting_options", "--backend and --ori-executable belong to launch.");
|
|
13308
|
-
if (command === "launch" && backend === "ori" &&
|
|
13316
|
+
if (command === "launch" && backend === "ori" && values2.executable !== undefined)
|
|
13309
13317
|
throw new Fault(400, "conflicting_options", "--executable is ambiguous with --backend ori; use --ori-executable PATH.");
|
|
13310
|
-
if (command === "launch" && backend === "direct" &&
|
|
13318
|
+
if (command === "launch" && backend === "direct" && values2["ori-executable"] !== undefined)
|
|
13311
13319
|
throw new Fault(400, "conflicting_options", "--ori-executable requires --backend ori.");
|
|
13312
|
-
const mutation = (command === "providers" || command === "profiles") && ["add", "update"].includes(
|
|
13313
|
-
if (
|
|
13320
|
+
const mutation = (command === "providers" || command === "profiles") && ["add", "update"].includes(action2);
|
|
13321
|
+
if (values2.file && !editingModel && (!mutation || provided([...providerFlags, "name", "provider", "harness", "model", "models-file", "model-policy-file", "role-model"])))
|
|
13314
13322
|
throw new Fault(400, "conflicting_options", "Use --file by itself for provider/profile settings; inline settings cannot override an input file.");
|
|
13315
|
-
if (command === "launch" && !
|
|
13323
|
+
if (command === "launch" && !values2.provider && provided([...providerFlags, "name", "harness", "model", "search", "model-policy-file", "role-model"]))
|
|
13316
13324
|
throw new Fault(400, "conflicting_options", "Use --provider PROVIDER for direct launch settings, or update the saved profile explicitly.");
|
|
13317
|
-
if (
|
|
13325
|
+
if (values2.preset && !(command === "providers" && mutation))
|
|
13318
13326
|
throw new Fault(400, "conflicting_options", "--preset belongs to providers add/update. For direct launches use --provider PRESET.");
|
|
13319
|
-
if (
|
|
13327
|
+
if (values2.refresh && command !== "models")
|
|
13320
13328
|
throw new Fault(400, "conflicting_options", "--refresh belongs to models. Launch always discovers a fresh catalog.");
|
|
13321
|
-
if (
|
|
13329
|
+
if (values2["dry-run"] && command !== "launch")
|
|
13322
13330
|
throw new Fault(400, "conflicting_options", "--dry-run belongs to launch.");
|
|
13323
13331
|
if (command === "launch" && provided(["name", "harness", "file"]))
|
|
13324
13332
|
throw new Fault(400, "conflicting_options", "Launch takes its harness from the positional argument or saved profile; edit named records through providers/profiles.");
|
|
13325
|
-
if (command === "launch" &&
|
|
13326
|
-
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" :
|
|
13333
|
+
if (command === "launch" && values2.provider) {
|
|
13334
|
+
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action2);
|
|
13327
13335
|
assertHarnessArguments(harness, nativeArgs);
|
|
13328
|
-
await validateHarnessConfiguration(harness,
|
|
13336
|
+
await validateHarnessConfiguration(harness, values2.cwd ?? process.cwd(), nativeArgs);
|
|
13329
13337
|
}
|
|
13330
|
-
const dryLaunch = command === "launch" && Boolean(
|
|
13338
|
+
const dryLaunch = command === "launch" && Boolean(values2["dry-run"]);
|
|
13331
13339
|
const runtimeEnvironment = dryLaunch ? Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("SWITCHER_PROVIDER_"))) : process.env;
|
|
13332
13340
|
const runtime = await openCliRuntime(runtimeEnvironment, dryLaunch ? undefined : (provider) => credentials.resolve(provider));
|
|
13333
13341
|
const client = runtime.client;
|
|
@@ -13340,16 +13348,16 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13340
13348
|
};
|
|
13341
13349
|
try {
|
|
13342
13350
|
const presetOptions = () => ({
|
|
13343
|
-
protocol:
|
|
13344
|
-
baseUrl:
|
|
13345
|
-
credentialEnv:
|
|
13346
|
-
authStyle:
|
|
13347
|
-
catalogBaseUrl:
|
|
13348
|
-
catalogCredentialEnv:
|
|
13349
|
-
catalogAuthStyle:
|
|
13350
|
-
catalogFormat:
|
|
13351
|
-
catalogAccountId:
|
|
13352
|
-
modelsPath:
|
|
13351
|
+
protocol: values2.protocol ? parse2(protocolSchema, values2.protocol) : undefined,
|
|
13352
|
+
baseUrl: values2.url,
|
|
13353
|
+
credentialEnv: values2["credential-env"],
|
|
13354
|
+
authStyle: values2["auth-style"],
|
|
13355
|
+
catalogBaseUrl: values2["catalog-url"],
|
|
13356
|
+
catalogCredentialEnv: values2["catalog-credential-env"],
|
|
13357
|
+
catalogAuthStyle: values2["catalog-auth-style"],
|
|
13358
|
+
catalogFormat: values2["catalog-format"],
|
|
13359
|
+
catalogAccountId: values2["catalog-account-id"],
|
|
13360
|
+
modelsPath: values2["models-path"]
|
|
13353
13361
|
});
|
|
13354
13362
|
if (command === "doctor") {
|
|
13355
13363
|
const harnesses = await Promise.all(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"].map((h) => detectHarness(h)));
|
|
@@ -13363,36 +13371,36 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13363
13371
|
output({ version: VERSION, harnesses, api, liveVerified: false });
|
|
13364
13372
|
return;
|
|
13365
13373
|
}
|
|
13366
|
-
const page = { limit:
|
|
13374
|
+
const page = { limit: values2.limit ? Number(values2.limit) : undefined, offset: values2.offset ? Number(values2.offset) : undefined, search: values2.search };
|
|
13367
13375
|
const currentVersion = () => {
|
|
13368
|
-
const n = Number(
|
|
13376
|
+
const n = Number(values2.version);
|
|
13369
13377
|
if (!Number.isSafeInteger(n) || n < 1)
|
|
13370
13378
|
throw new Error("Use --version N with the record's current version.");
|
|
13371
13379
|
return n;
|
|
13372
13380
|
};
|
|
13373
13381
|
if (command === "launch") {
|
|
13374
|
-
if (!
|
|
13382
|
+
if (!action2)
|
|
13375
13383
|
throw new Error("A harness or saved profile ID is required.");
|
|
13376
|
-
const timeoutMs =
|
|
13384
|
+
const timeoutMs = values2.timeout ? Number(values2.timeout) * 1000 : undefined;
|
|
13377
13385
|
if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs <= 0))
|
|
13378
13386
|
throw new Error("--timeout must be positive seconds.");
|
|
13379
|
-
let profileId =
|
|
13387
|
+
let profileId = action2;
|
|
13380
13388
|
let credentialPreflight;
|
|
13381
13389
|
let resolvePreparedCredential;
|
|
13382
|
-
if (
|
|
13383
|
-
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" :
|
|
13384
|
-
const modelPolicy = await readModelPolicy(
|
|
13385
|
-
const provider = await resolveLaunchProvider(client,
|
|
13390
|
+
if (values2.provider) {
|
|
13391
|
+
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action2);
|
|
13392
|
+
const modelPolicy = await readModelPolicy(values2["model-policy-file"], values2["role-model"]);
|
|
13393
|
+
const provider = await resolveLaunchProvider(client, values2.provider, { ...presetOptions(), harness });
|
|
13386
13394
|
validateHarnessProvider(harness, provider);
|
|
13387
13395
|
let prepared;
|
|
13388
|
-
if (!
|
|
13396
|
+
if (!values2["dry-run"]) {
|
|
13389
13397
|
prepared = await ensureProviderCredential(provider, { resolver: credentials });
|
|
13390
13398
|
credentialPreflight = prepared.providerFingerprint;
|
|
13391
13399
|
resolvePreparedCredential = prepared.resolveCredential;
|
|
13392
13400
|
}
|
|
13393
|
-
const catalog =
|
|
13394
|
-
const
|
|
13395
|
-
const selected = catalog.models.find((m) => m.id ===
|
|
13401
|
+
const catalog = values2["dry-run"] ? await launchCatalog(client, provider, true) : await refreshCatalog(provider, prepared);
|
|
13402
|
+
const model3 = values2.model ?? await selectModel(catalog.models, values2.search, harness);
|
|
13403
|
+
const selected = catalog.models.find((m) => m.id === model3);
|
|
13396
13404
|
if (!selected)
|
|
13397
13405
|
throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
|
|
13398
13406
|
if (modelExpired(selected))
|
|
@@ -13401,60 +13409,60 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13401
13409
|
throw new Fault(422, "model_ineligible", "Selected model explicitly lacks text output or tool support.");
|
|
13402
13410
|
if (harness === "codex")
|
|
13403
13411
|
codexReasoning(selected, provider.baseUrl, reasoning);
|
|
13404
|
-
profileId = (await ensureLaunchProfile(client, provider, harness,
|
|
13412
|
+
profileId = (await ensureLaunchProfile(client, provider, harness, model3, modelPolicy)).id;
|
|
13405
13413
|
} else {
|
|
13406
|
-
if (
|
|
13414
|
+
if (values2.model || values2.protocol || values2.url || values2["credential-env"] || values2["model-policy-file"] || values2["role-model"])
|
|
13407
13415
|
throw new Error("Use --provider PROVIDER for a direct launch, or update the saved profile explicitly.");
|
|
13408
13416
|
const profile = await client.getProfile(profileId);
|
|
13409
13417
|
assertHarnessArguments(profile.harness, nativeArgs);
|
|
13410
|
-
await validateHarnessConfiguration(profile.harness,
|
|
13418
|
+
await validateHarnessConfiguration(profile.harness, values2.cwd ?? process.cwd(), nativeArgs);
|
|
13411
13419
|
const provider = await client.getProvider(profile.providerId);
|
|
13412
13420
|
if (profile.harness === "gemini")
|
|
13413
13421
|
validateHarnessProvider(profile.harness, provider);
|
|
13414
13422
|
let prepared;
|
|
13415
|
-
if (!
|
|
13423
|
+
if (!values2["dry-run"]) {
|
|
13416
13424
|
prepared = await ensureProviderCredential(provider, { resolver: credentials });
|
|
13417
13425
|
credentialPreflight = prepared.providerFingerprint;
|
|
13418
13426
|
resolvePreparedCredential = prepared.resolveCredential;
|
|
13419
13427
|
}
|
|
13420
|
-
if (
|
|
13428
|
+
if (values2["dry-run"])
|
|
13421
13429
|
await launchCatalog(client, provider, true);
|
|
13422
13430
|
else
|
|
13423
13431
|
await refreshCatalog(provider, prepared);
|
|
13424
13432
|
}
|
|
13425
|
-
if (
|
|
13433
|
+
if (values2["dry-run"]) {
|
|
13426
13434
|
const plan = await client.launchPlan(profileId);
|
|
13427
13435
|
if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && plan.profile.harness !== "codex")
|
|
13428
13436
|
throw new Fault(400, "conflicting_options", "Reasoning and full-access options require Codex or ChatGPT.");
|
|
13429
13437
|
if (reasoning) {
|
|
13430
|
-
const
|
|
13431
|
-
if (
|
|
13432
|
-
codexReasoning(
|
|
13438
|
+
const model3 = plan.catalog.models.find((model4) => model4.id === plan.profile.model);
|
|
13439
|
+
if (model3)
|
|
13440
|
+
codexReasoning(model3, plan.provider.baseUrl, reasoning);
|
|
13433
13441
|
}
|
|
13434
13442
|
assertHarnessArguments(plan.profile.harness, nativeArgs);
|
|
13435
13443
|
if (backend === "ori") {
|
|
13436
|
-
const { contract, warnings } = await validateOriForPlan(plan, { oriExecutable:
|
|
13444
|
+
const { contract, warnings } = await validateOriForPlan(plan, { oriExecutable: values2["ori-executable"], args: nativeArgs, cwd: values2.cwd });
|
|
13437
13445
|
output({ ...plan, backend: { kind: "ori", executable: contract.executable, version: contract.version, target: plan.profile.harness, provider: "openrouter", model: plan.profile.model, warnings: [...plan.warnings, ...warnings] } });
|
|
13438
13446
|
} else
|
|
13439
13447
|
output({ ...plan, ...desktop ? { desktop: { ...desktop, mode: "isolated-provider", sessionProfile: profileId } } : {}, ...claudeApp ? { desktop: { ...claudeApp, mode: "claude-3p-gateway", sessionProfile: profileId } } : {}, ...reasoning ? { reasoning } : {}, ...dangerouslyBypassApprovalsAndSandbox ? { permissions: { approvalPolicy: "never", sandboxMode: "danger-full-access" } } : {} });
|
|
13440
13448
|
return;
|
|
13441
13449
|
}
|
|
13442
|
-
process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable:
|
|
13450
|
+
process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)) });
|
|
13443
13451
|
return;
|
|
13444
13452
|
}
|
|
13445
13453
|
if (editingModel) {
|
|
13446
|
-
const saved =
|
|
13454
|
+
const saved = action2 === "add" ? await client.addModel(id2, modelInput) : action2 === "update" ? await client.updateModel(id2, modelInput) : await client.removeModel(id2, positionals[3]);
|
|
13447
13455
|
output({ providerId: saved.id, version: saved.version, ...modelInput ? { model: modelInput, expired: modelExpired(modelInput) } : { removed: positionals[3] } });
|
|
13448
13456
|
return;
|
|
13449
13457
|
}
|
|
13450
13458
|
if (configuringModels) {
|
|
13451
|
-
const provider = await client.getProvider(
|
|
13459
|
+
const provider = await client.getProvider(id2);
|
|
13452
13460
|
output({ providerId: provider.id, version: provider.version, manualModels: provider.manualModels, additionalModels: provider.additionalModels ?? [] });
|
|
13453
13461
|
return;
|
|
13454
13462
|
}
|
|
13455
|
-
if (command === "models" &&
|
|
13456
|
-
const provider = await resolveLaunchProvider(client, listingModels ?
|
|
13457
|
-
if (
|
|
13463
|
+
if (command === "models" && action2) {
|
|
13464
|
+
const provider = await resolveLaunchProvider(client, listingModels ? id2 : action2, presetOptions());
|
|
13465
|
+
if (values2.refresh)
|
|
13458
13466
|
await refreshCatalog(provider);
|
|
13459
13467
|
try {
|
|
13460
13468
|
output(await client.listModels(provider.id, page));
|
|
@@ -13467,80 +13475,80 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13467
13475
|
return;
|
|
13468
13476
|
}
|
|
13469
13477
|
if (command === "runs") {
|
|
13470
|
-
output(
|
|
13478
|
+
output(action2 === "get" && id2 ? await client.getRun(id2) : action2 === "list" ? await client.listRuns(page) : (() => {
|
|
13471
13479
|
throw new Error("Use runs list|get ID.");
|
|
13472
13480
|
})());
|
|
13473
13481
|
return;
|
|
13474
13482
|
}
|
|
13475
13483
|
if (command === "providers") {
|
|
13476
|
-
if (
|
|
13477
|
-
output(
|
|
13484
|
+
if (action2 === "presets") {
|
|
13485
|
+
output(id2 ? await client.getProviderPreset(id2) : await client.listProviderPresets());
|
|
13478
13486
|
return;
|
|
13479
13487
|
}
|
|
13480
|
-
if (
|
|
13488
|
+
if (action2 === "list") {
|
|
13481
13489
|
output(await client.listProviders(page));
|
|
13482
13490
|
return;
|
|
13483
13491
|
}
|
|
13484
|
-
if (
|
|
13485
|
-
output(await client.getProvider(
|
|
13492
|
+
if (action2 === "get" && id2) {
|
|
13493
|
+
output(await client.getProvider(id2));
|
|
13486
13494
|
return;
|
|
13487
13495
|
}
|
|
13488
|
-
if (
|
|
13489
|
-
const provider = await client.getProvider(
|
|
13496
|
+
if (action2 === "refresh" && id2) {
|
|
13497
|
+
const provider = await client.getProvider(id2);
|
|
13490
13498
|
output(await refreshCatalog(provider));
|
|
13491
13499
|
return;
|
|
13492
13500
|
}
|
|
13493
|
-
if (
|
|
13494
|
-
output(await client.deleteProvider(
|
|
13501
|
+
if (action2 === "delete" && id2) {
|
|
13502
|
+
output(await client.deleteProvider(id2, currentVersion()));
|
|
13495
13503
|
return;
|
|
13496
13504
|
}
|
|
13497
|
-
if (["add", "update"].includes(
|
|
13498
|
-
let input = parse2(providerInputSchema,
|
|
13499
|
-
id,
|
|
13500
|
-
name:
|
|
13501
|
-
baseUrl:
|
|
13502
|
-
protocol:
|
|
13503
|
-
credentialEnv:
|
|
13504
|
-
authStyle:
|
|
13505
|
-
catalogBaseUrl:
|
|
13506
|
-
catalogCredentialEnv:
|
|
13507
|
-
catalogAuthStyle:
|
|
13508
|
-
catalogFormat:
|
|
13509
|
-
catalogAccountId:
|
|
13510
|
-
modelsPath:
|
|
13505
|
+
if (["add", "update"].includes(action2) && id2) {
|
|
13506
|
+
let input = parse2(providerInputSchema, values2.file ? await readInput(values2.file) : values2.preset ? { ...providerFromPreset(values2.preset, { ...presetOptions(), id: id2 }), ...values2.name ? { name: values2.name } : {} } : {
|
|
13507
|
+
id: id2,
|
|
13508
|
+
name: values2.name ?? id2,
|
|
13509
|
+
baseUrl: values2.url,
|
|
13510
|
+
protocol: values2.protocol,
|
|
13511
|
+
credentialEnv: values2["credential-env"],
|
|
13512
|
+
authStyle: values2["auth-style"],
|
|
13513
|
+
catalogBaseUrl: values2["catalog-url"],
|
|
13514
|
+
catalogCredentialEnv: values2["catalog-credential-env"],
|
|
13515
|
+
catalogAuthStyle: values2["catalog-auth-style"],
|
|
13516
|
+
catalogFormat: values2["catalog-format"],
|
|
13517
|
+
catalogAccountId: values2["catalog-account-id"],
|
|
13518
|
+
modelsPath: values2["models-path"]
|
|
13511
13519
|
});
|
|
13512
13520
|
if (starterModels) {
|
|
13513
13521
|
const field = input.catalogFormat === "none" ? "manualModels" : "additionalModels";
|
|
13514
|
-
const models = new Map((input[field] ?? []).map((
|
|
13515
|
-
for (const
|
|
13516
|
-
models.set(
|
|
13522
|
+
const models = new Map((input[field] ?? []).map((model3) => [model3.id, model3]));
|
|
13523
|
+
for (const model3 of starterModels)
|
|
13524
|
+
models.set(model3.id, model3);
|
|
13517
13525
|
input = parse2(providerInputSchema, { ...input, [field]: [...models.values()] });
|
|
13518
13526
|
}
|
|
13519
|
-
if (input.id !==
|
|
13527
|
+
if (input.id !== id2)
|
|
13520
13528
|
throw new Error("File id must match the command id.");
|
|
13521
|
-
output(
|
|
13529
|
+
output(action2 === "add" ? await client.createProvider(input) : await client.updateProvider(input, currentVersion()));
|
|
13522
13530
|
return;
|
|
13523
13531
|
}
|
|
13524
13532
|
}
|
|
13525
13533
|
if (command === "profiles") {
|
|
13526
|
-
if (
|
|
13534
|
+
if (action2 === "list") {
|
|
13527
13535
|
output(await client.listProfiles(page));
|
|
13528
13536
|
return;
|
|
13529
13537
|
}
|
|
13530
|
-
if (
|
|
13531
|
-
output(await client.getProfile(
|
|
13538
|
+
if (action2 === "get" && id2) {
|
|
13539
|
+
output(await client.getProfile(id2));
|
|
13532
13540
|
return;
|
|
13533
13541
|
}
|
|
13534
|
-
if (
|
|
13535
|
-
output(await client.deleteProfile(
|
|
13542
|
+
if (action2 === "delete" && id2) {
|
|
13543
|
+
output(await client.deleteProfile(id2, currentVersion()));
|
|
13536
13544
|
return;
|
|
13537
13545
|
}
|
|
13538
|
-
if (["add", "update"].includes(
|
|
13539
|
-
const modelPolicy = await readModelPolicy(
|
|
13540
|
-
const input = parse2(profileInputSchema,
|
|
13541
|
-
if (input.id !==
|
|
13546
|
+
if (["add", "update"].includes(action2) && id2) {
|
|
13547
|
+
const modelPolicy = await readModelPolicy(values2["model-policy-file"], values2["role-model"]);
|
|
13548
|
+
const input = parse2(profileInputSchema, values2.file ? await readInput(values2.file) : { id: id2, name: values2.name ?? id2, providerId: values2.provider, harness: values2.harness, model: values2.model, ...modelPolicy ? { modelPolicy } : {} });
|
|
13549
|
+
if (input.id !== id2)
|
|
13542
13550
|
throw new Error("File id must match the command id.");
|
|
13543
|
-
output(
|
|
13551
|
+
output(action2 === "add" ? await client.createProfile(input) : await client.updateProfile(input, currentVersion()));
|
|
13544
13552
|
return;
|
|
13545
13553
|
}
|
|
13546
13554
|
}
|
|
@@ -13559,6 +13567,6 @@ if (import.meta.main) {
|
|
|
13559
13567
|
});
|
|
13560
13568
|
}
|
|
13561
13569
|
export {
|
|
13562
|
-
|
|
13563
|
-
|
|
13570
|
+
readModelPolicy,
|
|
13571
|
+
main
|
|
13564
13572
|
};
|