@hasna/switcher 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +85 -6
- package/dist/cli/index.js +2034 -1169
- package/dist/credentials.d.ts +96 -7
- package/dist/direct-launch.d.ts +2 -1
- package/dist/domain.d.ts +63 -1
- package/dist/generated/api.d.ts +32 -0
- package/dist/index.js +11 -1
- package/dist/launcher.d.ts +1 -0
- package/dist/mcp/index.js +106 -4
- package/dist/opencode.d.ts +30 -0
- package/dist/presets.d.ts +8 -0
- package/dist/sdk.d.ts +36 -0
- package/dist/sdk.js +11 -1
- package/dist/serve/index.js +106 -4
- package/openapi.json +93 -1
- package/package.json +3 -2
package/dist/cli/index.js
CHANGED
|
@@ -514,7 +514,7 @@ function canonicalPolicyJSON(value) {
|
|
|
514
514
|
}
|
|
515
515
|
|
|
516
516
|
// src/domain.ts
|
|
517
|
-
var VERSION = "0.2.
|
|
517
|
+
var VERSION = "0.2.2";
|
|
518
518
|
var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
519
519
|
var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
520
520
|
var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
@@ -539,6 +539,8 @@ var urlSchema = z4.string().max(2000).superRefine((v, ctx) => {
|
|
|
539
539
|
ctx.addIssue({ code: "custom", message: "Invalid endpoint URL" });
|
|
540
540
|
}
|
|
541
541
|
}).transform(endpoint);
|
|
542
|
+
var credentialCheckPath = z4.string().min(1).max(200).regex(/^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$/).refine((value) => !value.startsWith("/") && !value.split("/").some((part) => part === "." || part === ".."), "credentialCheck.path must be relative without dot segments");
|
|
543
|
+
var credentialCheckSchema = z4.object({ method: z4.enum(["GET", "HEAD"]).default("GET"), path: credentialCheckPath }).strict();
|
|
542
544
|
var expiresOnSchema = z4.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
|
|
543
545
|
const day = new Date(`${value}T00:00:00.000Z`);
|
|
544
546
|
return Number.isFinite(day.getTime()) && day.toISOString().slice(0, 10) === value;
|
|
@@ -564,6 +566,7 @@ var providerInputSchema = z4.object({
|
|
|
564
566
|
protocol: protocolSchema,
|
|
565
567
|
credentialEnv: envRef.optional(),
|
|
566
568
|
authStyle: z4.enum(["bearer", "x-api-key", "api-key"]).default("bearer"),
|
|
569
|
+
credentialCheck: credentialCheckSchema.optional(),
|
|
567
570
|
catalogBaseUrl: urlSchema.optional(),
|
|
568
571
|
catalogFormat: z4.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]).optional(),
|
|
569
572
|
catalogAuthStyle: z4.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
|
|
@@ -582,6 +585,7 @@ var providerPresetSchema = z4.object({
|
|
|
582
585
|
protocol: protocolSchema,
|
|
583
586
|
baseUrl: urlSchema.optional(),
|
|
584
587
|
authStyle: z4.enum(["bearer", "x-api-key", "api-key"]),
|
|
588
|
+
credentialCheck: credentialCheckSchema.optional(),
|
|
585
589
|
catalogBaseUrl: urlSchema.optional(),
|
|
586
590
|
catalogFormat: z4.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]),
|
|
587
591
|
catalogAuthStyle: z4.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
|
|
@@ -1080,12 +1084,17 @@ var preset = (id, name, protocols, sources, alias) => parse2(providerPresetSchem
|
|
|
1080
1084
|
verification: "documented"
|
|
1081
1085
|
});
|
|
1082
1086
|
var providerPresets = [
|
|
1087
|
+
...["opencode", "opencode-go"].map((id) => preset(id, id === "opencode" ? "OpenCode Zen" : "OpenCode Go", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, id === "opencode" ? "https://opencode.ai/zen/v1" : "https://opencode.ai/zen/go/v1", {
|
|
1088
|
+
authStyle: protocol === "anthropic-messages" ? "x-api-key" : "bearer",
|
|
1089
|
+
catalogAuthStyle: "none",
|
|
1090
|
+
notes: ["Discovers the full live catalog. Claude requests are adapted to each model's documented native endpoint. Other harnesses require models compatible with their selected protocol. Go requires an active subscription and coding-agent session headers."]
|
|
1091
|
+
})), ["https://opencode.ai/docs/zen/", "https://opencode.ai/docs/go/"], "OPENCODE_API_KEY")),
|
|
1083
1092
|
preset("deepseek", "DeepSeek", [
|
|
1084
1093
|
route("openai-chat", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
1085
1094
|
route("openai-responses", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
1086
1095
|
route("anthropic-messages", "https://api.deepseek.com/anthropic/v1", { catalogBaseUrl: "https://api.deepseek.com" })
|
|
1087
1096
|
], ["https://api-docs.deepseek.com/guides/anthropic_api", "https://api-docs.deepseek.com/api/list-models", "https://api-docs.deepseek.com/updates/", "https://api-docs.deepseek.com/guides/responses_api/"], "DEEPSEEK_API_KEY"),
|
|
1088
|
-
preset("openrouter", "OpenRouter", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, "https://openrouter.ai/api/v1", { catalogAuthStyle: "none" })), ["https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties", "https://openrouter.ai/docs/guides/overview"], "OPENROUTER_API_KEY"),
|
|
1097
|
+
preset("openrouter", "OpenRouter", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, "https://openrouter.ai/api/v1", { catalogAuthStyle: "none", credentialCheck: { method: "GET", path: "key" } })), ["https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties", "https://openrouter.ai/docs/guides/overview"], "OPENROUTER_API_KEY"),
|
|
1089
1098
|
preset("anthropic", "Anthropic", [route("anthropic-messages", "https://api.anthropic.com/v1", { authStyle: "x-api-key" })], ["https://platform.claude.com/docs/en/api/overview", "https://platform.claude.com/docs/en/api/models/list"], "ANTHROPIC_API_KEY"),
|
|
1090
1099
|
preset("gemini", "Google Gemini", [route("gemini-generate-content", "https://generativelanguage.googleapis.com/v1beta", {
|
|
1091
1100
|
authStyle: "x-api-key",
|
|
@@ -1176,6 +1185,7 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
1176
1185
|
protocol: selected.protocol,
|
|
1177
1186
|
credentialEnv: options.credentialEnv ?? preset2.credentialEnv,
|
|
1178
1187
|
authStyle: options.authStyle ?? selected.authStyle,
|
|
1188
|
+
credentialCheck: selected.credentialCheck,
|
|
1179
1189
|
catalogBaseUrl,
|
|
1180
1190
|
catalogCredentialEnv: options.catalogCredentialEnv,
|
|
1181
1191
|
catalogAuthStyle: options.catalogAuthStyle ?? selected.catalogAuthStyle,
|
|
@@ -2020,7 +2030,7 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
2020
2030
|
return { models: provider.manualModels, source: "manual", refreshedAt };
|
|
2021
2031
|
if (provider.catalogFormat === "none")
|
|
2022
2032
|
throw new Fault(422, "catalog_unsupported", "This provider has no documented model-list contract; configure manual models or an explicit catalog URL and parser.");
|
|
2023
|
-
const headers = { accept: "application/json" };
|
|
2033
|
+
const headers = { accept: "application/json", "user-agent": `hasna-switcher/${VERSION}` };
|
|
2024
2034
|
if (provider.catalogFormat === "fireworks" && !provider.catalogBaseUrl && !provider.catalogAccountId)
|
|
2025
2035
|
throw new Fault(422, "catalog_account_required", "Fireworks model discovery requires a catalog account ID or an explicit catalog URL.");
|
|
2026
2036
|
if (provider.catalogFormat === "fireworks" && !provider.catalogBaseUrl && new URL(provider.baseUrl).origin !== "https://api.fireworks.ai")
|
|
@@ -2079,6 +2089,7 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
2079
2089
|
inputModalities: strings(row.architecture?.input_modalities ?? row.input_modalities) ?? modalities(row.inference_metadata?.request_modality),
|
|
2080
2090
|
outputModalities: strings(row.architecture?.output_modalities ?? row.output_modalities) ?? modalities(row.inference_metadata?.response_modality),
|
|
2081
2091
|
supportedParameters: strings(row.supported_parameters),
|
|
2092
|
+
reasoningEfforts: row.reasoning?.supported_efforts,
|
|
2082
2093
|
...provider.catalogFormat === "gemini" && row.supportedGenerationMethods !== undefined ? { supportedGenerationMethods: row.supportedGenerationMethods } : {}
|
|
2083
2094
|
};
|
|
2084
2095
|
if (provider.catalogFormat === "mistral") {
|
|
@@ -2374,7 +2385,7 @@ var openapi_default = {
|
|
|
2374
2385
|
openapi: "3.0.3",
|
|
2375
2386
|
info: {
|
|
2376
2387
|
title: "Switcher API",
|
|
2377
|
-
version: "0.2.
|
|
2388
|
+
version: "0.2.2",
|
|
2378
2389
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2379
2390
|
},
|
|
2380
2391
|
security: [
|
|
@@ -3604,6 +3615,29 @@ var openapi_default = {
|
|
|
3604
3615
|
"api-key"
|
|
3605
3616
|
]
|
|
3606
3617
|
},
|
|
3618
|
+
credentialCheck: {
|
|
3619
|
+
type: "object",
|
|
3620
|
+
properties: {
|
|
3621
|
+
method: {
|
|
3622
|
+
type: "string",
|
|
3623
|
+
enum: [
|
|
3624
|
+
"GET",
|
|
3625
|
+
"HEAD"
|
|
3626
|
+
],
|
|
3627
|
+
default: "GET"
|
|
3628
|
+
},
|
|
3629
|
+
path: {
|
|
3630
|
+
type: "string",
|
|
3631
|
+
minLength: 1,
|
|
3632
|
+
maxLength: 200,
|
|
3633
|
+
pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
|
|
3634
|
+
}
|
|
3635
|
+
},
|
|
3636
|
+
required: [
|
|
3637
|
+
"path"
|
|
3638
|
+
],
|
|
3639
|
+
additionalProperties: false
|
|
3640
|
+
},
|
|
3607
3641
|
catalogBaseUrl: {
|
|
3608
3642
|
type: "string",
|
|
3609
3643
|
maxLength: 2000
|
|
@@ -3713,6 +3747,29 @@ var openapi_default = {
|
|
|
3713
3747
|
],
|
|
3714
3748
|
default: "bearer"
|
|
3715
3749
|
},
|
|
3750
|
+
credentialCheck: {
|
|
3751
|
+
type: "object",
|
|
3752
|
+
properties: {
|
|
3753
|
+
method: {
|
|
3754
|
+
type: "string",
|
|
3755
|
+
enum: [
|
|
3756
|
+
"GET",
|
|
3757
|
+
"HEAD"
|
|
3758
|
+
],
|
|
3759
|
+
default: "GET"
|
|
3760
|
+
},
|
|
3761
|
+
path: {
|
|
3762
|
+
type: "string",
|
|
3763
|
+
minLength: 1,
|
|
3764
|
+
maxLength: 200,
|
|
3765
|
+
pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
|
|
3766
|
+
}
|
|
3767
|
+
},
|
|
3768
|
+
required: [
|
|
3769
|
+
"path"
|
|
3770
|
+
],
|
|
3771
|
+
additionalProperties: false
|
|
3772
|
+
},
|
|
3716
3773
|
catalogBaseUrl: {
|
|
3717
3774
|
type: "string",
|
|
3718
3775
|
maxLength: 2000
|
|
@@ -3991,6 +4048,29 @@ var openapi_default = {
|
|
|
3991
4048
|
],
|
|
3992
4049
|
default: "bearer"
|
|
3993
4050
|
},
|
|
4051
|
+
credentialCheck: {
|
|
4052
|
+
type: "object",
|
|
4053
|
+
properties: {
|
|
4054
|
+
method: {
|
|
4055
|
+
type: "string",
|
|
4056
|
+
enum: [
|
|
4057
|
+
"GET",
|
|
4058
|
+
"HEAD"
|
|
4059
|
+
],
|
|
4060
|
+
default: "GET"
|
|
4061
|
+
},
|
|
4062
|
+
path: {
|
|
4063
|
+
type: "string",
|
|
4064
|
+
minLength: 1,
|
|
4065
|
+
maxLength: 200,
|
|
4066
|
+
pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
|
|
4067
|
+
}
|
|
4068
|
+
},
|
|
4069
|
+
required: [
|
|
4070
|
+
"path"
|
|
4071
|
+
],
|
|
4072
|
+
additionalProperties: false
|
|
4073
|
+
},
|
|
3994
4074
|
catalogBaseUrl: {
|
|
3995
4075
|
type: "string",
|
|
3996
4076
|
maxLength: 2000
|
|
@@ -5113,6 +5193,29 @@ var openapi_default = {
|
|
|
5113
5193
|
],
|
|
5114
5194
|
default: "bearer"
|
|
5115
5195
|
},
|
|
5196
|
+
credentialCheck: {
|
|
5197
|
+
type: "object",
|
|
5198
|
+
properties: {
|
|
5199
|
+
method: {
|
|
5200
|
+
type: "string",
|
|
5201
|
+
enum: [
|
|
5202
|
+
"GET",
|
|
5203
|
+
"HEAD"
|
|
5204
|
+
],
|
|
5205
|
+
default: "GET"
|
|
5206
|
+
},
|
|
5207
|
+
path: {
|
|
5208
|
+
type: "string",
|
|
5209
|
+
minLength: 1,
|
|
5210
|
+
maxLength: 200,
|
|
5211
|
+
pattern: "^[a-zA-Z0-9_~!$&'()*+,;=:@%./-]+$"
|
|
5212
|
+
}
|
|
5213
|
+
},
|
|
5214
|
+
required: [
|
|
5215
|
+
"path"
|
|
5216
|
+
],
|
|
5217
|
+
additionalProperties: false
|
|
5218
|
+
},
|
|
5116
5219
|
catalogBaseUrl: {
|
|
5117
5220
|
type: "string",
|
|
5118
5221
|
maxLength: 2000
|
|
@@ -7160,16 +7263,477 @@ function normalizeCodexDelegation(body) {
|
|
|
7160
7263
|
}) };
|
|
7161
7264
|
}
|
|
7162
7265
|
|
|
7266
|
+
// src/opencode.ts
|
|
7267
|
+
function rememberGeminiTool(part, state) {
|
|
7268
|
+
const id2 = `call_${crypto.randomUUID()}`;
|
|
7269
|
+
if (typeof part.thoughtSignature === "string") {
|
|
7270
|
+
if (part.thoughtSignature.length > 65536 || state.size >= 2000)
|
|
7271
|
+
throw new Fault(502, "opencode_signature_limit", "Gemini tool continuation metadata exceeded the launch limit.");
|
|
7272
|
+
state.set(id2, part.thoughtSignature);
|
|
7273
|
+
}
|
|
7274
|
+
return id2;
|
|
7275
|
+
}
|
|
7276
|
+
function openCodeLane(baseUrl) {
|
|
7277
|
+
const url = new URL(baseUrl);
|
|
7278
|
+
if (url.origin !== "https://opencode.ai")
|
|
7279
|
+
return;
|
|
7280
|
+
const path = url.pathname.replace(/\/+$/, "");
|
|
7281
|
+
return path === "/zen/v1" ? "zen" : path === "/zen/go/v1" ? "go" : undefined;
|
|
7282
|
+
}
|
|
7283
|
+
function openCodeWire(model, lane) {
|
|
7284
|
+
if (/^claude-/.test(model) || /^qwen3\.(5|6|7|8)-/.test(model) || lane === "go" && /^minimax-/.test(model))
|
|
7285
|
+
return "messages";
|
|
7286
|
+
if (/^(gpt-|grok-|muse-spark-)/.test(model))
|
|
7287
|
+
return "responses";
|
|
7288
|
+
if (/^gemini-/.test(model))
|
|
7289
|
+
return "gemini";
|
|
7290
|
+
return "chat";
|
|
7291
|
+
}
|
|
7292
|
+
function openCodeHeaders(baseUrl, source, body, launchSession) {
|
|
7293
|
+
if (!openCodeLane(baseUrl))
|
|
7294
|
+
return {};
|
|
7295
|
+
const result = { "user-agent": `hasna-switcher/${VERSION}` };
|
|
7296
|
+
const names = ["x-opencode-session", "x-client-session-id", "x-session-id", "session_id", "x-codex-thread-id"];
|
|
7297
|
+
for (const name of names) {
|
|
7298
|
+
const value = source.get(name);
|
|
7299
|
+
if (value && /^[A-Za-z0-9._:-]{1,200}$/.test(value))
|
|
7300
|
+
result[name] = value;
|
|
7301
|
+
}
|
|
7302
|
+
let session = names.map((name) => result[name]).find(Boolean);
|
|
7303
|
+
if (!session && typeof body.metadata?.user_id === "string") {
|
|
7304
|
+
try {
|
|
7305
|
+
const value = JSON.parse(body.metadata.user_id)?.session_id;
|
|
7306
|
+
if (typeof value === "string" && /^[A-Za-z0-9._:-]{1,200}$/.test(value))
|
|
7307
|
+
session = value;
|
|
7308
|
+
} catch {}
|
|
7309
|
+
session ??= /_session_([a-f0-9-]{36})$/i.exec(body.metadata.user_id)?.[1];
|
|
7310
|
+
}
|
|
7311
|
+
result["x-opencode-session"] = session ?? launchSession;
|
|
7312
|
+
return result;
|
|
7313
|
+
}
|
|
7314
|
+
function unsupported2(feature) {
|
|
7315
|
+
throw new Fault(422, "opencode_translation_unsupported", `The selected OpenCode model cannot receive this Claude feature: ${feature}.`);
|
|
7316
|
+
}
|
|
7317
|
+
function blocks(value) {
|
|
7318
|
+
if (typeof value === "string")
|
|
7319
|
+
return [{ type: "text", text: value }];
|
|
7320
|
+
if (Array.isArray(value) && value.every((item) => item && typeof item === "object"))
|
|
7321
|
+
return value;
|
|
7322
|
+
return unsupported2("malformed content");
|
|
7323
|
+
}
|
|
7324
|
+
function imageUrl(block) {
|
|
7325
|
+
if (block.source?.type === "url" && typeof block.source.url === "string")
|
|
7326
|
+
return block.source.url;
|
|
7327
|
+
if (block.source?.type === "base64" && typeof block.source.data === "string" && typeof block.source.media_type === "string")
|
|
7328
|
+
return `data:${block.source.media_type};base64,${block.source.data}`;
|
|
7329
|
+
return unsupported2("image source");
|
|
7330
|
+
}
|
|
7331
|
+
function textContent(value) {
|
|
7332
|
+
return blocks(value).map((block) => block.type === "text" && typeof block.text === "string" ? block.text : unsupported2("non-text tool result")).join(`
|
|
7333
|
+
`);
|
|
7334
|
+
}
|
|
7335
|
+
function toolResult(part) {
|
|
7336
|
+
const content = blocks(part.content ?? ""), images = content.filter((block) => block.type === "image");
|
|
7337
|
+
const text = textContent(content.filter((block) => block.type !== "image"));
|
|
7338
|
+
return { text: (part.is_error ? "[Tool error] " : "") + text, images };
|
|
7339
|
+
}
|
|
7340
|
+
function chatContent(value) {
|
|
7341
|
+
return blocks(value).flatMap((block) => {
|
|
7342
|
+
if (block.type === "text" && typeof block.text === "string")
|
|
7343
|
+
return [{ type: "text", text: block.text }];
|
|
7344
|
+
if (block.type === "image")
|
|
7345
|
+
return [{ type: "image_url", image_url: { url: imageUrl(block) } }];
|
|
7346
|
+
if (block.type === "thinking" || block.type === "redacted_thinking")
|
|
7347
|
+
return [];
|
|
7348
|
+
return unsupported2(`content block ${String(block.type)}`);
|
|
7349
|
+
});
|
|
7350
|
+
}
|
|
7351
|
+
function toChat(body) {
|
|
7352
|
+
const messages = [];
|
|
7353
|
+
if (body.system)
|
|
7354
|
+
messages.push({ role: "system", content: textContent(body.system) });
|
|
7355
|
+
if (!Array.isArray(body.messages))
|
|
7356
|
+
unsupported2("missing messages");
|
|
7357
|
+
for (const message of body.messages) {
|
|
7358
|
+
if (["system", "developer"].includes(message.role)) {
|
|
7359
|
+
messages.push({ role: "system", content: textContent(message.content) });
|
|
7360
|
+
continue;
|
|
7361
|
+
}
|
|
7362
|
+
if (!["user", "assistant"].includes(message.role))
|
|
7363
|
+
unsupported2("message role");
|
|
7364
|
+
const parts = blocks(message.content);
|
|
7365
|
+
if (message.role === "assistant") {
|
|
7366
|
+
const calls = parts.filter((part) => part.type === "tool_use").map((part) => ({ id: part.id, type: "function", function: { name: part.name, arguments: JSON.stringify(part.input ?? {}) } }));
|
|
7367
|
+
const content = chatContent(parts.filter((part) => part.type !== "tool_use"));
|
|
7368
|
+
const thinking = parts.filter((part) => part.type === "thinking").map((part) => part.thinking ?? "").join("");
|
|
7369
|
+
messages.push({ role: "assistant", content: content.length ? content : null, ...calls.length ? { tool_calls: calls } : {}, ...thinking ? { reasoning_content: thinking } : {} });
|
|
7370
|
+
} else {
|
|
7371
|
+
const images = [];
|
|
7372
|
+
for (const part of parts.filter((part2) => part2.type === "tool_result")) {
|
|
7373
|
+
const result2 = toolResult(part);
|
|
7374
|
+
messages.push({ role: "tool", tool_call_id: part.tool_use_id, content: result2.text });
|
|
7375
|
+
if (result2.images.length)
|
|
7376
|
+
images.push({ type: "text", text: `Images returned by tool call ${part.tool_use_id}:` }, ...result2.images);
|
|
7377
|
+
}
|
|
7378
|
+
const content = chatContent([...images, ...parts.filter((part) => part.type !== "tool_result")]);
|
|
7379
|
+
if (content.length)
|
|
7380
|
+
messages.push({ role: "user", content });
|
|
7381
|
+
}
|
|
7382
|
+
}
|
|
7383
|
+
const tools = body.tools?.map((tool) => {
|
|
7384
|
+
if (tool.type && tool.type !== "custom")
|
|
7385
|
+
unsupported2(`server tool ${tool.type}`);
|
|
7386
|
+
if (!tool.name || !tool.input_schema)
|
|
7387
|
+
unsupported2("tool schema");
|
|
7388
|
+
return { type: "function", function: { name: tool.name, description: tool.description, parameters: tool.input_schema } };
|
|
7389
|
+
});
|
|
7390
|
+
const choice = body.tool_choice;
|
|
7391
|
+
const tool_choice = !choice ? undefined : choice.type === "tool" ? { type: "function", function: { name: choice.name } } : choice.type === "any" ? "required" : ["auto", "none"].includes(choice.type) ? choice.type : unsupported2("tool choice");
|
|
7392
|
+
const result = {
|
|
7393
|
+
model: body.model,
|
|
7394
|
+
messages,
|
|
7395
|
+
max_tokens: body.max_tokens,
|
|
7396
|
+
stream: !!body.stream,
|
|
7397
|
+
...tools?.length ? { tools, tool_choice } : {},
|
|
7398
|
+
...choice?.disable_parallel_tool_use ? { parallel_tool_calls: false } : {}
|
|
7399
|
+
};
|
|
7400
|
+
for (const key of ["temperature", "top_p"])
|
|
7401
|
+
if (body[key] !== undefined)
|
|
7402
|
+
result[key] = body[key];
|
|
7403
|
+
if (body.stop_sequences)
|
|
7404
|
+
result.stop = body.stop_sequences;
|
|
7405
|
+
const effort = body.output_config?.effort;
|
|
7406
|
+
if (effort)
|
|
7407
|
+
result.reasoning_effort = effort;
|
|
7408
|
+
if (body.thinking?.type === "disabled")
|
|
7409
|
+
result.thinking = { type: "disabled" };
|
|
7410
|
+
else if (body.thinking?.type === "enabled" || body.thinking?.type === "adaptive")
|
|
7411
|
+
result.thinking = { type: "enabled" };
|
|
7412
|
+
if (result.stream)
|
|
7413
|
+
result.stream_options = { include_usage: true };
|
|
7414
|
+
return result;
|
|
7415
|
+
}
|
|
7416
|
+
function toResponses(chat) {
|
|
7417
|
+
const input = [];
|
|
7418
|
+
let instructions = "";
|
|
7419
|
+
for (const message of chat.messages) {
|
|
7420
|
+
if (message.role === "system") {
|
|
7421
|
+
instructions += (instructions ? `
|
|
7422
|
+
|
|
7423
|
+
` : "") + message.content;
|
|
7424
|
+
continue;
|
|
7425
|
+
}
|
|
7426
|
+
if (message.role === "tool") {
|
|
7427
|
+
input.push({ type: "function_call_output", call_id: message.tool_call_id, output: message.content });
|
|
7428
|
+
continue;
|
|
7429
|
+
}
|
|
7430
|
+
if (message.content?.length)
|
|
7431
|
+
input.push({ role: message.role, content: message.content.map((part) => part.type === "image_url" ? { type: "input_image", image_url: part.image_url.url } : { type: message.role === "assistant" ? "output_text" : "input_text", text: part.text }) });
|
|
7432
|
+
for (const call of message.tool_calls ?? [])
|
|
7433
|
+
input.push({ type: "function_call", call_id: call.id, name: call.function.name, arguments: call.function.arguments });
|
|
7434
|
+
}
|
|
7435
|
+
const result = { model: chat.model, input, instructions, stream: chat.stream, max_output_tokens: chat.max_tokens, store: false };
|
|
7436
|
+
if (chat.tools)
|
|
7437
|
+
result.tools = chat.tools.map((tool) => ({ type: "function", ...tool.function }));
|
|
7438
|
+
if (chat.tool_choice)
|
|
7439
|
+
result.tool_choice = typeof chat.tool_choice === "string" ? chat.tool_choice : { type: "function", name: chat.tool_choice.function.name };
|
|
7440
|
+
for (const key of ["temperature", "top_p", "parallel_tool_calls"])
|
|
7441
|
+
if (chat[key] !== undefined)
|
|
7442
|
+
result[key] = chat[key];
|
|
7443
|
+
if (chat.reasoning_effort || chat.thinking?.type === "disabled")
|
|
7444
|
+
result.reasoning = { effort: chat.thinking?.type === "disabled" ? "none" : chat.reasoning_effort };
|
|
7445
|
+
if (chat.stop)
|
|
7446
|
+
unsupported2("stop sequences on Responses");
|
|
7447
|
+
return result;
|
|
7448
|
+
}
|
|
7449
|
+
function toGemini(chat, state) {
|
|
7450
|
+
const contents = [], names = new Map;
|
|
7451
|
+
let systemInstruction;
|
|
7452
|
+
for (const message of chat.messages) {
|
|
7453
|
+
if (message.role === "system") {
|
|
7454
|
+
systemInstruction ??= { parts: [] };
|
|
7455
|
+
systemInstruction.parts.push({ text: message.content });
|
|
7456
|
+
continue;
|
|
7457
|
+
}
|
|
7458
|
+
if (message.role === "tool") {
|
|
7459
|
+
const name = names.get(message.tool_call_id);
|
|
7460
|
+
if (!name)
|
|
7461
|
+
unsupported2("unpaired tool result");
|
|
7462
|
+
contents.push({ role: "user", parts: [{ functionResponse: { name, response: { result: message.content } } }] });
|
|
7463
|
+
continue;
|
|
7464
|
+
}
|
|
7465
|
+
const parts = (message.content ?? []).map((part) => {
|
|
7466
|
+
if (part.type === "text")
|
|
7467
|
+
return { text: part.text };
|
|
7468
|
+
const url = part.image_url.url, match = /^data:([^;]+);base64,(.+)$/s.exec(url);
|
|
7469
|
+
return match ? { inlineData: { mimeType: match[1], data: match[2] } } : { fileData: { fileUri: url } };
|
|
7470
|
+
});
|
|
7471
|
+
for (const call of message.tool_calls ?? []) {
|
|
7472
|
+
names.set(call.id, call.function.name);
|
|
7473
|
+
parts.push({ functionCall: { name: call.function.name, args: JSON.parse(call.function.arguments) }, ...state.has(call.id) ? { thoughtSignature: state.get(call.id) } : {} });
|
|
7474
|
+
}
|
|
7475
|
+
contents.push({ role: message.role === "assistant" ? "model" : "user", parts });
|
|
7476
|
+
}
|
|
7477
|
+
const generationConfig = { maxOutputTokens: chat.max_tokens };
|
|
7478
|
+
if (chat.temperature !== undefined)
|
|
7479
|
+
generationConfig.temperature = chat.temperature;
|
|
7480
|
+
if (chat.top_p !== undefined)
|
|
7481
|
+
generationConfig.topP = chat.top_p;
|
|
7482
|
+
if (chat.stop)
|
|
7483
|
+
generationConfig.stopSequences = chat.stop;
|
|
7484
|
+
if (chat.reasoning_effort)
|
|
7485
|
+
generationConfig.thinkingConfig = { thinkingLevel: chat.reasoning_effort.toUpperCase() };
|
|
7486
|
+
const result = { contents, systemInstruction, generationConfig };
|
|
7487
|
+
if (chat.tools)
|
|
7488
|
+
result.tools = [{ functionDeclarations: chat.tools.map((tool) => ({ name: tool.function.name, description: tool.function.description, parametersJsonSchema: tool.function.parameters })) }];
|
|
7489
|
+
if (chat.tool_choice)
|
|
7490
|
+
result.toolConfig = { functionCallingConfig: typeof chat.tool_choice === "object" ? { mode: "ANY", allowedFunctionNames: [chat.tool_choice.function.name] } : { mode: { auto: "AUTO", required: "ANY", none: "NONE" }[chat.tool_choice] } };
|
|
7491
|
+
return result;
|
|
7492
|
+
}
|
|
7493
|
+
var stopReason = (reason, hasTools) => hasTools ? "tool_use" : ["length", "max_tokens", "max_output_tokens", "MAX_TOKENS"].includes(reason ?? "") ? "max_tokens" : "end_turn";
|
|
7494
|
+
function usage(data, wire) {
|
|
7495
|
+
const value = wire === "gemini" ? data.usageMetadata ?? {} : data.usage ?? {};
|
|
7496
|
+
return {
|
|
7497
|
+
input_tokens: value.input_tokens ?? value.prompt_tokens ?? value.promptTokenCount ?? 0,
|
|
7498
|
+
output_tokens: value.output_tokens ?? value.completion_tokens ?? (value.candidatesTokenCount ?? 0) + (value.thoughtsTokenCount ?? 0)
|
|
7499
|
+
};
|
|
7500
|
+
}
|
|
7501
|
+
function toolInput(value) {
|
|
7502
|
+
try {
|
|
7503
|
+
return JSON.parse(value || "{}");
|
|
7504
|
+
} catch {
|
|
7505
|
+
throw new Fault(502, "invalid_provider_response", "Provider returned malformed tool arguments.");
|
|
7506
|
+
}
|
|
7507
|
+
}
|
|
7508
|
+
function fromJson(data, wire, model, state) {
|
|
7509
|
+
const content = [];
|
|
7510
|
+
let reason;
|
|
7511
|
+
if (wire === "chat") {
|
|
7512
|
+
const choice = data.choices?.[0], message = choice?.message;
|
|
7513
|
+
if (!message)
|
|
7514
|
+
throw new Fault(502, "invalid_provider_response", "Provider returned no completion.");
|
|
7515
|
+
if (message.reasoning_content ?? message.reasoning)
|
|
7516
|
+
content.push({ type: "thinking", thinking: message.reasoning_content ?? message.reasoning, signature: "" });
|
|
7517
|
+
if (message.content)
|
|
7518
|
+
content.push({ type: "text", text: message.content });
|
|
7519
|
+
for (const tool of message.tool_calls ?? [])
|
|
7520
|
+
content.push({ type: "tool_use", id: tool.id, name: tool.function.name, input: toolInput(tool.function.arguments) });
|
|
7521
|
+
reason = choice.finish_reason;
|
|
7522
|
+
} else if (wire === "responses") {
|
|
7523
|
+
if (!["completed", "incomplete"].includes(data.status))
|
|
7524
|
+
throw new Fault(502, "invalid_provider_response", "Provider response did not complete.");
|
|
7525
|
+
for (const item of data.output ?? []) {
|
|
7526
|
+
if (item.type === "message") {
|
|
7527
|
+
for (const part of item.content ?? [])
|
|
7528
|
+
if (part.type === "output_text")
|
|
7529
|
+
content.push({ type: "text", text: part.text });
|
|
7530
|
+
}
|
|
7531
|
+
if (item.type === "function_call")
|
|
7532
|
+
content.push({ type: "tool_use", id: item.call_id, name: item.name, input: toolInput(item.arguments) });
|
|
7533
|
+
if (item.type === "reasoning")
|
|
7534
|
+
for (const part of item.summary ?? [])
|
|
7535
|
+
content.push({ type: "thinking", thinking: part.text, signature: "" });
|
|
7536
|
+
}
|
|
7537
|
+
reason = data.incomplete_details?.reason;
|
|
7538
|
+
} else {
|
|
7539
|
+
const candidate = data.candidates?.[0];
|
|
7540
|
+
if (!candidate)
|
|
7541
|
+
throw new Fault(502, "invalid_provider_response", "Provider returned no candidate.");
|
|
7542
|
+
for (const part of candidate.content?.parts ?? []) {
|
|
7543
|
+
if (part.text)
|
|
7544
|
+
content.push(part.thought ? { type: "thinking", thinking: part.text, signature: "" } : { type: "text", text: part.text });
|
|
7545
|
+
if (part.functionCall)
|
|
7546
|
+
content.push({ type: "tool_use", id: rememberGeminiTool(part, state), name: part.functionCall.name, input: part.functionCall.args ?? {} });
|
|
7547
|
+
}
|
|
7548
|
+
reason = candidate.finishReason;
|
|
7549
|
+
}
|
|
7550
|
+
return {
|
|
7551
|
+
id: `msg_${crypto.randomUUID()}`,
|
|
7552
|
+
type: "message",
|
|
7553
|
+
role: "assistant",
|
|
7554
|
+
model: data.model ?? data.modelVersion ?? model,
|
|
7555
|
+
content,
|
|
7556
|
+
stop_reason: stopReason(reason, content.some((part) => part.type === "tool_use")),
|
|
7557
|
+
stop_sequence: null,
|
|
7558
|
+
usage: usage(data, wire)
|
|
7559
|
+
};
|
|
7560
|
+
}
|
|
7561
|
+
function fromStream(response, wire, model, state) {
|
|
7562
|
+
const reader = response.body.getReader(), decoder = new TextDecoder, encoder = new TextEncoder;
|
|
7563
|
+
let buffer = "", ended = false, started = false, index = 0, reason;
|
|
7564
|
+
let tokens = { input_tokens: 0, output_tokens: 0 };
|
|
7565
|
+
const active = new Map;
|
|
7566
|
+
const stream = new ReadableStream({
|
|
7567
|
+
async pull(controller) {
|
|
7568
|
+
const send = (event) => controller.enqueue(encoder.encode(`event: ${event.type}
|
|
7569
|
+
data: ${JSON.stringify(event)}
|
|
7570
|
+
|
|
7571
|
+
`));
|
|
7572
|
+
const start = () => {
|
|
7573
|
+
if (!started) {
|
|
7574
|
+
started = true;
|
|
7575
|
+
send({ type: "message_start", message: { id: `msg_${crypto.randomUUID()}`, type: "message", role: "assistant", model, content: [], stop_reason: null, stop_sequence: null, usage: tokens } });
|
|
7576
|
+
}
|
|
7577
|
+
};
|
|
7578
|
+
const part = (key, block, delta) => {
|
|
7579
|
+
start();
|
|
7580
|
+
let current = active.get(key);
|
|
7581
|
+
if (!current) {
|
|
7582
|
+
current = { index: index++, tool: block.type === "tool_use" };
|
|
7583
|
+
active.set(key, current);
|
|
7584
|
+
send({ type: "content_block_start", index: current.index, content_block: block });
|
|
7585
|
+
}
|
|
7586
|
+
if (delta)
|
|
7587
|
+
send({ type: "content_block_delta", index: current.index, delta });
|
|
7588
|
+
};
|
|
7589
|
+
const text = (value, thinking = false) => {
|
|
7590
|
+
if (value)
|
|
7591
|
+
part(thinking ? "thinking" : "text", thinking ? { type: "thinking", thinking: "", signature: "" } : { type: "text", text: "" }, thinking ? { type: "thinking_delta", thinking: value } : { type: "text_delta", text: value });
|
|
7592
|
+
};
|
|
7593
|
+
const finish = () => {
|
|
7594
|
+
start();
|
|
7595
|
+
for (const item of active.values())
|
|
7596
|
+
send({ type: "content_block_stop", index: item.index });
|
|
7597
|
+
send({ type: "message_delta", delta: { stop_reason: stopReason(reason, [...active.values()].some((item) => item.tool)), stop_sequence: null }, usage: tokens });
|
|
7598
|
+
send({ type: "message_stop" });
|
|
7599
|
+
ended = true;
|
|
7600
|
+
controller.close();
|
|
7601
|
+
reader.cancel().catch(() => {});
|
|
7602
|
+
};
|
|
7603
|
+
try {
|
|
7604
|
+
const chunk = await reader.read();
|
|
7605
|
+
if (chunk.done) {
|
|
7606
|
+
if (!ended)
|
|
7607
|
+
throw new Error("OpenCode stream ended before completion");
|
|
7608
|
+
return;
|
|
7609
|
+
}
|
|
7610
|
+
buffer = (buffer + decoder.decode(chunk.value, { stream: true })).replace(/\r\n/g, `
|
|
7611
|
+
`);
|
|
7612
|
+
if (buffer.length > 4 * 1024 * 1024)
|
|
7613
|
+
throw new Error("OpenCode SSE event too large");
|
|
7614
|
+
let end;
|
|
7615
|
+
while (!ended && (end = buffer.indexOf(`
|
|
7616
|
+
|
|
7617
|
+
`)) >= 0) {
|
|
7618
|
+
const frame = buffer.slice(0, end);
|
|
7619
|
+
buffer = buffer.slice(end + 2);
|
|
7620
|
+
const payload = frame.split(`
|
|
7621
|
+
`).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join(`
|
|
7622
|
+
`);
|
|
7623
|
+
if (!payload)
|
|
7624
|
+
continue;
|
|
7625
|
+
if (payload === "[DONE]") {
|
|
7626
|
+
if (wire !== "chat" || !reason)
|
|
7627
|
+
throw new Error("Missing completion reason");
|
|
7628
|
+
finish();
|
|
7629
|
+
break;
|
|
7630
|
+
}
|
|
7631
|
+
const data = JSON.parse(payload);
|
|
7632
|
+
if (data.error || data.type === "error" || data.type === "response.failed")
|
|
7633
|
+
throw new Error("OpenCode provider stream failed");
|
|
7634
|
+
if (wire === "chat") {
|
|
7635
|
+
if (data.usage)
|
|
7636
|
+
tokens = usage(data, wire);
|
|
7637
|
+
const choice = data.choices?.[0], delta = choice?.delta;
|
|
7638
|
+
if (choice?.finish_reason)
|
|
7639
|
+
reason = choice.finish_reason;
|
|
7640
|
+
if (!delta)
|
|
7641
|
+
continue;
|
|
7642
|
+
text(delta.reasoning_content ?? delta.reasoning ?? "", true);
|
|
7643
|
+
text(delta.content ?? "");
|
|
7644
|
+
for (const call of delta.tool_calls ?? []) {
|
|
7645
|
+
const key = `tool-${call.index}`;
|
|
7646
|
+
if (!active.has(key) && (!call.id || !call.function?.name))
|
|
7647
|
+
throw new Error("Incomplete tool start");
|
|
7648
|
+
part(key, { type: "tool_use", id: call.id, name: call.function?.name, input: {} }, call.function?.arguments ? { type: "input_json_delta", partial_json: call.function.arguments } : undefined);
|
|
7649
|
+
}
|
|
7650
|
+
} else if (wire === "responses") {
|
|
7651
|
+
if (data.type === "response.output_text.delta")
|
|
7652
|
+
text(data.delta);
|
|
7653
|
+
if (data.type === "response.reasoning_summary_text.delta")
|
|
7654
|
+
text(data.delta, true);
|
|
7655
|
+
if (data.type === "response.output_item.added" && data.item?.type === "function_call")
|
|
7656
|
+
part(`tool-${data.output_index}`, { type: "tool_use", id: data.item.call_id, name: data.item.name, input: {} });
|
|
7657
|
+
if (data.type === "response.function_call_arguments.delta") {
|
|
7658
|
+
const current = active.get(`tool-${data.output_index}`);
|
|
7659
|
+
if (!current)
|
|
7660
|
+
throw new Error("Missing tool start");
|
|
7661
|
+
send({ type: "content_block_delta", index: current.index, delta: { type: "input_json_delta", partial_json: data.delta } });
|
|
7662
|
+
}
|
|
7663
|
+
if (["response.completed", "response.incomplete"].includes(data.type)) {
|
|
7664
|
+
tokens = usage(data.response ?? {}, wire);
|
|
7665
|
+
reason = data.response?.incomplete_details?.reason;
|
|
7666
|
+
finish();
|
|
7667
|
+
}
|
|
7668
|
+
} else {
|
|
7669
|
+
if (data.usageMetadata)
|
|
7670
|
+
tokens = usage(data, wire);
|
|
7671
|
+
const candidate = data.candidates?.[0];
|
|
7672
|
+
for (const item of candidate?.content?.parts ?? []) {
|
|
7673
|
+
if (item.text)
|
|
7674
|
+
text(item.text, !!item.thought);
|
|
7675
|
+
if (item.functionCall)
|
|
7676
|
+
part(`tool-${index}`, { type: "tool_use", id: rememberGeminiTool(item, state), name: item.functionCall.name, input: {} }, { type: "input_json_delta", partial_json: JSON.stringify(item.functionCall.args ?? {}) });
|
|
7677
|
+
}
|
|
7678
|
+
if (candidate?.finishReason) {
|
|
7679
|
+
reason = candidate.finishReason;
|
|
7680
|
+
finish();
|
|
7681
|
+
}
|
|
7682
|
+
}
|
|
7683
|
+
}
|
|
7684
|
+
if (!ended)
|
|
7685
|
+
controller.enqueue(encoder.encode(`: upstream activity
|
|
7686
|
+
|
|
7687
|
+
`));
|
|
7688
|
+
} catch (error) {
|
|
7689
|
+
ended = true;
|
|
7690
|
+
controller.error(error);
|
|
7691
|
+
reader.cancel().catch(() => {});
|
|
7692
|
+
}
|
|
7693
|
+
},
|
|
7694
|
+
async cancel() {
|
|
7695
|
+
ended = true;
|
|
7696
|
+
await reader.cancel().catch(() => {});
|
|
7697
|
+
}
|
|
7698
|
+
});
|
|
7699
|
+
return new Response(stream, { headers: { "content-type": "text/event-stream", "cache-control": "no-store" } });
|
|
7700
|
+
}
|
|
7701
|
+
function prepareOpenCodeMessages(baseUrl, body, suffix, credential, state = new Map) {
|
|
7702
|
+
const lane = openCodeLane(baseUrl);
|
|
7703
|
+
if (!lane)
|
|
7704
|
+
return;
|
|
7705
|
+
const wire = openCodeWire(body.model, lane);
|
|
7706
|
+
if (wire === "messages")
|
|
7707
|
+
return;
|
|
7708
|
+
if (suffix !== "/messages")
|
|
7709
|
+
unsupported2("token counting on a translated model");
|
|
7710
|
+
const chat = toChat(body), outgoing = wire === "responses" ? toResponses(chat) : wire === "gemini" ? toGemini(chat, state) : chat;
|
|
7711
|
+
const path = wire === "responses" ? "/responses" : wire === "gemini" ? `/models/${encodeURIComponent(body.model)}:${body.stream ? "streamGenerateContent?alt=sse" : "generateContent"}` : "/chat/completions";
|
|
7712
|
+
const auth = credential ? wire === "gemini" ? { "x-goog-api-key": credential } : { authorization: `Bearer ${credential}` } : {};
|
|
7713
|
+
return { path, body: outgoing, auth, async response(response) {
|
|
7714
|
+
if (!response.ok || !response.body)
|
|
7715
|
+
return response;
|
|
7716
|
+
if (body.stream) {
|
|
7717
|
+
if (!response.headers.get("content-type")?.includes("text/event-stream"))
|
|
7718
|
+
throw new Fault(502, "invalid_provider_response", "Provider did not return an event stream.");
|
|
7719
|
+
return fromStream(response, wire, body.model, state);
|
|
7720
|
+
}
|
|
7721
|
+
return Response.json(fromJson(await boundedJson(response), wire, body.model, state));
|
|
7722
|
+
} };
|
|
7723
|
+
}
|
|
7724
|
+
|
|
7163
7725
|
// src/inference-gateway.ts
|
|
7164
7726
|
import { createHash as createHash5, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
7165
7727
|
var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
|
|
7166
7728
|
function createInferenceGateway(input, timing = {}) {
|
|
7167
7729
|
const token = crypto.randomUUID() + crypto.randomUUID();
|
|
7730
|
+
const openCodeSession = crypto.randomUUID();
|
|
7731
|
+
const openCodeState = new Map;
|
|
7168
7732
|
const digest = (value) => createHash5("sha256").update(value).digest();
|
|
7169
7733
|
const expected = digest(token), policy = input.compiledPolicy;
|
|
7170
7734
|
const known = new Set(input.models.map((m) => m.id));
|
|
7171
7735
|
const safeModel = (value) => typeof value === "string" && value !== input.credential && (known.has(value) || Object.hasOwn(policy.aliases, value)) ? value : "<unrecognized>";
|
|
7172
|
-
const fail = (status, code) => Response.json({ error: { type: "switcher_model_policy", code, 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 });
|
|
7736
|
+
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 });
|
|
7173
7737
|
let closing = false, stopped;
|
|
7174
7738
|
const active = new Set;
|
|
7175
7739
|
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
|
|
@@ -7256,6 +7820,7 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7256
7820
|
const signal = activity.fetchOptions.signal;
|
|
7257
7821
|
server2.timeout(request, 0);
|
|
7258
7822
|
const headers = { "content-type": "application/json" };
|
|
7823
|
+
Object.assign(headers, openCodeHeaders(input.baseUrl, request.headers, body, openCodeSession));
|
|
7259
7824
|
if (input.credential) {
|
|
7260
7825
|
const [name, value] = gemini ? ["x-goog-api-key", input.credential] : authHeader(input.authStyle ?? "bearer", input.credential);
|
|
7261
7826
|
headers[name] = value;
|
|
@@ -7290,9 +7855,18 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7290
7855
|
const guidance = renderModelGuidance({ harness: input.harness, providerId: input.providerId, baseUrl: input.baseUrl, model, compiled: policy, catalogPath: input.catalogPath });
|
|
7291
7856
|
const compatible2 = input.harness === "codex" && input.protocol === "openai-responses" && new URL(input.baseUrl).hostname !== "api.openai.com" ? normalizeCodexDelegation(payload) : payload;
|
|
7292
7857
|
const outgoing = injectModelGuidance(input.protocol, compatible2, guidance, match?.[2]);
|
|
7293
|
-
const
|
|
7858
|
+
const translated = input.protocol === "anthropic-messages" ? prepareOpenCodeMessages(input.baseUrl, outgoing, suffix, input.credential, openCodeState) : undefined;
|
|
7859
|
+
const path = translated?.path ?? (gemini ? `/models/${encodeURIComponent(model)}:${match[2]}${url.search}` : suffix + (betaQuery ? "?beta=true" : ""));
|
|
7860
|
+
const upstreamHeaders = { ...headers };
|
|
7861
|
+
if (translated) {
|
|
7862
|
+
delete upstreamHeaders["x-api-key"];
|
|
7863
|
+
delete upstreamHeaders.authorization;
|
|
7864
|
+
delete upstreamHeaders["anthropic-version"];
|
|
7865
|
+
delete upstreamHeaders["anthropic-beta"];
|
|
7866
|
+
Object.assign(upstreamHeaders, translated.auth);
|
|
7867
|
+
}
|
|
7294
7868
|
try {
|
|
7295
|
-
response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(outgoing), redirect: "manual", ...activity.fetchOptions }));
|
|
7869
|
+
response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers: upstreamHeaders, body: JSON.stringify(translated?.body ?? outgoing), redirect: "manual", ...activity.fetchOptions }));
|
|
7296
7870
|
} catch {
|
|
7297
7871
|
current.reason = activity.timedOut() ? "provider_idle_timeout" : signal.aborted ? "request_cancelled" : "network_error";
|
|
7298
7872
|
if (!signal.aborted && attempt + 1 < candidates.length)
|
|
@@ -7307,6 +7881,8 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7307
7881
|
response = undefined;
|
|
7308
7882
|
continue;
|
|
7309
7883
|
}
|
|
7884
|
+
if (translated)
|
|
7885
|
+
response = await activity.run(() => translated.response(response));
|
|
7310
7886
|
break;
|
|
7311
7887
|
}
|
|
7312
7888
|
if (!response)
|
|
@@ -7318,7 +7894,11 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7318
7894
|
release();
|
|
7319
7895
|
if (overflow)
|
|
7320
7896
|
return Response.json({ type: "error", error: { type: "invalid_request_error", code: "context_length_exceeded", message: "prompt is too long: the provider context window was exceeded. Compact the conversation or start a new session." } }, { status: 400 });
|
|
7321
|
-
|
|
7897
|
+
const rejected = fail(response.status >= 300 && response.status < 400 ? 502 : response.status, `upstream_http_${response.status}`);
|
|
7898
|
+
const retryAfter = response.headers.get("retry-after");
|
|
7899
|
+
if ((response.status === 429 || response.status === 503) && retryAfter && retryAfter.length <= 128 && (/^\d+$/.test(retryAfter) || Number.isFinite(Date.parse(retryAfter))))
|
|
7900
|
+
rejected.headers.set("retry-after", retryAfter);
|
|
7901
|
+
return rejected;
|
|
7322
7902
|
}
|
|
7323
7903
|
if (!response.body) {
|
|
7324
7904
|
release();
|
|
@@ -7369,7 +7949,7 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7369
7949
|
else if (activity.timedOut())
|
|
7370
7950
|
current.reason = "provider_idle_timeout";
|
|
7371
7951
|
release();
|
|
7372
|
-
return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : "provider_request_failed");
|
|
7952
|
+
return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : "provider_request_failed", error instanceof Fault && error.code === "opencode_translation_unsupported" ? error.message : undefined);
|
|
7373
7953
|
}
|
|
7374
7954
|
} });
|
|
7375
7955
|
return { baseUrl: new URL(input.protocol === "gemini-generate-content" ? "v1beta" : "v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
|
|
@@ -7470,9 +8050,9 @@ function compileCodexModelPolicy(input) {
|
|
|
7470
8050
|
const policy = modelPolicySchema.parse(input.policy ?? {});
|
|
7471
8051
|
const subagentModel = policy.roles?.subagent ?? input.model;
|
|
7472
8052
|
const reviewModel = policy.roles?.review ?? input.model;
|
|
7473
|
-
const
|
|
7474
|
-
if (
|
|
7475
|
-
throw new Error(`Codex does not expose role controls for: ${
|
|
8053
|
+
const unsupported3 = ["fast", "planning", "summary", "compaction", "weak", "editor"].filter((role) => policy.roles?.[role] !== undefined && policy.roles?.[role] !== input.model);
|
|
8054
|
+
if (unsupported3.length)
|
|
8055
|
+
throw new Error(`Codex does not expose role controls for: ${unsupported3.join(", ")}.`);
|
|
7476
8056
|
const agents = [];
|
|
7477
8057
|
const ignoredUntrustedAgents = [];
|
|
7478
8058
|
for (const [name, definition] of Object.entries(input.agents ?? {})) {
|
|
@@ -9728,6 +10308,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9728
10308
|
env.ANTHROPIC_MODEL = input.model;
|
|
9729
10309
|
env.ANTHROPIC_DEFAULT_MODEL = input.model;
|
|
9730
10310
|
env.CLAUDE_CODE_SUBAGENT_MODEL = input.compiledPolicy?.roles.subagent ?? input.model;
|
|
10311
|
+
env.ANTHROPIC_API_KEY = "";
|
|
10312
|
+
env.ANTHROPIC_AUTH_TOKEN = "";
|
|
9731
10313
|
env[input.authStyle === "x-api-key" ? "ANTHROPIC_API_KEY" : "ANTHROPIC_AUTH_TOKEN"] = input.credential ?? "switcher-local-no-auth";
|
|
9732
10314
|
const file2 = await jsonFile(input.stateDir, "claude-settings.json", { modelPicker: { replaceBuiltInOptions: true, options: input.models.map((m) => ({ model: m.id, label: m.name, description: m.description?.slice(0, 300) })) } });
|
|
9733
10315
|
configPaths.push(file2);
|
|
@@ -10080,9 +10662,9 @@ async function prepareHarnessLaunch(input) {
|
|
|
10080
10662
|
input = { ...input, models: input.models.filter((model3) => !modelExpired(model3)) };
|
|
10081
10663
|
const nativePolicy = compileNativeModelPolicy({ harness: input.harness, mainModel: input.model, roles: compiledPolicy.roles, version: input.version });
|
|
10082
10664
|
const specialized = new Set(["opencode", "opencode2", "gemini", "hermes"]);
|
|
10083
|
-
const
|
|
10084
|
-
if (
|
|
10085
|
-
throw new Error(`${input.harness} does not expose native model controls for: ${
|
|
10665
|
+
const unsupported3 = specialized.has(input.harness) ? [] : nativePolicy.unsupportedRoles.filter((role) => role !== "main" && compiledPolicy.roles[role] !== input.model);
|
|
10666
|
+
if (unsupported3.length)
|
|
10667
|
+
throw new Error(`${input.harness} does not expose native model controls for: ${unsupported3.join(", ")}.`);
|
|
10086
10668
|
await mkdir10(input.stateDir, { recursive: true, mode: 448 });
|
|
10087
10669
|
const catalogPath = await jsonFile(input.stateDir, `switcher-model-policy-${randomUUID4()}.json`, { policy: compiledPolicy, models: input.models });
|
|
10088
10670
|
const bridge = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
@@ -10132,72 +10714,817 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
|
|
|
10132
10714
|
|
|
10133
10715
|
// src/launcher.ts
|
|
10134
10716
|
import { mkdir as mkdir11, mkdtemp, rm as rm6, writeFile as writeFile14 } from "fs/promises";
|
|
10135
|
-
import { join as
|
|
10717
|
+
import { join as join16, resolve as resolve9 } from "path";
|
|
10136
10718
|
|
|
10137
|
-
// src/
|
|
10138
|
-
import {
|
|
10139
|
-
import {
|
|
10140
|
-
import {
|
|
10719
|
+
// src/credentials.ts
|
|
10720
|
+
import { z as z7 } from "zod";
|
|
10721
|
+
import { constants as constants5 } from "fs";
|
|
10722
|
+
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
|
+
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 createHash9, randomUUID as randomUUID5 } from "crypto";
|
|
10725
|
+
import { execFile as execFile3, spawn } from "child_process";
|
|
10726
|
+
import { promisify as promisify3 } from "util";
|
|
10727
|
+
import { createInterface } from "readline/promises";
|
|
10728
|
+
import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
|
|
10729
|
+
var execute3 = promisify3(execFile3);
|
|
10730
|
+
var reference = z7.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
|
|
10731
|
+
var item = z7.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
|
|
10732
|
+
var vaultKey = 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
|
+
var keychain = z7.object({ kind: z7.literal("keychain"), service: item, account: item }).strict();
|
|
10734
|
+
var credentialTier = z7.enum(["argument", "override", "pointer", "profile", "keychain", "disk", "env"]);
|
|
10735
|
+
var operator = z7.discriminatedUnion("kind", [
|
|
10736
|
+
z7.object({ kind: z7.literal("contracts"), expectedSource: item.optional(), expectedTier: credentialTier.optional() }).strict(),
|
|
10737
|
+
z7.object({ kind: z7.literal("env") }).strict(),
|
|
10738
|
+
z7.object({ kind: z7.literal("keychain"), account: item.refine((value) => value.trim().length > 0 && value === value.trim(), "Vault account must be nonblank without surrounding whitespace") }).strict()
|
|
10739
|
+
]);
|
|
10740
|
+
var origin = z7.string().transform((value) => new URL(endpoint(value)).origin);
|
|
10741
|
+
var credentialBindingSchema = z7.object({
|
|
10742
|
+
schema: z7.literal(1),
|
|
10743
|
+
credentialEnv: reference,
|
|
10744
|
+
origins: z7.array(origin).min(1).max(30),
|
|
10745
|
+
requireProviderAuthentication: z7.literal(true).optional(),
|
|
10746
|
+
source: z7.discriminatedUnion("kind", [keychain, z7.object({
|
|
10747
|
+
kind: z7.literal("vault"),
|
|
10748
|
+
key: vaultKey,
|
|
10749
|
+
url: z7.string().max(2000).transform(endpoint).optional(),
|
|
10750
|
+
executable: z7.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute13, "Secrets executable must be an absolute path"),
|
|
10751
|
+
operator
|
|
10752
|
+
}).strict()])
|
|
10753
|
+
}).strict().superRefine((binding, ctx) => {
|
|
10754
|
+
if (binding.source.kind === "vault" && binding.source.operator.kind !== "contracts" && !binding.source.url)
|
|
10755
|
+
ctx.addIssue({ code: "custom", path: ["source", "url"], message: "An explicit env or Keychain operator binding requires a vault URL." });
|
|
10756
|
+
if (binding.source.kind === "vault" && binding.source.operator.kind === "contracts" && Boolean(binding.source.operator.expectedSource) !== Boolean(binding.source.operator.expectedTier))
|
|
10757
|
+
ctx.addIssue({ code: "custom", path: ["source", "operator"], message: "A pinned Contracts operator requires both expectedSource and expectedTier." });
|
|
10758
|
+
});
|
|
10759
|
+
var fingerprint = (binding) => createHash9("sha256").update(JSON.stringify(binding)).digest("hex");
|
|
10141
10760
|
|
|
10142
|
-
|
|
10143
|
-
|
|
10144
|
-
|
|
10145
|
-
|
|
10146
|
-
|
|
10147
|
-
|
|
10148
|
-
const handle = dlopen(library, { dup: { args: ["int"], returns: "int" } });
|
|
10149
|
-
return { duplicate(fd) {
|
|
10150
|
-
const copy = handle.symbols.dup(fd);
|
|
10151
|
-
if (copy < 3)
|
|
10152
|
-
throw new Error("A redirected terminal descriptor could not be duplicated.");
|
|
10153
|
-
return copy;
|
|
10154
|
-
}, close: () => handle.close() };
|
|
10155
|
-
} catch {}
|
|
10761
|
+
class CredentialBindings {
|
|
10762
|
+
env;
|
|
10763
|
+
directory;
|
|
10764
|
+
constructor(env = process.env) {
|
|
10765
|
+
this.env = env;
|
|
10766
|
+
this.directory = join13(switcherHome(env), "config", "credential-bindings");
|
|
10156
10767
|
}
|
|
10157
|
-
|
|
10158
|
-
|
|
10159
|
-
|
|
10160
|
-
|
|
10161
|
-
|
|
10162
|
-
|
|
10163
|
-
const grouped = process.platform !== "win32", interactive = !options.silent && grouped && tty.some(Boolean);
|
|
10164
|
-
const redirects = interactive ? tty.flatMap((value, index) => value ? [] : [index]) : [];
|
|
10165
|
-
const duplicator = redirects.length ? await terminalDescriptorDuplicator() : undefined;
|
|
10166
|
-
return new Promise((resolveResult, reject2) => {
|
|
10167
|
-
const wasRaw = process.stdin.isRaw, wasFlowing = process.stdin.readableFlowing;
|
|
10168
|
-
let controllingInput;
|
|
10169
|
-
let inputTimer;
|
|
10170
|
-
let terminalFailure;
|
|
10171
|
-
let terminal;
|
|
10172
|
-
let terminalMode;
|
|
10173
|
-
let controllingOutput;
|
|
10174
|
-
const output = tty[1] ? process.stdout : tty[2] ? process.stderr : undefined;
|
|
10175
|
-
const stty = (args) => {
|
|
10176
|
-
const descriptor = openSync("/dev/tty", "r+");
|
|
10768
|
+
path(name) {
|
|
10769
|
+
return join13(this.directory, parse2(reference, name) + ".json");
|
|
10770
|
+
}
|
|
10771
|
+
async readableDirectory() {
|
|
10772
|
+
for (const path of [switcherHome(this.env), join13(switcherHome(this.env), "config"), this.directory]) {
|
|
10773
|
+
let info;
|
|
10177
10774
|
try {
|
|
10178
|
-
|
|
10179
|
-
|
|
10180
|
-
|
|
10181
|
-
|
|
10182
|
-
|
|
10183
|
-
closeSync(descriptor);
|
|
10775
|
+
info = await lstat4(path);
|
|
10776
|
+
} catch (error) {
|
|
10777
|
+
if (error.code === "ENOENT")
|
|
10778
|
+
return false;
|
|
10779
|
+
throw error;
|
|
10184
10780
|
}
|
|
10185
|
-
|
|
10186
|
-
|
|
10187
|
-
|
|
10188
|
-
|
|
10189
|
-
|
|
10190
|
-
|
|
10191
|
-
|
|
10192
|
-
|
|
10193
|
-
|
|
10194
|
-
|
|
10195
|
-
|
|
10196
|
-
|
|
10197
|
-
|
|
10198
|
-
|
|
10199
|
-
|
|
10200
|
-
|
|
10781
|
+
if (!info.isDirectory() || info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid?.()))
|
|
10782
|
+
throw new Fault(500, "credential_binding_permissions", "Credential binding directories must be real, owner-only directories (mode 0700).");
|
|
10783
|
+
}
|
|
10784
|
+
return true;
|
|
10785
|
+
}
|
|
10786
|
+
async get(name) {
|
|
10787
|
+
const path = this.path(name);
|
|
10788
|
+
if (!await this.readableDirectory())
|
|
10789
|
+
return;
|
|
10790
|
+
let file;
|
|
10791
|
+
try {
|
|
10792
|
+
file = await open3(path, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
|
|
10793
|
+
} catch (error) {
|
|
10794
|
+
if (error.code === "ENOENT")
|
|
10795
|
+
return;
|
|
10796
|
+
throw new Fault(500, "credential_binding_unreadable", "Cannot safely open the local credential binding.");
|
|
10797
|
+
}
|
|
10798
|
+
try {
|
|
10799
|
+
const info = await file.stat();
|
|
10800
|
+
if (!info.isFile() || info.size > 32768 || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid?.()))
|
|
10801
|
+
throw new Fault(500, "credential_binding_permissions", "Credential binding must be an owner-only regular file (mode 0600).");
|
|
10802
|
+
let value;
|
|
10803
|
+
try {
|
|
10804
|
+
value = JSON.parse(await file.readFile("utf8"));
|
|
10805
|
+
} catch {
|
|
10806
|
+
throw new Fault(500, "credential_binding_invalid", "Credential binding must contain valid JSON.");
|
|
10807
|
+
}
|
|
10808
|
+
const binding = parse2(credentialBindingSchema, value);
|
|
10809
|
+
if (binding.credentialEnv !== name)
|
|
10810
|
+
throw new Fault(500, "credential_binding_invalid", "Credential binding reference does not match its filename.");
|
|
10811
|
+
return binding;
|
|
10812
|
+
} finally {
|
|
10813
|
+
await file.close();
|
|
10814
|
+
}
|
|
10815
|
+
}
|
|
10816
|
+
async list() {
|
|
10817
|
+
if (!await this.readableDirectory())
|
|
10818
|
+
return [];
|
|
10819
|
+
let entries;
|
|
10820
|
+
try {
|
|
10821
|
+
entries = await readdir5(this.directory);
|
|
10822
|
+
} catch (error) {
|
|
10823
|
+
if (error.code === "ENOENT")
|
|
10824
|
+
return [];
|
|
10825
|
+
throw error;
|
|
10826
|
+
}
|
|
10827
|
+
const result = [];
|
|
10828
|
+
for (const name of entries.sort())
|
|
10829
|
+
if (/^SWITCHER_PROVIDER_[A-Z0-9_]+\.json$/.test(name)) {
|
|
10830
|
+
const binding = await this.get(name.slice(0, -5));
|
|
10831
|
+
if (binding)
|
|
10832
|
+
result.push(binding);
|
|
10833
|
+
}
|
|
10834
|
+
return result;
|
|
10835
|
+
}
|
|
10836
|
+
async bind(input) {
|
|
10837
|
+
const binding = parse2(credentialBindingSchema, input);
|
|
10838
|
+
if (binding.source.kind === "vault")
|
|
10839
|
+
await validateVaultExecutable(binding.source.executable);
|
|
10840
|
+
await privateDirectory(switcherHome(this.env));
|
|
10841
|
+
await privateDirectory(join13(switcherHome(this.env), "config"));
|
|
10842
|
+
await privateDirectory(this.directory);
|
|
10843
|
+
const temporary = join13(this.directory, `.binding-${randomUUID5()}`);
|
|
10844
|
+
const file = await open3(temporary, "wx", 384);
|
|
10845
|
+
try {
|
|
10846
|
+
await file.writeFile(JSON.stringify(binding, null, 2) + `
|
|
10847
|
+
`);
|
|
10848
|
+
await file.sync();
|
|
10849
|
+
try {
|
|
10850
|
+
await link(temporary, this.path(binding.credentialEnv));
|
|
10851
|
+
} catch (error) {
|
|
10852
|
+
if (error.code !== "EEXIST")
|
|
10853
|
+
throw error;
|
|
10854
|
+
const existing = await this.get(binding.credentialEnv);
|
|
10855
|
+
if (existing && fingerprint(existing) === fingerprint(binding))
|
|
10856
|
+
return existing;
|
|
10857
|
+
throw new Fault(409, "credential_binding_exists", "A different binding already exists. Remove it explicitly before binding another credential account.");
|
|
10858
|
+
}
|
|
10859
|
+
} finally {
|
|
10860
|
+
await file.close();
|
|
10861
|
+
await unlink(temporary);
|
|
10862
|
+
}
|
|
10863
|
+
return binding;
|
|
10864
|
+
}
|
|
10865
|
+
async remove(name) {
|
|
10866
|
+
const binding = await this.get(name);
|
|
10867
|
+
if (!binding)
|
|
10868
|
+
throw new Fault(404, "credential_binding_missing", "No local credential binding exists for this reference.");
|
|
10869
|
+
await unlink(this.path(name));
|
|
10870
|
+
return { removed: name };
|
|
10871
|
+
}
|
|
10872
|
+
}
|
|
10873
|
+
function credentialReference(selector) {
|
|
10874
|
+
const name = selector.startsWith("SWITCHER_PROVIDER_") ? selector : getProviderPreset(selector).credentialEnv;
|
|
10875
|
+
if (!name)
|
|
10876
|
+
throw new Fault(400, "credential_reference_required", "Use the explicit SWITCHER_PROVIDER_ reference for this provider.");
|
|
10877
|
+
return parse2(reference, name);
|
|
10878
|
+
}
|
|
10879
|
+
async function inspectVaultExecutable(path, permitWritableFile = false) {
|
|
10880
|
+
let info, resolved;
|
|
10881
|
+
try {
|
|
10882
|
+
resolved = await realpath6(path);
|
|
10883
|
+
await access4(resolved, constants5.X_OK);
|
|
10884
|
+
info = await stat6(resolved);
|
|
10885
|
+
if (!info.isFile())
|
|
10886
|
+
throw new Error;
|
|
10887
|
+
} catch {
|
|
10888
|
+
throw new Fault(422, "vault_exec_unavailable", "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.");
|
|
10889
|
+
}
|
|
10890
|
+
if (process.platform !== "win32" && (!permitWritableFile && info.mode & 18 || info.uid !== 0 && info.uid !== process.getuid?.()))
|
|
10891
|
+
throw new Fault(422, "vault_exec_permissions", "The secrets executable must be owned by this user or root and not writable by other users. Choose a trusted installation, or use credentials repair-executable REFERENCE --sha256 EXPECTED with the executable digest from a verified package artifact. Launch never repairs permissions automatically.");
|
|
10892
|
+
if (process.platform !== "win32") {
|
|
10893
|
+
const seen = new Set;
|
|
10894
|
+
const inspect = async (candidate) => {
|
|
10895
|
+
let prefix = pathParts(candidate).root;
|
|
10896
|
+
for (const part of candidate.slice(prefix.length).split(sep2)) {
|
|
10897
|
+
if (!part)
|
|
10898
|
+
continue;
|
|
10899
|
+
prefix = join13(prefix, part);
|
|
10900
|
+
if (seen.has(prefix))
|
|
10901
|
+
continue;
|
|
10902
|
+
seen.add(prefix);
|
|
10903
|
+
if (seen.size > 256)
|
|
10904
|
+
throw new Fault(422, "vault_exec_permissions", "The secrets executable path has too many symlink components.");
|
|
10905
|
+
const entry = await lstat4(prefix);
|
|
10906
|
+
const permittedFile = permitWritableFile && prefix === resolved && entry.isFile();
|
|
10907
|
+
if (entry.uid !== 0 && entry.uid !== process.getuid?.() || !entry.isSymbolicLink() && !permittedFile && entry.mode & 18)
|
|
10908
|
+
throw new Fault(422, "vault_exec_permissions", "The secrets executable and its ancestor directories must not be replaceable by other users. Choose an installation owned by this user or root without group/public write permissions.");
|
|
10909
|
+
if (entry.isSymbolicLink())
|
|
10910
|
+
await inspect(resolvePath(dirname8(prefix), await readlink(prefix)));
|
|
10911
|
+
}
|
|
10912
|
+
};
|
|
10913
|
+
try {
|
|
10914
|
+
await inspect(path);
|
|
10915
|
+
await inspect(resolved);
|
|
10916
|
+
} catch (error) {
|
|
10917
|
+
if (error instanceof Fault)
|
|
10918
|
+
throw error;
|
|
10919
|
+
throw new Fault(422, "vault_exec_unavailable", "The secrets executable path changed or could not be verified. Retry with a trusted installation.");
|
|
10920
|
+
}
|
|
10921
|
+
}
|
|
10922
|
+
return resolved;
|
|
10923
|
+
}
|
|
10924
|
+
async function validateVaultExecutable(path) {
|
|
10925
|
+
return inspectVaultExecutable(path);
|
|
10926
|
+
}
|
|
10927
|
+
async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
10928
|
+
if (!/^[a-f0-9]{64}$/.test(expectedSha256))
|
|
10929
|
+
throw new Fault(400, "invalid_request", "--sha256 requires the SHA256 of the executable member from a verified package artifact.");
|
|
10930
|
+
if (!isAbsolute13(path) || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path))
|
|
10931
|
+
throw new Fault(400, "invalid_request", "Secrets executable must be an absolute path without control characters.");
|
|
10932
|
+
if (process.platform === "win32")
|
|
10933
|
+
throw new Fault(422, "vault_exec_repair_unsafe", "Executable permission repair requires POSIX file permissions.");
|
|
10934
|
+
const resolved = await inspectVaultExecutable(path, true);
|
|
10935
|
+
const file = await open3(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
|
|
10936
|
+
const unsafe = () => new Fault(422, "vault_exec_repair_unsafe", "Executable ownership, type, links or contents changed; no trusted repair can be confirmed.");
|
|
10937
|
+
let temporary;
|
|
10938
|
+
try {
|
|
10939
|
+
const before = await file.stat();
|
|
10940
|
+
const limit = 256 * 1024 * 1024;
|
|
10941
|
+
if (!before.isFile() || before.uid !== process.getuid?.() || before.size > limit || before.mode & 3584)
|
|
10942
|
+
throw unsafe();
|
|
10943
|
+
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 hash2 = async (target) => {
|
|
10945
|
+
const digest = createHash9("sha256");
|
|
10946
|
+
const buffer = Buffer.alloc(1024 * 1024);
|
|
10947
|
+
let position = 0;
|
|
10948
|
+
while (true) {
|
|
10949
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
|
|
10950
|
+
if (!bytesRead)
|
|
10951
|
+
break;
|
|
10952
|
+
position += bytesRead;
|
|
10953
|
+
if (position > limit)
|
|
10954
|
+
throw unsafe();
|
|
10955
|
+
const bytes = buffer.subarray(0, bytesRead);
|
|
10956
|
+
digest.update(bytes);
|
|
10957
|
+
if (target)
|
|
10958
|
+
await target.writeFile(bytes);
|
|
10959
|
+
}
|
|
10960
|
+
if (position !== before.size || !sameFile(await file.stat()))
|
|
10961
|
+
throw unsafe();
|
|
10962
|
+
if (digest.digest("hex") !== expectedSha256)
|
|
10963
|
+
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
|
+
};
|
|
10965
|
+
await hash2();
|
|
10966
|
+
const mode = before.mode & 511 & ~18;
|
|
10967
|
+
const changed = mode !== (before.mode & 511);
|
|
10968
|
+
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat4(resolved)))
|
|
10969
|
+
throw unsafe();
|
|
10970
|
+
if (!changed) {
|
|
10971
|
+
await validateVaultExecutable(path);
|
|
10972
|
+
return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
|
|
10973
|
+
}
|
|
10974
|
+
temporary = join13(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
|
|
10975
|
+
const replacement = await open3(temporary, "wx", 384);
|
|
10976
|
+
try {
|
|
10977
|
+
await hash2(replacement);
|
|
10978
|
+
await replacement.chmod(mode);
|
|
10979
|
+
await replacement.sync();
|
|
10980
|
+
const ready = await replacement.stat();
|
|
10981
|
+
if (!ready.isFile() || ready.nlink !== 1 || ready.uid !== before.uid || ready.size !== before.size)
|
|
10982
|
+
throw unsafe();
|
|
10983
|
+
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat4(resolved)))
|
|
10984
|
+
throw unsafe();
|
|
10985
|
+
await rename2(temporary, resolved);
|
|
10986
|
+
temporary = undefined;
|
|
10987
|
+
const installed = await lstat4(resolved);
|
|
10988
|
+
if (installed.dev !== ready.dev || installed.ino !== ready.ino || await validateVaultExecutable(path) !== resolved)
|
|
10989
|
+
throw unsafe();
|
|
10990
|
+
const directory = await open3(dirname8(resolved), constants5.O_RDONLY | constants5.O_DIRECTORY | constants5.O_NOFOLLOW);
|
|
10991
|
+
try {
|
|
10992
|
+
await directory.sync();
|
|
10993
|
+
} finally {
|
|
10994
|
+
await directory.close();
|
|
10995
|
+
}
|
|
10996
|
+
} finally {
|
|
10997
|
+
await replacement.close();
|
|
10998
|
+
}
|
|
10999
|
+
return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
|
|
11000
|
+
} finally {
|
|
11001
|
+
await file.close();
|
|
11002
|
+
if (temporary)
|
|
11003
|
+
await unlink(temporary);
|
|
11004
|
+
}
|
|
11005
|
+
}
|
|
11006
|
+
function bindingTarget(selector, override, allowedOrigins) {
|
|
11007
|
+
if (selector.startsWith("SWITCHER_PROVIDER_")) {
|
|
11008
|
+
if (override)
|
|
11009
|
+
throw new Fault(400, "conflicting_options", "A credential reference does not also need --credential-env.");
|
|
11010
|
+
if (!allowedOrigins?.length)
|
|
11011
|
+
throw new Fault(400, "credential_origin_required", "Use --origin URL to authorize a custom credential destination.");
|
|
11012
|
+
return { credentialEnv: parse2(reference, selector), origins: allowedOrigins.map((value) => new URL(endpoint(value)).origin) };
|
|
11013
|
+
}
|
|
11014
|
+
const preset2 = getProviderPreset(selector);
|
|
11015
|
+
const credentialEnv = override ?? preset2.credentialEnv;
|
|
11016
|
+
if (!credentialEnv)
|
|
11017
|
+
throw new Fault(400, "credential_reference_required", "Use --credential-env for a preset without a default credential reference.");
|
|
11018
|
+
const origins = allowedOrigins ?? [...new Set(preset2.protocols.flatMap((route2) => route2.baseUrl ? [new URL(route2.baseUrl).origin] : []))];
|
|
11019
|
+
if (!origins.length)
|
|
11020
|
+
throw new Fault(400, "credential_origin_required", "Use --origin URL for this custom preset.");
|
|
11021
|
+
return { credentialEnv: parse2(reference, credentialEnv), origins };
|
|
11022
|
+
}
|
|
11023
|
+
async function readKeychain(source) {
|
|
11024
|
+
if (process.platform !== "darwin")
|
|
11025
|
+
throw new Fault(422, "keychain_unavailable", "This binding requires macOS Keychain. Use a supported vault binding or runtime environment on this station.");
|
|
11026
|
+
let stdout;
|
|
11027
|
+
try {
|
|
11028
|
+
({ stdout } = await execute3("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 }));
|
|
11029
|
+
} catch (error) {
|
|
11030
|
+
const status = error.code;
|
|
11031
|
+
if (status === 44)
|
|
11032
|
+
throw new Fault(422, "keychain_item_missing", "The configured Keychain item does not exist for that service and account; no alternate credential was selected.");
|
|
11033
|
+
throw new Fault(422, "keychain_unavailable", `The configured Keychain item could not be read (security exited ${typeof status === "number" ? status : "without a status"}); it is locked or inaccessible. No alternate credential was selected.`);
|
|
11034
|
+
}
|
|
11035
|
+
const value = stdout.replace(/\r?\n$/, "");
|
|
11036
|
+
if (!value || /[\x00-\x1f\x7f]/.test(value))
|
|
11037
|
+
throw new Fault(422, "keychain_item_invalid", "The configured Keychain item holds an unusable value; no alternate credential was selected.");
|
|
11038
|
+
return value;
|
|
11039
|
+
}
|
|
11040
|
+
|
|
11041
|
+
class CredentialResolver {
|
|
11042
|
+
env;
|
|
11043
|
+
keychainRead;
|
|
11044
|
+
bindings;
|
|
11045
|
+
constructor(env = process.env, keychainRead = readKeychain) {
|
|
11046
|
+
this.env = env;
|
|
11047
|
+
this.keychainRead = keychainRead;
|
|
11048
|
+
this.bindings = new CredentialBindings(env);
|
|
11049
|
+
}
|
|
11050
|
+
async resolve(provider) {
|
|
11051
|
+
if (!provider.credentialEnv)
|
|
11052
|
+
return;
|
|
11053
|
+
const binding = await this.bindings.get(provider.credentialEnv);
|
|
11054
|
+
if (!binding)
|
|
11055
|
+
return providerCredential(provider, this.env);
|
|
11056
|
+
if (!binding.origins.includes(new URL(provider.baseUrl).origin))
|
|
11057
|
+
throw new Fault(422, "credential_authority", "The local credential binding does not authorize this provider origin. Update the binding explicitly; no key was sent.");
|
|
11058
|
+
if (binding.source.kind === "keychain")
|
|
11059
|
+
return this.keychainRead(binding.source);
|
|
11060
|
+
return fetchVaultCredential(binding, this.env);
|
|
11061
|
+
}
|
|
11062
|
+
async check(name) {
|
|
11063
|
+
const binding = await this.bindings.get(name);
|
|
11064
|
+
if (!binding)
|
|
11065
|
+
throw new Fault(404, "credential_binding_missing", "No local credential binding exists for this reference.");
|
|
11066
|
+
if (binding.source.kind === "vault") {
|
|
11067
|
+
const output = await runVaultCommand(binding, ["get", binding.source.key, "--check"], this.env, {}, {
|
|
11068
|
+
captureBytes: 4096,
|
|
11069
|
+
oversizeCode: "vault_check_failed",
|
|
11070
|
+
oversizeMessage: "The secrets CLI returned an oversized check result."
|
|
11071
|
+
});
|
|
11072
|
+
const match = /^key=\S+ length=(\d+) sha256=([a-f0-9]{64})\s*$/.exec(output);
|
|
11073
|
+
if (!match)
|
|
11074
|
+
throw new Fault(422, "vault_check_failed", "The secrets CLI did not return a supported credential check result.");
|
|
11075
|
+
return { credentialEnv: name, source: "vault", available: true, length: Number(match[1]), sha256: match[2], providerAuthentication: "not tested" };
|
|
11076
|
+
}
|
|
11077
|
+
const value = await this.keychainRead(binding.source);
|
|
11078
|
+
return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash9("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
|
|
11079
|
+
}
|
|
11080
|
+
}
|
|
11081
|
+
var DELIVERY_URL = "SWITCHER_CREDENTIAL_DELIVERY_URL";
|
|
11082
|
+
var DELIVERY_NONCE = "SWITCHER_CREDENTIAL_DELIVERY_NONCE";
|
|
11083
|
+
var DELIVERY_VALUE = "SWITCHER_CREDENTIAL_DELIVERY_VALUE";
|
|
11084
|
+
|
|
11085
|
+
class CredentialInterrupted extends CommandInterrupted {
|
|
11086
|
+
constructor(exitCode) {
|
|
11087
|
+
super(exitCode, "Credential lookup was interrupted; no harness was started.");
|
|
11088
|
+
}
|
|
11089
|
+
}
|
|
11090
|
+
async function resolveVaultOperatorEnvironment(binding, env, options = {}) {
|
|
11091
|
+
if (binding.source.kind !== "vault")
|
|
11092
|
+
throw new Fault(500, "credential_resolution", "Unexpected credential source.");
|
|
11093
|
+
const source = binding.source;
|
|
11094
|
+
let credential, url = source.url;
|
|
11095
|
+
try {
|
|
11096
|
+
if (source.operator.kind === "contracts") {
|
|
11097
|
+
const pair = () => {
|
|
11098
|
+
const keys = clientTransportEnvKeys3("secrets");
|
|
11099
|
+
const configuredUrl = keys.apiUrlKeys.map((name) => env[name]).find((value) => value !== undefined) ?? keychainConfigValue2("secrets", env, options.keychain)?.value ?? appConfigDiskValue2("secrets", env, keys.apiUrlKeys)?.value;
|
|
11100
|
+
const resolution = resolveClientTransport("secrets", env, { credentials: options });
|
|
11101
|
+
const key = resolveCredential("secrets", env, options);
|
|
11102
|
+
if (key?.tier === "pointer")
|
|
11103
|
+
throw new Fault(422, "vault_operator_pointer", "A Secrets operator cannot bootstrap itself through HASNA_SECRETS_API_KEY_REF. Configure its operator in Keychain, canonical config/credentials, or an explicit key override.");
|
|
11104
|
+
if (!key?.apiKey || key.source !== resolution.apiKeySource || key.tier !== resolution.apiKeyTier)
|
|
11105
|
+
throw new Fault(422, "vault_operator_changed", "The vault operator changed during resolution; no credential was sent. Retry after configuration is stable.");
|
|
11106
|
+
const boundUrl = source.url ? toV1BaseUrl(source.url) : resolution.baseUrl;
|
|
11107
|
+
if (resolution.apiUrlSource !== "default" && boundUrl !== resolution.baseUrl)
|
|
11108
|
+
throw new Fault(422, "vault_operator_authority", "The binding vault URL conflicts with the canonical Secrets API URL; no credential was sent.");
|
|
11109
|
+
if (configuredUrl !== undefined && toV1BaseUrl(configuredUrl) !== resolution.baseUrl)
|
|
11110
|
+
throw new Fault(422, "vault_operator_changed", "The vault authority changed during resolution; no credential was sent.");
|
|
11111
|
+
return { key, url: configuredUrl?.trim() ?? source.url ?? boundUrl.replace(/\/v1$/, "") };
|
|
11112
|
+
};
|
|
11113
|
+
const first = pair(), second = pair();
|
|
11114
|
+
if (first.key.apiKey !== second.key.apiKey || first.key.source !== second.key.source || first.key.tier !== second.key.tier || first.url !== second.url)
|
|
11115
|
+
throw new Fault(422, "vault_operator_changed", "The vault operator or authority changed during resolution; no credential was sent. Retry after configuration is stable.");
|
|
11116
|
+
if (source.operator.expectedSource && (second.key.source !== source.operator.expectedSource || second.key.tier !== source.operator.expectedTier))
|
|
11117
|
+
throw new Fault(422, "vault_operator_changed", `The selected Secrets account/source changed from ${source.operator.expectedSource}; no alternate account was selected. Restore that source or rebind explicitly.`);
|
|
11118
|
+
credential = second.key;
|
|
11119
|
+
url = second.url;
|
|
11120
|
+
} else {
|
|
11121
|
+
credential = source.operator.kind === "keychain" ? resolveCredential("secrets", { HASNA_STATION: source.operator.account }, { keychain: { ...options.keychain, enabled: true } }) : resolveCredential("secrets", Object.fromEntries(Object.entries(env).filter(([name]) => name === "HASNA_SECRETS_API_KEY")), { keychain: { enabled: false } });
|
|
11122
|
+
}
|
|
11123
|
+
} catch (error) {
|
|
11124
|
+
if (error instanceof Fault)
|
|
11125
|
+
throw error;
|
|
11126
|
+
const kind = error instanceof Error ? error.name : "";
|
|
11127
|
+
const detail = error instanceof Error ? error.message : "";
|
|
11128
|
+
const reason = /keychain|security exited/i.test(detail) ? "selected Secrets Keychain source is locked or inaccessible" : kind === "CredentialFileUnsafeError" ? "unsafe canonical config/credentials file" : kind === "ClientTransportConfigurationError" ? "invalid or missing canonical API URL/key" : source.operator.kind === "keychain" ? "unavailable pinned Keychain account" : "credential selection refused by Contracts (Keychain, canonical file, profile, or environment)";
|
|
11129
|
+
throw new Fault(422, "vault_operator_unavailable", `Cannot resolve the Secrets vault operator: ${reason}. Check the selected source in this terminal session; no alternate account was selected.`);
|
|
11130
|
+
}
|
|
11131
|
+
if (!credential?.apiKey)
|
|
11132
|
+
throw new Fault(422, "vault_operator_missing", "The selected vault operator has no credential. Use a canonical Contracts binding, restore its named Keychain account, or inject HASNA_SECRETS_API_KEY for an explicit env binding.");
|
|
11133
|
+
const allowed = /^(PATH|HOME|USER|LOGNAME|SHELL|LANG|LC_[A-Z_]+|TMPDIR|TEMP|TMP|HASNA_HOME|HASNA_CONFIG_HOME|HASNA_SECRETS_HOME|HASNA_STATION)$/;
|
|
11134
|
+
const next = Object.fromEntries(Object.entries(env).filter(([name]) => allowed.test(name)));
|
|
11135
|
+
next.HASNA_SECRETS_API_URL = url;
|
|
11136
|
+
next.HASNA_SECRETS_API_KEY = credential.apiKey;
|
|
11137
|
+
next.HASNA_SECRETS_API_KEY_OVERRIDE = credential.apiKey;
|
|
11138
|
+
if (binding.source.operator.kind === "keychain")
|
|
11139
|
+
next.HASNA_STATION = binding.source.operator.account;
|
|
11140
|
+
return { environment: next, source: credential.source, tier: credential.tier, url };
|
|
11141
|
+
}
|
|
11142
|
+
async function runVaultCommand(binding, args, env, delivery = {}, options = {}) {
|
|
11143
|
+
if (binding.source.kind !== "vault")
|
|
11144
|
+
throw new Fault(500, "credential_resolution", "Unexpected credential source.");
|
|
11145
|
+
if (process.platform === "win32")
|
|
11146
|
+
throw new Fault(422, "vault_exec_unavailable", "Vault CLI bindings currently require POSIX process groups; use runtime environment injection on Windows.");
|
|
11147
|
+
const executable = await validateVaultExecutable(binding.source.executable);
|
|
11148
|
+
const operator2 = options.operator ?? await resolveVaultOperatorEnvironment(binding, env);
|
|
11149
|
+
const childEnv = { ...operator2.environment, ...delivery };
|
|
11150
|
+
return new Promise((resolveResult, reject2) => {
|
|
11151
|
+
const child = spawn(executable, args, { env: childEnv, stdio: ["ignore", options.captureBytes ? "pipe" : "ignore", "ignore"], detached: true, shell: false });
|
|
11152
|
+
let failure;
|
|
11153
|
+
let output = "";
|
|
11154
|
+
let outputBytes = 0;
|
|
11155
|
+
let cleaned = false;
|
|
11156
|
+
const kill = () => {
|
|
11157
|
+
if (child.pid) {
|
|
11158
|
+
try {
|
|
11159
|
+
process.kill(-child.pid, "SIGKILL");
|
|
11160
|
+
} catch {}
|
|
11161
|
+
}
|
|
11162
|
+
};
|
|
11163
|
+
const interrupt = (signal) => {
|
|
11164
|
+
failure = new CredentialInterrupted(signal === "SIGINT" ? 130 : 143);
|
|
11165
|
+
process.exitCode = signal === "SIGINT" ? 130 : 143;
|
|
11166
|
+
kill();
|
|
11167
|
+
};
|
|
11168
|
+
const onInt = () => interrupt("SIGINT");
|
|
11169
|
+
const onTerm = () => interrupt("SIGTERM");
|
|
11170
|
+
process.on("SIGINT", onInt);
|
|
11171
|
+
process.on("SIGTERM", onTerm);
|
|
11172
|
+
const timeout = setTimeout(() => {
|
|
11173
|
+
failure = new Fault(504, "vault_timeout", "Credential lookup exceeded 20 seconds; no alternate credential was selected.");
|
|
11174
|
+
kill();
|
|
11175
|
+
}, 20000);
|
|
11176
|
+
const cleanup = () => {
|
|
11177
|
+
if (cleaned)
|
|
11178
|
+
return;
|
|
11179
|
+
cleaned = true;
|
|
11180
|
+
clearTimeout(timeout);
|
|
11181
|
+
process.off("SIGINT", onInt);
|
|
11182
|
+
process.off("SIGTERM", onTerm);
|
|
11183
|
+
kill();
|
|
11184
|
+
};
|
|
11185
|
+
child.stdout?.on("data", (chunk) => {
|
|
11186
|
+
outputBytes += chunk.length;
|
|
11187
|
+
if (outputBytes > (options.captureBytes ?? 0)) {
|
|
11188
|
+
failure = new Fault(422, options.oversizeCode ?? "vault_check_failed", options.oversizeMessage ?? "The secrets CLI returned an oversized result.");
|
|
11189
|
+
kill();
|
|
11190
|
+
} else
|
|
11191
|
+
output += chunk.toString("utf8");
|
|
11192
|
+
});
|
|
11193
|
+
child.once("error", () => {
|
|
11194
|
+
cleanup();
|
|
11195
|
+
reject2(new Fault(422, "vault_exec_failed", "The configured secrets CLI could not start; check its executable and permissions."));
|
|
11196
|
+
});
|
|
11197
|
+
child.once("exit", cleanup);
|
|
11198
|
+
child.once("close", (code) => {
|
|
11199
|
+
if (failure)
|
|
11200
|
+
reject2(failure);
|
|
11201
|
+
else if (code !== 0)
|
|
11202
|
+
reject2(new Fault(422, options.lookupCode ?? "vault_lookup_failed", options.lookupMessage ?? "The secrets CLI could not read the configured key. Check vault access and conflicting local vault URL settings; no alternate account was selected."));
|
|
11203
|
+
else
|
|
11204
|
+
resolveResult(output);
|
|
11205
|
+
});
|
|
11206
|
+
});
|
|
11207
|
+
}
|
|
11208
|
+
async function fetchVaultCredential(binding, env) {
|
|
11209
|
+
if (binding.source.kind !== "vault")
|
|
11210
|
+
throw new Fault(500, "credential_resolution", "Unexpected credential source.");
|
|
11211
|
+
const nonce = crypto.randomUUID() + crypto.randomUUID();
|
|
11212
|
+
let value;
|
|
11213
|
+
const broker = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 65536, async fetch(request) {
|
|
11214
|
+
if (request.method !== "POST" || new URL(request.url).pathname !== "/credential" || request.headers.get("authorization") !== `Bearer ${nonce}` || value !== undefined)
|
|
11215
|
+
return new Response(null, { status: 404 });
|
|
11216
|
+
let candidate;
|
|
11217
|
+
try {
|
|
11218
|
+
candidate = await request.json();
|
|
11219
|
+
} catch {
|
|
11220
|
+
return new Response(null, { status: 400 });
|
|
11221
|
+
}
|
|
11222
|
+
if (typeof candidate !== "string" || !candidate || candidate.length > 64000 || /[\x00-\x1f\x7f]/.test(candidate))
|
|
11223
|
+
return new Response(null, { status: 400 });
|
|
11224
|
+
value = candidate;
|
|
11225
|
+
return new Response(null, { status: 204 });
|
|
11226
|
+
} });
|
|
11227
|
+
try {
|
|
11228
|
+
await runVaultCommand(binding, ["exec", binding.source.key, "--as", DELIVERY_VALUE, "--", process.execPath, process.argv[1], "__credential-delivery"], env, {
|
|
11229
|
+
[DELIVERY_URL]: broker.url.origin + "/credential",
|
|
11230
|
+
[DELIVERY_NONCE]: nonce
|
|
11231
|
+
});
|
|
11232
|
+
if (!value)
|
|
11233
|
+
throw new Fault(422, "vault_delivery_failed", "The secrets CLI completed without a valid credential handoff.");
|
|
11234
|
+
return value;
|
|
11235
|
+
} finally {
|
|
11236
|
+
await broker.stop(true);
|
|
11237
|
+
}
|
|
11238
|
+
}
|
|
11239
|
+
var secretMetadataSchema = z7.object({
|
|
11240
|
+
key: vaultKey,
|
|
11241
|
+
type: z7.enum(["api_key", "password", "token", "credential", "other"]),
|
|
11242
|
+
label: z7.string().max(1000).nullable().optional(),
|
|
11243
|
+
expires_at: z7.string().max(200).nullable().optional(),
|
|
11244
|
+
created_at: z7.string().max(200),
|
|
11245
|
+
updated_at: z7.string().max(200)
|
|
11246
|
+
}).strict();
|
|
11247
|
+
var cleanDisplay = (value) => value.replace(/[\x00-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]/g, "").slice(0, 500);
|
|
11248
|
+
var credentialOrigins = (provider) => {
|
|
11249
|
+
const origins = new Set([new URL(provider.baseUrl).origin]);
|
|
11250
|
+
const catalogAuthStyle = provider.catalogAuthStyle ?? provider.authStyle ?? "bearer";
|
|
11251
|
+
const catalogCredentialEnv = provider.catalogCredentialEnv ?? provider.credentialEnv;
|
|
11252
|
+
if (catalogAuthStyle !== "none" && provider.catalogBaseUrl && catalogCredentialEnv === provider.credentialEnv)
|
|
11253
|
+
origins.add(new URL(provider.catalogBaseUrl).origin);
|
|
11254
|
+
return [...origins];
|
|
11255
|
+
};
|
|
11256
|
+
var providerCredentialSetupCommand = (provider) => {
|
|
11257
|
+
if (!provider.credentialEnv)
|
|
11258
|
+
return "";
|
|
11259
|
+
const origins = credentialOrigins(provider).map((value) => ` --origin ${value}`).join("");
|
|
11260
|
+
return `switcher credentials bind ${provider.credentialEnv}${origins} --vault-key <vault-key>`;
|
|
11261
|
+
};
|
|
11262
|
+
var searchTerms = (provider) => {
|
|
11263
|
+
const fromReference = provider.credentialEnv?.replace(/^SWITCHER_PROVIDER_/, "").replace(/_API_KEY$/, "").toLowerCase().replace(/_/g, "-");
|
|
11264
|
+
const raw = [fromReference, provider.name.toLowerCase().replace(/[^a-z0-9]+/g, "-"), provider.id.toLowerCase()];
|
|
11265
|
+
return [...new Set(raw.flatMap((value) => value ? [value, ...value.split("-")] : []).filter((value) => value.length >= 3 && !new Set(["api", "key", "provider", "responses", "response", "messages", "message", "chat", "custom"]).has(value)))].slice(0, 4);
|
|
11266
|
+
};
|
|
11267
|
+
async function discoverVaultReferences(provider, env = process.env, vaultExecutable = Bun.which("secrets") ?? "") {
|
|
11268
|
+
if (!provider.credentialEnv)
|
|
11269
|
+
return [];
|
|
11270
|
+
if (!vaultExecutable)
|
|
11271
|
+
throw new Fault(422, "vault_exec_unavailable", "Hasna Secrets is not installed in this launcher process. Install it or run the exact credentials bind command with --vault-cli /absolute/path.");
|
|
11272
|
+
await validateVaultExecutable(vaultExecutable);
|
|
11273
|
+
const source = { kind: "vault", key: "switcher/provider-credential-discovery", executable: vaultExecutable, operator: { kind: "contracts" } };
|
|
11274
|
+
const provisional = parse2(credentialBindingSchema, { schema: 1, credentialEnv: provider.credentialEnv, origins: credentialOrigins(provider), source });
|
|
11275
|
+
const operator2 = await resolveVaultOperatorEnvironment(provisional, env);
|
|
11276
|
+
const entries = new Map;
|
|
11277
|
+
for (const query of searchTerms(provider)) {
|
|
11278
|
+
const output = await runVaultCommand(provisional, ["search", query, "--json"], env, {}, {
|
|
11279
|
+
captureBytes: 256 * 1024,
|
|
11280
|
+
oversizeCode: "vault_metadata_oversized",
|
|
11281
|
+
oversizeMessage: "Secrets returned too much credential metadata; narrow the vault naming or bind an exact key explicitly.",
|
|
11282
|
+
lookupCode: "vault_search_failed",
|
|
11283
|
+
lookupMessage: "Hasna Secrets could not search credential metadata. Check the selected vault/Keychain source; no alternate account was selected.",
|
|
11284
|
+
operator: operator2
|
|
11285
|
+
});
|
|
11286
|
+
let parsed;
|
|
11287
|
+
try {
|
|
11288
|
+
parsed = JSON.parse(output);
|
|
11289
|
+
} catch {
|
|
11290
|
+
throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned invalid credential metadata JSON.");
|
|
11291
|
+
}
|
|
11292
|
+
const result = secretMetadataSchema.array().max(1000).safeParse(parsed);
|
|
11293
|
+
if (!result.success)
|
|
11294
|
+
throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned an unsupported credential metadata shape.");
|
|
11295
|
+
for (const entry of result.data)
|
|
11296
|
+
entries.set(entry.key, entry);
|
|
11297
|
+
if (entries.size > 256)
|
|
11298
|
+
throw new Fault(422, "credential_matches_too_many", "More than 256 credential references matched. Bind an exact vault key explicitly.");
|
|
11299
|
+
}
|
|
11300
|
+
return [...entries.values()].sort((a, b) => a.key.localeCompare(b.key)).map((entry) => ({ account: operator2.source, key: entry.key, url: operator2.url, executable: vaultExecutable, operator: { kind: "contracts", expectedSource: operator2.source, expectedTier: operator2.tier } }));
|
|
11301
|
+
}
|
|
11302
|
+
async function selectVaultReference({ provider, matches }) {
|
|
11303
|
+
if (!process.stdin.isTTY || !process.stderr.isTTY)
|
|
11304
|
+
return;
|
|
11305
|
+
console.error(`Secrets account/source: ${cleanDisplay(matches[0]?.account ?? "unknown")}`);
|
|
11306
|
+
console.error(`Credential references matching ${cleanDisplay(provider.name)}:`);
|
|
11307
|
+
matches.forEach((match, index) => console.error(` ${index + 1}. ${cleanDisplay(match.key)}${match.account === matches[0]?.account ? "" : ` (account/source: ${cleanDisplay(match.account)})`}`));
|
|
11308
|
+
const reader = createInterface({ input: process.stdin, output: process.stderr });
|
|
11309
|
+
const cancellation = new AbortController;
|
|
11310
|
+
const cancel = () => cancellation.abort(new CommandInterrupted(130, "Credential setup was cancelled; no binding was saved and no harness was started."));
|
|
11311
|
+
const terminate = () => cancellation.abort(new CommandInterrupted(143, "Credential setup was interrupted; no binding was saved and no harness was started."));
|
|
11312
|
+
reader.on("SIGINT", cancel);
|
|
11313
|
+
reader.on("close", cancel);
|
|
11314
|
+
process.on("SIGINT", cancel);
|
|
11315
|
+
process.on("SIGTERM", terminate);
|
|
11316
|
+
try {
|
|
11317
|
+
for (;; ) {
|
|
11318
|
+
const answer = (await reader.question("Credential number (Ctrl-C cancels): ", { signal: cancellation.signal }).catch((error) => {
|
|
11319
|
+
throw cancellation.signal.aborted ? cancellation.signal.reason : error;
|
|
11320
|
+
})).trim();
|
|
11321
|
+
if (!answer || /^(q|quit|cancel)$/i.test(answer))
|
|
11322
|
+
return;
|
|
11323
|
+
if (/^[1-9]\d*$/.test(answer) && matches[Number(answer) - 1])
|
|
11324
|
+
return matches[Number(answer) - 1];
|
|
11325
|
+
console.error(`Enter a number from 1 to ${matches.length}, or q to cancel.`);
|
|
11326
|
+
}
|
|
11327
|
+
} finally {
|
|
11328
|
+
reader.off("SIGINT", cancel);
|
|
11329
|
+
reader.off("close", cancel);
|
|
11330
|
+
process.off("SIGINT", cancel);
|
|
11331
|
+
process.off("SIGTERM", terminate);
|
|
11332
|
+
reader.close();
|
|
11333
|
+
}
|
|
11334
|
+
}
|
|
11335
|
+
function authenticationProbe(provider) {
|
|
11336
|
+
if (provider.credentialCheck) {
|
|
11337
|
+
const root = provider.baseUrl.endsWith("/") ? provider.baseUrl : `${provider.baseUrl}/`;
|
|
11338
|
+
const url = new URL(provider.credentialCheck.path, root);
|
|
11339
|
+
if (url.origin !== new URL(provider.baseUrl).origin || !url.href.startsWith(root))
|
|
11340
|
+
throw new Fault(422, "provider_auth_check_invalid", "Provider authentication check must remain below its inference endpoint.");
|
|
11341
|
+
return { url, method: provider.credentialCheck.method ?? "GET", authStyle: provider.authStyle ?? "bearer" };
|
|
11342
|
+
}
|
|
11343
|
+
const base = new URL(provider.baseUrl);
|
|
11344
|
+
if (provider.credentialEnv === "SWITCHER_PROVIDER_OPENROUTER" && base.origin === "https://openrouter.ai" && base.pathname.replace(/\/+$/, "") === "/api/v1")
|
|
11345
|
+
return { url: new URL("https://openrouter.ai/api/v1/key"), method: "GET", authStyle: provider.authStyle ?? "bearer" };
|
|
11346
|
+
return;
|
|
11347
|
+
}
|
|
11348
|
+
async function verifyProviderAuthentication({ provider, credential, fetch: fetchImpl = fetch }) {
|
|
11349
|
+
const probe = authenticationProbe(provider);
|
|
11350
|
+
if (!probe)
|
|
11351
|
+
return { authenticated: false, unsupported: true };
|
|
11352
|
+
const [header, value] = authHeader(probe.authStyle, credential);
|
|
11353
|
+
const headers = { accept: "application/json", "user-agent": "hasna-switcher/credential-check" };
|
|
11354
|
+
headers[provider.catalogFormat === "gemini" && header === "x-api-key" ? "x-goog-api-key" : header] = value;
|
|
11355
|
+
if (provider.protocol === "anthropic-messages" && probe.url.hostname !== "openrouter.ai")
|
|
11356
|
+
headers["anthropic-version"] = "2023-06-01";
|
|
11357
|
+
let response;
|
|
11358
|
+
try {
|
|
11359
|
+
response = await fetchImpl(probe.url, { method: probe.method, headers, redirect: "manual", signal: AbortSignal.timeout(1e4) });
|
|
11360
|
+
} catch {
|
|
11361
|
+
throw new Fault(502, "provider_auth_unavailable", "Provider authentication check could not reach the configured authority. Retry without changing accounts.");
|
|
11362
|
+
}
|
|
11363
|
+
const status = response.status;
|
|
11364
|
+
await response.body?.cancel().catch(() => {});
|
|
11365
|
+
if (status >= 200 && status < 300)
|
|
11366
|
+
return { authenticated: true, status };
|
|
11367
|
+
if (status === 401 || status === 403)
|
|
11368
|
+
return { authenticated: false, status };
|
|
11369
|
+
if (status >= 300 && status < 400)
|
|
11370
|
+
throw new Fault(502, "provider_auth_unavailable", "Provider authentication check returned a redirect; credentials were not forwarded.");
|
|
11371
|
+
throw new Fault(502, "provider_auth_unavailable", `Provider authentication check returned HTTP ${status}; the selected credential was not replaced.`);
|
|
11372
|
+
}
|
|
11373
|
+
function providerCredentialFingerprint(provider) {
|
|
11374
|
+
return createHash9("sha256").update(JSON.stringify({
|
|
11375
|
+
id: provider.id,
|
|
11376
|
+
baseUrl: provider.baseUrl,
|
|
11377
|
+
protocol: provider.protocol,
|
|
11378
|
+
authStyle: provider.authStyle ?? "bearer",
|
|
11379
|
+
credentialEnv: provider.credentialEnv ?? null,
|
|
11380
|
+
credentialCheck: provider.credentialCheck ?? null
|
|
11381
|
+
})).digest("hex");
|
|
11382
|
+
}
|
|
11383
|
+
function preparedProviderCredential(provider, credential, fields) {
|
|
11384
|
+
const providerFingerprint = providerCredentialFingerprint(provider);
|
|
11385
|
+
const prepared = { ...fields, providerFingerprint };
|
|
11386
|
+
Object.defineProperty(prepared, "resolveCredential", { enumerable: false, configurable: false, writable: false, value: async (candidate) => {
|
|
11387
|
+
if (providerCredentialFingerprint(candidate) !== providerFingerprint)
|
|
11388
|
+
throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
|
|
11389
|
+
return credential;
|
|
11390
|
+
} });
|
|
11391
|
+
return Object.freeze(prepared);
|
|
11392
|
+
}
|
|
11393
|
+
async function ensureProviderCredential(provider, options = {}) {
|
|
11394
|
+
if (!provider.credentialEnv)
|
|
11395
|
+
return preparedProviderCredential(provider, undefined, { source: "not-required", configured: false, verified: false });
|
|
11396
|
+
const resolver = options.resolver ?? new CredentialResolver(options.env ?? process.env);
|
|
11397
|
+
const existing = await resolver.bindings.get(provider.credentialEnv);
|
|
11398
|
+
let credential = await resolver.resolve(provider);
|
|
11399
|
+
if (existing && !credential)
|
|
11400
|
+
throw new Fault(422, "credential_binding_unavailable", "The selected credential binding did not provide a usable value; no alternate account was selected.");
|
|
11401
|
+
let configured = false;
|
|
11402
|
+
if (!credential) {
|
|
11403
|
+
if (!(options.interactive ?? (process.stdin.isTTY && process.stderr.isTTY)))
|
|
11404
|
+
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 discover2 = options.discoverVaultReferences ?? ((request) => discoverVaultReferences(request.provider, options.env ?? process.env, options.vaultExecutable));
|
|
11406
|
+
let matches;
|
|
11407
|
+
try {
|
|
11408
|
+
matches = await discover2({ provider, credentialEnv: provider.credentialEnv });
|
|
11409
|
+
} catch (error) {
|
|
11410
|
+
if (error instanceof Fault && error.code === "vault_exec_unavailable")
|
|
11411
|
+
throw new Fault(error.status, error.code, `${error.message} Run: ${providerCredentialSetupCommand(provider)} --vault-cli /absolute/path/to/secrets.`);
|
|
11412
|
+
throw error;
|
|
11413
|
+
}
|
|
11414
|
+
if (!matches.length)
|
|
11415
|
+
throw new Fault(404, "credential_match_missing", `No matching Hasna Secrets credential reference was found for ${provider.name}. Run: ${providerCredentialSetupCommand(provider)}.`);
|
|
11416
|
+
const select = options.selectVaultReference ?? selectVaultReference;
|
|
11417
|
+
const candidate = await select({ provider, matches });
|
|
11418
|
+
if (!candidate)
|
|
11419
|
+
throw new CommandInterrupted(130, "Credential setup was cancelled; no binding was saved and no harness was started.");
|
|
11420
|
+
const selected = matches.find((match) => match.account === candidate.account && match.key === candidate.key && match.executable === candidate.executable && JSON.stringify(match.operator) === JSON.stringify(candidate.operator));
|
|
11421
|
+
if (!selected)
|
|
11422
|
+
throw new Fault(400, "credential_selection_invalid", "Choose one of the displayed credential references.");
|
|
11423
|
+
const source = { kind: "vault", key: selected.key, ...selected.url ? { url: selected.url } : {}, executable: selected.executable, operator: selected.operator };
|
|
11424
|
+
await resolver.bindings.bind(parse2(credentialBindingSchema, { schema: 1, credentialEnv: provider.credentialEnv, origins: credentialOrigins(provider), requireProviderAuthentication: true, source }));
|
|
11425
|
+
configured = true;
|
|
11426
|
+
credential = await resolver.resolve(provider);
|
|
11427
|
+
if (!credential)
|
|
11428
|
+
throw new Fault(422, "vault_delivery_failed", "The selected credential reference did not provide a usable value; no alternate account was selected.");
|
|
11429
|
+
}
|
|
11430
|
+
const verify = options.verifyProviderAuthentication ?? ((request) => verifyProviderAuthentication(request));
|
|
11431
|
+
const result = await verify({ provider, credential });
|
|
11432
|
+
if (result.unsupported) {
|
|
11433
|
+
if (configured || existing?.requireProviderAuthentication)
|
|
11434
|
+
throw new Fault(422, "provider_auth_check_unsupported", `This provider has no configured non-inference authentication check.${configured ? " The selected binding was preserved." : ""} Configure credentialCheck before launch; no unverified credential was sent.`);
|
|
11435
|
+
return preparedProviderCredential(provider, credential, { source: existing ? "binding" : "environment", configured, verified: false });
|
|
11436
|
+
}
|
|
11437
|
+
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}.` : ""}`);
|
|
11439
|
+
return preparedProviderCredential(provider, credential, { source: existing || configured ? "binding" : "environment", configured, verified: true });
|
|
11440
|
+
}
|
|
11441
|
+
async function deliverVaultCredential() {
|
|
11442
|
+
const address = process.env[DELIVERY_URL];
|
|
11443
|
+
const nonce = process.env[DELIVERY_NONCE];
|
|
11444
|
+
const value = process.env[DELIVERY_VALUE];
|
|
11445
|
+
if (!address || !nonce || !value)
|
|
11446
|
+
throw new Fault(400, "credential_delivery_invalid", "Credential delivery requires an owned vault lookup.");
|
|
11447
|
+
let url;
|
|
11448
|
+
try {
|
|
11449
|
+
url = new URL(address);
|
|
11450
|
+
} catch {
|
|
11451
|
+
throw new Fault(400, "credential_delivery_invalid", "Invalid credential delivery address.");
|
|
11452
|
+
}
|
|
11453
|
+
if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || url.pathname !== "/credential" || url.username || url.password || url.search || url.hash)
|
|
11454
|
+
throw new Fault(400, "credential_delivery_invalid", "Credential delivery is restricted to the owned loopback receiver.");
|
|
11455
|
+
try {
|
|
11456
|
+
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) });
|
|
11457
|
+
if (response.status !== 204)
|
|
11458
|
+
throw new Error;
|
|
11459
|
+
} catch {
|
|
11460
|
+
throw new Fault(422, "credential_delivery_failed", "The owned credential receiver was unavailable.");
|
|
11461
|
+
}
|
|
11462
|
+
}
|
|
11463
|
+
|
|
11464
|
+
// src/harness-process.ts
|
|
11465
|
+
import { spawn as spawn2, spawnSync } from "child_process";
|
|
11466
|
+
import { EventEmitter } from "events";
|
|
11467
|
+
import { existsSync, openSync, closeSync, writeSync, readSync, constants as constants6 } from "fs";
|
|
11468
|
+
|
|
11469
|
+
// src/terminal-descriptors.ts
|
|
11470
|
+
async function terminalDescriptorDuplicator() {
|
|
11471
|
+
const { dlopen } = await import("bun:ffi");
|
|
11472
|
+
const candidates = process.platform === "darwin" ? ["/usr/lib/libSystem.B.dylib"] : ["libc.so.6", `/lib/libc.musl-${process.arch === "arm64" ? "aarch64" : "x86_64"}.so.1`];
|
|
11473
|
+
for (const library of candidates) {
|
|
11474
|
+
try {
|
|
11475
|
+
const handle = dlopen(library, { dup: { args: ["int"], returns: "int" } });
|
|
11476
|
+
return { duplicate(fd) {
|
|
11477
|
+
const copy = handle.symbols.dup(fd);
|
|
11478
|
+
if (copy < 3)
|
|
11479
|
+
throw new Error("A redirected terminal descriptor could not be duplicated.");
|
|
11480
|
+
return copy;
|
|
11481
|
+
}, close: () => handle.close() };
|
|
11482
|
+
} catch {}
|
|
11483
|
+
}
|
|
11484
|
+
throw new Error("Mixed terminal redirection requires the system C library's dup function on this platform.");
|
|
11485
|
+
}
|
|
11486
|
+
|
|
11487
|
+
// src/harness-process.ts
|
|
11488
|
+
async function runHarnessProcess(options) {
|
|
11489
|
+
const tty = [Boolean(process.stdin.isTTY), Boolean(process.stdout.isTTY), Boolean(process.stderr.isTTY)];
|
|
11490
|
+
const grouped = process.platform !== "win32", interactive = !options.silent && grouped && tty.some(Boolean);
|
|
11491
|
+
const redirects = interactive ? tty.flatMap((value, index) => value ? [] : [index]) : [];
|
|
11492
|
+
const duplicator = redirects.length ? await terminalDescriptorDuplicator() : undefined;
|
|
11493
|
+
return new Promise((resolveResult, reject2) => {
|
|
11494
|
+
const wasRaw = process.stdin.isRaw, wasFlowing = process.stdin.readableFlowing;
|
|
11495
|
+
let controllingInput;
|
|
11496
|
+
let inputTimer;
|
|
11497
|
+
let terminalFailure;
|
|
11498
|
+
let terminal;
|
|
11499
|
+
let terminalMode;
|
|
11500
|
+
let controllingOutput;
|
|
11501
|
+
const output = tty[1] ? process.stdout : tty[2] ? process.stderr : undefined;
|
|
11502
|
+
const stty = (args) => {
|
|
11503
|
+
const descriptor = openSync("/dev/tty", "r+");
|
|
11504
|
+
try {
|
|
11505
|
+
const result = spawnSync(existsSync("/bin/stty") ? "/bin/stty" : "/usr/bin/stty", args, { stdio: [descriptor, "pipe", "pipe"], env: { PATH: "/usr/bin:/bin", LANG: "C" }, encoding: "utf8", timeout: 1000, maxBuffer: 4096 });
|
|
11506
|
+
if (result.status !== 0)
|
|
11507
|
+
throw new Error("Terminal mode could not be configured.");
|
|
11508
|
+
return result.stdout.trim();
|
|
11509
|
+
} finally {
|
|
11510
|
+
closeSync(descriptor);
|
|
11511
|
+
}
|
|
11512
|
+
};
|
|
11513
|
+
let relay;
|
|
11514
|
+
let resize;
|
|
11515
|
+
const child = (() => {
|
|
11516
|
+
if (!interactive)
|
|
11517
|
+
return spawn2(options.executable, options.args, { cwd: options.cwd, env: options.env, stdio: options.silent ? "ignore" : "inherit", shell: false, detached: grouped });
|
|
11518
|
+
const duplicates = [];
|
|
11519
|
+
let native;
|
|
11520
|
+
try {
|
|
11521
|
+
if (!output)
|
|
11522
|
+
controllingOutput = openSync("/dev/tty", "w");
|
|
11523
|
+
const [rows, cols] = stty(["size"]).split(/\s+/).map(Number);
|
|
11524
|
+
for (const fd of redirects)
|
|
11525
|
+
duplicates.push(duplicator.duplicate(fd));
|
|
11526
|
+
const script = redirects.map((fd, index) => `exec ${fd}${fd === 0 ? "<&" : ">&"}${index + 3};`).join(" ") + " " + redirects.map((_, index) => `exec ${index + 3}<&-;`).join(" ") + ' exec "$@"';
|
|
11527
|
+
const command = redirects.length ? ["/bin/sh", "-c", script, "switcher-native", options.executable, ...options.args] : [options.executable, ...options.args];
|
|
10201
11528
|
native = Bun.spawn(command, {
|
|
10202
11529
|
cwd: options.cwd,
|
|
10203
11530
|
env: options.env,
|
|
@@ -10393,7 +11720,7 @@ async function runHarnessProcess(options) {
|
|
|
10393
11720
|
process.stdin.on("data", relay);
|
|
10394
11721
|
process.stdin.resume();
|
|
10395
11722
|
} else {
|
|
10396
|
-
controllingInput = openSync("/dev/tty",
|
|
11723
|
+
controllingInput = openSync("/dev/tty", constants6.O_RDONLY | constants6.O_NONBLOCK);
|
|
10397
11724
|
stty(["raw", "-echo"]);
|
|
10398
11725
|
const buffer = Buffer.alloc(4096);
|
|
10399
11726
|
inputTimer = setInterval(() => {
|
|
@@ -10424,9 +11751,9 @@ async function runHarnessProcess(options) {
|
|
|
10424
11751
|
}
|
|
10425
11752
|
|
|
10426
11753
|
// src/ori-backend.ts
|
|
10427
|
-
import { execFile as
|
|
10428
|
-
import { promisify as
|
|
10429
|
-
var exec =
|
|
11754
|
+
import { execFile as execFile4 } from "child_process";
|
|
11755
|
+
import { promisify as promisify4 } from "util";
|
|
11756
|
+
var exec = promisify4(execFile4);
|
|
10430
11757
|
var oriProviderCatalog = Object.freeze([{
|
|
10431
11758
|
id: "openrouter",
|
|
10432
11759
|
displayName: "OpenRouter",
|
|
@@ -10514,14 +11841,14 @@ function parseHarnesses(stdout) {
|
|
|
10514
11841
|
return rows.flatMap((row) => {
|
|
10515
11842
|
if (!row || typeof row !== "object")
|
|
10516
11843
|
return [];
|
|
10517
|
-
const
|
|
10518
|
-
if (typeof
|
|
11844
|
+
const item2 = row;
|
|
11845
|
+
if (typeof item2.kind !== "string" || typeof item2.installed !== "boolean")
|
|
10519
11846
|
return [];
|
|
10520
11847
|
return [{
|
|
10521
|
-
kind:
|
|
10522
|
-
displayName: typeof
|
|
10523
|
-
installed:
|
|
10524
|
-
path: typeof
|
|
11848
|
+
kind: item2.kind,
|
|
11849
|
+
displayName: typeof item2.displayName === "string" ? item2.displayName : undefined,
|
|
11850
|
+
installed: item2.installed,
|
|
11851
|
+
path: typeof item2.path === "string" ? item2.path : undefined
|
|
10525
11852
|
}];
|
|
10526
11853
|
});
|
|
10527
11854
|
}
|
|
@@ -10659,16 +11986,16 @@ function oriLaunchWarnings(target) {
|
|
|
10659
11986
|
}
|
|
10660
11987
|
|
|
10661
11988
|
// src/chatgpt-launch.ts
|
|
10662
|
-
import { createHash as
|
|
11989
|
+
import { createHash as createHash10 } from "crypto";
|
|
10663
11990
|
import { writeFile as writeFile12, rm as rm4 } from "fs/promises";
|
|
10664
|
-
import { join as
|
|
11991
|
+
import { join as join14 } from "path";
|
|
10665
11992
|
|
|
10666
11993
|
// src/desktop-state.ts
|
|
10667
11994
|
import { Database as Database3 } from "bun:sqlite";
|
|
10668
|
-
import { readFile as readFile5, writeFile as writeFile11, rm as rm3, lstat as
|
|
11995
|
+
import { readFile as readFile5, writeFile as writeFile11, rm as rm3, lstat as lstat5, rename as rename3, chmod as chmod2 } from "fs/promises";
|
|
10669
11996
|
async function safeDesktopRead(path) {
|
|
10670
11997
|
try {
|
|
10671
|
-
const info = await
|
|
11998
|
+
const info = await lstat5(path);
|
|
10672
11999
|
if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
|
|
10673
12000
|
throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user.");
|
|
10674
12001
|
return await readFile5(path, "utf8");
|
|
@@ -10682,14 +12009,14 @@ async function writeDesktopPrivate(path, text) {
|
|
|
10682
12009
|
const temporary = path + "." + crypto.randomUUID() + ".tmp";
|
|
10683
12010
|
try {
|
|
10684
12011
|
await writeFile11(temporary, text, { mode: 384, flag: "wx" });
|
|
10685
|
-
await
|
|
12012
|
+
await rename3(temporary, path);
|
|
10686
12013
|
} finally {
|
|
10687
12014
|
await rm3(temporary, { force: true });
|
|
10688
12015
|
}
|
|
10689
12016
|
}
|
|
10690
12017
|
async function desktopLease(path) {
|
|
10691
12018
|
try {
|
|
10692
|
-
const info = await
|
|
12019
|
+
const info = await lstat5(path);
|
|
10693
12020
|
if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
|
|
10694
12021
|
throw new Fault(422, "desktop_state_permissions", "Desktop lease must be a regular file owned by this user.");
|
|
10695
12022
|
} catch (error) {
|
|
@@ -10721,16 +12048,16 @@ function merge2(base, overlay) {
|
|
|
10721
12048
|
result[key] = object5(value) && object5(result[key]) ? merge2(result[key], value) : value;
|
|
10722
12049
|
return result;
|
|
10723
12050
|
}
|
|
10724
|
-
var digest = (value) =>
|
|
12051
|
+
var digest = (value) => createHash10("sha256").update(value).digest("hex");
|
|
10725
12052
|
var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
10726
12053
|
async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
10727
12054
|
await privateDirectory(sessionDir);
|
|
10728
|
-
const home =
|
|
12055
|
+
const home = join14(sessionDir, "codex"), userData = join14(sessionDir, "electron");
|
|
10729
12056
|
await privateDirectory(home);
|
|
10730
12057
|
await privateDirectory(userData);
|
|
10731
|
-
const release = await desktopLease(
|
|
12058
|
+
const release = await desktopLease(join14(sessionDir, "launch.sqlite"));
|
|
10732
12059
|
let released = false, authText;
|
|
10733
|
-
const authPath =
|
|
12060
|
+
const authPath = join14(home, "auth.json"), receiptPath = join14(home, ".switcher-auth.sha256");
|
|
10734
12061
|
const cleanup = async () => {
|
|
10735
12062
|
if (released)
|
|
10736
12063
|
return;
|
|
@@ -10756,7 +12083,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
|
10756
12083
|
settings2.push('approval_policy="on-request"');
|
|
10757
12084
|
if (!settings2.some((setting) => setting.startsWith("sandbox_mode=")))
|
|
10758
12085
|
settings2.push('sandbox_mode="workspace-write"');
|
|
10759
|
-
const configPath =
|
|
12086
|
+
const configPath = join14(home, "config.toml");
|
|
10760
12087
|
const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
|
|
10761
12088
|
if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
|
|
10762
12089
|
throw new Fault(409, "desktop_auth_changed", "This isolated desktop profile contains authentication that Switcher did not create. Sign out of that provider profile before launching it again; Switcher will not overwrite it.");
|
|
@@ -10777,7 +12104,7 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
|
10777
12104
|
`;
|
|
10778
12105
|
await writeDesktopPrivate(receiptPath, digest(authText));
|
|
10779
12106
|
await writeDesktopPrivate(authPath, authText);
|
|
10780
|
-
const wrapper =
|
|
12107
|
+
const wrapper = join14(stateDir, "chatgpt-codex");
|
|
10781
12108
|
const overrides = settings2.flatMap((setting) => ["-c", setting]);
|
|
10782
12109
|
await writeFile12(wrapper, `#!/bin/sh
|
|
10783
12110
|
set -eu
|
|
@@ -10790,1126 +12117,639 @@ exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
|
|
|
10790
12117
|
`, { mode: 448, flag: "wx" });
|
|
10791
12118
|
return {
|
|
10792
12119
|
...native,
|
|
10793
|
-
executable: app.executable,
|
|
10794
|
-
args: [`--user-data-dir=${userData}`],
|
|
10795
|
-
env: { ...native.env, CODEX_HOME: home, CODEX_ELECTRON_USER_DATA_PATH: userData, CODEX_CLI_PATH: wrapper, CODEX_APP_SERVER_FORCE_CLI: "1", CODEX_APP_SERVER_USE_LOCAL_DAEMON: "0" },
|
|
10796
|
-
configPaths: [...native.configPaths, configPath, wrapper],
|
|
10797
|
-
warnings: [...native.warnings, `ChatGPT provider profile: ${sessionDir}. Local Codex conversations use this provider; ChatGPT cloud Chat/Work and account-only features are not redirected. Keep Switcher running until you quit this app instance.`],
|
|
10798
|
-
cleanup: async () => {
|
|
10799
|
-
try {
|
|
10800
|
-
await native.cleanup?.();
|
|
10801
|
-
} finally {
|
|
10802
|
-
await cleanup();
|
|
10803
|
-
}
|
|
10804
|
-
}
|
|
10805
|
-
};
|
|
10806
|
-
} catch (error) {
|
|
10807
|
-
await cleanup();
|
|
10808
|
-
throw error;
|
|
10809
|
-
}
|
|
10810
|
-
}
|
|
10811
|
-
|
|
10812
|
-
// src/claude-desktop-launch.ts
|
|
10813
|
-
import { createHash as createHash10 } from "crypto";
|
|
10814
|
-
import { execFile as execFile4 } from "child_process";
|
|
10815
|
-
import { access as access4, rm as rm5, writeFile as writeFile13 } from "fs/promises";
|
|
10816
|
-
import { homedir as homedir8, userInfo as userInfo2 } from "os";
|
|
10817
|
-
import { join as join14 } from "path";
|
|
10818
|
-
import { promisify as promisify4 } from "util";
|
|
10819
|
-
var execute3 = promisify4(execFile4);
|
|
10820
|
-
var hash2 = (text) => createHash10("sha256").update(text).digest("hex");
|
|
10821
|
-
var claudeDesktopDataDirectory = () => join14(homedir8(), "Library/Application Support/Claude-3p");
|
|
10822
|
-
async function assertAvailable(userData) {
|
|
10823
|
-
for (const path of [join14("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
|
|
10824
|
-
if (await access4(path).then(() => true, () => false))
|
|
10825
|
-
throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
|
|
10826
|
-
let openFiles;
|
|
10827
|
-
try {
|
|
10828
|
-
openFiles = (await execute3("/usr/sbin/lsof", ["-n", "-P", "-Fpn", "-a", "-u", String(process.getuid?.()), "-c", "Claude"], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, timeout: 8000 })).stdout;
|
|
10829
|
-
} catch (error) {
|
|
10830
|
-
if (error.code === 1)
|
|
10831
|
-
return;
|
|
10832
|
-
throw new Fault(409, "desktop_process_check", "Could not check whether Claude's third-party profile is already running.");
|
|
10833
|
-
}
|
|
10834
|
-
if (openFiles.split(`
|
|
10835
|
-
`).some((line) => line.startsWith("n" + userData + "/")))
|
|
10836
|
-
throw new Fault(409, "desktop_busy", "Claude's third-party instance is already running. Quit that instance before changing its provider; the normal Claude instance can stay open.");
|
|
10837
|
-
}
|
|
10838
|
-
function metadata(text) {
|
|
10839
|
-
const value = text === undefined ? { entries: [] } : JSON.parse(text);
|
|
10840
|
-
if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((item) => !item || typeof item !== "object" || Array.isArray(item)))
|
|
10841
|
-
throw new Fault(422, "desktop_config_invalid", "Claude's configuration library metadata is invalid.");
|
|
10842
|
-
return value;
|
|
10843
|
-
}
|
|
10844
|
-
async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
10845
|
-
if (input.harness !== "claude")
|
|
10846
|
-
throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
|
|
10847
|
-
validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
|
|
10848
|
-
if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
|
|
10849
|
-
throw new Fault(400, "desktop_arguments", "Claude desktop uses its own effort and permission controls; native CLI arguments and Codex-only launch controls are not accepted.");
|
|
10850
|
-
const version = app.version.split(".").map(Number);
|
|
10851
|
-
if (version.length < 3 || version.some((n) => !Number.isSafeInteger(n)) || version[0] < 1 || version[0] === 1 && version[1] < 52386)
|
|
10852
|
-
throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
|
|
10853
|
-
const userData = system?.userData ?? claudeDesktopDataDirectory();
|
|
10854
|
-
const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
|
|
10855
|
-
await check2();
|
|
10856
|
-
await privateDirectory(userData);
|
|
10857
|
-
const library = join14(userData, "configLibrary");
|
|
10858
|
-
await privateDirectory(library);
|
|
10859
|
-
const release = await desktopLease(join14(library, ".switcher-lease.sqlite"));
|
|
10860
|
-
const metaPath = join14(library, "_meta.json"), receiptPath = join14(library, ".switcher-selection.json");
|
|
10861
|
-
let receipt, gateway, closed = false;
|
|
10862
|
-
const restore = async (record3) => {
|
|
10863
|
-
if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
|
|
10864
|
-
throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
|
|
10865
|
-
const configPath = join14(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
|
|
10866
|
-
if (current !== undefined && hash2(current) !== record3.configHash)
|
|
10867
|
-
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.");
|
|
10868
|
-
const currentMeta = await safeDesktopRead(metaPath);
|
|
10869
|
-
if (currentMeta !== record3.appliedMeta && currentMeta !== (record3.previousMeta ?? undefined))
|
|
10870
|
-
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.");
|
|
10871
|
-
if (record3.previousMeta === null)
|
|
10872
|
-
await rm5(metaPath, { force: true });
|
|
10873
|
-
else
|
|
10874
|
-
await writeDesktopPrivate(metaPath, record3.previousMeta);
|
|
10875
|
-
await rm5(configPath, { force: true });
|
|
10876
|
-
await rm5(receiptPath, { force: true });
|
|
10877
|
-
};
|
|
10878
|
-
const cleanup = async () => {
|
|
10879
|
-
if (closed)
|
|
10880
|
-
return;
|
|
10881
|
-
closed = true;
|
|
10882
|
-
try {
|
|
10883
|
-
await gateway?.cleanup();
|
|
10884
|
-
if (receipt)
|
|
10885
|
-
await restore(receipt);
|
|
10886
|
-
} finally {
|
|
10887
|
-
release();
|
|
10888
|
-
}
|
|
10889
|
-
};
|
|
10890
|
-
try {
|
|
10891
|
-
const recovery = await safeDesktopRead(receiptPath);
|
|
10892
|
-
if (recovery)
|
|
10893
|
-
await restore(JSON.parse(recovery));
|
|
10894
|
-
const localConfig = await safeDesktopRead(join14(userData, "claude_desktop_config.json"));
|
|
10895
|
-
if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
|
|
10896
|
-
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.");
|
|
10897
|
-
await privateDirectory(sessionDir);
|
|
10898
|
-
const roles2 = input.modelPolicy?.roles;
|
|
10899
|
-
const targets = { sonnet: input.model, opus: roles2?.planning ?? input.model, haiku: roles2?.fast ?? input.model };
|
|
10900
|
-
const aliases = Object.fromEntries(Object.entries(targets).map(([tier, model3]) => ["switcher/" + tier, model3]));
|
|
10901
|
-
for (const [alias, target] of Object.entries(aliases))
|
|
10902
|
-
if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
|
|
10903
|
-
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.");
|
|
10904
|
-
const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
|
|
10905
|
-
const catalogPath = join14(input.stateDir, "claude-desktop-policy.json");
|
|
10906
|
-
await writeFile13(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
|
|
10907
|
-
gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
10908
|
-
const id2 = crypto.randomUUID(), configPath = join14(library, id2 + ".json");
|
|
10909
|
-
const config = JSON.stringify({
|
|
10910
|
-
inferenceProvider: "gateway",
|
|
10911
|
-
inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
|
|
10912
|
-
inferenceGatewayApiKey: gateway.token,
|
|
10913
|
-
inferenceGatewayAuthScheme: "bearer",
|
|
10914
|
-
modelDiscoveryEnabled: false,
|
|
10915
|
-
inferenceModels: Object.entries(targets).map(([tier, model3]) => ({ name: "switcher/" + tier, labelOverride: model3, anthropicFamilyTier: tier, isFamilyDefault: true }))
|
|
10916
|
-
});
|
|
10917
|
-
const previousMeta = await safeDesktopRead(metaPath);
|
|
10918
|
-
const meta = metadata(previousMeta);
|
|
10919
|
-
const appliedMeta = JSON.stringify({ ...meta, appliedId: id2, entries: [...meta.entries, { id: id2, name: `Switcher: ${input.providerId ?? "provider"} / ${input.model}` }] });
|
|
10920
|
-
receipt = { id: id2, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
|
|
10921
|
-
await writeDesktopPrivate(configPath, config);
|
|
10922
|
-
await writeDesktopPrivate(receiptPath, JSON.stringify(receipt));
|
|
10923
|
-
await writeDesktopPrivate(metaPath, appliedMeta);
|
|
10924
|
-
return {
|
|
10925
|
-
executable: app.executable,
|
|
10926
|
-
args: [],
|
|
10927
|
-
env: { CLAUDE_CONFIG_DIR: sessionDir },
|
|
10928
|
-
configPaths: [catalogPath, configPath],
|
|
10929
|
-
beforeLaunch: check2,
|
|
10930
|
-
cleanup,
|
|
10931
|
-
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.`]
|
|
10932
|
-
};
|
|
10933
|
-
} catch (error) {
|
|
10934
|
-
try {
|
|
10935
|
-
await cleanup();
|
|
10936
|
-
} catch {}
|
|
10937
|
-
throw error;
|
|
10938
|
-
}
|
|
10939
|
-
}
|
|
10940
|
-
|
|
10941
|
-
// src/launcher.ts
|
|
10942
|
-
var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
|
|
10943
|
-
async function writeOriCodexCatalog(stateDir, models) {
|
|
10944
|
-
const path = join15(stateDir, "ori-codex-models.json");
|
|
10945
|
-
const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
|
|
10946
|
-
await writeFile14(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
|
|
10947
|
-
`, { mode: 384, flag: "wx" });
|
|
10948
|
-
return path;
|
|
10949
|
-
}
|
|
10950
|
-
function oriTarget(harness) {
|
|
10951
|
-
if (harness === "kilo")
|
|
10952
|
-
throw new Error("Ori does not launch Kilo; use the direct backend.");
|
|
10953
|
-
if (harness === "opencode")
|
|
10954
|
-
throw new Error("Ori does not launch legacy OpenCode; use the direct backend.");
|
|
10955
|
-
if (harness === "aider")
|
|
10956
|
-
throw new Error("Ori does not launch Aider; use the direct backend.");
|
|
10957
|
-
if (harness === "gemini")
|
|
10958
|
-
throw new Error("Ori does not launch Gemini CLI; use the direct backend.");
|
|
10959
|
-
if (harness === "prime-agent")
|
|
10960
|
-
throw new Error("Ori does not launch Prime Agent; use the direct backend.");
|
|
10961
|
-
if (harness === "omp")
|
|
10962
|
-
throw new Error("Ori does not support OMP; use the direct OMP adapter.");
|
|
10963
|
-
if (harness === "cline")
|
|
10964
|
-
throw new Error("Ori does not support Cline; use the direct Cline adapter.");
|
|
10965
|
-
if (harness === "hermes")
|
|
10966
|
-
throw new Error("Ori does not provide a Hermes adapter; use the direct Hermes backend.");
|
|
10967
|
-
return harness;
|
|
10968
|
-
}
|
|
10969
|
-
async function oriRequestForPlan(plan, options = {}) {
|
|
10970
|
-
validateHarnessProvider(plan.profile.harness, plan.provider);
|
|
10971
|
-
if (options.oriExecutable === "")
|
|
10972
|
-
throw new Error("--ori-executable requires a non-empty executable path.");
|
|
10973
|
-
const target = oriTarget(plan.profile.harness);
|
|
10974
|
-
if (plan.provider.authStyle !== "bearer")
|
|
10975
|
-
throw new Error("Ori requires the OpenRouter Bearer authentication contract; use the direct adapter for other auth styles.");
|
|
10976
|
-
assertOriLoginAllowed({ ...process.env, ...options.credentialEnv });
|
|
10977
|
-
const policyEnvironment = { ...process.env, ...options.credentialEnv };
|
|
10978
|
-
if (plan.profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((policyEnvironment.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
|
|
10979
|
-
throw new Error("Grok API-key authentication is disabled by GROK_DISABLE_API_KEY_AUTH. This provider launch cannot proceed under that native authentication policy.");
|
|
10980
|
-
if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
|
|
10981
|
-
throw new Error("Grok requires a native team login through GROK_FORCE_LOGIN_TEAM_ID. This provider launch cannot proceed under that native authentication policy.");
|
|
10982
|
-
const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve9(options.cwd) : undefined });
|
|
10983
|
-
const native = requireOriHarness(contract, target);
|
|
10984
|
-
if (!native.path)
|
|
10985
|
-
throw new Error("Ori did not report the native harness executable path.");
|
|
10986
|
-
const detection = await detectHarness(target, native.path);
|
|
10987
|
-
if (!detection.available)
|
|
10988
|
-
throw new Error("The native harness reported by Ori could not report its version.");
|
|
10989
|
-
validateHarnessVersion(target, detection.version);
|
|
10990
|
-
const catalogPath = target === "codex" && options.stateDir ? await writeOriCodexCatalog(options.stateDir, plan.catalog.models) : undefined;
|
|
10991
|
-
const request = buildOriRequest(plan, target, catalogPath, options.args ?? []);
|
|
10992
|
-
validateOriLaunchRequest(request);
|
|
10993
|
-
return { contract, request, detection };
|
|
10994
|
-
}
|
|
10995
|
-
async function validateOriForPlan(plan, options = {}) {
|
|
10996
|
-
const result = await oriRequestForPlan(plan, options);
|
|
10997
|
-
return { ...result, warnings: oriLaunchWarnings(result.request.target) };
|
|
10998
|
-
}
|
|
10999
|
-
function buildOriRequest(plan, target, catalogPath, args) {
|
|
11000
|
-
return {
|
|
11001
|
-
target,
|
|
11002
|
-
provider: plan.provider.id,
|
|
11003
|
-
providerBaseUrl: plan.provider.baseUrl,
|
|
11004
|
-
protocol: plan.provider.protocol,
|
|
11005
|
-
model: plan.profile.model,
|
|
11006
|
-
catalog: { source: "switcher-openrouter", modelIds: plan.catalog.models.filter(codingEligible).map((model3) => model3.id), ...catalogPath ? { codexModelCatalogPath: catalogPath } : {} },
|
|
11007
|
-
args
|
|
11008
|
-
};
|
|
11009
|
-
}
|
|
11010
|
-
async function prepareOriForPlan(plan, options) {
|
|
11011
|
-
const { contract, request, detection } = await oriRequestForPlan(plan, options);
|
|
11012
|
-
const credential = options.resolveCredential ? await options.resolveCredential(plan.provider) : providerCredential(plan.provider, options.credentialEnv);
|
|
11013
|
-
if (!credential)
|
|
11014
|
-
throw new Error("OpenRouter credential is required for an Ori launch; configure a Switcher credential binding.");
|
|
11015
|
-
const ori = prepareOriLaunch({ ...request, executable: contract.executable, environment: { ...process.env, ...options.credentialEnv, OPENROUTER_API_KEY: credential } });
|
|
11016
|
-
const native = await prepareHarnessLaunch({
|
|
11017
|
-
harness: plan.profile.harness,
|
|
11018
|
-
baseUrl: plan.provider.baseUrl,
|
|
11019
|
-
protocol: plan.provider.protocol,
|
|
11020
|
-
authStyle: plan.provider.authStyle,
|
|
11021
|
-
model: plan.profile.model,
|
|
11022
|
-
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
11023
|
-
modelPolicy: plan.profile.modelPolicy,
|
|
11024
|
-
providerId: plan.provider.id,
|
|
11025
|
-
onRoutingEvent: options.onRoutingEvent,
|
|
11026
|
-
credential,
|
|
11027
|
-
executable: detection.executable,
|
|
11028
|
-
version: detection.version,
|
|
11029
|
-
stateDir: options.stateDir,
|
|
11030
|
-
cwd: resolve9(options.cwd ?? process.cwd()),
|
|
11031
|
-
args: options.args ?? []
|
|
11032
|
-
});
|
|
11033
|
-
try {
|
|
11034
|
-
const shim = prepareOriModelPolicy(request.target, native);
|
|
11035
|
-
const dir = join15(options.stateDir, "ori-bin"), path = join15(dir, shim.name);
|
|
11036
|
-
await mkdir11(dir, { mode: 448 });
|
|
11037
|
-
await writeFile14(path, shim.script, { mode: 448, flag: "wx" });
|
|
11038
|
-
return { contract, prepared: {
|
|
11039
|
-
...ori,
|
|
11040
|
-
env: { ...ori.env, ...shim.env, PATH: `${dir}:${ori.env.PATH ?? process.env.PATH ?? ""}` },
|
|
11041
|
-
configPaths: [...native.configPaths, path],
|
|
11042
|
-
beforeLaunch: native.beforeLaunch,
|
|
11043
|
-
cleanup: native.cleanup,
|
|
11044
|
-
warnings: [...native.warnings, "Ori performs its own OpenRouter catalog/auth checks; its native child uses Switcher's prepared model policy and gateway."]
|
|
11045
|
-
} };
|
|
12120
|
+
executable: app.executable,
|
|
12121
|
+
args: [`--user-data-dir=${userData}`],
|
|
12122
|
+
env: { ...native.env, CODEX_HOME: home, CODEX_ELECTRON_USER_DATA_PATH: userData, CODEX_CLI_PATH: wrapper, CODEX_APP_SERVER_FORCE_CLI: "1", CODEX_APP_SERVER_USE_LOCAL_DAEMON: "0" },
|
|
12123
|
+
configPaths: [...native.configPaths, configPath, wrapper],
|
|
12124
|
+
warnings: [...native.warnings, `ChatGPT provider profile: ${sessionDir}. Local Codex conversations use this provider; ChatGPT cloud Chat/Work and account-only features are not redirected. Keep Switcher running until you quit this app instance.`],
|
|
12125
|
+
cleanup: async () => {
|
|
12126
|
+
try {
|
|
12127
|
+
await native.cleanup?.();
|
|
12128
|
+
} finally {
|
|
12129
|
+
await cleanup();
|
|
12130
|
+
}
|
|
12131
|
+
}
|
|
12132
|
+
};
|
|
11046
12133
|
} catch (error) {
|
|
11047
|
-
await
|
|
12134
|
+
await cleanup();
|
|
11048
12135
|
throw error;
|
|
11049
12136
|
}
|
|
11050
12137
|
}
|
|
11051
|
-
|
|
11052
|
-
|
|
11053
|
-
|
|
11054
|
-
|
|
11055
|
-
|
|
11056
|
-
|
|
11057
|
-
|
|
11058
|
-
|
|
11059
|
-
|
|
11060
|
-
|
|
11061
|
-
|
|
11062
|
-
|
|
11063
|
-
|
|
11064
|
-
|
|
11065
|
-
|
|
11066
|
-
|
|
11067
|
-
|
|
11068
|
-
|
|
11069
|
-
|
|
11070
|
-
|
|
11071
|
-
|
|
11072
|
-
|
|
11073
|
-
throw new Error("--executable is ambiguous with --backend ori; use --ori-executable PATH.");
|
|
11074
|
-
if (backend === "direct" && options.oriExecutable)
|
|
11075
|
-
throw new Error("--ori-executable requires --backend ori.");
|
|
11076
|
-
if (options.desktop && (plan.profile.harness !== "codex" || backend !== "direct"))
|
|
11077
|
-
throw new Error("ChatGPT requires the direct Codex provider adapter.");
|
|
11078
|
-
if (options.claudeDesktop && (options.desktop || plan.profile.harness !== "claude" || backend !== "direct" || options.executable || options.args?.length))
|
|
11079
|
-
throw new Error("Claude desktop requires its direct Messages gateway adapter without native CLI overrides.");
|
|
11080
|
-
const nativeExecutable = options.desktop?.codexExecutable ?? options.executable;
|
|
11081
|
-
const detection = backend === "direct" && !options.claudeDesktop ? await detectHarness(plan.profile.harness, nativeExecutable) : undefined;
|
|
11082
|
-
if (backend === "direct" && !options.claudeDesktop && !detection?.available)
|
|
11083
|
-
throw new Error(harnessInstallationMessage(plan.profile.harness, detection?.executable ?? plan.profile.harness, Boolean(options.executable)));
|
|
11084
|
-
if (backend === "direct" && plan.profile.harness === "gemini")
|
|
11085
|
-
validateHarnessVersion("gemini", detection?.version);
|
|
11086
|
-
if (backend === "direct" && plan.profile.harness === "aider")
|
|
11087
|
-
validateHarnessVersion(plan.profile.harness, detection?.version);
|
|
11088
|
-
const root = resolve9(options.stateDir ?? join15(switcherHome(), "state"));
|
|
11089
|
-
await privateDirectory(root);
|
|
11090
|
-
const stateDir = await mkdtemp(join15(root, "launch-"));
|
|
11091
|
-
let credential;
|
|
11092
|
-
if (backend === "direct") {
|
|
11093
|
-
try {
|
|
11094
|
-
credential = options.resolveCredential ? await options.resolveCredential(plan.provider) : providerCredential(plan.provider, options.credentialEnv);
|
|
11095
|
-
if (plan.provider.credentialEnv && !credential)
|
|
11096
|
-
throw new Error("Provider credential environment reference is not available in this local launcher process.");
|
|
11097
|
-
} catch (error) {
|
|
11098
|
-
await rm6(stateDir, { recursive: true, force: true });
|
|
11099
|
-
throw error;
|
|
11100
|
-
}
|
|
12138
|
+
|
|
12139
|
+
// src/claude-desktop-launch.ts
|
|
12140
|
+
import { createHash as createHash11 } from "crypto";
|
|
12141
|
+
import { execFile as execFile5 } from "child_process";
|
|
12142
|
+
import { access as access5, rm as rm5, writeFile as writeFile13 } from "fs/promises";
|
|
12143
|
+
import { homedir as homedir8, userInfo as userInfo2 } from "os";
|
|
12144
|
+
import { join as join15 } from "path";
|
|
12145
|
+
import { promisify as promisify5 } from "util";
|
|
12146
|
+
var execute4 = promisify5(execFile5);
|
|
12147
|
+
var hash2 = (text) => createHash11("sha256").update(text).digest("hex");
|
|
12148
|
+
var claudeDesktopDataDirectory = () => join15(homedir8(), "Library/Application Support/Claude-3p");
|
|
12149
|
+
async function assertAvailable(userData) {
|
|
12150
|
+
for (const path of [join15("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
|
|
12151
|
+
if (await access5(path).then(() => true, () => false))
|
|
12152
|
+
throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
|
|
12153
|
+
let openFiles;
|
|
12154
|
+
try {
|
|
12155
|
+
openFiles = (await execute4("/usr/sbin/lsof", ["-n", "-P", "-Fpn", "-a", "-u", String(process.getuid?.()), "-c", "Claude"], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, timeout: 8000 })).stdout;
|
|
12156
|
+
} catch (error) {
|
|
12157
|
+
if (error.code === 1)
|
|
12158
|
+
return;
|
|
12159
|
+
throw new Fault(409, "desktop_process_check", "Could not check whether Claude's third-party profile is already running.");
|
|
11101
12160
|
}
|
|
11102
|
-
|
|
11103
|
-
|
|
11104
|
-
|
|
11105
|
-
|
|
11106
|
-
|
|
11107
|
-
|
|
11108
|
-
|
|
11109
|
-
|
|
11110
|
-
|
|
11111
|
-
|
|
11112
|
-
|
|
11113
|
-
|
|
11114
|
-
|
|
11115
|
-
|
|
11116
|
-
|
|
11117
|
-
|
|
11118
|
-
|
|
12161
|
+
if (openFiles.split(`
|
|
12162
|
+
`).some((line) => line.startsWith("n" + userData + "/")))
|
|
12163
|
+
throw new Fault(409, "desktop_busy", "Claude's third-party instance is already running. Quit that instance before changing its provider; the normal Claude instance can stay open.");
|
|
12164
|
+
}
|
|
12165
|
+
function metadata(text) {
|
|
12166
|
+
const value = text === undefined ? { entries: [] } : JSON.parse(text);
|
|
12167
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((item2) => !item2 || typeof item2 !== "object" || Array.isArray(item2)))
|
|
12168
|
+
throw new Fault(422, "desktop_config_invalid", "Claude's configuration library metadata is invalid.");
|
|
12169
|
+
return value;
|
|
12170
|
+
}
|
|
12171
|
+
async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
12172
|
+
if (input.harness !== "claude")
|
|
12173
|
+
throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
|
|
12174
|
+
validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
|
|
12175
|
+
if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
|
|
12176
|
+
throw new Fault(400, "desktop_arguments", "Claude desktop uses its own effort and permission controls; native CLI arguments and Codex-only launch controls are not accepted.");
|
|
12177
|
+
const version = app.version.split(".").map(Number);
|
|
12178
|
+
if (version.length < 3 || version.some((n) => !Number.isSafeInteger(n)) || version[0] < 1 || version[0] === 1 && version[1] < 52386)
|
|
12179
|
+
throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
|
|
12180
|
+
const userData = system?.userData ?? claudeDesktopDataDirectory();
|
|
12181
|
+
const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
|
|
12182
|
+
await check2();
|
|
12183
|
+
await privateDirectory(userData);
|
|
12184
|
+
const library = join15(userData, "configLibrary");
|
|
12185
|
+
await privateDirectory(library);
|
|
12186
|
+
const release = await desktopLease(join15(library, ".switcher-lease.sqlite"));
|
|
12187
|
+
const metaPath = join15(library, "_meta.json"), receiptPath = join15(library, ".switcher-selection.json");
|
|
12188
|
+
let receipt, gateway, closed = false;
|
|
12189
|
+
const restore = async (record3) => {
|
|
12190
|
+
if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
|
|
12191
|
+
throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
|
|
12192
|
+
const configPath = join15(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
|
|
12193
|
+
if (current !== undefined && hash2(current) !== record3.configHash)
|
|
12194
|
+
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
|
+
const currentMeta = await safeDesktopRead(metaPath);
|
|
12196
|
+
if (currentMeta !== record3.appliedMeta && currentMeta !== (record3.previousMeta ?? undefined))
|
|
12197
|
+
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 (record3.previousMeta === null)
|
|
12199
|
+
await rm5(metaPath, { force: true });
|
|
12200
|
+
else
|
|
12201
|
+
await writeDesktopPrivate(metaPath, record3.previousMeta);
|
|
12202
|
+
await rm5(configPath, { force: true });
|
|
12203
|
+
await rm5(receiptPath, { force: true });
|
|
11119
12204
|
};
|
|
11120
|
-
const
|
|
11121
|
-
if (
|
|
12205
|
+
const cleanup = async () => {
|
|
12206
|
+
if (closed)
|
|
11122
12207
|
return;
|
|
11123
|
-
|
|
11124
|
-
await client.finishRun(candidate.id, candidate.version, { ...body, routingEvents, routingEventsDropped }, crypto.randomUUID()).catch(() => console.error(message));
|
|
11125
|
-
};
|
|
11126
|
-
let cancelPreparation;
|
|
11127
|
-
const preparationCancellation = new Promise((_, reject2) => {
|
|
11128
|
-
cancelPreparation = reject2;
|
|
11129
|
-
});
|
|
11130
|
-
preparationCancellation.catch(() => {
|
|
11131
|
-
return;
|
|
11132
|
-
});
|
|
11133
|
-
try {
|
|
11134
|
-
const input = {
|
|
11135
|
-
harness: plan.profile.harness,
|
|
11136
|
-
baseUrl: plan.provider.baseUrl,
|
|
11137
|
-
protocol: plan.provider.protocol,
|
|
11138
|
-
authStyle: plan.provider.authStyle,
|
|
11139
|
-
model: plan.profile.model,
|
|
11140
|
-
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
11141
|
-
modelPolicy: plan.profile.modelPolicy,
|
|
11142
|
-
providerId: plan.provider.id,
|
|
11143
|
-
onRoutingEvent,
|
|
11144
|
-
credential,
|
|
11145
|
-
stateDir,
|
|
11146
|
-
cwd: resolve9(options.cwd ?? process.cwd())
|
|
11147
|
-
};
|
|
11148
|
-
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join15(root, "desktop-claude", profileId)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent })).prepared : await prepareHarnessLaunch({
|
|
11149
|
-
harness: plan.profile.harness,
|
|
11150
|
-
baseUrl: plan.provider.baseUrl,
|
|
11151
|
-
protocol: plan.provider.protocol,
|
|
11152
|
-
model: plan.profile.model,
|
|
11153
|
-
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
11154
|
-
modelPolicy: plan.profile.modelPolicy,
|
|
11155
|
-
providerId: plan.provider.id,
|
|
11156
|
-
onRoutingEvent,
|
|
11157
|
-
reasoning: options.reasoning,
|
|
11158
|
-
dangerouslyBypassApprovalsAndSandbox: options.dangerouslyBypassApprovalsAndSandbox,
|
|
11159
|
-
credential,
|
|
11160
|
-
authStyle: plan.provider.authStyle,
|
|
11161
|
-
executable: nativeExecutable ?? detection?.executable,
|
|
11162
|
-
args: options.args ?? [],
|
|
11163
|
-
stateDir,
|
|
11164
|
-
cwd: resolve9(options.cwd ?? process.cwd()),
|
|
11165
|
-
version: detection?.version,
|
|
11166
|
-
...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo"].includes(plan.profile.harness) ? { sessionDir: join15(root, "sessions", plan.profile.harness, profileId) } : {}
|
|
11167
|
-
});
|
|
11168
|
-
cleanup = prepared.cleanup;
|
|
11169
|
-
if (options.desktop) {
|
|
11170
|
-
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join15(root, "desktop", profileId));
|
|
11171
|
-
cleanup = prepared.cleanup;
|
|
11172
|
-
}
|
|
11173
|
-
for (const warning of [...plan.warnings, ...prepared.warnings])
|
|
11174
|
-
console.error(`switcher: ${warning}`);
|
|
11175
|
-
const interruptPreparation = (error, cancel = true) => {
|
|
11176
|
-
if (preparationSignal)
|
|
11177
|
-
return;
|
|
11178
|
-
preparationSignal = error;
|
|
11179
|
-
createRunCancelled = true;
|
|
11180
|
-
preparationCleanup ??= cleanup?.().catch((error2) => {
|
|
11181
|
-
console.error(`switcher: Could not clean up the interrupted launch: ${error2 instanceof Error ? error2.message : "unknown cleanup failure"}.`);
|
|
11182
|
-
});
|
|
11183
|
-
if (cancel)
|
|
11184
|
-
cancelPreparation(preparationSignal);
|
|
11185
|
-
};
|
|
11186
|
-
const onPreparationSignal = (signal) => {
|
|
11187
|
-
if (preparationSignal)
|
|
11188
|
-
return;
|
|
11189
|
-
const exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 129;
|
|
11190
|
-
interruptPreparation(new CommandInterrupted(exitCode, "Launch was interrupted before the native harness started."));
|
|
11191
|
-
};
|
|
11192
|
-
const onInt = () => onPreparationSignal("SIGINT");
|
|
11193
|
-
const onTerm = () => onPreparationSignal("SIGTERM");
|
|
11194
|
-
const onHangup = () => onPreparationSignal("SIGHUP");
|
|
11195
|
-
const hasPreparation = Boolean(prepared.beforeLaunch);
|
|
11196
|
-
const needsPreparationCancellation = hasPreparation || launchDeadline !== undefined;
|
|
11197
|
-
if (needsPreparationCancellation) {
|
|
11198
|
-
process.on("SIGINT", onInt);
|
|
11199
|
-
process.on("SIGTERM", onTerm);
|
|
11200
|
-
process.on("SIGHUP", onHangup);
|
|
11201
|
-
const remaining = launchDeadline === undefined ? undefined : launchDeadline - Date.now();
|
|
11202
|
-
if (remaining !== undefined) {
|
|
11203
|
-
if (remaining <= 0)
|
|
11204
|
-
interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."));
|
|
11205
|
-
else
|
|
11206
|
-
preparationTimeout = setTimeout(() => interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started.")), remaining);
|
|
11207
|
-
}
|
|
11208
|
-
}
|
|
12208
|
+
closed = true;
|
|
11209
12209
|
try {
|
|
11210
|
-
|
|
11211
|
-
|
|
11212
|
-
|
|
11213
|
-
|
|
11214
|
-
|
|
11215
|
-
throw preparationSignal;
|
|
11216
|
-
const createRunPromise = client.createRun({ profileId, model: plan.profile.model, harness: plan.profile.harness, planToken: plan.planToken });
|
|
11217
|
-
lateCreateRunFinalization = createRunPromise.then(async (lateRun) => {
|
|
11218
|
-
if (!createRunCancelled)
|
|
11219
|
-
return;
|
|
11220
|
-
await finishRunOnce(lateRun, { status: "interrupted", exitCode: preparationSignal?.exitCode ?? 143 }, "switcher: A cancelled run could not be finalized; inspect the run through the API.");
|
|
11221
|
-
}).catch((error) => {
|
|
11222
|
-
if (createRunCancelled)
|
|
11223
|
-
console.error(`switcher: A cancelled run could not be created: ${error instanceof Error ? error.message : "unknown error"}.`);
|
|
11224
|
-
});
|
|
11225
|
-
try {
|
|
11226
|
-
run = await Promise.race([createRunPromise, preparationCancellation]);
|
|
11227
|
-
} catch (error) {
|
|
11228
|
-
createRunCancelled = true;
|
|
11229
|
-
throw error;
|
|
11230
|
-
}
|
|
11231
|
-
if (preparationSignal)
|
|
11232
|
-
throw preparationSignal;
|
|
11233
|
-
} finally {
|
|
11234
|
-
if (preparationTimeout)
|
|
11235
|
-
clearTimeout(preparationTimeout);
|
|
11236
|
-
if (needsPreparationCancellation) {
|
|
11237
|
-
process.off("SIGINT", onInt);
|
|
11238
|
-
process.off("SIGTERM", onTerm);
|
|
11239
|
-
process.off("SIGHUP", onHangup);
|
|
11240
|
-
}
|
|
11241
|
-
}
|
|
11242
|
-
const remainingRuntime = launchDeadline === undefined ? undefined : launchDeadline - Date.now();
|
|
11243
|
-
if (remainingRuntime !== undefined && remainingRuntime <= 0) {
|
|
11244
|
-
interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
|
|
11245
|
-
throw preparationSignal;
|
|
12210
|
+
await gateway?.cleanup();
|
|
12211
|
+
if (receipt)
|
|
12212
|
+
await restore(receipt);
|
|
12213
|
+
} finally {
|
|
12214
|
+
release();
|
|
11246
12215
|
}
|
|
11247
|
-
|
|
11248
|
-
|
|
11249
|
-
|
|
11250
|
-
|
|
11251
|
-
|
|
12216
|
+
};
|
|
12217
|
+
try {
|
|
12218
|
+
const recovery = await safeDesktopRead(receiptPath);
|
|
12219
|
+
if (recovery)
|
|
12220
|
+
await restore(JSON.parse(recovery));
|
|
12221
|
+
const localConfig = await safeDesktopRead(join15(userData, "claude_desktop_config.json"));
|
|
12222
|
+
if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
|
|
12223
|
+
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
|
+
await privateDirectory(sessionDir);
|
|
12225
|
+
const roles2 = input.modelPolicy?.roles;
|
|
12226
|
+
const targets = { sonnet: input.model, opus: roles2?.planning ?? input.model, haiku: roles2?.fast ?? input.model };
|
|
12227
|
+
const aliases = Object.fromEntries(Object.entries(targets).map(([tier, model3]) => ["switcher/" + tier, model3]));
|
|
12228
|
+
for (const [alias, target] of Object.entries(aliases))
|
|
12229
|
+
if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
|
|
12230
|
+
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.");
|
|
12231
|
+
const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
|
|
12232
|
+
const catalogPath = join15(input.stateDir, "claude-desktop-policy.json");
|
|
12233
|
+
await writeFile13(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
|
|
12234
|
+
gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
12235
|
+
const id2 = crypto.randomUUID(), configPath = join15(library, id2 + ".json");
|
|
12236
|
+
const config = JSON.stringify({
|
|
12237
|
+
inferenceProvider: "gateway",
|
|
12238
|
+
inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
|
|
12239
|
+
inferenceGatewayApiKey: gateway.token,
|
|
12240
|
+
inferenceGatewayAuthScheme: "bearer",
|
|
12241
|
+
modelDiscoveryEnabled: false,
|
|
12242
|
+
inferenceModels: Object.entries(targets).map(([tier, model3]) => ({ name: "switcher/" + tier, labelOverride: model3, anthropicFamilyTier: tier, isFamilyDefault: true }))
|
|
12243
|
+
});
|
|
12244
|
+
const previousMeta = await safeDesktopRead(metaPath);
|
|
12245
|
+
const meta = metadata(previousMeta);
|
|
12246
|
+
const appliedMeta = JSON.stringify({ ...meta, appliedId: id2, entries: [...meta.entries, { id: id2, name: `Switcher: ${input.providerId ?? "provider"} / ${input.model}` }] });
|
|
12247
|
+
receipt = { id: id2, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
|
|
12248
|
+
await writeDesktopPrivate(configPath, config);
|
|
12249
|
+
await writeDesktopPrivate(receiptPath, JSON.stringify(receipt));
|
|
12250
|
+
await writeDesktopPrivate(metaPath, appliedMeta);
|
|
12251
|
+
return {
|
|
12252
|
+
executable: app.executable,
|
|
12253
|
+
args: [],
|
|
12254
|
+
env: { CLAUDE_CONFIG_DIR: sessionDir },
|
|
12255
|
+
configPaths: [catalogPath, configPath],
|
|
12256
|
+
beforeLaunch: check2,
|
|
12257
|
+
cleanup,
|
|
12258
|
+
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
|
+
};
|
|
11252
12260
|
} catch (error) {
|
|
11253
|
-
await preparationCleanup;
|
|
11254
12261
|
try {
|
|
11255
|
-
await cleanup
|
|
11256
|
-
cleanup = undefined;
|
|
12262
|
+
await cleanup();
|
|
11257
12263
|
} catch {}
|
|
11258
|
-
if (run)
|
|
11259
|
-
await finishRunOnce(run, { status: preparationSignal ? "interrupted" : "failed", exitCode: preparationSignal?.exitCode ?? 1 }, "switcher: Could not persist final run status; inspect the run through the API.");
|
|
11260
12264
|
throw error;
|
|
11261
|
-
} finally {
|
|
11262
|
-
if (lateCreateRunFinalization) {
|
|
11263
|
-
let finalizationTimer;
|
|
11264
|
-
const finalizationTimeout = new Promise((resolve10) => {
|
|
11265
|
-
finalizationTimer = setTimeout(resolve10, LATE_RUN_FINALIZATION_TIMEOUT_MS);
|
|
11266
|
-
});
|
|
11267
|
-
try {
|
|
11268
|
-
await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
|
|
11269
|
-
} finally {
|
|
11270
|
-
if (finalizationTimer)
|
|
11271
|
-
clearTimeout(finalizationTimer);
|
|
11272
|
-
}
|
|
11273
|
-
}
|
|
11274
|
-
await preparationCleanup;
|
|
11275
|
-
try {
|
|
11276
|
-
await cleanup?.();
|
|
11277
|
-
} finally {
|
|
11278
|
-
await rm6(stateDir, { recursive: true, force: true });
|
|
11279
|
-
}
|
|
11280
12265
|
}
|
|
11281
12266
|
}
|
|
11282
12267
|
|
|
11283
|
-
// src/
|
|
11284
|
-
|
|
11285
|
-
|
|
11286
|
-
|
|
11287
|
-
|
|
11288
|
-
|
|
11289
|
-
|
|
11290
|
-
|
|
11291
|
-
} catch (error) {
|
|
11292
|
-
if (!absent(error))
|
|
11293
|
-
throw error;
|
|
11294
|
-
}
|
|
11295
|
-
if (existing) {
|
|
11296
|
-
if (Object.entries(options).some(([key, value]) => key !== "harness" && value !== undefined))
|
|
11297
|
-
throw new Fault(409, "provider_override", "This ID names a saved provider. Update it explicitly or use a different preset/provider ID.");
|
|
11298
|
-
return existing;
|
|
11299
|
-
}
|
|
11300
|
-
const desired = providerFromPreset(selector, options);
|
|
11301
|
-
try {
|
|
11302
|
-
existing = await client.getProvider(desired.id);
|
|
11303
|
-
} catch (error) {
|
|
11304
|
-
if (!absent(error))
|
|
11305
|
-
throw error;
|
|
11306
|
-
}
|
|
11307
|
-
if (!existing) {
|
|
11308
|
-
try {
|
|
11309
|
-
return await client.createProvider(desired);
|
|
11310
|
-
} catch (error) {
|
|
11311
|
-
if (!(error instanceof SwitcherError && error.status === 409))
|
|
11312
|
-
throw error;
|
|
11313
|
-
existing = await client.getProvider(desired.id);
|
|
11314
|
-
}
|
|
11315
|
-
}
|
|
11316
|
-
const { version, updatedAt, ...input } = existing;
|
|
11317
|
-
const { additionalModels: _savedAdditions, ...savedSettings } = parse2(providerInputSchema, input);
|
|
11318
|
-
const { additionalModels: _presetAdditions, ...presetSettings } = desired;
|
|
11319
|
-
if (JSON.stringify(savedSettings) !== JSON.stringify(presetSettings))
|
|
11320
|
-
throw new Fault(409, "provider_conflict", "A saved provider with this preset ID has different settings. Select its ID directly or update it explicitly.");
|
|
11321
|
-
return existing;
|
|
12268
|
+
// src/launcher.ts
|
|
12269
|
+
var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
|
|
12270
|
+
async function writeOriCodexCatalog(stateDir, models) {
|
|
12271
|
+
const path = join16(stateDir, "ori-codex-models.json");
|
|
12272
|
+
const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
|
|
12273
|
+
await writeFile14(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
|
|
12274
|
+
`, { mode: 384, flag: "wx" });
|
|
12275
|
+
return path;
|
|
11322
12276
|
}
|
|
11323
|
-
|
|
11324
|
-
|
|
11325
|
-
|
|
11326
|
-
|
|
11327
|
-
|
|
11328
|
-
if (
|
|
11329
|
-
throw new
|
|
11330
|
-
|
|
11331
|
-
|
|
11332
|
-
|
|
11333
|
-
|
|
11334
|
-
|
|
11335
|
-
|
|
11336
|
-
|
|
11337
|
-
|
|
11338
|
-
|
|
11339
|
-
|
|
11340
|
-
|
|
11341
|
-
const visible = matching.slice(0, 30);
|
|
11342
|
-
console.error(`Models: ${matching.length} match${matching.length === 1 ? "" : "es"}${matching.length > 30 ? " (first 30 shown; type to narrow)" : ""}.`);
|
|
11343
|
-
visible.forEach((m, i) => console.error(` ${i + 1}. ${display(m.id)} \u2014 ${display(m.name)}${m.expiresOn ? ` (expires ${m.expiresOn}, inclusive UTC)` : ""}`));
|
|
11344
|
-
const answer = (await reader.question("Model number, exact model ID, or search text (Ctrl-C cancels): ", { signal: cancellation.signal }).catch((error) => {
|
|
11345
|
-
throw cancellation.signal.aborted ? cancellation.signal.reason : error;
|
|
11346
|
-
})).trim();
|
|
11347
|
-
if (/^[1-9]\d*$/.test(answer) && visible[Number(answer) - 1])
|
|
11348
|
-
return visible[Number(answer) - 1].id;
|
|
11349
|
-
if (eligible.some((m) => m.id === answer))
|
|
11350
|
-
return answer;
|
|
11351
|
-
query = answer;
|
|
11352
|
-
}
|
|
11353
|
-
} finally {
|
|
11354
|
-
reader.off("SIGINT", cancel);
|
|
11355
|
-
reader.off("close", cancel);
|
|
11356
|
-
process.off("SIGINT", cancel);
|
|
11357
|
-
process.off("SIGTERM", terminate);
|
|
11358
|
-
reader.close();
|
|
11359
|
-
}
|
|
12277
|
+
function oriTarget(harness) {
|
|
12278
|
+
if (harness === "kilo")
|
|
12279
|
+
throw new Error("Ori does not launch Kilo; use the direct backend.");
|
|
12280
|
+
if (harness === "opencode")
|
|
12281
|
+
throw new Error("Ori does not launch legacy OpenCode; use the direct backend.");
|
|
12282
|
+
if (harness === "aider")
|
|
12283
|
+
throw new Error("Ori does not launch Aider; use the direct backend.");
|
|
12284
|
+
if (harness === "gemini")
|
|
12285
|
+
throw new Error("Ori does not launch Gemini CLI; use the direct backend.");
|
|
12286
|
+
if (harness === "prime-agent")
|
|
12287
|
+
throw new Error("Ori does not launch Prime Agent; use the direct backend.");
|
|
12288
|
+
if (harness === "omp")
|
|
12289
|
+
throw new Error("Ori does not support OMP; use the direct OMP adapter.");
|
|
12290
|
+
if (harness === "cline")
|
|
12291
|
+
throw new Error("Ori does not support Cline; use the direct Cline adapter.");
|
|
12292
|
+
if (harness === "hermes")
|
|
12293
|
+
throw new Error("Ori does not provide a Hermes adapter; use the direct Hermes backend.");
|
|
12294
|
+
return harness;
|
|
11360
12295
|
}
|
|
11361
|
-
async function
|
|
11362
|
-
|
|
11363
|
-
|
|
11364
|
-
|
|
11365
|
-
const
|
|
11366
|
-
|
|
12296
|
+
async function oriRequestForPlan(plan, options = {}) {
|
|
12297
|
+
validateHarnessProvider(plan.profile.harness, plan.provider);
|
|
12298
|
+
if (options.oriExecutable === "")
|
|
12299
|
+
throw new Error("--ori-executable requires a non-empty executable path.");
|
|
12300
|
+
const target = oriTarget(plan.profile.harness);
|
|
12301
|
+
if (plan.provider.authStyle !== "bearer")
|
|
12302
|
+
throw new Error("Ori requires the OpenRouter Bearer authentication contract; use the direct adapter for other auth styles.");
|
|
12303
|
+
assertOriLoginAllowed({ ...process.env, ...options.credentialEnv });
|
|
12304
|
+
const policyEnvironment = { ...process.env, ...options.credentialEnv };
|
|
12305
|
+
if (plan.profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((policyEnvironment.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
|
|
12306
|
+
throw new Error("Grok API-key authentication is disabled by GROK_DISABLE_API_KEY_AUTH. This provider launch cannot proceed under that native authentication policy.");
|
|
12307
|
+
if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
|
|
12308
|
+
throw new Error("Grok requires a native team login through GROK_FORCE_LOGIN_TEAM_ID. This provider launch cannot proceed under that native authentication policy.");
|
|
12309
|
+
const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve9(options.cwd) : undefined });
|
|
12310
|
+
const native = requireOriHarness(contract, target);
|
|
12311
|
+
if (!native.path)
|
|
12312
|
+
throw new Error("Ori did not report the native harness executable path.");
|
|
12313
|
+
const detection = await detectHarness(target, native.path);
|
|
12314
|
+
if (!detection.available)
|
|
12315
|
+
throw new Error("The native harness reported by Ori could not report its version.");
|
|
12316
|
+
validateHarnessVersion(target, detection.version);
|
|
12317
|
+
const catalogPath = target === "codex" && options.stateDir ? await writeOriCodexCatalog(options.stateDir, plan.catalog.models) : undefined;
|
|
12318
|
+
const request = buildOriRequest(plan, target, catalogPath, options.args ?? []);
|
|
12319
|
+
validateOriLaunchRequest(request);
|
|
12320
|
+
return { contract, request, detection };
|
|
12321
|
+
}
|
|
12322
|
+
async function validateOriForPlan(plan, options = {}) {
|
|
12323
|
+
const result = await oriRequestForPlan(plan, options);
|
|
12324
|
+
return { ...result, warnings: oriLaunchWarnings(result.request.target) };
|
|
12325
|
+
}
|
|
12326
|
+
function buildOriRequest(plan, target, catalogPath, args) {
|
|
12327
|
+
return {
|
|
12328
|
+
target,
|
|
12329
|
+
provider: plan.provider.id,
|
|
12330
|
+
providerBaseUrl: plan.provider.baseUrl,
|
|
12331
|
+
protocol: plan.provider.protocol,
|
|
12332
|
+
model: plan.profile.model,
|
|
12333
|
+
catalog: { source: "switcher-openrouter", modelIds: plan.catalog.models.filter(codingEligible).map((model3) => model3.id), ...catalogPath ? { codexModelCatalogPath: catalogPath } : {} },
|
|
12334
|
+
args
|
|
12335
|
+
};
|
|
12336
|
+
}
|
|
12337
|
+
async function prepareOriForPlan(plan, options) {
|
|
12338
|
+
const { contract, request, detection } = await oriRequestForPlan(plan, options);
|
|
12339
|
+
const credential = options.resolveCredential ? await options.resolveCredential(plan.provider) : providerCredential(plan.provider, options.credentialEnv);
|
|
12340
|
+
if (!credential)
|
|
12341
|
+
throw new Fault(400, "credential_setup_required", `OpenRouter credential setup is required. Run: ${providerCredentialSetupCommand(plan.provider)}.`);
|
|
12342
|
+
const ori = prepareOriLaunch({ ...request, executable: contract.executable, environment: { ...process.env, ...options.credentialEnv, OPENROUTER_API_KEY: credential } });
|
|
12343
|
+
const native = await prepareHarnessLaunch({
|
|
12344
|
+
harness: plan.profile.harness,
|
|
12345
|
+
baseUrl: plan.provider.baseUrl,
|
|
12346
|
+
protocol: plan.provider.protocol,
|
|
12347
|
+
authStyle: plan.provider.authStyle,
|
|
12348
|
+
model: plan.profile.model,
|
|
12349
|
+
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
12350
|
+
modelPolicy: plan.profile.modelPolicy,
|
|
12351
|
+
providerId: plan.provider.id,
|
|
12352
|
+
onRoutingEvent: options.onRoutingEvent,
|
|
12353
|
+
credential,
|
|
12354
|
+
executable: detection.executable,
|
|
12355
|
+
version: detection.version,
|
|
12356
|
+
stateDir: options.stateDir,
|
|
12357
|
+
cwd: resolve9(options.cwd ?? process.cwd()),
|
|
12358
|
+
args: options.args ?? []
|
|
12359
|
+
});
|
|
11367
12360
|
try {
|
|
11368
|
-
|
|
11369
|
-
|
|
11370
|
-
|
|
11371
|
-
|
|
11372
|
-
|
|
11373
|
-
|
|
11374
|
-
|
|
11375
|
-
|
|
11376
|
-
|
|
11377
|
-
|
|
11378
|
-
|
|
11379
|
-
|
|
11380
|
-
|
|
12361
|
+
const shim = prepareOriModelPolicy(request.target, native);
|
|
12362
|
+
const dir = join16(options.stateDir, "ori-bin"), path = join16(dir, shim.name);
|
|
12363
|
+
await mkdir11(dir, { mode: 448 });
|
|
12364
|
+
await writeFile14(path, shim.script, { mode: 448, flag: "wx" });
|
|
12365
|
+
return { contract, prepared: {
|
|
12366
|
+
...ori,
|
|
12367
|
+
env: { ...ori.env, ...shim.env, PATH: `${dir}:${ori.env.PATH ?? process.env.PATH ?? ""}` },
|
|
12368
|
+
configPaths: [...native.configPaths, path],
|
|
12369
|
+
beforeLaunch: native.beforeLaunch,
|
|
12370
|
+
cleanup: native.cleanup,
|
|
12371
|
+
warnings: [...native.warnings, "Ori performs its own OpenRouter catalog/auth checks; its native child uses Switcher's prepared model policy and gateway."]
|
|
12372
|
+
} };
|
|
12373
|
+
} catch (error) {
|
|
12374
|
+
await native.cleanup?.();
|
|
12375
|
+
throw error;
|
|
11381
12376
|
}
|
|
11382
|
-
if (existing.providerId !== desired.providerId || existing.harness !== harness || existing.model !== model3 || canonicalPolicyJSON(existing.modelPolicy ?? null) !== canonicalPolicyJSON(desired.modelPolicy ?? null))
|
|
11383
|
-
throw new Fault(409, "profile_conflict", "An existing launch profile has different settings. Select a saved profile explicitly.");
|
|
11384
|
-
return existing;
|
|
11385
12377
|
}
|
|
11386
|
-
|
|
11387
|
-
|
|
11388
|
-
|
|
11389
|
-
|
|
11390
|
-
|
|
11391
|
-
|
|
11392
|
-
|
|
11393
|
-
|
|
11394
|
-
|
|
11395
|
-
|
|
11396
|
-
|
|
11397
|
-
|
|
11398
|
-
|
|
11399
|
-
|
|
11400
|
-
|
|
11401
|
-
|
|
11402
|
-
|
|
11403
|
-
|
|
11404
|
-
|
|
11405
|
-
|
|
11406
|
-
|
|
11407
|
-
|
|
11408
|
-
|
|
11409
|
-
|
|
11410
|
-
|
|
11411
|
-
|
|
11412
|
-
|
|
11413
|
-
|
|
11414
|
-
|
|
11415
|
-
|
|
11416
|
-
|
|
11417
|
-
|
|
11418
|
-
|
|
11419
|
-
if (
|
|
11420
|
-
|
|
11421
|
-
|
|
11422
|
-
|
|
11423
|
-
|
|
11424
|
-
|
|
11425
|
-
|
|
11426
|
-
|
|
11427
|
-
|
|
11428
|
-
|
|
11429
|
-
|
|
11430
|
-
}
|
|
11431
|
-
path(name) {
|
|
11432
|
-
return join16(this.directory, parse2(reference, name) + ".json");
|
|
11433
|
-
}
|
|
11434
|
-
async readableDirectory() {
|
|
11435
|
-
for (const path of [switcherHome(this.env), join16(switcherHome(this.env), "config"), this.directory]) {
|
|
11436
|
-
let info;
|
|
11437
|
-
try {
|
|
11438
|
-
info = await lstat5(path);
|
|
11439
|
-
} catch (error) {
|
|
11440
|
-
if (error.code === "ENOENT")
|
|
11441
|
-
return false;
|
|
11442
|
-
throw error;
|
|
11443
|
-
}
|
|
11444
|
-
if (!info.isDirectory() || info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid?.()))
|
|
11445
|
-
throw new Fault(500, "credential_binding_permissions", "Credential binding directories must be real, owner-only directories (mode 0700).");
|
|
11446
|
-
}
|
|
11447
|
-
return true;
|
|
11448
|
-
}
|
|
11449
|
-
async get(name) {
|
|
11450
|
-
const path = this.path(name);
|
|
11451
|
-
if (!await this.readableDirectory())
|
|
11452
|
-
return;
|
|
11453
|
-
let file;
|
|
11454
|
-
try {
|
|
11455
|
-
file = await open3(path, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
11456
|
-
} catch (error) {
|
|
11457
|
-
if (error.code === "ENOENT")
|
|
11458
|
-
return;
|
|
11459
|
-
throw new Fault(500, "credential_binding_unreadable", "Cannot safely open the local credential binding.");
|
|
11460
|
-
}
|
|
11461
|
-
try {
|
|
11462
|
-
const info = await file.stat();
|
|
11463
|
-
if (!info.isFile() || info.size > 32768 || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid?.()))
|
|
11464
|
-
throw new Fault(500, "credential_binding_permissions", "Credential binding must be an owner-only regular file (mode 0600).");
|
|
11465
|
-
let value;
|
|
11466
|
-
try {
|
|
11467
|
-
value = JSON.parse(await file.readFile("utf8"));
|
|
11468
|
-
} catch {
|
|
11469
|
-
throw new Fault(500, "credential_binding_invalid", "Credential binding must contain valid JSON.");
|
|
11470
|
-
}
|
|
11471
|
-
const binding = parse2(credentialBindingSchema, value);
|
|
11472
|
-
if (binding.credentialEnv !== name)
|
|
11473
|
-
throw new Fault(500, "credential_binding_invalid", "Credential binding reference does not match its filename.");
|
|
11474
|
-
return binding;
|
|
11475
|
-
} finally {
|
|
11476
|
-
await file.close();
|
|
11477
|
-
}
|
|
11478
|
-
}
|
|
11479
|
-
async list() {
|
|
11480
|
-
if (!await this.readableDirectory())
|
|
11481
|
-
return [];
|
|
11482
|
-
let entries;
|
|
12378
|
+
async function launch(client, profileId, options = {}) {
|
|
12379
|
+
const launchDeadline = options.timeoutMs === undefined ? undefined : Date.now() + options.timeoutMs;
|
|
12380
|
+
const profile = await client.getProfile(profileId);
|
|
12381
|
+
if ((options.reasoning || options.dangerouslyBypassApprovalsAndSandbox) && (profile.harness !== "codex" || (options.backend ?? "direct") !== "direct"))
|
|
12382
|
+
throw new Error("Reasoning and full-access launch options require direct Codex or ChatGPT.");
|
|
12383
|
+
assertHarnessArguments(profile.harness, options.args ?? []);
|
|
12384
|
+
if (profile.harness === "gemini")
|
|
12385
|
+
validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
|
|
12386
|
+
await validateHarnessConfiguration(profile.harness, resolve9(options.cwd ?? process.cwd()), options.args);
|
|
12387
|
+
if (profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((process.env.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
|
|
12388
|
+
throw new Error("Grok API-key authentication is disabled by GROK_DISABLE_API_KEY_AUTH. This provider launch cannot proceed under that native authentication policy.");
|
|
12389
|
+
if (profile.harness === "grok" && process.env.GROK_FORCE_LOGIN_TEAM_ID?.trim())
|
|
12390
|
+
throw new Error("Grok requires a native team login through GROK_FORCE_LOGIN_TEAM_ID. This provider launch cannot proceed under that native authentication policy.");
|
|
12391
|
+
if (options.refresh !== false)
|
|
12392
|
+
await client.refreshModels(profile.providerId);
|
|
12393
|
+
const plan = await client.launchPlan(profileId);
|
|
12394
|
+
assertHarnessArguments(plan.profile.harness, options.args ?? []);
|
|
12395
|
+
await validateHarnessConfiguration(plan.profile.harness, resolve9(options.cwd ?? process.cwd()), options.args);
|
|
12396
|
+
if (options.credentialPreflight && providerCredentialFingerprint(plan.provider) !== options.credentialPreflight)
|
|
12397
|
+
throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
|
|
12398
|
+
const backend = options.backend ?? "direct";
|
|
12399
|
+
if (backend !== "direct" && backend !== "ori")
|
|
12400
|
+
throw new Error("Unknown launch backend; use direct or ori.");
|
|
12401
|
+
if (backend === "ori" && options.executable)
|
|
12402
|
+
throw new Error("--executable is ambiguous with --backend ori; use --ori-executable PATH.");
|
|
12403
|
+
if (backend === "direct" && options.oriExecutable)
|
|
12404
|
+
throw new Error("--ori-executable requires --backend ori.");
|
|
12405
|
+
if (options.desktop && (plan.profile.harness !== "codex" || backend !== "direct"))
|
|
12406
|
+
throw new Error("ChatGPT requires the direct Codex provider adapter.");
|
|
12407
|
+
if (options.claudeDesktop && (options.desktop || plan.profile.harness !== "claude" || backend !== "direct" || options.executable || options.args?.length))
|
|
12408
|
+
throw new Error("Claude desktop requires its direct Messages gateway adapter without native CLI overrides.");
|
|
12409
|
+
const nativeExecutable = options.desktop?.codexExecutable ?? options.executable;
|
|
12410
|
+
const detection = backend === "direct" && !options.claudeDesktop ? await detectHarness(plan.profile.harness, nativeExecutable) : undefined;
|
|
12411
|
+
if (backend === "direct" && !options.claudeDesktop && !detection?.available)
|
|
12412
|
+
throw new Error(harnessInstallationMessage(plan.profile.harness, detection?.executable ?? plan.profile.harness, Boolean(options.executable)));
|
|
12413
|
+
if (backend === "direct" && plan.profile.harness === "gemini")
|
|
12414
|
+
validateHarnessVersion("gemini", detection?.version);
|
|
12415
|
+
if (backend === "direct" && plan.profile.harness === "aider")
|
|
12416
|
+
validateHarnessVersion(plan.profile.harness, detection?.version);
|
|
12417
|
+
const root = resolve9(options.stateDir ?? join16(switcherHome(), "state"));
|
|
12418
|
+
await privateDirectory(root);
|
|
12419
|
+
const stateDir = await mkdtemp(join16(root, "launch-"));
|
|
12420
|
+
let credential;
|
|
12421
|
+
if (backend === "direct") {
|
|
11483
12422
|
try {
|
|
11484
|
-
|
|
12423
|
+
credential = options.resolveCredential ? await options.resolveCredential(plan.provider) : providerCredential(plan.provider, options.credentialEnv);
|
|
12424
|
+
if (plan.provider.credentialEnv && !credential)
|
|
12425
|
+
throw new Fault(400, "credential_setup_required", `Provider credential setup is required. Run: ${providerCredentialSetupCommand(plan.provider)}. Or provide ${plan.provider.credentialEnv} in this launch process.`);
|
|
11485
12426
|
} catch (error) {
|
|
11486
|
-
|
|
11487
|
-
return [];
|
|
12427
|
+
await rm6(stateDir, { recursive: true, force: true });
|
|
11488
12428
|
throw error;
|
|
11489
12429
|
}
|
|
11490
|
-
const result = [];
|
|
11491
|
-
for (const name of entries.sort())
|
|
11492
|
-
if (/^SWITCHER_PROVIDER_[A-Z0-9_]+\.json$/.test(name)) {
|
|
11493
|
-
const binding = await this.get(name.slice(0, -5));
|
|
11494
|
-
if (binding)
|
|
11495
|
-
result.push(binding);
|
|
11496
|
-
}
|
|
11497
|
-
return result;
|
|
11498
|
-
}
|
|
11499
|
-
async bind(input) {
|
|
11500
|
-
const binding = parse2(credentialBindingSchema, input);
|
|
11501
|
-
if (binding.source.kind === "vault")
|
|
11502
|
-
await validateVaultExecutable(binding.source.executable);
|
|
11503
|
-
await privateDirectory(switcherHome(this.env));
|
|
11504
|
-
await privateDirectory(join16(switcherHome(this.env), "config"));
|
|
11505
|
-
await privateDirectory(this.directory);
|
|
11506
|
-
const temporary = join16(this.directory, `.binding-${randomUUID5()}`);
|
|
11507
|
-
const file = await open3(temporary, "wx", 384);
|
|
11508
|
-
try {
|
|
11509
|
-
await file.writeFile(JSON.stringify(binding, null, 2) + `
|
|
11510
|
-
`);
|
|
11511
|
-
await file.sync();
|
|
11512
|
-
try {
|
|
11513
|
-
await link(temporary, this.path(binding.credentialEnv));
|
|
11514
|
-
} catch (error) {
|
|
11515
|
-
if (error.code !== "EEXIST")
|
|
11516
|
-
throw error;
|
|
11517
|
-
const existing = await this.get(binding.credentialEnv);
|
|
11518
|
-
if (existing && fingerprint(existing) === fingerprint(binding))
|
|
11519
|
-
return existing;
|
|
11520
|
-
throw new Fault(409, "credential_binding_exists", "A different binding already exists. Remove it explicitly before binding another credential account.");
|
|
11521
|
-
}
|
|
11522
|
-
} finally {
|
|
11523
|
-
await file.close();
|
|
11524
|
-
await unlink(temporary);
|
|
11525
|
-
}
|
|
11526
|
-
return binding;
|
|
11527
|
-
}
|
|
11528
|
-
async remove(name) {
|
|
11529
|
-
const binding = await this.get(name);
|
|
11530
|
-
if (!binding)
|
|
11531
|
-
throw new Fault(404, "credential_binding_missing", "No local credential binding exists for this reference.");
|
|
11532
|
-
await unlink(this.path(name));
|
|
11533
|
-
return { removed: name };
|
|
11534
|
-
}
|
|
11535
|
-
}
|
|
11536
|
-
function credentialReference(selector) {
|
|
11537
|
-
const name = selector.startsWith("SWITCHER_PROVIDER_") ? selector : getProviderPreset(selector).credentialEnv;
|
|
11538
|
-
if (!name)
|
|
11539
|
-
throw new Fault(400, "credential_reference_required", "Use the explicit SWITCHER_PROVIDER_ reference for this provider.");
|
|
11540
|
-
return parse2(reference, name);
|
|
11541
|
-
}
|
|
11542
|
-
async function inspectVaultExecutable(path, permitWritableFile = false) {
|
|
11543
|
-
let info, resolved;
|
|
11544
|
-
try {
|
|
11545
|
-
resolved = await realpath6(path);
|
|
11546
|
-
await access5(resolved, constants6.X_OK);
|
|
11547
|
-
info = await stat6(resolved);
|
|
11548
|
-
if (!info.isFile())
|
|
11549
|
-
throw new Error;
|
|
11550
|
-
} catch {
|
|
11551
|
-
throw new Fault(422, "vault_exec_unavailable", "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.");
|
|
11552
12430
|
}
|
|
11553
|
-
|
|
11554
|
-
|
|
11555
|
-
|
|
11556
|
-
|
|
11557
|
-
|
|
11558
|
-
|
|
11559
|
-
|
|
11560
|
-
|
|
11561
|
-
|
|
11562
|
-
|
|
11563
|
-
|
|
11564
|
-
|
|
11565
|
-
|
|
11566
|
-
|
|
11567
|
-
|
|
11568
|
-
|
|
11569
|
-
|
|
11570
|
-
|
|
11571
|
-
|
|
11572
|
-
|
|
11573
|
-
|
|
11574
|
-
|
|
12431
|
+
let run;
|
|
12432
|
+
let cleanup;
|
|
12433
|
+
let preparationSignal;
|
|
12434
|
+
let preparationCleanup;
|
|
12435
|
+
let preparationTimeout;
|
|
12436
|
+
let lateCreateRunFinalization;
|
|
12437
|
+
let createRunCancelled = false;
|
|
12438
|
+
let runFinalized = false;
|
|
12439
|
+
const routingEvents = [];
|
|
12440
|
+
let routingEventsDropped = 0, routingBytes = 0;
|
|
12441
|
+
const onRoutingEvent = (event) => {
|
|
12442
|
+
const bytes = Buffer.byteLength(JSON.stringify(event));
|
|
12443
|
+
if (routingEvents.length < 1000 && routingBytes + bytes <= 512 * 1024) {
|
|
12444
|
+
routingEvents.push(event);
|
|
12445
|
+
routingBytes += bytes;
|
|
12446
|
+
} else
|
|
12447
|
+
routingEventsDropped = Math.min(1e6, routingEventsDropped + 1);
|
|
12448
|
+
};
|
|
12449
|
+
const finishRunOnce = async (candidate, body, message) => {
|
|
12450
|
+
if (runFinalized)
|
|
12451
|
+
return;
|
|
12452
|
+
runFinalized = true;
|
|
12453
|
+
await client.finishRun(candidate.id, candidate.version, { ...body, routingEvents, routingEventsDropped }, crypto.randomUUID()).catch(() => console.error(message));
|
|
12454
|
+
};
|
|
12455
|
+
let cancelPreparation;
|
|
12456
|
+
const preparationCancellation = new Promise((_, reject2) => {
|
|
12457
|
+
cancelPreparation = reject2;
|
|
12458
|
+
});
|
|
12459
|
+
preparationCancellation.catch(() => {
|
|
12460
|
+
return;
|
|
12461
|
+
});
|
|
12462
|
+
try {
|
|
12463
|
+
const input = {
|
|
12464
|
+
harness: plan.profile.harness,
|
|
12465
|
+
baseUrl: plan.provider.baseUrl,
|
|
12466
|
+
protocol: plan.provider.protocol,
|
|
12467
|
+
authStyle: plan.provider.authStyle,
|
|
12468
|
+
model: plan.profile.model,
|
|
12469
|
+
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
12470
|
+
modelPolicy: plan.profile.modelPolicy,
|
|
12471
|
+
providerId: plan.provider.id,
|
|
12472
|
+
onRoutingEvent,
|
|
12473
|
+
credential,
|
|
12474
|
+
stateDir,
|
|
12475
|
+
cwd: resolve9(options.cwd ?? process.cwd())
|
|
11575
12476
|
};
|
|
11576
|
-
|
|
11577
|
-
|
|
11578
|
-
|
|
11579
|
-
|
|
11580
|
-
|
|
11581
|
-
|
|
11582
|
-
|
|
12477
|
+
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join16(root, "desktop-claude", profileId)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent })).prepared : await prepareHarnessLaunch({
|
|
12478
|
+
harness: plan.profile.harness,
|
|
12479
|
+
baseUrl: plan.provider.baseUrl,
|
|
12480
|
+
protocol: plan.provider.protocol,
|
|
12481
|
+
model: plan.profile.model,
|
|
12482
|
+
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
12483
|
+
modelPolicy: plan.profile.modelPolicy,
|
|
12484
|
+
providerId: plan.provider.id,
|
|
12485
|
+
onRoutingEvent,
|
|
12486
|
+
reasoning: options.reasoning,
|
|
12487
|
+
dangerouslyBypassApprovalsAndSandbox: options.dangerouslyBypassApprovalsAndSandbox,
|
|
12488
|
+
credential,
|
|
12489
|
+
authStyle: plan.provider.authStyle,
|
|
12490
|
+
executable: nativeExecutable ?? detection?.executable,
|
|
12491
|
+
args: options.args ?? [],
|
|
12492
|
+
stateDir,
|
|
12493
|
+
cwd: resolve9(options.cwd ?? process.cwd()),
|
|
12494
|
+
version: detection?.version,
|
|
12495
|
+
...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo"].includes(plan.profile.harness) ? { sessionDir: join16(root, "sessions", plan.profile.harness, profileId) } : {}
|
|
12496
|
+
});
|
|
12497
|
+
cleanup = prepared.cleanup;
|
|
12498
|
+
if (options.desktop) {
|
|
12499
|
+
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join16(root, "desktop", profileId));
|
|
12500
|
+
cleanup = prepared.cleanup;
|
|
11583
12501
|
}
|
|
11584
|
-
|
|
11585
|
-
|
|
11586
|
-
|
|
11587
|
-
|
|
11588
|
-
|
|
11589
|
-
|
|
11590
|
-
|
|
11591
|
-
|
|
11592
|
-
|
|
11593
|
-
|
|
11594
|
-
|
|
11595
|
-
|
|
11596
|
-
throw new Fault(422, "vault_exec_repair_unsafe", "Executable permission repair requires POSIX file permissions.");
|
|
11597
|
-
const resolved = await inspectVaultExecutable(path, true);
|
|
11598
|
-
const file = await open3(resolved, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
11599
|
-
const unsafe = () => new Fault(422, "vault_exec_repair_unsafe", "Executable ownership, type, links or contents changed; no trusted repair can be confirmed.");
|
|
11600
|
-
let temporary;
|
|
11601
|
-
try {
|
|
11602
|
-
const before = await file.stat();
|
|
11603
|
-
const limit = 256 * 1024 * 1024;
|
|
11604
|
-
if (!before.isFile() || before.uid !== process.getuid?.() || before.size > limit || before.mode & 3584)
|
|
11605
|
-
throw unsafe();
|
|
11606
|
-
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;
|
|
11607
|
-
const hash3 = async (target) => {
|
|
11608
|
-
const digest2 = createHash12("sha256");
|
|
11609
|
-
const buffer = Buffer.alloc(1024 * 1024);
|
|
11610
|
-
let position = 0;
|
|
11611
|
-
while (true) {
|
|
11612
|
-
const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
|
|
11613
|
-
if (!bytesRead)
|
|
11614
|
-
break;
|
|
11615
|
-
position += bytesRead;
|
|
11616
|
-
if (position > limit)
|
|
11617
|
-
throw unsafe();
|
|
11618
|
-
const bytes = buffer.subarray(0, bytesRead);
|
|
11619
|
-
digest2.update(bytes);
|
|
11620
|
-
if (target)
|
|
11621
|
-
await target.writeFile(bytes);
|
|
11622
|
-
}
|
|
11623
|
-
if (position !== before.size || !sameFile(await file.stat()))
|
|
11624
|
-
throw unsafe();
|
|
11625
|
-
if (digest2.digest("hex") !== expectedSha256)
|
|
11626
|
-
throw new Fault(422, "vault_exec_digest_mismatch", "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed.");
|
|
12502
|
+
for (const warning of [...plan.warnings, ...prepared.warnings])
|
|
12503
|
+
console.error(`switcher: ${warning}`);
|
|
12504
|
+
const interruptPreparation = (error, cancel = true) => {
|
|
12505
|
+
if (preparationSignal)
|
|
12506
|
+
return;
|
|
12507
|
+
preparationSignal = error;
|
|
12508
|
+
createRunCancelled = true;
|
|
12509
|
+
preparationCleanup ??= cleanup?.().catch((error2) => {
|
|
12510
|
+
console.error(`switcher: Could not clean up the interrupted launch: ${error2 instanceof Error ? error2.message : "unknown cleanup failure"}.`);
|
|
12511
|
+
});
|
|
12512
|
+
if (cancel)
|
|
12513
|
+
cancelPreparation(preparationSignal);
|
|
11627
12514
|
};
|
|
11628
|
-
|
|
11629
|
-
|
|
11630
|
-
|
|
11631
|
-
|
|
11632
|
-
|
|
11633
|
-
|
|
11634
|
-
|
|
11635
|
-
|
|
12515
|
+
const onPreparationSignal = (signal) => {
|
|
12516
|
+
if (preparationSignal)
|
|
12517
|
+
return;
|
|
12518
|
+
const exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 129;
|
|
12519
|
+
interruptPreparation(new CommandInterrupted(exitCode, "Launch was interrupted before the native harness started."));
|
|
12520
|
+
};
|
|
12521
|
+
const onInt = () => onPreparationSignal("SIGINT");
|
|
12522
|
+
const onTerm = () => onPreparationSignal("SIGTERM");
|
|
12523
|
+
const onHangup = () => onPreparationSignal("SIGHUP");
|
|
12524
|
+
const hasPreparation = Boolean(prepared.beforeLaunch);
|
|
12525
|
+
const needsPreparationCancellation = hasPreparation || launchDeadline !== undefined;
|
|
12526
|
+
if (needsPreparationCancellation) {
|
|
12527
|
+
process.on("SIGINT", onInt);
|
|
12528
|
+
process.on("SIGTERM", onTerm);
|
|
12529
|
+
process.on("SIGHUP", onHangup);
|
|
12530
|
+
const remaining = launchDeadline === undefined ? undefined : launchDeadline - Date.now();
|
|
12531
|
+
if (remaining !== undefined) {
|
|
12532
|
+
if (remaining <= 0)
|
|
12533
|
+
interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."));
|
|
12534
|
+
else
|
|
12535
|
+
preparationTimeout = setTimeout(() => interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started.")), remaining);
|
|
12536
|
+
}
|
|
11636
12537
|
}
|
|
11637
|
-
temporary = join16(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
|
|
11638
|
-
const replacement = await open3(temporary, "wx", 384);
|
|
11639
12538
|
try {
|
|
11640
|
-
|
|
11641
|
-
|
|
11642
|
-
|
|
11643
|
-
|
|
11644
|
-
if (
|
|
11645
|
-
throw
|
|
11646
|
-
|
|
11647
|
-
|
|
11648
|
-
|
|
11649
|
-
|
|
11650
|
-
|
|
11651
|
-
|
|
11652
|
-
|
|
11653
|
-
|
|
12539
|
+
if (preparationSignal)
|
|
12540
|
+
throw preparationSignal;
|
|
12541
|
+
if (prepared.beforeLaunch)
|
|
12542
|
+
await Promise.race([prepared.beforeLaunch(), preparationCancellation]);
|
|
12543
|
+
if (preparationSignal)
|
|
12544
|
+
throw preparationSignal;
|
|
12545
|
+
const createRunPromise = client.createRun({ profileId, model: plan.profile.model, harness: plan.profile.harness, planToken: plan.planToken });
|
|
12546
|
+
lateCreateRunFinalization = createRunPromise.then(async (lateRun) => {
|
|
12547
|
+
if (!createRunCancelled)
|
|
12548
|
+
return;
|
|
12549
|
+
await finishRunOnce(lateRun, { status: "interrupted", exitCode: preparationSignal?.exitCode ?? 143 }, "switcher: A cancelled run could not be finalized; inspect the run through the API.");
|
|
12550
|
+
}).catch((error) => {
|
|
12551
|
+
if (createRunCancelled)
|
|
12552
|
+
console.error(`switcher: A cancelled run could not be created: ${error instanceof Error ? error.message : "unknown error"}.`);
|
|
12553
|
+
});
|
|
11654
12554
|
try {
|
|
11655
|
-
await
|
|
11656
|
-
}
|
|
11657
|
-
|
|
12555
|
+
run = await Promise.race([createRunPromise, preparationCancellation]);
|
|
12556
|
+
} catch (error) {
|
|
12557
|
+
createRunCancelled = true;
|
|
12558
|
+
throw error;
|
|
11658
12559
|
}
|
|
12560
|
+
if (preparationSignal)
|
|
12561
|
+
throw preparationSignal;
|
|
11659
12562
|
} finally {
|
|
11660
|
-
|
|
12563
|
+
if (preparationTimeout)
|
|
12564
|
+
clearTimeout(preparationTimeout);
|
|
12565
|
+
if (needsPreparationCancellation) {
|
|
12566
|
+
process.off("SIGINT", onInt);
|
|
12567
|
+
process.off("SIGTERM", onTerm);
|
|
12568
|
+
process.off("SIGHUP", onHangup);
|
|
12569
|
+
}
|
|
11661
12570
|
}
|
|
11662
|
-
|
|
11663
|
-
|
|
11664
|
-
|
|
11665
|
-
|
|
11666
|
-
|
|
11667
|
-
|
|
11668
|
-
|
|
11669
|
-
|
|
11670
|
-
|
|
11671
|
-
|
|
11672
|
-
throw new Fault(400, "conflicting_options", "A credential reference does not also need --credential-env.");
|
|
11673
|
-
if (!allowedOrigins?.length)
|
|
11674
|
-
throw new Fault(400, "credential_origin_required", "Use --origin URL to authorize a custom credential destination.");
|
|
11675
|
-
return { credentialEnv: parse2(reference, selector), origins: allowedOrigins.map((value) => new URL(endpoint(value)).origin) };
|
|
11676
|
-
}
|
|
11677
|
-
const preset2 = getProviderPreset(selector);
|
|
11678
|
-
const credentialEnv = override ?? preset2.credentialEnv;
|
|
11679
|
-
if (!credentialEnv)
|
|
11680
|
-
throw new Fault(400, "credential_reference_required", "Use --credential-env for a preset without a default credential reference.");
|
|
11681
|
-
const origins = allowedOrigins ?? [...new Set(preset2.protocols.flatMap((route2) => route2.baseUrl ? [new URL(route2.baseUrl).origin] : []))];
|
|
11682
|
-
if (!origins.length)
|
|
11683
|
-
throw new Fault(400, "credential_origin_required", "Use --origin URL for this custom preset.");
|
|
11684
|
-
return { credentialEnv: parse2(reference, credentialEnv), origins };
|
|
11685
|
-
}
|
|
11686
|
-
async function readKeychain(source) {
|
|
11687
|
-
if (process.platform !== "darwin")
|
|
11688
|
-
throw new Fault(422, "keychain_unavailable", "This binding requires macOS Keychain. Use a supported vault binding or runtime environment on this station.");
|
|
11689
|
-
let stdout;
|
|
11690
|
-
try {
|
|
11691
|
-
({ stdout } = await execute4("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 }));
|
|
12571
|
+
const remainingRuntime = launchDeadline === undefined ? undefined : launchDeadline - Date.now();
|
|
12572
|
+
if (remainingRuntime !== undefined && remainingRuntime <= 0) {
|
|
12573
|
+
interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
|
|
12574
|
+
throw preparationSignal;
|
|
12575
|
+
}
|
|
12576
|
+
const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve9(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
|
|
12577
|
+
await cleanup?.();
|
|
12578
|
+
cleanup = undefined;
|
|
12579
|
+
await finishRunOnce(run, { status: interrupted ? "interrupted" : code === 0 ? "exited" : "failed", exitCode: code }, `switcher: Harness exited ${code}; final metadata could not be saved for run ${run.id}.`);
|
|
12580
|
+
return code;
|
|
11692
12581
|
} catch (error) {
|
|
11693
|
-
|
|
11694
|
-
|
|
11695
|
-
|
|
11696
|
-
|
|
11697
|
-
|
|
11698
|
-
|
|
11699
|
-
|
|
11700
|
-
throw
|
|
11701
|
-
|
|
11702
|
-
|
|
11703
|
-
|
|
11704
|
-
|
|
11705
|
-
|
|
11706
|
-
|
|
11707
|
-
|
|
11708
|
-
|
|
11709
|
-
|
|
11710
|
-
|
|
11711
|
-
|
|
11712
|
-
|
|
11713
|
-
|
|
11714
|
-
|
|
11715
|
-
|
|
11716
|
-
|
|
11717
|
-
|
|
11718
|
-
|
|
11719
|
-
if (!binding.origins.includes(new URL(provider.baseUrl).origin))
|
|
11720
|
-
throw new Fault(422, "credential_authority", "The local credential binding does not authorize this provider origin. Update the binding explicitly; no key was sent.");
|
|
11721
|
-
if (binding.source.kind === "keychain")
|
|
11722
|
-
return this.keychainRead(binding.source);
|
|
11723
|
-
return fetchVaultCredential(binding, this.env);
|
|
11724
|
-
}
|
|
11725
|
-
async check(name) {
|
|
11726
|
-
const binding = await this.bindings.get(name);
|
|
11727
|
-
if (!binding)
|
|
11728
|
-
throw new Fault(404, "credential_binding_missing", "No local credential binding exists for this reference.");
|
|
11729
|
-
if (binding.source.kind === "vault") {
|
|
11730
|
-
const output = await runVaultCommand(binding, ["get", binding.source.key, "--check"], this.env, {}, true);
|
|
11731
|
-
const match = /^key=\S+ length=(\d+) sha256=([a-f0-9]{64})\s*$/.exec(output);
|
|
11732
|
-
if (!match)
|
|
11733
|
-
throw new Fault(422, "vault_check_failed", "The secrets CLI did not return a supported credential check result.");
|
|
11734
|
-
return { credentialEnv: name, source: "vault", available: true, length: Number(match[1]), sha256: match[2], providerAuthentication: "not tested" };
|
|
12582
|
+
await preparationCleanup;
|
|
12583
|
+
try {
|
|
12584
|
+
await cleanup?.();
|
|
12585
|
+
cleanup = undefined;
|
|
12586
|
+
} catch {}
|
|
12587
|
+
if (run)
|
|
12588
|
+
await finishRunOnce(run, { status: preparationSignal ? "interrupted" : "failed", exitCode: preparationSignal?.exitCode ?? 1 }, "switcher: Could not persist final run status; inspect the run through the API.");
|
|
12589
|
+
throw error;
|
|
12590
|
+
} finally {
|
|
12591
|
+
if (lateCreateRunFinalization) {
|
|
12592
|
+
let finalizationTimer;
|
|
12593
|
+
const finalizationTimeout = new Promise((resolve10) => {
|
|
12594
|
+
finalizationTimer = setTimeout(resolve10, LATE_RUN_FINALIZATION_TIMEOUT_MS);
|
|
12595
|
+
});
|
|
12596
|
+
try {
|
|
12597
|
+
await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
|
|
12598
|
+
} finally {
|
|
12599
|
+
if (finalizationTimer)
|
|
12600
|
+
clearTimeout(finalizationTimer);
|
|
12601
|
+
}
|
|
12602
|
+
}
|
|
12603
|
+
await preparationCleanup;
|
|
12604
|
+
try {
|
|
12605
|
+
await cleanup?.();
|
|
12606
|
+
} finally {
|
|
12607
|
+
await rm6(stateDir, { recursive: true, force: true });
|
|
11735
12608
|
}
|
|
11736
|
-
const value = await this.keychainRead(binding.source);
|
|
11737
|
-
return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash12("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
|
|
11738
12609
|
}
|
|
11739
12610
|
}
|
|
11740
|
-
var DELIVERY_URL = "SWITCHER_CREDENTIAL_DELIVERY_URL";
|
|
11741
|
-
var DELIVERY_NONCE = "SWITCHER_CREDENTIAL_DELIVERY_NONCE";
|
|
11742
|
-
var DELIVERY_VALUE = "SWITCHER_CREDENTIAL_DELIVERY_VALUE";
|
|
11743
12611
|
|
|
11744
|
-
|
|
11745
|
-
|
|
11746
|
-
|
|
12612
|
+
// src/direct-launch.ts
|
|
12613
|
+
import { createHash as createHash12 } from "crypto";
|
|
12614
|
+
import { createInterface as createInterface2 } from "readline/promises";
|
|
12615
|
+
var absent = (error) => error instanceof SwitcherError && error.status === 404;
|
|
12616
|
+
async function resolveLaunchProvider(client, selector, options = {}) {
|
|
12617
|
+
let existing;
|
|
12618
|
+
try {
|
|
12619
|
+
existing = await client.getProvider(selector);
|
|
12620
|
+
} catch (error) {
|
|
12621
|
+
if (!absent(error))
|
|
12622
|
+
throw error;
|
|
11747
12623
|
}
|
|
11748
|
-
|
|
11749
|
-
|
|
11750
|
-
|
|
11751
|
-
|
|
11752
|
-
|
|
11753
|
-
|
|
12624
|
+
if (existing) {
|
|
12625
|
+
if (Object.entries(options).some(([key, value]) => key !== "harness" && value !== undefined))
|
|
12626
|
+
throw new Fault(409, "provider_override", "This ID names a saved provider. Update it explicitly or use a different preset/provider ID.");
|
|
12627
|
+
return existing;
|
|
12628
|
+
}
|
|
12629
|
+
const desired = providerFromPreset(selector, options);
|
|
11754
12630
|
try {
|
|
11755
|
-
|
|
11756
|
-
const pair = () => {
|
|
11757
|
-
const keys = clientTransportEnvKeys3("secrets");
|
|
11758
|
-
const configuredUrl = keys.apiUrlKeys.map((name) => env[name]).find((value) => value !== undefined) ?? keychainConfigValue2("secrets", env, options.keychain)?.value ?? appConfigDiskValue2("secrets", env, keys.apiUrlKeys)?.value;
|
|
11759
|
-
const resolution = resolveClientTransport("secrets", env, { credentials: options });
|
|
11760
|
-
const key = resolveCredential("secrets", env, options);
|
|
11761
|
-
if (key?.tier === "pointer")
|
|
11762
|
-
throw new Fault(422, "vault_operator_pointer", "A Secrets operator cannot bootstrap itself through HASNA_SECRETS_API_KEY_REF. Configure its operator in Keychain, canonical config/credentials, or an explicit key override.");
|
|
11763
|
-
if (!key?.apiKey || key.source !== resolution.apiKeySource || key.tier !== resolution.apiKeyTier)
|
|
11764
|
-
throw new Fault(422, "vault_operator_changed", "The vault operator changed during resolution; no credential was sent. Retry after configuration is stable.");
|
|
11765
|
-
const boundUrl = source.url ? toV1BaseUrl(source.url) : resolution.baseUrl;
|
|
11766
|
-
if (resolution.apiUrlSource !== "default" && boundUrl !== resolution.baseUrl)
|
|
11767
|
-
throw new Fault(422, "vault_operator_authority", "The binding vault URL conflicts with the canonical Secrets API URL; no credential was sent.");
|
|
11768
|
-
if (configuredUrl !== undefined && toV1BaseUrl(configuredUrl) !== resolution.baseUrl)
|
|
11769
|
-
throw new Fault(422, "vault_operator_changed", "The vault authority changed during resolution; no credential was sent.");
|
|
11770
|
-
return { key, url: configuredUrl?.trim() ?? source.url ?? boundUrl.replace(/\/v1$/, "") };
|
|
11771
|
-
};
|
|
11772
|
-
const first = pair(), second = pair();
|
|
11773
|
-
if (first.key.apiKey !== second.key.apiKey || first.key.source !== second.key.source || first.key.tier !== second.key.tier || first.url !== second.url)
|
|
11774
|
-
throw new Fault(422, "vault_operator_changed", "The vault operator or authority changed during resolution; no credential was sent. Retry after configuration is stable.");
|
|
11775
|
-
credential = second.key;
|
|
11776
|
-
url = second.url;
|
|
11777
|
-
} else {
|
|
11778
|
-
credential = source.operator.kind === "keychain" ? resolveCredential("secrets", { HASNA_STATION: source.operator.account }, { keychain: { ...options.keychain, enabled: true } }) : resolveCredential("secrets", Object.fromEntries(Object.entries(env).filter(([name]) => name === "HASNA_SECRETS_API_KEY")), { keychain: { enabled: false } });
|
|
11779
|
-
}
|
|
12631
|
+
existing = await client.getProvider(desired.id);
|
|
11780
12632
|
} catch (error) {
|
|
11781
|
-
if (error
|
|
12633
|
+
if (!absent(error))
|
|
11782
12634
|
throw error;
|
|
11783
|
-
const kind = error instanceof Error ? error.name : "";
|
|
11784
|
-
const reason = kind === "CredentialFileUnsafeError" ? "unsafe canonical config/credentials file" : kind === "ClientTransportConfigurationError" ? "invalid or missing canonical API URL/key" : source.operator.kind === "keychain" ? "unavailable pinned Keychain account" : "credential selection refused by Contracts (Keychain, canonical file, profile, or environment)";
|
|
11785
|
-
throw new Fault(422, "vault_operator_unavailable", `Cannot resolve the Secrets vault operator: ${reason}. Check the selected source in this terminal session; no alternate account was selected.`);
|
|
11786
12635
|
}
|
|
11787
|
-
if (!
|
|
11788
|
-
|
|
11789
|
-
|
|
11790
|
-
|
|
11791
|
-
|
|
11792
|
-
|
|
11793
|
-
|
|
11794
|
-
|
|
11795
|
-
|
|
11796
|
-
|
|
11797
|
-
}
|
|
11798
|
-
|
|
11799
|
-
if (
|
|
11800
|
-
throw new Fault(
|
|
11801
|
-
|
|
11802
|
-
throw new Fault(422, "vault_exec_unavailable", "Vault CLI bindings currently require POSIX process groups; use runtime environment injection on Windows.");
|
|
11803
|
-
const executable = await validateVaultExecutable(binding.source.executable);
|
|
11804
|
-
const childEnv = { ...await vaultEnvironment(binding, env), ...delivery };
|
|
11805
|
-
return new Promise((resolveResult, reject2) => {
|
|
11806
|
-
const child = spawn2(executable, args, { env: childEnv, stdio: ["ignore", captureCheck ? "pipe" : "ignore", "ignore"], detached: true, shell: false });
|
|
11807
|
-
let failure;
|
|
11808
|
-
let output = "";
|
|
11809
|
-
let cleaned = false;
|
|
11810
|
-
const kill = () => {
|
|
11811
|
-
if (child.pid) {
|
|
11812
|
-
try {
|
|
11813
|
-
process.kill(-child.pid, "SIGKILL");
|
|
11814
|
-
} catch {}
|
|
11815
|
-
}
|
|
11816
|
-
};
|
|
11817
|
-
const interrupt = (signal) => {
|
|
11818
|
-
failure = new CredentialInterrupted(signal === "SIGINT" ? 130 : 143);
|
|
11819
|
-
process.exitCode = signal === "SIGINT" ? 130 : 143;
|
|
11820
|
-
kill();
|
|
11821
|
-
};
|
|
11822
|
-
const onInt = () => interrupt("SIGINT");
|
|
11823
|
-
const onTerm = () => interrupt("SIGTERM");
|
|
11824
|
-
process.on("SIGINT", onInt);
|
|
11825
|
-
process.on("SIGTERM", onTerm);
|
|
11826
|
-
const timeout = setTimeout(() => {
|
|
11827
|
-
failure = new Fault(504, "vault_timeout", "Credential lookup exceeded 20 seconds; no alternate credential was selected.");
|
|
11828
|
-
kill();
|
|
11829
|
-
}, 20000);
|
|
11830
|
-
const cleanup = () => {
|
|
11831
|
-
if (cleaned)
|
|
11832
|
-
return;
|
|
11833
|
-
cleaned = true;
|
|
11834
|
-
clearTimeout(timeout);
|
|
11835
|
-
process.off("SIGINT", onInt);
|
|
11836
|
-
process.off("SIGTERM", onTerm);
|
|
11837
|
-
kill();
|
|
11838
|
-
};
|
|
11839
|
-
child.stdout?.on("data", (chunk) => {
|
|
11840
|
-
if (output.length + chunk.length > 4096) {
|
|
11841
|
-
failure = new Fault(422, "vault_check_failed", "The secrets CLI returned an oversized check result.");
|
|
11842
|
-
kill();
|
|
11843
|
-
} else
|
|
11844
|
-
output += chunk.toString("utf8");
|
|
11845
|
-
});
|
|
11846
|
-
child.once("error", () => {
|
|
11847
|
-
cleanup();
|
|
11848
|
-
reject2(new Fault(422, "vault_exec_failed", "The configured secrets CLI could not start; check its executable and permissions."));
|
|
11849
|
-
});
|
|
11850
|
-
child.once("exit", cleanup);
|
|
11851
|
-
child.once("close", (code) => {
|
|
11852
|
-
if (failure)
|
|
11853
|
-
reject2(failure);
|
|
11854
|
-
else if (code !== 0)
|
|
11855
|
-
reject2(new Fault(422, "vault_lookup_failed", "The secrets CLI could not read the configured key. Check vault access and conflicting local vault URL settings; no alternate account was selected."));
|
|
11856
|
-
else
|
|
11857
|
-
resolveResult(output);
|
|
11858
|
-
});
|
|
11859
|
-
});
|
|
12636
|
+
if (!existing) {
|
|
12637
|
+
try {
|
|
12638
|
+
return await client.createProvider(desired);
|
|
12639
|
+
} catch (error) {
|
|
12640
|
+
if (!(error instanceof SwitcherError && error.status === 409))
|
|
12641
|
+
throw error;
|
|
12642
|
+
existing = await client.getProvider(desired.id);
|
|
12643
|
+
}
|
|
12644
|
+
}
|
|
12645
|
+
const { version, updatedAt, ...input } = existing;
|
|
12646
|
+
const { additionalModels: _savedAdditions, credentialCheck: savedCredentialCheck, ...savedSettings } = parse2(providerInputSchema, input);
|
|
12647
|
+
const { additionalModels: _presetAdditions, credentialCheck: presetCredentialCheck, ...presetSettings } = desired;
|
|
12648
|
+
if (JSON.stringify(savedSettings) !== JSON.stringify(presetSettings) || savedCredentialCheck !== undefined && JSON.stringify(savedCredentialCheck) !== JSON.stringify(presetCredentialCheck))
|
|
12649
|
+
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
|
+
return existing;
|
|
11860
12651
|
}
|
|
11861
|
-
|
|
11862
|
-
if (
|
|
11863
|
-
|
|
11864
|
-
|
|
11865
|
-
|
|
11866
|
-
|
|
11867
|
-
|
|
11868
|
-
|
|
11869
|
-
|
|
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;
|
|
11870
12664
|
try {
|
|
11871
|
-
|
|
11872
|
-
} catch {
|
|
11873
|
-
|
|
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;
|
|
11874
12670
|
}
|
|
11875
|
-
if (
|
|
11876
|
-
|
|
11877
|
-
|
|
11878
|
-
|
|
11879
|
-
|
|
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
|
+
var display = (value) => value.replace(/[\x00-\x1f\x7f-\x9f]/g, "");
|
|
12692
|
+
async function selectModel(models, query = "", harness) {
|
|
12693
|
+
if (!process.stdin.isTTY || !process.stderr.isTTY)
|
|
12694
|
+
throw new Fault(400, "model_required", "Use --model MODEL in noninteractive mode. List available models with switcher models PROVIDER.");
|
|
12695
|
+
const eligible = models.filter((m) => harness ? harnessEligible(m, harness) : codingEligible(m));
|
|
12696
|
+
if (!eligible.length)
|
|
12697
|
+
throw new Fault(422, "model_missing", "This provider has no models eligible for coding in its current catalog.");
|
|
12698
|
+
const reader = createInterface2({ input: process.stdin, output: process.stderr });
|
|
12699
|
+
const cancellation = new AbortController;
|
|
12700
|
+
const cancel = () => cancellation.abort(new CommandInterrupted(130, "Model selection was cancelled; no harness was started."));
|
|
12701
|
+
const terminate = () => cancellation.abort(new CommandInterrupted(143, "Model selection was interrupted; no harness was started."));
|
|
12702
|
+
reader.on("SIGINT", cancel);
|
|
12703
|
+
reader.on("close", cancel);
|
|
12704
|
+
process.on("SIGINT", cancel);
|
|
12705
|
+
process.on("SIGTERM", terminate);
|
|
11880
12706
|
try {
|
|
11881
|
-
|
|
11882
|
-
|
|
11883
|
-
|
|
11884
|
-
|
|
11885
|
-
|
|
11886
|
-
|
|
11887
|
-
|
|
12707
|
+
for (;; ) {
|
|
12708
|
+
const matching = eligible.filter((m) => `${m.id} ${m.name}`.toLowerCase().includes(query.toLowerCase()));
|
|
12709
|
+
const visible = matching.slice(0, 30);
|
|
12710
|
+
console.error(`Models: ${matching.length} match${matching.length === 1 ? "" : "es"}${matching.length > 30 ? " (first 30 shown; type to narrow)" : ""}.`);
|
|
12711
|
+
visible.forEach((m, i) => console.error(` ${i + 1}. ${display(m.id)} \u2014 ${display(m.name)}${m.expiresOn ? ` (expires ${m.expiresOn}, inclusive UTC)` : ""}`));
|
|
12712
|
+
const answer = (await reader.question("Model number, exact model ID, or search text (Ctrl-C cancels): ", { signal: cancellation.signal }).catch((error) => {
|
|
12713
|
+
throw cancellation.signal.aborted ? cancellation.signal.reason : error;
|
|
12714
|
+
})).trim();
|
|
12715
|
+
if (/^[1-9]\d*$/.test(answer) && visible[Number(answer) - 1])
|
|
12716
|
+
return visible[Number(answer) - 1].id;
|
|
12717
|
+
if (eligible.some((m) => m.id === answer))
|
|
12718
|
+
return answer;
|
|
12719
|
+
query = answer;
|
|
12720
|
+
}
|
|
11888
12721
|
} finally {
|
|
11889
|
-
|
|
12722
|
+
reader.off("SIGINT", cancel);
|
|
12723
|
+
reader.off("close", cancel);
|
|
12724
|
+
process.off("SIGINT", cancel);
|
|
12725
|
+
process.off("SIGTERM", terminate);
|
|
12726
|
+
reader.close();
|
|
11890
12727
|
}
|
|
11891
12728
|
}
|
|
11892
|
-
async function
|
|
11893
|
-
const
|
|
11894
|
-
const
|
|
11895
|
-
const
|
|
11896
|
-
|
|
11897
|
-
|
|
11898
|
-
let url;
|
|
12729
|
+
async function ensureLaunchProfile(client, provider, harness, model3, modelPolicy) {
|
|
12730
|
+
const normalizedPolicy = modelPolicy === undefined ? undefined : parse2(modelPolicySchema, modelPolicy);
|
|
12731
|
+
const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
|
|
12732
|
+
const hash3 = createHash12("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
|
|
12733
|
+
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
|
|
12734
|
+
let existing;
|
|
11899
12735
|
try {
|
|
11900
|
-
|
|
11901
|
-
} catch {
|
|
11902
|
-
|
|
12736
|
+
existing = await client.getProfile(desired.id);
|
|
12737
|
+
} catch (error) {
|
|
12738
|
+
if (!absent(error))
|
|
12739
|
+
throw error;
|
|
11903
12740
|
}
|
|
11904
|
-
if (
|
|
11905
|
-
|
|
11906
|
-
|
|
11907
|
-
|
|
11908
|
-
|
|
11909
|
-
|
|
11910
|
-
|
|
11911
|
-
|
|
12741
|
+
if (!existing) {
|
|
12742
|
+
try {
|
|
12743
|
+
return await client.createProfile(desired);
|
|
12744
|
+
} catch (error) {
|
|
12745
|
+
if (!(error instanceof SwitcherError && error.status === 409))
|
|
12746
|
+
throw error;
|
|
12747
|
+
existing = await client.getProfile(desired.id);
|
|
12748
|
+
}
|
|
11912
12749
|
}
|
|
12750
|
+
if (existing.providerId !== desired.providerId || existing.harness !== harness || existing.model !== model3 || canonicalPolicyJSON(existing.modelPolicy ?? null) !== canonicalPolicyJSON(desired.modelPolicy ?? null))
|
|
12751
|
+
throw new Fault(409, "profile_conflict", "An existing launch profile has different settings. Select a saved profile explicitly.");
|
|
12752
|
+
return existing;
|
|
11913
12753
|
}
|
|
11914
12754
|
|
|
11915
12755
|
// src/cli.ts
|
|
@@ -11973,6 +12813,16 @@ Use --catalog-format none for a manual catalog; otherwise discovery stays active
|
|
|
11973
12813
|
models update replaces saved metadata; omit expiry in its JSON to clear it.
|
|
11974
12814
|
models remove removes saved metadata, not entries in an upstream catalog.
|
|
11975
12815
|
Credential bindings contain references only. Custom destinations require --origin URL.
|
|
12816
|
+
Before a real launch, Switcher resolves the provider credential and runs its
|
|
12817
|
+
declared safe authentication check before catalog refresh or a model picker. When no source exists in
|
|
12818
|
+
an interactive terminal, it searches Hasna Secrets metadata, displays the selected
|
|
12819
|
+
Secrets account/source and matching key references, and requires a selection.
|
|
12820
|
+
Auto-onboarded bindings refuse providers without a safe check; older explicit
|
|
12821
|
+
bindings remain compatible and are never validated by inferring catalog behavior.
|
|
12822
|
+
Noninteractive launches return credential_setup_required with exact binding syntax.
|
|
12823
|
+
Dry-runs do not bind, resolve, or authenticate provider credentials. Public and
|
|
12824
|
+
credentialless catalogs may refresh; authenticated catalogs use a saved snapshot
|
|
12825
|
+
and name the explicit refresh command when no snapshot exists.
|
|
11976
12826
|
Vault bindings use the installed secrets CLI and its canonical Contracts URL/key
|
|
11977
12827
|
by default. --vault-account pins a Keychain account; --vault-operator env requires
|
|
11978
12828
|
per-process HASNA_SECRETS_API_KEY. Explicit operators also require --vault-url.
|
|
@@ -12204,7 +13054,9 @@ async function main(args = process.argv.slice(2)) {
|
|
|
12204
13054
|
assertHarnessArguments(harness, nativeArgs);
|
|
12205
13055
|
await validateHarnessConfiguration(harness, values2.cwd ?? process.cwd(), nativeArgs);
|
|
12206
13056
|
}
|
|
12207
|
-
const
|
|
13057
|
+
const dryLaunch = command === "launch" && Boolean(values2["dry-run"]);
|
|
13058
|
+
const runtimeEnvironment = dryLaunch ? Object.fromEntries(Object.entries(process.env).filter(([name]) => !name.startsWith("SWITCHER_PROVIDER_"))) : process.env;
|
|
13059
|
+
const runtime = await openCliRuntime(runtimeEnvironment, dryLaunch ? undefined : (provider) => credentials.resolve(provider));
|
|
12208
13060
|
const client = runtime.client;
|
|
12209
13061
|
try {
|
|
12210
13062
|
const presetOptions = () => ({
|
|
@@ -12245,12 +13097,19 @@ async function main(args = process.argv.slice(2)) {
|
|
|
12245
13097
|
if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs <= 0))
|
|
12246
13098
|
throw new Error("--timeout must be positive seconds.");
|
|
12247
13099
|
let profileId = action2;
|
|
13100
|
+
let credentialPreflight;
|
|
13101
|
+
let resolvePreparedCredential;
|
|
12248
13102
|
if (values2.provider) {
|
|
12249
13103
|
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action2);
|
|
12250
13104
|
const modelPolicy = await readModelPolicy(values2["model-policy-file"], values2["role-model"]);
|
|
12251
13105
|
const provider = await resolveLaunchProvider(client, values2.provider, { ...presetOptions(), harness });
|
|
12252
13106
|
validateHarnessProvider(harness, provider);
|
|
12253
|
-
|
|
13107
|
+
if (!values2["dry-run"]) {
|
|
13108
|
+
const prepared = await ensureProviderCredential(provider, { resolver: credentials });
|
|
13109
|
+
credentialPreflight = prepared.providerFingerprint;
|
|
13110
|
+
resolvePreparedCredential = prepared.resolveCredential;
|
|
13111
|
+
}
|
|
13112
|
+
const catalog = await launchCatalog(client, provider, Boolean(values2["dry-run"]));
|
|
12254
13113
|
const model3 = values2.model ?? await selectModel(catalog.models, values2.search, harness);
|
|
12255
13114
|
const selected = catalog.models.find((m) => m.id === model3);
|
|
12256
13115
|
if (!selected)
|
|
@@ -12266,11 +13125,17 @@ async function main(args = process.argv.slice(2)) {
|
|
|
12266
13125
|
if (values2.model || values2.protocol || values2.url || values2["credential-env"] || values2["model-policy-file"] || values2["role-model"])
|
|
12267
13126
|
throw new Error("Use --provider PROVIDER for a direct launch, or update the saved profile explicitly.");
|
|
12268
13127
|
const profile = await client.getProfile(profileId);
|
|
12269
|
-
if (profile.harness === "gemini")
|
|
12270
|
-
validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
|
|
12271
13128
|
assertHarnessArguments(profile.harness, nativeArgs);
|
|
12272
13129
|
await validateHarnessConfiguration(profile.harness, values2.cwd ?? process.cwd(), nativeArgs);
|
|
12273
|
-
await client.
|
|
13130
|
+
const provider = await client.getProvider(profile.providerId);
|
|
13131
|
+
if (profile.harness === "gemini")
|
|
13132
|
+
validateHarnessProvider(profile.harness, provider);
|
|
13133
|
+
if (!values2["dry-run"]) {
|
|
13134
|
+
const prepared = await ensureProviderCredential(provider, { resolver: credentials });
|
|
13135
|
+
credentialPreflight = prepared.providerFingerprint;
|
|
13136
|
+
resolvePreparedCredential = prepared.resolveCredential;
|
|
13137
|
+
}
|
|
13138
|
+
await launchCatalog(client, provider, Boolean(values2["dry-run"]));
|
|
12274
13139
|
}
|
|
12275
13140
|
if (values2["dry-run"]) {
|
|
12276
13141
|
const plan = await client.launchPlan(profileId);
|
|
@@ -12289,7 +13154,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
12289
13154
|
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" } } : {} });
|
|
12290
13155
|
return;
|
|
12291
13156
|
}
|
|
12292
|
-
process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, resolveCredential: (provider) => credentials.resolve(provider) });
|
|
13157
|
+
process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, credentialPreflight, resolveCredential: resolvePreparedCredential ?? ((provider) => credentials.resolve(provider)) });
|
|
12293
13158
|
return;
|
|
12294
13159
|
}
|
|
12295
13160
|
if (editingModel) {
|