@hasna/switcher 0.2.1 → 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 +29 -4
- package/dist/cli/index.js +2044 -1664
- 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 +6 -1
- package/dist/launcher.d.ts +1 -0
- package/dist/mcp/index.js +99 -3
- package/dist/presets.d.ts +8 -0
- package/dist/sdk.d.ts +36 -0
- package/dist/sdk.js +6 -1
- package/dist/serve/index.js +99 -3
- package/openapi.json +93 -1
- package/package.json +1 -1
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(),
|
|
@@ -1090,7 +1094,7 @@ var providerPresets = [
|
|
|
1090
1094
|
route("openai-responses", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
1091
1095
|
route("anthropic-messages", "https://api.deepseek.com/anthropic/v1", { catalogBaseUrl: "https://api.deepseek.com" })
|
|
1092
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"),
|
|
1093
|
-
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"),
|
|
1094
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"),
|
|
1095
1099
|
preset("gemini", "Google Gemini", [route("gemini-generate-content", "https://generativelanguage.googleapis.com/v1beta", {
|
|
1096
1100
|
authStyle: "x-api-key",
|
|
@@ -1181,6 +1185,7 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
1181
1185
|
protocol: selected.protocol,
|
|
1182
1186
|
credentialEnv: options.credentialEnv ?? preset2.credentialEnv,
|
|
1183
1187
|
authStyle: options.authStyle ?? selected.authStyle,
|
|
1188
|
+
credentialCheck: selected.credentialCheck,
|
|
1184
1189
|
catalogBaseUrl,
|
|
1185
1190
|
catalogCredentialEnv: options.catalogCredentialEnv,
|
|
1186
1191
|
catalogAuthStyle: options.catalogAuthStyle ?? selected.catalogAuthStyle,
|
|
@@ -2380,7 +2385,7 @@ var openapi_default = {
|
|
|
2380
2385
|
openapi: "3.0.3",
|
|
2381
2386
|
info: {
|
|
2382
2387
|
title: "Switcher API",
|
|
2383
|
-
version: "0.2.
|
|
2388
|
+
version: "0.2.2",
|
|
2384
2389
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2385
2390
|
},
|
|
2386
2391
|
security: [
|
|
@@ -3610,6 +3615,29 @@ var openapi_default = {
|
|
|
3610
3615
|
"api-key"
|
|
3611
3616
|
]
|
|
3612
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
|
+
},
|
|
3613
3641
|
catalogBaseUrl: {
|
|
3614
3642
|
type: "string",
|
|
3615
3643
|
maxLength: 2000
|
|
@@ -3719,6 +3747,29 @@ var openapi_default = {
|
|
|
3719
3747
|
],
|
|
3720
3748
|
default: "bearer"
|
|
3721
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
|
+
},
|
|
3722
3773
|
catalogBaseUrl: {
|
|
3723
3774
|
type: "string",
|
|
3724
3775
|
maxLength: 2000
|
|
@@ -3997,6 +4048,29 @@ var openapi_default = {
|
|
|
3997
4048
|
],
|
|
3998
4049
|
default: "bearer"
|
|
3999
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
|
+
},
|
|
4000
4074
|
catalogBaseUrl: {
|
|
4001
4075
|
type: "string",
|
|
4002
4076
|
maxLength: 2000
|
|
@@ -5119,6 +5193,29 @@ var openapi_default = {
|
|
|
5119
5193
|
],
|
|
5120
5194
|
default: "bearer"
|
|
5121
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
|
+
},
|
|
5122
5219
|
catalogBaseUrl: {
|
|
5123
5220
|
type: "string",
|
|
5124
5221
|
maxLength: 2000
|
|
@@ -10617,1784 +10714,2042 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
|
|
|
10617
10714
|
|
|
10618
10715
|
// src/launcher.ts
|
|
10619
10716
|
import { mkdir as mkdir11, mkdtemp, rm as rm6, writeFile as writeFile14 } from "fs/promises";
|
|
10620
|
-
import { join as
|
|
10717
|
+
import { join as join16, resolve as resolve9 } from "path";
|
|
10621
10718
|
|
|
10622
|
-
// src/
|
|
10623
|
-
import {
|
|
10624
|
-
import {
|
|
10625
|
-
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");
|
|
10626
10760
|
|
|
10627
|
-
|
|
10628
|
-
|
|
10629
|
-
|
|
10630
|
-
|
|
10631
|
-
|
|
10632
|
-
|
|
10633
|
-
const handle = dlopen(library, { dup: { args: ["int"], returns: "int" } });
|
|
10634
|
-
return { duplicate(fd) {
|
|
10635
|
-
const copy = handle.symbols.dup(fd);
|
|
10636
|
-
if (copy < 3)
|
|
10637
|
-
throw new Error("A redirected terminal descriptor could not be duplicated.");
|
|
10638
|
-
return copy;
|
|
10639
|
-
}, close: () => handle.close() };
|
|
10640
|
-
} 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");
|
|
10641
10767
|
}
|
|
10642
|
-
|
|
10643
|
-
|
|
10644
|
-
|
|
10645
|
-
|
|
10646
|
-
|
|
10647
|
-
|
|
10648
|
-
const grouped = process.platform !== "win32", interactive = !options.silent && grouped && tty.some(Boolean);
|
|
10649
|
-
const redirects = interactive ? tty.flatMap((value, index) => value ? [] : [index]) : [];
|
|
10650
|
-
const duplicator = redirects.length ? await terminalDescriptorDuplicator() : undefined;
|
|
10651
|
-
return new Promise((resolveResult, reject2) => {
|
|
10652
|
-
const wasRaw = process.stdin.isRaw, wasFlowing = process.stdin.readableFlowing;
|
|
10653
|
-
let controllingInput;
|
|
10654
|
-
let inputTimer;
|
|
10655
|
-
let terminalFailure;
|
|
10656
|
-
let terminal;
|
|
10657
|
-
let terminalMode;
|
|
10658
|
-
let controllingOutput;
|
|
10659
|
-
const output = tty[1] ? process.stdout : tty[2] ? process.stderr : undefined;
|
|
10660
|
-
const stty = (args) => {
|
|
10661
|
-
const descriptor = openSync("/dev/tty", "r+");
|
|
10662
|
-
try {
|
|
10663
|
-
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 });
|
|
10664
|
-
if (result.status !== 0)
|
|
10665
|
-
throw new Error("Terminal mode could not be configured.");
|
|
10666
|
-
return result.stdout.trim();
|
|
10667
|
-
} finally {
|
|
10668
|
-
closeSync(descriptor);
|
|
10669
|
-
}
|
|
10670
|
-
};
|
|
10671
|
-
let relay;
|
|
10672
|
-
let resize;
|
|
10673
|
-
const child = (() => {
|
|
10674
|
-
if (!interactive)
|
|
10675
|
-
return spawn(options.executable, options.args, { cwd: options.cwd, env: options.env, stdio: options.silent ? "ignore" : "inherit", shell: false, detached: grouped });
|
|
10676
|
-
const duplicates = [];
|
|
10677
|
-
let native;
|
|
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;
|
|
10678
10774
|
try {
|
|
10679
|
-
|
|
10680
|
-
controllingOutput = openSync("/dev/tty", "w");
|
|
10681
|
-
const [rows, cols] = stty(["size"]).split(/\s+/).map(Number);
|
|
10682
|
-
for (const fd of redirects)
|
|
10683
|
-
duplicates.push(duplicator.duplicate(fd));
|
|
10684
|
-
const script = redirects.map((fd, index) => `exec ${fd}${fd === 0 ? "<&" : ">&"}${index + 3};`).join(" ") + " " + redirects.map((_, index) => `exec ${index + 3}<&-;`).join(" ") + ' exec "$@"';
|
|
10685
|
-
const command = redirects.length ? ["/bin/sh", "-c", script, "switcher-native", options.executable, ...options.args] : [options.executable, ...options.args];
|
|
10686
|
-
native = Bun.spawn(command, {
|
|
10687
|
-
cwd: options.cwd,
|
|
10688
|
-
env: options.env,
|
|
10689
|
-
stdio: ["inherit", "inherit", "inherit", ...duplicates],
|
|
10690
|
-
terminal: { cols, rows, name: options.env.TERM ?? "xterm-256color", data(_terminal, data2) {
|
|
10691
|
-
try {
|
|
10692
|
-
if (output)
|
|
10693
|
-
output.write(data2);
|
|
10694
|
-
else if (controllingOutput !== undefined)
|
|
10695
|
-
writeSync(controllingOutput, data2);
|
|
10696
|
-
} catch {
|
|
10697
|
-
failTerminal();
|
|
10698
|
-
}
|
|
10699
|
-
} }
|
|
10700
|
-
});
|
|
10775
|
+
info = await lstat4(path);
|
|
10701
10776
|
} catch (error) {
|
|
10702
|
-
if (
|
|
10703
|
-
|
|
10704
|
-
controllingOutput = undefined;
|
|
10705
|
-
}
|
|
10777
|
+
if (error.code === "ENOENT")
|
|
10778
|
+
return false;
|
|
10706
10779
|
throw error;
|
|
10707
|
-
} finally {
|
|
10708
|
-
for (const fd of duplicates)
|
|
10709
|
-
closeSync(fd);
|
|
10710
|
-
duplicator?.close();
|
|
10711
10780
|
}
|
|
10712
|
-
|
|
10713
|
-
|
|
10714
|
-
|
|
10715
|
-
|
|
10716
|
-
|
|
10717
|
-
|
|
10718
|
-
|
|
10719
|
-
|
|
10720
|
-
|
|
10721
|
-
|
|
10722
|
-
|
|
10723
|
-
|
|
10724
|
-
|
|
10725
|
-
|
|
10726
|
-
} catch {
|
|
10727
|
-
failTerminal();
|
|
10728
|
-
}
|
|
10729
|
-
};
|
|
10730
|
-
return events;
|
|
10731
|
-
})();
|
|
10732
|
-
let interrupted = false;
|
|
10733
|
-
let interruptionExitCode;
|
|
10734
|
-
let killTimer;
|
|
10735
|
-
const signalGroup = (signal) => {
|
|
10736
|
-
if (!child.pid)
|
|
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")
|
|
10737
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;
|
|
10738
10803
|
try {
|
|
10739
|
-
|
|
10740
|
-
process.kill(-child.pid, signal);
|
|
10741
|
-
else
|
|
10742
|
-
child.kill(signal);
|
|
10743
|
-
} catch (error) {
|
|
10744
|
-
if (error.code !== "ESRCH")
|
|
10745
|
-
console.error("switcher: Could not signal an owned harness process.");
|
|
10746
|
-
}
|
|
10747
|
-
};
|
|
10748
|
-
const groupExists = () => {
|
|
10749
|
-
if (!grouped || !child.pid)
|
|
10750
|
-
return false;
|
|
10751
|
-
try {
|
|
10752
|
-
process.kill(-child.pid, 0);
|
|
10753
|
-
return true;
|
|
10804
|
+
value = JSON.parse(await file.readFile("utf8"));
|
|
10754
10805
|
} catch {
|
|
10755
|
-
|
|
10806
|
+
throw new Fault(500, "credential_binding_invalid", "Credential binding must contain valid JSON.");
|
|
10756
10807
|
}
|
|
10757
|
-
|
|
10758
|
-
|
|
10759
|
-
|
|
10760
|
-
|
|
10761
|
-
|
|
10762
|
-
|
|
10763
|
-
}
|
|
10764
|
-
|
|
10765
|
-
|
|
10766
|
-
|
|
10767
|
-
|
|
10768
|
-
|
|
10769
|
-
|
|
10770
|
-
|
|
10771
|
-
|
|
10772
|
-
|
|
10773
|
-
|
|
10774
|
-
|
|
10775
|
-
|
|
10776
|
-
|
|
10777
|
-
|
|
10778
|
-
|
|
10779
|
-
|
|
10780
|
-
|
|
10781
|
-
|
|
10782
|
-
const cleanup = () => {
|
|
10783
|
-
if (cleaned)
|
|
10784
|
-
return;
|
|
10785
|
-
cleaned = true;
|
|
10786
|
-
let failed = false;
|
|
10787
|
-
const attempt = (operation) => {
|
|
10788
|
-
try {
|
|
10789
|
-
operation();
|
|
10790
|
-
} catch {
|
|
10791
|
-
failed = true;
|
|
10792
|
-
}
|
|
10793
|
-
};
|
|
10794
|
-
attempt(() => {
|
|
10795
|
-
process.off("SIGINT", onInt);
|
|
10796
|
-
process.off("SIGTERM", onTerm);
|
|
10797
|
-
process.off("SIGHUP", onHangup);
|
|
10798
|
-
process.off("SIGWINCH", onResize);
|
|
10799
|
-
});
|
|
10800
|
-
if (timeout)
|
|
10801
|
-
clearTimeout(timeout);
|
|
10802
|
-
if (killTimer)
|
|
10803
|
-
clearTimeout(killTimer);
|
|
10804
|
-
if (relay)
|
|
10805
|
-
attempt(() => {
|
|
10806
|
-
process.stdin.off("data", relay);
|
|
10807
|
-
});
|
|
10808
|
-
attempt(() => {
|
|
10809
|
-
process.stdin.off("error", failTerminal);
|
|
10810
|
-
output?.off("error", failTerminal);
|
|
10811
|
-
});
|
|
10812
|
-
if (resize)
|
|
10813
|
-
attempt(() => {
|
|
10814
|
-
output?.off("resize", resize);
|
|
10815
|
-
});
|
|
10816
|
-
if (interactive) {
|
|
10817
|
-
if (tty[0])
|
|
10818
|
-
attempt(() => {
|
|
10819
|
-
process.stdin.setRawMode(wasRaw);
|
|
10820
|
-
});
|
|
10821
|
-
if (terminalMode)
|
|
10822
|
-
attempt(() => {
|
|
10823
|
-
stty([terminalMode]);
|
|
10824
|
-
});
|
|
10825
|
-
if (tty[0] && wasFlowing !== true)
|
|
10826
|
-
attempt(() => {
|
|
10827
|
-
process.stdin.pause();
|
|
10828
|
-
});
|
|
10829
|
-
}
|
|
10830
|
-
if (inputTimer)
|
|
10831
|
-
clearInterval(inputTimer);
|
|
10832
|
-
if (controllingInput !== undefined)
|
|
10833
|
-
attempt(() => {
|
|
10834
|
-
closeSync(controllingInput);
|
|
10835
|
-
controllingInput = undefined;
|
|
10836
|
-
});
|
|
10837
|
-
attempt(() => {
|
|
10838
|
-
terminal?.close();
|
|
10839
|
-
});
|
|
10840
|
-
if (controllingOutput !== undefined)
|
|
10841
|
-
attempt(() => {
|
|
10842
|
-
closeSync(controllingOutput);
|
|
10843
|
-
controllingOutput = undefined;
|
|
10844
|
-
});
|
|
10845
|
-
if (failed)
|
|
10846
|
-
console.error("switcher: Terminal restoration was incomplete; the owned harness has stopped.");
|
|
10847
|
-
};
|
|
10848
|
-
child.once("error", () => {
|
|
10849
|
-
cleanup();
|
|
10850
|
-
reject2(new Error("Harness process could not start; check executable and permissions."));
|
|
10851
|
-
});
|
|
10852
|
-
child.once("exit", async (code, signal) => {
|
|
10853
|
-
if (timeout)
|
|
10854
|
-
clearTimeout(timeout);
|
|
10855
|
-
if (groupExists()) {
|
|
10856
|
-
signalGroup("SIGTERM");
|
|
10857
|
-
const deadline = Date.now() + 5000;
|
|
10858
|
-
while (groupExists() && Date.now() < deadline)
|
|
10859
|
-
await new Promise((resolve9) => setTimeout(resolve9, 25));
|
|
10860
|
-
if (groupExists())
|
|
10861
|
-
signalGroup("SIGKILL");
|
|
10862
|
-
}
|
|
10863
|
-
cleanup();
|
|
10864
|
-
if (terminalFailure) {
|
|
10865
|
-
reject2(terminalFailure);
|
|
10866
|
-
return;
|
|
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);
|
|
10867
10833
|
}
|
|
10868
|
-
|
|
10869
|
-
|
|
10870
|
-
|
|
10871
|
-
|
|
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();
|
|
10872
10849
|
try {
|
|
10873
|
-
|
|
10874
|
-
|
|
10875
|
-
if (
|
|
10876
|
-
|
|
10877
|
-
|
|
10878
|
-
|
|
10879
|
-
|
|
10880
|
-
|
|
10881
|
-
controllingInput = openSync("/dev/tty", constants5.O_RDONLY | constants5.O_NONBLOCK);
|
|
10882
|
-
stty(["raw", "-echo"]);
|
|
10883
|
-
const buffer = Buffer.alloc(4096);
|
|
10884
|
-
inputTimer = setInterval(() => {
|
|
10885
|
-
try {
|
|
10886
|
-
for (let bytes = 0;bytes < 65536; ) {
|
|
10887
|
-
const count = readSync(controllingInput, buffer);
|
|
10888
|
-
if (!count) {
|
|
10889
|
-
failTerminal();
|
|
10890
|
-
break;
|
|
10891
|
-
}
|
|
10892
|
-
terminal?.write(buffer.subarray(0, count));
|
|
10893
|
-
bytes += count;
|
|
10894
|
-
}
|
|
10895
|
-
} catch (error) {
|
|
10896
|
-
if (!["EAGAIN", "EWOULDBLOCK", "EINTR"].includes(error.code ?? ""))
|
|
10897
|
-
failTerminal();
|
|
10898
|
-
}
|
|
10899
|
-
}, 16);
|
|
10900
|
-
}
|
|
10901
|
-
stty(["-opost"]);
|
|
10902
|
-
output?.on("resize", resize);
|
|
10903
|
-
} catch {
|
|
10904
|
-
terminalFailure = new Error("The native terminal could not be initialized; the owned harness was stopped.");
|
|
10905
|
-
signalGroup("SIGKILL");
|
|
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.");
|
|
10906
10858
|
}
|
|
10859
|
+
} finally {
|
|
10860
|
+
await file.close();
|
|
10861
|
+
await unlink(temporary);
|
|
10907
10862
|
}
|
|
10908
|
-
|
|
10909
|
-
}
|
|
10910
|
-
|
|
10911
|
-
// src/ori-backend.ts
|
|
10912
|
-
import { execFile as execFile3 } from "child_process";
|
|
10913
|
-
import { promisify as promisify3 } from "util";
|
|
10914
|
-
var exec = promisify3(execFile3);
|
|
10915
|
-
var oriProviderCatalog = Object.freeze([{
|
|
10916
|
-
id: "openrouter",
|
|
10917
|
-
displayName: "OpenRouter",
|
|
10918
|
-
credentialEnv: "OPENROUTER_API_KEY",
|
|
10919
|
-
publicModelsUrl: "https://openrouter.ai/api/v1/models",
|
|
10920
|
-
entitledModelsUrl: "https://openrouter.ai/api/v1/models/user",
|
|
10921
|
-
protocols: ["anthropic-messages", "openai-responses", "openai-chat"]
|
|
10922
|
-
}]);
|
|
10923
|
-
var oriNativeFlags = Object.freeze({
|
|
10924
|
-
claude: ["--model", "--reasoning-effort"],
|
|
10925
|
-
codex: ["--model", "--reasoning-effort"],
|
|
10926
|
-
grok: ["--model", "--reasoning-effort"]
|
|
10927
|
-
});
|
|
10928
|
-
|
|
10929
|
-
class OriBackendError extends Error {
|
|
10930
|
-
code;
|
|
10931
|
-
constructor(code, message) {
|
|
10932
|
-
super(message);
|
|
10933
|
-
this.code = code;
|
|
10934
|
-
this.name = "OriBackendError";
|
|
10863
|
+
return binding;
|
|
10935
10864
|
}
|
|
10936
|
-
|
|
10937
|
-
|
|
10938
|
-
|
|
10939
|
-
|
|
10940
|
-
|
|
10941
|
-
|
|
10942
|
-
"SHELL",
|
|
10943
|
-
"TMPDIR",
|
|
10944
|
-
"TEMP",
|
|
10945
|
-
"TMP",
|
|
10946
|
-
"TERM",
|
|
10947
|
-
"COLORTERM",
|
|
10948
|
-
"LANG",
|
|
10949
|
-
"LC_ALL",
|
|
10950
|
-
"LC_CTYPE",
|
|
10951
|
-
"LC_MESSAGES",
|
|
10952
|
-
"XDG_CONFIG_HOME",
|
|
10953
|
-
"XDG_DATA_HOME",
|
|
10954
|
-
"XDG_STATE_HOME",
|
|
10955
|
-
"XDG_CACHE_HOME",
|
|
10956
|
-
"SSH_AUTH_SOCK",
|
|
10957
|
-
"GIT_SSH_COMMAND",
|
|
10958
|
-
"EDITOR",
|
|
10959
|
-
"VISUAL",
|
|
10960
|
-
"NO_COLOR",
|
|
10961
|
-
"FORCE_COLOR",
|
|
10962
|
-
"CODEX_HOME",
|
|
10963
|
-
"CLAUDE_CONFIG_DIR",
|
|
10964
|
-
"OPENROUTER_API_KEY"
|
|
10965
|
-
]);
|
|
10966
|
-
function safeEnvironment(environment) {
|
|
10967
|
-
const result = {};
|
|
10968
|
-
for (const [name, value] of Object.entries(environment)) {
|
|
10969
|
-
if (safeEnvironmentNames.has(name) && value !== undefined)
|
|
10970
|
-
result[name] = value;
|
|
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 };
|
|
10971
10871
|
}
|
|
10972
|
-
result.ORI_FORCE_OPENROUTER_API_KEY = "1";
|
|
10973
|
-
return result;
|
|
10974
10872
|
}
|
|
10975
|
-
function
|
|
10976
|
-
const
|
|
10977
|
-
if (
|
|
10978
|
-
throw new
|
|
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);
|
|
10979
10878
|
}
|
|
10980
|
-
function
|
|
10981
|
-
|
|
10982
|
-
const value = JSON.parse(stdout);
|
|
10983
|
-
if (typeof value.data?.version === "string")
|
|
10984
|
-
return value.data.version;
|
|
10985
|
-
} catch {}
|
|
10986
|
-
const match = stdout.match(/(?:@ori-runtime\/cli\s+|ori\s+v?)(\d+\.\d+\.\d+(?:[+.-][A-Za-z0-9.-]+)?)/i);
|
|
10987
|
-
return match?.[1];
|
|
10988
|
-
}
|
|
10989
|
-
function parseHarnesses(stdout) {
|
|
10990
|
-
let value;
|
|
10879
|
+
async function inspectVaultExecutable(path, permitWritableFile = false) {
|
|
10880
|
+
let info, resolved;
|
|
10991
10881
|
try {
|
|
10992
|
-
|
|
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;
|
|
10993
10887
|
} catch {
|
|
10994
|
-
throw new
|
|
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.");
|
|
10995
10889
|
}
|
|
10996
|
-
|
|
10997
|
-
|
|
10998
|
-
|
|
10999
|
-
|
|
11000
|
-
|
|
11001
|
-
|
|
11002
|
-
|
|
11003
|
-
|
|
11004
|
-
|
|
11005
|
-
|
|
11006
|
-
|
|
11007
|
-
|
|
11008
|
-
|
|
11009
|
-
|
|
11010
|
-
|
|
11011
|
-
|
|
11012
|
-
|
|
11013
|
-
|
|
11014
|
-
|
|
11015
|
-
|
|
11016
|
-
|
|
11017
|
-
|
|
11018
|
-
|
|
11019
|
-
|
|
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
|
+
}
|
|
11020
10921
|
}
|
|
10922
|
+
return resolved;
|
|
11021
10923
|
}
|
|
11022
|
-
async function
|
|
11023
|
-
|
|
11024
|
-
const environment = options.environment ?? process.env;
|
|
11025
|
-
const versionResult = await readOnly(executable, ["--version"], environment, options.cwd);
|
|
11026
|
-
if (versionResult.code !== 0)
|
|
11027
|
-
throw new OriBackendError("ori_unavailable", "Ori could not report its version; install it or pass an explicit executable.");
|
|
11028
|
-
const version = parseVersion(versionResult.stdout);
|
|
11029
|
-
if (!version)
|
|
11030
|
-
throw new OriBackendError("invalid_contract", "Ori --version did not report a version.");
|
|
11031
|
-
const inventoryResult = await readOnly(executable, ["harness", "list", "--json"], environment, options.cwd);
|
|
11032
|
-
if (inventoryResult.code !== 0)
|
|
11033
|
-
throw new OriBackendError("ori_unavailable", "Ori could not report its harness inventory.");
|
|
11034
|
-
return { executable, version, harnesses: parseHarnesses(inventoryResult.stdout) };
|
|
11035
|
-
}
|
|
11036
|
-
function assertSupportedOriVersion(contract) {
|
|
11037
|
-
if (!/^0\.12\./.test(contract.version))
|
|
11038
|
-
throw new OriBackendError("ori_version_unsupported", `Ori ${contract.version} is outside the verified 0.12.x adapter contract.`);
|
|
10924
|
+
async function validateVaultExecutable(path) {
|
|
10925
|
+
return inspectVaultExecutable(path);
|
|
11039
10926
|
}
|
|
11040
|
-
function
|
|
11041
|
-
|
|
11042
|
-
|
|
11043
|
-
|
|
11044
|
-
|
|
11045
|
-
|
|
11046
|
-
|
|
11047
|
-
|
|
11048
|
-
|
|
11049
|
-
|
|
11050
|
-
|
|
11051
|
-
|
|
11052
|
-
|
|
11053
|
-
|
|
11054
|
-
|
|
11055
|
-
|
|
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
|
+
}
|
|
11056
11005
|
}
|
|
11057
|
-
function
|
|
11058
|
-
|
|
11059
|
-
|
|
11060
|
-
|
|
11061
|
-
|
|
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 };
|
|
11062
11022
|
}
|
|
11063
|
-
function
|
|
11064
|
-
|
|
11065
|
-
|
|
11066
|
-
|
|
11067
|
-
throw new OriBackendError("provider_authority", "Ori requires an explicit OpenRouter provider URL and a protocol supported by the selected Ori target.");
|
|
11068
|
-
let url;
|
|
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;
|
|
11069
11027
|
try {
|
|
11070
|
-
|
|
11071
|
-
} catch {
|
|
11072
|
-
|
|
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.`);
|
|
11073
11034
|
}
|
|
11074
|
-
const
|
|
11075
|
-
if (
|
|
11076
|
-
throw new
|
|
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;
|
|
11077
11039
|
}
|
|
11078
|
-
|
|
11079
|
-
|
|
11080
|
-
|
|
11081
|
-
|
|
11082
|
-
|
|
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" };
|
|
11083
11079
|
}
|
|
11084
11080
|
}
|
|
11085
|
-
|
|
11086
|
-
|
|
11087
|
-
|
|
11088
|
-
|
|
11089
|
-
|
|
11090
|
-
|
|
11091
|
-
|
|
11092
|
-
if (request.target === "pi" || request.target === "aider")
|
|
11093
|
-
throw new OriBackendError("unsupported_harness", "Pi is supported through the direct Switcher adapter; the Ori preservation subset supports Codex and Grok only.");
|
|
11094
|
-
assertProviderAuthority(request.target, request.provider, request.providerBaseUrl, request.protocol);
|
|
11095
|
-
if (!request.model.trim())
|
|
11096
|
-
throw new OriBackendError("model_required", "An OpenRouter model ID is required for an Ori launch.");
|
|
11097
|
-
assertPassthrough(request.target, request.args ?? []);
|
|
11098
|
-
if (request.target === "opencode2")
|
|
11099
|
-
throw new OriBackendError("unsupported_harness", "Ori 0.12.1 targets legacy `opencode`; it cannot launch OpenCode 2 (`opencode2`).");
|
|
11100
|
-
if (request.target === "claude")
|
|
11101
|
-
throw new OriBackendError("global_config_mutation", "Ori Claude launches may update ~/.claude.json; the preservation subset supports Codex and Grok only.");
|
|
11102
|
-
if (request.target === "grok" && request.protocol !== "openai-chat")
|
|
11103
|
-
throw new OriBackendError("unsupported_protocol", "Ori Grok is verified only for OpenAI Chat; use the direct adapter for Messages or Responses.");
|
|
11104
|
-
const catalog = request.catalog;
|
|
11105
|
-
if (!catalog || catalog.source !== "switcher-openrouter" || !catalog.modelIds.includes(request.model))
|
|
11106
|
-
throw new OriBackendError("catalog_required", "The selected model must come from Switcher's OpenRouter catalog before an Ori launch.");
|
|
11107
|
-
}
|
|
11108
|
-
function prepareOriLaunch(request) {
|
|
11109
|
-
validateOriLaunchRequest(request);
|
|
11110
|
-
const args = request.args ?? [];
|
|
11111
|
-
const environment = request.environment ?? process.env;
|
|
11112
|
-
assertOriLoginAllowed(environment);
|
|
11113
|
-
const credential = environment.OPENROUTER_API_KEY?.trim();
|
|
11114
|
-
if (!credential)
|
|
11115
|
-
throw new OriBackendError("openrouter_key_missing", "An OpenRouter API key must be supplied in the launch environment before starting Ori.");
|
|
11116
|
-
if (/[\r\n]/.test(credential))
|
|
11117
|
-
throw new OriBackendError("openrouter_key_invalid", "The OpenRouter API key contains invalid characters.");
|
|
11118
|
-
const oriArgs = [request.target, "--model", request.model];
|
|
11119
|
-
if (request.target === "grok") {
|
|
11120
|
-
validateGrokResume(args);
|
|
11121
|
-
oriArgs.splice(1, 0, "--no-leader");
|
|
11122
|
-
}
|
|
11123
|
-
if (request.reasoningEffort)
|
|
11124
|
-
oriArgs.push("--reasoning-effort", request.reasoningEffort);
|
|
11125
|
-
if (request.target === "codex" && request.catalog?.codexModelCatalogPath) {
|
|
11126
|
-
const path = request.catalog.codexModelCatalogPath;
|
|
11127
|
-
if (!path.startsWith("/") || /[\r\n\0]/.test(path))
|
|
11128
|
-
throw new OriBackendError("catalog_path_invalid", "The Switcher Codex catalog path must be an absolute safe path.");
|
|
11129
|
-
oriArgs.push("-c", `model_catalog_json=${JSON.stringify(path)}`);
|
|
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.");
|
|
11130
11088
|
}
|
|
11131
|
-
oriArgs.push(...args);
|
|
11132
|
-
return {
|
|
11133
|
-
executable: request.executable ?? "ori",
|
|
11134
|
-
args: oriArgs,
|
|
11135
|
-
env: safeEnvironment(environment),
|
|
11136
|
-
target: request.target,
|
|
11137
|
-
provider: "openrouter",
|
|
11138
|
-
model: request.model,
|
|
11139
|
-
warnings: oriLaunchWarnings(request.target)
|
|
11140
|
-
};
|
|
11141
|
-
}
|
|
11142
|
-
function oriLaunchWarnings(target) {
|
|
11143
|
-
return target === "grok" ? ["Ori supplies Grok's account-entitled OpenRouter catalog; it is not the Switcher-filtered catalog snapshot."] : [];
|
|
11144
11089
|
}
|
|
11145
|
-
|
|
11146
|
-
|
|
11147
|
-
|
|
11148
|
-
|
|
11149
|
-
|
|
11150
|
-
|
|
11151
|
-
// src/desktop-state.ts
|
|
11152
|
-
import { Database as Database3 } from "bun:sqlite";
|
|
11153
|
-
import { readFile as readFile5, writeFile as writeFile11, rm as rm3, lstat as lstat4, rename as rename2, chmod as chmod2 } from "fs/promises";
|
|
11154
|
-
async function safeDesktopRead(path) {
|
|
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;
|
|
11155
11095
|
try {
|
|
11156
|
-
|
|
11157
|
-
|
|
11158
|
-
|
|
11159
|
-
|
|
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
|
+
}
|
|
11160
11123
|
} catch (error) {
|
|
11161
|
-
if (error
|
|
11162
|
-
|
|
11163
|
-
|
|
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.`);
|
|
11164
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 };
|
|
11165
11141
|
}
|
|
11166
|
-
async function
|
|
11167
|
-
|
|
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
|
+
} });
|
|
11168
11227
|
try {
|
|
11169
|
-
await
|
|
11170
|
-
|
|
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;
|
|
11171
11235
|
} finally {
|
|
11172
|
-
await
|
|
11236
|
+
await broker.stop(true);
|
|
11173
11237
|
}
|
|
11174
11238
|
}
|
|
11175
|
-
|
|
11176
|
-
|
|
11177
|
-
|
|
11178
|
-
|
|
11179
|
-
|
|
11180
|
-
|
|
11181
|
-
|
|
11182
|
-
|
|
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.");
|
|
11183
11299
|
}
|
|
11184
|
-
|
|
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);
|
|
11185
11316
|
try {
|
|
11186
|
-
|
|
11187
|
-
|
|
11188
|
-
|
|
11189
|
-
|
|
11190
|
-
|
|
11191
|
-
|
|
11192
|
-
|
|
11193
|
-
|
|
11194
|
-
|
|
11195
|
-
closed = true;
|
|
11196
|
-
lease.close();
|
|
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.`);
|
|
11197
11326
|
}
|
|
11198
|
-
}
|
|
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
|
+
}
|
|
11199
11334
|
}
|
|
11200
|
-
|
|
11201
|
-
|
|
11202
|
-
|
|
11203
|
-
|
|
11204
|
-
|
|
11205
|
-
|
|
11206
|
-
|
|
11207
|
-
|
|
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;
|
|
11208
11347
|
}
|
|
11209
|
-
|
|
11210
|
-
|
|
11211
|
-
|
|
11212
|
-
|
|
11213
|
-
const
|
|
11214
|
-
|
|
11215
|
-
|
|
11216
|
-
|
|
11217
|
-
|
|
11218
|
-
|
|
11219
|
-
const cleanup = async () => {
|
|
11220
|
-
if (released)
|
|
11221
|
-
return;
|
|
11222
|
-
released = true;
|
|
11223
|
-
try {
|
|
11224
|
-
if (authText !== undefined && await safeDesktopRead(authPath) === authText) {
|
|
11225
|
-
await rm4(authPath, { force: true });
|
|
11226
|
-
await rm4(receiptPath, { force: true });
|
|
11227
|
-
}
|
|
11228
|
-
} finally {
|
|
11229
|
-
release();
|
|
11230
|
-
}
|
|
11231
|
-
};
|
|
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;
|
|
11232
11358
|
try {
|
|
11233
|
-
|
|
11234
|
-
|
|
11235
|
-
|
|
11236
|
-
|
|
11237
|
-
|
|
11238
|
-
|
|
11239
|
-
|
|
11240
|
-
|
|
11241
|
-
|
|
11242
|
-
|
|
11243
|
-
|
|
11244
|
-
|
|
11245
|
-
|
|
11246
|
-
|
|
11247
|
-
|
|
11248
|
-
|
|
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;
|
|
11249
11407
|
try {
|
|
11250
|
-
|
|
11408
|
+
matches = await discover2({ provider, credentialEnv: provider.credentialEnv });
|
|
11251
11409
|
} catch (error) {
|
|
11252
|
-
if (error.code
|
|
11253
|
-
throw new Fault(
|
|
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;
|
|
11254
11413
|
}
|
|
11255
|
-
|
|
11256
|
-
`))
|
|
11257
|
-
|
|
11258
|
-
const
|
|
11259
|
-
if (!
|
|
11260
|
-
throw new
|
|
11261
|
-
|
|
11262
|
-
|
|
11263
|
-
|
|
11264
|
-
|
|
11265
|
-
|
|
11266
|
-
|
|
11267
|
-
await
|
|
11268
|
-
|
|
11269
|
-
|
|
11270
|
-
export CODEX_HOME=${quote2(home)}
|
|
11271
|
-
if [ "\${1-}" = sandbox ]; then
|
|
11272
|
-
exec ${quote2(app.codexExecutable)} "$@"
|
|
11273
|
-
fi
|
|
11274
|
-
exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
|
|
11275
|
-
`, { mode: 448, flag: "wx" });
|
|
11276
|
-
return {
|
|
11277
|
-
...native,
|
|
11278
|
-
executable: app.executable,
|
|
11279
|
-
args: [`--user-data-dir=${userData}`],
|
|
11280
|
-
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" },
|
|
11281
|
-
configPaths: [...native.configPaths, configPath, wrapper],
|
|
11282
|
-
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.`],
|
|
11283
|
-
cleanup: async () => {
|
|
11284
|
-
try {
|
|
11285
|
-
await native.cleanup?.();
|
|
11286
|
-
} finally {
|
|
11287
|
-
await cleanup();
|
|
11288
|
-
}
|
|
11289
|
-
}
|
|
11290
|
-
};
|
|
11291
|
-
} catch (error) {
|
|
11292
|
-
await cleanup();
|
|
11293
|
-
throw error;
|
|
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.");
|
|
11294
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 });
|
|
11295
11440
|
}
|
|
11296
|
-
|
|
11297
|
-
|
|
11298
|
-
|
|
11299
|
-
|
|
11300
|
-
|
|
11301
|
-
|
|
11302
|
-
|
|
11303
|
-
import { promisify as promisify4 } from "util";
|
|
11304
|
-
var execute3 = promisify4(execFile4);
|
|
11305
|
-
var hash2 = (text) => createHash10("sha256").update(text).digest("hex");
|
|
11306
|
-
var claudeDesktopDataDirectory = () => join14(homedir8(), "Library/Application Support/Claude-3p");
|
|
11307
|
-
async function assertAvailable(userData) {
|
|
11308
|
-
for (const path of [join14("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
|
|
11309
|
-
if (await access4(path).then(() => true, () => false))
|
|
11310
|
-
throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
|
|
11311
|
-
let openFiles;
|
|
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;
|
|
11312
11448
|
try {
|
|
11313
|
-
|
|
11314
|
-
} catch
|
|
11315
|
-
|
|
11316
|
-
return;
|
|
11317
|
-
throw new Fault(409, "desktop_process_check", "Could not check whether Claude's third-party profile is already running.");
|
|
11449
|
+
url = new URL(address);
|
|
11450
|
+
} catch {
|
|
11451
|
+
throw new Fault(400, "credential_delivery_invalid", "Invalid credential delivery address.");
|
|
11318
11452
|
}
|
|
11319
|
-
if (
|
|
11320
|
-
|
|
11321
|
-
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.");
|
|
11322
|
-
}
|
|
11323
|
-
function metadata(text) {
|
|
11324
|
-
const value = text === undefined ? { entries: [] } : JSON.parse(text);
|
|
11325
|
-
if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((item) => !item || typeof item !== "object" || Array.isArray(item)))
|
|
11326
|
-
throw new Fault(422, "desktop_config_invalid", "Claude's configuration library metadata is invalid.");
|
|
11327
|
-
return value;
|
|
11328
|
-
}
|
|
11329
|
-
async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
11330
|
-
if (input.harness !== "claude")
|
|
11331
|
-
throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
|
|
11332
|
-
validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
|
|
11333
|
-
if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
|
|
11334
|
-
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.");
|
|
11335
|
-
const version = app.version.split(".").map(Number);
|
|
11336
|
-
if (version.length < 3 || version.some((n) => !Number.isSafeInteger(n)) || version[0] < 1 || version[0] === 1 && version[1] < 52386)
|
|
11337
|
-
throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
|
|
11338
|
-
const userData = system?.userData ?? claudeDesktopDataDirectory();
|
|
11339
|
-
const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
|
|
11340
|
-
await check2();
|
|
11341
|
-
await privateDirectory(userData);
|
|
11342
|
-
const library = join14(userData, "configLibrary");
|
|
11343
|
-
await privateDirectory(library);
|
|
11344
|
-
const release = await desktopLease(join14(library, ".switcher-lease.sqlite"));
|
|
11345
|
-
const metaPath = join14(library, "_meta.json"), receiptPath = join14(library, ".switcher-selection.json");
|
|
11346
|
-
let receipt, gateway, closed = false;
|
|
11347
|
-
const restore = async (record3) => {
|
|
11348
|
-
if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
|
|
11349
|
-
throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
|
|
11350
|
-
const configPath = join14(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
|
|
11351
|
-
if (current !== undefined && hash2(current) !== record3.configHash)
|
|
11352
|
-
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.");
|
|
11353
|
-
const currentMeta = await safeDesktopRead(metaPath);
|
|
11354
|
-
if (currentMeta !== record3.appliedMeta && currentMeta !== (record3.previousMeta ?? undefined))
|
|
11355
|
-
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.");
|
|
11356
|
-
if (record3.previousMeta === null)
|
|
11357
|
-
await rm5(metaPath, { force: true });
|
|
11358
|
-
else
|
|
11359
|
-
await writeDesktopPrivate(metaPath, record3.previousMeta);
|
|
11360
|
-
await rm5(configPath, { force: true });
|
|
11361
|
-
await rm5(receiptPath, { force: true });
|
|
11362
|
-
};
|
|
11363
|
-
const cleanup = async () => {
|
|
11364
|
-
if (closed)
|
|
11365
|
-
return;
|
|
11366
|
-
closed = true;
|
|
11367
|
-
try {
|
|
11368
|
-
await gateway?.cleanup();
|
|
11369
|
-
if (receipt)
|
|
11370
|
-
await restore(receipt);
|
|
11371
|
-
} finally {
|
|
11372
|
-
release();
|
|
11373
|
-
}
|
|
11374
|
-
};
|
|
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.");
|
|
11375
11455
|
try {
|
|
11376
|
-
const
|
|
11377
|
-
if (
|
|
11378
|
-
|
|
11379
|
-
|
|
11380
|
-
|
|
11381
|
-
|
|
11382
|
-
|
|
11383
|
-
|
|
11384
|
-
|
|
11385
|
-
|
|
11386
|
-
|
|
11387
|
-
|
|
11388
|
-
|
|
11389
|
-
|
|
11390
|
-
|
|
11391
|
-
|
|
11392
|
-
|
|
11393
|
-
|
|
11394
|
-
const config = JSON.stringify({
|
|
11395
|
-
inferenceProvider: "gateway",
|
|
11396
|
-
inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
|
|
11397
|
-
inferenceGatewayApiKey: gateway.token,
|
|
11398
|
-
inferenceGatewayAuthScheme: "bearer",
|
|
11399
|
-
modelDiscoveryEnabled: false,
|
|
11400
|
-
inferenceModels: Object.entries(targets).map(([tier, model3]) => ({ name: "switcher/" + tier, labelOverride: model3, anthropicFamilyTier: tier, isFamilyDefault: true }))
|
|
11401
|
-
});
|
|
11402
|
-
const previousMeta = await safeDesktopRead(metaPath);
|
|
11403
|
-
const meta = metadata(previousMeta);
|
|
11404
|
-
const appliedMeta = JSON.stringify({ ...meta, appliedId: id2, entries: [...meta.entries, { id: id2, name: `Switcher: ${input.providerId ?? "provider"} / ${input.model}` }] });
|
|
11405
|
-
receipt = { id: id2, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
|
|
11406
|
-
await writeDesktopPrivate(configPath, config);
|
|
11407
|
-
await writeDesktopPrivate(receiptPath, JSON.stringify(receipt));
|
|
11408
|
-
await writeDesktopPrivate(metaPath, appliedMeta);
|
|
11409
|
-
return {
|
|
11410
|
-
executable: app.executable,
|
|
11411
|
-
args: [],
|
|
11412
|
-
env: { CLAUDE_CONFIG_DIR: sessionDir },
|
|
11413
|
-
configPaths: [catalogPath, configPath],
|
|
11414
|
-
beforeLaunch: check2,
|
|
11415
|
-
cleanup,
|
|
11416
|
-
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.`]
|
|
11417
|
-
};
|
|
11418
|
-
} catch (error) {
|
|
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) {
|
|
11419
11474
|
try {
|
|
11420
|
-
|
|
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() };
|
|
11421
11482
|
} catch {}
|
|
11422
|
-
throw error;
|
|
11423
11483
|
}
|
|
11484
|
+
throw new Error("Mixed terminal redirection requires the system C library's dup function on this platform.");
|
|
11424
11485
|
}
|
|
11425
11486
|
|
|
11426
|
-
// src/
|
|
11427
|
-
|
|
11428
|
-
|
|
11429
|
-
const
|
|
11430
|
-
const
|
|
11431
|
-
|
|
11432
|
-
|
|
11433
|
-
|
|
11434
|
-
|
|
11435
|
-
|
|
11436
|
-
|
|
11437
|
-
|
|
11438
|
-
|
|
11439
|
-
|
|
11440
|
-
|
|
11441
|
-
|
|
11442
|
-
|
|
11443
|
-
|
|
11444
|
-
|
|
11445
|
-
|
|
11446
|
-
|
|
11447
|
-
|
|
11448
|
-
|
|
11449
|
-
|
|
11450
|
-
|
|
11451
|
-
|
|
11452
|
-
|
|
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];
|
|
11528
|
+
native = Bun.spawn(command, {
|
|
11529
|
+
cwd: options.cwd,
|
|
11530
|
+
env: options.env,
|
|
11531
|
+
stdio: ["inherit", "inherit", "inherit", ...duplicates],
|
|
11532
|
+
terminal: { cols, rows, name: options.env.TERM ?? "xterm-256color", data(_terminal, data2) {
|
|
11533
|
+
try {
|
|
11534
|
+
if (output)
|
|
11535
|
+
output.write(data2);
|
|
11536
|
+
else if (controllingOutput !== undefined)
|
|
11537
|
+
writeSync(controllingOutput, data2);
|
|
11538
|
+
} catch {
|
|
11539
|
+
failTerminal();
|
|
11540
|
+
}
|
|
11541
|
+
} }
|
|
11542
|
+
});
|
|
11543
|
+
} catch (error) {
|
|
11544
|
+
if (controllingOutput !== undefined) {
|
|
11545
|
+
closeSync(controllingOutput);
|
|
11546
|
+
controllingOutput = undefined;
|
|
11547
|
+
}
|
|
11548
|
+
throw error;
|
|
11549
|
+
} finally {
|
|
11550
|
+
for (const fd of duplicates)
|
|
11551
|
+
closeSync(fd);
|
|
11552
|
+
duplicator?.close();
|
|
11553
|
+
}
|
|
11554
|
+
terminal = native.terminal;
|
|
11555
|
+
const events = Object.assign(new EventEmitter, { pid: native.pid, kill: (signal) => native.kill(signal) });
|
|
11556
|
+
native.exited.then((code) => events.emit("exit", native.signalCode ? null : code, native.signalCode), () => events.emit("error"));
|
|
11557
|
+
relay = (chunk) => {
|
|
11558
|
+
try {
|
|
11559
|
+
terminal?.write(chunk);
|
|
11560
|
+
} catch {
|
|
11561
|
+
failTerminal();
|
|
11562
|
+
}
|
|
11563
|
+
};
|
|
11564
|
+
resize = () => {
|
|
11565
|
+
try {
|
|
11566
|
+
const [rows, cols] = stty(["size"]).split(/\s+/).map(Number);
|
|
11567
|
+
terminal?.resize(cols, rows);
|
|
11568
|
+
} catch {
|
|
11569
|
+
failTerminal();
|
|
11570
|
+
}
|
|
11571
|
+
};
|
|
11572
|
+
return events;
|
|
11573
|
+
})();
|
|
11574
|
+
let interrupted = false;
|
|
11575
|
+
let interruptionExitCode;
|
|
11576
|
+
let killTimer;
|
|
11577
|
+
const signalGroup = (signal) => {
|
|
11578
|
+
if (!child.pid)
|
|
11579
|
+
return;
|
|
11580
|
+
try {
|
|
11581
|
+
if (grouped)
|
|
11582
|
+
process.kill(-child.pid, signal);
|
|
11583
|
+
else
|
|
11584
|
+
child.kill(signal);
|
|
11585
|
+
} catch (error) {
|
|
11586
|
+
if (error.code !== "ESRCH")
|
|
11587
|
+
console.error("switcher: Could not signal an owned harness process.");
|
|
11588
|
+
}
|
|
11589
|
+
};
|
|
11590
|
+
const groupExists = () => {
|
|
11591
|
+
if (!grouped || !child.pid)
|
|
11592
|
+
return false;
|
|
11593
|
+
try {
|
|
11594
|
+
process.kill(-child.pid, 0);
|
|
11595
|
+
return true;
|
|
11596
|
+
} catch {
|
|
11597
|
+
return false;
|
|
11598
|
+
}
|
|
11599
|
+
};
|
|
11600
|
+
const forward = (signal) => {
|
|
11601
|
+
interruptionExitCode ??= signal === "SIGINT" ? 130 : signal === "SIGHUP" ? 129 : 143;
|
|
11602
|
+
interrupted = true;
|
|
11603
|
+
signalGroup(signal);
|
|
11604
|
+
killTimer ??= setTimeout(() => signalGroup("SIGKILL"), 5000).unref();
|
|
11605
|
+
};
|
|
11606
|
+
const failTerminal = () => {
|
|
11607
|
+
terminalFailure ??= new Error("Terminal I/O failed; the owned harness was stopped.");
|
|
11608
|
+
forward("SIGTERM");
|
|
11609
|
+
};
|
|
11610
|
+
const onInt = () => forward("SIGINT"), onTerm = () => forward("SIGTERM"), onHangup = () => forward("SIGHUP");
|
|
11611
|
+
const onResize = () => {
|
|
11612
|
+
if (resize)
|
|
11613
|
+
resize();
|
|
11614
|
+
else
|
|
11615
|
+
signalGroup("SIGWINCH");
|
|
11616
|
+
};
|
|
11617
|
+
process.on("SIGINT", onInt);
|
|
11618
|
+
process.on("SIGTERM", onTerm);
|
|
11619
|
+
process.on("SIGHUP", onHangup);
|
|
11620
|
+
if (grouped)
|
|
11621
|
+
process.on("SIGWINCH", onResize);
|
|
11622
|
+
const timeout = options.timeoutMs ? setTimeout(() => forward("SIGTERM"), options.timeoutMs) : undefined;
|
|
11623
|
+
let cleaned = false;
|
|
11624
|
+
const cleanup = () => {
|
|
11625
|
+
if (cleaned)
|
|
11626
|
+
return;
|
|
11627
|
+
cleaned = true;
|
|
11628
|
+
let failed = false;
|
|
11629
|
+
const attempt = (operation) => {
|
|
11630
|
+
try {
|
|
11631
|
+
operation();
|
|
11632
|
+
} catch {
|
|
11633
|
+
failed = true;
|
|
11634
|
+
}
|
|
11635
|
+
};
|
|
11636
|
+
attempt(() => {
|
|
11637
|
+
process.off("SIGINT", onInt);
|
|
11638
|
+
process.off("SIGTERM", onTerm);
|
|
11639
|
+
process.off("SIGHUP", onHangup);
|
|
11640
|
+
process.off("SIGWINCH", onResize);
|
|
11641
|
+
});
|
|
11642
|
+
if (timeout)
|
|
11643
|
+
clearTimeout(timeout);
|
|
11644
|
+
if (killTimer)
|
|
11645
|
+
clearTimeout(killTimer);
|
|
11646
|
+
if (relay)
|
|
11647
|
+
attempt(() => {
|
|
11648
|
+
process.stdin.off("data", relay);
|
|
11649
|
+
});
|
|
11650
|
+
attempt(() => {
|
|
11651
|
+
process.stdin.off("error", failTerminal);
|
|
11652
|
+
output?.off("error", failTerminal);
|
|
11653
|
+
});
|
|
11654
|
+
if (resize)
|
|
11655
|
+
attempt(() => {
|
|
11656
|
+
output?.off("resize", resize);
|
|
11657
|
+
});
|
|
11658
|
+
if (interactive) {
|
|
11659
|
+
if (tty[0])
|
|
11660
|
+
attempt(() => {
|
|
11661
|
+
process.stdin.setRawMode(wasRaw);
|
|
11662
|
+
});
|
|
11663
|
+
if (terminalMode)
|
|
11664
|
+
attempt(() => {
|
|
11665
|
+
stty([terminalMode]);
|
|
11666
|
+
});
|
|
11667
|
+
if (tty[0] && wasFlowing !== true)
|
|
11668
|
+
attempt(() => {
|
|
11669
|
+
process.stdin.pause();
|
|
11670
|
+
});
|
|
11671
|
+
}
|
|
11672
|
+
if (inputTimer)
|
|
11673
|
+
clearInterval(inputTimer);
|
|
11674
|
+
if (controllingInput !== undefined)
|
|
11675
|
+
attempt(() => {
|
|
11676
|
+
closeSync(controllingInput);
|
|
11677
|
+
controllingInput = undefined;
|
|
11678
|
+
});
|
|
11679
|
+
attempt(() => {
|
|
11680
|
+
terminal?.close();
|
|
11681
|
+
});
|
|
11682
|
+
if (controllingOutput !== undefined)
|
|
11683
|
+
attempt(() => {
|
|
11684
|
+
closeSync(controllingOutput);
|
|
11685
|
+
controllingOutput = undefined;
|
|
11686
|
+
});
|
|
11687
|
+
if (failed)
|
|
11688
|
+
console.error("switcher: Terminal restoration was incomplete; the owned harness has stopped.");
|
|
11689
|
+
};
|
|
11690
|
+
child.once("error", () => {
|
|
11691
|
+
cleanup();
|
|
11692
|
+
reject2(new Error("Harness process could not start; check executable and permissions."));
|
|
11693
|
+
});
|
|
11694
|
+
child.once("exit", async (code, signal) => {
|
|
11695
|
+
if (timeout)
|
|
11696
|
+
clearTimeout(timeout);
|
|
11697
|
+
if (groupExists()) {
|
|
11698
|
+
signalGroup("SIGTERM");
|
|
11699
|
+
const deadline = Date.now() + 5000;
|
|
11700
|
+
while (groupExists() && Date.now() < deadline)
|
|
11701
|
+
await new Promise((resolve9) => setTimeout(resolve9, 25));
|
|
11702
|
+
if (groupExists())
|
|
11703
|
+
signalGroup("SIGKILL");
|
|
11704
|
+
}
|
|
11705
|
+
cleanup();
|
|
11706
|
+
if (terminalFailure) {
|
|
11707
|
+
reject2(terminalFailure);
|
|
11708
|
+
return;
|
|
11709
|
+
}
|
|
11710
|
+
const exitCode = interruptionExitCode ?? code ?? (signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : signal === "SIGHUP" ? 129 : 137);
|
|
11711
|
+
resolveResult({ code: exitCode, interrupted: interrupted || exitCode === 130 || exitCode === 143 || exitCode === 129 });
|
|
11712
|
+
});
|
|
11713
|
+
if (interactive) {
|
|
11714
|
+
try {
|
|
11715
|
+
terminalMode = stty(["-g"]);
|
|
11716
|
+
output?.on("error", failTerminal);
|
|
11717
|
+
if (tty[0]) {
|
|
11718
|
+
process.stdin.on("error", failTerminal);
|
|
11719
|
+
process.stdin.setRawMode(true);
|
|
11720
|
+
process.stdin.on("data", relay);
|
|
11721
|
+
process.stdin.resume();
|
|
11722
|
+
} else {
|
|
11723
|
+
controllingInput = openSync("/dev/tty", constants6.O_RDONLY | constants6.O_NONBLOCK);
|
|
11724
|
+
stty(["raw", "-echo"]);
|
|
11725
|
+
const buffer = Buffer.alloc(4096);
|
|
11726
|
+
inputTimer = setInterval(() => {
|
|
11727
|
+
try {
|
|
11728
|
+
for (let bytes = 0;bytes < 65536; ) {
|
|
11729
|
+
const count = readSync(controllingInput, buffer);
|
|
11730
|
+
if (!count) {
|
|
11731
|
+
failTerminal();
|
|
11732
|
+
break;
|
|
11733
|
+
}
|
|
11734
|
+
terminal?.write(buffer.subarray(0, count));
|
|
11735
|
+
bytes += count;
|
|
11736
|
+
}
|
|
11737
|
+
} catch (error) {
|
|
11738
|
+
if (!["EAGAIN", "EWOULDBLOCK", "EINTR"].includes(error.code ?? ""))
|
|
11739
|
+
failTerminal();
|
|
11740
|
+
}
|
|
11741
|
+
}, 16);
|
|
11742
|
+
}
|
|
11743
|
+
stty(["-opost"]);
|
|
11744
|
+
output?.on("resize", resize);
|
|
11745
|
+
} catch {
|
|
11746
|
+
terminalFailure = new Error("The native terminal could not be initialized; the owned harness was stopped.");
|
|
11747
|
+
signalGroup("SIGKILL");
|
|
11748
|
+
}
|
|
11749
|
+
}
|
|
11750
|
+
});
|
|
11751
|
+
}
|
|
11752
|
+
|
|
11753
|
+
// src/ori-backend.ts
|
|
11754
|
+
import { execFile as execFile4 } from "child_process";
|
|
11755
|
+
import { promisify as promisify4 } from "util";
|
|
11756
|
+
var exec = promisify4(execFile4);
|
|
11757
|
+
var oriProviderCatalog = Object.freeze([{
|
|
11758
|
+
id: "openrouter",
|
|
11759
|
+
displayName: "OpenRouter",
|
|
11760
|
+
credentialEnv: "OPENROUTER_API_KEY",
|
|
11761
|
+
publicModelsUrl: "https://openrouter.ai/api/v1/models",
|
|
11762
|
+
entitledModelsUrl: "https://openrouter.ai/api/v1/models/user",
|
|
11763
|
+
protocols: ["anthropic-messages", "openai-responses", "openai-chat"]
|
|
11764
|
+
}]);
|
|
11765
|
+
var oriNativeFlags = Object.freeze({
|
|
11766
|
+
claude: ["--model", "--reasoning-effort"],
|
|
11767
|
+
codex: ["--model", "--reasoning-effort"],
|
|
11768
|
+
grok: ["--model", "--reasoning-effort"]
|
|
11769
|
+
});
|
|
11770
|
+
|
|
11771
|
+
class OriBackendError extends Error {
|
|
11772
|
+
code;
|
|
11773
|
+
constructor(code, message) {
|
|
11774
|
+
super(message);
|
|
11775
|
+
this.code = code;
|
|
11776
|
+
this.name = "OriBackendError";
|
|
11777
|
+
}
|
|
11778
|
+
}
|
|
11779
|
+
var safeEnvironmentNames = new Set([
|
|
11780
|
+
"PATH",
|
|
11781
|
+
"HOME",
|
|
11782
|
+
"USER",
|
|
11783
|
+
"LOGNAME",
|
|
11784
|
+
"SHELL",
|
|
11785
|
+
"TMPDIR",
|
|
11786
|
+
"TEMP",
|
|
11787
|
+
"TMP",
|
|
11788
|
+
"TERM",
|
|
11789
|
+
"COLORTERM",
|
|
11790
|
+
"LANG",
|
|
11791
|
+
"LC_ALL",
|
|
11792
|
+
"LC_CTYPE",
|
|
11793
|
+
"LC_MESSAGES",
|
|
11794
|
+
"XDG_CONFIG_HOME",
|
|
11795
|
+
"XDG_DATA_HOME",
|
|
11796
|
+
"XDG_STATE_HOME",
|
|
11797
|
+
"XDG_CACHE_HOME",
|
|
11798
|
+
"SSH_AUTH_SOCK",
|
|
11799
|
+
"GIT_SSH_COMMAND",
|
|
11800
|
+
"EDITOR",
|
|
11801
|
+
"VISUAL",
|
|
11802
|
+
"NO_COLOR",
|
|
11803
|
+
"FORCE_COLOR",
|
|
11804
|
+
"CODEX_HOME",
|
|
11805
|
+
"CLAUDE_CONFIG_DIR",
|
|
11806
|
+
"OPENROUTER_API_KEY"
|
|
11807
|
+
]);
|
|
11808
|
+
function safeEnvironment(environment) {
|
|
11809
|
+
const result = {};
|
|
11810
|
+
for (const [name, value] of Object.entries(environment)) {
|
|
11811
|
+
if (safeEnvironmentNames.has(name) && value !== undefined)
|
|
11812
|
+
result[name] = value;
|
|
11813
|
+
}
|
|
11814
|
+
result.ORI_FORCE_OPENROUTER_API_KEY = "1";
|
|
11815
|
+
return result;
|
|
11816
|
+
}
|
|
11817
|
+
function assertOriLoginAllowed(environment) {
|
|
11818
|
+
const loginPolicy = environment.ORI_REQUIRE_LOGIN?.trim().toLowerCase();
|
|
11819
|
+
if (loginPolicy && !["0", "false", "no", "off"].includes(loginPolicy))
|
|
11820
|
+
throw new OriBackendError("ori_login_required", "ORI_REQUIRE_LOGIN is enabled; this adapter cannot bypass native Ori login policy with an environment key.");
|
|
11821
|
+
}
|
|
11822
|
+
function parseVersion(stdout) {
|
|
11823
|
+
try {
|
|
11824
|
+
const value = JSON.parse(stdout);
|
|
11825
|
+
if (typeof value.data?.version === "string")
|
|
11826
|
+
return value.data.version;
|
|
11827
|
+
} catch {}
|
|
11828
|
+
const match = stdout.match(/(?:@ori-runtime\/cli\s+|ori\s+v?)(\d+\.\d+\.\d+(?:[+.-][A-Za-z0-9.-]+)?)/i);
|
|
11829
|
+
return match?.[1];
|
|
11830
|
+
}
|
|
11831
|
+
function parseHarnesses(stdout) {
|
|
11832
|
+
let value;
|
|
11833
|
+
try {
|
|
11834
|
+
value = JSON.parse(stdout);
|
|
11835
|
+
} catch {
|
|
11836
|
+
throw new OriBackendError("invalid_contract", "Ori harness list was not valid JSON.");
|
|
11837
|
+
}
|
|
11838
|
+
const rows = value?.data?.launchable;
|
|
11839
|
+
if (!Array.isArray(rows))
|
|
11840
|
+
throw new OriBackendError("invalid_contract", "Ori harness list did not contain a launchable array.");
|
|
11841
|
+
return rows.flatMap((row) => {
|
|
11842
|
+
if (!row || typeof row !== "object")
|
|
11843
|
+
return [];
|
|
11844
|
+
const item2 = row;
|
|
11845
|
+
if (typeof item2.kind !== "string" || typeof item2.installed !== "boolean")
|
|
11846
|
+
return [];
|
|
11847
|
+
return [{
|
|
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
|
|
11852
|
+
}];
|
|
11853
|
+
});
|
|
11854
|
+
}
|
|
11855
|
+
async function readOnly(executable, args, environment, cwd) {
|
|
11856
|
+
try {
|
|
11857
|
+
const result = await exec(executable, args, { cwd, env: safeEnvironment({ ...environment, OPENROUTER_API_KEY: undefined }), timeout: 1e4, maxBuffer: 256 * 1024 });
|
|
11858
|
+
return { code: 0, stdout: typeof result.stdout === "string" ? result.stdout : "", stderr: typeof result.stderr === "string" ? result.stderr : "" };
|
|
11859
|
+
} catch (error) {
|
|
11860
|
+
const failure = error;
|
|
11861
|
+
return { code: typeof failure.code === "number" ? failure.code : 1, stdout: failure.stdout ?? "", stderr: failure.stderr ?? failure.message ?? "" };
|
|
11862
|
+
}
|
|
11863
|
+
}
|
|
11864
|
+
async function inspectOri(options = {}) {
|
|
11865
|
+
const executable = options.executable ?? "ori";
|
|
11866
|
+
const environment = options.environment ?? process.env;
|
|
11867
|
+
const versionResult = await readOnly(executable, ["--version"], environment, options.cwd);
|
|
11868
|
+
if (versionResult.code !== 0)
|
|
11869
|
+
throw new OriBackendError("ori_unavailable", "Ori could not report its version; install it or pass an explicit executable.");
|
|
11870
|
+
const version = parseVersion(versionResult.stdout);
|
|
11871
|
+
if (!version)
|
|
11872
|
+
throw new OriBackendError("invalid_contract", "Ori --version did not report a version.");
|
|
11873
|
+
const inventoryResult = await readOnly(executable, ["harness", "list", "--json"], environment, options.cwd);
|
|
11874
|
+
if (inventoryResult.code !== 0)
|
|
11875
|
+
throw new OriBackendError("ori_unavailable", "Ori could not report its harness inventory.");
|
|
11876
|
+
return { executable, version, harnesses: parseHarnesses(inventoryResult.stdout) };
|
|
11877
|
+
}
|
|
11878
|
+
function assertSupportedOriVersion(contract) {
|
|
11879
|
+
if (!/^0\.12\./.test(contract.version))
|
|
11880
|
+
throw new OriBackendError("ori_version_unsupported", `Ori ${contract.version} is outside the verified 0.12.x adapter contract.`);
|
|
11881
|
+
}
|
|
11882
|
+
function requireOriHarness(contract, target) {
|
|
11883
|
+
assertSupportedOriVersion(contract);
|
|
11884
|
+
if (target === "kilo")
|
|
11885
|
+
throw new OriBackendError("unsupported_harness", "Ori does not launch Kilo; use the direct adapter.");
|
|
11886
|
+
if (target === "dsh")
|
|
11887
|
+
throw new OriBackendError("unsupported_harness", "Ori dsh performs setup only. Use the direct DeepSeek Harness adapter to launch the native harness.");
|
|
11888
|
+
if (target === "gemini")
|
|
11889
|
+
throw new OriBackendError("unsupported_harness", "Gemini CLI is supported through the direct Switcher adapter; Ori has no verified Gemini target.");
|
|
11890
|
+
if (target === "pi" || target === "aider")
|
|
11891
|
+
throw new OriBackendError("unsupported_harness", "Pi is supported through the direct Switcher adapter; the Ori preservation subset supports Codex and Grok only.");
|
|
11892
|
+
if (target === "opencode2")
|
|
11893
|
+
throw new OriBackendError("unsupported_harness", "Ori 0.12.1 targets legacy `opencode`; it cannot launch OpenCode 2 (`opencode2`).");
|
|
11894
|
+
const row = contract.harnesses.find((harness) => harness.kind === target);
|
|
11895
|
+
if (!row?.installed)
|
|
11896
|
+
throw new OriBackendError("harness_unavailable", `Ori cannot launch ${target} because its native harness is not installed; no installer was started.`);
|
|
11897
|
+
return row;
|
|
11898
|
+
}
|
|
11899
|
+
function oriProvider(id2) {
|
|
11900
|
+
const provider = oriProviderCatalog.find((entry) => entry.id === id2);
|
|
11901
|
+
if (!provider)
|
|
11902
|
+
throw new OriBackendError("provider_unsupported", "Ori supports OpenRouter only; use a direct Switcher adapter for this provider.");
|
|
11903
|
+
return provider;
|
|
11904
|
+
}
|
|
11905
|
+
function assertProviderAuthority(target, provider, providerBaseUrl, protocol) {
|
|
11906
|
+
const catalog = oriProvider("openrouter");
|
|
11907
|
+
const compatible2 = target === "codex" ? protocol === "openai-responses" : target === "claude" ? protocol === "anthropic-messages" : catalog.protocols.includes(protocol);
|
|
11908
|
+
if (!providerBaseUrl || !protocol || !compatible2)
|
|
11909
|
+
throw new OriBackendError("provider_authority", "Ori requires an explicit OpenRouter provider URL and a protocol supported by the selected Ori target.");
|
|
11910
|
+
let url;
|
|
11911
|
+
try {
|
|
11912
|
+
url = new URL(providerBaseUrl);
|
|
11913
|
+
} catch {
|
|
11914
|
+
throw new OriBackendError("provider_authority", "Ori requires the OpenRouter HTTPS provider URL.");
|
|
11915
|
+
}
|
|
11916
|
+
const path = url.pathname.replace(/\/+$/, "");
|
|
11917
|
+
if (url.protocol !== "https:" || url.origin !== "https://openrouter.ai" || path !== "/api/v1" || url.username || url.password || url.search || url.hash)
|
|
11918
|
+
throw new OriBackendError("provider_authority", "Ori provider credentials may only be sent to https://openrouter.ai/api/v1.");
|
|
11453
11919
|
}
|
|
11454
|
-
|
|
11455
|
-
|
|
11456
|
-
|
|
11457
|
-
|
|
11458
|
-
|
|
11459
|
-
|
|
11460
|
-
throw new Error("Ori requires the OpenRouter Bearer authentication contract; use the direct adapter for other auth styles.");
|
|
11461
|
-
assertOriLoginAllowed({ ...process.env, ...options.credentialEnv });
|
|
11462
|
-
const policyEnvironment = { ...process.env, ...options.credentialEnv };
|
|
11463
|
-
if (plan.profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((policyEnvironment.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
|
|
11464
|
-
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.");
|
|
11465
|
-
if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
|
|
11466
|
-
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.");
|
|
11467
|
-
const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve9(options.cwd) : undefined });
|
|
11468
|
-
const native = requireOriHarness(contract, target);
|
|
11469
|
-
if (!native.path)
|
|
11470
|
-
throw new Error("Ori did not report the native harness executable path.");
|
|
11471
|
-
const detection = await detectHarness(target, native.path);
|
|
11472
|
-
if (!detection.available)
|
|
11473
|
-
throw new Error("The native harness reported by Ori could not report its version.");
|
|
11474
|
-
validateHarnessVersion(target, detection.version);
|
|
11475
|
-
const catalogPath = target === "codex" && options.stateDir ? await writeOriCodexCatalog(options.stateDir, plan.catalog.models) : undefined;
|
|
11476
|
-
const request = buildOriRequest(plan, target, catalogPath, options.args ?? []);
|
|
11477
|
-
validateOriLaunchRequest(request);
|
|
11478
|
-
return { contract, request, detection };
|
|
11920
|
+
function assertPassthrough(target, args) {
|
|
11921
|
+
try {
|
|
11922
|
+
assertHarnessArguments(target, args, { additionalReserved: ["--reasoning-effort", "--provider", "--model-provider", "--model_provider"], reserveCodexConfig: true });
|
|
11923
|
+
} catch {
|
|
11924
|
+
throw new OriBackendError("reserved_argument", "Provider, model, profile, leader and authentication options are reserved by the Ori launch profile.");
|
|
11925
|
+
}
|
|
11479
11926
|
}
|
|
11480
|
-
|
|
11481
|
-
|
|
11482
|
-
|
|
11927
|
+
function validateOriLaunchRequest(request) {
|
|
11928
|
+
if (request.target === "kilo")
|
|
11929
|
+
throw new OriBackendError("unsupported_harness", "Ori does not launch Kilo; use the direct adapter.");
|
|
11930
|
+
if (request.target === "dsh")
|
|
11931
|
+
throw new OriBackendError("unsupported_harness", "Ori dsh performs setup only. Use the direct DeepSeek Harness adapter to launch the native harness.");
|
|
11932
|
+
if (request.target === "gemini")
|
|
11933
|
+
throw new OriBackendError("unsupported_harness", "Gemini CLI is supported through the direct Switcher adapter; Ori has no verified Gemini target.");
|
|
11934
|
+
if (request.target === "pi" || request.target === "aider")
|
|
11935
|
+
throw new OriBackendError("unsupported_harness", "Pi is supported through the direct Switcher adapter; the Ori preservation subset supports Codex and Grok only.");
|
|
11936
|
+
assertProviderAuthority(request.target, request.provider, request.providerBaseUrl, request.protocol);
|
|
11937
|
+
if (!request.model.trim())
|
|
11938
|
+
throw new OriBackendError("model_required", "An OpenRouter model ID is required for an Ori launch.");
|
|
11939
|
+
assertPassthrough(request.target, request.args ?? []);
|
|
11940
|
+
if (request.target === "opencode2")
|
|
11941
|
+
throw new OriBackendError("unsupported_harness", "Ori 0.12.1 targets legacy `opencode`; it cannot launch OpenCode 2 (`opencode2`).");
|
|
11942
|
+
if (request.target === "claude")
|
|
11943
|
+
throw new OriBackendError("global_config_mutation", "Ori Claude launches may update ~/.claude.json; the preservation subset supports Codex and Grok only.");
|
|
11944
|
+
if (request.target === "grok" && request.protocol !== "openai-chat")
|
|
11945
|
+
throw new OriBackendError("unsupported_protocol", "Ori Grok is verified only for OpenAI Chat; use the direct adapter for Messages or Responses.");
|
|
11946
|
+
const catalog = request.catalog;
|
|
11947
|
+
if (!catalog || catalog.source !== "switcher-openrouter" || !catalog.modelIds.includes(request.model))
|
|
11948
|
+
throw new OriBackendError("catalog_required", "The selected model must come from Switcher's OpenRouter catalog before an Ori launch.");
|
|
11483
11949
|
}
|
|
11484
|
-
function
|
|
11950
|
+
function prepareOriLaunch(request) {
|
|
11951
|
+
validateOriLaunchRequest(request);
|
|
11952
|
+
const args = request.args ?? [];
|
|
11953
|
+
const environment = request.environment ?? process.env;
|
|
11954
|
+
assertOriLoginAllowed(environment);
|
|
11955
|
+
const credential = environment.OPENROUTER_API_KEY?.trim();
|
|
11956
|
+
if (!credential)
|
|
11957
|
+
throw new OriBackendError("openrouter_key_missing", "An OpenRouter API key must be supplied in the launch environment before starting Ori.");
|
|
11958
|
+
if (/[\r\n]/.test(credential))
|
|
11959
|
+
throw new OriBackendError("openrouter_key_invalid", "The OpenRouter API key contains invalid characters.");
|
|
11960
|
+
const oriArgs = [request.target, "--model", request.model];
|
|
11961
|
+
if (request.target === "grok") {
|
|
11962
|
+
validateGrokResume(args);
|
|
11963
|
+
oriArgs.splice(1, 0, "--no-leader");
|
|
11964
|
+
}
|
|
11965
|
+
if (request.reasoningEffort)
|
|
11966
|
+
oriArgs.push("--reasoning-effort", request.reasoningEffort);
|
|
11967
|
+
if (request.target === "codex" && request.catalog?.codexModelCatalogPath) {
|
|
11968
|
+
const path = request.catalog.codexModelCatalogPath;
|
|
11969
|
+
if (!path.startsWith("/") || /[\r\n\0]/.test(path))
|
|
11970
|
+
throw new OriBackendError("catalog_path_invalid", "The Switcher Codex catalog path must be an absolute safe path.");
|
|
11971
|
+
oriArgs.push("-c", `model_catalog_json=${JSON.stringify(path)}`);
|
|
11972
|
+
}
|
|
11973
|
+
oriArgs.push(...args);
|
|
11485
11974
|
return {
|
|
11486
|
-
|
|
11487
|
-
|
|
11488
|
-
|
|
11489
|
-
|
|
11490
|
-
|
|
11491
|
-
|
|
11492
|
-
|
|
11975
|
+
executable: request.executable ?? "ori",
|
|
11976
|
+
args: oriArgs,
|
|
11977
|
+
env: safeEnvironment(environment),
|
|
11978
|
+
target: request.target,
|
|
11979
|
+
provider: "openrouter",
|
|
11980
|
+
model: request.model,
|
|
11981
|
+
warnings: oriLaunchWarnings(request.target)
|
|
11493
11982
|
};
|
|
11494
11983
|
}
|
|
11495
|
-
|
|
11496
|
-
|
|
11497
|
-
|
|
11498
|
-
|
|
11499
|
-
|
|
11500
|
-
|
|
11501
|
-
|
|
11502
|
-
|
|
11503
|
-
|
|
11504
|
-
|
|
11505
|
-
|
|
11506
|
-
|
|
11507
|
-
|
|
11508
|
-
modelPolicy: plan.profile.modelPolicy,
|
|
11509
|
-
providerId: plan.provider.id,
|
|
11510
|
-
onRoutingEvent: options.onRoutingEvent,
|
|
11511
|
-
credential,
|
|
11512
|
-
executable: detection.executable,
|
|
11513
|
-
version: detection.version,
|
|
11514
|
-
stateDir: options.stateDir,
|
|
11515
|
-
cwd: resolve9(options.cwd ?? process.cwd()),
|
|
11516
|
-
args: options.args ?? []
|
|
11517
|
-
});
|
|
11984
|
+
function oriLaunchWarnings(target) {
|
|
11985
|
+
return target === "grok" ? ["Ori supplies Grok's account-entitled OpenRouter catalog; it is not the Switcher-filtered catalog snapshot."] : [];
|
|
11986
|
+
}
|
|
11987
|
+
|
|
11988
|
+
// src/chatgpt-launch.ts
|
|
11989
|
+
import { createHash as createHash10 } from "crypto";
|
|
11990
|
+
import { writeFile as writeFile12, rm as rm4 } from "fs/promises";
|
|
11991
|
+
import { join as join14 } from "path";
|
|
11992
|
+
|
|
11993
|
+
// src/desktop-state.ts
|
|
11994
|
+
import { Database as Database3 } from "bun:sqlite";
|
|
11995
|
+
import { readFile as readFile5, writeFile as writeFile11, rm as rm3, lstat as lstat5, rename as rename3, chmod as chmod2 } from "fs/promises";
|
|
11996
|
+
async function safeDesktopRead(path) {
|
|
11518
11997
|
try {
|
|
11519
|
-
const
|
|
11520
|
-
|
|
11521
|
-
|
|
11522
|
-
await
|
|
11523
|
-
|
|
11524
|
-
|
|
11525
|
-
|
|
11526
|
-
|
|
11527
|
-
|
|
11528
|
-
|
|
11529
|
-
|
|
11530
|
-
|
|
11998
|
+
const info = await lstat5(path);
|
|
11999
|
+
if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
|
|
12000
|
+
throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user.");
|
|
12001
|
+
return await readFile5(path, "utf8");
|
|
12002
|
+
} catch (error) {
|
|
12003
|
+
if (error.code === "ENOENT")
|
|
12004
|
+
return;
|
|
12005
|
+
throw error;
|
|
12006
|
+
}
|
|
12007
|
+
}
|
|
12008
|
+
async function writeDesktopPrivate(path, text) {
|
|
12009
|
+
const temporary = path + "." + crypto.randomUUID() + ".tmp";
|
|
12010
|
+
try {
|
|
12011
|
+
await writeFile11(temporary, text, { mode: 384, flag: "wx" });
|
|
12012
|
+
await rename3(temporary, path);
|
|
12013
|
+
} finally {
|
|
12014
|
+
await rm3(temporary, { force: true });
|
|
12015
|
+
}
|
|
12016
|
+
}
|
|
12017
|
+
async function desktopLease(path) {
|
|
12018
|
+
try {
|
|
12019
|
+
const info = await lstat5(path);
|
|
12020
|
+
if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
|
|
12021
|
+
throw new Fault(422, "desktop_state_permissions", "Desktop lease must be a regular file owned by this user.");
|
|
12022
|
+
} catch (error) {
|
|
12023
|
+
if (error.code !== "ENOENT")
|
|
12024
|
+
throw error;
|
|
12025
|
+
}
|
|
12026
|
+
const lease = new Database3(path);
|
|
12027
|
+
try {
|
|
12028
|
+
await chmod2(path, 384);
|
|
12029
|
+
lease.exec("PRAGMA busy_timeout=0; CREATE TABLE IF NOT EXISTS lease (id INTEGER PRIMARY KEY); BEGIN EXCLUSIVE;");
|
|
12030
|
+
} catch {
|
|
12031
|
+
lease.close();
|
|
12032
|
+
throw new Fault(409, "desktop_busy", "This desktop provider profile is already running. Quit that instance before launching it again.");
|
|
12033
|
+
}
|
|
12034
|
+
let closed = false;
|
|
12035
|
+
return () => {
|
|
12036
|
+
if (!closed) {
|
|
12037
|
+
closed = true;
|
|
12038
|
+
lease.close();
|
|
12039
|
+
}
|
|
12040
|
+
};
|
|
12041
|
+
}
|
|
12042
|
+
|
|
12043
|
+
// src/chatgpt-launch.ts
|
|
12044
|
+
var object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
12045
|
+
function merge2(base, overlay) {
|
|
12046
|
+
const result = { ...base };
|
|
12047
|
+
for (const [key, value] of Object.entries(overlay))
|
|
12048
|
+
result[key] = object5(value) && object5(result[key]) ? merge2(result[key], value) : value;
|
|
12049
|
+
return result;
|
|
12050
|
+
}
|
|
12051
|
+
var digest = (value) => createHash10("sha256").update(value).digest("hex");
|
|
12052
|
+
var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
12053
|
+
async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
12054
|
+
await privateDirectory(sessionDir);
|
|
12055
|
+
const home = join14(sessionDir, "codex"), userData = join14(sessionDir, "electron");
|
|
12056
|
+
await privateDirectory(home);
|
|
12057
|
+
await privateDirectory(userData);
|
|
12058
|
+
const release = await desktopLease(join14(sessionDir, "launch.sqlite"));
|
|
12059
|
+
let released = false, authText;
|
|
12060
|
+
const authPath = join14(home, "auth.json"), receiptPath = join14(home, ".switcher-auth.sha256");
|
|
12061
|
+
const cleanup = async () => {
|
|
12062
|
+
if (released)
|
|
12063
|
+
return;
|
|
12064
|
+
released = true;
|
|
12065
|
+
try {
|
|
12066
|
+
if (authText !== undefined && await safeDesktopRead(authPath) === authText) {
|
|
12067
|
+
await rm4(authPath, { force: true });
|
|
12068
|
+
await rm4(receiptPath, { force: true });
|
|
12069
|
+
}
|
|
12070
|
+
} finally {
|
|
12071
|
+
release();
|
|
12072
|
+
}
|
|
12073
|
+
};
|
|
12074
|
+
try {
|
|
12075
|
+
const settings2 = [];
|
|
12076
|
+
for (let i = 0;i < native.args.length; i += 2) {
|
|
12077
|
+
if (native.args[i] !== "-c" || typeof native.args[i + 1] !== "string")
|
|
12078
|
+
throw new Fault(400, "desktop_arguments", "Desktop launches accept provider/model settings, not native CLI commands.");
|
|
12079
|
+
settings2.push(native.args[i + 1]);
|
|
12080
|
+
}
|
|
12081
|
+
settings2.push('cli_auth_credentials_store="file"', 'forced_login_method="api"');
|
|
12082
|
+
if (!settings2.some((setting) => setting.startsWith("approval_policy=")))
|
|
12083
|
+
settings2.push('approval_policy="on-request"');
|
|
12084
|
+
if (!settings2.some((setting) => setting.startsWith("sandbox_mode=")))
|
|
12085
|
+
settings2.push('sandbox_mode="workspace-write"');
|
|
12086
|
+
const configPath = join14(home, "config.toml");
|
|
12087
|
+
const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
|
|
12088
|
+
if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
|
|
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.");
|
|
12090
|
+
let existing = {};
|
|
12091
|
+
try {
|
|
12092
|
+
existing = Bun.TOML.parse(await safeDesktopRead(configPath) ?? "");
|
|
12093
|
+
} catch (error) {
|
|
12094
|
+
if (error.code !== "ENOENT")
|
|
12095
|
+
throw new Fault(422, "desktop_config_invalid", "The desktop profile config cannot be read safely.");
|
|
12096
|
+
}
|
|
12097
|
+
const config = merge2(existing, Bun.TOML.parse(settings2.join(`
|
|
12098
|
+
`)));
|
|
12099
|
+
await writeDesktopPrivate(configPath, renderCodexAgentToml(config));
|
|
12100
|
+
const key = native.env.SWITCHER_HARNESS_API_KEY;
|
|
12101
|
+
if (!key)
|
|
12102
|
+
throw new Fault(500, "desktop_auth_missing", "Desktop preparation did not receive a scoped gateway credential.");
|
|
12103
|
+
authText = JSON.stringify({ OPENAI_API_KEY: key }) + `
|
|
12104
|
+
`;
|
|
12105
|
+
await writeDesktopPrivate(receiptPath, digest(authText));
|
|
12106
|
+
await writeDesktopPrivate(authPath, authText);
|
|
12107
|
+
const wrapper = join14(stateDir, "chatgpt-codex");
|
|
12108
|
+
const overrides = settings2.flatMap((setting) => ["-c", setting]);
|
|
12109
|
+
await writeFile12(wrapper, `#!/bin/sh
|
|
12110
|
+
set -eu
|
|
12111
|
+
unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
|
|
12112
|
+
export CODEX_HOME=${quote2(home)}
|
|
12113
|
+
if [ "\${1-}" = sandbox ]; then
|
|
12114
|
+
exec ${quote2(app.codexExecutable)} "$@"
|
|
12115
|
+
fi
|
|
12116
|
+
exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
|
|
12117
|
+
`, { mode: 448, flag: "wx" });
|
|
12118
|
+
return {
|
|
12119
|
+
...native,
|
|
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
|
+
};
|
|
11531
12133
|
} catch (error) {
|
|
11532
|
-
await
|
|
12134
|
+
await cleanup();
|
|
11533
12135
|
throw error;
|
|
11534
12136
|
}
|
|
11535
12137
|
}
|
|
11536
|
-
|
|
11537
|
-
|
|
11538
|
-
|
|
11539
|
-
|
|
11540
|
-
|
|
11541
|
-
|
|
11542
|
-
|
|
11543
|
-
|
|
11544
|
-
|
|
11545
|
-
|
|
11546
|
-
|
|
11547
|
-
|
|
11548
|
-
|
|
11549
|
-
|
|
11550
|
-
|
|
11551
|
-
|
|
11552
|
-
|
|
11553
|
-
|
|
11554
|
-
|
|
11555
|
-
|
|
11556
|
-
|
|
11557
|
-
|
|
11558
|
-
throw new Error("--executable is ambiguous with --backend ori; use --ori-executable PATH.");
|
|
11559
|
-
if (backend === "direct" && options.oriExecutable)
|
|
11560
|
-
throw new Error("--ori-executable requires --backend ori.");
|
|
11561
|
-
if (options.desktop && (plan.profile.harness !== "codex" || backend !== "direct"))
|
|
11562
|
-
throw new Error("ChatGPT requires the direct Codex provider adapter.");
|
|
11563
|
-
if (options.claudeDesktop && (options.desktop || plan.profile.harness !== "claude" || backend !== "direct" || options.executable || options.args?.length))
|
|
11564
|
-
throw new Error("Claude desktop requires its direct Messages gateway adapter without native CLI overrides.");
|
|
11565
|
-
const nativeExecutable = options.desktop?.codexExecutable ?? options.executable;
|
|
11566
|
-
const detection = backend === "direct" && !options.claudeDesktop ? await detectHarness(plan.profile.harness, nativeExecutable) : undefined;
|
|
11567
|
-
if (backend === "direct" && !options.claudeDesktop && !detection?.available)
|
|
11568
|
-
throw new Error(harnessInstallationMessage(plan.profile.harness, detection?.executable ?? plan.profile.harness, Boolean(options.executable)));
|
|
11569
|
-
if (backend === "direct" && plan.profile.harness === "gemini")
|
|
11570
|
-
validateHarnessVersion("gemini", detection?.version);
|
|
11571
|
-
if (backend === "direct" && plan.profile.harness === "aider")
|
|
11572
|
-
validateHarnessVersion(plan.profile.harness, detection?.version);
|
|
11573
|
-
const root = resolve9(options.stateDir ?? join15(switcherHome(), "state"));
|
|
11574
|
-
await privateDirectory(root);
|
|
11575
|
-
const stateDir = await mkdtemp(join15(root, "launch-"));
|
|
11576
|
-
let credential;
|
|
11577
|
-
if (backend === "direct") {
|
|
11578
|
-
try {
|
|
11579
|
-
credential = options.resolveCredential ? await options.resolveCredential(plan.provider) : providerCredential(plan.provider, options.credentialEnv);
|
|
11580
|
-
if (plan.provider.credentialEnv && !credential)
|
|
11581
|
-
throw new Error("Provider credential environment reference is not available in this local launcher process.");
|
|
11582
|
-
} catch (error) {
|
|
11583
|
-
await rm6(stateDir, { recursive: true, force: true });
|
|
11584
|
-
throw error;
|
|
11585
|
-
}
|
|
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.");
|
|
11586
12160
|
}
|
|
11587
|
-
|
|
11588
|
-
|
|
11589
|
-
|
|
11590
|
-
|
|
11591
|
-
|
|
11592
|
-
|
|
11593
|
-
|
|
11594
|
-
|
|
11595
|
-
|
|
11596
|
-
|
|
11597
|
-
|
|
11598
|
-
|
|
11599
|
-
|
|
11600
|
-
|
|
11601
|
-
|
|
11602
|
-
|
|
11603
|
-
|
|
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 });
|
|
11604
12204
|
};
|
|
11605
|
-
const
|
|
11606
|
-
if (
|
|
12205
|
+
const cleanup = async () => {
|
|
12206
|
+
if (closed)
|
|
11607
12207
|
return;
|
|
11608
|
-
|
|
11609
|
-
await client.finishRun(candidate.id, candidate.version, { ...body, routingEvents, routingEventsDropped }, crypto.randomUUID()).catch(() => console.error(message));
|
|
11610
|
-
};
|
|
11611
|
-
let cancelPreparation;
|
|
11612
|
-
const preparationCancellation = new Promise((_, reject2) => {
|
|
11613
|
-
cancelPreparation = reject2;
|
|
11614
|
-
});
|
|
11615
|
-
preparationCancellation.catch(() => {
|
|
11616
|
-
return;
|
|
11617
|
-
});
|
|
11618
|
-
try {
|
|
11619
|
-
const input = {
|
|
11620
|
-
harness: plan.profile.harness,
|
|
11621
|
-
baseUrl: plan.provider.baseUrl,
|
|
11622
|
-
protocol: plan.provider.protocol,
|
|
11623
|
-
authStyle: plan.provider.authStyle,
|
|
11624
|
-
model: plan.profile.model,
|
|
11625
|
-
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
11626
|
-
modelPolicy: plan.profile.modelPolicy,
|
|
11627
|
-
providerId: plan.provider.id,
|
|
11628
|
-
onRoutingEvent,
|
|
11629
|
-
credential,
|
|
11630
|
-
stateDir,
|
|
11631
|
-
cwd: resolve9(options.cwd ?? process.cwd())
|
|
11632
|
-
};
|
|
11633
|
-
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({
|
|
11634
|
-
harness: plan.profile.harness,
|
|
11635
|
-
baseUrl: plan.provider.baseUrl,
|
|
11636
|
-
protocol: plan.provider.protocol,
|
|
11637
|
-
model: plan.profile.model,
|
|
11638
|
-
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
11639
|
-
modelPolicy: plan.profile.modelPolicy,
|
|
11640
|
-
providerId: plan.provider.id,
|
|
11641
|
-
onRoutingEvent,
|
|
11642
|
-
reasoning: options.reasoning,
|
|
11643
|
-
dangerouslyBypassApprovalsAndSandbox: options.dangerouslyBypassApprovalsAndSandbox,
|
|
11644
|
-
credential,
|
|
11645
|
-
authStyle: plan.provider.authStyle,
|
|
11646
|
-
executable: nativeExecutable ?? detection?.executable,
|
|
11647
|
-
args: options.args ?? [],
|
|
11648
|
-
stateDir,
|
|
11649
|
-
cwd: resolve9(options.cwd ?? process.cwd()),
|
|
11650
|
-
version: detection?.version,
|
|
11651
|
-
...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo"].includes(plan.profile.harness) ? { sessionDir: join15(root, "sessions", plan.profile.harness, profileId) } : {}
|
|
11652
|
-
});
|
|
11653
|
-
cleanup = prepared.cleanup;
|
|
11654
|
-
if (options.desktop) {
|
|
11655
|
-
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join15(root, "desktop", profileId));
|
|
11656
|
-
cleanup = prepared.cleanup;
|
|
11657
|
-
}
|
|
11658
|
-
for (const warning of [...plan.warnings, ...prepared.warnings])
|
|
11659
|
-
console.error(`switcher: ${warning}`);
|
|
11660
|
-
const interruptPreparation = (error, cancel = true) => {
|
|
11661
|
-
if (preparationSignal)
|
|
11662
|
-
return;
|
|
11663
|
-
preparationSignal = error;
|
|
11664
|
-
createRunCancelled = true;
|
|
11665
|
-
preparationCleanup ??= cleanup?.().catch((error2) => {
|
|
11666
|
-
console.error(`switcher: Could not clean up the interrupted launch: ${error2 instanceof Error ? error2.message : "unknown cleanup failure"}.`);
|
|
11667
|
-
});
|
|
11668
|
-
if (cancel)
|
|
11669
|
-
cancelPreparation(preparationSignal);
|
|
11670
|
-
};
|
|
11671
|
-
const onPreparationSignal = (signal) => {
|
|
11672
|
-
if (preparationSignal)
|
|
11673
|
-
return;
|
|
11674
|
-
const exitCode = signal === "SIGINT" ? 130 : signal === "SIGTERM" ? 143 : 129;
|
|
11675
|
-
interruptPreparation(new CommandInterrupted(exitCode, "Launch was interrupted before the native harness started."));
|
|
11676
|
-
};
|
|
11677
|
-
const onInt = () => onPreparationSignal("SIGINT");
|
|
11678
|
-
const onTerm = () => onPreparationSignal("SIGTERM");
|
|
11679
|
-
const onHangup = () => onPreparationSignal("SIGHUP");
|
|
11680
|
-
const hasPreparation = Boolean(prepared.beforeLaunch);
|
|
11681
|
-
const needsPreparationCancellation = hasPreparation || launchDeadline !== undefined;
|
|
11682
|
-
if (needsPreparationCancellation) {
|
|
11683
|
-
process.on("SIGINT", onInt);
|
|
11684
|
-
process.on("SIGTERM", onTerm);
|
|
11685
|
-
process.on("SIGHUP", onHangup);
|
|
11686
|
-
const remaining = launchDeadline === undefined ? undefined : launchDeadline - Date.now();
|
|
11687
|
-
if (remaining !== undefined) {
|
|
11688
|
-
if (remaining <= 0)
|
|
11689
|
-
interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."));
|
|
11690
|
-
else
|
|
11691
|
-
preparationTimeout = setTimeout(() => interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started.")), remaining);
|
|
11692
|
-
}
|
|
11693
|
-
}
|
|
12208
|
+
closed = true;
|
|
11694
12209
|
try {
|
|
11695
|
-
|
|
11696
|
-
|
|
11697
|
-
|
|
11698
|
-
|
|
11699
|
-
|
|
11700
|
-
throw preparationSignal;
|
|
11701
|
-
const createRunPromise = client.createRun({ profileId, model: plan.profile.model, harness: plan.profile.harness, planToken: plan.planToken });
|
|
11702
|
-
lateCreateRunFinalization = createRunPromise.then(async (lateRun) => {
|
|
11703
|
-
if (!createRunCancelled)
|
|
11704
|
-
return;
|
|
11705
|
-
await finishRunOnce(lateRun, { status: "interrupted", exitCode: preparationSignal?.exitCode ?? 143 }, "switcher: A cancelled run could not be finalized; inspect the run through the API.");
|
|
11706
|
-
}).catch((error) => {
|
|
11707
|
-
if (createRunCancelled)
|
|
11708
|
-
console.error(`switcher: A cancelled run could not be created: ${error instanceof Error ? error.message : "unknown error"}.`);
|
|
11709
|
-
});
|
|
11710
|
-
try {
|
|
11711
|
-
run = await Promise.race([createRunPromise, preparationCancellation]);
|
|
11712
|
-
} catch (error) {
|
|
11713
|
-
createRunCancelled = true;
|
|
11714
|
-
throw error;
|
|
11715
|
-
}
|
|
11716
|
-
if (preparationSignal)
|
|
11717
|
-
throw preparationSignal;
|
|
11718
|
-
} finally {
|
|
11719
|
-
if (preparationTimeout)
|
|
11720
|
-
clearTimeout(preparationTimeout);
|
|
11721
|
-
if (needsPreparationCancellation) {
|
|
11722
|
-
process.off("SIGINT", onInt);
|
|
11723
|
-
process.off("SIGTERM", onTerm);
|
|
11724
|
-
process.off("SIGHUP", onHangup);
|
|
11725
|
-
}
|
|
11726
|
-
}
|
|
11727
|
-
const remainingRuntime = launchDeadline === undefined ? undefined : launchDeadline - Date.now();
|
|
11728
|
-
if (remainingRuntime !== undefined && remainingRuntime <= 0) {
|
|
11729
|
-
interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
|
|
11730
|
-
throw preparationSignal;
|
|
12210
|
+
await gateway?.cleanup();
|
|
12211
|
+
if (receipt)
|
|
12212
|
+
await restore(receipt);
|
|
12213
|
+
} finally {
|
|
12214
|
+
release();
|
|
11731
12215
|
}
|
|
11732
|
-
|
|
11733
|
-
|
|
11734
|
-
|
|
11735
|
-
|
|
11736
|
-
|
|
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
|
+
};
|
|
11737
12260
|
} catch (error) {
|
|
11738
|
-
await preparationCleanup;
|
|
11739
12261
|
try {
|
|
11740
|
-
await cleanup
|
|
11741
|
-
cleanup = undefined;
|
|
12262
|
+
await cleanup();
|
|
11742
12263
|
} catch {}
|
|
11743
|
-
if (run)
|
|
11744
|
-
await finishRunOnce(run, { status: preparationSignal ? "interrupted" : "failed", exitCode: preparationSignal?.exitCode ?? 1 }, "switcher: Could not persist final run status; inspect the run through the API.");
|
|
11745
12264
|
throw error;
|
|
11746
|
-
} finally {
|
|
11747
|
-
if (lateCreateRunFinalization) {
|
|
11748
|
-
let finalizationTimer;
|
|
11749
|
-
const finalizationTimeout = new Promise((resolve10) => {
|
|
11750
|
-
finalizationTimer = setTimeout(resolve10, LATE_RUN_FINALIZATION_TIMEOUT_MS);
|
|
11751
|
-
});
|
|
11752
|
-
try {
|
|
11753
|
-
await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
|
|
11754
|
-
} finally {
|
|
11755
|
-
if (finalizationTimer)
|
|
11756
|
-
clearTimeout(finalizationTimer);
|
|
11757
|
-
}
|
|
11758
|
-
}
|
|
11759
|
-
await preparationCleanup;
|
|
11760
|
-
try {
|
|
11761
|
-
await cleanup?.();
|
|
11762
|
-
} finally {
|
|
11763
|
-
await rm6(stateDir, { recursive: true, force: true });
|
|
11764
|
-
}
|
|
11765
12265
|
}
|
|
11766
12266
|
}
|
|
11767
12267
|
|
|
11768
|
-
// src/
|
|
11769
|
-
|
|
11770
|
-
|
|
11771
|
-
|
|
11772
|
-
|
|
11773
|
-
|
|
11774
|
-
|
|
11775
|
-
|
|
11776
|
-
} catch (error) {
|
|
11777
|
-
if (!absent(error))
|
|
11778
|
-
throw error;
|
|
11779
|
-
}
|
|
11780
|
-
if (existing) {
|
|
11781
|
-
if (Object.entries(options).some(([key, value]) => key !== "harness" && value !== undefined))
|
|
11782
|
-
throw new Fault(409, "provider_override", "This ID names a saved provider. Update it explicitly or use a different preset/provider ID.");
|
|
11783
|
-
return existing;
|
|
11784
|
-
}
|
|
11785
|
-
const desired = providerFromPreset(selector, options);
|
|
11786
|
-
try {
|
|
11787
|
-
existing = await client.getProvider(desired.id);
|
|
11788
|
-
} catch (error) {
|
|
11789
|
-
if (!absent(error))
|
|
11790
|
-
throw error;
|
|
11791
|
-
}
|
|
11792
|
-
if (!existing) {
|
|
11793
|
-
try {
|
|
11794
|
-
return await client.createProvider(desired);
|
|
11795
|
-
} catch (error) {
|
|
11796
|
-
if (!(error instanceof SwitcherError && error.status === 409))
|
|
11797
|
-
throw error;
|
|
11798
|
-
existing = await client.getProvider(desired.id);
|
|
11799
|
-
}
|
|
11800
|
-
}
|
|
11801
|
-
const { version, updatedAt, ...input } = existing;
|
|
11802
|
-
const { additionalModels: _savedAdditions, ...savedSettings } = parse2(providerInputSchema, input);
|
|
11803
|
-
const { additionalModels: _presetAdditions, ...presetSettings } = desired;
|
|
11804
|
-
if (JSON.stringify(savedSettings) !== JSON.stringify(presetSettings))
|
|
11805
|
-
throw new Fault(409, "provider_conflict", "A saved provider with this preset ID has different settings. Select its ID directly or update it explicitly.");
|
|
11806
|
-
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;
|
|
11807
12276
|
}
|
|
11808
|
-
|
|
11809
|
-
|
|
11810
|
-
|
|
11811
|
-
|
|
11812
|
-
|
|
11813
|
-
if (
|
|
11814
|
-
throw new
|
|
11815
|
-
|
|
11816
|
-
|
|
11817
|
-
|
|
11818
|
-
|
|
11819
|
-
|
|
11820
|
-
|
|
11821
|
-
|
|
11822
|
-
|
|
11823
|
-
|
|
11824
|
-
|
|
11825
|
-
|
|
11826
|
-
const visible = matching.slice(0, 30);
|
|
11827
|
-
console.error(`Models: ${matching.length} match${matching.length === 1 ? "" : "es"}${matching.length > 30 ? " (first 30 shown; type to narrow)" : ""}.`);
|
|
11828
|
-
visible.forEach((m, i) => console.error(` ${i + 1}. ${display(m.id)} \u2014 ${display(m.name)}${m.expiresOn ? ` (expires ${m.expiresOn}, inclusive UTC)` : ""}`));
|
|
11829
|
-
const answer = (await reader.question("Model number, exact model ID, or search text (Ctrl-C cancels): ", { signal: cancellation.signal }).catch((error) => {
|
|
11830
|
-
throw cancellation.signal.aborted ? cancellation.signal.reason : error;
|
|
11831
|
-
})).trim();
|
|
11832
|
-
if (/^[1-9]\d*$/.test(answer) && visible[Number(answer) - 1])
|
|
11833
|
-
return visible[Number(answer) - 1].id;
|
|
11834
|
-
if (eligible.some((m) => m.id === answer))
|
|
11835
|
-
return answer;
|
|
11836
|
-
query = answer;
|
|
11837
|
-
}
|
|
11838
|
-
} finally {
|
|
11839
|
-
reader.off("SIGINT", cancel);
|
|
11840
|
-
reader.off("close", cancel);
|
|
11841
|
-
process.off("SIGINT", cancel);
|
|
11842
|
-
process.off("SIGTERM", terminate);
|
|
11843
|
-
reader.close();
|
|
11844
|
-
}
|
|
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;
|
|
11845
12295
|
}
|
|
11846
|
-
async function
|
|
11847
|
-
|
|
11848
|
-
|
|
11849
|
-
|
|
11850
|
-
const
|
|
11851
|
-
|
|
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
|
+
});
|
|
11852
12360
|
try {
|
|
11853
|
-
|
|
11854
|
-
|
|
11855
|
-
|
|
11856
|
-
|
|
11857
|
-
|
|
11858
|
-
|
|
11859
|
-
|
|
11860
|
-
|
|
11861
|
-
|
|
11862
|
-
|
|
11863
|
-
|
|
11864
|
-
|
|
11865
|
-
|
|
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;
|
|
11866
12376
|
}
|
|
11867
|
-
if (existing.providerId !== desired.providerId || existing.harness !== harness || existing.model !== model3 || canonicalPolicyJSON(existing.modelPolicy ?? null) !== canonicalPolicyJSON(desired.modelPolicy ?? null))
|
|
11868
|
-
throw new Fault(409, "profile_conflict", "An existing launch profile has different settings. Select a saved profile explicitly.");
|
|
11869
|
-
return existing;
|
|
11870
12377
|
}
|
|
11871
|
-
|
|
11872
|
-
|
|
11873
|
-
|
|
11874
|
-
|
|
11875
|
-
|
|
11876
|
-
|
|
11877
|
-
|
|
11878
|
-
|
|
11879
|
-
|
|
11880
|
-
|
|
11881
|
-
|
|
11882
|
-
|
|
11883
|
-
|
|
11884
|
-
|
|
11885
|
-
|
|
11886
|
-
|
|
11887
|
-
|
|
11888
|
-
|
|
11889
|
-
|
|
11890
|
-
|
|
11891
|
-
|
|
11892
|
-
|
|
11893
|
-
|
|
11894
|
-
|
|
11895
|
-
|
|
11896
|
-
|
|
11897
|
-
|
|
11898
|
-
|
|
11899
|
-
|
|
11900
|
-
|
|
11901
|
-
|
|
11902
|
-
|
|
11903
|
-
|
|
11904
|
-
if (
|
|
11905
|
-
|
|
11906
|
-
|
|
11907
|
-
|
|
11908
|
-
|
|
11909
|
-
|
|
11910
|
-
|
|
11911
|
-
|
|
11912
|
-
|
|
11913
|
-
|
|
11914
|
-
|
|
11915
|
-
}
|
|
11916
|
-
path(name) {
|
|
11917
|
-
return join16(this.directory, parse2(reference, name) + ".json");
|
|
11918
|
-
}
|
|
11919
|
-
async readableDirectory() {
|
|
11920
|
-
for (const path of [switcherHome(this.env), join16(switcherHome(this.env), "config"), this.directory]) {
|
|
11921
|
-
let info;
|
|
11922
|
-
try {
|
|
11923
|
-
info = await lstat5(path);
|
|
11924
|
-
} catch (error) {
|
|
11925
|
-
if (error.code === "ENOENT")
|
|
11926
|
-
return false;
|
|
11927
|
-
throw error;
|
|
11928
|
-
}
|
|
11929
|
-
if (!info.isDirectory() || info.isSymbolicLink() || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid?.()))
|
|
11930
|
-
throw new Fault(500, "credential_binding_permissions", "Credential binding directories must be real, owner-only directories (mode 0700).");
|
|
11931
|
-
}
|
|
11932
|
-
return true;
|
|
11933
|
-
}
|
|
11934
|
-
async get(name) {
|
|
11935
|
-
const path = this.path(name);
|
|
11936
|
-
if (!await this.readableDirectory())
|
|
11937
|
-
return;
|
|
11938
|
-
let file;
|
|
11939
|
-
try {
|
|
11940
|
-
file = await open3(path, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
11941
|
-
} catch (error) {
|
|
11942
|
-
if (error.code === "ENOENT")
|
|
11943
|
-
return;
|
|
11944
|
-
throw new Fault(500, "credential_binding_unreadable", "Cannot safely open the local credential binding.");
|
|
11945
|
-
}
|
|
11946
|
-
try {
|
|
11947
|
-
const info = await file.stat();
|
|
11948
|
-
if (!info.isFile() || info.size > 32768 || process.platform !== "win32" && (info.mode & 63 || info.uid !== process.getuid?.()))
|
|
11949
|
-
throw new Fault(500, "credential_binding_permissions", "Credential binding must be an owner-only regular file (mode 0600).");
|
|
11950
|
-
let value;
|
|
11951
|
-
try {
|
|
11952
|
-
value = JSON.parse(await file.readFile("utf8"));
|
|
11953
|
-
} catch {
|
|
11954
|
-
throw new Fault(500, "credential_binding_invalid", "Credential binding must contain valid JSON.");
|
|
11955
|
-
}
|
|
11956
|
-
const binding = parse2(credentialBindingSchema, value);
|
|
11957
|
-
if (binding.credentialEnv !== name)
|
|
11958
|
-
throw new Fault(500, "credential_binding_invalid", "Credential binding reference does not match its filename.");
|
|
11959
|
-
return binding;
|
|
11960
|
-
} finally {
|
|
11961
|
-
await file.close();
|
|
11962
|
-
}
|
|
11963
|
-
}
|
|
11964
|
-
async list() {
|
|
11965
|
-
if (!await this.readableDirectory())
|
|
11966
|
-
return [];
|
|
11967
|
-
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") {
|
|
11968
12422
|
try {
|
|
11969
|
-
|
|
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.`);
|
|
11970
12426
|
} catch (error) {
|
|
11971
|
-
|
|
11972
|
-
return [];
|
|
12427
|
+
await rm6(stateDir, { recursive: true, force: true });
|
|
11973
12428
|
throw error;
|
|
11974
12429
|
}
|
|
11975
|
-
const result = [];
|
|
11976
|
-
for (const name of entries.sort())
|
|
11977
|
-
if (/^SWITCHER_PROVIDER_[A-Z0-9_]+\.json$/.test(name)) {
|
|
11978
|
-
const binding = await this.get(name.slice(0, -5));
|
|
11979
|
-
if (binding)
|
|
11980
|
-
result.push(binding);
|
|
11981
|
-
}
|
|
11982
|
-
return result;
|
|
11983
|
-
}
|
|
11984
|
-
async bind(input) {
|
|
11985
|
-
const binding = parse2(credentialBindingSchema, input);
|
|
11986
|
-
if (binding.source.kind === "vault")
|
|
11987
|
-
await validateVaultExecutable(binding.source.executable);
|
|
11988
|
-
await privateDirectory(switcherHome(this.env));
|
|
11989
|
-
await privateDirectory(join16(switcherHome(this.env), "config"));
|
|
11990
|
-
await privateDirectory(this.directory);
|
|
11991
|
-
const temporary = join16(this.directory, `.binding-${randomUUID5()}`);
|
|
11992
|
-
const file = await open3(temporary, "wx", 384);
|
|
11993
|
-
try {
|
|
11994
|
-
await file.writeFile(JSON.stringify(binding, null, 2) + `
|
|
11995
|
-
`);
|
|
11996
|
-
await file.sync();
|
|
11997
|
-
try {
|
|
11998
|
-
await link(temporary, this.path(binding.credentialEnv));
|
|
11999
|
-
} catch (error) {
|
|
12000
|
-
if (error.code !== "EEXIST")
|
|
12001
|
-
throw error;
|
|
12002
|
-
const existing = await this.get(binding.credentialEnv);
|
|
12003
|
-
if (existing && fingerprint(existing) === fingerprint(binding))
|
|
12004
|
-
return existing;
|
|
12005
|
-
throw new Fault(409, "credential_binding_exists", "A different binding already exists. Remove it explicitly before binding another credential account.");
|
|
12006
|
-
}
|
|
12007
|
-
} finally {
|
|
12008
|
-
await file.close();
|
|
12009
|
-
await unlink(temporary);
|
|
12010
|
-
}
|
|
12011
|
-
return binding;
|
|
12012
|
-
}
|
|
12013
|
-
async remove(name) {
|
|
12014
|
-
const binding = await this.get(name);
|
|
12015
|
-
if (!binding)
|
|
12016
|
-
throw new Fault(404, "credential_binding_missing", "No local credential binding exists for this reference.");
|
|
12017
|
-
await unlink(this.path(name));
|
|
12018
|
-
return { removed: name };
|
|
12019
|
-
}
|
|
12020
|
-
}
|
|
12021
|
-
function credentialReference(selector) {
|
|
12022
|
-
const name = selector.startsWith("SWITCHER_PROVIDER_") ? selector : getProviderPreset(selector).credentialEnv;
|
|
12023
|
-
if (!name)
|
|
12024
|
-
throw new Fault(400, "credential_reference_required", "Use the explicit SWITCHER_PROVIDER_ reference for this provider.");
|
|
12025
|
-
return parse2(reference, name);
|
|
12026
|
-
}
|
|
12027
|
-
async function inspectVaultExecutable(path, permitWritableFile = false) {
|
|
12028
|
-
let info, resolved;
|
|
12029
|
-
try {
|
|
12030
|
-
resolved = await realpath6(path);
|
|
12031
|
-
await access5(resolved, constants6.X_OK);
|
|
12032
|
-
info = await stat6(resolved);
|
|
12033
|
-
if (!info.isFile())
|
|
12034
|
-
throw new Error;
|
|
12035
|
-
} catch {
|
|
12036
|
-
throw new Fault(422, "vault_exec_unavailable", "The configured secrets CLI must be an installed executable file. Use --vault-cli with its absolute path.");
|
|
12037
12430
|
}
|
|
12038
|
-
|
|
12039
|
-
|
|
12040
|
-
|
|
12041
|
-
|
|
12042
|
-
|
|
12043
|
-
|
|
12044
|
-
|
|
12045
|
-
|
|
12046
|
-
|
|
12047
|
-
|
|
12048
|
-
|
|
12049
|
-
|
|
12050
|
-
|
|
12051
|
-
|
|
12052
|
-
|
|
12053
|
-
|
|
12054
|
-
|
|
12055
|
-
|
|
12056
|
-
|
|
12057
|
-
|
|
12058
|
-
|
|
12059
|
-
|
|
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())
|
|
12060
12476
|
};
|
|
12061
|
-
|
|
12062
|
-
|
|
12063
|
-
|
|
12064
|
-
|
|
12065
|
-
|
|
12066
|
-
|
|
12067
|
-
|
|
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;
|
|
12068
12501
|
}
|
|
12069
|
-
|
|
12070
|
-
|
|
12071
|
-
|
|
12072
|
-
|
|
12073
|
-
|
|
12074
|
-
|
|
12075
|
-
|
|
12076
|
-
|
|
12077
|
-
|
|
12078
|
-
|
|
12079
|
-
|
|
12080
|
-
|
|
12081
|
-
throw new Fault(422, "vault_exec_repair_unsafe", "Executable permission repair requires POSIX file permissions.");
|
|
12082
|
-
const resolved = await inspectVaultExecutable(path, true);
|
|
12083
|
-
const file = await open3(resolved, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
12084
|
-
const unsafe = () => new Fault(422, "vault_exec_repair_unsafe", "Executable ownership, type, links or contents changed; no trusted repair can be confirmed.");
|
|
12085
|
-
let temporary;
|
|
12086
|
-
try {
|
|
12087
|
-
const before = await file.stat();
|
|
12088
|
-
const limit = 256 * 1024 * 1024;
|
|
12089
|
-
if (!before.isFile() || before.uid !== process.getuid?.() || before.size > limit || before.mode & 3584)
|
|
12090
|
-
throw unsafe();
|
|
12091
|
-
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;
|
|
12092
|
-
const hash3 = async (target) => {
|
|
12093
|
-
const digest2 = createHash12("sha256");
|
|
12094
|
-
const buffer = Buffer.alloc(1024 * 1024);
|
|
12095
|
-
let position = 0;
|
|
12096
|
-
while (true) {
|
|
12097
|
-
const { bytesRead } = await file.read(buffer, 0, buffer.length, position);
|
|
12098
|
-
if (!bytesRead)
|
|
12099
|
-
break;
|
|
12100
|
-
position += bytesRead;
|
|
12101
|
-
if (position > limit)
|
|
12102
|
-
throw unsafe();
|
|
12103
|
-
const bytes = buffer.subarray(0, bytesRead);
|
|
12104
|
-
digest2.update(bytes);
|
|
12105
|
-
if (target)
|
|
12106
|
-
await target.writeFile(bytes);
|
|
12107
|
-
}
|
|
12108
|
-
if (position !== before.size || !sameFile(await file.stat()))
|
|
12109
|
-
throw unsafe();
|
|
12110
|
-
if (digest2.digest("hex") !== expectedSha256)
|
|
12111
|
-
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);
|
|
12112
12514
|
};
|
|
12113
|
-
|
|
12114
|
-
|
|
12115
|
-
|
|
12116
|
-
|
|
12117
|
-
|
|
12118
|
-
|
|
12119
|
-
|
|
12120
|
-
|
|
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
|
+
}
|
|
12121
12537
|
}
|
|
12122
|
-
temporary = join16(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
|
|
12123
|
-
const replacement = await open3(temporary, "wx", 384);
|
|
12124
12538
|
try {
|
|
12125
|
-
|
|
12126
|
-
|
|
12127
|
-
|
|
12128
|
-
|
|
12129
|
-
if (
|
|
12130
|
-
throw
|
|
12131
|
-
|
|
12132
|
-
|
|
12133
|
-
|
|
12134
|
-
|
|
12135
|
-
|
|
12136
|
-
|
|
12137
|
-
|
|
12138
|
-
|
|
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
|
+
});
|
|
12139
12554
|
try {
|
|
12140
|
-
await
|
|
12141
|
-
}
|
|
12142
|
-
|
|
12555
|
+
run = await Promise.race([createRunPromise, preparationCancellation]);
|
|
12556
|
+
} catch (error) {
|
|
12557
|
+
createRunCancelled = true;
|
|
12558
|
+
throw error;
|
|
12143
12559
|
}
|
|
12560
|
+
if (preparationSignal)
|
|
12561
|
+
throw preparationSignal;
|
|
12144
12562
|
} finally {
|
|
12145
|
-
|
|
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
|
+
}
|
|
12146
12570
|
}
|
|
12147
|
-
|
|
12148
|
-
|
|
12149
|
-
|
|
12150
|
-
|
|
12151
|
-
|
|
12152
|
-
|
|
12153
|
-
|
|
12154
|
-
|
|
12155
|
-
|
|
12156
|
-
|
|
12157
|
-
throw new Fault(400, "conflicting_options", "A credential reference does not also need --credential-env.");
|
|
12158
|
-
if (!allowedOrigins?.length)
|
|
12159
|
-
throw new Fault(400, "credential_origin_required", "Use --origin URL to authorize a custom credential destination.");
|
|
12160
|
-
return { credentialEnv: parse2(reference, selector), origins: allowedOrigins.map((value) => new URL(endpoint(value)).origin) };
|
|
12161
|
-
}
|
|
12162
|
-
const preset2 = getProviderPreset(selector);
|
|
12163
|
-
const credentialEnv = override ?? preset2.credentialEnv;
|
|
12164
|
-
if (!credentialEnv)
|
|
12165
|
-
throw new Fault(400, "credential_reference_required", "Use --credential-env for a preset without a default credential reference.");
|
|
12166
|
-
const origins = allowedOrigins ?? [...new Set(preset2.protocols.flatMap((route2) => route2.baseUrl ? [new URL(route2.baseUrl).origin] : []))];
|
|
12167
|
-
if (!origins.length)
|
|
12168
|
-
throw new Fault(400, "credential_origin_required", "Use --origin URL for this custom preset.");
|
|
12169
|
-
return { credentialEnv: parse2(reference, credentialEnv), origins };
|
|
12170
|
-
}
|
|
12171
|
-
async function readKeychain(source) {
|
|
12172
|
-
if (process.platform !== "darwin")
|
|
12173
|
-
throw new Fault(422, "keychain_unavailable", "This binding requires macOS Keychain. Use a supported vault binding or runtime environment on this station.");
|
|
12174
|
-
let stdout;
|
|
12175
|
-
try {
|
|
12176
|
-
({ 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;
|
|
12177
12581
|
} catch (error) {
|
|
12178
|
-
|
|
12179
|
-
|
|
12180
|
-
|
|
12181
|
-
|
|
12182
|
-
|
|
12183
|
-
|
|
12184
|
-
|
|
12185
|
-
throw
|
|
12186
|
-
|
|
12187
|
-
|
|
12188
|
-
|
|
12189
|
-
|
|
12190
|
-
|
|
12191
|
-
|
|
12192
|
-
|
|
12193
|
-
|
|
12194
|
-
|
|
12195
|
-
|
|
12196
|
-
|
|
12197
|
-
|
|
12198
|
-
|
|
12199
|
-
|
|
12200
|
-
|
|
12201
|
-
|
|
12202
|
-
|
|
12203
|
-
|
|
12204
|
-
if (!binding.origins.includes(new URL(provider.baseUrl).origin))
|
|
12205
|
-
throw new Fault(422, "credential_authority", "The local credential binding does not authorize this provider origin. Update the binding explicitly; no key was sent.");
|
|
12206
|
-
if (binding.source.kind === "keychain")
|
|
12207
|
-
return this.keychainRead(binding.source);
|
|
12208
|
-
return fetchVaultCredential(binding, this.env);
|
|
12209
|
-
}
|
|
12210
|
-
async check(name) {
|
|
12211
|
-
const binding = await this.bindings.get(name);
|
|
12212
|
-
if (!binding)
|
|
12213
|
-
throw new Fault(404, "credential_binding_missing", "No local credential binding exists for this reference.");
|
|
12214
|
-
if (binding.source.kind === "vault") {
|
|
12215
|
-
const output = await runVaultCommand(binding, ["get", binding.source.key, "--check"], this.env, {}, true);
|
|
12216
|
-
const match = /^key=\S+ length=(\d+) sha256=([a-f0-9]{64})\s*$/.exec(output);
|
|
12217
|
-
if (!match)
|
|
12218
|
-
throw new Fault(422, "vault_check_failed", "The secrets CLI did not return a supported credential check result.");
|
|
12219
|
-
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 });
|
|
12220
12608
|
}
|
|
12221
|
-
const value = await this.keychainRead(binding.source);
|
|
12222
|
-
return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash12("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
|
|
12223
12609
|
}
|
|
12224
12610
|
}
|
|
12225
|
-
var DELIVERY_URL = "SWITCHER_CREDENTIAL_DELIVERY_URL";
|
|
12226
|
-
var DELIVERY_NONCE = "SWITCHER_CREDENTIAL_DELIVERY_NONCE";
|
|
12227
|
-
var DELIVERY_VALUE = "SWITCHER_CREDENTIAL_DELIVERY_VALUE";
|
|
12228
12611
|
|
|
12229
|
-
|
|
12230
|
-
|
|
12231
|
-
|
|
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;
|
|
12232
12623
|
}
|
|
12233
|
-
|
|
12234
|
-
|
|
12235
|
-
|
|
12236
|
-
|
|
12237
|
-
|
|
12238
|
-
|
|
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);
|
|
12239
12630
|
try {
|
|
12240
|
-
|
|
12241
|
-
const pair = () => {
|
|
12242
|
-
const keys = clientTransportEnvKeys3("secrets");
|
|
12243
|
-
const configuredUrl = keys.apiUrlKeys.map((name) => env[name]).find((value) => value !== undefined) ?? keychainConfigValue2("secrets", env, options.keychain)?.value ?? appConfigDiskValue2("secrets", env, keys.apiUrlKeys)?.value;
|
|
12244
|
-
const resolution = resolveClientTransport("secrets", env, { credentials: options });
|
|
12245
|
-
const key = resolveCredential("secrets", env, options);
|
|
12246
|
-
if (key?.tier === "pointer")
|
|
12247
|
-
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.");
|
|
12248
|
-
if (!key?.apiKey || key.source !== resolution.apiKeySource || key.tier !== resolution.apiKeyTier)
|
|
12249
|
-
throw new Fault(422, "vault_operator_changed", "The vault operator changed during resolution; no credential was sent. Retry after configuration is stable.");
|
|
12250
|
-
const boundUrl = source.url ? toV1BaseUrl(source.url) : resolution.baseUrl;
|
|
12251
|
-
if (resolution.apiUrlSource !== "default" && boundUrl !== resolution.baseUrl)
|
|
12252
|
-
throw new Fault(422, "vault_operator_authority", "The binding vault URL conflicts with the canonical Secrets API URL; no credential was sent.");
|
|
12253
|
-
if (configuredUrl !== undefined && toV1BaseUrl(configuredUrl) !== resolution.baseUrl)
|
|
12254
|
-
throw new Fault(422, "vault_operator_changed", "The vault authority changed during resolution; no credential was sent.");
|
|
12255
|
-
return { key, url: configuredUrl?.trim() ?? source.url ?? boundUrl.replace(/\/v1$/, "") };
|
|
12256
|
-
};
|
|
12257
|
-
const first = pair(), second = pair();
|
|
12258
|
-
if (first.key.apiKey !== second.key.apiKey || first.key.source !== second.key.source || first.key.tier !== second.key.tier || first.url !== second.url)
|
|
12259
|
-
throw new Fault(422, "vault_operator_changed", "The vault operator or authority changed during resolution; no credential was sent. Retry after configuration is stable.");
|
|
12260
|
-
credential = second.key;
|
|
12261
|
-
url = second.url;
|
|
12262
|
-
} else {
|
|
12263
|
-
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 } });
|
|
12264
|
-
}
|
|
12631
|
+
existing = await client.getProvider(desired.id);
|
|
12265
12632
|
} catch (error) {
|
|
12266
|
-
if (error
|
|
12633
|
+
if (!absent(error))
|
|
12267
12634
|
throw error;
|
|
12268
|
-
const kind = error instanceof Error ? error.name : "";
|
|
12269
|
-
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)";
|
|
12270
|
-
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.`);
|
|
12271
12635
|
}
|
|
12272
|
-
if (!
|
|
12273
|
-
|
|
12274
|
-
|
|
12275
|
-
|
|
12276
|
-
|
|
12277
|
-
|
|
12278
|
-
|
|
12279
|
-
|
|
12280
|
-
|
|
12281
|
-
|
|
12282
|
-
}
|
|
12283
|
-
|
|
12284
|
-
if (
|
|
12285
|
-
throw new Fault(
|
|
12286
|
-
|
|
12287
|
-
throw new Fault(422, "vault_exec_unavailable", "Vault CLI bindings currently require POSIX process groups; use runtime environment injection on Windows.");
|
|
12288
|
-
const executable = await validateVaultExecutable(binding.source.executable);
|
|
12289
|
-
const childEnv = { ...await vaultEnvironment(binding, env), ...delivery };
|
|
12290
|
-
return new Promise((resolveResult, reject2) => {
|
|
12291
|
-
const child = spawn2(executable, args, { env: childEnv, stdio: ["ignore", captureCheck ? "pipe" : "ignore", "ignore"], detached: true, shell: false });
|
|
12292
|
-
let failure;
|
|
12293
|
-
let output = "";
|
|
12294
|
-
let cleaned = false;
|
|
12295
|
-
const kill = () => {
|
|
12296
|
-
if (child.pid) {
|
|
12297
|
-
try {
|
|
12298
|
-
process.kill(-child.pid, "SIGKILL");
|
|
12299
|
-
} catch {}
|
|
12300
|
-
}
|
|
12301
|
-
};
|
|
12302
|
-
const interrupt = (signal) => {
|
|
12303
|
-
failure = new CredentialInterrupted(signal === "SIGINT" ? 130 : 143);
|
|
12304
|
-
process.exitCode = signal === "SIGINT" ? 130 : 143;
|
|
12305
|
-
kill();
|
|
12306
|
-
};
|
|
12307
|
-
const onInt = () => interrupt("SIGINT");
|
|
12308
|
-
const onTerm = () => interrupt("SIGTERM");
|
|
12309
|
-
process.on("SIGINT", onInt);
|
|
12310
|
-
process.on("SIGTERM", onTerm);
|
|
12311
|
-
const timeout = setTimeout(() => {
|
|
12312
|
-
failure = new Fault(504, "vault_timeout", "Credential lookup exceeded 20 seconds; no alternate credential was selected.");
|
|
12313
|
-
kill();
|
|
12314
|
-
}, 20000);
|
|
12315
|
-
const cleanup = () => {
|
|
12316
|
-
if (cleaned)
|
|
12317
|
-
return;
|
|
12318
|
-
cleaned = true;
|
|
12319
|
-
clearTimeout(timeout);
|
|
12320
|
-
process.off("SIGINT", onInt);
|
|
12321
|
-
process.off("SIGTERM", onTerm);
|
|
12322
|
-
kill();
|
|
12323
|
-
};
|
|
12324
|
-
child.stdout?.on("data", (chunk) => {
|
|
12325
|
-
if (output.length + chunk.length > 4096) {
|
|
12326
|
-
failure = new Fault(422, "vault_check_failed", "The secrets CLI returned an oversized check result.");
|
|
12327
|
-
kill();
|
|
12328
|
-
} else
|
|
12329
|
-
output += chunk.toString("utf8");
|
|
12330
|
-
});
|
|
12331
|
-
child.once("error", () => {
|
|
12332
|
-
cleanup();
|
|
12333
|
-
reject2(new Fault(422, "vault_exec_failed", "The configured secrets CLI could not start; check its executable and permissions."));
|
|
12334
|
-
});
|
|
12335
|
-
child.once("exit", cleanup);
|
|
12336
|
-
child.once("close", (code) => {
|
|
12337
|
-
if (failure)
|
|
12338
|
-
reject2(failure);
|
|
12339
|
-
else if (code !== 0)
|
|
12340
|
-
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."));
|
|
12341
|
-
else
|
|
12342
|
-
resolveResult(output);
|
|
12343
|
-
});
|
|
12344
|
-
});
|
|
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;
|
|
12345
12651
|
}
|
|
12346
|
-
|
|
12347
|
-
if (
|
|
12348
|
-
|
|
12349
|
-
|
|
12350
|
-
|
|
12351
|
-
|
|
12352
|
-
|
|
12353
|
-
|
|
12354
|
-
|
|
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;
|
|
12355
12664
|
try {
|
|
12356
|
-
|
|
12357
|
-
} catch {
|
|
12358
|
-
|
|
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;
|
|
12359
12670
|
}
|
|
12360
|
-
if (
|
|
12361
|
-
|
|
12362
|
-
|
|
12363
|
-
|
|
12364
|
-
|
|
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);
|
|
12365
12706
|
try {
|
|
12366
|
-
|
|
12367
|
-
|
|
12368
|
-
|
|
12369
|
-
|
|
12370
|
-
|
|
12371
|
-
|
|
12372
|
-
|
|
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
|
+
}
|
|
12373
12721
|
} finally {
|
|
12374
|
-
|
|
12722
|
+
reader.off("SIGINT", cancel);
|
|
12723
|
+
reader.off("close", cancel);
|
|
12724
|
+
process.off("SIGINT", cancel);
|
|
12725
|
+
process.off("SIGTERM", terminate);
|
|
12726
|
+
reader.close();
|
|
12375
12727
|
}
|
|
12376
12728
|
}
|
|
12377
|
-
async function
|
|
12378
|
-
const
|
|
12379
|
-
const
|
|
12380
|
-
const
|
|
12381
|
-
|
|
12382
|
-
|
|
12383
|
-
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;
|
|
12384
12735
|
try {
|
|
12385
|
-
|
|
12386
|
-
} catch {
|
|
12387
|
-
|
|
12736
|
+
existing = await client.getProfile(desired.id);
|
|
12737
|
+
} catch (error) {
|
|
12738
|
+
if (!absent(error))
|
|
12739
|
+
throw error;
|
|
12388
12740
|
}
|
|
12389
|
-
if (
|
|
12390
|
-
|
|
12391
|
-
|
|
12392
|
-
|
|
12393
|
-
|
|
12394
|
-
|
|
12395
|
-
|
|
12396
|
-
|
|
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
|
+
}
|
|
12397
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;
|
|
12398
12753
|
}
|
|
12399
12754
|
|
|
12400
12755
|
// src/cli.ts
|
|
@@ -12458,6 +12813,16 @@ Use --catalog-format none for a manual catalog; otherwise discovery stays active
|
|
|
12458
12813
|
models update replaces saved metadata; omit expiry in its JSON to clear it.
|
|
12459
12814
|
models remove removes saved metadata, not entries in an upstream catalog.
|
|
12460
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.
|
|
12461
12826
|
Vault bindings use the installed secrets CLI and its canonical Contracts URL/key
|
|
12462
12827
|
by default. --vault-account pins a Keychain account; --vault-operator env requires
|
|
12463
12828
|
per-process HASNA_SECRETS_API_KEY. Explicit operators also require --vault-url.
|
|
@@ -12689,7 +13054,9 @@ async function main(args = process.argv.slice(2)) {
|
|
|
12689
13054
|
assertHarnessArguments(harness, nativeArgs);
|
|
12690
13055
|
await validateHarnessConfiguration(harness, values2.cwd ?? process.cwd(), nativeArgs);
|
|
12691
13056
|
}
|
|
12692
|
-
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));
|
|
12693
13060
|
const client = runtime.client;
|
|
12694
13061
|
try {
|
|
12695
13062
|
const presetOptions = () => ({
|
|
@@ -12730,12 +13097,19 @@ async function main(args = process.argv.slice(2)) {
|
|
|
12730
13097
|
if (timeoutMs !== undefined && (!Number.isFinite(timeoutMs) || timeoutMs <= 0))
|
|
12731
13098
|
throw new Error("--timeout must be positive seconds.");
|
|
12732
13099
|
let profileId = action2;
|
|
13100
|
+
let credentialPreflight;
|
|
13101
|
+
let resolvePreparedCredential;
|
|
12733
13102
|
if (values2.provider) {
|
|
12734
13103
|
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action2);
|
|
12735
13104
|
const modelPolicy = await readModelPolicy(values2["model-policy-file"], values2["role-model"]);
|
|
12736
13105
|
const provider = await resolveLaunchProvider(client, values2.provider, { ...presetOptions(), harness });
|
|
12737
13106
|
validateHarnessProvider(harness, provider);
|
|
12738
|
-
|
|
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"]));
|
|
12739
13113
|
const model3 = values2.model ?? await selectModel(catalog.models, values2.search, harness);
|
|
12740
13114
|
const selected = catalog.models.find((m) => m.id === model3);
|
|
12741
13115
|
if (!selected)
|
|
@@ -12751,11 +13125,17 @@ async function main(args = process.argv.slice(2)) {
|
|
|
12751
13125
|
if (values2.model || values2.protocol || values2.url || values2["credential-env"] || values2["model-policy-file"] || values2["role-model"])
|
|
12752
13126
|
throw new Error("Use --provider PROVIDER for a direct launch, or update the saved profile explicitly.");
|
|
12753
13127
|
const profile = await client.getProfile(profileId);
|
|
12754
|
-
if (profile.harness === "gemini")
|
|
12755
|
-
validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
|
|
12756
13128
|
assertHarnessArguments(profile.harness, nativeArgs);
|
|
12757
13129
|
await validateHarnessConfiguration(profile.harness, values2.cwd ?? process.cwd(), nativeArgs);
|
|
12758
|
-
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"]));
|
|
12759
13139
|
}
|
|
12760
13140
|
if (values2["dry-run"]) {
|
|
12761
13141
|
const plan = await client.launchPlan(profileId);
|
|
@@ -12774,7 +13154,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
12774
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" } } : {} });
|
|
12775
13155
|
return;
|
|
12776
13156
|
}
|
|
12777
|
-
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)) });
|
|
12778
13158
|
return;
|
|
12779
13159
|
}
|
|
12780
13160
|
if (editingModel) {
|