@hasna/switcher 0.2.2 → 0.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Dockerfile +38 -8
- package/README.md +14 -9
- package/dist/cli/index.js +992 -706
- package/dist/credentials.d.ts +18 -62
- package/dist/direct-launch.d.ts +2 -2
- package/dist/domain.d.ts +78 -4
- package/dist/generated/api.d.ts +109 -1
- package/dist/index.js +15 -11
- package/dist/mcp/index.js +1055 -95
- package/dist/mint/index.js +136 -0
- package/dist/mint-key.d.ts +34 -0
- package/dist/provider-credential-onboarding.d.ts +73 -0
- package/dist/sdk.d.ts +21 -1
- package/dist/sdk.js +15 -11
- package/dist/serve/index.js +350 -90
- package/dist/server.d.ts +2 -1
- package/dist/service.d.ts +8 -1
- package/dist/store.d.ts +4 -0
- package/hasna.contract.json +20 -6
- package/openapi.json +135 -9
- package/package.json +6 -3
package/dist/cli/index.js
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
var __require = import.meta.require;
|
|
4
3
|
|
|
5
4
|
// src/kilo.ts
|
|
6
5
|
import { createHash } from "crypto";
|
|
@@ -188,8 +187,8 @@ async function kiloSettings(cwd, stateDir, env = process.env, options = {}) {
|
|
|
188
187
|
const out = {};
|
|
189
188
|
if (own(v, "tools")) {
|
|
190
189
|
const tools = record(v.tools, path, "tools permission");
|
|
191
|
-
for (const
|
|
192
|
-
if (typeof
|
|
190
|
+
for (const enabled of Object.values(tools))
|
|
191
|
+
if (typeof enabled !== "boolean")
|
|
193
192
|
invalid(path, "tools permission");
|
|
194
193
|
out.tools = tools;
|
|
195
194
|
}
|
|
@@ -514,7 +513,7 @@ function canonicalPolicyJSON(value) {
|
|
|
514
513
|
}
|
|
515
514
|
|
|
516
515
|
// src/domain.ts
|
|
517
|
-
var VERSION = "0.2.
|
|
516
|
+
var VERSION = "0.2.3";
|
|
518
517
|
var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
519
518
|
var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
520
519
|
var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
@@ -617,6 +616,7 @@ var runUpdateSchema = z4.object({
|
|
|
617
616
|
routingEvents: routingEventsSchema.optional(),
|
|
618
617
|
routingEventsDropped: z4.number().int().min(0).max(1e6).optional()
|
|
619
618
|
}).strict();
|
|
619
|
+
var catalogSchema = z4.object({ models: z4.array(modelSchema).max(1e4), refreshedAt: z4.string().datetime(), source: z4.enum(["remote", "manual"]) }).strict();
|
|
620
620
|
|
|
621
621
|
class Fault extends Error {
|
|
622
622
|
status;
|
|
@@ -995,8 +995,8 @@ function assertHarnessArguments(harness, args, options = {}) {
|
|
|
995
995
|
if (arg.startsWith("--") || !short[harness]) {
|
|
996
996
|
if (harness === "codex" && flag === "--config")
|
|
997
997
|
config(equals < 0 ? args[i + 1] ?? "" : arg.slice(equals + 1));
|
|
998
|
-
const
|
|
999
|
-
if (equals < 0 && (
|
|
998
|
+
const required = values[harness].includes(flag) && !(harness === "hermes" && hermesChat && flag === "--oneshot") && !(harness === "opencode" && args[i + 1]?.startsWith("-"));
|
|
999
|
+
if (equals < 0 && (required || optionalValues[harness]?.includes(flag) && args[i + 1] !== undefined && !args[i + 1].startsWith("-")))
|
|
1000
1000
|
i++;
|
|
1001
1001
|
continue;
|
|
1002
1002
|
}
|
|
@@ -1161,8 +1161,8 @@ function getProviderPreset(id) {
|
|
|
1161
1161
|
return structuredClone(entry);
|
|
1162
1162
|
}
|
|
1163
1163
|
function providerFromPreset(presetId, options = {}) {
|
|
1164
|
-
const
|
|
1165
|
-
const selected =
|
|
1164
|
+
const preset = getProviderPreset(presetId);
|
|
1165
|
+
const selected = preset.protocols.find((p) => (!options.protocol || p.protocol === options.protocol) && (!options.harness || compatible(options.harness, p.protocol)));
|
|
1166
1166
|
if (!selected)
|
|
1167
1167
|
throw new Fault(422, "protocol_mismatch", "This provider preset has no native protocol compatible with the requested harness. Choose an explicitly compatible gateway.");
|
|
1168
1168
|
const baseUrl = options.baseUrl ?? selected.baseUrl;
|
|
@@ -1170,7 +1170,7 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
1170
1170
|
throw new Fault(400, "endpoint_required", "This preset requires an explicit --url for its inference endpoint.");
|
|
1171
1171
|
if (presetId === "azure-openai" && !/\/openai\/v1$/.test(endpoint(baseUrl)))
|
|
1172
1172
|
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 &&
|
|
1173
|
+
if (options.baseUrl && selected.baseUrl && new URL(endpoint(options.baseUrl)).origin !== new URL(selected.baseUrl).origin && preset.credentialEnv && !options.credentialEnv)
|
|
1174
1174
|
throw new Fault(422, "credential_authority", "An endpoint on another origin requires an explicit --credential-env reference.");
|
|
1175
1175
|
const suffix = selected.protocol === "anthropic-messages" ? "messages" : selected.protocol === "openai-responses" ? "responses" : "chat";
|
|
1176
1176
|
if (presetId === "fireworks" && !options.catalogBaseUrl && !options.catalogAccountId)
|
|
@@ -1179,11 +1179,11 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
1179
1179
|
throw new Fault(400, "catalog_url_required", "This preset requires an explicit --catalog-url when enabling a catalog parser.");
|
|
1180
1180
|
const catalogBaseUrl = options.catalogBaseUrl ?? (presetId === "fireworks" && options.catalogAccountId ? `https://api.fireworks.ai/v1/accounts/${encodeURIComponent(options.catalogAccountId)}` : options.baseUrl ? undefined : selected.catalogBaseUrl);
|
|
1181
1181
|
return parse2(providerInputSchema, {
|
|
1182
|
-
id: options.id ?? `${
|
|
1183
|
-
name:
|
|
1182
|
+
id: options.id ?? `${preset.id}-${suffix}`,
|
|
1183
|
+
name: preset.name,
|
|
1184
1184
|
baseUrl,
|
|
1185
1185
|
protocol: selected.protocol,
|
|
1186
|
-
credentialEnv: options.credentialEnv ??
|
|
1186
|
+
credentialEnv: options.credentialEnv ?? preset.credentialEnv,
|
|
1187
1187
|
authStyle: options.authStyle ?? selected.authStyle,
|
|
1188
1188
|
credentialCheck: selected.credentialCheck,
|
|
1189
1189
|
catalogBaseUrl,
|
|
@@ -1206,8 +1206,8 @@ function providerCredential(provider, env = process.env) {
|
|
|
1206
1206
|
return;
|
|
1207
1207
|
let value = env[provider.credentialEnv];
|
|
1208
1208
|
if (!value) {
|
|
1209
|
-
const
|
|
1210
|
-
value =
|
|
1209
|
+
const preset = providerPresets.find((p) => p.credentialEnv === provider.credentialEnv && p.protocols.some((route) => route.protocol === provider.protocol && (route.baseUrl ? new URL(route.baseUrl).origin === new URL(provider.baseUrl).origin : p.id === "azure-openai")));
|
|
1210
|
+
value = preset?.credentialAliases.map((name) => env[name]).find(Boolean);
|
|
1211
1211
|
}
|
|
1212
1212
|
if (value && /[\r\n]/.test(value))
|
|
1213
1213
|
throw new Fault(422, "credential_invalid", "Provider credential contains invalid header characters.");
|
|
@@ -1319,13 +1319,13 @@ class SwitcherError extends Error {
|
|
|
1319
1319
|
}
|
|
1320
1320
|
}
|
|
1321
1321
|
function apiError(status, data, apiKey) {
|
|
1322
|
-
const
|
|
1323
|
-
const error =
|
|
1322
|
+
const object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1323
|
+
const error = object(data) && object(data.error) ? data.error : {};
|
|
1324
1324
|
const escape = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1325
1325
|
const base64 = Buffer.from(apiKey, "utf8").toString("base64");
|
|
1326
|
-
const
|
|
1326
|
+
const literal = [apiKey, JSON.stringify(apiKey).slice(1, -1), base64, base64.replace(/=+$/, ""), Buffer.from(apiKey, "utf8").toString("base64url")];
|
|
1327
1327
|
const encoded = [encodeURIComponent(apiKey), new URLSearchParams({ key: apiKey }).toString().slice(4)];
|
|
1328
|
-
const patterns = [...new Set(
|
|
1328
|
+
const patterns = [...new Set(literal)].sort((a, b) => b.length - a.length).map(escape);
|
|
1329
1329
|
for (const value of encoded) {
|
|
1330
1330
|
patterns.unshift(escape(value).replace(/%[0-9A-F]{2}/g, (part) => part.replace(/[A-F]/g, (letter) => `[${letter}${letter.toLowerCase()}]`)));
|
|
1331
1331
|
}
|
|
@@ -1482,6 +1482,9 @@ class SwitcherClient {
|
|
|
1482
1482
|
refreshModels(id, idempotencyKey) {
|
|
1483
1483
|
return this.request("POST", `/v1/providers/${encodeURIComponent(id)}/refresh`, {}, { idempotencyKey });
|
|
1484
1484
|
}
|
|
1485
|
+
saveCatalog(id, providerVersion, catalog, idempotencyKey) {
|
|
1486
|
+
return this.request("PUT", `/v1/providers/${encodeURIComponent(id)}/catalog`, catalog, { version: providerVersion, idempotencyKey });
|
|
1487
|
+
}
|
|
1485
1488
|
listModels(id, options = {}) {
|
|
1486
1489
|
return this.request("GET", `/v1/providers/${encodeURIComponent(id)}/models?${this.query(options)}`);
|
|
1487
1490
|
}
|
|
@@ -1753,7 +1756,7 @@ function compileOpenCodeModelPolicy(input) {
|
|
|
1753
1756
|
}
|
|
1754
1757
|
function openCodeInvocationModel(args, policy, defaultAgent) {
|
|
1755
1758
|
let name = defaultAgent;
|
|
1756
|
-
const
|
|
1759
|
+
const values = new Set(["--session", "--prompt", "--agent", "--format", "--file", "--title", "--command", "--variant", "--log-level", "--replay-limit", "--completions", "-s", "-f"]);
|
|
1757
1760
|
for (let i = 0;i < args.length; i++) {
|
|
1758
1761
|
const arg = args[i];
|
|
1759
1762
|
if (arg === "--")
|
|
@@ -1762,7 +1765,7 @@ function openCodeInvocationModel(args, policy, defaultAgent) {
|
|
|
1762
1765
|
name = arg.slice(8);
|
|
1763
1766
|
continue;
|
|
1764
1767
|
}
|
|
1765
|
-
if (
|
|
1768
|
+
if (values.has(arg)) {
|
|
1766
1769
|
if (arg === "--agent")
|
|
1767
1770
|
name = args[i + 1];
|
|
1768
1771
|
i++;
|
|
@@ -1788,6 +1791,10 @@ import { isAbsolute as isAbsolute4, join as join4, resolve as resolve3 } from "p
|
|
|
1788
1791
|
var {SQL } = globalThis.Bun;
|
|
1789
1792
|
import { chmod, mkdir as mkdir3 } from "fs/promises";
|
|
1790
1793
|
import { dirname as dirname2, resolve as resolve2 } from "path";
|
|
1794
|
+
import { createHash as createHash2 } from "crypto";
|
|
1795
|
+
import { apiKeyMigrations } from "@hasna/contracts/auth";
|
|
1796
|
+
var authMigrationPlan = () => apiKeyMigrations().map((migration) => ({ ...migration, checksum: createHash2("sha256").update(migration.sql).digest("hex") }));
|
|
1797
|
+
|
|
1791
1798
|
class Store {
|
|
1792
1799
|
tail = Promise.resolve();
|
|
1793
1800
|
async exclusive(action) {
|
|
@@ -1825,13 +1832,16 @@ class Store {
|
|
|
1825
1832
|
await chmod(file, 384);
|
|
1826
1833
|
}
|
|
1827
1834
|
const store = new Store(sql, engine);
|
|
1828
|
-
|
|
1835
|
+
if (config.migrate === false)
|
|
1836
|
+
await store.verifySchema();
|
|
1837
|
+
else
|
|
1838
|
+
await store.migrate();
|
|
1829
1839
|
return store;
|
|
1830
1840
|
} catch (error) {
|
|
1831
1841
|
await sql?.close().catch(() => {});
|
|
1832
1842
|
const code = error?.code;
|
|
1833
1843
|
if (engine === "sqlite" && ["SQLITE_BUSY", "SQLITE_BUSY_SNAPSHOT", "SQLITE_LOCKED"].includes(code ?? "") && Date.now() < deadline) {
|
|
1834
|
-
await new Promise((
|
|
1844
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(200, 20 * (attempt + 1))));
|
|
1835
1845
|
continue;
|
|
1836
1846
|
}
|
|
1837
1847
|
throw new Fault(500, "storage_unavailable", "Database startup failed; check configuration, permissions and other database users.");
|
|
@@ -1844,23 +1854,66 @@ class Store {
|
|
|
1844
1854
|
await tx.unsafe("SELECT pg_advisory_xact_lock(782034215)");
|
|
1845
1855
|
await tx.unsafe("CREATE TABLE IF NOT EXISTS switcher_migrations (version INTEGER PRIMARY KEY)");
|
|
1846
1856
|
const versions = await tx.unsafe("SELECT version FROM switcher_migrations ORDER BY version");
|
|
1847
|
-
if (versions.some((v) => v.version >
|
|
1857
|
+
if (versions.some((v) => v.version > 2))
|
|
1848
1858
|
throw new Error("Newer database schema");
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1859
|
+
const applied = new Set(versions.map((v) => Number(v.version)));
|
|
1860
|
+
if (!applied.has(1)) {
|
|
1861
|
+
await tx.unsafe("CREATE TABLE switcher_providers (id TEXT PRIMARY KEY, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
|
|
1862
|
+
await tx.unsafe("CREATE TABLE switcher_profiles (id TEXT PRIMARY KEY, provider_id TEXT NOT NULL REFERENCES switcher_providers(id), version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
|
|
1863
|
+
await tx.unsafe("CREATE TABLE switcher_catalogs (id TEXT PRIMARY KEY REFERENCES switcher_providers(id) ON DELETE CASCADE, version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
|
|
1864
|
+
await tx.unsafe("CREATE TABLE switcher_runs (id TEXT PRIMARY KEY, profile_id TEXT NOT NULL REFERENCES switcher_profiles(id), version INTEGER NOT NULL, updated_at TEXT NOT NULL, payload TEXT NOT NULL)");
|
|
1865
|
+
await tx.unsafe("CREATE TABLE switcher_idempotency (key TEXT PRIMARY KEY, fingerprint TEXT NOT NULL, payload TEXT NOT NULL, created_at TEXT NOT NULL)");
|
|
1866
|
+
await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (1)");
|
|
1867
|
+
}
|
|
1868
|
+
if (this.engine === "postgresql") {
|
|
1869
|
+
await tx.unsafe("CREATE TABLE IF NOT EXISTS switcher_auth_migrations (id TEXT PRIMARY KEY, checksum TEXT NOT NULL)");
|
|
1870
|
+
const migrations = authMigrationPlan();
|
|
1871
|
+
const authRows = await tx.unsafe("SELECT id, checksum FROM switcher_auth_migrations ORDER BY id");
|
|
1872
|
+
const known = new Map(migrations.map((migration) => [migration.id, migration.checksum]));
|
|
1873
|
+
for (const row of authRows) {
|
|
1874
|
+
if (known.get(String(row.id)) !== String(row.checksum))
|
|
1875
|
+
throw new Error("Unknown or changed API-key migration");
|
|
1876
|
+
}
|
|
1877
|
+
const completed = new Set(authRows.map((row) => String(row.id)));
|
|
1878
|
+
for (const migration of migrations)
|
|
1879
|
+
if (!completed.has(migration.id)) {
|
|
1880
|
+
await tx.unsafe(migration.sql);
|
|
1881
|
+
await tx.unsafe("INSERT INTO switcher_auth_migrations(id,checksum) VALUES ($1,$2)", [migration.id, migration.checksum]);
|
|
1882
|
+
}
|
|
1883
|
+
if (!applied.has(2))
|
|
1884
|
+
await tx.unsafe("INSERT INTO switcher_migrations(version) VALUES (2)");
|
|
1885
|
+
}
|
|
1857
1886
|
});
|
|
1858
1887
|
}
|
|
1888
|
+
async verifySchema() {
|
|
1889
|
+
const versions = await this.sql.unsafe("SELECT version FROM switcher_migrations ORDER BY version");
|
|
1890
|
+
const applied = new Set(versions.map((row) => Number(row.version)));
|
|
1891
|
+
if (!applied.has(1) || this.engine === "postgresql" && !applied.has(2) || versions.some((row) => Number(row.version) > 2))
|
|
1892
|
+
throw new Error("Unsupported database schema");
|
|
1893
|
+
if (this.engine === "postgresql") {
|
|
1894
|
+
const expected = authMigrationPlan(), rows = await this.sql.unsafe("SELECT id, checksum FROM switcher_auth_migrations ORDER BY id");
|
|
1895
|
+
const actual = new Map(rows.map((row) => [String(row.id), String(row.checksum)]));
|
|
1896
|
+
if (actual.size !== expected.length || expected.some((migration) => actual.get(migration.id) !== migration.checksum))
|
|
1897
|
+
throw new Error("Unsupported API-key schema");
|
|
1898
|
+
await this.sql.unsafe("SELECT kid, app, agent, tid, scopes, token_hash, issued_at, expires_at, revoked_at, revoked_reason, last_used_at, created_by FROM api_keys LIMIT 0");
|
|
1899
|
+
}
|
|
1900
|
+
}
|
|
1859
1901
|
async ready() {
|
|
1860
1902
|
await this.exclusive(async () => {
|
|
1861
1903
|
await this.sql.unsafe("SELECT 1");
|
|
1862
1904
|
});
|
|
1863
1905
|
}
|
|
1906
|
+
authQueryClient() {
|
|
1907
|
+
if (this.engine !== "postgresql")
|
|
1908
|
+
throw new Fault(500, "auth_config", "Signed API keys require the PostgreSQL backend.");
|
|
1909
|
+
return {
|
|
1910
|
+
many: async (sql, params = []) => await this.sql.unsafe(sql, [...params]),
|
|
1911
|
+
get: async (sql, params = []) => (await this.sql.unsafe(sql, [...params]))[0] ?? null,
|
|
1912
|
+
execute: async (sql, params = []) => {
|
|
1913
|
+
await this.sql.unsafe(sql, [...params]);
|
|
1914
|
+
}
|
|
1915
|
+
};
|
|
1916
|
+
}
|
|
1864
1917
|
async close() {
|
|
1865
1918
|
await this.tail;
|
|
1866
1919
|
await this.sql.close();
|
|
@@ -1946,7 +1999,8 @@ class Store {
|
|
|
1946
1999
|
}
|
|
1947
2000
|
|
|
1948
2001
|
// src/service.ts
|
|
1949
|
-
import { createHash as
|
|
2002
|
+
import { createHash as createHash4, timingSafeEqual } from "crypto";
|
|
2003
|
+
import { verifyApiKey } from "@hasna/contracts/auth";
|
|
1950
2004
|
import { z as z5 } from "zod";
|
|
1951
2005
|
|
|
1952
2006
|
// src/auth.ts
|
|
@@ -1994,7 +2048,7 @@ async function waitForCatalogRetry(delayMs, deadline) {
|
|
|
1994
2048
|
if (Date.now() + delayMs > deadline)
|
|
1995
2049
|
throw catalogDeadlineFault();
|
|
1996
2050
|
if (delayMs > 0)
|
|
1997
|
-
await new Promise((
|
|
2051
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
1998
2052
|
}
|
|
1999
2053
|
async function fetchCatalogPage(url, headers, deadline) {
|
|
2000
2054
|
for (let retry = 0;; retry++) {
|
|
@@ -2102,8 +2156,8 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
2102
2156
|
candidate.outputModalities = capabilities.completion_chat ? ["text"] : [];
|
|
2103
2157
|
}
|
|
2104
2158
|
if (provider.catalogFormat === "together") {
|
|
2105
|
-
const
|
|
2106
|
-
candidate.outputModalities =
|
|
2159
|
+
const modalities = { chat: ["text"], language: ["text"], code: ["text"], image: ["image"], audio: ["audio"], video: ["video"], embedding: ["embedding"], rerank: ["rerank"], moderation: ["classification"] };
|
|
2160
|
+
candidate.outputModalities = modalities[row.type];
|
|
2107
2161
|
}
|
|
2108
2162
|
if (provider.catalogFormat === "fireworks") {
|
|
2109
2163
|
if (row.supportsImageInput === true)
|
|
@@ -2221,11 +2275,11 @@ async function discover(provider, env = process.env, resolveCredential) {
|
|
|
2221
2275
|
}
|
|
2222
2276
|
|
|
2223
2277
|
// src/model-policy.ts
|
|
2224
|
-
import { createHash as
|
|
2278
|
+
import { createHash as createHash3 } from "crypto";
|
|
2225
2279
|
var roles = ["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"];
|
|
2226
|
-
var id = (v,
|
|
2280
|
+
var id = (v, label) => {
|
|
2227
2281
|
if (typeof v !== "string" || !v || v.length > 300 || /[\u0000-\u001f\u007f]/.test(v))
|
|
2228
|
-
throw new Fault(400, "invalid_model_policy", `${
|
|
2282
|
+
throw new Fault(400, "invalid_model_policy", `${label} is invalid.`);
|
|
2229
2283
|
return v;
|
|
2230
2284
|
};
|
|
2231
2285
|
var uniq = (xs) => [...new Set(xs)];
|
|
@@ -2272,18 +2326,18 @@ function compileModelPolicy(model, catalog, policy) {
|
|
|
2272
2326
|
for (const [source, targets] of Object.entries(p.fallbacks ?? {})) {
|
|
2273
2327
|
if (!allowedSources.has(source) || !available.has(source) || !Array.isArray(targets) || Object.keys(fallbacks).length >= 200 || targets.length > 20)
|
|
2274
2328
|
throw new Fault(400, "invalid_model_policy", "Fallback source or list is invalid.");
|
|
2275
|
-
const
|
|
2276
|
-
for (const value of
|
|
2329
|
+
const values = targets.map((v, i) => id(v, `fallbacks.${source}[${i}]`));
|
|
2330
|
+
for (const value of values)
|
|
2277
2331
|
requireAvailable(value, "A fallback model is not present in the eligible catalog.");
|
|
2278
|
-
if (
|
|
2332
|
+
if (values.includes(source))
|
|
2279
2333
|
throw new Fault(400, "invalid_model_policy", "A model cannot fall back to itself.");
|
|
2280
|
-
fallbacks[source] = uniq(
|
|
2334
|
+
fallbacks[source] = uniq(values);
|
|
2281
2335
|
}
|
|
2282
2336
|
const allowedModels = uniq([selected, ...Object.values(compiledRoles), ...explicitAllowed, ...Object.values(fallbacks).flat()]).sort();
|
|
2283
2337
|
if (Object.values(aliases).some((value) => !allowedModels.includes(value)))
|
|
2284
2338
|
throw new Fault(422, "model_not_allowed", "A model alias target must be explicitly allowed by the launch policy.");
|
|
2285
2339
|
const result = { version: 1, model: selected, roles: compiledRoles, allowedModels, aliases, fallbacks };
|
|
2286
|
-
return { ...result, digest:
|
|
2340
|
+
return { ...result, digest: createHash3("sha256").update(stable(result)).digest("hex") };
|
|
2287
2341
|
}
|
|
2288
2342
|
function resolvePolicyModel(compiled, requested) {
|
|
2289
2343
|
const value = id(requested, "requested model");
|
|
@@ -2385,10 +2439,13 @@ var openapi_default = {
|
|
|
2385
2439
|
openapi: "3.0.3",
|
|
2386
2440
|
info: {
|
|
2387
2441
|
title: "Switcher API",
|
|
2388
|
-
version: "0.2.
|
|
2442
|
+
version: "0.2.3",
|
|
2389
2443
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2390
2444
|
},
|
|
2391
2445
|
security: [
|
|
2446
|
+
{
|
|
2447
|
+
apiKeyAuth: []
|
|
2448
|
+
},
|
|
2392
2449
|
{
|
|
2393
2450
|
bearerAuth: []
|
|
2394
2451
|
}
|
|
@@ -3142,6 +3199,73 @@ var openapi_default = {
|
|
|
3142
3199
|
}
|
|
3143
3200
|
}
|
|
3144
3201
|
},
|
|
3202
|
+
responses: {
|
|
3203
|
+
"200": {
|
|
3204
|
+
description: "Success",
|
|
3205
|
+
content: {
|
|
3206
|
+
"application/json": {
|
|
3207
|
+
schema: {
|
|
3208
|
+
$ref: "#/components/schemas/Catalog"
|
|
3209
|
+
}
|
|
3210
|
+
}
|
|
3211
|
+
}
|
|
3212
|
+
},
|
|
3213
|
+
default: {
|
|
3214
|
+
description: "Structured error",
|
|
3215
|
+
content: {
|
|
3216
|
+
"application/json": {
|
|
3217
|
+
schema: {
|
|
3218
|
+
$ref: "#/components/schemas/Error"
|
|
3219
|
+
}
|
|
3220
|
+
}
|
|
3221
|
+
}
|
|
3222
|
+
}
|
|
3223
|
+
},
|
|
3224
|
+
description: "Self-hosted/local server refresh. Hosted clients discover locally and commit catalog metadata through the version-checked catalog endpoint."
|
|
3225
|
+
}
|
|
3226
|
+
},
|
|
3227
|
+
"/v1/providers/{id}/catalog": {
|
|
3228
|
+
put: {
|
|
3229
|
+
operationId: "saveCatalog",
|
|
3230
|
+
parameters: [
|
|
3231
|
+
{
|
|
3232
|
+
name: "id",
|
|
3233
|
+
in: "path",
|
|
3234
|
+
required: true,
|
|
3235
|
+
schema: {
|
|
3236
|
+
type: "string"
|
|
3237
|
+
}
|
|
3238
|
+
},
|
|
3239
|
+
{
|
|
3240
|
+
name: "Idempotency-Key",
|
|
3241
|
+
in: "header",
|
|
3242
|
+
required: true,
|
|
3243
|
+
schema: {
|
|
3244
|
+
type: "string",
|
|
3245
|
+
minLength: 8,
|
|
3246
|
+
maxLength: 128
|
|
3247
|
+
}
|
|
3248
|
+
},
|
|
3249
|
+
{
|
|
3250
|
+
name: "If-Match",
|
|
3251
|
+
in: "header",
|
|
3252
|
+
required: true,
|
|
3253
|
+
schema: {
|
|
3254
|
+
type: "integer",
|
|
3255
|
+
minimum: 1
|
|
3256
|
+
}
|
|
3257
|
+
}
|
|
3258
|
+
],
|
|
3259
|
+
requestBody: {
|
|
3260
|
+
required: true,
|
|
3261
|
+
content: {
|
|
3262
|
+
"application/json": {
|
|
3263
|
+
schema: {
|
|
3264
|
+
$ref: "#/components/schemas/Catalog"
|
|
3265
|
+
}
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3268
|
+
},
|
|
3145
3269
|
responses: {
|
|
3146
3270
|
"200": {
|
|
3147
3271
|
description: "Success",
|
|
@@ -3529,6 +3653,36 @@ var openapi_default = {
|
|
|
3529
3653
|
}
|
|
3530
3654
|
},
|
|
3531
3655
|
"/v1/openapi.json": {
|
|
3656
|
+
get: {
|
|
3657
|
+
operationId: "openApiV1",
|
|
3658
|
+
parameters: [],
|
|
3659
|
+
responses: {
|
|
3660
|
+
"200": {
|
|
3661
|
+
description: "Success",
|
|
3662
|
+
content: {
|
|
3663
|
+
"application/json": {
|
|
3664
|
+
schema: {
|
|
3665
|
+
type: "object",
|
|
3666
|
+
additionalProperties: true
|
|
3667
|
+
}
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
3670
|
+
},
|
|
3671
|
+
default: {
|
|
3672
|
+
description: "Structured error",
|
|
3673
|
+
content: {
|
|
3674
|
+
"application/json": {
|
|
3675
|
+
schema: {
|
|
3676
|
+
$ref: "#/components/schemas/Error"
|
|
3677
|
+
}
|
|
3678
|
+
}
|
|
3679
|
+
}
|
|
3680
|
+
}
|
|
3681
|
+
},
|
|
3682
|
+
security: []
|
|
3683
|
+
}
|
|
3684
|
+
},
|
|
3685
|
+
"/openapi.json": {
|
|
3532
3686
|
get: {
|
|
3533
3687
|
operationId: "openApi",
|
|
3534
3688
|
parameters: [],
|
|
@@ -3554,12 +3708,18 @@ var openapi_default = {
|
|
|
3554
3708
|
}
|
|
3555
3709
|
}
|
|
3556
3710
|
}
|
|
3557
|
-
}
|
|
3711
|
+
},
|
|
3712
|
+
security: []
|
|
3558
3713
|
}
|
|
3559
3714
|
}
|
|
3560
3715
|
},
|
|
3561
3716
|
components: {
|
|
3562
3717
|
securitySchemes: {
|
|
3718
|
+
apiKeyAuth: {
|
|
3719
|
+
type: "apiKey",
|
|
3720
|
+
in: "header",
|
|
3721
|
+
name: "x-api-key"
|
|
3722
|
+
},
|
|
3563
3723
|
bearerAuth: {
|
|
3564
3724
|
type: "http",
|
|
3565
3725
|
scheme: "bearer"
|
|
@@ -5132,10 +5292,12 @@ var openapi_default = {
|
|
|
5132
5292
|
"name"
|
|
5133
5293
|
],
|
|
5134
5294
|
additionalProperties: false
|
|
5135
|
-
}
|
|
5295
|
+
},
|
|
5296
|
+
maxItems: 1e4
|
|
5136
5297
|
},
|
|
5137
5298
|
refreshedAt: {
|
|
5138
|
-
type: "string"
|
|
5299
|
+
type: "string",
|
|
5300
|
+
format: "date-time"
|
|
5139
5301
|
},
|
|
5140
5302
|
source: {
|
|
5141
5303
|
type: "string",
|
|
@@ -5720,10 +5882,12 @@ var openapi_default = {
|
|
|
5720
5882
|
"name"
|
|
5721
5883
|
],
|
|
5722
5884
|
additionalProperties: false
|
|
5723
|
-
}
|
|
5885
|
+
},
|
|
5886
|
+
maxItems: 1e4
|
|
5724
5887
|
},
|
|
5725
5888
|
refreshedAt: {
|
|
5726
|
-
type: "string"
|
|
5889
|
+
type: "string",
|
|
5890
|
+
format: "date-time"
|
|
5727
5891
|
},
|
|
5728
5892
|
source: {
|
|
5729
5893
|
type: "string",
|
|
@@ -6349,15 +6513,31 @@ var openapi_default = {
|
|
|
6349
6513
|
Ready: {
|
|
6350
6514
|
type: "object",
|
|
6351
6515
|
properties: {
|
|
6352
|
-
|
|
6353
|
-
type: "
|
|
6516
|
+
status: {
|
|
6517
|
+
type: "string",
|
|
6518
|
+
enum: [
|
|
6519
|
+
"ready",
|
|
6520
|
+
"unavailable"
|
|
6521
|
+
]
|
|
6522
|
+
},
|
|
6523
|
+
version: {
|
|
6524
|
+
type: "string"
|
|
6525
|
+
},
|
|
6526
|
+
backend: {
|
|
6527
|
+
type: "string",
|
|
6528
|
+
enum: [
|
|
6529
|
+
"sqlite",
|
|
6530
|
+
"postgresql"
|
|
6531
|
+
]
|
|
6354
6532
|
},
|
|
6355
6533
|
reason: {
|
|
6356
6534
|
type: "string"
|
|
6357
6535
|
}
|
|
6358
6536
|
},
|
|
6359
6537
|
required: [
|
|
6360
|
-
"
|
|
6538
|
+
"status",
|
|
6539
|
+
"version",
|
|
6540
|
+
"backend"
|
|
6361
6541
|
],
|
|
6362
6542
|
additionalProperties: false
|
|
6363
6543
|
},
|
|
@@ -6425,41 +6605,64 @@ var openapi_default = {
|
|
|
6425
6605
|
};
|
|
6426
6606
|
|
|
6427
6607
|
// src/service.ts
|
|
6428
|
-
var
|
|
6429
|
-
var
|
|
6430
|
-
|
|
6431
|
-
|
|
6608
|
+
var providerCatalogFingerprint = (provider) => createHash4("sha256").update(JSON.stringify(provider)).digest("hex");
|
|
6609
|
+
var snapshot = (profile, provider, catalog) => createHash4("sha256").update(JSON.stringify([profile, provider, { models: catalog.models, source: catalog.source }])).digest("hex");
|
|
6610
|
+
var hash = (s) => createHash4("sha256").update(s).digest();
|
|
6611
|
+
function localApiKey(headers) {
|
|
6612
|
+
const direct = headers.get("x-api-key");
|
|
6613
|
+
if (direct)
|
|
6614
|
+
return direct;
|
|
6615
|
+
const authorization = headers.get("authorization") ?? "";
|
|
6616
|
+
return authorization.startsWith("Bearer ") ? authorization.slice("Bearer ".length) : "";
|
|
6617
|
+
}
|
|
6618
|
+
function createHandler(store, authentication, providerEnv = process.env, resolveCredential) {
|
|
6619
|
+
const localToken = typeof authentication === "string" ? authentication : undefined;
|
|
6620
|
+
if (localToken !== undefined && (localToken.length < 24 || /[\r\n]/.test(localToken)))
|
|
6432
6621
|
throw new Fault(500, "auth_config", "Set HASNA_SWITCHER_API_KEY to a random token of at least 24 characters.");
|
|
6433
|
-
const expected = hash(
|
|
6622
|
+
const expected = localToken === undefined ? undefined : hash(localToken);
|
|
6623
|
+
const verifier = typeof authentication === "string" ? undefined : verifyApiKey({
|
|
6624
|
+
app: "switcher",
|
|
6625
|
+
signingSecret: authentication.signingSecret,
|
|
6626
|
+
keyStatus: authentication.keyStatus,
|
|
6627
|
+
...authentication.audit ? { audit: authentication.audit } : {}
|
|
6628
|
+
});
|
|
6434
6629
|
return async (request) => {
|
|
6435
6630
|
const requestId = crypto.randomUUID();
|
|
6436
6631
|
const json = (body, status = 200) => Response.json(body, { status, headers: { "x-request-id": requestId, "cache-control": "no-store", "x-content-type-options": "nosniff" } });
|
|
6437
6632
|
try {
|
|
6438
6633
|
const url = new URL(request.url);
|
|
6439
|
-
const
|
|
6440
|
-
if (request.method === "GET" &&
|
|
6634
|
+
const route = url.pathname.replace(/\/$/, "");
|
|
6635
|
+
if (request.method === "GET" && route === "/health")
|
|
6441
6636
|
return json({ status: "ok", version: VERSION, backend: store.engine });
|
|
6442
|
-
if (request.method === "GET" &&
|
|
6637
|
+
if (request.method === "GET" && route === "/version")
|
|
6443
6638
|
return json({ version: VERSION });
|
|
6444
|
-
if (request.method === "GET" &&
|
|
6639
|
+
if (request.method === "GET" && route === "/ready") {
|
|
6445
6640
|
try {
|
|
6446
6641
|
await store.ready();
|
|
6447
|
-
return json({ ready:
|
|
6642
|
+
return json({ status: "ready", version: VERSION, backend: store.engine });
|
|
6448
6643
|
} catch {
|
|
6449
|
-
return json({
|
|
6644
|
+
return json({ status: "unavailable", version: VERSION, backend: store.engine, reason: "Storage is unavailable." }, 503);
|
|
6450
6645
|
}
|
|
6451
6646
|
}
|
|
6452
|
-
if (
|
|
6453
|
-
throw new Fault(401, "unauthorized", "A valid API bearer token is required.");
|
|
6454
|
-
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route2))
|
|
6647
|
+
if (request.method === "GET" && ["/v1/openapi.json", "/openapi.json"].includes(route))
|
|
6455
6648
|
return json(openapi_default);
|
|
6456
|
-
|
|
6649
|
+
if (expected) {
|
|
6650
|
+
const presented = hash(localApiKey(request.headers));
|
|
6651
|
+
if (!timingSafeEqual(expected, presented))
|
|
6652
|
+
throw new Fault(401, "unauthorized", "A valid API key is required.");
|
|
6653
|
+
} else {
|
|
6654
|
+
const requiredScopes = [request.method === "GET" || request.method === "HEAD" ? "switcher:read" : "switcher:write"];
|
|
6655
|
+
const decision = await verifier.authenticate(request.headers, { method: request.method, path: route, requiredScopes });
|
|
6656
|
+
if (!decision.ok)
|
|
6657
|
+
throw new Fault(decision.status, `auth_${decision.reason}`, decision.message);
|
|
6658
|
+
}
|
|
6659
|
+
const parts = route.split("/").filter(Boolean);
|
|
6457
6660
|
if (parts[0] !== "v1")
|
|
6458
6661
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
6459
6662
|
const resource = parts[1];
|
|
6460
|
-
const
|
|
6461
|
-
if (
|
|
6462
|
-
parse2(idSchema,
|
|
6663
|
+
const id = parts[2];
|
|
6664
|
+
if (id)
|
|
6665
|
+
parse2(idSchema, id);
|
|
6463
6666
|
const page = () => parse2(z5.object({
|
|
6464
6667
|
limit: z5.coerce.number().int().min(1).max(1000).default(100),
|
|
6465
6668
|
offset: z5.coerce.number().int().min(0).max(1e6).default(0),
|
|
@@ -6467,16 +6670,16 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
6467
6670
|
}).strict(), Object.fromEntries(url.searchParams));
|
|
6468
6671
|
if (request.method === "GET") {
|
|
6469
6672
|
if (resource === "provider-presets" && parts.length <= 3)
|
|
6470
|
-
return json(
|
|
6673
|
+
return json(id ? getProviderPreset(id) : { data: providerPresets });
|
|
6471
6674
|
if (["providers", "profiles", "runs"].includes(resource) && parts.length <= 3) {
|
|
6472
6675
|
const kind = resource;
|
|
6473
|
-
return json(
|
|
6676
|
+
return json(id ? await store.get(kind, id) : await store.list(kind, page()));
|
|
6474
6677
|
}
|
|
6475
|
-
if (resource === "providers" &&
|
|
6476
|
-
const catalog = await store.get("catalogs",
|
|
6678
|
+
if (resource === "providers" && id && parts[3] === "models" && parts.length === 4) {
|
|
6679
|
+
const catalog = await store.get("catalogs", id);
|
|
6477
6680
|
const p = page();
|
|
6478
6681
|
const filtered = catalog.models.filter((m) => [m.id, m.name].some((s) => s.toLowerCase().includes(p.search.toLowerCase())));
|
|
6479
|
-
return json({ ...catalog, models: undefined, data: filtered.slice(p.offset, p.offset + p.limit).map((m) => ({ ...m, codingEligible: codingEligible(m), expired: modelExpired(m) })), total: filtered.length, ...p });
|
|
6682
|
+
return json({ ...catalog, providerVersion: undefined, providerFingerprint: undefined, models: undefined, data: filtered.slice(p.offset, p.offset + p.limit).map((m) => ({ ...m, codingEligible: codingEligible(m), expired: modelExpired(m) })), total: filtered.length, ...p });
|
|
6480
6683
|
}
|
|
6481
6684
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
6482
6685
|
}
|
|
@@ -6495,7 +6698,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
6495
6698
|
throw new Fault(400, "invalid_json", "Request must contain valid JSON under 1 MiB.");
|
|
6496
6699
|
}
|
|
6497
6700
|
}
|
|
6498
|
-
const fingerprint = hash(JSON.stringify([request.method,
|
|
6701
|
+
const fingerprint = hash(JSON.stringify([request.method, route, body, request.headers.get("if-match")])).toString("hex");
|
|
6499
6702
|
const version = () => {
|
|
6500
6703
|
const v = request.headers.get("if-match");
|
|
6501
6704
|
if (!v || !/^[1-9]\d*$/.test(v))
|
|
@@ -6504,49 +6707,73 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
6504
6707
|
};
|
|
6505
6708
|
const replay = await store.replay(key, fingerprint);
|
|
6506
6709
|
if (replay.found)
|
|
6507
|
-
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
6710
|
+
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id ? 201 : 200);
|
|
6508
6711
|
let refreshed;
|
|
6509
|
-
if (resource === "providers" &&
|
|
6712
|
+
if (!expected && resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST")
|
|
6713
|
+
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" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
6510
6715
|
parse2(z5.object({}).strict(), body);
|
|
6511
|
-
const provider = await store.get("providers",
|
|
6716
|
+
const provider = await store.get("providers", id);
|
|
6512
6717
|
refreshed = { provider, catalog: await discover(provider, providerEnv, resolveCredential) };
|
|
6513
6718
|
}
|
|
6514
6719
|
const result = await store.mutate(key, fingerprint, async (db) => {
|
|
6515
6720
|
if ((resource === "providers" || resource === "profiles") && parts.length <= 3) {
|
|
6516
|
-
if (request.method === "DELETE" &&
|
|
6517
|
-
return store.remove(resource,
|
|
6518
|
-
if (request.method === "POST" && !
|
|
6721
|
+
if (request.method === "DELETE" && id)
|
|
6722
|
+
return store.remove(resource, id, version(), db);
|
|
6723
|
+
if (request.method === "POST" && !id || request.method === "PUT" && id) {
|
|
6519
6724
|
const value = resource === "providers" ? parse2(providerInputSchema, body) : parse2(profileInputSchema, body);
|
|
6520
|
-
if (
|
|
6725
|
+
if (id && value.id !== id)
|
|
6521
6726
|
throw new Fault(400, "id_mismatch", "Path and body IDs must match.");
|
|
6522
6727
|
if (resource === "profiles") {
|
|
6523
6728
|
const profile = value;
|
|
6524
6729
|
const provider = await store.get("providers", profile.providerId, db);
|
|
6525
6730
|
validateHarnessProvider(profile.harness, provider);
|
|
6526
6731
|
}
|
|
6527
|
-
const saved = await store.put(resource, value,
|
|
6528
|
-
if (resource === "providers" &&
|
|
6529
|
-
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [
|
|
6732
|
+
const saved = await store.put(resource, value, id ? version() : undefined, db);
|
|
6733
|
+
if (resource === "providers" && id)
|
|
6734
|
+
await db.unsafe("DELETE FROM switcher_catalogs WHERE id = $1", [id]);
|
|
6530
6735
|
return saved;
|
|
6531
6736
|
}
|
|
6532
6737
|
}
|
|
6533
|
-
if (resource === "providers" &&
|
|
6738
|
+
if (resource === "providers" && id && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
6534
6739
|
if (store.engine === "postgresql")
|
|
6535
|
-
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [
|
|
6536
|
-
const provider = await store.get("providers",
|
|
6740
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id]);
|
|
6741
|
+
const provider = await store.get("providers", id, db);
|
|
6537
6742
|
if (!refreshed || provider.version !== refreshed.provider.version)
|
|
6538
6743
|
throw new Fault(409, "provider_changed", "Provider changed during discovery; refresh again.");
|
|
6539
6744
|
const catalog = refreshed.catalog;
|
|
6540
6745
|
let old;
|
|
6541
6746
|
try {
|
|
6542
|
-
old = await store.get("catalogs",
|
|
6747
|
+
old = await store.get("catalogs", id, db);
|
|
6543
6748
|
} catch (e) {
|
|
6544
6749
|
if (!(e instanceof Fault && e.status === 404))
|
|
6545
6750
|
throw e;
|
|
6546
6751
|
}
|
|
6547
|
-
|
|
6752
|
+
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
6753
|
+
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
6754
|
+
}
|
|
6755
|
+
if (resource === "providers" && id && parts[3] === "catalog" && parts.length === 4 && request.method === "PUT") {
|
|
6756
|
+
if (store.engine === "postgresql")
|
|
6757
|
+
await db.unsafe("SELECT id FROM switcher_providers WHERE id = $1 FOR SHARE", [id]);
|
|
6758
|
+
const provider = await store.get("providers", id, db);
|
|
6759
|
+
if (provider.version !== version())
|
|
6760
|
+
throw new Fault(409, "provider_changed", "Provider changed during local discovery; refresh again.");
|
|
6761
|
+
const catalog = parse2(catalogSchema, body);
|
|
6762
|
+
const expectedSource = provider.manualModels.length ? "manual" : "remote";
|
|
6763
|
+
if (catalog.source !== expectedSource)
|
|
6764
|
+
throw new Fault(422, "catalog_source_mismatch", "Catalog provenance does not match the current provider configuration.");
|
|
6765
|
+
catalog.refreshedAt = new Date().toISOString();
|
|
6766
|
+
let old;
|
|
6767
|
+
try {
|
|
6768
|
+
old = await store.get("catalogs", id, db);
|
|
6769
|
+
} catch (error) {
|
|
6770
|
+
if (!(error instanceof Fault && error.status === 404))
|
|
6771
|
+
throw error;
|
|
6772
|
+
}
|
|
6773
|
+
const saved = await store.put("catalogs", { id, ...catalog, providerVersion: provider.version, providerFingerprint: providerCatalogFingerprint(provider) }, old?.version, db);
|
|
6774
|
+
return { models: saved.models, refreshedAt: saved.refreshedAt, source: saved.source };
|
|
6548
6775
|
}
|
|
6549
|
-
if (resource === "launch-plans" && !
|
|
6776
|
+
if (resource === "launch-plans" && !id && request.method === "POST") {
|
|
6550
6777
|
const { profileId } = parse2(z5.object({ profileId: idSchema }).strict(), body);
|
|
6551
6778
|
const profile = await store.get("profiles", profileId, db);
|
|
6552
6779
|
const provider = await store.get("providers", profile.providerId, db);
|
|
@@ -6559,6 +6786,9 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
6559
6786
|
throw new Fault(422, "catalog_missing", "Refresh the provider catalog before launching.");
|
|
6560
6787
|
throw e;
|
|
6561
6788
|
}
|
|
6789
|
+
const stored = catalog;
|
|
6790
|
+
if (stored.providerVersion !== undefined && stored.providerVersion !== provider.version || stored.providerFingerprint !== undefined && stored.providerFingerprint !== providerCatalogFingerprint(provider))
|
|
6791
|
+
throw new Fault(409, "catalog_provider_changed", "Catalog metadata belongs to an older provider configuration; refresh locally before launching.");
|
|
6562
6792
|
const selected = catalog.models.find((m) => m.id === profile.model);
|
|
6563
6793
|
if (!selected)
|
|
6564
6794
|
throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
|
|
@@ -6576,7 +6806,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
6576
6806
|
warnings.push("Catalog snapshot is older than five minutes; refresh before launching.");
|
|
6577
6807
|
return { profile, provider, catalog, warnings, planToken: snapshot(profile, provider, catalog) };
|
|
6578
6808
|
}
|
|
6579
|
-
if (resource === "runs" && !
|
|
6809
|
+
if (resource === "runs" && !id && request.method === "POST") {
|
|
6580
6810
|
if (body?.modelPolicyVersion !== 1)
|
|
6581
6811
|
throw new Fault(409, "launcher_upgrade_required", "This API requires a launcher with automatic model policy version 1; upgrade the Switcher CLI/SDK.");
|
|
6582
6812
|
const input = parse2(runInputSchema, body);
|
|
@@ -6601,16 +6831,16 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
6601
6831
|
compileModelPolicy(profile.model, catalog.models.filter((model) => modelExpired(model) || harnessEligible(model, profile.harness)), profile.modelPolicy);
|
|
6602
6832
|
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);
|
|
6603
6833
|
}
|
|
6604
|
-
if (resource === "runs" &&
|
|
6834
|
+
if (resource === "runs" && id && request.method === "PATCH" && parts.length === 3) {
|
|
6605
6835
|
const input = parse2(runUpdateSchema, body);
|
|
6606
|
-
const run = await store.get("runs",
|
|
6836
|
+
const run = await store.get("runs", id, db);
|
|
6607
6837
|
if (run.status !== "running")
|
|
6608
6838
|
throw new Fault(409, "run_finished", "Run has already finished.");
|
|
6609
6839
|
return store.put("runs", { ...run, ...input, endedAt: new Date().toISOString() }, version(), db);
|
|
6610
6840
|
}
|
|
6611
6841
|
throw new Fault(404, "not_found", "Route was not found.");
|
|
6612
6842
|
});
|
|
6613
|
-
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !
|
|
6843
|
+
return json(result, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id ? 201 : 200);
|
|
6614
6844
|
} catch (error) {
|
|
6615
6845
|
const safe = error instanceof Fault ? error : new Fault(500, "internal_error", "Request failed.");
|
|
6616
6846
|
return json({ error: { code: safe.code, message: safe.message, requestId } }, safe.status);
|
|
@@ -6619,21 +6849,35 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
6619
6849
|
}
|
|
6620
6850
|
|
|
6621
6851
|
// src/server.ts
|
|
6852
|
+
import { ApiKeyStore } from "@hasna/contracts/auth";
|
|
6622
6853
|
async function startServer(options) {
|
|
6623
6854
|
const port = options.port ?? 0;
|
|
6624
6855
|
if (!Number.isInteger(port) || port < 0 || port > 65535)
|
|
6625
6856
|
throw new Fault(400, "invalid_port", "Port must be an integer between 0 and 65535.");
|
|
6626
|
-
if (options.apiKey
|
|
6857
|
+
if (Boolean(options.apiKey) === Boolean(options.signingSecret))
|
|
6858
|
+
throw new Fault(500, "auth_config", "Configure exactly one local API token or hosted API signing secret.");
|
|
6859
|
+
if (options.apiKey && (options.apiKey.length < 24 || /[\r\n]/.test(options.apiKey)))
|
|
6627
6860
|
throw new Fault(500, "auth_config", "Use a random operator token of at least 24 characters.");
|
|
6628
|
-
|
|
6861
|
+
if (options.signingSecret && (options.signingSecret.length < 32 || /[\r\n]/.test(options.signingSecret)))
|
|
6862
|
+
throw new Fault(500, "auth_config", "Use an API signing secret of at least 32 characters.");
|
|
6863
|
+
if (options.signingSecret && !options.databaseUrl)
|
|
6864
|
+
throw new Fault(500, "storage_config", "Hosted signed-key authentication requires PostgreSQL; configure HASNA_SWITCHER_DATABASE_URL.");
|
|
6865
|
+
const store = await Store.open({ databaseUrl: options.databaseUrl, sqlitePath: options.sqlitePath, migrate: !options.signingSecret });
|
|
6629
6866
|
let server;
|
|
6630
6867
|
try {
|
|
6868
|
+
const authentication = options.apiKey ?? (() => {
|
|
6869
|
+
const keyStore = new ApiKeyStore(store.authQueryClient());
|
|
6870
|
+
return { kind: "signed-api-key", signingSecret: options.signingSecret, keyStatus: keyStore.keyStatus, audit: (event) => {
|
|
6871
|
+
if (event.outcome === "deny")
|
|
6872
|
+
console.error(`api_auth deny kid=${event.kid ?? "-"} reason=${event.reason ?? "-"} ${event.method ?? "-"} ${event.path ?? "-"}`);
|
|
6873
|
+
} };
|
|
6874
|
+
})();
|
|
6631
6875
|
server = Bun.serve({
|
|
6632
6876
|
hostname: options.hostname ?? "127.0.0.1",
|
|
6633
6877
|
port,
|
|
6634
6878
|
maxRequestBodySize: 1024 * 1024,
|
|
6635
6879
|
idleTimeout: 60,
|
|
6636
|
-
fetch: createHandler(store,
|
|
6880
|
+
fetch: createHandler(store, authentication, options.providerEnv, options.resolveCredential)
|
|
6637
6881
|
});
|
|
6638
6882
|
await store.ready();
|
|
6639
6883
|
} catch (error) {
|
|
@@ -6673,7 +6917,19 @@ var SWITCHER_LOCAL_OPT_IN_ENV_KEYS = ["HASNA_SWITCHER_LOCAL", "SWITCHER_LOCAL"];
|
|
|
6673
6917
|
var SWITCHER_KEYCHAIN_ITEM = "hasna.credentials.switcher.api-key";
|
|
6674
6918
|
var SWITCHER_CREDENTIALS_FILE = "~/.hasna/switcher/config/credentials";
|
|
6675
6919
|
function isSwitcherLocalOptIn(env = process.env) {
|
|
6676
|
-
|
|
6920
|
+
let selected;
|
|
6921
|
+
for (const key of SWITCHER_LOCAL_OPT_IN_ENV_KEYS) {
|
|
6922
|
+
if (env[key] === undefined)
|
|
6923
|
+
continue;
|
|
6924
|
+
const value = env[key].trim().toLowerCase();
|
|
6925
|
+
const decision = !value || ["0", "false", "no", "off"].includes(value) ? false : ["1", "true", "yes", "on"].includes(value) ? true : undefined;
|
|
6926
|
+
if (decision === undefined)
|
|
6927
|
+
throw new Fault(400, "invalid_local_opt_in", `${key} must be one of 1, true, yes, on, 0, false, no, or off.`);
|
|
6928
|
+
if (selected !== undefined && selected !== decision)
|
|
6929
|
+
throw new Fault(400, "conflicting_local_opt_in", "HASNA_SWITCHER_LOCAL and SWITCHER_LOCAL must not disagree.");
|
|
6930
|
+
selected = decision;
|
|
6931
|
+
}
|
|
6932
|
+
return selected ?? false;
|
|
6677
6933
|
}
|
|
6678
6934
|
function switcherAuthorityEnvKeys() {
|
|
6679
6935
|
const keys = clientTransportEnvKeys("switcher");
|
|
@@ -6769,14 +7025,14 @@ var nativeUtilityAliases = ["auto", "pro", "flash", "flash-lite", "auto-gemini-3
|
|
|
6769
7025
|
function ownRecord() {
|
|
6770
7026
|
return Object.create(null);
|
|
6771
7027
|
}
|
|
6772
|
-
function safeId(value,
|
|
7028
|
+
function safeId(value, label) {
|
|
6773
7029
|
if (typeof value !== "string" || value.length < 1 || value.length > 300 || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
6774
|
-
throw new Fault(400, "invalid_model_policy", `${
|
|
7030
|
+
throw new Fault(400, "invalid_model_policy", `${label} is invalid.`);
|
|
6775
7031
|
}
|
|
6776
7032
|
return value;
|
|
6777
7033
|
}
|
|
6778
|
-
function compileGeminiModelPolicy(
|
|
6779
|
-
const selected = safeId(
|
|
7034
|
+
function compileGeminiModelPolicy(selectedModel, models, compiled) {
|
|
7035
|
+
const selected = safeId(selectedModel, "model");
|
|
6780
7036
|
if (compiled.model !== selected)
|
|
6781
7037
|
throw new Fault(400, "invalid_model_policy", "Gemini policy does not match the selected model.");
|
|
6782
7038
|
for (const role of ["planning", "review"])
|
|
@@ -6802,8 +7058,8 @@ function compileGeminiModelPolicy(selectedModel2, models, compiled) {
|
|
|
6802
7058
|
const modelChains = ownRecord();
|
|
6803
7059
|
const modelDefinitions = ownRecord();
|
|
6804
7060
|
for (const model of models) {
|
|
6805
|
-
const
|
|
6806
|
-
modelDefinitions[
|
|
7061
|
+
const id = safeId(model.id, "catalog model");
|
|
7062
|
+
modelDefinitions[id] = {
|
|
6807
7063
|
displayName: model.name,
|
|
6808
7064
|
tier: "custom",
|
|
6809
7065
|
family: "switcher",
|
|
@@ -6812,9 +7068,9 @@ function compileGeminiModelPolicy(selectedModel2, models, compiled) {
|
|
|
6812
7068
|
features: { thinking: false, multimodalToolUse: model.inputModalities?.includes("image") ?? false }
|
|
6813
7069
|
};
|
|
6814
7070
|
}
|
|
6815
|
-
for (const
|
|
6816
|
-
safeId(
|
|
6817
|
-
modelIdResolutions[
|
|
7071
|
+
for (const id of [...new Set([...compiled.allowedModels, ...models.map((model) => model.id)])]) {
|
|
7072
|
+
safeId(id, "catalog model");
|
|
7073
|
+
modelIdResolutions[id] = { default: id, contexts: [] };
|
|
6818
7074
|
}
|
|
6819
7075
|
for (const alias of nativeUtilityAliases) {
|
|
6820
7076
|
if (!eligible.has(alias))
|
|
@@ -6838,8 +7094,8 @@ var nativeModels = ["gemini-3.1-flash-lite", "gemini-3.1-pro-preview", "gemini-3
|
|
|
6838
7094
|
var object2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
6839
7095
|
async function regular(path, limit = 2 * 1024 * 1024) {
|
|
6840
7096
|
try {
|
|
6841
|
-
const
|
|
6842
|
-
if (!
|
|
7097
|
+
const stat = await lstat2(path);
|
|
7098
|
+
if (!stat.isFile() || stat.size > limit)
|
|
6843
7099
|
throw new Error("unsupported");
|
|
6844
7100
|
return true;
|
|
6845
7101
|
} catch (error) {
|
|
@@ -6898,17 +7154,17 @@ async function validateGeminiConfiguration(cwd, env = process.env) {
|
|
|
6898
7154
|
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");
|
|
6899
7155
|
const defaultsPath = env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ?? join5(dirname3(systemPath), "system-defaults.json");
|
|
6900
7156
|
const paths = [defaultsPath, join5(home, ".gemini", "settings.json"), join5(resolve4(cwd), ".gemini", "settings.json"), systemPath];
|
|
6901
|
-
const
|
|
7157
|
+
const values = [];
|
|
6902
7158
|
for (const path of paths) {
|
|
6903
7159
|
const value = await settings(path);
|
|
6904
7160
|
check(value, path);
|
|
6905
|
-
|
|
7161
|
+
values.push(value);
|
|
6906
7162
|
}
|
|
6907
7163
|
for (const key of ["policyPaths", "adminPolicyPaths"])
|
|
6908
|
-
if (
|
|
7164
|
+
if (values[2][key]?.some?.((path) => typeof path === "string" && (path === "~" || path.startsWith("~/"))))
|
|
6909
7165
|
throw new Error("Gemini project policy paths using ~ must use an absolute path so workspace trust remains authoritative under an isolated native home.");
|
|
6910
|
-
const contextNames = [...new Set(["GEMINI.md", ...
|
|
6911
|
-
return { home, defaults: originalPaths(
|
|
7166
|
+
const contextNames = [...new Set(["GEMINI.md", ...values.flatMap((value) => [value.context?.fileName ?? []].flat())])];
|
|
7167
|
+
return { home, defaults: originalPaths(values[0], home), user: originalPaths(values[1], home), system: originalPaths(values[3], home), contextNames, trustPath: env.GEMINI_CLI_TRUSTED_FOLDERS_PATH ?? join5(home, ".gemini", "trustedFolders.json") };
|
|
6912
7168
|
}
|
|
6913
7169
|
async function snapshotFile(source, destination) {
|
|
6914
7170
|
if (await regular(source))
|
|
@@ -6917,8 +7173,8 @@ async function snapshotFile(source, destination) {
|
|
|
6917
7173
|
async function snapshotPolicies(source, destination) {
|
|
6918
7174
|
let entries;
|
|
6919
7175
|
try {
|
|
6920
|
-
const
|
|
6921
|
-
if (!
|
|
7176
|
+
const stat = await lstat2(source);
|
|
7177
|
+
if (!stat.isDirectory() || stat.isSymbolicLink())
|
|
6922
7178
|
throw new Error("Unsupported Gemini policy directory");
|
|
6923
7179
|
entries = await readdir2(source, { withFileTypes: true });
|
|
6924
7180
|
} catch (error) {
|
|
@@ -6993,7 +7249,7 @@ async function prepareGemini(input) {
|
|
|
6993
7249
|
}
|
|
6994
7250
|
const defaults = join5(input.stateDir, "gemini-system-defaults.json"), system = join5(input.stateDir, "gemini-system.json"), user = join5(dir, "settings.json");
|
|
6995
7251
|
const modelPolicy = compileGeminiModelPolicy(input.model, input.models, input.compiledPolicy ?? compileModelPolicy(input.model, input.models, input.modelPolicy));
|
|
6996
|
-
const modelDefinitions = { ...Object.fromEntries(nativeModels.map((
|
|
7252
|
+
const modelDefinitions = { ...Object.fromEntries(nativeModels.map((id) => [id, { isVisible: false }])), ...modelPolicy.modelConfigs.modelDefinitions };
|
|
6997
7253
|
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 } };
|
|
6998
7254
|
for (const [path, value] of [[defaults, original.defaults], [user, original.user], [system, enforced]]) {
|
|
6999
7255
|
const text = JSON.stringify(value, null, 2) + `
|
|
@@ -7033,13 +7289,13 @@ async function prepareGemini(input) {
|
|
|
7033
7289
|
}
|
|
7034
7290
|
|
|
7035
7291
|
// src/gemini-bridge.ts
|
|
7036
|
-
import { createHash as
|
|
7292
|
+
import { createHash as createHash5, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
7037
7293
|
function geminiBridge(input, timing = {}) {
|
|
7038
|
-
const token = crypto.randomUUID() + crypto.randomUUID(), digest = (value) =>
|
|
7294
|
+
const token = crypto.randomUUID() + crypto.randomUUID(), digest = (value) => createHash5("sha256").update(value).digest(), expected = digest(token);
|
|
7039
7295
|
const models = new Set(input.models.map((model) => model.id));
|
|
7040
7296
|
let closing = false, stopped;
|
|
7041
7297
|
const active = new Set;
|
|
7042
|
-
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request,
|
|
7298
|
+
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server) {
|
|
7043
7299
|
const fail = (status, message) => Response.json({ error: { code: status, message } }, { status });
|
|
7044
7300
|
if (closing)
|
|
7045
7301
|
return fail(503, "Bridge is closing");
|
|
@@ -7076,17 +7332,17 @@ function geminiBridge(input, timing = {}) {
|
|
|
7076
7332
|
if (input.credential)
|
|
7077
7333
|
headers["x-goog-api-key"] = input.credential;
|
|
7078
7334
|
let complete;
|
|
7079
|
-
const
|
|
7080
|
-
complete =
|
|
7335
|
+
const record = { abort: new AbortController, done: new Promise((resolve) => {
|
|
7336
|
+
complete = resolve;
|
|
7081
7337
|
}) };
|
|
7082
|
-
const activity = createProviderRequest(request.signal,
|
|
7338
|
+
const activity = createProviderRequest(request.signal, record.abort.signal, timing);
|
|
7083
7339
|
const release = () => {
|
|
7084
7340
|
activity.finish();
|
|
7085
|
-
active.delete(
|
|
7341
|
+
active.delete(record);
|
|
7086
7342
|
complete();
|
|
7087
7343
|
};
|
|
7088
|
-
active.add(
|
|
7089
|
-
|
|
7344
|
+
active.add(record);
|
|
7345
|
+
server.timeout(request, 0);
|
|
7090
7346
|
try {
|
|
7091
7347
|
const response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
|
|
7092
7348
|
if (!response.ok) {
|
|
@@ -7100,8 +7356,8 @@ function geminiBridge(input, timing = {}) {
|
|
|
7100
7356
|
release();
|
|
7101
7357
|
return new Response(null, { status: response.status });
|
|
7102
7358
|
}
|
|
7103
|
-
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort:
|
|
7104
|
-
|
|
7359
|
+
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record.abort, closing: () => closing, release, activity });
|
|
7360
|
+
record.cancel = cancel;
|
|
7105
7361
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
7106
7362
|
} catch {
|
|
7107
7363
|
release();
|
|
@@ -7143,7 +7399,7 @@ function exactModels(input) {
|
|
|
7143
7399
|
throw new Error(`Native model policy role ${role} is empty.`);
|
|
7144
7400
|
return result;
|
|
7145
7401
|
}
|
|
7146
|
-
var unsupported = (...
|
|
7402
|
+
var unsupported = (...roles) => roles;
|
|
7147
7403
|
function compileNativeModelPolicy(input) {
|
|
7148
7404
|
const models = exactModels(input);
|
|
7149
7405
|
const env = {};
|
|
@@ -7265,13 +7521,13 @@ function normalizeCodexDelegation(body) {
|
|
|
7265
7521
|
|
|
7266
7522
|
// src/opencode.ts
|
|
7267
7523
|
function rememberGeminiTool(part, state) {
|
|
7268
|
-
const
|
|
7524
|
+
const id = `call_${crypto.randomUUID()}`;
|
|
7269
7525
|
if (typeof part.thoughtSignature === "string") {
|
|
7270
7526
|
if (part.thoughtSignature.length > 65536 || state.size >= 2000)
|
|
7271
7527
|
throw new Fault(502, "opencode_signature_limit", "Gemini tool continuation metadata exceeded the launch limit.");
|
|
7272
|
-
state.set(
|
|
7528
|
+
state.set(id, part.thoughtSignature);
|
|
7273
7529
|
}
|
|
7274
|
-
return
|
|
7530
|
+
return id;
|
|
7275
7531
|
}
|
|
7276
7532
|
function openCodeLane(baseUrl) {
|
|
7277
7533
|
const url = new URL(baseUrl);
|
|
@@ -7369,11 +7625,11 @@ function toChat(body) {
|
|
|
7369
7625
|
messages.push({ role: "assistant", content: content.length ? content : null, ...calls.length ? { tool_calls: calls } : {}, ...thinking ? { reasoning_content: thinking } : {} });
|
|
7370
7626
|
} else {
|
|
7371
7627
|
const images = [];
|
|
7372
|
-
for (const part of parts.filter((
|
|
7373
|
-
const
|
|
7374
|
-
messages.push({ role: "tool", tool_call_id: part.tool_use_id, content:
|
|
7375
|
-
if (
|
|
7376
|
-
images.push({ type: "text", text: `Images returned by tool call ${part.tool_use_id}:` }, ...
|
|
7628
|
+
for (const part of parts.filter((part) => part.type === "tool_result")) {
|
|
7629
|
+
const result = toolResult(part);
|
|
7630
|
+
messages.push({ role: "tool", tool_call_id: part.tool_use_id, content: result.text });
|
|
7631
|
+
if (result.images.length)
|
|
7632
|
+
images.push({ type: "text", text: `Images returned by tool call ${part.tool_use_id}:` }, ...result.images);
|
|
7377
7633
|
}
|
|
7378
7634
|
const content = chatContent([...images, ...parts.filter((part) => part.type !== "tool_result")]);
|
|
7379
7635
|
if (content.length)
|
|
@@ -7723,20 +7979,20 @@ function prepareOpenCodeMessages(baseUrl, body, suffix, credential, state = new
|
|
|
7723
7979
|
}
|
|
7724
7980
|
|
|
7725
7981
|
// src/inference-gateway.ts
|
|
7726
|
-
import { createHash as
|
|
7982
|
+
import { createHash as createHash6, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
7727
7983
|
var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
|
|
7728
7984
|
function createInferenceGateway(input, timing = {}) {
|
|
7729
7985
|
const token = crypto.randomUUID() + crypto.randomUUID();
|
|
7730
7986
|
const openCodeSession = crypto.randomUUID();
|
|
7731
7987
|
const openCodeState = new Map;
|
|
7732
|
-
const digest = (value) =>
|
|
7988
|
+
const digest = (value) => createHash6("sha256").update(value).digest();
|
|
7733
7989
|
const expected = digest(token), policy = input.compiledPolicy;
|
|
7734
7990
|
const known = new Set(input.models.map((m) => m.id));
|
|
7735
7991
|
const safeModel = (value) => typeof value === "string" && value !== input.credential && (known.has(value) || Object.hasOwn(policy.aliases, value)) ? value : "<unrecognized>";
|
|
7736
7992
|
const fail = (status, code, message) => Response.json({ error: { type: "switcher_model_policy", code, message: message ?? (code === "model_not_allowed" ? "This model is outside the launch policy. Select it with switcher launch --model or explicitly assign an allowed role model." : `Switcher inference gateway: ${code}.`) } }, { status });
|
|
7737
7993
|
let closing = false, stopped;
|
|
7738
7994
|
const active = new Set;
|
|
7739
|
-
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request,
|
|
7995
|
+
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server) {
|
|
7740
7996
|
if (closing)
|
|
7741
7997
|
return fail(503, "closing");
|
|
7742
7998
|
const credential = request.headers.get("x-goog-api-key") ?? request.headers.get("x-api-key") ?? request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
|
|
@@ -7808,17 +8064,17 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7808
8064
|
};
|
|
7809
8065
|
const abort = new AbortController;
|
|
7810
8066
|
let complete;
|
|
7811
|
-
const
|
|
8067
|
+
const record = { abort, done: new Promise((r) => complete = r) };
|
|
7812
8068
|
const activity = createProviderRequest(request.signal, abort.signal, timing);
|
|
7813
8069
|
const release = () => {
|
|
7814
8070
|
activity.finish();
|
|
7815
8071
|
flush();
|
|
7816
|
-
active.delete(
|
|
8072
|
+
active.delete(record);
|
|
7817
8073
|
complete();
|
|
7818
8074
|
};
|
|
7819
|
-
active.add(
|
|
8075
|
+
active.add(record);
|
|
7820
8076
|
const signal = activity.fetchOptions.signal;
|
|
7821
|
-
|
|
8077
|
+
server.timeout(request, 0);
|
|
7822
8078
|
const headers = { "content-type": "application/json" };
|
|
7823
8079
|
Object.assign(headers, openCodeHeaders(input.baseUrl, request.headers, body, openCodeSession));
|
|
7824
8080
|
if (input.credential) {
|
|
@@ -7853,8 +8109,8 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7853
8109
|
} else
|
|
7854
8110
|
payload.model = model;
|
|
7855
8111
|
const guidance = renderModelGuidance({ harness: input.harness, providerId: input.providerId, baseUrl: input.baseUrl, model, compiled: policy, catalogPath: input.catalogPath });
|
|
7856
|
-
const
|
|
7857
|
-
const outgoing = injectModelGuidance(input.protocol,
|
|
8112
|
+
const compatible = input.harness === "codex" && input.protocol === "openai-responses" && new URL(input.baseUrl).hostname !== "api.openai.com" ? normalizeCodexDelegation(payload) : payload;
|
|
8113
|
+
const outgoing = injectModelGuidance(input.protocol, compatible, guidance, match?.[2]);
|
|
7858
8114
|
const translated = input.protocol === "anthropic-messages" ? prepareOpenCodeMessages(input.baseUrl, outgoing, suffix, input.credential, openCodeState) : undefined;
|
|
7859
8115
|
const path = translated?.path ?? (gemini ? `/models/${encodeURIComponent(model)}:${match[2]}${url.search}` : suffix + (betaQuery ? "?beta=true" : ""));
|
|
7860
8116
|
const upstreamHeaders = { ...headers };
|
|
@@ -7941,7 +8197,7 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7941
8197
|
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort, closing: () => closing, release, activity, inspect, interrupted: (reason) => {
|
|
7942
8198
|
current.reason = reason;
|
|
7943
8199
|
} });
|
|
7944
|
-
|
|
8200
|
+
record.cancel = cancel;
|
|
7945
8201
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
7946
8202
|
} catch (error) {
|
|
7947
8203
|
if (error instanceof Fault)
|
|
@@ -7969,7 +8225,7 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7969
8225
|
import { mkdir as mkdir5, readFile as readFile2, realpath as realpath3, stat as stat4, writeFile as writeFile4 } from "fs/promises";
|
|
7970
8226
|
import { dirname as dirname4, isAbsolute as isAbsolute6, join as join6, resolve as resolve5 } from "path";
|
|
7971
8227
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
7972
|
-
import { createHash as
|
|
8228
|
+
import { createHash as createHash7 } from "crypto";
|
|
7973
8229
|
var dict = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
7974
8230
|
var model = (v) => JSON.stringify(v);
|
|
7975
8231
|
var codexRoutingKeys = new Set(["model", "model_provider", "model_providers", "model_catalog_json", "base_url", "wire_api", "env_key", "env_http_headers", "http_headers", "auth_command", "include"]);
|
|
@@ -8008,13 +8264,13 @@ function codexAgentsFromEffectiveConfig(config, trustedProject = true, baseDir)
|
|
|
8008
8264
|
function reject(key) {
|
|
8009
8265
|
throw new Error(`Codex policy cannot preserve ${key}; provider, transport, and include configuration are launch-owned.`);
|
|
8010
8266
|
}
|
|
8011
|
-
function cloneAgentConfig(value,
|
|
8267
|
+
function cloneAgentConfig(value, selectedModel, provider) {
|
|
8012
8268
|
const out = {};
|
|
8013
8269
|
for (const [key, item] of Object.entries(value)) {
|
|
8014
8270
|
if (codexTransportKeys.has(key) || key === "include" || key === "model_providers")
|
|
8015
8271
|
reject(key);
|
|
8016
8272
|
if (key === "model") {
|
|
8017
|
-
out.model =
|
|
8273
|
+
out.model = selectedModel;
|
|
8018
8274
|
continue;
|
|
8019
8275
|
}
|
|
8020
8276
|
if (key === "model_provider" || key === "provider") {
|
|
@@ -8025,7 +8281,7 @@ function cloneAgentConfig(value, selectedModel2, provider) {
|
|
|
8025
8281
|
reject(key);
|
|
8026
8282
|
out[key] = scanNested(item, key);
|
|
8027
8283
|
}
|
|
8028
|
-
out.model =
|
|
8284
|
+
out.model = selectedModel;
|
|
8029
8285
|
out.model_provider = provider;
|
|
8030
8286
|
return out;
|
|
8031
8287
|
}
|
|
@@ -8050,9 +8306,9 @@ function compileCodexModelPolicy(input) {
|
|
|
8050
8306
|
const policy = modelPolicySchema.parse(input.policy ?? {});
|
|
8051
8307
|
const subagentModel = policy.roles?.subagent ?? input.model;
|
|
8052
8308
|
const reviewModel = policy.roles?.review ?? input.model;
|
|
8053
|
-
const
|
|
8054
|
-
if (
|
|
8055
|
-
throw new Error(`Codex does not expose role controls for: ${
|
|
8309
|
+
const unsupported = ["fast", "planning", "summary", "compaction", "weak", "editor"].filter((role) => policy.roles?.[role] !== undefined && policy.roles?.[role] !== input.model);
|
|
8310
|
+
if (unsupported.length)
|
|
8311
|
+
throw new Error(`Codex does not expose role controls for: ${unsupported.join(", ")}.`);
|
|
8056
8312
|
const agents = [];
|
|
8057
8313
|
const ignoredUntrustedAgents = [];
|
|
8058
8314
|
for (const [name, definition] of Object.entries(input.agents ?? {})) {
|
|
@@ -8115,7 +8371,7 @@ async function writeCodexAgentOverrides(result, stateDir) {
|
|
|
8115
8371
|
await mkdir5(root, { recursive: true });
|
|
8116
8372
|
const paths = {};
|
|
8117
8373
|
for (const agent of result.agents) {
|
|
8118
|
-
const digest =
|
|
8374
|
+
const digest = createHash7("sha256").update(agent.name).digest("hex").slice(0, 16);
|
|
8119
8375
|
const path = join6(root, `agent-${digest}.toml`);
|
|
8120
8376
|
await writeFile4(path, renderCodexAgentToml(agent.config), { encoding: "utf8", mode: 384, flag: "wx" });
|
|
8121
8377
|
paths[agent.name] = path;
|
|
@@ -8236,7 +8492,7 @@ async function readCodexAgentConfig(path) {
|
|
|
8236
8492
|
import { access as access3, mkdir as mkdir10, readFile as readFile4, readdir as readdir4, writeFile as writeFile10, rm as rm2 } from "fs/promises";
|
|
8237
8493
|
import { basename as basename2, dirname as dirname7, join as join12, isAbsolute as isAbsolute11, resolve as resolve8 } from "path";
|
|
8238
8494
|
import { homedir as homedir7, tmpdir } from "os";
|
|
8239
|
-
import { createHash as
|
|
8495
|
+
import { createHash as createHash9, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual5 } from "crypto";
|
|
8240
8496
|
import { execFile as execFile2 } from "child_process";
|
|
8241
8497
|
import { promisify as promisify2 } from "util";
|
|
8242
8498
|
import { createConnection } from "net";
|
|
@@ -8252,8 +8508,8 @@ var object3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
|
8252
8508
|
async function data(path) {
|
|
8253
8509
|
let text;
|
|
8254
8510
|
try {
|
|
8255
|
-
const
|
|
8256
|
-
if (!
|
|
8511
|
+
const stat = await lstat3(path);
|
|
8512
|
+
if (!stat.isFile() || stat.size > 1024 * 1024)
|
|
8257
8513
|
throw new Error("unsupported");
|
|
8258
8514
|
text = await readFile3(path, "utf8");
|
|
8259
8515
|
} catch (error) {
|
|
@@ -8339,11 +8595,11 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
8339
8595
|
}
|
|
8340
8596
|
effective = { ...effective, ...normalized };
|
|
8341
8597
|
}
|
|
8342
|
-
const
|
|
8343
|
-
if (
|
|
8344
|
-
if (!Array.isArray(
|
|
8598
|
+
const settings = await data(join7(root, ".aider.model.settings.yml"));
|
|
8599
|
+
if (settings !== undefined) {
|
|
8600
|
+
if (!Array.isArray(settings))
|
|
8345
8601
|
throw new Error("Aider model settings must be a list.");
|
|
8346
|
-
for (const entry of
|
|
8602
|
+
for (const entry of settings)
|
|
8347
8603
|
if (!object3(entry) || entry.extra_params !== undefined && (!object3(entry.extra_params) || Object.keys(entry.extra_params).some((key) => !safeParameters.has(key))))
|
|
8348
8604
|
throw new Error(`Aider custom transport or callback model settings cannot be preserved safely: ${join7(root, ".aider.model.settings.yml")}`);
|
|
8349
8605
|
}
|
|
@@ -8362,12 +8618,12 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
8362
8618
|
effective.read = typeof effective.read === "string" ? expandHome(effective.read, home) : effective.read.map((path) => expandHome(path, home));
|
|
8363
8619
|
return effective;
|
|
8364
8620
|
}
|
|
8365
|
-
function aiderModelName(protocol,
|
|
8366
|
-
return `${protocol === "anthropic-messages" ? "anthropic" : protocol === "openai-responses" ? "openai/responses" : "openai"}/${
|
|
8621
|
+
function aiderModelName(protocol, id) {
|
|
8622
|
+
return `${protocol === "anthropic-messages" ? "anthropic" : protocol === "openai-responses" ? "openai/responses" : "openai"}/${id}`;
|
|
8367
8623
|
}
|
|
8368
8624
|
async function historyFile(path) {
|
|
8369
|
-
const
|
|
8370
|
-
if (!
|
|
8625
|
+
const stat = await lstat3(path);
|
|
8626
|
+
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 64 * 1024 * 1024 || process.platform !== "win32" && ((stat.mode & 63) !== 0 || stat.uid !== process.getuid?.()))
|
|
8371
8627
|
throw new Error("Aider history must be an owner-only regular file smaller than 64 MiB.");
|
|
8372
8628
|
}
|
|
8373
8629
|
async function prepareAider(input) {
|
|
@@ -8376,9 +8632,9 @@ async function prepareAider(input) {
|
|
|
8376
8632
|
if (input.protocol === "openai-responses" && input.models.some((m) => m.id.includes("responses/")))
|
|
8377
8633
|
throw new Error("Aider/LiteLLM removes responses/ segments from Responses model names; this catalog cannot be mapped exactly.");
|
|
8378
8634
|
const parsed = aiderArguments(input.args ?? []), global = await validateAiderConfiguration(input.cwd, input.args);
|
|
8379
|
-
const
|
|
8380
|
-
if (
|
|
8381
|
-
const files = parsed.args.splice(
|
|
8635
|
+
const literal = parsed.args.indexOf("--");
|
|
8636
|
+
if (literal >= 0) {
|
|
8637
|
+
const files = parsed.args.splice(literal).slice(1);
|
|
8382
8638
|
parsed.args.push(...files.map((path) => resolve6(input.cwd, path)));
|
|
8383
8639
|
}
|
|
8384
8640
|
const sourceHome = process.env.HOME ?? homedir5();
|
|
@@ -8399,7 +8655,7 @@ async function prepareAider(input) {
|
|
|
8399
8655
|
`).join(""), { mode: 384, flag: "wx" });
|
|
8400
8656
|
const sessions = input.sessionDir ?? join7(input.stateDir, "sessions");
|
|
8401
8657
|
await privateDirectory(sessions);
|
|
8402
|
-
const
|
|
8658
|
+
const id = crypto.randomUUID(), history = join7(sessions, `${id}.chat.md`), inputHistory = join7(sessions, `${id}.input`);
|
|
8403
8659
|
if (parsed.restore) {
|
|
8404
8660
|
const latest = join7(sessions, "latest.json");
|
|
8405
8661
|
await historyFile(latest).catch(() => {
|
|
@@ -8415,12 +8671,12 @@ async function prepareAider(input) {
|
|
|
8415
8671
|
await writeFile5(history, "", { mode: 384, flag: "wx" });
|
|
8416
8672
|
const originalHistoryLength = (await readFile3(history, "utf8")).length;
|
|
8417
8673
|
await writeFile5(inputHistory, "", { mode: 384, flag: "wx" });
|
|
8418
|
-
const
|
|
8674
|
+
const model = aiderModelName(input.protocol, input.model);
|
|
8419
8675
|
const weakModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.weak ?? input.model), editorModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.editor ?? input.model);
|
|
8420
8676
|
const extra = { api_base: input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl, api_key: `os.environ/${KEY2}` };
|
|
8421
|
-
const
|
|
8677
|
+
const settings = 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");
|
|
8422
8678
|
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 }));
|
|
8423
|
-
await writeFile5(
|
|
8679
|
+
await writeFile5(settings, JSON.stringify([...definitions, { name: "aider/extra_params", extra_params: extra }]), { mode: 384, flag: "wx" });
|
|
8424
8680
|
await writeFile5(metadata, JSON.stringify(Object.fromEntries(input.models.map((m) => [aiderModelName(input.protocol, m.id), {
|
|
8425
8681
|
...m.contextWindow ? { max_input_tokens: m.contextWindow } : {},
|
|
8426
8682
|
...m.maxOutputTokens ? { max_output_tokens: m.maxOutputTokens, max_tokens: m.maxOutputTokens } : {},
|
|
@@ -8430,15 +8686,15 @@ async function prepareAider(input) {
|
|
|
8430
8686
|
}]))), { mode: 384, flag: "wx" });
|
|
8431
8687
|
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(" "));
|
|
8432
8688
|
const preserved = Object.fromEntries(Object.entries(global).filter(([key]) => !ignored.has(key) && !startup.includes(key)));
|
|
8433
|
-
await writeFile5(config, JSON.stringify({ ...preserved, model
|
|
8689
|
+
await writeFile5(config, JSON.stringify({ ...preserved, model, "weak-model": weakModel, "editor-model": editorModel, "model-settings-file": settings, "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" });
|
|
8434
8690
|
await writeFile5(empty, "", { mode: 384, flag: "wx" });
|
|
8435
|
-
const aliases = ["--alias", `switcher-${
|
|
8691
|
+
const aliases = ["--alias", `switcher-${id}:${model}`];
|
|
8436
8692
|
let cleaned = false;
|
|
8437
8693
|
return {
|
|
8438
8694
|
executable: input.executable ?? "aider",
|
|
8439
|
-
args: ["--config", config, "--model",
|
|
8695
|
+
args: ["--config", config, "--model", model, "--weak-model", weakModel, "--editor-model", editorModel, "--set-env", "PYTHON_DOTENV_DISABLED=1", "--api-key", "SWITCHER_UNUSED=unused", ...aliases, ...parsed.args],
|
|
8440
8696
|
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 },
|
|
8441
|
-
configPaths: [config,
|
|
8697
|
+
configPaths: [config, settings, metadata, empty, gitConfig],
|
|
8442
8698
|
warnings: [
|
|
8443
8699
|
...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."] : [],
|
|
8444
8700
|
"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.",
|
|
@@ -8453,8 +8709,8 @@ async function prepareAider(input) {
|
|
|
8453
8709
|
await historyFile(history);
|
|
8454
8710
|
if (!/^#### /m.test((await readFile3(history, "utf8")).slice(originalHistoryLength)))
|
|
8455
8711
|
return;
|
|
8456
|
-
const pending = join7(sessions, `${
|
|
8457
|
-
await writeFile5(pending, JSON.stringify({ id
|
|
8712
|
+
const pending = join7(sessions, `${id}.latest.json`);
|
|
8713
|
+
await writeFile5(pending, JSON.stringify({ id }), { mode: 384, flag: "wx" });
|
|
8458
8714
|
await rename(pending, join7(sessions, "latest.json"));
|
|
8459
8715
|
}
|
|
8460
8716
|
};
|
|
@@ -8462,7 +8718,7 @@ async function prepareAider(input) {
|
|
|
8462
8718
|
|
|
8463
8719
|
// src/grok-args.ts
|
|
8464
8720
|
function validateGrokResume(args) {
|
|
8465
|
-
const
|
|
8721
|
+
const values = new Set([
|
|
8466
8722
|
"--cwd",
|
|
8467
8723
|
"--leader-socket",
|
|
8468
8724
|
"--debug-file",
|
|
@@ -8514,7 +8770,7 @@ function validateGrokResume(args) {
|
|
|
8514
8770
|
if (prompts.has(flag))
|
|
8515
8771
|
headless = true;
|
|
8516
8772
|
const optionalValue = ["--resume", "--worktree", "--local-workspace"].includes(flag);
|
|
8517
|
-
if (!attached && (
|
|
8773
|
+
if (!attached && (values.has(flag) || prompts.has(flag) || flag === "--load" || optionalValue && args[i + 1] !== undefined && !args[i + 1].startsWith("-")))
|
|
8518
8774
|
i++;
|
|
8519
8775
|
} else if (arg.startsWith("-") && arg.length > 1) {
|
|
8520
8776
|
for (let j = 1;j < arg.length; j++) {
|
|
@@ -8550,17 +8806,17 @@ var PROTOCOL = {
|
|
|
8550
8806
|
"openai-responses": { protocol: "openai-responses", client: "openai", providerId: "openai-native", authStyle: "bearer" },
|
|
8551
8807
|
"openai-chat": { protocol: "openai-chat", client: "openai-compatible", providerId: "openai-compatible", authStyle: "bearer" }
|
|
8552
8808
|
};
|
|
8553
|
-
function modelEntry(
|
|
8809
|
+
function modelEntry(model, protocol) {
|
|
8554
8810
|
return {
|
|
8555
|
-
id:
|
|
8556
|
-
name:
|
|
8557
|
-
...
|
|
8558
|
-
...
|
|
8811
|
+
id: model.id,
|
|
8812
|
+
name: model.name,
|
|
8813
|
+
...model.contextWindow ? { contextWindow: model.contextWindow } : {},
|
|
8814
|
+
...model.maxOutputTokens ? { maxTokens: model.maxOutputTokens } : {},
|
|
8559
8815
|
capabilities: ["streaming", "tools"],
|
|
8560
8816
|
...protocol === "openai-responses" ? { apiFormat: "openai-responses" } : {},
|
|
8561
8817
|
modalities: {
|
|
8562
|
-
input:
|
|
8563
|
-
output:
|
|
8818
|
+
input: model.inputModalities?.filter((modality) => modality === "text" || modality === "image") ?? ["text"],
|
|
8819
|
+
output: model.outputModalities?.filter((modality) => modality === "text") ?? ["text"]
|
|
8564
8820
|
}
|
|
8565
8821
|
};
|
|
8566
8822
|
}
|
|
@@ -8573,12 +8829,12 @@ async function prepareClineLaunch(input) {
|
|
|
8573
8829
|
if (input.protocol === "gemini-generate-content")
|
|
8574
8830
|
throw new Error("Cline does not support the Gemini generateContent protocol.");
|
|
8575
8831
|
const requestedProtocol = input.protocol;
|
|
8576
|
-
const selected = input.models.find((
|
|
8832
|
+
const selected = input.models.find((model) => model.id === input.model);
|
|
8577
8833
|
if (!selected)
|
|
8578
8834
|
throw new Error("Selected model is missing from the launch catalog.");
|
|
8579
|
-
if (input.models.some((
|
|
8835
|
+
if (input.models.some((model) => !codingEligible(model)))
|
|
8580
8836
|
throw new Error("Launch catalog contains a model explicitly ineligible for coding.");
|
|
8581
|
-
if (new Set(input.models.map((
|
|
8837
|
+
if (new Set(input.models.map((model) => model.id.toLowerCase())).size !== input.models.length)
|
|
8582
8838
|
throw new Error("Cline cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
8583
8839
|
const mapping = PROTOCOL[input.protocol];
|
|
8584
8840
|
if ((input.authStyle ?? "bearer") !== mapping.authStyle)
|
|
@@ -8627,7 +8883,7 @@ async function prepareClineLaunch(input) {
|
|
|
8627
8883
|
protocol: mapping.protocol,
|
|
8628
8884
|
client: mapping.client
|
|
8629
8885
|
},
|
|
8630
|
-
models: Object.fromEntries(input.models.map((
|
|
8886
|
+
models: Object.fromEntries(input.models.map((model) => [model.id, modelEntry(model, requestedProtocol)]))
|
|
8631
8887
|
}
|
|
8632
8888
|
}
|
|
8633
8889
|
});
|
|
@@ -8714,8 +8970,8 @@ function permissions(value, path, home) {
|
|
|
8714
8970
|
}
|
|
8715
8971
|
if (own2(value, "permission")) {
|
|
8716
8972
|
const legacy = typeof value.permission === "string" ? { "*": value.permission } : record2(value.permission, path, "permission");
|
|
8717
|
-
for (const [name,
|
|
8718
|
-
const entries = typeof
|
|
8973
|
+
for (const [name, permission] of Object.entries(legacy)) {
|
|
8974
|
+
const entries = typeof permission === "string" ? { "*": permission } : record2(permission, path, "permission");
|
|
8719
8975
|
for (const [resource, item] of Object.entries(entries)) {
|
|
8720
8976
|
const parsed = effect.safeParse(item);
|
|
8721
8977
|
if (!parsed.success)
|
|
@@ -8873,9 +9129,9 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
8873
9129
|
seen.add(canonical);
|
|
8874
9130
|
documents.push({ path, value: jsonc2(text, path) });
|
|
8875
9131
|
}
|
|
8876
|
-
async function agentsDirectory(
|
|
9132
|
+
async function agentsDirectory(directory) {
|
|
8877
9133
|
for (const source of ["agent", "agents", "mode", "modes"]) {
|
|
8878
|
-
const base = join9(
|
|
9134
|
+
const base = join9(directory, source), entries = [];
|
|
8879
9135
|
const visited = new Set;
|
|
8880
9136
|
let examined = 0;
|
|
8881
9137
|
async function walk(dir, depth) {
|
|
@@ -8907,22 +9163,22 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
8907
9163
|
for (const path of entries.sort()) {
|
|
8908
9164
|
const text = await read(path, false);
|
|
8909
9165
|
const match = text.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
|
|
8910
|
-
let
|
|
9166
|
+
let data = {};
|
|
8911
9167
|
if (match) {
|
|
8912
9168
|
const parsed = parseDocument3(match[1], { uniqueKeys: true });
|
|
8913
9169
|
if (parsed.errors.length)
|
|
8914
9170
|
invalid2(path, "agent YAML frontmatter");
|
|
8915
9171
|
try {
|
|
8916
|
-
|
|
9172
|
+
data = record2(parsed.toJS({ maxAliasCount: 0 }), path, "agent YAML frontmatter");
|
|
8917
9173
|
} catch {
|
|
8918
9174
|
invalid2(path, "agent YAML frontmatter");
|
|
8919
9175
|
}
|
|
8920
9176
|
}
|
|
8921
9177
|
const body = text.slice(match?.[0].length ?? 0).trim();
|
|
8922
9178
|
const nativeKeys = new Set(["model", "request", "system", "description", "mode", "hidden", "color", "steps", "disabled", "permissions", "variant"]);
|
|
8923
|
-
const legacy = Object.keys(
|
|
9179
|
+
const legacy = Object.keys(data).some((key) => !nativeKeys.has(key));
|
|
8924
9180
|
const name = relative4(base, path).replaceAll("\\", "/").replace(/\.md$/, "");
|
|
8925
|
-
const value = { ...
|
|
9181
|
+
const value = { ...data, [legacy ? "prompt" : "system"]: body, ...source === "mode" || source === "modes" ? { mode: "primary" } : {} };
|
|
8926
9182
|
documents.push({ path, value: { [legacy ? "agent" : "agents"]: { [name]: value }, __literalAgentBody: true } });
|
|
8927
9183
|
}
|
|
8928
9184
|
}
|
|
@@ -9103,11 +9359,11 @@ var API = {
|
|
|
9103
9359
|
"openai-chat": "openai-completions"
|
|
9104
9360
|
};
|
|
9105
9361
|
function selectedModels(input) {
|
|
9106
|
-
if (!input.models.length || !input.models.some((
|
|
9362
|
+
if (!input.models.length || !input.models.some((model) => model.id === input.model))
|
|
9107
9363
|
throw new Error("Selected model is missing from the launch catalog.");
|
|
9108
|
-
if (input.models.some((
|
|
9364
|
+
if (input.models.some((model) => !codingEligible(model)))
|
|
9109
9365
|
throw new Error("Launch catalog contains a model explicitly ineligible for coding.");
|
|
9110
|
-
if (new Set(input.models.map((
|
|
9366
|
+
if (new Set(input.models.map((model) => model.id.toLowerCase())).size !== input.models.length)
|
|
9111
9367
|
throw new Error("OMP cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
9112
9368
|
return input.models;
|
|
9113
9369
|
}
|
|
@@ -9125,14 +9381,14 @@ async function prepareOmpLaunch(input) {
|
|
|
9125
9381
|
await mkdir8(agentDir, { recursive: true, mode: 448 });
|
|
9126
9382
|
await mkdir8(sessionDir, { recursive: true, mode: 448 });
|
|
9127
9383
|
const api = API[input.protocol];
|
|
9128
|
-
const modelDefinitions = models.map((
|
|
9129
|
-
id:
|
|
9130
|
-
name:
|
|
9384
|
+
const modelDefinitions = models.map((model) => ({
|
|
9385
|
+
id: model.id,
|
|
9386
|
+
name: model.name,
|
|
9131
9387
|
api,
|
|
9132
|
-
input: (
|
|
9133
|
-
supportsTools:
|
|
9134
|
-
...
|
|
9135
|
-
...
|
|
9388
|
+
input: (model.inputModalities ?? ["text"]).filter((value) => value === "text" || value === "image").length ? (model.inputModalities ?? ["text"]).filter((value) => value === "text" || value === "image") : ["text"],
|
|
9389
|
+
supportsTools: model.supportedParameters?.includes("tools") ?? true,
|
|
9390
|
+
...model.contextWindow ? { contextWindow: model.contextWindow } : {},
|
|
9391
|
+
...model.maxOutputTokens ? { maxTokens: model.maxOutputTokens } : {}
|
|
9136
9392
|
}));
|
|
9137
9393
|
const provider = {
|
|
9138
9394
|
name: "Switcher",
|
|
@@ -9192,9 +9448,9 @@ var tasks = {
|
|
|
9192
9448
|
session_search: "fast",
|
|
9193
9449
|
web_extract: "fast"
|
|
9194
9450
|
};
|
|
9195
|
-
function model2(value,
|
|
9451
|
+
function model2(value, label) {
|
|
9196
9452
|
if (typeof value !== "string" || value.length < 1 || value.length > 300 || /[\u0000-\u001f\u007f]/.test(value))
|
|
9197
|
-
throw new Fault(400, "invalid_model_policy", `${
|
|
9453
|
+
throw new Fault(400, "invalid_model_policy", `${label} is invalid.`);
|
|
9198
9454
|
return value;
|
|
9199
9455
|
}
|
|
9200
9456
|
function endpoint2(value) {
|
|
@@ -9211,12 +9467,12 @@ function endpoint2(value) {
|
|
|
9211
9467
|
throw new Fault(400, "invalid_url", "Hermes auxiliary endpoint must be HTTPS or loopback HTTP without credentials.");
|
|
9212
9468
|
return url.href.replace(/\/+$/, "");
|
|
9213
9469
|
}
|
|
9214
|
-
function compileHermesModelPolicy(currentModel,
|
|
9470
|
+
function compileHermesModelPolicy(currentModel, roles, baseUrl, apiMode = "chat_completions") {
|
|
9215
9471
|
const selected = model2(currentModel, "model");
|
|
9216
|
-
if (
|
|
9472
|
+
if (roles.editor && roles.editor !== selected)
|
|
9217
9473
|
throw new Fault(422, "unsupported_role", "Hermes does not expose a separate editor model.");
|
|
9218
9474
|
const endpointUrl = endpoint2(baseUrl);
|
|
9219
|
-
const chosen = (role) => model2(
|
|
9475
|
+
const chosen = (role) => model2(roles[role] ?? selected, `roles.${role}`);
|
|
9220
9476
|
const auxiliary = Object.create(null);
|
|
9221
9477
|
for (const [task, role] of Object.entries(tasks))
|
|
9222
9478
|
auxiliary[task] = { api_mode: apiMode, provider: "custom", model: chosen(role), base_url: endpointUrl, api_key_env: "SWITCHER_HERMES_AUX_API_KEY", fallback_chain: [] };
|
|
@@ -9224,7 +9480,7 @@ function compileHermesModelPolicy(currentModel, roles2, baseUrl, apiMode = "chat
|
|
|
9224
9480
|
}
|
|
9225
9481
|
|
|
9226
9482
|
// src/hermes-backend.ts
|
|
9227
|
-
import { createHash as
|
|
9483
|
+
import { createHash as createHash8, timingSafeEqual as timingSafeEqual4 } from "crypto";
|
|
9228
9484
|
import { mkdir as mkdir9, symlink as symlink2, writeFile as writeFile9 } from "fs/promises";
|
|
9229
9485
|
import { isAbsolute as isAbsolute10, join as join11 } from "path";
|
|
9230
9486
|
var hermesApiMode = {
|
|
@@ -9241,7 +9497,7 @@ var apiMode = hermesApiMode;
|
|
|
9241
9497
|
function createHermesBridge(input, timing = {}) {
|
|
9242
9498
|
const protocol = input.protocol;
|
|
9243
9499
|
const token = crypto.randomUUID() + crypto.randomUUID();
|
|
9244
|
-
const modelIds = new Set(input.models.map((
|
|
9500
|
+
const modelIds = new Set(input.models.map((model) => model.id));
|
|
9245
9501
|
const active = new Set;
|
|
9246
9502
|
let closing = false;
|
|
9247
9503
|
let server;
|
|
@@ -9251,27 +9507,27 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9251
9507
|
port: 0,
|
|
9252
9508
|
maxRequestBodySize: 4 * 1024 * 1024,
|
|
9253
9509
|
idleTimeout: 255,
|
|
9254
|
-
async fetch(request,
|
|
9510
|
+
async fetch(request, server) {
|
|
9255
9511
|
if (closing)
|
|
9256
9512
|
return Response.json({ error: { message: "Hermes bridge is closing" } }, { status: 503 });
|
|
9257
9513
|
const nativeHeader = protocol === "anthropic-messages" ? "x-api-key" : "authorization";
|
|
9258
9514
|
const nativeCredential = request.headers.get(nativeHeader) ?? "";
|
|
9259
9515
|
const expectedCredential = nativeHeader === "x-api-key" ? token : `Bearer ${token}`;
|
|
9260
|
-
const actual =
|
|
9261
|
-
const expectedHeader =
|
|
9516
|
+
const actual = createHash8("sha256").update(nativeCredential).digest();
|
|
9517
|
+
const expectedHeader = createHash8("sha256").update(expectedCredential).digest();
|
|
9262
9518
|
if (actual.length !== expectedHeader.length || !timingSafeEqual4(actual, expectedHeader))
|
|
9263
9519
|
return Response.json({ error: { message: "Unauthorized" } }, { status: 401 });
|
|
9264
9520
|
const path = new URL(request.url).pathname;
|
|
9265
9521
|
if (request.method === "GET" && path === "/v1/models") {
|
|
9266
9522
|
return Response.json({
|
|
9267
9523
|
object: "list",
|
|
9268
|
-
data: input.models.map((
|
|
9269
|
-
id:
|
|
9524
|
+
data: input.models.map((model) => ({
|
|
9525
|
+
id: model.id,
|
|
9270
9526
|
object: "model",
|
|
9271
|
-
name:
|
|
9527
|
+
name: model.name,
|
|
9272
9528
|
owned_by: "switcher",
|
|
9273
|
-
context_window:
|
|
9274
|
-
max_output_tokens:
|
|
9529
|
+
context_window: model.contextWindow,
|
|
9530
|
+
max_output_tokens: model.maxOutputTokens
|
|
9275
9531
|
}))
|
|
9276
9532
|
});
|
|
9277
9533
|
}
|
|
@@ -9285,25 +9541,25 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9285
9541
|
}
|
|
9286
9542
|
if (!body || typeof body !== "object" || typeof body.model !== "string")
|
|
9287
9543
|
return Response.json({ error: { message: "A model is required" } }, { status: 400 });
|
|
9288
|
-
const
|
|
9289
|
-
if (!modelIds.has(
|
|
9544
|
+
const selectedModel = body.model;
|
|
9545
|
+
if (!modelIds.has(selectedModel))
|
|
9290
9546
|
return Response.json({ error: { message: "Model is outside the Switcher launch catalog" } }, { status: 403 });
|
|
9291
9547
|
const abortController = new AbortController;
|
|
9292
9548
|
let complete;
|
|
9293
|
-
const
|
|
9549
|
+
const record = {
|
|
9294
9550
|
abort: abortController,
|
|
9295
|
-
done: new Promise((
|
|
9296
|
-
complete =
|
|
9551
|
+
done: new Promise((resolve) => {
|
|
9552
|
+
complete = resolve;
|
|
9297
9553
|
})
|
|
9298
9554
|
};
|
|
9299
9555
|
const activity = createProviderRequest(request.signal, abortController.signal, timing);
|
|
9300
9556
|
const release = () => {
|
|
9301
9557
|
activity.finish();
|
|
9302
|
-
active.delete(
|
|
9558
|
+
active.delete(record);
|
|
9303
9559
|
complete();
|
|
9304
9560
|
};
|
|
9305
|
-
active.add(
|
|
9306
|
-
|
|
9561
|
+
active.add(record);
|
|
9562
|
+
record.cancel = async () => {
|
|
9307
9563
|
abortController.abort();
|
|
9308
9564
|
release();
|
|
9309
9565
|
};
|
|
@@ -9318,7 +9574,7 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9318
9574
|
if (beta)
|
|
9319
9575
|
headers["anthropic-beta"] = beta;
|
|
9320
9576
|
}
|
|
9321
|
-
|
|
9577
|
+
server.timeout(request, 0);
|
|
9322
9578
|
try {
|
|
9323
9579
|
const upstream = await activity.run(() => fetch(`${input.baseUrl}${routePath[protocol].replace(/^\/v1/, "")}`, {
|
|
9324
9580
|
method: "POST",
|
|
@@ -9339,7 +9595,7 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9339
9595
|
return new Response(null, { status: upstream.status });
|
|
9340
9596
|
}
|
|
9341
9597
|
const { stream, cancel } = proxyProviderStream({ response: upstream, protocol: input.protocol, requestSignal: request.signal, abort: abortController, closing: () => closing, release, activity });
|
|
9342
|
-
|
|
9598
|
+
record.cancel = cancel;
|
|
9343
9599
|
return new Response(stream, {
|
|
9344
9600
|
status: upstream.status,
|
|
9345
9601
|
headers: {
|
|
@@ -9359,11 +9615,11 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9359
9615
|
cleanup: () => stopped ??= (async () => {
|
|
9360
9616
|
closing = true;
|
|
9361
9617
|
const pending = [...active];
|
|
9362
|
-
for (const
|
|
9363
|
-
|
|
9364
|
-
await Promise.allSettled(pending.map(async (
|
|
9365
|
-
await
|
|
9366
|
-
await
|
|
9618
|
+
for (const record of pending)
|
|
9619
|
+
record.abort.abort();
|
|
9620
|
+
await Promise.allSettled(pending.map(async (record) => {
|
|
9621
|
+
await record.cancel?.();
|
|
9622
|
+
await record.done;
|
|
9367
9623
|
}));
|
|
9368
9624
|
await server.stop(true);
|
|
9369
9625
|
})()
|
|
@@ -9374,9 +9630,9 @@ async function prepareHermesLaunch(input) {
|
|
|
9374
9630
|
throw new Error("Launch state and working directories must be absolute.");
|
|
9375
9631
|
if (input.protocol !== "anthropic-messages" && input.protocol !== "openai-responses" && input.protocol !== "openai-chat")
|
|
9376
9632
|
throw new Error("Hermes does not support this provider protocol.");
|
|
9377
|
-
if (!input.models.length || !input.models.some((
|
|
9633
|
+
if (!input.models.length || !input.models.some((model) => model.id === input.model))
|
|
9378
9634
|
throw new Error("Selected model is missing from the launch catalog.");
|
|
9379
|
-
if (new Set(input.models.map((
|
|
9635
|
+
if (new Set(input.models.map((model) => model.id.toLowerCase())).size !== input.models.length)
|
|
9380
9636
|
throw new Error("Hermes cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
9381
9637
|
if (input.credential && /[\r\n]/.test(input.credential))
|
|
9382
9638
|
throw new Error("Provider credential contains invalid header characters.");
|
|
@@ -9708,20 +9964,20 @@ function toolsPermission(value, path) {
|
|
|
9708
9964
|
const tools = policyRecord(value, path);
|
|
9709
9965
|
if (tools === undefined)
|
|
9710
9966
|
return;
|
|
9711
|
-
const
|
|
9967
|
+
const permission = {};
|
|
9712
9968
|
for (const [name, enabled] of Object.entries(tools)) {
|
|
9713
9969
|
if (typeof enabled !== "boolean")
|
|
9714
9970
|
throw new Error(`OpenCode tools policy at ${path}.${name} must be boolean.`);
|
|
9715
|
-
|
|
9971
|
+
permission[name === "write" || name === "edit" || name === "patch" ? "edit" : name] = enabled ? "allow" : "deny";
|
|
9716
9972
|
}
|
|
9717
|
-
return
|
|
9973
|
+
return permission;
|
|
9718
9974
|
}
|
|
9719
9975
|
function expandHomePattern(value) {
|
|
9720
9976
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
9721
9977
|
return value;
|
|
9722
|
-
const
|
|
9978
|
+
const record = value;
|
|
9723
9979
|
const output = {};
|
|
9724
|
-
for (const [key, item] of Object.entries(
|
|
9980
|
+
for (const [key, item] of Object.entries(record)) {
|
|
9725
9981
|
const expanded = key === "~" ? homedir7() : key.startsWith("~/") ? join12(homedir7(), key.slice(2)) : key;
|
|
9726
9982
|
output[expanded] = expandHomePattern(item);
|
|
9727
9983
|
}
|
|
@@ -9730,9 +9986,9 @@ function expandHomePattern(value) {
|
|
|
9730
9986
|
function policyWithExpandedPatterns(value) {
|
|
9731
9987
|
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
9732
9988
|
return value;
|
|
9733
|
-
const
|
|
9989
|
+
const record = value;
|
|
9734
9990
|
const output = {};
|
|
9735
|
-
for (const [key, item] of Object.entries(
|
|
9991
|
+
for (const [key, item] of Object.entries(record))
|
|
9736
9992
|
output[key] = typeof item === "object" && item !== null && !Array.isArray(item) ? expandHomePattern(item) : item;
|
|
9737
9993
|
return output;
|
|
9738
9994
|
}
|
|
@@ -9746,7 +10002,7 @@ function decodePolicy(text, file) {
|
|
|
9746
10002
|
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
|
|
9747
10003
|
throw new Error(`OpenCode config at ${file} must be an object.`);
|
|
9748
10004
|
const config = parsed;
|
|
9749
|
-
const
|
|
10005
|
+
const permission = policyWithExpandedPatterns(policyValue(config.permission, `${file}:permission`));
|
|
9750
10006
|
const toolsValue = policyRecord(config.tools, `${file}:tools`);
|
|
9751
10007
|
const tools = {};
|
|
9752
10008
|
for (const [name, value] of Object.entries(toolsValue ?? {})) {
|
|
@@ -9773,7 +10029,7 @@ function decodePolicy(text, file) {
|
|
|
9773
10029
|
if (merged !== undefined)
|
|
9774
10030
|
mode[name] = { permission: merged };
|
|
9775
10031
|
}
|
|
9776
|
-
return { ...
|
|
10032
|
+
return { ...permission !== undefined ? { permission } : {}, ...Object.keys(tools).length ? { tools } : {}, ...Object.keys(agent).length ? { agent } : {}, ...Object.keys(mode).length ? { mode } : {} };
|
|
9777
10033
|
}
|
|
9778
10034
|
async function readPolicyFile(file) {
|
|
9779
10035
|
let text;
|
|
@@ -9821,13 +10077,13 @@ async function readAgentPolicyFile(file, kind, root) {
|
|
|
9821
10077
|
throw new Error(`OpenCode ${kind} policy could not be parsed safely: ${file}`, { cause: error });
|
|
9822
10078
|
}
|
|
9823
10079
|
const frontmatter = policyRecord(parsed, `${file}:frontmatter`);
|
|
9824
|
-
const
|
|
10080
|
+
const permission = policyWithExpandedPatterns(policyValue(frontmatter?.permission, `${file}:permission`));
|
|
9825
10081
|
const toolPermission = toolsPermission(frontmatter?.tools, `${file}:tools`);
|
|
9826
|
-
const merged = mergePolicyValue(toolPermission,
|
|
10082
|
+
const merged = mergePolicyValue(toolPermission, permission);
|
|
9827
10083
|
const fields = nativeAgentFields(frontmatter, file);
|
|
9828
10084
|
fields.prompt = text.slice(match[0].length).trim();
|
|
9829
|
-
const
|
|
9830
|
-
return { name:
|
|
10085
|
+
const relative = file.slice(root.length + 1).replaceAll("\\", "/").replace(/\.md$/i, "");
|
|
10086
|
+
return { name: relative || basename2(file, ".md"), ...fields, ...merged !== undefined ? { permission: merged } : {} };
|
|
9831
10087
|
}
|
|
9832
10088
|
async function preservedOpenCodePolicy(cwd) {
|
|
9833
10089
|
const result = {};
|
|
@@ -9848,8 +10104,8 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
9848
10104
|
applyLayer(layer);
|
|
9849
10105
|
};
|
|
9850
10106
|
const applyText = (text, source) => applyLayer(decodePolicy(text, source));
|
|
9851
|
-
const applyMarkdown = async (
|
|
9852
|
-
for (const entry of await agentPolicyFiles(
|
|
10107
|
+
const applyMarkdown = async (dir, kind) => {
|
|
10108
|
+
for (const entry of await agentPolicyFiles(dir, kind)) {
|
|
9853
10109
|
const policy = await readAgentPolicyFile(entry.file, kind, entry.root);
|
|
9854
10110
|
if (!policy)
|
|
9855
10111
|
continue;
|
|
@@ -9902,25 +10158,25 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
9902
10158
|
if (process.env.OPENCODE_CONFIG_CONTENT)
|
|
9903
10159
|
applyText(process.env.OPENCODE_CONFIG_CONTENT, "OPENCODE_CONFIG_CONTENT");
|
|
9904
10160
|
if (process.env.OPENCODE_PERMISSION) {
|
|
9905
|
-
let
|
|
10161
|
+
let permission;
|
|
9906
10162
|
try {
|
|
9907
|
-
|
|
10163
|
+
permission = JSON.parse(process.env.OPENCODE_PERMISSION);
|
|
9908
10164
|
} catch (error) {
|
|
9909
10165
|
throw new Error("OpenCode permission policy could not be parsed safely: OPENCODE_PERMISSION", { cause: error });
|
|
9910
10166
|
}
|
|
9911
|
-
const value = policyWithExpandedPatterns(policyValue(
|
|
10167
|
+
const value = policyWithExpandedPatterns(policyValue(permission, "OPENCODE_PERMISSION"));
|
|
9912
10168
|
applyLayer({ permission: value });
|
|
9913
10169
|
}
|
|
9914
10170
|
if (result.tools)
|
|
9915
10171
|
result.permission = mergePolicyValue(toolsPermission(result.tools, "OpenCode tools policy"), result.permission);
|
|
9916
10172
|
return result;
|
|
9917
10173
|
}
|
|
9918
|
-
function codexModel(
|
|
9919
|
-
const reasoning = codexReasoning(
|
|
10174
|
+
function codexModel(model, priority, baseUrl = "https://provider.invalid", selectedReasoning) {
|
|
10175
|
+
const reasoning = codexReasoning(model, baseUrl, selectedReasoning);
|
|
9920
10176
|
return {
|
|
9921
|
-
slug:
|
|
9922
|
-
display_name:
|
|
9923
|
-
description:
|
|
10177
|
+
slug: model.id,
|
|
10178
|
+
display_name: model.name,
|
|
10179
|
+
description: model.description ?? model.id,
|
|
9924
10180
|
shell_type: "shell_command",
|
|
9925
10181
|
visibility: "list",
|
|
9926
10182
|
supported_in_api: true,
|
|
@@ -9934,9 +10190,9 @@ function codexModel(model3, priority, baseUrl = "https://provider.invalid", sele
|
|
|
9934
10190
|
apply_patch_tool_type: null,
|
|
9935
10191
|
truncation_policy: { mode: "tokens", limit: 1e4 },
|
|
9936
10192
|
experimental_supported_tools: [],
|
|
9937
|
-
context_window:
|
|
9938
|
-
max_context_window:
|
|
9939
|
-
input_modalities: (
|
|
10193
|
+
context_window: model.contextWindow ?? null,
|
|
10194
|
+
max_context_window: model.contextWindow ?? null,
|
|
10195
|
+
input_modalities: (model.inputModalities ?? ["text"]).filter((m) => m === "text" || m === "image"),
|
|
9940
10196
|
prefer_websockets: false,
|
|
9941
10197
|
use_responses_lite: false,
|
|
9942
10198
|
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 }
|
|
@@ -9944,7 +10200,7 @@ function codexModel(model3, priority, baseUrl = "https://provider.invalid", sele
|
|
|
9944
10200
|
}
|
|
9945
10201
|
function grokBridge(input, timing = {}) {
|
|
9946
10202
|
const token = crypto.randomUUID() + crypto.randomUUID();
|
|
9947
|
-
const expected =
|
|
10203
|
+
const expected = createHash9("sha256").update(`Bearer ${token}`).digest();
|
|
9948
10204
|
const models = new Map(input.models.flatMap((m) => [[m.id, m.id], [grokAlias(input, m.id), m.id]]));
|
|
9949
10205
|
let server;
|
|
9950
10206
|
let closing = false;
|
|
@@ -9952,11 +10208,11 @@ function grokBridge(input, timing = {}) {
|
|
|
9952
10208
|
const active = new Set;
|
|
9953
10209
|
const apiBackend = { "anthropic-messages": "messages", "openai-responses": "responses", "openai-chat": "chat_completions", "gemini-generate-content": "generate_content" }[input.protocol];
|
|
9954
10210
|
const apiPath = { "anthropic-messages": "/messages", "openai-responses": "/responses", "openai-chat": "/chat/completions", "gemini-generate-content": "/generateContent" }[input.protocol];
|
|
9955
|
-
server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request,
|
|
10211
|
+
server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server) {
|
|
9956
10212
|
if (closing)
|
|
9957
10213
|
return Response.json({ error: { message: "Bridge is closing" } }, { status: 503 });
|
|
9958
10214
|
const auth = request.headers.get("authorization") ?? (request.headers.has("x-api-key") ? `Bearer ${request.headers.get("x-api-key")}` : "");
|
|
9959
|
-
if (!timingSafeEqual5(expected,
|
|
10215
|
+
if (!timingSafeEqual5(expected, createHash9("sha256").update(auth).digest()))
|
|
9960
10216
|
return Response.json({ error: { message: "Unauthorized" } }, { status: 401 });
|
|
9961
10217
|
const path = new URL(request.url).pathname;
|
|
9962
10218
|
if (request.method === "GET" && path === "/v1/api-key")
|
|
@@ -9967,7 +10223,7 @@ function grokBridge(input, timing = {}) {
|
|
|
9967
10223
|
model: m.id,
|
|
9968
10224
|
name: m.name,
|
|
9969
10225
|
description: m.description,
|
|
9970
|
-
base_url: new URL("v1",
|
|
10226
|
+
base_url: new URL("v1", server.url).href,
|
|
9971
10227
|
context_window: m.contextWindow,
|
|
9972
10228
|
max_completion_tokens: m.maxOutputTokens,
|
|
9973
10229
|
api_backend: apiBackend,
|
|
@@ -9997,17 +10253,17 @@ function grokBridge(input, timing = {}) {
|
|
|
9997
10253
|
if (closing)
|
|
9998
10254
|
return Response.json({ error: { message: "Bridge is closing" } }, { status: 503 });
|
|
9999
10255
|
let complete;
|
|
10000
|
-
const
|
|
10001
|
-
complete =
|
|
10256
|
+
const record = { abort: new AbortController, done: new Promise((resolve) => {
|
|
10257
|
+
complete = resolve;
|
|
10002
10258
|
}) };
|
|
10003
|
-
const activity = createProviderRequest(request.signal,
|
|
10259
|
+
const activity = createProviderRequest(request.signal, record.abort.signal, timing);
|
|
10004
10260
|
const release = () => {
|
|
10005
10261
|
activity.finish();
|
|
10006
|
-
active.delete(
|
|
10262
|
+
active.delete(record);
|
|
10007
10263
|
complete();
|
|
10008
10264
|
};
|
|
10009
|
-
active.add(
|
|
10010
|
-
|
|
10265
|
+
active.add(record);
|
|
10266
|
+
server.timeout(request, 0);
|
|
10011
10267
|
try {
|
|
10012
10268
|
const response = await activity.run(() => fetch(`${input.baseUrl}${apiPath}`, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
|
|
10013
10269
|
if (!response.ok) {
|
|
@@ -10021,8 +10277,8 @@ function grokBridge(input, timing = {}) {
|
|
|
10021
10277
|
release();
|
|
10022
10278
|
return new Response(null, { status: response.status });
|
|
10023
10279
|
}
|
|
10024
|
-
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort:
|
|
10025
|
-
|
|
10280
|
+
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record.abort, closing: () => closing, release, activity });
|
|
10281
|
+
record.cancel = cancel;
|
|
10026
10282
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
10027
10283
|
} catch {
|
|
10028
10284
|
release();
|
|
@@ -10032,44 +10288,44 @@ function grokBridge(input, timing = {}) {
|
|
|
10032
10288
|
return { baseUrl: new URL("v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
|
|
10033
10289
|
closing = true;
|
|
10034
10290
|
const pending = [...active];
|
|
10035
|
-
for (const
|
|
10036
|
-
|
|
10037
|
-
await Promise.allSettled(pending.map(async (
|
|
10038
|
-
await
|
|
10039
|
-
await
|
|
10291
|
+
for (const record of pending)
|
|
10292
|
+
record.abort.abort();
|
|
10293
|
+
await Promise.allSettled(pending.map(async (record) => {
|
|
10294
|
+
await record.cancel?.();
|
|
10295
|
+
await record.done;
|
|
10040
10296
|
}));
|
|
10041
10297
|
await server.stop(true);
|
|
10042
10298
|
})() };
|
|
10043
10299
|
}
|
|
10044
|
-
function grokAlias(input,
|
|
10045
|
-
return "switcher-" +
|
|
10300
|
+
function grokAlias(input, model) {
|
|
10301
|
+
return "switcher-" + createHash9("sha256").update(JSON.stringify([input.providerBaseUrl ?? input.baseUrl, input.protocol])).digest("hex").slice(0, 12) + "/" + model;
|
|
10046
10302
|
}
|
|
10047
10303
|
function piProviderId(input, providerBaseUrl) {
|
|
10048
|
-
return "switcher-" +
|
|
10304
|
+
return "switcher-" + createHash9("sha256").update(JSON.stringify([endpoint(providerBaseUrl), input.protocol])).digest("hex").slice(0, 12);
|
|
10049
10305
|
}
|
|
10050
10306
|
function piModel(input, api) {
|
|
10051
|
-
return input.models.map((
|
|
10052
|
-
id:
|
|
10053
|
-
name:
|
|
10307
|
+
return input.models.map((model) => ({
|
|
10308
|
+
id: model.id,
|
|
10309
|
+
name: model.name,
|
|
10054
10310
|
api,
|
|
10055
|
-
...
|
|
10056
|
-
...
|
|
10057
|
-
input: (
|
|
10058
|
-
...
|
|
10311
|
+
...model.contextWindow ? { contextWindow: model.contextWindow } : {},
|
|
10312
|
+
...model.maxOutputTokens ? { maxTokens: model.maxOutputTokens } : {},
|
|
10313
|
+
input: (model.inputModalities ?? ["text"]).filter((modality) => modality === "text" || modality === "image").length > 0 ? (model.inputModalities ?? ["text"]).filter((modality) => modality === "text" || modality === "image") : ["text"],
|
|
10314
|
+
...model.supportedParameters?.includes("reasoning") ? { reasoning: true } : {}
|
|
10059
10315
|
}));
|
|
10060
10316
|
}
|
|
10061
10317
|
function primeProviderId(input, providerBaseUrl) {
|
|
10062
|
-
return "switcher-" +
|
|
10318
|
+
return "switcher-" + createHash9("sha256").update(JSON.stringify([endpoint(providerBaseUrl), input.protocol])).digest("hex").slice(0, 12);
|
|
10063
10319
|
}
|
|
10064
10320
|
var PRIME_UNIX_SOCKET_LIMIT = 100;
|
|
10065
10321
|
var PRIME_DAEMON_STARTUP_TIMEOUT_MS = 30000;
|
|
10066
10322
|
var PRIME_DAEMON_SHUTDOWN_TIMEOUT_MS = 5000;
|
|
10067
10323
|
function primeSocketPaths(runtimeDir) {
|
|
10068
|
-
const
|
|
10069
|
-
const daemonSocket = join12(runtimeDir,
|
|
10324
|
+
const basename = `p-${randomUUID4().replaceAll("-", "").slice(0, 8)}.sock`;
|
|
10325
|
+
const daemonSocket = join12(runtimeDir, basename);
|
|
10070
10326
|
const uid = typeof process.getuid === "function" ? String(process.getuid()) : "user";
|
|
10071
10327
|
const workerDir = join12(runtimeDir, `prime-agent-${uid}`);
|
|
10072
|
-
const workerKey =
|
|
10328
|
+
const workerKey = createHash9("sha256").update(daemonSocket).digest("hex").slice(0, 12);
|
|
10073
10329
|
const workerSocket = join12(workerDir, `worker-${workerKey}-${"x".repeat(12)}.sock`);
|
|
10074
10330
|
const overlong = [daemonSocket, workerSocket].find((path) => Buffer.byteLength(path, "utf8") > PRIME_UNIX_SOCKET_LIMIT);
|
|
10075
10331
|
return { daemonSocket, runtimeDir, workerDir, workerPrefix: join12(workerDir, `worker-${workerKey}-`), overlong };
|
|
@@ -10099,7 +10355,7 @@ function primeSignalSupervisor(supervisor, signal) {
|
|
|
10099
10355
|
} catch {}
|
|
10100
10356
|
}
|
|
10101
10357
|
async function primeReadinessProbe(socketPath) {
|
|
10102
|
-
await new Promise((
|
|
10358
|
+
await new Promise((resolve, reject) => {
|
|
10103
10359
|
const socket = createConnection(socketPath);
|
|
10104
10360
|
let settled = false;
|
|
10105
10361
|
let buffer = "";
|
|
@@ -10109,7 +10365,7 @@ async function primeReadinessProbe(socketPath) {
|
|
|
10109
10365
|
settled = true;
|
|
10110
10366
|
socket.removeAllListeners();
|
|
10111
10367
|
socket.destroy();
|
|
10112
|
-
error ?
|
|
10368
|
+
error ? reject(error) : resolve();
|
|
10113
10369
|
};
|
|
10114
10370
|
const timer = setTimeout(() => finish(new Error("Prime Agent daemon hello timed out.")), 500);
|
|
10115
10371
|
const onLine = (line) => {
|
|
@@ -10164,12 +10420,12 @@ async function primeStartSupervisor(input, executable, socketPath, env, onSpawn)
|
|
|
10164
10420
|
await primeReadinessProbe(socketPath);
|
|
10165
10421
|
return supervisor;
|
|
10166
10422
|
} catch {}
|
|
10167
|
-
await new Promise((
|
|
10423
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
10168
10424
|
}
|
|
10169
10425
|
throw new Error(`Prime Agent daemon did not become ready within ${PRIME_DAEMON_STARTUP_TIMEOUT_MS / 1000} seconds.`);
|
|
10170
10426
|
} catch (error) {
|
|
10171
10427
|
primeSignalSupervisor(supervisor, "SIGTERM");
|
|
10172
|
-
await Promise.race([supervisor.exited, new Promise((
|
|
10428
|
+
await Promise.race([supervisor.exited, new Promise((resolve) => setTimeout(resolve, 1000))]);
|
|
10173
10429
|
if (!exited)
|
|
10174
10430
|
primeSignalSupervisor(supervisor, "SIGKILL");
|
|
10175
10431
|
throw error;
|
|
@@ -10183,7 +10439,7 @@ async function primeOwnedShutdown(socketPath, workerPrefix) {
|
|
|
10183
10439
|
let responseSeen = false;
|
|
10184
10440
|
const requestId = `switcher_${randomUUID4()}`;
|
|
10185
10441
|
let requestSent = false;
|
|
10186
|
-
await new Promise((
|
|
10442
|
+
await new Promise((resolve, reject) => {
|
|
10187
10443
|
const socket = createConnection(socketPath);
|
|
10188
10444
|
let settled = false;
|
|
10189
10445
|
let buffer = "";
|
|
@@ -10197,9 +10453,9 @@ async function primeOwnedShutdown(socketPath, workerPrefix) {
|
|
|
10197
10453
|
socket.removeAllListeners();
|
|
10198
10454
|
socket.destroy();
|
|
10199
10455
|
if (error)
|
|
10200
|
-
|
|
10456
|
+
reject(error);
|
|
10201
10457
|
else
|
|
10202
|
-
|
|
10458
|
+
resolve();
|
|
10203
10459
|
};
|
|
10204
10460
|
timeout = setTimeout(() => finish(new Error(`Timed out shutting down the Prime Agent daemon on ${socketPath}.`)), 3000);
|
|
10205
10461
|
const onLine = (line) => {
|
|
@@ -10248,12 +10504,12 @@ async function primeOwnedShutdown(socketPath, workerPrefix) {
|
|
|
10248
10504
|
const [daemonExists, workers] = await Promise.all([exists(), workerEntries()]);
|
|
10249
10505
|
if (!daemonExists && !workers.length)
|
|
10250
10506
|
return;
|
|
10251
|
-
await new Promise((
|
|
10507
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
10252
10508
|
}
|
|
10253
10509
|
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}).`);
|
|
10254
10510
|
}
|
|
10255
10511
|
async function primeWaitExit(supervisor, timeout) {
|
|
10256
|
-
return await Promise.race([supervisor.exited.then(() => true), new Promise((
|
|
10512
|
+
return await Promise.race([supervisor.exited.then(() => true), new Promise((resolve) => setTimeout(() => resolve(false), timeout))]);
|
|
10257
10513
|
}
|
|
10258
10514
|
async function primeRemainingSockets(socketPath, workerPrefix) {
|
|
10259
10515
|
const daemon = await access3(socketPath).then(() => true, () => false);
|
|
@@ -10263,14 +10519,14 @@ async function primeRemainingSockets(socketPath, workerPrefix) {
|
|
|
10263
10519
|
return [...daemon ? [socketPath] : [], ...workers.map((entry) => join12(workerDir, entry))];
|
|
10264
10520
|
}
|
|
10265
10521
|
function primeModel(input, api) {
|
|
10266
|
-
return input.models.map((
|
|
10267
|
-
id:
|
|
10268
|
-
...
|
|
10522
|
+
return input.models.map((model) => ({
|
|
10523
|
+
id: model.id,
|
|
10524
|
+
...model.name ? { name: model.name } : {},
|
|
10269
10525
|
api,
|
|
10270
|
-
reasoning:
|
|
10271
|
-
input: (
|
|
10272
|
-
...
|
|
10273
|
-
...
|
|
10526
|
+
reasoning: model.supportedParameters?.includes("reasoning") ?? false,
|
|
10527
|
+
input: (model.inputModalities ?? ["text"]).filter((modality) => modality === "text" || modality === "image").length > 0 ? (model.inputModalities ?? ["text"]).filter((modality) => modality === "text" || modality === "image") : ["text"],
|
|
10528
|
+
...model.contextWindow ? { contextWindow: model.contextWindow } : {},
|
|
10529
|
+
...model.maxOutputTokens ? { maxTokens: model.maxOutputTokens } : {}
|
|
10274
10530
|
}));
|
|
10275
10531
|
}
|
|
10276
10532
|
async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUrl ?? input.baseUrl) {
|
|
@@ -10311,16 +10567,16 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10311
10567
|
env.ANTHROPIC_API_KEY = "";
|
|
10312
10568
|
env.ANTHROPIC_AUTH_TOKEN = "";
|
|
10313
10569
|
env[input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"] = input.credential ?? "switcher-local-no-auth";
|
|
10314
|
-
const
|
|
10315
|
-
configPaths.push(
|
|
10570
|
+
const file = 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) })) } });
|
|
10571
|
+
configPaths.push(file);
|
|
10316
10572
|
warnings.push("Claude managed settings and model allowlists can restrict the generated picker.");
|
|
10317
|
-
return { executable, args: ["--settings",
|
|
10573
|
+
return { executable, args: ["--settings", file, "--model", input.model, ...args], env, configPaths, warnings };
|
|
10318
10574
|
}
|
|
10319
10575
|
if (input.harness === "codex") {
|
|
10320
|
-
const
|
|
10321
|
-
const
|
|
10322
|
-
configPaths.push(
|
|
10323
|
-
configPaths.push(...Object.values(
|
|
10576
|
+
const rolePolicy = await prepareCodexModelPolicy({ cwd: input.cwd, stateDir: input.stateDir, model: input.model, policy: input.modelPolicy ? { version: 1, ...input.modelPolicy } : undefined, switcherProvider: "switcher", switcherBaseUrl: input.baseUrl });
|
|
10577
|
+
const file = await jsonFile(input.stateDir, "codex-models.json", { models: input.models.map((model, index) => codexModel(model, index, providerBaseUrl, model.id === input.model ? input.reasoning : undefined)) });
|
|
10578
|
+
configPaths.push(file);
|
|
10579
|
+
configPaths.push(...Object.values(rolePolicy.agentConfigPaths));
|
|
10324
10580
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
10325
10581
|
const provider = { name: "Switcher", base_url: input.baseUrl, wire_api: "responses", requires_openai_auth: false };
|
|
10326
10582
|
{
|
|
@@ -10330,8 +10586,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10330
10586
|
provider.env_key = KEY4;
|
|
10331
10587
|
}
|
|
10332
10588
|
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(", ");
|
|
10333
|
-
const overrides = ["-c", `model_provider="switcher"`, "-c", `model_providers.switcher={ ${toml} }`, "-c", `model_catalog_json=${quote(
|
|
10334
|
-
for (const [name, path] of Object.entries(
|
|
10589
|
+
const overrides = ["-c", `model_provider="switcher"`, "-c", `model_providers.switcher={ ${toml} }`, "-c", `model_catalog_json=${quote(file)}`, "-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)}`];
|
|
10590
|
+
for (const [name, path] of Object.entries(rolePolicy.agentConfigPaths)) {
|
|
10335
10591
|
if (!/^[A-Za-z0-9_-]+$/.test(name))
|
|
10336
10592
|
throw new Error("Codex role names containing punctuation beyond hyphens/underscores cannot be safely overridden by this native CLI.");
|
|
10337
10593
|
overrides.push("-c", `agents.${name}.config_file=${quote(path)}`);
|
|
@@ -10348,22 +10604,22 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10348
10604
|
}
|
|
10349
10605
|
if (input.harness === "grok") {
|
|
10350
10606
|
validateGrokResume(args);
|
|
10351
|
-
const
|
|
10352
|
-
configPaths.push(
|
|
10607
|
+
const file = 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)) } });
|
|
10608
|
+
configPaths.push(file);
|
|
10353
10609
|
const bridge = grokBridge(input);
|
|
10354
10610
|
env.GROK_MODELS_BASE_URL = bridge.baseUrl;
|
|
10355
10611
|
env.GROK_MODELS_LIST_URL = bridge.baseUrl + "/models";
|
|
10356
10612
|
env.GROK_XAI_API_BASE_URL = bridge.baseUrl;
|
|
10357
10613
|
env.XAI_API_KEY = bridge.token;
|
|
10358
10614
|
env[KEY4] = bridge.token;
|
|
10359
|
-
env.GROK_CONFIG_PATH =
|
|
10615
|
+
env.GROK_CONFIG_PATH = file;
|
|
10360
10616
|
warnings.push("Grok uses a per-launch loopback catalog/auth bridge; native managed model policies still apply.");
|
|
10361
10617
|
return { executable, args: ["--model", grokAlias(input, input.model), "--no-leader", ...args], env, configPaths, warnings, cleanup: bridge.cleanup };
|
|
10362
10618
|
}
|
|
10363
10619
|
if (input.harness === "pi") {
|
|
10364
10620
|
if (input.authStyle === "x-api-key" && input.protocol !== "anthropic-messages")
|
|
10365
10621
|
throw new Error("Pi can use x-api-key authentication only with the Anthropic Messages protocol.");
|
|
10366
|
-
if (new Set(input.models.map((
|
|
10622
|
+
if (new Set(input.models.map((model) => model.id.toLowerCase())).size !== input.models.length)
|
|
10367
10623
|
throw new Error("Pi cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
10368
10624
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions", "gemini-generate-content": "gemini" }[input.protocol];
|
|
10369
10625
|
const providerId = piProviderId(input, providerBaseUrl);
|
|
@@ -10372,14 +10628,14 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10372
10628
|
const piBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
|
|
10373
10629
|
await mkdir10(agentDir, { recursive: true, mode: 448 });
|
|
10374
10630
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
10375
|
-
const
|
|
10631
|
+
const file = await jsonFile(agentDir, "models.json", { providers: { [providerId]: {
|
|
10376
10632
|
name: "Switcher",
|
|
10377
10633
|
baseUrl: piBaseUrl,
|
|
10378
10634
|
api,
|
|
10379
10635
|
apiKey: `$${KEY4}`,
|
|
10380
10636
|
models: piModel(input, api)
|
|
10381
10637
|
} } });
|
|
10382
|
-
configPaths.push(
|
|
10638
|
+
configPaths.push(file);
|
|
10383
10639
|
env.PI_CODING_AGENT_DIR = agentDir;
|
|
10384
10640
|
env.PI_CODING_AGENT_SESSION_DIR = sessionDir;
|
|
10385
10641
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
@@ -10399,7 +10655,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10399
10655
|
throw new Error("DSH session directory must be absolute.");
|
|
10400
10656
|
await mkdir10(home, { recursive: true, mode: 448 });
|
|
10401
10657
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
10402
|
-
const
|
|
10658
|
+
const route = { provider: providerId, model: input.model };
|
|
10403
10659
|
const overlay = [
|
|
10404
10660
|
{ id: "llm-deepseek", disabled: true },
|
|
10405
10661
|
{ id: "llm-pi-ai", config: { providers: { [providerId]: {
|
|
@@ -10407,21 +10663,21 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10407
10663
|
api,
|
|
10408
10664
|
apiKeyEnv: KEY4,
|
|
10409
10665
|
baseURL: input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl,
|
|
10410
|
-
models: input.models.map((
|
|
10411
|
-
id:
|
|
10412
|
-
name:
|
|
10413
|
-
...
|
|
10414
|
-
...
|
|
10415
|
-
input: (
|
|
10666
|
+
models: input.models.map((model) => ({
|
|
10667
|
+
id: model.id,
|
|
10668
|
+
name: model.name,
|
|
10669
|
+
...model.contextWindow ? { contextWindow: model.contextWindow } : {},
|
|
10670
|
+
...model.maxOutputTokens ? { maxTokens: model.maxOutputTokens } : {},
|
|
10671
|
+
input: (model.inputModalities ?? ["text"]).filter((modality) => modality === "text" || modality === "image")
|
|
10416
10672
|
}))
|
|
10417
10673
|
} } } },
|
|
10418
|
-
{ id: "agent-default-model", config:
|
|
10674
|
+
{ id: "agent-default-model", config: route },
|
|
10419
10675
|
{ id: "session-persistence-jsonl", config: { root: join12(sessionDir, "sessions") } },
|
|
10420
10676
|
{ id: "attachment-local", config: { dshHome: sessionDir } },
|
|
10421
|
-
...selected.profile === "acp" ? [{ id: "acp", config:
|
|
10677
|
+
...selected.profile === "acp" ? [{ id: "acp", config: route }] : []
|
|
10422
10678
|
];
|
|
10423
|
-
const
|
|
10424
|
-
configPaths.push(
|
|
10679
|
+
const file = await jsonFile(input.stateDir, "dsh-patch.json", overlay);
|
|
10680
|
+
configPaths.push(file);
|
|
10425
10681
|
env.DSH_HOME = home;
|
|
10426
10682
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
10427
10683
|
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.");
|
|
@@ -10429,7 +10685,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10429
10685
|
warnings.push("DSH opens its native browser UI on an allocated loopback port; use -- --no-open to print the URL without opening a browser.");
|
|
10430
10686
|
if (selected.profile === "headless")
|
|
10431
10687
|
warnings.push("DSH headless runs one fresh task; resume is available through the native web UI or ACP session/resume.");
|
|
10432
|
-
return { executable, args: ["--profile", selected.profile, "--patch",
|
|
10688
|
+
return { executable, args: ["--profile", selected.profile, "--patch", file, ...selected.args], env, configPaths, warnings };
|
|
10433
10689
|
}
|
|
10434
10690
|
if (input.harness === "cline")
|
|
10435
10691
|
return prepareClineLaunch(input);
|
|
@@ -10438,7 +10694,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10438
10694
|
if (input.harness === "prime-agent") {
|
|
10439
10695
|
if (input.authStyle === "x-api-key" && input.protocol !== "anthropic-messages")
|
|
10440
10696
|
throw new Error("Prime Agent can use x-api-key authentication only with the Anthropic Messages protocol.");
|
|
10441
|
-
if (new Set(input.models.map((
|
|
10697
|
+
if (new Set(input.models.map((model) => model.id.toLowerCase())).size !== input.models.length)
|
|
10442
10698
|
throw new Error("Prime Agent cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
10443
10699
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
|
|
10444
10700
|
const providerId = primeProviderId(input, providerBaseUrl);
|
|
@@ -10449,8 +10705,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10449
10705
|
const primeBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
|
|
10450
10706
|
await mkdir10(agentDir, { recursive: true, mode: 448 });
|
|
10451
10707
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
10452
|
-
const
|
|
10453
|
-
await writeFile10(
|
|
10708
|
+
const file = join12(agentDir, "models.json");
|
|
10709
|
+
await writeFile10(file, JSON.stringify({ providers: { [providerId]: {
|
|
10454
10710
|
name: "Switcher",
|
|
10455
10711
|
baseUrl: primeBaseUrl,
|
|
10456
10712
|
api,
|
|
@@ -10458,21 +10714,21 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10458
10714
|
models: primeModel(input, api)
|
|
10459
10715
|
} } }, null, 2) + `
|
|
10460
10716
|
`, { mode: 384, flag: "w" });
|
|
10461
|
-
configPaths.push(
|
|
10717
|
+
configPaths.push(file);
|
|
10462
10718
|
env.PRIME_AGENT_CODING_AGENT_DIR = agentDir;
|
|
10463
10719
|
env.PRIME_AGENT_SESSION_DIR = sessionDir;
|
|
10464
10720
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
10465
10721
|
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.");
|
|
10466
10722
|
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.");
|
|
10467
10723
|
env.TMPDIR = runtimeDir;
|
|
10468
|
-
const
|
|
10724
|
+
const executable = input.executable ?? input.harness;
|
|
10469
10725
|
let supervisor;
|
|
10470
10726
|
let starting;
|
|
10471
10727
|
let ready = false;
|
|
10472
10728
|
const beforeLaunch = async () => {
|
|
10473
10729
|
if (ready)
|
|
10474
10730
|
return;
|
|
10475
|
-
starting ??= primeStartSupervisor(input,
|
|
10731
|
+
starting ??= primeStartSupervisor(input, executable, daemonSocket, env, (child) => {
|
|
10476
10732
|
supervisor = child;
|
|
10477
10733
|
});
|
|
10478
10734
|
supervisor = await starting;
|
|
@@ -10511,36 +10767,36 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10511
10767
|
if (failure)
|
|
10512
10768
|
throw failure;
|
|
10513
10769
|
};
|
|
10514
|
-
return { executable
|
|
10770
|
+
return { executable, args: ["--daemon-socket", daemonSocket, "--provider", providerId, "--model", input.model, "--models", `${providerId}/**`, ...args], env, configPaths, warnings, beforeLaunch, cleanup };
|
|
10515
10771
|
}
|
|
10516
10772
|
if (input.harness === "opencode") {
|
|
10517
|
-
const
|
|
10518
|
-
const
|
|
10519
|
-
const modelConfig = Object.fromEntries(input.models.map((
|
|
10520
|
-
name:
|
|
10521
|
-
...
|
|
10773
|
+
const providerID = "switcher-" + createHash9("sha256").update(endpoint(providerBaseUrl) + input.protocol).digest("hex").slice(0, 12);
|
|
10774
|
+
const packageName = { "anthropic-messages": "@ai-sdk/anthropic", "openai-responses": "@ai-sdk/openai", "openai-chat": "@ai-sdk/openai-compatible" }[input.protocol];
|
|
10775
|
+
const modelConfig = Object.fromEntries(input.models.map((model) => [model.id, {
|
|
10776
|
+
name: model.name,
|
|
10777
|
+
...model.contextWindow && model.maxOutputTokens ? { limit: { context: model.contextWindow, output: model.maxOutputTokens } } : {}
|
|
10522
10778
|
}]));
|
|
10523
10779
|
const instructions = await projectInstructionPaths(input.cwd);
|
|
10524
10780
|
const policy = await preservedOpenCodePolicy(input.cwd);
|
|
10525
|
-
const
|
|
10526
|
-
const
|
|
10781
|
+
const rolePolicy = compileOpenCodeModelPolicy({ providerId: providerID, mainModel: input.model, roles: input.compiledPolicy?.roles, format: "legacy", preservedAgents: Object.entries(policy.agent ?? {}).map(([name, agent]) => ({ ...agent, name })) });
|
|
10782
|
+
const config = {
|
|
10527
10783
|
$schema: "https://opencode.ai/config.json",
|
|
10528
|
-
small_model: `${
|
|
10529
|
-
enabled_providers: [
|
|
10784
|
+
small_model: `${providerID}/${input.compiledPolicy?.roles.fast ?? input.model}`,
|
|
10785
|
+
enabled_providers: [providerID],
|
|
10530
10786
|
...instructions.length ? { instructions } : {},
|
|
10531
10787
|
...policy.permission ? { permission: policy.permission } : {},
|
|
10532
|
-
...
|
|
10788
|
+
...rolePolicy.config,
|
|
10533
10789
|
...policy.mode ? { mode: policy.mode } : {},
|
|
10534
|
-
provider: { [
|
|
10535
|
-
npm:
|
|
10790
|
+
provider: { [providerID]: {
|
|
10791
|
+
npm: packageName,
|
|
10536
10792
|
name: "Switcher",
|
|
10537
10793
|
options: { baseURL: input.baseUrl, apiKey: `{env:${KEY4}}` },
|
|
10538
10794
|
models: modelConfig
|
|
10539
10795
|
} }
|
|
10540
10796
|
};
|
|
10541
|
-
const
|
|
10542
|
-
configPaths.push(
|
|
10543
|
-
env.OPENCODE_CONFIG =
|
|
10797
|
+
const file = await jsonFile(input.stateDir, "opencode-legacy.json", config);
|
|
10798
|
+
configPaths.push(file);
|
|
10799
|
+
env.OPENCODE_CONFIG = file;
|
|
10544
10800
|
const sessionDir = input.sessionDir ?? join12(input.stateDir, "sessions");
|
|
10545
10801
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
10546
10802
|
env.XDG_DATA_HOME = join12(sessionDir, "data");
|
|
@@ -10549,14 +10805,14 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10549
10805
|
env.XDG_STATE_HOME = join12(input.stateDir, "state");
|
|
10550
10806
|
env.HOME = join12(input.stateDir, "home");
|
|
10551
10807
|
env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";
|
|
10552
|
-
env.OPENCODE_CONFIG_CONTENT = JSON.stringify(
|
|
10808
|
+
env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config);
|
|
10553
10809
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
10554
|
-
const
|
|
10555
|
-
const
|
|
10810
|
+
const modelRef = openCodeInvocationModel(args, rolePolicy);
|
|
10811
|
+
const native = args[0] === "run" ? ["run", "--model", modelRef, ...args.slice(1)] : args[0] === "models" ? ["models", ...args.slice(1)] : ["--model", modelRef, ...args];
|
|
10556
10812
|
warnings.push("Legacy OpenCode uses the documented singular provider configuration and an isolated XDG data root for durable sessions; it is separate from OpenCode 2.");
|
|
10557
|
-
return { executable, args:
|
|
10813
|
+
return { executable, args: native, env, configPaths, warnings };
|
|
10558
10814
|
}
|
|
10559
|
-
const providerID = "switcher-" +
|
|
10815
|
+
const providerID = "switcher-" + createHash9("sha256").update(endpoint(providerBaseUrl) + input.protocol).digest("hex").slice(0, 12);
|
|
10560
10816
|
const packageName = { "anthropic-messages": "anthropic", "openai-responses": "openai/responses", "openai-chat": "openai-compatible", "gemini-generate-content": "gemini" }[input.protocol];
|
|
10561
10817
|
const models = Object.fromEntries(input.models.map((m) => [m.id, {
|
|
10562
10818
|
modelID: m.id,
|
|
@@ -10564,13 +10820,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10564
10820
|
capabilities: { tools: m.supportedParameters?.includes("tools") ?? true, input: m.inputModalities ?? ["text"], output: m.outputModalities ?? ["text"] },
|
|
10565
10821
|
limit: { ...m.contextWindow ? { context: m.contextWindow } : {}, ...m.maxOutputTokens ? { output: m.maxOutputTokens } : {} }
|
|
10566
10822
|
}]));
|
|
10567
|
-
const
|
|
10823
|
+
const settings = { baseURL: input.baseUrl };
|
|
10568
10824
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
10569
|
-
|
|
10825
|
+
settings.apiKey = `{env:${KEY4}}`;
|
|
10570
10826
|
const isolated = await isolateOpenCode2(input.cwd, input.stateDir, providerID);
|
|
10571
10827
|
const rolePolicy = compileOpenCodeModelPolicy({ providerId: providerID, mainModel: input.model, roles: input.compiledPolicy?.roles, preservedAgents: Object.entries(isolated.config.agents ?? {}).map(([name, agent]) => ({ ...agent, name })) });
|
|
10572
10828
|
const modelRef = openCodeInvocationModel(args, rolePolicy, isolated.config.default_agent);
|
|
10573
|
-
const config = { ...isolated.config, ...rolePolicy.config, providers: { [providerID]: { name: "Switcher", env: [KEY4], package: `@opencode-ai/ai/providers/${packageName}`, settings
|
|
10829
|
+
const config = { ...isolated.config, ...rolePolicy.config, providers: { [providerID]: { name: "Switcher", env: [KEY4], package: `@opencode-ai/ai/providers/${packageName}`, settings, models } } };
|
|
10574
10830
|
const file = join12(input.stateDir, "opencode.json");
|
|
10575
10831
|
await writeFile10(file, openCode2ConfigText(config, providerID, KEY4), { mode: 384, flag: "wx" });
|
|
10576
10832
|
configPaths.push(file, isolated.instructionFile);
|
|
@@ -10591,18 +10847,18 @@ async function prepareTransportLaunch(input) {
|
|
|
10591
10847
|
if (input.protocol === "gemini-generate-content")
|
|
10592
10848
|
throw new Error("Kilo is incompatible with this protocol.");
|
|
10593
10849
|
validateHarnessVersion(input.harness, input.version);
|
|
10594
|
-
const
|
|
10850
|
+
const bridge = grokBridge({ ...input, baseUrl: endpoint(input.baseUrl) });
|
|
10595
10851
|
try {
|
|
10596
|
-
const prepared = await prepareKilo({ ...input, credential:
|
|
10852
|
+
const prepared = await prepareKilo({ ...input, credential: bridge.token }, bridge.baseUrl);
|
|
10597
10853
|
return { ...prepared, cleanup: async () => {
|
|
10598
10854
|
try {
|
|
10599
10855
|
await prepared.cleanup?.();
|
|
10600
10856
|
} finally {
|
|
10601
|
-
await
|
|
10857
|
+
await bridge.cleanup();
|
|
10602
10858
|
}
|
|
10603
10859
|
} };
|
|
10604
10860
|
} catch (error) {
|
|
10605
|
-
await
|
|
10861
|
+
await bridge.cleanup();
|
|
10606
10862
|
throw error;
|
|
10607
10863
|
}
|
|
10608
10864
|
}
|
|
@@ -10617,18 +10873,18 @@ async function prepareTransportLaunch(input) {
|
|
|
10617
10873
|
const configuration = await validateGeminiConfiguration(input.cwd);
|
|
10618
10874
|
if (input.credential && JSON.stringify([configuration.defaults, configuration.user, configuration.system]).includes(input.credential))
|
|
10619
10875
|
throw new Error("Gemini native configuration must not contain the upstream provider credential.");
|
|
10620
|
-
const
|
|
10876
|
+
const bridge = geminiBridge(input);
|
|
10621
10877
|
try {
|
|
10622
|
-
const prepared = await prepareNativeLaunch({ ...input, baseUrl:
|
|
10878
|
+
const prepared = await prepareNativeLaunch({ ...input, baseUrl: bridge.baseUrl, credential: bridge.token });
|
|
10623
10879
|
return { ...prepared, cleanup: async () => {
|
|
10624
10880
|
try {
|
|
10625
10881
|
await prepared.cleanup?.();
|
|
10626
10882
|
} finally {
|
|
10627
|
-
await
|
|
10883
|
+
await bridge.cleanup();
|
|
10628
10884
|
}
|
|
10629
10885
|
} };
|
|
10630
10886
|
} catch (error) {
|
|
10631
|
-
await
|
|
10887
|
+
await bridge.cleanup();
|
|
10632
10888
|
throw error;
|
|
10633
10889
|
}
|
|
10634
10890
|
}
|
|
@@ -10659,12 +10915,12 @@ async function prepareHarnessLaunch(input) {
|
|
|
10659
10915
|
if (!isAbsolute11(input.stateDir) || !isAbsolute11(input.cwd))
|
|
10660
10916
|
throw new Error("Launch state and working directories must be absolute.");
|
|
10661
10917
|
const compiledPolicy = compileModelPolicy(input.model, input.models, input.modelPolicy);
|
|
10662
|
-
input = { ...input, models: input.models.filter((
|
|
10918
|
+
input = { ...input, models: input.models.filter((model) => !modelExpired(model)) };
|
|
10663
10919
|
const nativePolicy = compileNativeModelPolicy({ harness: input.harness, mainModel: input.model, roles: compiledPolicy.roles, version: input.version });
|
|
10664
10920
|
const specialized = new Set(["opencode", "opencode2", "gemini", "hermes"]);
|
|
10665
|
-
const
|
|
10666
|
-
if (
|
|
10667
|
-
throw new Error(`${input.harness} does not expose native model controls for: ${
|
|
10921
|
+
const unsupported = specialized.has(input.harness) ? [] : nativePolicy.unsupportedRoles.filter((role) => role !== "main" && compiledPolicy.roles[role] !== input.model);
|
|
10922
|
+
if (unsupported.length)
|
|
10923
|
+
throw new Error(`${input.harness} does not expose native model controls for: ${unsupported.join(", ")}.`);
|
|
10668
10924
|
await mkdir10(input.stateDir, { recursive: true, mode: 448 });
|
|
10669
10925
|
const catalogPath = await jsonFile(input.stateDir, `switcher-model-policy-${randomUUID4()}.json`, { policy: compiledPolicy, models: input.models });
|
|
10670
10926
|
const bridge = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
@@ -10698,7 +10954,7 @@ function prepareOriModelPolicy(target, prepared) {
|
|
|
10698
10954
|
throw new Error("Invalid native environment value.");
|
|
10699
10955
|
if (prepared.args.some((arg) => arg.includes("\x00")))
|
|
10700
10956
|
throw new Error("Invalid native argument.");
|
|
10701
|
-
const
|
|
10957
|
+
const quote = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
10702
10958
|
const env = { SWITCHER_ORI_NATIVE_EXECUTABLE: prepared.executable };
|
|
10703
10959
|
for (const [key, value] of entries)
|
|
10704
10960
|
env[`SWITCHER_ORI_CHILD_${key}`] = value;
|
|
@@ -10708,7 +10964,7 @@ function prepareOriModelPolicy(target, prepared) {
|
|
|
10708
10964
|
set -eu
|
|
10709
10965
|
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
|
|
10710
10966
|
${restore}
|
|
10711
|
-
exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(
|
|
10967
|
+
exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote).join(" ")}
|
|
10712
10968
|
` };
|
|
10713
10969
|
}
|
|
10714
10970
|
|
|
@@ -10716,20 +10972,24 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
|
|
|
10716
10972
|
import { mkdir as mkdir11, mkdtemp, rm as rm6, writeFile as writeFile14 } from "fs/promises";
|
|
10717
10973
|
import { join as join16, resolve as resolve9 } from "path";
|
|
10718
10974
|
|
|
10975
|
+
// src/provider-credential-onboarding.ts
|
|
10976
|
+
import { z as z8 } from "zod";
|
|
10977
|
+
import { createHash as createHash11 } from "crypto";
|
|
10978
|
+
import { createInterface } from "readline/promises";
|
|
10979
|
+
|
|
10719
10980
|
// src/credentials.ts
|
|
10720
10981
|
import { z as z7 } from "zod";
|
|
10721
10982
|
import { constants as constants5 } from "fs";
|
|
10722
10983
|
import { open as open3, readdir as readdir5, unlink, link, lstat as lstat4, access as access4, stat as stat6, realpath as realpath6, readlink, rename as rename2 } from "fs/promises";
|
|
10723
10984
|
import { join as join13, isAbsolute as isAbsolute13, dirname as dirname8, parse as pathParts, resolve as resolvePath, sep as sep2 } from "path";
|
|
10724
|
-
import { createHash as
|
|
10985
|
+
import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
|
|
10725
10986
|
import { execFile as execFile3, spawn } from "child_process";
|
|
10726
10987
|
import { promisify as promisify3 } from "util";
|
|
10727
|
-
import { createInterface } from "readline/promises";
|
|
10728
10988
|
import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
|
|
10729
10989
|
var execute3 = promisify3(execFile3);
|
|
10730
10990
|
var reference = z7.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
|
|
10731
10991
|
var item = z7.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
|
|
10732
|
-
var
|
|
10992
|
+
var vaultKeySchema = z7.string().max(500).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*)*$/, "Use a vault key path, not an option or secret value");
|
|
10733
10993
|
var keychain = z7.object({ kind: z7.literal("keychain"), service: item, account: item }).strict();
|
|
10734
10994
|
var credentialTier = z7.enum(["argument", "override", "pointer", "profile", "keychain", "disk", "env"]);
|
|
10735
10995
|
var operator = z7.discriminatedUnion("kind", [
|
|
@@ -10745,7 +11005,7 @@ var credentialBindingSchema = z7.object({
|
|
|
10745
11005
|
requireProviderAuthentication: z7.literal(true).optional(),
|
|
10746
11006
|
source: z7.discriminatedUnion("kind", [keychain, z7.object({
|
|
10747
11007
|
kind: z7.literal("vault"),
|
|
10748
|
-
key:
|
|
11008
|
+
key: vaultKeySchema,
|
|
10749
11009
|
url: z7.string().max(2000).transform(endpoint).optional(),
|
|
10750
11010
|
executable: z7.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute13, "Secrets executable must be an absolute path"),
|
|
10751
11011
|
operator
|
|
@@ -10756,7 +11016,7 @@ var credentialBindingSchema = z7.object({
|
|
|
10756
11016
|
if (binding.source.kind === "vault" && binding.source.operator.kind === "contracts" && Boolean(binding.source.operator.expectedSource) !== Boolean(binding.source.operator.expectedTier))
|
|
10757
11017
|
ctx.addIssue({ code: "custom", path: ["source", "operator"], message: "A pinned Contracts operator requires both expectedSource and expectedTier." });
|
|
10758
11018
|
});
|
|
10759
|
-
var fingerprint = (binding) =>
|
|
11019
|
+
var fingerprint = (binding) => createHash10("sha256").update(JSON.stringify(binding)).digest("hex");
|
|
10760
11020
|
|
|
10761
11021
|
class CredentialBindings {
|
|
10762
11022
|
env;
|
|
@@ -10941,8 +11201,8 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
10941
11201
|
if (!before.isFile() || before.uid !== process.getuid?.() || before.size > limit || before.mode & 3584)
|
|
10942
11202
|
throw unsafe();
|
|
10943
11203
|
const sameFile = (info) => info.dev === before.dev && info.ino === before.ino && info.size === before.size && info.uid === before.uid && info.nlink === before.nlink && info.mode === before.mode && info.mtimeMs === before.mtimeMs && info.ctimeMs === before.ctimeMs;
|
|
10944
|
-
const
|
|
10945
|
-
const digest =
|
|
11204
|
+
const hash = async (target) => {
|
|
11205
|
+
const digest = createHash10("sha256");
|
|
10946
11206
|
const buffer = Buffer.alloc(1024 * 1024);
|
|
10947
11207
|
let position = 0;
|
|
10948
11208
|
while (true) {
|
|
@@ -10962,7 +11222,7 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
10962
11222
|
if (digest.digest("hex") !== expectedSha256)
|
|
10963
11223
|
throw new Fault(422, "vault_exec_digest_mismatch", "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed.");
|
|
10964
11224
|
};
|
|
10965
|
-
await
|
|
11225
|
+
await hash();
|
|
10966
11226
|
const mode = before.mode & 511 & ~18;
|
|
10967
11227
|
const changed = mode !== (before.mode & 511);
|
|
10968
11228
|
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat4(resolved)))
|
|
@@ -10974,7 +11234,7 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
10974
11234
|
temporary = join13(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
|
|
10975
11235
|
const replacement = await open3(temporary, "wx", 384);
|
|
10976
11236
|
try {
|
|
10977
|
-
await
|
|
11237
|
+
await hash(replacement);
|
|
10978
11238
|
await replacement.chmod(mode);
|
|
10979
11239
|
await replacement.sync();
|
|
10980
11240
|
const ready = await replacement.stat();
|
|
@@ -11011,11 +11271,11 @@ function bindingTarget(selector, override, allowedOrigins) {
|
|
|
11011
11271
|
throw new Fault(400, "credential_origin_required", "Use --origin URL to authorize a custom credential destination.");
|
|
11012
11272
|
return { credentialEnv: parse2(reference, selector), origins: allowedOrigins.map((value) => new URL(endpoint(value)).origin) };
|
|
11013
11273
|
}
|
|
11014
|
-
const
|
|
11015
|
-
const credentialEnv = override ??
|
|
11274
|
+
const preset = getProviderPreset(selector);
|
|
11275
|
+
const credentialEnv = override ?? preset.credentialEnv;
|
|
11016
11276
|
if (!credentialEnv)
|
|
11017
11277
|
throw new Fault(400, "credential_reference_required", "Use --credential-env for a preset without a default credential reference.");
|
|
11018
|
-
const origins = allowedOrigins ?? [...new Set(
|
|
11278
|
+
const origins = allowedOrigins ?? [...new Set(preset.protocols.flatMap((route) => route.baseUrl ? [new URL(route.baseUrl).origin] : []))];
|
|
11019
11279
|
if (!origins.length)
|
|
11020
11280
|
throw new Fault(400, "credential_origin_required", "Use --origin URL for this custom preset.");
|
|
11021
11281
|
return { credentialEnv: parse2(reference, credentialEnv), origins };
|
|
@@ -11075,7 +11335,7 @@ class CredentialResolver {
|
|
|
11075
11335
|
return { credentialEnv: name, source: "vault", available: true, length: Number(match[1]), sha256: match[2], providerAuthentication: "not tested" };
|
|
11076
11336
|
}
|
|
11077
11337
|
const value = await this.keychainRead(binding.source);
|
|
11078
|
-
return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256:
|
|
11338
|
+
return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash10("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
|
|
11079
11339
|
}
|
|
11080
11340
|
}
|
|
11081
11341
|
var DELIVERY_URL = "SWITCHER_CREDENTIAL_DELIVERY_URL";
|
|
@@ -11145,9 +11405,9 @@ async function runVaultCommand(binding, args, env, delivery = {}, options = {})
|
|
|
11145
11405
|
if (process.platform === "win32")
|
|
11146
11406
|
throw new Fault(422, "vault_exec_unavailable", "Vault CLI bindings currently require POSIX process groups; use runtime environment injection on Windows.");
|
|
11147
11407
|
const executable = await validateVaultExecutable(binding.source.executable);
|
|
11148
|
-
const
|
|
11149
|
-
const childEnv = { ...
|
|
11150
|
-
return new Promise((resolveResult,
|
|
11408
|
+
const operator = options.operator ?? await resolveVaultOperatorEnvironment(binding, env);
|
|
11409
|
+
const childEnv = { ...operator.environment, ...delivery };
|
|
11410
|
+
return new Promise((resolveResult, reject) => {
|
|
11151
11411
|
const child = spawn(executable, args, { env: childEnv, stdio: ["ignore", options.captureBytes ? "pipe" : "ignore", "ignore"], detached: true, shell: false });
|
|
11152
11412
|
let failure;
|
|
11153
11413
|
let output = "";
|
|
@@ -11192,14 +11452,14 @@ async function runVaultCommand(binding, args, env, delivery = {}, options = {})
|
|
|
11192
11452
|
});
|
|
11193
11453
|
child.once("error", () => {
|
|
11194
11454
|
cleanup();
|
|
11195
|
-
|
|
11455
|
+
reject(new Fault(422, "vault_exec_failed", "The configured secrets CLI could not start; check its executable and permissions."));
|
|
11196
11456
|
});
|
|
11197
11457
|
child.once("exit", cleanup);
|
|
11198
11458
|
child.once("close", (code) => {
|
|
11199
11459
|
if (failure)
|
|
11200
|
-
|
|
11460
|
+
reject(failure);
|
|
11201
11461
|
else if (code !== 0)
|
|
11202
|
-
|
|
11462
|
+
reject(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."));
|
|
11203
11463
|
else
|
|
11204
11464
|
resolveResult(output);
|
|
11205
11465
|
});
|
|
@@ -11236,13 +11496,38 @@ async function fetchVaultCredential(binding, env) {
|
|
|
11236
11496
|
await broker.stop(true);
|
|
11237
11497
|
}
|
|
11238
11498
|
}
|
|
11239
|
-
|
|
11240
|
-
|
|
11241
|
-
|
|
11242
|
-
|
|
11243
|
-
|
|
11244
|
-
|
|
11245
|
-
|
|
11499
|
+
async function deliverVaultCredential() {
|
|
11500
|
+
const address = process.env[DELIVERY_URL];
|
|
11501
|
+
const nonce = process.env[DELIVERY_NONCE];
|
|
11502
|
+
const value = process.env[DELIVERY_VALUE];
|
|
11503
|
+
if (!address || !nonce || !value)
|
|
11504
|
+
throw new Fault(400, "credential_delivery_invalid", "Credential delivery requires an owned vault lookup.");
|
|
11505
|
+
let url;
|
|
11506
|
+
try {
|
|
11507
|
+
url = new URL(address);
|
|
11508
|
+
} catch {
|
|
11509
|
+
throw new Fault(400, "credential_delivery_invalid", "Invalid credential delivery address.");
|
|
11510
|
+
}
|
|
11511
|
+
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.pathname !== "/credential" || url.username || url.password || url.search || url.hash)
|
|
11512
|
+
throw new Fault(400, "credential_delivery_invalid", "Credential delivery is restricted to the owned loopback receiver.");
|
|
11513
|
+
try {
|
|
11514
|
+
const response = await fetch(url, { method: "POST", headers: { authorization: `Bearer ${nonce}`, "content-type": "application/json" }, body: JSON.stringify(value), redirect: "error", signal: AbortSignal.timeout(5000) });
|
|
11515
|
+
if (response.status !== 204)
|
|
11516
|
+
throw new Error;
|
|
11517
|
+
} catch {
|
|
11518
|
+
throw new Fault(422, "credential_delivery_failed", "The owned credential receiver was unavailable.");
|
|
11519
|
+
}
|
|
11520
|
+
}
|
|
11521
|
+
|
|
11522
|
+
// src/provider-credential-onboarding.ts
|
|
11523
|
+
var absent = (error) => error instanceof SwitcherError && error.status === 404;
|
|
11524
|
+
var secretMetadataSchema = z8.object({
|
|
11525
|
+
key: vaultKeySchema,
|
|
11526
|
+
type: z8.enum(["api_key", "password", "token", "credential", "other"]),
|
|
11527
|
+
label: z8.string().max(1000).nullable().optional(),
|
|
11528
|
+
expires_at: z8.string().max(200).nullable().optional(),
|
|
11529
|
+
created_at: z8.string().max(200),
|
|
11530
|
+
updated_at: z8.string().max(200)
|
|
11246
11531
|
}).strict();
|
|
11247
11532
|
var cleanDisplay = (value) => value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, "").slice(0, 500);
|
|
11248
11533
|
var credentialOrigins = (provider) => {
|
|
@@ -11272,7 +11557,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
|
|
|
11272
11557
|
await validateVaultExecutable(vaultExecutable);
|
|
11273
11558
|
const source = { kind: "vault", key: "switcher/provider-credential-discovery", executable: vaultExecutable, operator: { kind: "contracts" } };
|
|
11274
11559
|
const provisional = parse2(credentialBindingSchema, { schema: 1, credentialEnv: provider.credentialEnv, origins: credentialOrigins(provider), source });
|
|
11275
|
-
const
|
|
11560
|
+
const operator = await resolveVaultOperatorEnvironment(provisional, env);
|
|
11276
11561
|
const entries = new Map;
|
|
11277
11562
|
for (const query of searchTerms(provider)) {
|
|
11278
11563
|
const output = await runVaultCommand(provisional, ["search", query, "--json"], env, {}, {
|
|
@@ -11281,7 +11566,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
|
|
|
11281
11566
|
oversizeMessage: "Secrets returned too much credential metadata; narrow the vault naming or bind an exact key explicitly.",
|
|
11282
11567
|
lookupCode: "vault_search_failed",
|
|
11283
11568
|
lookupMessage: "Hasna Secrets could not search credential metadata. Check the selected vault/Keychain source; no alternate account was selected.",
|
|
11284
|
-
operator
|
|
11569
|
+
operator
|
|
11285
11570
|
});
|
|
11286
11571
|
let parsed;
|
|
11287
11572
|
try {
|
|
@@ -11297,7 +11582,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
|
|
|
11297
11582
|
if (entries.size > 256)
|
|
11298
11583
|
throw new Fault(422, "credential_matches_too_many", "More than 256 credential references matched. Bind an exact vault key explicitly.");
|
|
11299
11584
|
}
|
|
11300
|
-
return [...entries.values()].sort((a, b) => a.key.localeCompare(b.key)).map((entry) => ({ account:
|
|
11585
|
+
return [...entries.values()].sort((a, b) => a.key.localeCompare(b.key)).map((entry) => ({ account: operator.source, key: entry.key, url: operator.url, executable: vaultExecutable, operator: { kind: "contracts", expectedSource: operator.source, expectedTier: operator.tier } }));
|
|
11301
11586
|
}
|
|
11302
11587
|
async function selectVaultReference({ provider, matches }) {
|
|
11303
11588
|
if (!process.stdin.isTTY || !process.stderr.isTTY)
|
|
@@ -11371,7 +11656,7 @@ async function verifyProviderAuthentication({ provider, credential, fetch: fetch
|
|
|
11371
11656
|
throw new Fault(502, "provider_auth_unavailable", `Provider authentication check returned HTTP ${status}; the selected credential was not replaced.`);
|
|
11372
11657
|
}
|
|
11373
11658
|
function providerCredentialFingerprint(provider) {
|
|
11374
|
-
return
|
|
11659
|
+
return createHash11("sha256").update(JSON.stringify({
|
|
11375
11660
|
id: provider.id,
|
|
11376
11661
|
baseUrl: provider.baseUrl,
|
|
11377
11662
|
protocol: provider.protocol,
|
|
@@ -11402,10 +11687,10 @@ async function ensureProviderCredential(provider, options = {}) {
|
|
|
11402
11687
|
if (!credential) {
|
|
11403
11688
|
if (!(options.interactive ?? (process.stdin.isTTY && process.stderr.isTTY)))
|
|
11404
11689
|
throw new Fault(400, "credential_setup_required", `Provider credential setup is required. Run: ${providerCredentialSetupCommand(provider)}. Or provide ${provider.credentialEnv} in this launch process.`);
|
|
11405
|
-
const
|
|
11690
|
+
const discover = options.discoverVaultReferences ?? ((request) => discoverVaultReferences(request.provider, options.env ?? process.env, options.vaultExecutable));
|
|
11406
11691
|
let matches;
|
|
11407
11692
|
try {
|
|
11408
|
-
matches = await
|
|
11693
|
+
matches = await discover({ provider, credentialEnv: provider.credentialEnv });
|
|
11409
11694
|
} catch (error) {
|
|
11410
11695
|
if (error instanceof Fault && error.code === "vault_exec_unavailable")
|
|
11411
11696
|
throw new Fault(error.status, error.code, `${error.message} Run: ${providerCredentialSetupCommand(provider)} --vault-cli /absolute/path/to/secrets.`);
|
|
@@ -11435,30 +11720,57 @@ async function ensureProviderCredential(provider, options = {}) {
|
|
|
11435
11720
|
return preparedProviderCredential(provider, credential, { source: existing ? "binding" : "environment", configured, verified: false });
|
|
11436
11721
|
}
|
|
11437
11722
|
if (!result.authenticated)
|
|
11438
|
-
throw new Fault(401, "provider_credential_rejected", `The provider rejected the selected credential${result.status ? ` with HTTP ${result.status}` : ""}. No alternate account was selected.${configured ? ` To choose a different reference, run: switcher credentials remove ${provider.credentialEnv}.` : ""}`);
|
|
11723
|
+
throw new Fault(401, "provider_credential_rejected", `The provider rejected the selected credential${result.status ? ` with HTTP ${result.status}` : ""}. No alternate account was selected.${existing || configured ? ` To choose a different reference, run: switcher credentials remove ${provider.credentialEnv}.` : ""}`);
|
|
11439
11724
|
return preparedProviderCredential(provider, credential, { source: existing || configured ? "binding" : "environment", configured, verified: true });
|
|
11440
11725
|
}
|
|
11441
|
-
|
|
11442
|
-
|
|
11443
|
-
|
|
11444
|
-
|
|
11445
|
-
|
|
11446
|
-
|
|
11447
|
-
|
|
11448
|
-
|
|
11449
|
-
|
|
11450
|
-
|
|
11451
|
-
|
|
11726
|
+
function catalogRequiresCredential(provider) {
|
|
11727
|
+
if (provider.manualModels.length)
|
|
11728
|
+
return false;
|
|
11729
|
+
return (provider.catalogAuthStyle ?? provider.authStyle) !== "none" && Boolean(provider.catalogCredentialEnv ?? provider.credentialEnv);
|
|
11730
|
+
}
|
|
11731
|
+
async function launchCatalog(client, provider, dryRun = false, options = {}) {
|
|
11732
|
+
if (!dryRun && options.clientSide) {
|
|
11733
|
+
const origins = credentialOrigins(provider);
|
|
11734
|
+
const resolve = async (candidate) => {
|
|
11735
|
+
if (options.credential && candidate.credentialEnv === provider.credentialEnv && origins.includes(new URL(candidate.baseUrl).origin))
|
|
11736
|
+
return options.credential;
|
|
11737
|
+
return options.resolveCredential?.(candidate);
|
|
11738
|
+
};
|
|
11739
|
+
const catalog = await discover(provider, {}, resolve);
|
|
11740
|
+
return client.saveCatalog(provider.id, provider.version, catalog);
|
|
11452
11741
|
}
|
|
11453
|
-
if (
|
|
11454
|
-
|
|
11455
|
-
|
|
11456
|
-
|
|
11457
|
-
|
|
11458
|
-
|
|
11459
|
-
|
|
11460
|
-
|
|
11742
|
+
if (!dryRun || !catalogRequiresCredential(provider))
|
|
11743
|
+
return client.refreshModels(provider.id);
|
|
11744
|
+
const models = [];
|
|
11745
|
+
let offset = 0, refreshedAt, source, total;
|
|
11746
|
+
for (let pageNumber = 0;pageNumber < 10; pageNumber++) {
|
|
11747
|
+
let page;
|
|
11748
|
+
try {
|
|
11749
|
+
page = await client.listModels(provider.id, { limit: 1000, offset });
|
|
11750
|
+
} catch (error) {
|
|
11751
|
+
if (absent(error))
|
|
11752
|
+
throw new Fault(400, "dry_run_catalog_unavailable", `Dry-run will not retrieve provider credentials. Refresh ${provider.id} explicitly with switcher models ${provider.id} --refresh, then rerun the plan.`);
|
|
11753
|
+
throw error;
|
|
11754
|
+
}
|
|
11755
|
+
if (total === undefined) {
|
|
11756
|
+
total = page.total;
|
|
11757
|
+
refreshedAt = page.refreshedAt;
|
|
11758
|
+
source = page.source;
|
|
11759
|
+
} else if (total !== page.total || refreshedAt !== page.refreshedAt || source !== page.source)
|
|
11760
|
+
throw new Fault(409, "catalog_changed", "The cached catalog changed while the dry-run plan was being read; retry.");
|
|
11761
|
+
for (const row of page.data) {
|
|
11762
|
+
const { codingEligible: _codingEligible, expired: _expired, ...model } = row;
|
|
11763
|
+
models.push(model);
|
|
11764
|
+
}
|
|
11765
|
+
offset += page.data.length;
|
|
11766
|
+
if (offset >= page.total)
|
|
11767
|
+
break;
|
|
11768
|
+
if (!page.data.length)
|
|
11769
|
+
throw new Fault(502, "invalid_catalog", "The cached catalog page did not advance.");
|
|
11461
11770
|
}
|
|
11771
|
+
if (total === undefined || models.length !== total || !refreshedAt || !source)
|
|
11772
|
+
throw new Fault(502, "invalid_catalog", "The cached catalog exceeds the bounded dry-run reader or is incomplete.");
|
|
11773
|
+
return { models, refreshedAt, source };
|
|
11462
11774
|
}
|
|
11463
11775
|
|
|
11464
11776
|
// src/harness-process.ts
|
|
@@ -11490,7 +11802,7 @@ async function runHarnessProcess(options) {
|
|
|
11490
11802
|
const grouped = process.platform !== "win32", interactive = !options.silent && grouped && tty.some(Boolean);
|
|
11491
11803
|
const redirects = interactive ? tty.flatMap((value, index) => value ? [] : [index]) : [];
|
|
11492
11804
|
const duplicator = redirects.length ? await terminalDescriptorDuplicator() : undefined;
|
|
11493
|
-
return new Promise((resolveResult,
|
|
11805
|
+
return new Promise((resolveResult, reject) => {
|
|
11494
11806
|
const wasRaw = process.stdin.isRaw, wasFlowing = process.stdin.readableFlowing;
|
|
11495
11807
|
let controllingInput;
|
|
11496
11808
|
let inputTimer;
|
|
@@ -11529,12 +11841,12 @@ async function runHarnessProcess(options) {
|
|
|
11529
11841
|
cwd: options.cwd,
|
|
11530
11842
|
env: options.env,
|
|
11531
11843
|
stdio: ["inherit", "inherit", "inherit", ...duplicates],
|
|
11532
|
-
terminal: { cols, rows, name: options.env.TERM ?? "xterm-256color", data(_terminal,
|
|
11844
|
+
terminal: { cols, rows, name: options.env.TERM ?? "xterm-256color", data(_terminal, data) {
|
|
11533
11845
|
try {
|
|
11534
11846
|
if (output)
|
|
11535
|
-
output.write(
|
|
11847
|
+
output.write(data);
|
|
11536
11848
|
else if (controllingOutput !== undefined)
|
|
11537
|
-
writeSync(controllingOutput,
|
|
11849
|
+
writeSync(controllingOutput, data);
|
|
11538
11850
|
} catch {
|
|
11539
11851
|
failTerminal();
|
|
11540
11852
|
}
|
|
@@ -11689,7 +12001,7 @@ async function runHarnessProcess(options) {
|
|
|
11689
12001
|
};
|
|
11690
12002
|
child.once("error", () => {
|
|
11691
12003
|
cleanup();
|
|
11692
|
-
|
|
12004
|
+
reject(new Error("Harness process could not start; check executable and permissions."));
|
|
11693
12005
|
});
|
|
11694
12006
|
child.once("exit", async (code, signal) => {
|
|
11695
12007
|
if (timeout)
|
|
@@ -11698,13 +12010,13 @@ async function runHarnessProcess(options) {
|
|
|
11698
12010
|
signalGroup("SIGTERM");
|
|
11699
12011
|
const deadline = Date.now() + 5000;
|
|
11700
12012
|
while (groupExists() && Date.now() < deadline)
|
|
11701
|
-
await new Promise((
|
|
12013
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
11702
12014
|
if (groupExists())
|
|
11703
12015
|
signalGroup("SIGKILL");
|
|
11704
12016
|
}
|
|
11705
12017
|
cleanup();
|
|
11706
12018
|
if (terminalFailure) {
|
|
11707
|
-
|
|
12019
|
+
reject(terminalFailure);
|
|
11708
12020
|
return;
|
|
11709
12021
|
}
|
|
11710
12022
|
const exitCode = interruptionExitCode ?? code ?? (signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : signal === "SIGHUP" ? 129 : 137);
|
|
@@ -11841,14 +12153,14 @@ function parseHarnesses(stdout) {
|
|
|
11841
12153
|
return rows.flatMap((row) => {
|
|
11842
12154
|
if (!row || typeof row !== "object")
|
|
11843
12155
|
return [];
|
|
11844
|
-
const
|
|
11845
|
-
if (typeof
|
|
12156
|
+
const item = row;
|
|
12157
|
+
if (typeof item.kind !== "string" || typeof item.installed !== "boolean")
|
|
11846
12158
|
return [];
|
|
11847
12159
|
return [{
|
|
11848
|
-
kind:
|
|
11849
|
-
displayName: typeof
|
|
11850
|
-
installed:
|
|
11851
|
-
path: typeof
|
|
12160
|
+
kind: item.kind,
|
|
12161
|
+
displayName: typeof item.displayName === "string" ? item.displayName : undefined,
|
|
12162
|
+
installed: item.installed,
|
|
12163
|
+
path: typeof item.path === "string" ? item.path : undefined
|
|
11852
12164
|
}];
|
|
11853
12165
|
});
|
|
11854
12166
|
}
|
|
@@ -11896,16 +12208,16 @@ function requireOriHarness(contract, target) {
|
|
|
11896
12208
|
throw new OriBackendError("harness_unavailable", `Ori cannot launch ${target} because its native harness is not installed; no installer was started.`);
|
|
11897
12209
|
return row;
|
|
11898
12210
|
}
|
|
11899
|
-
function oriProvider(
|
|
11900
|
-
const provider = oriProviderCatalog.find((entry) => entry.id ===
|
|
12211
|
+
function oriProvider(id) {
|
|
12212
|
+
const provider = oriProviderCatalog.find((entry) => entry.id === id);
|
|
11901
12213
|
if (!provider)
|
|
11902
12214
|
throw new OriBackendError("provider_unsupported", "Ori supports OpenRouter only; use a direct Switcher adapter for this provider.");
|
|
11903
12215
|
return provider;
|
|
11904
12216
|
}
|
|
11905
12217
|
function assertProviderAuthority(target, provider, providerBaseUrl, protocol) {
|
|
11906
12218
|
const catalog = oriProvider("openrouter");
|
|
11907
|
-
const
|
|
11908
|
-
if (!providerBaseUrl || !protocol || !
|
|
12219
|
+
const compatible = target === "codex" ? protocol === "openai-responses" : target === "claude" ? protocol === "anthropic-messages" : catalog.protocols.includes(protocol);
|
|
12220
|
+
if (!providerBaseUrl || !protocol || !compatible)
|
|
11909
12221
|
throw new OriBackendError("provider_authority", "Ori requires an explicit OpenRouter provider URL and a protocol supported by the selected Ori target.");
|
|
11910
12222
|
let url;
|
|
11911
12223
|
try {
|
|
@@ -11986,7 +12298,7 @@ function oriLaunchWarnings(target) {
|
|
|
11986
12298
|
}
|
|
11987
12299
|
|
|
11988
12300
|
// src/chatgpt-launch.ts
|
|
11989
|
-
import { createHash as
|
|
12301
|
+
import { createHash as createHash12 } from "crypto";
|
|
11990
12302
|
import { writeFile as writeFile12, rm as rm4 } from "fs/promises";
|
|
11991
12303
|
import { join as join14 } from "path";
|
|
11992
12304
|
|
|
@@ -12048,7 +12360,7 @@ function merge2(base, overlay) {
|
|
|
12048
12360
|
result[key] = object5(value) && object5(result[key]) ? merge2(result[key], value) : value;
|
|
12049
12361
|
return result;
|
|
12050
12362
|
}
|
|
12051
|
-
var digest = (value) =>
|
|
12363
|
+
var digest = (value) => createHash12("sha256").update(value).digest("hex");
|
|
12052
12364
|
var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
12053
12365
|
async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
12054
12366
|
await privateDirectory(sessionDir);
|
|
@@ -12072,17 +12384,17 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
|
12072
12384
|
}
|
|
12073
12385
|
};
|
|
12074
12386
|
try {
|
|
12075
|
-
const
|
|
12387
|
+
const settings = [];
|
|
12076
12388
|
for (let i = 0;i < native.args.length; i += 2) {
|
|
12077
12389
|
if (native.args[i] !== "-c" || typeof native.args[i + 1] !== "string")
|
|
12078
12390
|
throw new Fault(400, "desktop_arguments", "Desktop launches accept provider/model settings, not native CLI commands.");
|
|
12079
|
-
|
|
12391
|
+
settings.push(native.args[i + 1]);
|
|
12080
12392
|
}
|
|
12081
|
-
|
|
12082
|
-
if (!
|
|
12083
|
-
|
|
12084
|
-
if (!
|
|
12085
|
-
|
|
12393
|
+
settings.push('cli_auth_credentials_store="file"', 'forced_login_method="api"');
|
|
12394
|
+
if (!settings.some((setting) => setting.startsWith("approval_policy=")))
|
|
12395
|
+
settings.push('approval_policy="on-request"');
|
|
12396
|
+
if (!settings.some((setting) => setting.startsWith("sandbox_mode=")))
|
|
12397
|
+
settings.push('sandbox_mode="workspace-write"');
|
|
12086
12398
|
const configPath = join14(home, "config.toml");
|
|
12087
12399
|
const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
|
|
12088
12400
|
if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
|
|
@@ -12094,7 +12406,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
|
12094
12406
|
if (error.code !== "ENOENT")
|
|
12095
12407
|
throw new Fault(422, "desktop_config_invalid", "The desktop profile config cannot be read safely.");
|
|
12096
12408
|
}
|
|
12097
|
-
const config = merge2(existing, Bun.TOML.parse(
|
|
12409
|
+
const config = merge2(existing, Bun.TOML.parse(settings.join(`
|
|
12098
12410
|
`)));
|
|
12099
12411
|
await writeDesktopPrivate(configPath, renderCodexAgentToml(config));
|
|
12100
12412
|
const key = native.env.SWITCHER_HARNESS_API_KEY;
|
|
@@ -12105,7 +12417,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
|
12105
12417
|
await writeDesktopPrivate(receiptPath, digest(authText));
|
|
12106
12418
|
await writeDesktopPrivate(authPath, authText);
|
|
12107
12419
|
const wrapper = join14(stateDir, "chatgpt-codex");
|
|
12108
|
-
const overrides =
|
|
12420
|
+
const overrides = settings.flatMap((setting) => ["-c", setting]);
|
|
12109
12421
|
await writeFile12(wrapper, `#!/bin/sh
|
|
12110
12422
|
set -eu
|
|
12111
12423
|
unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
|
|
@@ -12137,14 +12449,14 @@ exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
|
|
|
12137
12449
|
}
|
|
12138
12450
|
|
|
12139
12451
|
// src/claude-desktop-launch.ts
|
|
12140
|
-
import { createHash as
|
|
12452
|
+
import { createHash as createHash13 } from "crypto";
|
|
12141
12453
|
import { execFile as execFile5 } from "child_process";
|
|
12142
12454
|
import { access as access5, rm as rm5, writeFile as writeFile13 } from "fs/promises";
|
|
12143
12455
|
import { homedir as homedir8, userInfo as userInfo2 } from "os";
|
|
12144
12456
|
import { join as join15 } from "path";
|
|
12145
12457
|
import { promisify as promisify5 } from "util";
|
|
12146
12458
|
var execute4 = promisify5(execFile5);
|
|
12147
|
-
var hash2 = (text) =>
|
|
12459
|
+
var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
|
|
12148
12460
|
var claudeDesktopDataDirectory = () => join15(homedir8(), "Library/Application Support/Claude-3p");
|
|
12149
12461
|
async function assertAvailable(userData) {
|
|
12150
12462
|
for (const path of [join15("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
|
|
@@ -12164,7 +12476,7 @@ async function assertAvailable(userData) {
|
|
|
12164
12476
|
}
|
|
12165
12477
|
function metadata(text) {
|
|
12166
12478
|
const value = text === undefined ? { entries: [] } : JSON.parse(text);
|
|
12167
|
-
if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((
|
|
12479
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((item) => !item || typeof item !== "object" || Array.isArray(item)))
|
|
12168
12480
|
throw new Fault(422, "desktop_config_invalid", "Claude's configuration library metadata is invalid.");
|
|
12169
12481
|
return value;
|
|
12170
12482
|
}
|
|
@@ -12178,27 +12490,27 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12178
12490
|
if (version.length < 3 || version.some((n) => !Number.isSafeInteger(n)) || version[0] < 1 || version[0] === 1 && version[1] < 52386)
|
|
12179
12491
|
throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
|
|
12180
12492
|
const userData = system?.userData ?? claudeDesktopDataDirectory();
|
|
12181
|
-
const
|
|
12182
|
-
await
|
|
12493
|
+
const check = system?.assertAvailable ?? (() => assertAvailable(userData));
|
|
12494
|
+
await check();
|
|
12183
12495
|
await privateDirectory(userData);
|
|
12184
12496
|
const library = join15(userData, "configLibrary");
|
|
12185
12497
|
await privateDirectory(library);
|
|
12186
12498
|
const release = await desktopLease(join15(library, ".switcher-lease.sqlite"));
|
|
12187
12499
|
const metaPath = join15(library, "_meta.json"), receiptPath = join15(library, ".switcher-selection.json");
|
|
12188
12500
|
let receipt, gateway, closed = false;
|
|
12189
|
-
const restore = async (
|
|
12190
|
-
if (!/^[a-f0-9-]{36}$/.test(
|
|
12501
|
+
const restore = async (record) => {
|
|
12502
|
+
if (!/^[a-f0-9-]{36}$/.test(record.id) || typeof record.configHash !== "string" || typeof record.appliedMeta !== "string" || record.previousMeta !== null && typeof record.previousMeta !== "string")
|
|
12191
12503
|
throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
|
|
12192
|
-
const configPath = join15(library,
|
|
12193
|
-
if (current !== undefined && hash2(current) !==
|
|
12504
|
+
const configPath = join15(library, record.id + ".json"), current = await safeDesktopRead(configPath);
|
|
12505
|
+
if (current !== undefined && hash2(current) !== record.configHash)
|
|
12194
12506
|
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.");
|
|
12195
12507
|
const currentMeta = await safeDesktopRead(metaPath);
|
|
12196
|
-
if (currentMeta !==
|
|
12508
|
+
if (currentMeta !== record.appliedMeta && currentMeta !== (record.previousMeta ?? undefined))
|
|
12197
12509
|
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.");
|
|
12198
|
-
if (
|
|
12510
|
+
if (record.previousMeta === null)
|
|
12199
12511
|
await rm5(metaPath, { force: true });
|
|
12200
12512
|
else
|
|
12201
|
-
await writeDesktopPrivate(metaPath,
|
|
12513
|
+
await writeDesktopPrivate(metaPath, record.previousMeta);
|
|
12202
12514
|
await rm5(configPath, { force: true });
|
|
12203
12515
|
await rm5(receiptPath, { force: true });
|
|
12204
12516
|
};
|
|
@@ -12222,9 +12534,9 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12222
12534
|
if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
|
|
12223
12535
|
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.");
|
|
12224
12536
|
await privateDirectory(sessionDir);
|
|
12225
|
-
const
|
|
12226
|
-
const targets = { sonnet: input.model, opus:
|
|
12227
|
-
const aliases = Object.fromEntries(Object.entries(targets).map(([tier,
|
|
12537
|
+
const roles = input.modelPolicy?.roles;
|
|
12538
|
+
const targets = { sonnet: input.model, opus: roles?.planning ?? input.model, haiku: roles?.fast ?? input.model };
|
|
12539
|
+
const aliases = Object.fromEntries(Object.entries(targets).map(([tier, model]) => ["switcher/" + tier, model]));
|
|
12228
12540
|
for (const [alias, target] of Object.entries(aliases))
|
|
12229
12541
|
if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
|
|
12230
12542
|
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.");
|
|
@@ -12232,19 +12544,19 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12232
12544
|
const catalogPath = join15(input.stateDir, "claude-desktop-policy.json");
|
|
12233
12545
|
await writeFile13(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
|
|
12234
12546
|
gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
12235
|
-
const
|
|
12547
|
+
const id = crypto.randomUUID(), configPath = join15(library, id + ".json");
|
|
12236
12548
|
const config = JSON.stringify({
|
|
12237
12549
|
inferenceProvider: "gateway",
|
|
12238
12550
|
inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
|
|
12239
12551
|
inferenceGatewayApiKey: gateway.token,
|
|
12240
12552
|
inferenceGatewayAuthScheme: "bearer",
|
|
12241
12553
|
modelDiscoveryEnabled: false,
|
|
12242
|
-
inferenceModels: Object.entries(targets).map(([tier,
|
|
12554
|
+
inferenceModels: Object.entries(targets).map(([tier, model]) => ({ name: "switcher/" + tier, labelOverride: model, anthropicFamilyTier: tier, isFamilyDefault: true }))
|
|
12243
12555
|
});
|
|
12244
12556
|
const previousMeta = await safeDesktopRead(metaPath);
|
|
12245
12557
|
const meta = metadata(previousMeta);
|
|
12246
|
-
const appliedMeta = JSON.stringify({ ...meta, appliedId:
|
|
12247
|
-
receipt = { id
|
|
12558
|
+
const appliedMeta = JSON.stringify({ ...meta, appliedId: id, entries: [...meta.entries, { id, name: `Switcher: ${input.providerId ?? "provider"} / ${input.model}` }] });
|
|
12559
|
+
receipt = { id, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
|
|
12248
12560
|
await writeDesktopPrivate(configPath, config);
|
|
12249
12561
|
await writeDesktopPrivate(receiptPath, JSON.stringify(receipt));
|
|
12250
12562
|
await writeDesktopPrivate(metaPath, appliedMeta);
|
|
@@ -12253,7 +12565,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12253
12565
|
args: [],
|
|
12254
12566
|
env: { CLAUDE_CONFIG_DIR: sessionDir },
|
|
12255
12567
|
configPaths: [catalogPath, configPath],
|
|
12256
|
-
beforeLaunch:
|
|
12568
|
+
beforeLaunch: check,
|
|
12257
12569
|
cleanup,
|
|
12258
12570
|
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.`]
|
|
12259
12571
|
};
|
|
@@ -12269,8 +12581,8 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12269
12581
|
var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
|
|
12270
12582
|
async function writeOriCodexCatalog(stateDir, models) {
|
|
12271
12583
|
const path = join16(stateDir, "ori-codex-models.json");
|
|
12272
|
-
const
|
|
12273
|
-
await writeFile14(path, JSON.stringify({ models:
|
|
12584
|
+
const nativeModels = models.filter(codingEligible).map((model, index) => codexModel(model, index));
|
|
12585
|
+
await writeFile14(path, JSON.stringify({ models: nativeModels }, null, 2) + `
|
|
12274
12586
|
`, { mode: 384, flag: "wx" });
|
|
12275
12587
|
return path;
|
|
12276
12588
|
}
|
|
@@ -12330,7 +12642,7 @@ function buildOriRequest(plan, target, catalogPath, args) {
|
|
|
12330
12642
|
providerBaseUrl: plan.provider.baseUrl,
|
|
12331
12643
|
protocol: plan.provider.protocol,
|
|
12332
12644
|
model: plan.profile.model,
|
|
12333
|
-
catalog: { source: "switcher-openrouter", modelIds: plan.catalog.models.filter(codingEligible).map((
|
|
12645
|
+
catalog: { source: "switcher-openrouter", modelIds: plan.catalog.models.filter(codingEligible).map((model) => model.id), ...catalogPath ? { codexModelCatalogPath: catalogPath } : {} },
|
|
12334
12646
|
args
|
|
12335
12647
|
};
|
|
12336
12648
|
}
|
|
@@ -12453,8 +12765,8 @@ async function launch(client, profileId, options = {}) {
|
|
|
12453
12765
|
await client.finishRun(candidate.id, candidate.version, { ...body, routingEvents, routingEventsDropped }, crypto.randomUUID()).catch(() => console.error(message));
|
|
12454
12766
|
};
|
|
12455
12767
|
let cancelPreparation;
|
|
12456
|
-
const preparationCancellation = new Promise((_,
|
|
12457
|
-
cancelPreparation =
|
|
12768
|
+
const preparationCancellation = new Promise((_, reject) => {
|
|
12769
|
+
cancelPreparation = reject;
|
|
12458
12770
|
});
|
|
12459
12771
|
preparationCancellation.catch(() => {
|
|
12460
12772
|
return;
|
|
@@ -12506,8 +12818,8 @@ async function launch(client, profileId, options = {}) {
|
|
|
12506
12818
|
return;
|
|
12507
12819
|
preparationSignal = error;
|
|
12508
12820
|
createRunCancelled = true;
|
|
12509
|
-
preparationCleanup ??= cleanup?.().catch((
|
|
12510
|
-
console.error(`switcher: Could not clean up the interrupted launch: ${
|
|
12821
|
+
preparationCleanup ??= cleanup?.().catch((error) => {
|
|
12822
|
+
console.error(`switcher: Could not clean up the interrupted launch: ${error instanceof Error ? error.message : "unknown cleanup failure"}.`);
|
|
12511
12823
|
});
|
|
12512
12824
|
if (cancel)
|
|
12513
12825
|
cancelPreparation(preparationSignal);
|
|
@@ -12590,8 +12902,8 @@ async function launch(client, profileId, options = {}) {
|
|
|
12590
12902
|
} finally {
|
|
12591
12903
|
if (lateCreateRunFinalization) {
|
|
12592
12904
|
let finalizationTimer;
|
|
12593
|
-
const finalizationTimeout = new Promise((
|
|
12594
|
-
finalizationTimer = setTimeout(
|
|
12905
|
+
const finalizationTimeout = new Promise((resolve) => {
|
|
12906
|
+
finalizationTimer = setTimeout(resolve, LATE_RUN_FINALIZATION_TIMEOUT_MS);
|
|
12595
12907
|
});
|
|
12596
12908
|
try {
|
|
12597
12909
|
await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
|
|
@@ -12610,15 +12922,15 @@ async function launch(client, profileId, options = {}) {
|
|
|
12610
12922
|
}
|
|
12611
12923
|
|
|
12612
12924
|
// src/direct-launch.ts
|
|
12613
|
-
import { createHash as
|
|
12925
|
+
import { createHash as createHash14 } from "crypto";
|
|
12614
12926
|
import { createInterface as createInterface2 } from "readline/promises";
|
|
12615
|
-
var
|
|
12927
|
+
var absent2 = (error) => error instanceof SwitcherError && error.status === 404;
|
|
12616
12928
|
async function resolveLaunchProvider(client, selector, options = {}) {
|
|
12617
12929
|
let existing;
|
|
12618
12930
|
try {
|
|
12619
12931
|
existing = await client.getProvider(selector);
|
|
12620
12932
|
} catch (error) {
|
|
12621
|
-
if (!
|
|
12933
|
+
if (!absent2(error))
|
|
12622
12934
|
throw error;
|
|
12623
12935
|
}
|
|
12624
12936
|
if (existing) {
|
|
@@ -12630,7 +12942,7 @@ async function resolveLaunchProvider(client, selector, options = {}) {
|
|
|
12630
12942
|
try {
|
|
12631
12943
|
existing = await client.getProvider(desired.id);
|
|
12632
12944
|
} catch (error) {
|
|
12633
|
-
if (!
|
|
12945
|
+
if (!absent2(error))
|
|
12634
12946
|
throw error;
|
|
12635
12947
|
}
|
|
12636
12948
|
if (!existing) {
|
|
@@ -12649,45 +12961,6 @@ async function resolveLaunchProvider(client, selector, options = {}) {
|
|
|
12649
12961
|
throw new Fault(409, "provider_conflict", "A saved provider with this preset ID has different settings. Select its ID directly or update it explicitly.");
|
|
12650
12962
|
return existing;
|
|
12651
12963
|
}
|
|
12652
|
-
function catalogRequiresCredential(provider) {
|
|
12653
|
-
if (provider.manualModels.length)
|
|
12654
|
-
return false;
|
|
12655
|
-
return (provider.catalogAuthStyle ?? provider.authStyle) !== "none" && Boolean(provider.catalogCredentialEnv ?? provider.credentialEnv);
|
|
12656
|
-
}
|
|
12657
|
-
async function launchCatalog(client, provider, dryRun = false) {
|
|
12658
|
-
if (!dryRun || !catalogRequiresCredential(provider))
|
|
12659
|
-
return client.refreshModels(provider.id);
|
|
12660
|
-
const models = [];
|
|
12661
|
-
let offset = 0, refreshedAt, source, total;
|
|
12662
|
-
for (let pageNumber = 0;pageNumber < 10; pageNumber++) {
|
|
12663
|
-
let page;
|
|
12664
|
-
try {
|
|
12665
|
-
page = await client.listModels(provider.id, { limit: 1000, offset });
|
|
12666
|
-
} catch (error) {
|
|
12667
|
-
if (absent(error))
|
|
12668
|
-
throw new Fault(400, "dry_run_catalog_unavailable", `Dry-run will not retrieve provider credentials. Refresh ${provider.id} explicitly with switcher models ${provider.id} --refresh, then rerun the plan.`);
|
|
12669
|
-
throw error;
|
|
12670
|
-
}
|
|
12671
|
-
if (total === undefined) {
|
|
12672
|
-
total = page.total;
|
|
12673
|
-
refreshedAt = page.refreshedAt;
|
|
12674
|
-
source = page.source;
|
|
12675
|
-
} else if (total !== page.total || refreshedAt !== page.refreshedAt || source !== page.source)
|
|
12676
|
-
throw new Fault(409, "catalog_changed", "The cached catalog changed while the dry-run plan was being read; retry.");
|
|
12677
|
-
for (const row of page.data) {
|
|
12678
|
-
const { codingEligible: _codingEligible, expired: _expired, ...model3 } = row;
|
|
12679
|
-
models.push(model3);
|
|
12680
|
-
}
|
|
12681
|
-
offset += page.data.length;
|
|
12682
|
-
if (offset >= page.total)
|
|
12683
|
-
break;
|
|
12684
|
-
if (!page.data.length)
|
|
12685
|
-
throw new Fault(502, "invalid_catalog", "The cached catalog page did not advance.");
|
|
12686
|
-
}
|
|
12687
|
-
if (total === undefined || models.length !== total || !refreshedAt || !source)
|
|
12688
|
-
throw new Fault(502, "invalid_catalog", "The cached catalog exceeds the bounded dry-run reader or is incomplete.");
|
|
12689
|
-
return { models, refreshedAt, source };
|
|
12690
|
-
}
|
|
12691
12964
|
var display = (value) => value.replace(/[\x00-\x1f\x7f-\x9f]/g, "");
|
|
12692
12965
|
async function selectModel(models, query = "", harness) {
|
|
12693
12966
|
if (!process.stdin.isTTY || !process.stderr.isTTY)
|
|
@@ -12726,16 +12999,16 @@ async function selectModel(models, query = "", harness) {
|
|
|
12726
12999
|
reader.close();
|
|
12727
13000
|
}
|
|
12728
13001
|
}
|
|
12729
|
-
async function ensureLaunchProfile(client, provider, harness,
|
|
13002
|
+
async function ensureLaunchProfile(client, provider, harness, model, modelPolicy) {
|
|
12730
13003
|
const normalizedPolicy = modelPolicy === undefined ? undefined : parse2(modelPolicySchema, modelPolicy);
|
|
12731
|
-
const identity = normalizedPolicy === undefined ? [provider.id, harness,
|
|
12732
|
-
const
|
|
12733
|
-
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${
|
|
13004
|
+
const identity = normalizedPolicy === undefined ? [provider.id, harness, model] : [provider.id, harness, model, normalizedPolicy];
|
|
13005
|
+
const hash = createHash14("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
|
|
13006
|
+
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash}`, name: `${harness}: ${model}`.slice(0, 200), providerId: provider.id, harness, model, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
|
|
12734
13007
|
let existing;
|
|
12735
13008
|
try {
|
|
12736
13009
|
existing = await client.getProfile(desired.id);
|
|
12737
13010
|
} catch (error) {
|
|
12738
|
-
if (!
|
|
13011
|
+
if (!absent2(error))
|
|
12739
13012
|
throw error;
|
|
12740
13013
|
}
|
|
12741
13014
|
if (!existing) {
|
|
@@ -12747,7 +13020,7 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
12747
13020
|
existing = await client.getProfile(desired.id);
|
|
12748
13021
|
}
|
|
12749
13022
|
}
|
|
12750
|
-
if (existing.providerId !== desired.providerId || existing.harness !== harness || existing.model !==
|
|
13023
|
+
if (existing.providerId !== desired.providerId || existing.harness !== harness || existing.model !== model || canonicalPolicyJSON(existing.modelPolicy ?? null) !== canonicalPolicyJSON(desired.modelPolicy ?? null))
|
|
12751
13024
|
throw new Fault(409, "profile_conflict", "An existing launch profile has different settings. Select a saved profile explicitly.");
|
|
12752
13025
|
return existing;
|
|
12753
13026
|
}
|
|
@@ -12847,28 +13120,28 @@ async function readModelPolicy(file, roleValues) {
|
|
|
12847
13120
|
return parse2(modelPolicySchema, await readInput(file));
|
|
12848
13121
|
if (!roleValues?.length)
|
|
12849
13122
|
return;
|
|
12850
|
-
const
|
|
13123
|
+
const roles = {};
|
|
12851
13124
|
const valid = new Set(["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"]);
|
|
12852
|
-
for (const
|
|
12853
|
-
const split =
|
|
12854
|
-
if (split <= 0 || split ===
|
|
13125
|
+
for (const item of roleValues) {
|
|
13126
|
+
const split = item.indexOf("=");
|
|
13127
|
+
if (split <= 0 || split === item.length - 1)
|
|
12855
13128
|
throw new Fault(400, "invalid_request", "Each --role-model must use ROLE=MODEL.");
|
|
12856
|
-
const role =
|
|
12857
|
-
const
|
|
13129
|
+
const role = item.slice(0, split);
|
|
13130
|
+
const model = item.slice(split + 1);
|
|
12858
13131
|
if (!valid.has(role))
|
|
12859
13132
|
throw new Fault(400, "invalid_request", `Unknown model policy role: ${role}.`);
|
|
12860
|
-
if (
|
|
13133
|
+
if (roles[role] !== undefined)
|
|
12861
13134
|
throw new Fault(400, "conflicting_options", `Duplicate model policy role: ${role}.`);
|
|
12862
|
-
|
|
13135
|
+
roles[role] = model;
|
|
12863
13136
|
}
|
|
12864
|
-
return parse2(modelPolicySchema, { version: 1, roles
|
|
13137
|
+
return parse2(modelPolicySchema, { version: 1, roles });
|
|
12865
13138
|
}
|
|
12866
13139
|
async function main(args = process.argv.slice(2)) {
|
|
12867
13140
|
if (args.length === 1 && args[0] === "__credential-delivery")
|
|
12868
13141
|
return deliverVaultCredential();
|
|
12869
13142
|
const split = args.indexOf("--");
|
|
12870
13143
|
const nativeArgs = split >= 0 ? args.slice(split + 1) : [];
|
|
12871
|
-
const { values
|
|
13144
|
+
const { values, positionals } = parseArgs({ args: split >= 0 ? args.slice(0, split) : args, allowPositionals: true, options: {
|
|
12872
13145
|
help: { type: "boolean" },
|
|
12873
13146
|
version: { type: "string" },
|
|
12874
13147
|
json: { type: "boolean" },
|
|
@@ -12916,160 +13189,167 @@ async function main(args = process.argv.slice(2)) {
|
|
|
12916
13189
|
"keychain-account": { type: "string" },
|
|
12917
13190
|
origin: { type: "string", multiple: true }
|
|
12918
13191
|
} });
|
|
12919
|
-
if (
|
|
13192
|
+
if (values.help || !positionals.length) {
|
|
12920
13193
|
console.log(HELP);
|
|
12921
13194
|
return;
|
|
12922
13195
|
}
|
|
12923
|
-
const [command,
|
|
13196
|
+
const [command, action, id] = positionals;
|
|
12924
13197
|
const output = (value) => console.log(JSON.stringify(value, null, 2));
|
|
12925
|
-
const reasoning =
|
|
12926
|
-
const dangerouslyBypassApprovalsAndSandbox =
|
|
12927
|
-
if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" ||
|
|
13198
|
+
const reasoning = values.reasoning === undefined ? undefined : parse2(reasoningEffortSchema, values.reasoning);
|
|
13199
|
+
const dangerouslyBypassApprovalsAndSandbox = values["dangerously-bypass-approvals-and-sandbox"];
|
|
13200
|
+
if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" || values.provider && !["chatgpt", "codex"].includes(action) || values.backend && values.backend !== "direct"))
|
|
12928
13201
|
throw new Fault(400, "conflicting_options", "--reasoning and --dangerously-bypass-approvals-and-sandbox require a direct Codex or ChatGPT launch.");
|
|
12929
|
-
const chatgpt = command === "launch" &&
|
|
12930
|
-
const claudeDesktop = command === "launch" &&
|
|
12931
|
-
if (
|
|
13202
|
+
const chatgpt = command === "launch" && action === "chatgpt" && values.provider !== undefined;
|
|
13203
|
+
const claudeDesktop = command === "launch" && action === "claude-desktop" && values.provider !== undefined;
|
|
13204
|
+
if (values["app-path"] !== undefined && !chatgpt && !claudeDesktop)
|
|
12932
13205
|
throw new Fault(400, "conflicting_options", "--app-path belongs to launch chatgpt or claude-desktop --provider PROVIDER --model MODEL.");
|
|
12933
|
-
if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 ||
|
|
13206
|
+
if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 || values.executable !== undefined || values.backend !== undefined || values["ori-executable"] !== undefined))
|
|
12934
13207
|
throw new Fault(400, "conflicting_options", "Desktop apps use their own runtime; native CLI arguments, --executable and --backend are not accepted.");
|
|
12935
|
-
const desktop = chatgpt ? await detectChatGPTApp(
|
|
12936
|
-
const claudeApp = claudeDesktop ? await detectClaudeDesktopApp(
|
|
13208
|
+
const desktop = chatgpt ? await detectChatGPTApp(values["app-path"]) : undefined;
|
|
13209
|
+
const claudeApp = claudeDesktop ? await detectClaudeDesktopApp(values["app-path"]) : undefined;
|
|
12937
13210
|
if (!["doctor", "launch", "models", "runs", "providers", "profiles", "credentials"].includes(command))
|
|
12938
13211
|
throw new Error("Unknown command. Run switcher --help.");
|
|
12939
13212
|
const providerFlags = ["url", "protocol", "preset", "credential-env", "auth-style", "catalog-url", "catalog-format", "catalog-auth-style", "catalog-credential-env", "catalog-account-id", "models-path"];
|
|
12940
|
-
const provided = (names) => names.some((name) =>
|
|
12941
|
-
const editingModel = command === "models" && positionals.length > 2 && ["add", "update", "remove"].includes(
|
|
12942
|
-
const configuringModels = command === "models" && positionals.length > 2 &&
|
|
12943
|
-
const listingModels = command === "models" && positionals.length > 2 &&
|
|
12944
|
-
if (listingModels && (positionals.length !== 3 || nativeArgs.length || Object.keys(
|
|
13213
|
+
const provided = (names) => names.some((name) => values[name] !== undefined);
|
|
13214
|
+
const editingModel = command === "models" && positionals.length > 2 && ["add", "update", "remove"].includes(action);
|
|
13215
|
+
const configuringModels = command === "models" && positionals.length > 2 && action === "config";
|
|
13216
|
+
const listingModels = command === "models" && positionals.length > 2 && action === "list";
|
|
13217
|
+
if (listingModels && (positionals.length !== 3 || nativeArgs.length || Object.keys(values).some((name) => !["refresh", "search", "limit", "offset", "json"].includes(name))))
|
|
12945
13218
|
throw new Fault(400, "invalid_request", "Use models list PROVIDER with optional --refresh, --search, --limit and --offset.");
|
|
12946
|
-
if (
|
|
13219
|
+
if (values["expires-on"] !== undefined && (!editingModel || action === "remove"))
|
|
12947
13220
|
throw new Fault(400, "conflicting_options", "--expires-on belongs to models add/update.");
|
|
12948
|
-
if (editingModel && (positionals.length !== 4 || nativeArgs.length || Object.keys(
|
|
13221
|
+
if (editingModel && (positionals.length !== 4 || nativeArgs.length || Object.keys(values).some((name) => !(action === "remove" ? ["json"] : ["name", "expires-on", "file", "json"]).includes(name))))
|
|
12949
13222
|
throw new Fault(400, "invalid_request", "Use models add/update PROVIDER MODEL with --file or --name/--expires-on; models remove accepts only PROVIDER MODEL.");
|
|
12950
|
-
if (configuringModels && (positionals.length !== 3 || nativeArgs.length || Object.keys(
|
|
13223
|
+
if (configuringModels && (positionals.length !== 3 || nativeArgs.length || Object.keys(values).some((name) => name !== "json")))
|
|
12951
13224
|
throw new Fault(400, "invalid_request", "Use models config PROVIDER without other settings.");
|
|
12952
|
-
if (editingModel &&
|
|
13225
|
+
if (editingModel && values.file !== undefined && (values.name !== undefined || values["expires-on"] !== undefined))
|
|
12953
13226
|
throw new Fault(400, "conflicting_options", "Use --file by itself for model metadata.");
|
|
12954
|
-
const modelInput = editingModel &&
|
|
13227
|
+
const modelInput = editingModel && action !== "remove" ? parse2(modelSchema, values.file !== undefined ? await readInput(values.file) : { id: positionals[3], name: values.name ?? positionals[3], expiresOn: values["expires-on"] }) : undefined;
|
|
12955
13228
|
if (modelInput && modelInput.id !== positionals[3])
|
|
12956
13229
|
throw new Fault(400, "id_mismatch", "Model file id must match the command model ID.");
|
|
12957
|
-
if (editingModel &&
|
|
13230
|
+
if (editingModel && action === "remove")
|
|
12958
13231
|
parse2(modelSchema.shape.id, positionals[3]);
|
|
12959
|
-
const seedingProvider = command === "providers" &&
|
|
12960
|
-
if (
|
|
13232
|
+
const seedingProvider = command === "providers" && action === "add";
|
|
13233
|
+
if (values["models-file"] !== undefined && !seedingProvider)
|
|
12961
13234
|
throw new Fault(400, "conflicting_options", "--models-file belongs to providers add.");
|
|
12962
|
-
if (command === "providers" &&
|
|
13235
|
+
if (command === "providers" && values.model !== undefined && !seedingProvider)
|
|
12963
13236
|
throw new Fault(400, "conflicting_options", "Provider --model belongs to providers add. Use models add/update/remove for saved providers.");
|
|
12964
|
-
if (seedingProvider &&
|
|
13237
|
+
if (seedingProvider && values["models-file"] !== undefined && values.model !== undefined)
|
|
12965
13238
|
throw new Fault(400, "conflicting_options", "Use --model or --models-file, not both.");
|
|
12966
13239
|
let starterModels;
|
|
12967
|
-
if (seedingProvider && (
|
|
12968
|
-
starterModels = parse2(modelSchema.array().min(1).max(1e4),
|
|
12969
|
-
if (new Set(starterModels.map((
|
|
13240
|
+
if (seedingProvider && (values.model !== undefined || values["models-file"] !== undefined)) {
|
|
13241
|
+
starterModels = parse2(modelSchema.array().min(1).max(1e4), values["models-file"] !== undefined ? await readInput(values["models-file"]) : [{ id: values.model, name: values.model }]);
|
|
13242
|
+
if (new Set(starterModels.map((model) => model.id)).size !== starterModels.length)
|
|
12970
13243
|
throw new Fault(400, "duplicate_model", "Model IDs must be unique.");
|
|
12971
13244
|
}
|
|
12972
13245
|
const credentialFlags = ["vault-key", "vault-url", "vault-cli", "vault-account", "vault-operator", "keychain-service", "keychain-account", "origin"];
|
|
12973
13246
|
const credentials = new CredentialResolver;
|
|
12974
|
-
if (
|
|
13247
|
+
if (values.sha256 !== undefined && !(command === "credentials" && action === "repair-executable"))
|
|
12975
13248
|
throw new Fault(400, "conflicting_options", "--sha256 belongs to credentials repair-executable.");
|
|
12976
13249
|
if (command === "credentials") {
|
|
12977
|
-
if (
|
|
12978
|
-
const explicitPath =
|
|
12979
|
-
if (Boolean(
|
|
13250
|
+
if (action === "repair-executable") {
|
|
13251
|
+
const explicitPath = values["vault-cli"];
|
|
13252
|
+
if (Boolean(id) === (explicitPath !== undefined) || positionals.length !== (id ? 3 : 2) || nativeArgs.length || Object.keys(values).some((name) => !["sha256", "json", "vault-cli"].includes(name)) || !/^[a-f0-9]{64}$/.test(values.sha256 ?? ""))
|
|
12980
13253
|
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.");
|
|
12981
13254
|
let executable = explicitPath;
|
|
12982
|
-
if (
|
|
12983
|
-
const binding = await credentials.bindings.get(credentialReference(
|
|
13255
|
+
if (id) {
|
|
13256
|
+
const binding = await credentials.bindings.get(credentialReference(id));
|
|
12984
13257
|
if (!binding || binding.source.kind !== "vault")
|
|
12985
13258
|
throw new Fault(422, "vault_binding_required", "Choose an existing vault credential binding to repair its configured executable.");
|
|
12986
13259
|
executable = binding.source.executable;
|
|
12987
13260
|
}
|
|
12988
|
-
output(await repairVaultExecutablePermissions(executable,
|
|
13261
|
+
output(await repairVaultExecutablePermissions(executable, values.sha256));
|
|
12989
13262
|
return;
|
|
12990
13263
|
}
|
|
12991
13264
|
const bindingFlags = [...credentialFlags, "credential-env"];
|
|
12992
|
-
if (nativeArgs.length || positionals.length > 3 || Object.keys(
|
|
13265
|
+
if (nativeArgs.length || positionals.length > 3 || Object.keys(values).some((name) => name !== "json" && !bindingFlags.includes(name)))
|
|
12993
13266
|
throw new Fault(400, "conflicting_options", "Credentials accepts only binding options; no API, profile or harness settings.");
|
|
12994
|
-
if (
|
|
13267
|
+
if (action !== "bind" && provided(bindingFlags))
|
|
12995
13268
|
throw new Fault(400, "conflicting_options", "Credential source and origin options belong to credentials bind.");
|
|
12996
|
-
if (
|
|
13269
|
+
if (action === "list" && !id) {
|
|
12997
13270
|
output(await credentials.bindings.list());
|
|
12998
13271
|
return;
|
|
12999
13272
|
}
|
|
13000
|
-
if (
|
|
13001
|
-
output(await credentials.bindings.remove(credentialReference(
|
|
13273
|
+
if (action === "remove" && id) {
|
|
13274
|
+
output(await credentials.bindings.remove(credentialReference(id)));
|
|
13002
13275
|
return;
|
|
13003
13276
|
}
|
|
13004
|
-
if (
|
|
13005
|
-
output(await credentials.check(credentialReference(
|
|
13277
|
+
if (action === "check" && id) {
|
|
13278
|
+
output(await credentials.check(credentialReference(id)));
|
|
13006
13279
|
return;
|
|
13007
13280
|
}
|
|
13008
|
-
if (
|
|
13281
|
+
if (action !== "bind" || !id)
|
|
13009
13282
|
throw new Fault(400, "invalid_request", "Use credentials bind PRESET, list, check PRESET_OR_REFERENCE, or remove PRESET_OR_REFERENCE.");
|
|
13010
13283
|
const hasVault = provided(["vault-key", "vault-url", "vault-cli", "vault-account", "vault-operator"]);
|
|
13011
13284
|
const hasKeychain = provided(["keychain-service", "keychain-account"]);
|
|
13012
13285
|
if (hasVault === hasKeychain)
|
|
13013
13286
|
throw new Fault(400, "conflicting_options", "Choose one credential source: vault or Keychain.");
|
|
13014
|
-
if (
|
|
13287
|
+
if (values["vault-operator"] !== undefined && !["contracts", "env"].includes(values["vault-operator"]))
|
|
13015
13288
|
throw new Fault(400, "invalid_request", "Use --vault-operator contracts or env.");
|
|
13016
|
-
if (
|
|
13289
|
+
if (values["vault-account"] !== undefined && values["vault-operator"] !== undefined)
|
|
13017
13290
|
throw new Fault(400, "conflicting_options", "Use either --vault-account or --vault-operator.");
|
|
13018
13291
|
const source = hasVault ? {
|
|
13019
13292
|
kind: "vault",
|
|
13020
|
-
key:
|
|
13021
|
-
url:
|
|
13022
|
-
executable:
|
|
13023
|
-
operator:
|
|
13024
|
-
} : { kind: "keychain", service:
|
|
13025
|
-
output(await credentials.bindings.bind(parse2(credentialBindingSchema, { schema: 1, ...bindingTarget(
|
|
13293
|
+
key: values["vault-key"],
|
|
13294
|
+
url: values["vault-url"],
|
|
13295
|
+
executable: values["vault-cli"] ?? Bun.which("secrets"),
|
|
13296
|
+
operator: values["vault-account"] !== undefined ? { kind: "keychain", account: values["vault-account"] } : { kind: values["vault-operator"] ?? "contracts" }
|
|
13297
|
+
} : { kind: "keychain", service: values["keychain-service"], account: values["keychain-account"] };
|
|
13298
|
+
output(await credentials.bindings.bind(parse2(credentialBindingSchema, { schema: 1, ...bindingTarget(id, values["credential-env"], values.origin), source })));
|
|
13026
13299
|
return;
|
|
13027
13300
|
}
|
|
13028
13301
|
if (provided(credentialFlags))
|
|
13029
13302
|
throw new Fault(400, "conflicting_options", "Credential source and origin options belong to credentials bind.");
|
|
13030
|
-
const backend =
|
|
13303
|
+
const backend = values.backend ?? "direct";
|
|
13031
13304
|
if (backend !== "direct" && backend !== "ori")
|
|
13032
13305
|
throw new Fault(400, "invalid_backend", "Use --backend direct or --backend ori.");
|
|
13033
|
-
if (command !== "launch" && (
|
|
13306
|
+
if (command !== "launch" && (values.backend !== undefined || values["ori-executable"] !== undefined))
|
|
13034
13307
|
throw new Fault(400, "conflicting_options", "--backend and --ori-executable belong to launch.");
|
|
13035
|
-
if (command === "launch" && backend === "ori" &&
|
|
13308
|
+
if (command === "launch" && backend === "ori" && values.executable !== undefined)
|
|
13036
13309
|
throw new Fault(400, "conflicting_options", "--executable is ambiguous with --backend ori; use --ori-executable PATH.");
|
|
13037
|
-
if (command === "launch" && backend === "direct" &&
|
|
13310
|
+
if (command === "launch" && backend === "direct" && values["ori-executable"] !== undefined)
|
|
13038
13311
|
throw new Fault(400, "conflicting_options", "--ori-executable requires --backend ori.");
|
|
13039
|
-
const mutation = (command === "providers" || command === "profiles") && ["add", "update"].includes(
|
|
13040
|
-
if (
|
|
13312
|
+
const mutation = (command === "providers" || command === "profiles") && ["add", "update"].includes(action);
|
|
13313
|
+
if (values.file && !editingModel && (!mutation || provided([...providerFlags, "name", "provider", "harness", "model", "models-file", "model-policy-file", "role-model"])))
|
|
13041
13314
|
throw new Fault(400, "conflicting_options", "Use --file by itself for provider/profile settings; inline settings cannot override an input file.");
|
|
13042
|
-
if (command === "launch" && !
|
|
13315
|
+
if (command === "launch" && !values.provider && provided([...providerFlags, "name", "harness", "model", "search", "model-policy-file", "role-model"]))
|
|
13043
13316
|
throw new Fault(400, "conflicting_options", "Use --provider PROVIDER for direct launch settings, or update the saved profile explicitly.");
|
|
13044
|
-
if (
|
|
13317
|
+
if (values.preset && !(command === "providers" && mutation))
|
|
13045
13318
|
throw new Fault(400, "conflicting_options", "--preset belongs to providers add/update. For direct launches use --provider PRESET.");
|
|
13046
|
-
if (
|
|
13319
|
+
if (values.refresh && command !== "models")
|
|
13047
13320
|
throw new Fault(400, "conflicting_options", "--refresh belongs to models. Launch always discovers a fresh catalog.");
|
|
13048
|
-
if (
|
|
13321
|
+
if (values["dry-run"] && command !== "launch")
|
|
13049
13322
|
throw new Fault(400, "conflicting_options", "--dry-run belongs to launch.");
|
|
13050
13323
|
if (command === "launch" && provided(["name", "harness", "file"]))
|
|
13051
13324
|
throw new Fault(400, "conflicting_options", "Launch takes its harness from the positional argument or saved profile; edit named records through providers/profiles.");
|
|
13052
|
-
if (command === "launch" &&
|
|
13053
|
-
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" :
|
|
13325
|
+
if (command === "launch" && values.provider) {
|
|
13326
|
+
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action);
|
|
13054
13327
|
assertHarnessArguments(harness, nativeArgs);
|
|
13055
|
-
await validateHarnessConfiguration(harness,
|
|
13328
|
+
await validateHarnessConfiguration(harness, values.cwd ?? process.cwd(), nativeArgs);
|
|
13056
13329
|
}
|
|
13057
|
-
const dryLaunch = command === "launch" && Boolean(
|
|
13330
|
+
const dryLaunch = command === "launch" && Boolean(values["dry-run"]);
|
|
13058
13331
|
const runtimeEnvironment = dryLaunch ? Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("SWITCHER_PROVIDER_"))) : process.env;
|
|
13059
13332
|
const runtime = await openCliRuntime(runtimeEnvironment, dryLaunch ? undefined : (provider) => credentials.resolve(provider));
|
|
13060
13333
|
const client = runtime.client;
|
|
13334
|
+
const refreshCatalog = async (provider, prepared) => {
|
|
13335
|
+
if (runtime.mode !== "remote")
|
|
13336
|
+
return client.refreshModels(provider.id);
|
|
13337
|
+
const checked = prepared ?? await ensureProviderCredential(provider, { resolver: credentials });
|
|
13338
|
+
const credential = await checked.resolveCredential(provider);
|
|
13339
|
+
return launchCatalog(client, provider, false, { clientSide: true, credential, resolveCredential: (candidate) => credentials.resolve(candidate) });
|
|
13340
|
+
};
|
|
13061
13341
|
try {
|
|
13062
13342
|
const presetOptions = () => ({
|
|
13063
|
-
protocol:
|
|
13064
|
-
baseUrl:
|
|
13065
|
-
credentialEnv:
|
|
13066
|
-
authStyle:
|
|
13067
|
-
catalogBaseUrl:
|
|
13068
|
-
catalogCredentialEnv:
|
|
13069
|
-
catalogAuthStyle:
|
|
13070
|
-
catalogFormat:
|
|
13071
|
-
catalogAccountId:
|
|
13072
|
-
modelsPath:
|
|
13343
|
+
protocol: values.protocol ? parse2(protocolSchema, values.protocol) : undefined,
|
|
13344
|
+
baseUrl: values.url,
|
|
13345
|
+
credentialEnv: values["credential-env"],
|
|
13346
|
+
authStyle: values["auth-style"],
|
|
13347
|
+
catalogBaseUrl: values["catalog-url"],
|
|
13348
|
+
catalogCredentialEnv: values["catalog-credential-env"],
|
|
13349
|
+
catalogAuthStyle: values["catalog-auth-style"],
|
|
13350
|
+
catalogFormat: values["catalog-format"],
|
|
13351
|
+
catalogAccountId: values["catalog-account-id"],
|
|
13352
|
+
modelsPath: values["models-path"]
|
|
13073
13353
|
});
|
|
13074
13354
|
if (command === "doctor") {
|
|
13075
13355
|
const harnesses = await Promise.all(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"].map((h) => detectHarness(h)));
|
|
@@ -13083,35 +13363,36 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13083
13363
|
output({ version: VERSION, harnesses, api, liveVerified: false });
|
|
13084
13364
|
return;
|
|
13085
13365
|
}
|
|
13086
|
-
const page = { limit:
|
|
13366
|
+
const page = { limit: values.limit ? Number(values.limit) : undefined, offset: values.offset ? Number(values.offset) : undefined, search: values.search };
|
|
13087
13367
|
const currentVersion = () => {
|
|
13088
|
-
const n = Number(
|
|
13368
|
+
const n = Number(values.version);
|
|
13089
13369
|
if (!Number.isSafeInteger(n) || n < 1)
|
|
13090
13370
|
throw new Error("Use --version N with the record's current version.");
|
|
13091
13371
|
return n;
|
|
13092
13372
|
};
|
|
13093
13373
|
if (command === "launch") {
|
|
13094
|
-
if (!
|
|
13374
|
+
if (!action)
|
|
13095
13375
|
throw new Error("A harness or saved profile ID is required.");
|
|
13096
|
-
const timeoutMs =
|
|
13376
|
+
const timeoutMs = values.timeout ? Number(values.timeout) * 1000 : undefined;
|
|
13097
13377
|
if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs <= 0))
|
|
13098
13378
|
throw new Error("--timeout must be positive seconds.");
|
|
13099
|
-
let profileId =
|
|
13379
|
+
let profileId = action;
|
|
13100
13380
|
let credentialPreflight;
|
|
13101
13381
|
let resolvePreparedCredential;
|
|
13102
|
-
if (
|
|
13103
|
-
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" :
|
|
13104
|
-
const modelPolicy = await readModelPolicy(
|
|
13105
|
-
const provider = await resolveLaunchProvider(client,
|
|
13382
|
+
if (values.provider) {
|
|
13383
|
+
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action);
|
|
13384
|
+
const modelPolicy = await readModelPolicy(values["model-policy-file"], values["role-model"]);
|
|
13385
|
+
const provider = await resolveLaunchProvider(client, values.provider, { ...presetOptions(), harness });
|
|
13106
13386
|
validateHarnessProvider(harness, provider);
|
|
13107
|
-
|
|
13108
|
-
|
|
13387
|
+
let prepared;
|
|
13388
|
+
if (!values["dry-run"]) {
|
|
13389
|
+
prepared = await ensureProviderCredential(provider, { resolver: credentials });
|
|
13109
13390
|
credentialPreflight = prepared.providerFingerprint;
|
|
13110
13391
|
resolvePreparedCredential = prepared.resolveCredential;
|
|
13111
13392
|
}
|
|
13112
|
-
const catalog = await launchCatalog(client, provider,
|
|
13113
|
-
const
|
|
13114
|
-
const selected = catalog.models.find((m) => m.id ===
|
|
13393
|
+
const catalog = values["dry-run"] ? await launchCatalog(client, provider, true) : await refreshCatalog(provider, prepared);
|
|
13394
|
+
const model = values.model ?? await selectModel(catalog.models, values.search, harness);
|
|
13395
|
+
const selected = catalog.models.find((m) => m.id === model);
|
|
13115
13396
|
if (!selected)
|
|
13116
13397
|
throw new Fault(422, "model_missing", "Selected model is not in the provider catalog.");
|
|
13117
13398
|
if (modelExpired(selected))
|
|
@@ -13120,141 +13401,146 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13120
13401
|
throw new Fault(422, "model_ineligible", "Selected model explicitly lacks text output or tool support.");
|
|
13121
13402
|
if (harness === "codex")
|
|
13122
13403
|
codexReasoning(selected, provider.baseUrl, reasoning);
|
|
13123
|
-
profileId = (await ensureLaunchProfile(client, provider, harness,
|
|
13404
|
+
profileId = (await ensureLaunchProfile(client, provider, harness, model, modelPolicy)).id;
|
|
13124
13405
|
} else {
|
|
13125
|
-
if (
|
|
13406
|
+
if (values.model || values.protocol || values.url || values["credential-env"] || values["model-policy-file"] || values["role-model"])
|
|
13126
13407
|
throw new Error("Use --provider PROVIDER for a direct launch, or update the saved profile explicitly.");
|
|
13127
13408
|
const profile = await client.getProfile(profileId);
|
|
13128
13409
|
assertHarnessArguments(profile.harness, nativeArgs);
|
|
13129
|
-
await validateHarnessConfiguration(profile.harness,
|
|
13410
|
+
await validateHarnessConfiguration(profile.harness, values.cwd ?? process.cwd(), nativeArgs);
|
|
13130
13411
|
const provider = await client.getProvider(profile.providerId);
|
|
13131
13412
|
if (profile.harness === "gemini")
|
|
13132
13413
|
validateHarnessProvider(profile.harness, provider);
|
|
13133
|
-
|
|
13134
|
-
|
|
13414
|
+
let prepared;
|
|
13415
|
+
if (!values["dry-run"]) {
|
|
13416
|
+
prepared = await ensureProviderCredential(provider, { resolver: credentials });
|
|
13135
13417
|
credentialPreflight = prepared.providerFingerprint;
|
|
13136
13418
|
resolvePreparedCredential = prepared.resolveCredential;
|
|
13137
13419
|
}
|
|
13138
|
-
|
|
13420
|
+
if (values["dry-run"])
|
|
13421
|
+
await launchCatalog(client, provider, true);
|
|
13422
|
+
else
|
|
13423
|
+
await refreshCatalog(provider, prepared);
|
|
13139
13424
|
}
|
|
13140
|
-
if (
|
|
13425
|
+
if (values["dry-run"]) {
|
|
13141
13426
|
const plan = await client.launchPlan(profileId);
|
|
13142
13427
|
if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && plan.profile.harness !== "codex")
|
|
13143
13428
|
throw new Fault(400, "conflicting_options", "Reasoning and full-access options require Codex or ChatGPT.");
|
|
13144
13429
|
if (reasoning) {
|
|
13145
|
-
const
|
|
13146
|
-
if (
|
|
13147
|
-
codexReasoning(
|
|
13430
|
+
const model = plan.catalog.models.find((model) => model.id === plan.profile.model);
|
|
13431
|
+
if (model)
|
|
13432
|
+
codexReasoning(model, plan.provider.baseUrl, reasoning);
|
|
13148
13433
|
}
|
|
13149
13434
|
assertHarnessArguments(plan.profile.harness, nativeArgs);
|
|
13150
13435
|
if (backend === "ori") {
|
|
13151
|
-
const { contract, warnings } = await validateOriForPlan(plan, { oriExecutable:
|
|
13436
|
+
const { contract, warnings } = await validateOriForPlan(plan, { oriExecutable: values["ori-executable"], args: nativeArgs, cwd: values.cwd });
|
|
13152
13437
|
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] } });
|
|
13153
13438
|
} else
|
|
13154
13439
|
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" } } : {} });
|
|
13155
13440
|
return;
|
|
13156
13441
|
}
|
|
13157
|
-
process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable:
|
|
13442
|
+
process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values["ori-executable"], cwd: values.cwd, executable: values.executable, stateDir: values["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)) });
|
|
13158
13443
|
return;
|
|
13159
13444
|
}
|
|
13160
13445
|
if (editingModel) {
|
|
13161
|
-
const saved =
|
|
13446
|
+
const saved = action === "add" ? await client.addModel(id, modelInput) : action === "update" ? await client.updateModel(id, modelInput) : await client.removeModel(id, positionals[3]);
|
|
13162
13447
|
output({ providerId: saved.id, version: saved.version, ...modelInput ? { model: modelInput, expired: modelExpired(modelInput) } : { removed: positionals[3] } });
|
|
13163
13448
|
return;
|
|
13164
13449
|
}
|
|
13165
13450
|
if (configuringModels) {
|
|
13166
|
-
const provider = await client.getProvider(
|
|
13451
|
+
const provider = await client.getProvider(id);
|
|
13167
13452
|
output({ providerId: provider.id, version: provider.version, manualModels: provider.manualModels, additionalModels: provider.additionalModels ?? [] });
|
|
13168
13453
|
return;
|
|
13169
13454
|
}
|
|
13170
|
-
if (command === "models" &&
|
|
13171
|
-
const provider = await resolveLaunchProvider(client, listingModels ?
|
|
13172
|
-
if (
|
|
13173
|
-
await
|
|
13455
|
+
if (command === "models" && action) {
|
|
13456
|
+
const provider = await resolveLaunchProvider(client, listingModels ? id : action, presetOptions());
|
|
13457
|
+
if (values.refresh)
|
|
13458
|
+
await refreshCatalog(provider);
|
|
13174
13459
|
try {
|
|
13175
13460
|
output(await client.listModels(provider.id, page));
|
|
13176
13461
|
} catch (error) {
|
|
13177
13462
|
if (!(error instanceof SwitcherError && error.status === 404))
|
|
13178
13463
|
throw error;
|
|
13179
|
-
await
|
|
13464
|
+
await refreshCatalog(provider);
|
|
13180
13465
|
output(await client.listModels(provider.id, page));
|
|
13181
13466
|
}
|
|
13182
13467
|
return;
|
|
13183
13468
|
}
|
|
13184
13469
|
if (command === "runs") {
|
|
13185
|
-
output(
|
|
13470
|
+
output(action === "get" && id ? await client.getRun(id) : action === "list" ? await client.listRuns(page) : (() => {
|
|
13186
13471
|
throw new Error("Use runs list|get ID.");
|
|
13187
13472
|
})());
|
|
13188
13473
|
return;
|
|
13189
13474
|
}
|
|
13190
13475
|
if (command === "providers") {
|
|
13191
|
-
if (
|
|
13192
|
-
output(
|
|
13476
|
+
if (action === "presets") {
|
|
13477
|
+
output(id ? await client.getProviderPreset(id) : await client.listProviderPresets());
|
|
13193
13478
|
return;
|
|
13194
13479
|
}
|
|
13195
|
-
if (
|
|
13480
|
+
if (action === "list") {
|
|
13196
13481
|
output(await client.listProviders(page));
|
|
13197
13482
|
return;
|
|
13198
13483
|
}
|
|
13199
|
-
if (
|
|
13200
|
-
output(await client.getProvider(
|
|
13484
|
+
if (action === "get" && id) {
|
|
13485
|
+
output(await client.getProvider(id));
|
|
13201
13486
|
return;
|
|
13202
13487
|
}
|
|
13203
|
-
if (
|
|
13204
|
-
|
|
13488
|
+
if (action === "refresh" && id) {
|
|
13489
|
+
const provider = await client.getProvider(id);
|
|
13490
|
+
output(await refreshCatalog(provider));
|
|
13205
13491
|
return;
|
|
13206
13492
|
}
|
|
13207
|
-
if (
|
|
13208
|
-
output(await client.deleteProvider(
|
|
13493
|
+
if (action === "delete" && id) {
|
|
13494
|
+
output(await client.deleteProvider(id, currentVersion()));
|
|
13209
13495
|
return;
|
|
13210
13496
|
}
|
|
13211
|
-
if (["add", "update"].includes(
|
|
13212
|
-
let input = parse2(providerInputSchema,
|
|
13213
|
-
id
|
|
13214
|
-
name:
|
|
13215
|
-
baseUrl:
|
|
13216
|
-
protocol:
|
|
13217
|
-
credentialEnv:
|
|
13218
|
-
authStyle:
|
|
13219
|
-
catalogBaseUrl:
|
|
13220
|
-
catalogCredentialEnv:
|
|
13221
|
-
catalogAuthStyle:
|
|
13222
|
-
catalogFormat:
|
|
13223
|
-
catalogAccountId:
|
|
13224
|
-
modelsPath:
|
|
13497
|
+
if (["add", "update"].includes(action) && id) {
|
|
13498
|
+
let input = parse2(providerInputSchema, values.file ? await readInput(values.file) : values.preset ? { ...providerFromPreset(values.preset, { ...presetOptions(), id }), ...values.name ? { name: values.name } : {} } : {
|
|
13499
|
+
id,
|
|
13500
|
+
name: values.name ?? id,
|
|
13501
|
+
baseUrl: values.url,
|
|
13502
|
+
protocol: values.protocol,
|
|
13503
|
+
credentialEnv: values["credential-env"],
|
|
13504
|
+
authStyle: values["auth-style"],
|
|
13505
|
+
catalogBaseUrl: values["catalog-url"],
|
|
13506
|
+
catalogCredentialEnv: values["catalog-credential-env"],
|
|
13507
|
+
catalogAuthStyle: values["catalog-auth-style"],
|
|
13508
|
+
catalogFormat: values["catalog-format"],
|
|
13509
|
+
catalogAccountId: values["catalog-account-id"],
|
|
13510
|
+
modelsPath: values["models-path"]
|
|
13225
13511
|
});
|
|
13226
13512
|
if (starterModels) {
|
|
13227
13513
|
const field = input.catalogFormat === "none" ? "manualModels" : "additionalModels";
|
|
13228
|
-
const models = new Map((input[field] ?? []).map((
|
|
13229
|
-
for (const
|
|
13230
|
-
models.set(
|
|
13514
|
+
const models = new Map((input[field] ?? []).map((model) => [model.id, model]));
|
|
13515
|
+
for (const model of starterModels)
|
|
13516
|
+
models.set(model.id, model);
|
|
13231
13517
|
input = parse2(providerInputSchema, { ...input, [field]: [...models.values()] });
|
|
13232
13518
|
}
|
|
13233
|
-
if (input.id !==
|
|
13519
|
+
if (input.id !== id)
|
|
13234
13520
|
throw new Error("File id must match the command id.");
|
|
13235
|
-
output(
|
|
13521
|
+
output(action === "add" ? await client.createProvider(input) : await client.updateProvider(input, currentVersion()));
|
|
13236
13522
|
return;
|
|
13237
13523
|
}
|
|
13238
13524
|
}
|
|
13239
13525
|
if (command === "profiles") {
|
|
13240
|
-
if (
|
|
13526
|
+
if (action === "list") {
|
|
13241
13527
|
output(await client.listProfiles(page));
|
|
13242
13528
|
return;
|
|
13243
13529
|
}
|
|
13244
|
-
if (
|
|
13245
|
-
output(await client.getProfile(
|
|
13530
|
+
if (action === "get" && id) {
|
|
13531
|
+
output(await client.getProfile(id));
|
|
13246
13532
|
return;
|
|
13247
13533
|
}
|
|
13248
|
-
if (
|
|
13249
|
-
output(await client.deleteProfile(
|
|
13534
|
+
if (action === "delete" && id) {
|
|
13535
|
+
output(await client.deleteProfile(id, currentVersion()));
|
|
13250
13536
|
return;
|
|
13251
13537
|
}
|
|
13252
|
-
if (["add", "update"].includes(
|
|
13253
|
-
const modelPolicy = await readModelPolicy(
|
|
13254
|
-
const input = parse2(profileInputSchema,
|
|
13255
|
-
if (input.id !==
|
|
13538
|
+
if (["add", "update"].includes(action) && id) {
|
|
13539
|
+
const modelPolicy = await readModelPolicy(values["model-policy-file"], values["role-model"]);
|
|
13540
|
+
const input = parse2(profileInputSchema, values.file ? await readInput(values.file) : { id, name: values.name ?? id, providerId: values.provider, harness: values.harness, model: values.model, ...modelPolicy ? { modelPolicy } : {} });
|
|
13541
|
+
if (input.id !== id)
|
|
13256
13542
|
throw new Error("File id must match the command id.");
|
|
13257
|
-
output(
|
|
13543
|
+
output(action === "add" ? await client.createProfile(input) : await client.updateProfile(input, currentVersion()));
|
|
13258
13544
|
return;
|
|
13259
13545
|
}
|
|
13260
13546
|
}
|
|
@@ -13273,6 +13559,6 @@ if (import.meta.main) {
|
|
|
13273
13559
|
});
|
|
13274
13560
|
}
|
|
13275
13561
|
export {
|
|
13276
|
-
|
|
13277
|
-
|
|
13562
|
+
main,
|
|
13563
|
+
readModelPolicy
|
|
13278
13564
|
};
|