@hasna/switcher 0.2.6 → 0.2.8
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 +148 -8
- package/dist/antigravity-config.d.ts +7 -0
- package/dist/bedrock.d.ts +2 -0
- package/dist/chatgpt-launch.d.ts +2 -1
- package/dist/cli/index.js +1665 -267
- package/dist/codex-session-discovery.d.ts +24 -0
- package/dist/codex-state-bridge.d.ts +14 -0
- package/dist/codex-state-bridge.js +568 -0
- package/dist/domain.d.ts +18 -8
- package/dist/generated/api.d.ts +17 -5
- package/dist/harness-arguments.d.ts +8 -0
- package/dist/harness-types.d.ts +2 -0
- package/dist/harnesses.d.ts +2 -2
- package/dist/index.js +23 -4
- package/dist/junie-config.d.ts +8 -0
- package/dist/launcher.d.ts +4 -1
- package/dist/mcp/index.js +88 -11
- package/dist/model-policy-schema.d.ts +3 -0
- package/dist/model-policy.d.ts +1 -0
- package/dist/native-cli-settings.d.ts +6 -0
- package/dist/native-model-policy.d.ts +1 -1
- package/dist/native-state-import.d.ts +44 -0
- package/dist/native-state.d.ts +32 -0
- package/dist/sdk.d.ts +18 -9
- package/dist/sdk.js +23 -4
- package/dist/serve/index.js +78 -7
- package/docs/MODEL-POLICY.md +6 -2
- package/openapi.json +53 -1
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -480,6 +480,7 @@ var fallbacksSchema = z3.record(policyModelIdSchema, z3.array(policyModelIdSchem
|
|
|
480
480
|
});
|
|
481
481
|
var modelPolicySchema = z3.object({
|
|
482
482
|
version: z3.literal(1).default(1),
|
|
483
|
+
selection: z3.enum(["restricted", "catalog"]).optional(),
|
|
483
484
|
roles: z3.object({
|
|
484
485
|
subagent: policyModelIdSchema.optional(),
|
|
485
486
|
fast: policyModelIdSchema.optional(),
|
|
@@ -514,8 +515,8 @@ function canonicalPolicyJSON(value) {
|
|
|
514
515
|
}
|
|
515
516
|
|
|
516
517
|
// src/domain.ts
|
|
517
|
-
var VERSION = "0.2.
|
|
518
|
-
var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
518
|
+
var VERSION = "0.2.7";
|
|
519
|
+
var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "antigravity", "junie", "aider", "kilo"]);
|
|
519
520
|
var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
520
521
|
var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
521
522
|
var label = z4.string().min(1).max(200);
|
|
@@ -647,7 +648,7 @@ function compatible(harness, protocol) {
|
|
|
647
648
|
return protocol === "anthropic-messages";
|
|
648
649
|
if (harness === "codex")
|
|
649
650
|
return protocol === "openai-responses";
|
|
650
|
-
if (harness === "gemini")
|
|
651
|
+
if (harness === "gemini" || harness === "antigravity")
|
|
651
652
|
return protocol === "gemini-generate-content";
|
|
652
653
|
if (protocol === "gemini-generate-content")
|
|
653
654
|
return false;
|
|
@@ -656,7 +657,7 @@ function compatible(harness, protocol) {
|
|
|
656
657
|
function validateHarnessProvider(harness, provider) {
|
|
657
658
|
if (!compatible(harness, provider.protocol))
|
|
658
659
|
throw new Fault(422, "protocol_mismatch", "Harness does not support this provider protocol.");
|
|
659
|
-
if (harness === "gemini" && provider.authStyle !== "x-api-key")
|
|
660
|
+
if ((harness === "gemini" || harness === "antigravity") && provider.authStyle !== "x-api-key")
|
|
660
661
|
throw new Fault(422, "auth_mismatch", "Gemini CLI requires x-api-key authentication for its native generateContent protocol.");
|
|
661
662
|
}
|
|
662
663
|
function modelExpired(model, now = new Date) {
|
|
@@ -855,6 +856,8 @@ function aiderArguments(args) {
|
|
|
855
856
|
|
|
856
857
|
// src/harness-arguments.ts
|
|
857
858
|
var reserved2 = {
|
|
859
|
+
antigravity: ["--model", "--agent", "--remote-control", "--project", "--new-project"],
|
|
860
|
+
junie: ["--model", "--provider", "--auth", "-a", "--openai-api-key", "--anthropic-api-key", "--grok-api-key", "--openrouter-api-key", "--google-api-key", "--litellm-api-key", "--litellm-url", "--config-location", "--config-default-locations", "--model-location", "--model-default-locations", "--cache-dir", "-c", "--project", "-p", "--acp", "--gateway", "--gateway-stop", "--gateway-status"],
|
|
858
861
|
gemini: ["--model", "--no-model", "--no-m", "-m", "--settings", "--acp", "--experimental-acp", "--experimentalAcp"],
|
|
859
862
|
"prime-agent": ["--model", "--provider", "--api-key", "--models", "--session-dir", "--daemon-socket"],
|
|
860
863
|
hermes: ["--model", "-m", "--provider", "--config", "--profile", "-p", "--api-key", "--base-url", "--ignore-user-config", "--safe-mode", "--worktree", "-w"],
|
|
@@ -871,6 +874,8 @@ var reserved2 = {
|
|
|
871
874
|
omp: ["--model", "--provider", "--api-key", "--profile", "--cwd", "--config", "--session-dir", "--models", "--no-rules", "--smol", "--slow", "--plan", "--prewalk", "--prewalk-into", "--plan-yolo-into", "--plan-yolo", "--auto-approve", "--yolo", "--approval-mode", "--alias", "--plugin-dir", "--hook", "--extension", "-e", "--trusted-extension", "--from-claude", "--from-codex"]
|
|
872
875
|
};
|
|
873
876
|
var values = {
|
|
877
|
+
antigravity: ["--add-dir", "--conversation", "--effort", "-i", "--prompt-interactive", "--input-format", "--json-schema", "--log-file", "--mode", "--output-format", "-p", "--print", "--prompt", "--print-timeout"],
|
|
878
|
+
junie: ["--task", "--prompt", "--session-id", "--share-anonymous-statistics", "--input-format", "--output-format", "--json-output-file", "--agent-mode", "--guidelines-filename", "--ide-guidelines", "--effort", "--mcp-default-locations", "--mcp-location", "--extensions-default-location", "--skill-default-locations", "--skill-location", "--command-default-location", "--command-location", "--agent-default-location", "--agent-location"],
|
|
874
879
|
gemini: ["--prompt", "-p", "--prompt-interactive", "--promptInteractive", "-i", "--approval-mode", "--approvalMode", "--policy", "--admin-policy", "--adminPolicy", "--allowed-mcp-server-names", "--allowedMcpServerNames", "--extensions", "-e", "--session-file", "--sessionFile", "--session-id", "--sessionId", "--include-directories", "--includeDirectories", "--output-format", "--outputFormat", "-o", "--allowed-tools", "--allowedTools", "--delete-session", "--deleteSession"],
|
|
875
880
|
"prime-agent": ["--mode", "--system-prompt", "--append-system-prompt", "--name", "--session", "--session-id", "--fork", "--tools", "--exclude-tools", "--thinking", "--export", "--extension", "--skill", "--prompt-template", "--theme", "--use-theme", "--tui-mode", "--prompt", "--output-format"],
|
|
876
881
|
hermes: ["--model", "--provider", "--reasoning", "--toolsets", "--skills", "--resume", "--usage-file", "--in", "--oneshot", "--query", "--query-file", "--image", "--max-turns", "--run-budget", "--source"],
|
|
@@ -896,6 +901,7 @@ var optionalValues = {
|
|
|
896
901
|
omp: ["--resume", "-r", "--session"]
|
|
897
902
|
};
|
|
898
903
|
var short = {
|
|
904
|
+
junie: { required: "apc", optional: "", boolean: "hv" },
|
|
899
905
|
hermes: { required: "zmtsrqp", optional: "c", boolean: "VhvQw" },
|
|
900
906
|
cline: { required: "Pmksct", optional: "", boolean: "yz" },
|
|
901
907
|
codex: { required: "cimpsCao", optional: "", boolean: "hV" },
|
|
@@ -905,7 +911,66 @@ var short = {
|
|
|
905
911
|
"prime-agent": { required: "p", optional: "", boolean: "hv" },
|
|
906
912
|
gemini: { required: "mpieo", optional: "rw", boolean: "shvydl" }
|
|
907
913
|
};
|
|
908
|
-
var providerKeys = new Set(["model", "model_provider", "model_providers", "model_catalog_json", "review_model", "agents", "memories"]);
|
|
914
|
+
var providerKeys = new Set(["model", "model_provider", "provider", "model_providers", "model_catalog_json", "review_model", "agents", "memories"]);
|
|
915
|
+
function codexOptionTakesValue(option) {
|
|
916
|
+
return values.codex.includes(option) || option.length === 2 && option[0] === "-" && short.codex.required.includes(option[1]);
|
|
917
|
+
}
|
|
918
|
+
function codexOptionRequestsHelp(option) {
|
|
919
|
+
if (["--help", "--version", "-h", "-V"].includes(option))
|
|
920
|
+
return true;
|
|
921
|
+
if (!/^-[^-]/.test(option))
|
|
922
|
+
return false;
|
|
923
|
+
for (let index = 1;index < option.length; index++) {
|
|
924
|
+
const name = option[index];
|
|
925
|
+
if (name === "h" || name === "V")
|
|
926
|
+
return true;
|
|
927
|
+
if (short.codex.required.includes(name))
|
|
928
|
+
return false;
|
|
929
|
+
}
|
|
930
|
+
return false;
|
|
931
|
+
}
|
|
932
|
+
function codexConfigPath(key) {
|
|
933
|
+
if (key.length > 4096 || /[\r\n\0]/.test(key))
|
|
934
|
+
throw new Error("Invalid Codex configuration key.");
|
|
935
|
+
let value = Bun.TOML.parse(`${key} = 0`);
|
|
936
|
+
const path = [];
|
|
937
|
+
while (value !== 0) {
|
|
938
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
939
|
+
throw new Error("Invalid Codex configuration key.");
|
|
940
|
+
const entries = Object.entries(value);
|
|
941
|
+
if (entries.length !== 1)
|
|
942
|
+
throw new Error("Ambiguous Codex configuration key.");
|
|
943
|
+
path.push(entries[0][0]);
|
|
944
|
+
value = entries[0][1];
|
|
945
|
+
}
|
|
946
|
+
if (!path.length)
|
|
947
|
+
throw new Error("Invalid Codex configuration key.");
|
|
948
|
+
return path;
|
|
949
|
+
}
|
|
950
|
+
function codexConfigRoots(key) {
|
|
951
|
+
return [codexConfigPath(key)[0]];
|
|
952
|
+
}
|
|
953
|
+
function codexCommandIndex(args) {
|
|
954
|
+
for (let i = 0;i < args.length; i++) {
|
|
955
|
+
const arg = args[i];
|
|
956
|
+
if (arg === "--")
|
|
957
|
+
return -1;
|
|
958
|
+
if (!arg.startsWith("-"))
|
|
959
|
+
return i;
|
|
960
|
+
if (arg.startsWith("--")) {
|
|
961
|
+
if (!arg.includes("=") && values.codex.includes(arg))
|
|
962
|
+
i++;
|
|
963
|
+
continue;
|
|
964
|
+
}
|
|
965
|
+
for (let j = 1;j < arg.length; j++)
|
|
966
|
+
if (short.codex.required.includes(arg[j])) {
|
|
967
|
+
if (j === arg.length - 1)
|
|
968
|
+
i++;
|
|
969
|
+
break;
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
return -1;
|
|
973
|
+
}
|
|
909
974
|
function geminiPolicyArguments(input, originalHome) {
|
|
910
975
|
const args = [...input], expand = (value) => value.split(",").map((part) => {
|
|
911
976
|
const path = part.trim();
|
|
@@ -938,9 +1003,9 @@ function geminiPolicyArguments(input, originalHome) {
|
|
|
938
1003
|
function codexProviderOverride(value) {
|
|
939
1004
|
const key = value.slice(0, value.indexOf("=") < 0 ? value.length : value.indexOf("=")).trim();
|
|
940
1005
|
try {
|
|
941
|
-
return
|
|
1006
|
+
return codexConfigRoots(key).some((root) => providerKeys.has(root));
|
|
942
1007
|
} catch {
|
|
943
|
-
return /^(model|model_provider|model_providers|model_catalog_json|review_model|agents|memories)(?:\s*\.|\s*$)/.test(key);
|
|
1008
|
+
return /^(model|model_provider|provider|model_providers|model_catalog_json|review_model|agents|memories)(?:\s*\.|\s*$)/.test(key);
|
|
944
1009
|
}
|
|
945
1010
|
}
|
|
946
1011
|
function assertHarnessArguments(harness, args, options = {}) {
|
|
@@ -953,6 +1018,8 @@ function assertHarnessArguments(harness, args, options = {}) {
|
|
|
953
1018
|
return;
|
|
954
1019
|
}
|
|
955
1020
|
const blocked = new Set([...reserved2[harness], ...options.additionalReserved ?? []]);
|
|
1021
|
+
if (harness === "antigravity" && args[0] && !args[0].startsWith("-"))
|
|
1022
|
+
throw new Error("Antigravity subcommands are outside the managed inference launch; pass prompts with -p.");
|
|
956
1023
|
const reject = () => {
|
|
957
1024
|
throw new Error("Provider/model configuration arguments are reserved by the launch profile; update the profile instead.");
|
|
958
1025
|
};
|
|
@@ -969,7 +1036,16 @@ function assertHarnessArguments(harness, args, options = {}) {
|
|
|
969
1036
|
}
|
|
970
1037
|
}
|
|
971
1038
|
const config = (value) => {
|
|
972
|
-
if (harness
|
|
1039
|
+
if (harness !== "codex")
|
|
1040
|
+
return;
|
|
1041
|
+
const key = value.slice(0, value.indexOf("=") < 0 ? value.length : value.indexOf("=")).trim();
|
|
1042
|
+
let reserved3 = false;
|
|
1043
|
+
try {
|
|
1044
|
+
reserved3 = codexConfigRoots(key).some((root) => options.reservedCodexRoots?.includes(root));
|
|
1045
|
+
} catch {
|
|
1046
|
+
reserved3 = Boolean(options.reservedCodexRoots?.some((root) => new RegExp(`^${root.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s*\\.|\\s*$)`).test(key)));
|
|
1047
|
+
}
|
|
1048
|
+
if (options.reserveCodexConfig || codexProviderOverride(value) || reserved3)
|
|
973
1049
|
reject();
|
|
974
1050
|
};
|
|
975
1051
|
let hermesChat = false;
|
|
@@ -984,6 +1060,8 @@ function assertHarnessArguments(harness, args, options = {}) {
|
|
|
984
1060
|
}
|
|
985
1061
|
const equals = arg.indexOf("=");
|
|
986
1062
|
let flag = equals < 0 ? arg : arg.slice(0, equals);
|
|
1063
|
+
if (harness === "antigravity" && /^-[^-].+/.test(flag))
|
|
1064
|
+
flag = "-" + flag;
|
|
987
1065
|
if (harness === "hermes" && flag.startsWith("--")) {
|
|
988
1066
|
if ([...blocked].some((option) => option.startsWith(flag)))
|
|
989
1067
|
reject();
|
|
@@ -1065,6 +1143,19 @@ async function boundedJson(response, maxBytes = MAX_BYTES) {
|
|
|
1065
1143
|
// src/sdk.ts
|
|
1066
1144
|
import { createClientTransport } from "@hasna/contracts/client";
|
|
1067
1145
|
|
|
1146
|
+
// src/bedrock.ts
|
|
1147
|
+
function bedrockMantleOrigin(value) {
|
|
1148
|
+
let url;
|
|
1149
|
+
try {
|
|
1150
|
+
url = new URL(value);
|
|
1151
|
+
} catch {
|
|
1152
|
+
return;
|
|
1153
|
+
}
|
|
1154
|
+
if (url.protocol !== "https:" || url.port || url.username || url.password || url.search || url.hash || url.pathname.replace(/\/+$/, "") !== "/anthropic/v1")
|
|
1155
|
+
return;
|
|
1156
|
+
return /^bedrock-mantle\.[a-z]{2}(?:-[a-z]+)+-\d+\.api\.aws$/.test(url.hostname) ? url.origin : undefined;
|
|
1157
|
+
}
|
|
1158
|
+
|
|
1068
1159
|
// src/presets.ts
|
|
1069
1160
|
var route = (protocol, baseUrl, options = {}) => ({
|
|
1070
1161
|
protocol,
|
|
@@ -1097,8 +1188,10 @@ var providerPresets = [
|
|
|
1097
1188
|
], ["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"),
|
|
1098
1189
|
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"),
|
|
1099
1190
|
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"),
|
|
1191
|
+
preset("bedrock", "Amazon Bedrock (Mantle)", [route("anthropic-messages", undefined, { authStyle: "x-api-key", catalogAuthStyle: "bearer", notes: ["Pass the regional https://bedrock-mantle.<region>.api.aws/anthropic/v1 endpoint and a Bedrock API key. The authenticated catalog is /v1/models on that same origin. Model access and regional availability remain controlled by the AWS account; this route does not distribute or inherit AWS administrative credentials."] })], ["https://docs.aws.amazon.com/bedrock/latest/userguide/inference-messages-api.html", "https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html"], "AWS_BEARER_TOKEN_BEDROCK"),
|
|
1100
1192
|
preset("gemini", "Google Gemini", [route("gemini-generate-content", "https://generativelanguage.googleapis.com/v1beta", {
|
|
1101
1193
|
authStyle: "x-api-key",
|
|
1194
|
+
credentialCheck: { method: "GET", path: "models" },
|
|
1102
1195
|
catalogBaseUrl: "https://generativelanguage.googleapis.com/v1beta",
|
|
1103
1196
|
catalogFormat: "gemini",
|
|
1104
1197
|
catalogAuthStyle: "x-api-key",
|
|
@@ -1169,16 +1262,19 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
1169
1262
|
const baseUrl = options.baseUrl ?? selected.baseUrl;
|
|
1170
1263
|
if (!baseUrl)
|
|
1171
1264
|
throw new Fault(400, "endpoint_required", "This preset requires an explicit --url for its inference endpoint.");
|
|
1265
|
+
const bedrockOrigin = presetId === "bedrock" ? bedrockMantleOrigin(endpoint(baseUrl)) : undefined;
|
|
1266
|
+
if (presetId === "bedrock" && !bedrockOrigin)
|
|
1267
|
+
throw new Fault(400, "invalid_url", "Bedrock requires a regional HTTPS Mantle endpoint ending in /anthropic/v1.");
|
|
1172
1268
|
if (presetId === "azure-openai" && !/\/openai\/v1$/.test(endpoint(baseUrl)))
|
|
1173
1269
|
throw new Fault(400, "invalid_url", "Azure OpenAI v1 requires an explicit endpoint ending in /openai/v1; deployment and api-version URLs are unsupported.");
|
|
1174
1270
|
if (options.baseUrl && selected.baseUrl && new URL(endpoint(options.baseUrl)).origin !== new URL(selected.baseUrl).origin && preset2.credentialEnv && !options.credentialEnv)
|
|
1175
1271
|
throw new Fault(422, "credential_authority", "An endpoint on another origin requires an explicit --credential-env reference.");
|
|
1176
|
-
const suffix = selected.protocol === "anthropic-messages" ? "messages" : selected.protocol === "openai-responses" ? "responses" : "chat";
|
|
1272
|
+
const suffix = selected.protocol === "anthropic-messages" ? "messages" : selected.protocol === "openai-responses" ? "responses" : selected.protocol === "gemini-generate-content" ? "generate-content" : "chat";
|
|
1177
1273
|
if (presetId === "fireworks" && !options.catalogBaseUrl && !options.catalogAccountId)
|
|
1178
1274
|
throw new Fault(400, "catalog_account_required", "Fireworks model discovery requires --catalog-account-id or an explicit --catalog-url.");
|
|
1179
1275
|
if (selected.catalogFormat === "none" && options.catalogFormat && options.catalogFormat !== "none" && !options.catalogBaseUrl)
|
|
1180
1276
|
throw new Fault(400, "catalog_url_required", "This preset requires an explicit --catalog-url when enabling a catalog parser.");
|
|
1181
|
-
const catalogBaseUrl = options.catalogBaseUrl ?? (presetId === "fireworks" && options.catalogAccountId ? `https://api.fireworks.ai/v1/accounts/${encodeURIComponent(options.catalogAccountId)}` : options.baseUrl ? undefined : selected.catalogBaseUrl);
|
|
1277
|
+
const catalogBaseUrl = options.catalogBaseUrl ?? (bedrockOrigin ? `${bedrockOrigin}/v1` : presetId === "fireworks" && options.catalogAccountId ? `https://api.fireworks.ai/v1/accounts/${encodeURIComponent(options.catalogAccountId)}` : options.baseUrl ? undefined : selected.catalogBaseUrl);
|
|
1182
1278
|
return parse2(providerInputSchema, {
|
|
1183
1279
|
id: options.id ?? `${preset2.id}-${suffix}`,
|
|
1184
1280
|
name: preset2.name,
|
|
@@ -1207,7 +1303,7 @@ function providerCredential(provider, env = process.env) {
|
|
|
1207
1303
|
return;
|
|
1208
1304
|
let value = env[provider.credentialEnv];
|
|
1209
1305
|
if (!value) {
|
|
1210
|
-
const preset2 = providerPresets.find((p) => p.credentialEnv === provider.credentialEnv && p.protocols.some((route2) => route2.protocol === provider.protocol && (route2.baseUrl ? new URL(route2.baseUrl).origin === new URL(provider.baseUrl).origin : p.id === "azure-openai")));
|
|
1306
|
+
const preset2 = providerPresets.find((p) => p.credentialEnv === provider.credentialEnv && p.protocols.some((route2) => route2.protocol === provider.protocol && (route2.baseUrl ? new URL(route2.baseUrl).origin === new URL(provider.baseUrl).origin : p.id === "azure-openai" || p.id === "bedrock" && !!bedrockMantleOrigin(provider.baseUrl))));
|
|
1211
1307
|
value = preset2?.credentialAliases.map((name) => env[name]).find(Boolean);
|
|
1212
1308
|
}
|
|
1213
1309
|
if (value && /[\r\n]/.test(value))
|
|
@@ -2147,6 +2243,8 @@ async function discoverBase(provider, env = process.env, resolveCredential) {
|
|
|
2147
2243
|
reasoningEfforts: row.reasoning?.supported_efforts,
|
|
2148
2244
|
...provider.catalogFormat === "gemini" && row.supportedGenerationMethods !== undefined ? { supportedGenerationMethods: row.supportedGenerationMethods } : {}
|
|
2149
2245
|
};
|
|
2246
|
+
if (provider.protocol === "anthropic-messages" && bedrockMantleOrigin(provider.baseUrl) && !id.startsWith("anthropic."))
|
|
2247
|
+
candidate.available = false;
|
|
2150
2248
|
if (provider.catalogFormat === "mistral") {
|
|
2151
2249
|
const capabilities = row.capabilities;
|
|
2152
2250
|
if (typeof capabilities?.function_calling === "boolean")
|
|
@@ -2312,6 +2410,7 @@ function compileModelPolicy(model, catalog, policy) {
|
|
|
2312
2410
|
throw new Fault(400, "invalid_model_policy", "Model policy allowedModels is too large.");
|
|
2313
2411
|
for (const value of explicitAllowed)
|
|
2314
2412
|
requireAvailable(value, "An allowed model is not present in the eligible catalog.");
|
|
2413
|
+
const catalogAllowed = p.selection === "catalog" ? [...available] : [];
|
|
2315
2414
|
const aliases = Object.create(null);
|
|
2316
2415
|
for (const [name, target] of Object.entries(p.aliases ?? {})) {
|
|
2317
2416
|
if (Object.keys(aliases).length >= 200 || !/^[A-Za-z0-9._/-]{1,120}$/.test(name) || ["__proto__", "prototype", "constructor"].includes(name))
|
|
@@ -2323,7 +2422,7 @@ function compileModelPolicy(model, catalog, policy) {
|
|
|
2323
2422
|
aliases[name] = canonical;
|
|
2324
2423
|
}
|
|
2325
2424
|
const fallbacks = Object.create(null);
|
|
2326
|
-
const allowedSources = new Set([selected, ...Object.values(compiledRoles), ...explicitAllowed]);
|
|
2425
|
+
const allowedSources = new Set([selected, ...Object.values(compiledRoles), ...explicitAllowed, ...catalogAllowed]);
|
|
2327
2426
|
for (const [source, targets] of Object.entries(p.fallbacks ?? {})) {
|
|
2328
2427
|
if (!allowedSources.has(source) || !available.has(source) || !Array.isArray(targets) || Object.keys(fallbacks).length >= 200 || targets.length > 20)
|
|
2329
2428
|
throw new Fault(400, "invalid_model_policy", "Fallback source or list is invalid.");
|
|
@@ -2334,7 +2433,7 @@ function compileModelPolicy(model, catalog, policy) {
|
|
|
2334
2433
|
throw new Fault(400, "invalid_model_policy", "A model cannot fall back to itself.");
|
|
2335
2434
|
fallbacks[source] = uniq(values2);
|
|
2336
2435
|
}
|
|
2337
|
-
const allowedModels = uniq([selected, ...Object.values(compiledRoles), ...explicitAllowed, ...Object.values(fallbacks).flat()]).sort();
|
|
2436
|
+
const allowedModels = uniq([selected, ...Object.values(compiledRoles), ...explicitAllowed, ...catalogAllowed, ...Object.values(fallbacks).flat()]).sort();
|
|
2338
2437
|
if (Object.values(aliases).some((value) => !allowedModels.includes(value)))
|
|
2339
2438
|
throw new Fault(422, "model_not_allowed", "A model alias target must be explicitly allowed by the launch policy.");
|
|
2340
2439
|
const result = { version: 1, model: selected, roles: compiledRoles, allowedModels, aliases, fallbacks };
|
|
@@ -2440,7 +2539,7 @@ var openapi_default = {
|
|
|
2440
2539
|
openapi: "3.0.3",
|
|
2441
2540
|
info: {
|
|
2442
2541
|
title: "Switcher API",
|
|
2443
|
-
version: "0.2.
|
|
2542
|
+
version: "0.2.7",
|
|
2444
2543
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2445
2544
|
},
|
|
2446
2545
|
security: [
|
|
@@ -4513,6 +4612,8 @@ var openapi_default = {
|
|
|
4513
4612
|
"hermes",
|
|
4514
4613
|
"prime-agent",
|
|
4515
4614
|
"gemini",
|
|
4615
|
+
"antigravity",
|
|
4616
|
+
"junie",
|
|
4516
4617
|
"aider",
|
|
4517
4618
|
"kilo"
|
|
4518
4619
|
]
|
|
@@ -4532,6 +4633,13 @@ var openapi_default = {
|
|
|
4532
4633
|
],
|
|
4533
4634
|
default: 1
|
|
4534
4635
|
},
|
|
4636
|
+
selection: {
|
|
4637
|
+
type: "string",
|
|
4638
|
+
enum: [
|
|
4639
|
+
"restricted",
|
|
4640
|
+
"catalog"
|
|
4641
|
+
]
|
|
4642
|
+
},
|
|
4535
4643
|
roles: {
|
|
4536
4644
|
type: "object",
|
|
4537
4645
|
properties: {
|
|
@@ -4662,6 +4770,8 @@ var openapi_default = {
|
|
|
4662
4770
|
"hermes",
|
|
4663
4771
|
"prime-agent",
|
|
4664
4772
|
"gemini",
|
|
4773
|
+
"antigravity",
|
|
4774
|
+
"junie",
|
|
4665
4775
|
"aider",
|
|
4666
4776
|
"kilo"
|
|
4667
4777
|
]
|
|
@@ -4681,6 +4791,13 @@ var openapi_default = {
|
|
|
4681
4791
|
],
|
|
4682
4792
|
default: 1
|
|
4683
4793
|
},
|
|
4794
|
+
selection: {
|
|
4795
|
+
type: "string",
|
|
4796
|
+
enum: [
|
|
4797
|
+
"restricted",
|
|
4798
|
+
"catalog"
|
|
4799
|
+
]
|
|
4800
|
+
},
|
|
4684
4801
|
roles: {
|
|
4685
4802
|
type: "object",
|
|
4686
4803
|
properties: {
|
|
@@ -4891,6 +5008,13 @@ var openapi_default = {
|
|
|
4891
5008
|
],
|
|
4892
5009
|
default: 1
|
|
4893
5010
|
},
|
|
5011
|
+
selection: {
|
|
5012
|
+
type: "string",
|
|
5013
|
+
enum: [
|
|
5014
|
+
"restricted",
|
|
5015
|
+
"catalog"
|
|
5016
|
+
]
|
|
5017
|
+
},
|
|
4894
5018
|
roles: {
|
|
4895
5019
|
type: "object",
|
|
4896
5020
|
properties: {
|
|
@@ -5660,6 +5784,8 @@ var openapi_default = {
|
|
|
5660
5784
|
"hermes",
|
|
5661
5785
|
"prime-agent",
|
|
5662
5786
|
"gemini",
|
|
5787
|
+
"antigravity",
|
|
5788
|
+
"junie",
|
|
5663
5789
|
"aider",
|
|
5664
5790
|
"kilo"
|
|
5665
5791
|
]
|
|
@@ -5679,6 +5805,13 @@ var openapi_default = {
|
|
|
5679
5805
|
],
|
|
5680
5806
|
default: 1
|
|
5681
5807
|
},
|
|
5808
|
+
selection: {
|
|
5809
|
+
type: "string",
|
|
5810
|
+
enum: [
|
|
5811
|
+
"restricted",
|
|
5812
|
+
"catalog"
|
|
5813
|
+
]
|
|
5814
|
+
},
|
|
5682
5815
|
roles: {
|
|
5683
5816
|
type: "object",
|
|
5684
5817
|
properties: {
|
|
@@ -5952,6 +6085,8 @@ var openapi_default = {
|
|
|
5952
6085
|
"hermes",
|
|
5953
6086
|
"prime-agent",
|
|
5954
6087
|
"gemini",
|
|
6088
|
+
"antigravity",
|
|
6089
|
+
"junie",
|
|
5955
6090
|
"aider",
|
|
5956
6091
|
"kilo"
|
|
5957
6092
|
]
|
|
@@ -5971,6 +6106,13 @@ var openapi_default = {
|
|
|
5971
6106
|
],
|
|
5972
6107
|
default: 1
|
|
5973
6108
|
},
|
|
6109
|
+
selection: {
|
|
6110
|
+
type: "string",
|
|
6111
|
+
enum: [
|
|
6112
|
+
"restricted",
|
|
6113
|
+
"catalog"
|
|
6114
|
+
]
|
|
6115
|
+
},
|
|
5974
6116
|
roles: {
|
|
5975
6117
|
type: "object",
|
|
5976
6118
|
properties: {
|
|
@@ -6217,6 +6359,8 @@ var openapi_default = {
|
|
|
6217
6359
|
"hermes",
|
|
6218
6360
|
"prime-agent",
|
|
6219
6361
|
"gemini",
|
|
6362
|
+
"antigravity",
|
|
6363
|
+
"junie",
|
|
6220
6364
|
"aider",
|
|
6221
6365
|
"kilo"
|
|
6222
6366
|
]
|
|
@@ -6236,6 +6380,13 @@ var openapi_default = {
|
|
|
6236
6380
|
],
|
|
6237
6381
|
default: 1
|
|
6238
6382
|
},
|
|
6383
|
+
selection: {
|
|
6384
|
+
type: "string",
|
|
6385
|
+
enum: [
|
|
6386
|
+
"restricted",
|
|
6387
|
+
"catalog"
|
|
6388
|
+
]
|
|
6389
|
+
},
|
|
6239
6390
|
roles: {
|
|
6240
6391
|
type: "object",
|
|
6241
6392
|
properties: {
|
|
@@ -7289,6 +7440,164 @@ async function prepareGemini(input) {
|
|
|
7289
7440
|
] };
|
|
7290
7441
|
}
|
|
7291
7442
|
|
|
7443
|
+
// src/antigravity-config.ts
|
|
7444
|
+
import { join as join7 } from "path";
|
|
7445
|
+
import { readFile as readFile3, writeFile as writeFile5, lstat as lstat4 } from "fs/promises";
|
|
7446
|
+
|
|
7447
|
+
// src/native-cli-settings.ts
|
|
7448
|
+
import { lstat as lstat3, readFile as readFile2, writeFile as writeFile4, symlink as symlink2 } from "fs/promises";
|
|
7449
|
+
import { join as join6, isAbsolute as isAbsolute6 } from "path";
|
|
7450
|
+
import { homedir as homedir5 } from "os";
|
|
7451
|
+
function nativeHome(env) {
|
|
7452
|
+
const home = env.HOME ?? homedir5();
|
|
7453
|
+
if (!isAbsolute6(home))
|
|
7454
|
+
throw new Error("Native CLI requires an absolute home.");
|
|
7455
|
+
return home;
|
|
7456
|
+
}
|
|
7457
|
+
async function readNativeSettings(path) {
|
|
7458
|
+
let file;
|
|
7459
|
+
try {
|
|
7460
|
+
file = await lstat3(path);
|
|
7461
|
+
} catch (error) {
|
|
7462
|
+
if (error.code === "ENOENT")
|
|
7463
|
+
return {};
|
|
7464
|
+
throw error;
|
|
7465
|
+
}
|
|
7466
|
+
if (!file.isFile() || file.size > 1024 * 1024)
|
|
7467
|
+
throw new Error("Native CLI settings must be a bounded regular file.");
|
|
7468
|
+
let value;
|
|
7469
|
+
try {
|
|
7470
|
+
value = JSON.parse(await readFile2(path, "utf8"));
|
|
7471
|
+
} catch {
|
|
7472
|
+
throw new Error("Native CLI settings must contain a JSON object.");
|
|
7473
|
+
}
|
|
7474
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
7475
|
+
throw new Error("Native CLI settings must contain a JSON object.");
|
|
7476
|
+
return value;
|
|
7477
|
+
}
|
|
7478
|
+
function rejectNativeRouting(value, keys) {
|
|
7479
|
+
if (!value || typeof value !== "object")
|
|
7480
|
+
return;
|
|
7481
|
+
for (const [key, item] of Object.entries(value)) {
|
|
7482
|
+
const normalized = key.toLowerCase().replace(/[-_]/g, "");
|
|
7483
|
+
if (keys.has(normalized))
|
|
7484
|
+
throw new Error("Native CLI routing configuration conflicts with the Switcher launch profile.");
|
|
7485
|
+
rejectNativeRouting(item, keys);
|
|
7486
|
+
}
|
|
7487
|
+
}
|
|
7488
|
+
async function writeNativeSettings(path, value) {
|
|
7489
|
+
await writeFile4(path, JSON.stringify(value, null, 2) + `
|
|
7490
|
+
`, { mode: 384, flag: "wx" });
|
|
7491
|
+
return path;
|
|
7492
|
+
}
|
|
7493
|
+
async function durableNativeDirectory(root, target, name) {
|
|
7494
|
+
const directory = join6(target, name);
|
|
7495
|
+
await privateDirectory(directory);
|
|
7496
|
+
await symlink2(directory, join6(root, name), "dir");
|
|
7497
|
+
}
|
|
7498
|
+
async function readNativeText(path) {
|
|
7499
|
+
let file;
|
|
7500
|
+
try {
|
|
7501
|
+
file = await lstat3(path);
|
|
7502
|
+
} catch (error) {
|
|
7503
|
+
if (error.code === "ENOENT")
|
|
7504
|
+
return;
|
|
7505
|
+
throw error;
|
|
7506
|
+
}
|
|
7507
|
+
if (!file.isFile() || file.size > 1024 * 1024)
|
|
7508
|
+
throw new Error("Native CLI policy and instructions must be bounded regular files.");
|
|
7509
|
+
const text = await readFile2(path, "utf8");
|
|
7510
|
+
if (Buffer.byteLength(text) > 1024 * 1024)
|
|
7511
|
+
throw new Error("Native CLI policy and instructions exceed their size limit.");
|
|
7512
|
+
return text;
|
|
7513
|
+
}
|
|
7514
|
+
|
|
7515
|
+
// src/antigravity-config.ts
|
|
7516
|
+
var antigravityHelperModel = "gemini-3.1-flash-lite-preview";
|
|
7517
|
+
var routing = new Set(["custommodels", "custommodelsconfig", "apikey", "baseurl", "modelconfig", "modelconfigoverrides"]);
|
|
7518
|
+
async function validateAntigravityConfiguration(cwd, env = process.env) {
|
|
7519
|
+
const home = nativeHome(env), paths = [join7(home, ".gemini", "config", "config.json"), join7(home, ".gemini", "antigravity-cli", "settings.json"), join7(cwd, ".gemini", "antigravity-cli", "settings.json")];
|
|
7520
|
+
const layers = [];
|
|
7521
|
+
for (const path of [...new Set(paths)]) {
|
|
7522
|
+
const settings2 = await readNativeSettings(path);
|
|
7523
|
+
rejectNativeRouting(settings2, routing);
|
|
7524
|
+
layers.push(settings2);
|
|
7525
|
+
}
|
|
7526
|
+
if (cwd !== home && Object.keys(layers.at(-1) ?? {}).length)
|
|
7527
|
+
throw new Error("Antigravity project settings are not a supported native routing or permission source.");
|
|
7528
|
+
return { home, settings: Object.assign({}, ...layers) };
|
|
7529
|
+
}
|
|
7530
|
+
async function prepareAntigravity(input) {
|
|
7531
|
+
const original = await validateAntigravityConfiguration(input.cwd);
|
|
7532
|
+
const home = join7(input.stateDir, "antigravity-home"), gemini = join7(home, ".gemini"), dir = join7(gemini, "antigravity-cli"), shared = join7(gemini, "config");
|
|
7533
|
+
for (const path2 of [home, gemini, dir, shared])
|
|
7534
|
+
await privateDirectory(path2);
|
|
7535
|
+
const durable = join7(input.sessionDir ?? join7(input.stateDir, "sessions"), "antigravity");
|
|
7536
|
+
await privateDirectory(durable);
|
|
7537
|
+
for (const name of ["conversations", "brain", "annotations", "knowledge", "cache"])
|
|
7538
|
+
await durableNativeDirectory(dir, durable, name);
|
|
7539
|
+
await durableNativeDirectory(shared, join7(durable, "shared"), "projects");
|
|
7540
|
+
const settings2 = { ...original.settings, modelProvider: "gemini", customModelsConfig: { customModels: { switcher: { modelName: input.model } } } };
|
|
7541
|
+
const path = await writeNativeSettings(join7(dir, "settings.json"), settings2);
|
|
7542
|
+
const context = join7(original.home, ".gemini", "GEMINI.md");
|
|
7543
|
+
try {
|
|
7544
|
+
const file = await lstat4(context);
|
|
7545
|
+
if (!file.isFile() || file.size > 1024 * 1024)
|
|
7546
|
+
throw new Error("Antigravity global instructions must be a bounded regular file.");
|
|
7547
|
+
await writeFile5(join7(gemini, "GEMINI.md"), await readFile3(context), { mode: 384, flag: "wx" });
|
|
7548
|
+
} catch (error) {
|
|
7549
|
+
if (error.code !== "ENOENT")
|
|
7550
|
+
throw error;
|
|
7551
|
+
}
|
|
7552
|
+
return { executable: input.executable ?? "agy", args: ["--add-dir", input.cwd, "--model", "switcher", ...input.args ?? []], env: { HOME: home, GEMINI_API_KEY: input.credential, GOOGLE_GEMINI_BASE_URL: input.baseUrl.replace(/\/v1beta\/?$/i, "") }, configPaths: [path], warnings: [
|
|
7553
|
+
"Antigravity 1.2.5 uses an isolated native home, preserved permission settings and durable profile conversations. Native project instructions and permissions remain active.",
|
|
7554
|
+
"The native Flash Lite helper is routed to the policy fast model (main by default). Other models remain subject to the launch policy. Global plugins, authentication and shared app state are not imported; ~ in native tools resolves to the private home."
|
|
7555
|
+
] };
|
|
7556
|
+
}
|
|
7557
|
+
|
|
7558
|
+
// src/junie-config.ts
|
|
7559
|
+
import { writeFile as writeFile6 } from "fs/promises";
|
|
7560
|
+
import { join as join8, isAbsolute as isAbsolute7 } from "path";
|
|
7561
|
+
var routing2 = new Set(["model", "provider", "llmprovider", "byok", "apikey", "auth", "baseurl", "litellmurl", "configlocation", "configdefaultlocations", "modellocation", "modeldefaultlocations", "cachedir", "juniehome", "primarymodel", "fastermodel", "flags"]);
|
|
7562
|
+
async function validateJunieConfiguration(cwd, env = process.env) {
|
|
7563
|
+
const home = env.JUNIE_HOME ?? join8(nativeHome(env), ".junie");
|
|
7564
|
+
if (!isAbsolute7(home))
|
|
7565
|
+
throw new Error("Junie requires an absolute native home.");
|
|
7566
|
+
const configs = [], settings2 = [];
|
|
7567
|
+
for (const root of [...new Set([home, join8(cwd, ".junie")])]) {
|
|
7568
|
+
const config = await readNativeSettings(join8(root, "config.json")), setting = await readNativeSettings(join8(root, "settings.json"));
|
|
7569
|
+
rejectNativeRouting(config, routing2);
|
|
7570
|
+
rejectNativeRouting(setting, routing2);
|
|
7571
|
+
configs.push(config);
|
|
7572
|
+
settings2.push(setting);
|
|
7573
|
+
}
|
|
7574
|
+
return { configs, settings: settings2, allowlist: await readNativeText(join8(home, "allowlist.json")), globalInstructions: await readNativeText(join8(home, "AGENTS.md")) };
|
|
7575
|
+
}
|
|
7576
|
+
async function prepareJunie(input) {
|
|
7577
|
+
const original = await validateJunieConfiguration(input.cwd);
|
|
7578
|
+
const home = join8(input.stateDir, "junie-home"), models = join8(home, "models"), cache = join8(input.sessionDir ?? join8(input.stateDir, "sessions"), "junie-cache");
|
|
7579
|
+
for (const path of [home, models, cache])
|
|
7580
|
+
await privateDirectory(path);
|
|
7581
|
+
await durableNativeDirectory(home, join8(input.sessionDir ?? join8(input.stateDir, "sessions"), "junie"), "sessions");
|
|
7582
|
+
const preservedPaths = [];
|
|
7583
|
+
for (const [name, content] of [["allowlist.json", original.allowlist], ["AGENTS.md", original.globalInstructions]])
|
|
7584
|
+
if (content !== undefined) {
|
|
7585
|
+
const path = join8(home, name);
|
|
7586
|
+
await writeFile6(path, content, { mode: 384, flag: "wx" });
|
|
7587
|
+
preservedPaths.push(path);
|
|
7588
|
+
}
|
|
7589
|
+
const apiType = input.protocol === "openai-chat" ? "OpenAICompletion" : input.protocol === "openai-responses" ? "OpenAIResponses" : "Anthropic";
|
|
7590
|
+
const suffix = input.protocol === "openai-chat" ? "/chat/completions" : input.protocol === "openai-responses" ? "/responses" : "/messages";
|
|
7591
|
+
const model = (id2) => ({ id: id2, displayName: id2, providerName: "Switcher", baseUrl: input.baseUrl + suffix, apiType, apiKey: "${SWITCHER_HARNESS_API_KEY}", maxContextLength: input.models.find((m) => m.id === id2)?.contextWindow ?? 128000 });
|
|
7592
|
+
const profile = await writeNativeSettings(join8(models, "switcher.json"), { ...model(input.model), fasterModel: model(input.compiledPolicy.roles.fast) });
|
|
7593
|
+
const config = await writeNativeSettings(join8(home, "config.json"), Object.assign({}, ...original.configs, { "auto-update": false }));
|
|
7594
|
+
const settings2 = await writeNativeSettings(join8(home, "settings.json"), Object.assign({}, ...original.settings));
|
|
7595
|
+
return { executable: input.executable ?? "junie", args: ["--skip-update-check", "--config-default-locations", "false", "--config-location", config, "--model-default-locations", "false", "--model-location", models, "--model", "custom:switcher", "--cache-dir", cache, ...input.args ?? []], env: { JUNIE_HOME: home, SWITCHER_HARNESS_API_KEY: input.credential }, configPaths: [profile, config, settings2, ...preservedPaths], warnings: [
|
|
7596
|
+
"Junie build 3196.5 uses an isolated custom model profile and durable profile cache and sessions. The primary and faster models use the managed gateway; inherited routing configuration fails preflight.",
|
|
7597
|
+
"Native permissions, project guidelines and native noninteractive trust behavior remain active. User and project settings, ordered global permission rules and global AGENTS.md are snapshotted; global authentication is not imported."
|
|
7598
|
+
] };
|
|
7599
|
+
}
|
|
7600
|
+
|
|
7292
7601
|
// src/gemini-bridge.ts
|
|
7293
7602
|
import { createHash as createHash5, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
7294
7603
|
function geminiBridge(input, timing = {}) {
|
|
@@ -7407,6 +7716,12 @@ function compileNativeModelPolicy(input) {
|
|
|
7407
7716
|
const config = {};
|
|
7408
7717
|
let unsupportedRoles = [];
|
|
7409
7718
|
switch (input.harness) {
|
|
7719
|
+
case "antigravity":
|
|
7720
|
+
case "junie":
|
|
7721
|
+
config.model = models.main;
|
|
7722
|
+
config.fast = models.fast;
|
|
7723
|
+
unsupportedRoles = nativeRoles.filter((role) => role !== "main" && role !== "fast");
|
|
7724
|
+
break;
|
|
7410
7725
|
case "claude":
|
|
7411
7726
|
if (!versionAtLeast(input.version, [2, 1, 257]))
|
|
7412
7727
|
throw new Error("Claude model policy enforcement requires Claude Code >=2.1.257.");
|
|
@@ -7997,7 +8312,7 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
7997
8312
|
const digest = (value) => createHash6("sha256").update(value).digest();
|
|
7998
8313
|
const expected = digest(token), policy = input.compiledPolicy;
|
|
7999
8314
|
const known = new Set(input.models.map((m) => m.id));
|
|
8000
|
-
const safeModel = (value) => typeof value === "string" && value !== input.credential && (known.has(value) || Object.hasOwn(policy.aliases, value)) ? value : "<unrecognized>";
|
|
8315
|
+
const safeModel = (value) => typeof value === "string" && value !== input.credential && (known.has(value) || Object.hasOwn(policy.aliases, value) || input.harness === "antigravity" && value === antigravityHelperModel) ? value : "<unrecognized>";
|
|
8001
8316
|
const fail = (status, code, message) => Response.json({ error: { type: "switcher_model_policy", code, message: message ?? (code === "model_not_allowed" ? "This model is outside the launch policy. Select it with switcher launch --model or explicitly assign an allowed role model." : `Switcher inference gateway: ${code}.`) } }, { status });
|
|
8002
8317
|
let closing = false, stopped;
|
|
8003
8318
|
const active = new Set;
|
|
@@ -8048,7 +8363,10 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8048
8363
|
throw new Fault(403, "routing_override", "Unmanaged model routing is disabled.");
|
|
8049
8364
|
if (typeof requested !== "string")
|
|
8050
8365
|
throw new Fault(400, "model_required", "A model is required.");
|
|
8051
|
-
|
|
8366
|
+
const nativeHelper = input.harness === "antigravity" && requested === antigravityHelperModel;
|
|
8367
|
+
resolved = resolvePolicyModel(policy, nativeHelper ? policy.roles.fast : requested);
|
|
8368
|
+
if (nativeHelper)
|
|
8369
|
+
event.reason = "antigravity_helper_model";
|
|
8052
8370
|
if (input.models.some((model) => model.id === resolved && modelExpired(model)))
|
|
8053
8371
|
throw new Fault(422, "model_expired", "Selected model has expired.");
|
|
8054
8372
|
if (gemini) {
|
|
@@ -8235,13 +8553,13 @@ function createInferenceGateway(input, timing = {}) {
|
|
|
8235
8553
|
}
|
|
8236
8554
|
|
|
8237
8555
|
// src/codex-model-policy.ts
|
|
8238
|
-
import { mkdir as mkdir5, readFile as
|
|
8239
|
-
import { dirname as dirname4, isAbsolute as
|
|
8556
|
+
import { mkdir as mkdir5, readFile as readFile4, realpath as realpath3, stat as stat4, writeFile as writeFile7 } from "fs/promises";
|
|
8557
|
+
import { dirname as dirname4, isAbsolute as isAbsolute8, join as join9, resolve as resolve5 } from "path";
|
|
8240
8558
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
8241
8559
|
import { createHash as createHash7 } from "crypto";
|
|
8242
8560
|
var dict = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
8243
8561
|
var model = (v) => JSON.stringify(v);
|
|
8244
|
-
var codexRoutingKeys = new Set(["model", "model_provider", "model_providers", "model_catalog_json", "base_url", "wire_api", "env_key", "env_http_headers", "http_headers", "auth_command", "include"]);
|
|
8562
|
+
var codexRoutingKeys = new Set(["model", "model_provider", "provider", "model_providers", "model_catalog_json", "base_url", "wire_api", "env_key", "env_http_headers", "http_headers", "auth_command", "include"]);
|
|
8245
8563
|
var codexTransportKeys = new Set(["mcp_servers", "mcp_server", "transport", "transports", "plugins"]);
|
|
8246
8564
|
function codexAgentsFromEffectiveConfig(config, trustedProject = true, baseDir) {
|
|
8247
8565
|
const raw = config.agents;
|
|
@@ -8256,7 +8574,7 @@ function codexAgentsFromEffectiveConfig(config, trustedProject = true, baseDir)
|
|
|
8256
8574
|
const rawConfigFile = value.config_file;
|
|
8257
8575
|
if (rawConfigFile !== undefined && typeof rawConfigFile !== "string")
|
|
8258
8576
|
throw new Error(`Codex agents.${name}.config_file must be a string.`);
|
|
8259
|
-
const configFile = rawConfigFile === undefined ? undefined :
|
|
8577
|
+
const configFile = rawConfigFile === undefined ? undefined : isAbsolute8(rawConfigFile) ? rawConfigFile : baseDir ? resolve5(baseDir, rawConfigFile) : undefined;
|
|
8260
8578
|
if (rawConfigFile !== undefined && !configFile)
|
|
8261
8579
|
throw new Error(`Codex agents.${name}.config_file must be absolute after precedence resolution.`);
|
|
8262
8580
|
const definition = { trusted: trustedProject, config_file: configFile };
|
|
@@ -8304,7 +8622,7 @@ function scanNested(value, path) {
|
|
|
8304
8622
|
if (!dict(value))
|
|
8305
8623
|
return value;
|
|
8306
8624
|
for (const [key, item] of Object.entries(value)) {
|
|
8307
|
-
if (codexTransportKeys.has(key) || key === "config_file" || key === "include" || key === "model_providers" || key === "base_url" || key === "auth_command" || key === "model_instructions_file")
|
|
8625
|
+
if (codexTransportKeys.has(key) || key === "config_file" || key === "include" || key === "model" || key === "model_provider" || key === "provider" || key === "model_providers" || key === "base_url" || key === "wire_api" || key === "env_key" || key === "env_http_headers" || key === "http_headers" || key === "auth_command" || key === "model_instructions_file")
|
|
8308
8626
|
reject(`${path}.${key}`);
|
|
8309
8627
|
if (key === "agents" && dict(item)) {
|
|
8310
8628
|
for (const [name, role] of Object.entries(item))
|
|
@@ -8385,16 +8703,16 @@ async function writeCodexAgentOverrides(result, stateDir) {
|
|
|
8385
8703
|
const paths = {};
|
|
8386
8704
|
for (const agent of result.agents) {
|
|
8387
8705
|
const digest = createHash7("sha256").update(agent.name).digest("hex").slice(0, 16);
|
|
8388
|
-
const path =
|
|
8389
|
-
await
|
|
8706
|
+
const path = join9(root, `agent-${digest}.toml`);
|
|
8707
|
+
await writeFile7(path, renderCodexAgentToml(agent.config), { encoding: "utf8", mode: 384, flag: "wx" });
|
|
8390
8708
|
paths[agent.name] = path;
|
|
8391
8709
|
}
|
|
8392
8710
|
return paths;
|
|
8393
8711
|
}
|
|
8394
8712
|
async function prepareCodexModelPolicy(input) {
|
|
8395
|
-
const home = resolve5(input.home ?? process.env.CODEX_HOME ??
|
|
8713
|
+
const home = resolve5(input.home ?? process.env.CODEX_HOME ?? join9(process.env.HOME ?? "/", ".codex"));
|
|
8396
8714
|
const cwd = resolve5(input.cwd);
|
|
8397
|
-
const globalPath =
|
|
8715
|
+
const globalPath = join9(home, "config.toml");
|
|
8398
8716
|
const readConfig = async (path) => {
|
|
8399
8717
|
let info;
|
|
8400
8718
|
try {
|
|
@@ -8406,7 +8724,7 @@ async function prepareCodexModelPolicy(input) {
|
|
|
8406
8724
|
}
|
|
8407
8725
|
if (!info.isFile() || info.size > 1024 * 1024)
|
|
8408
8726
|
throw new Error(`Codex config must be a regular file no larger than 1 MiB: ${path}`);
|
|
8409
|
-
const text = await
|
|
8727
|
+
const text = await readFile4(path, "utf8");
|
|
8410
8728
|
if (Buffer.byteLength(text) > 1024 * 1024)
|
|
8411
8729
|
throw new Error(`Codex config exceeds 1 MiB: ${path}`);
|
|
8412
8730
|
try {
|
|
@@ -8418,7 +8736,7 @@ async function prepareCodexModelPolicy(input) {
|
|
|
8418
8736
|
const global = await readConfig(globalPath) ?? {};
|
|
8419
8737
|
const projects = dict(global.projects) ? global.projects : {};
|
|
8420
8738
|
const markers = global.project_root_markers ?? [".git"];
|
|
8421
|
-
if (!Array.isArray(markers) || markers.some((m) => typeof m !== "string" ||
|
|
8739
|
+
if (!Array.isArray(markers) || markers.some((m) => typeof m !== "string" || isAbsolute8(m) || m.includes("..")))
|
|
8422
8740
|
throw new Error("Unsupported Codex project root markers.");
|
|
8423
8741
|
const ancestorDirs = [];
|
|
8424
8742
|
for (let dir = cwd;; dir = dirname4(dir)) {
|
|
@@ -8431,9 +8749,9 @@ async function prepareCodexModelPolicy(input) {
|
|
|
8431
8749
|
for (const dir of ancestorDirs)
|
|
8432
8750
|
for (const marker of markers) {
|
|
8433
8751
|
try {
|
|
8434
|
-
const info = await stat4(
|
|
8752
|
+
const info = await stat4(join9(dir, marker));
|
|
8435
8753
|
if (marker === ".git" && info.isDirectory())
|
|
8436
|
-
await stat4(
|
|
8754
|
+
await stat4(join9(dir, marker, "HEAD"));
|
|
8437
8755
|
projectRoot = dir;
|
|
8438
8756
|
break findRoot;
|
|
8439
8757
|
} catch {}
|
|
@@ -8458,7 +8776,7 @@ async function prepareCodexModelPolicy(input) {
|
|
|
8458
8776
|
const layers = [{ path: globalPath, config: global }];
|
|
8459
8777
|
const projectDirs = ancestorDirs.slice(0, ancestorDirs.indexOf(projectRoot) + 1).reverse();
|
|
8460
8778
|
for (const dir of projectDirs) {
|
|
8461
|
-
const path =
|
|
8779
|
+
const path = join9(dir, ".codex", "config.toml");
|
|
8462
8780
|
if (path === globalPath)
|
|
8463
8781
|
continue;
|
|
8464
8782
|
const decision = await trust(dir) ?? projectTrust ?? repoTrust;
|
|
@@ -8487,13 +8805,13 @@ async function prepareCodexModelPolicy(input) {
|
|
|
8487
8805
|
return { ...result, agentConfigPaths: await writeCodexAgentOverrides(result, input.stateDir), configPaths: loaded };
|
|
8488
8806
|
}
|
|
8489
8807
|
async function readCodexAgentConfig(path) {
|
|
8490
|
-
if (!
|
|
8808
|
+
if (!isAbsolute8(path))
|
|
8491
8809
|
throw new Error("Codex agent config_file must be absolute before launch.");
|
|
8492
8810
|
const canonical = await realpath3(path);
|
|
8493
8811
|
const info = await stat4(canonical);
|
|
8494
8812
|
if (!info.isFile() || info.size > 1024 * 1024)
|
|
8495
8813
|
throw new Error(`Codex agent config must be a regular file no larger than 1 MiB: ${path}`);
|
|
8496
|
-
const text = await
|
|
8814
|
+
const text = await readFile4(canonical, "utf8");
|
|
8497
8815
|
try {
|
|
8498
8816
|
return Bun.TOML.parse(text);
|
|
8499
8817
|
} catch {
|
|
@@ -8502,29 +8820,29 @@ async function readCodexAgentConfig(path) {
|
|
|
8502
8820
|
}
|
|
8503
8821
|
|
|
8504
8822
|
// src/harnesses.ts
|
|
8505
|
-
import { access as access3, mkdir as mkdir10, readFile as
|
|
8506
|
-
import { basename as basename2, dirname as dirname7, join as
|
|
8507
|
-
import { homedir as
|
|
8823
|
+
import { access as access3, mkdir as mkdir10, readFile as readFile6, readdir as readdir4, writeFile as writeFile13, rm as rm2 } from "fs/promises";
|
|
8824
|
+
import { basename as basename2, dirname as dirname7, join as join15, isAbsolute as isAbsolute13, resolve as resolve8 } from "path";
|
|
8825
|
+
import { homedir as homedir8, tmpdir } from "os";
|
|
8508
8826
|
import { createHash as createHash9, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual5 } from "crypto";
|
|
8509
8827
|
import { execFile as execFile2 } from "child_process";
|
|
8510
8828
|
import { promisify as promisify2 } from "util";
|
|
8511
8829
|
import { createConnection } from "net";
|
|
8512
8830
|
|
|
8513
8831
|
// src/aider-config.ts
|
|
8514
|
-
import { readFile as
|
|
8832
|
+
import { readFile as readFile5, writeFile as writeFile8, lstat as lstat5, copyFile, rename, realpath as realpath4, access as access2 } from "fs/promises";
|
|
8515
8833
|
import { constants as constants3 } from "fs";
|
|
8516
|
-
import { dirname as dirname5, basename, join as
|
|
8517
|
-
import { homedir as
|
|
8834
|
+
import { dirname as dirname5, basename, join as join10, resolve as resolve6, isAbsolute as isAbsolute9 } from "path";
|
|
8835
|
+
import { homedir as homedir6 } from "os";
|
|
8518
8836
|
import { parseDocument as parseDocument2 } from "yaml";
|
|
8519
8837
|
var KEY2 = "SWITCHER_HARNESS_API_KEY";
|
|
8520
8838
|
var object3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
8521
8839
|
async function data(path) {
|
|
8522
8840
|
let text;
|
|
8523
8841
|
try {
|
|
8524
|
-
const stat5 = await
|
|
8842
|
+
const stat5 = await lstat5(path);
|
|
8525
8843
|
if (!stat5.isFile() || stat5.size > 1024 * 1024)
|
|
8526
8844
|
throw new Error("unsupported");
|
|
8527
|
-
text = await
|
|
8845
|
+
text = await readFile5(path, "utf8");
|
|
8528
8846
|
} catch (error) {
|
|
8529
8847
|
if (error.code === "ENOENT")
|
|
8530
8848
|
return;
|
|
@@ -8555,9 +8873,9 @@ async function gitRoot(path) {
|
|
|
8555
8873
|
parent = dirname5(parent);
|
|
8556
8874
|
}
|
|
8557
8875
|
}
|
|
8558
|
-
for (let dir =
|
|
8876
|
+
for (let dir = join10(parent, ...missing);; dir = dirname5(dir)) {
|
|
8559
8877
|
try {
|
|
8560
|
-
await
|
|
8878
|
+
await lstat5(join10(dir, ".git"));
|
|
8561
8879
|
return dir;
|
|
8562
8880
|
} catch (error) {
|
|
8563
8881
|
if (!["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
|
|
@@ -8570,9 +8888,9 @@ async function gitRoot(path) {
|
|
|
8570
8888
|
var falseValue = (v) => v === undefined || v === null || v === false || v === 0 || typeof v === "string" && ["", "false", "no", "off", "0"].includes(v.toLowerCase());
|
|
8571
8889
|
var startup = `yes-always gui browser upgrade install-main-branch just-check-update apply-clipboard-edits test lint commit`.split(" ");
|
|
8572
8890
|
var safeParameters = new Set(`max_tokens temperature top_p top_k min_p stop seed reasoning_effort thinking`.split(" "));
|
|
8573
|
-
var expandHome = (path, home) => path === "~" ? home : path.startsWith("~/") ?
|
|
8574
|
-
async function validateAiderConfiguration(cwd, args = [], home = process.env.HOME ??
|
|
8575
|
-
if (!
|
|
8891
|
+
var expandHome = (path, home) => path === "~" ? home : path.startsWith("~/") ? join10(home, path.slice(2)) : path;
|
|
8892
|
+
async function validateAiderConfiguration(cwd, args = [], home = process.env.HOME ?? homedir6()) {
|
|
8893
|
+
if (!isAbsolute9(home))
|
|
8576
8894
|
throw new Error("Aider requires an absolute HOME to preserve native instruction paths.");
|
|
8577
8895
|
const parsed = aiderArguments(args), cwdRoot = await gitRoot(cwd);
|
|
8578
8896
|
const roots = new Set([resolve6(home), ...cwdRoot ? [cwdRoot] : [], resolve6(cwd)]);
|
|
@@ -8583,7 +8901,7 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
8583
8901
|
}
|
|
8584
8902
|
let effective = {};
|
|
8585
8903
|
for (const root of roots) {
|
|
8586
|
-
const path =
|
|
8904
|
+
const path = join10(root, ".aider.conf.yml"), value = await data(path);
|
|
8587
8905
|
if (value !== undefined) {
|
|
8588
8906
|
if (!object3(value))
|
|
8589
8907
|
throw new Error(`Aider configuration must be a mapping: ${path}`);
|
|
@@ -8608,13 +8926,13 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
8608
8926
|
}
|
|
8609
8927
|
effective = { ...effective, ...normalized };
|
|
8610
8928
|
}
|
|
8611
|
-
const settings2 = await data(
|
|
8929
|
+
const settings2 = await data(join10(root, ".aider.model.settings.yml"));
|
|
8612
8930
|
if (settings2 !== undefined) {
|
|
8613
8931
|
if (!Array.isArray(settings2))
|
|
8614
8932
|
throw new Error("Aider model settings must be a list.");
|
|
8615
8933
|
for (const entry of settings2)
|
|
8616
8934
|
if (!object3(entry) || entry.extra_params !== undefined && (!object3(entry.extra_params) || Object.keys(entry.extra_params).some((key) => !safeParameters.has(key))))
|
|
8617
|
-
throw new Error(`Aider custom transport or callback model settings cannot be preserved safely: ${
|
|
8935
|
+
throw new Error(`Aider custom transport or callback model settings cannot be preserved safely: ${join10(root, ".aider.model.settings.yml")}`);
|
|
8618
8936
|
}
|
|
8619
8937
|
}
|
|
8620
8938
|
if (effective.read !== undefined && !(typeof effective.read === "string" || Array.isArray(effective.read) && effective.read.every((v) => typeof v === "string")))
|
|
@@ -8635,7 +8953,7 @@ function aiderModelName(protocol, id2) {
|
|
|
8635
8953
|
return `${protocol === "anthropic-messages" ? "anthropic" : protocol === "openai-responses" ? "openai/responses" : "openai"}/${id2}`;
|
|
8636
8954
|
}
|
|
8637
8955
|
async function historyFile(path) {
|
|
8638
|
-
const stat5 = await
|
|
8956
|
+
const stat5 = await lstat5(path);
|
|
8639
8957
|
if (!stat5.isFile() || stat5.isSymbolicLink() || stat5.size > 64 * 1024 * 1024 || process.platform !== "win32" && ((stat5.mode & 63) !== 0 || stat5.uid !== process.getuid?.()))
|
|
8640
8958
|
throw new Error("Aider history must be an owner-only regular file smaller than 64 MiB.");
|
|
8641
8959
|
}
|
|
@@ -8650,7 +8968,7 @@ async function prepareAider(input) {
|
|
|
8650
8968
|
const files = parsed.args.splice(literal2).slice(1);
|
|
8651
8969
|
parsed.args.push(...files.map((path) => resolve6(input.cwd, path)));
|
|
8652
8970
|
}
|
|
8653
|
-
const sourceHome = process.env.HOME ??
|
|
8971
|
+
const sourceHome = process.env.HOME ?? homedir6();
|
|
8654
8972
|
for (let i = 0;i < parsed.args.length; i++) {
|
|
8655
8973
|
if (parsed.args[i] === "--read") {
|
|
8656
8974
|
i++;
|
|
@@ -8658,39 +8976,39 @@ async function prepareAider(input) {
|
|
|
8658
8976
|
} else if (parsed.args[i].startsWith("--read="))
|
|
8659
8977
|
parsed.args[i] = "--read=" + expandHome(parsed.args[i].slice(7), sourceHome);
|
|
8660
8978
|
}
|
|
8661
|
-
const home =
|
|
8979
|
+
const home = join10(input.stateDir, "aider-home");
|
|
8662
8980
|
await privateDirectory(home);
|
|
8663
|
-
const originalHome = process.env.HOME ??
|
|
8664
|
-
const gitSources = process.env.GIT_CONFIG_GLOBAL ? [resolve6(process.env.GIT_CONFIG_GLOBAL)] : [
|
|
8665
|
-
const gitConfig =
|
|
8666
|
-
await
|
|
8981
|
+
const originalHome = process.env.HOME ?? homedir6();
|
|
8982
|
+
const gitSources = process.env.GIT_CONFIG_GLOBAL ? [resolve6(process.env.GIT_CONFIG_GLOBAL)] : [join10(process.env.XDG_CONFIG_HOME ?? join10(originalHome, ".config"), "git", "config"), join10(originalHome, ".gitconfig")];
|
|
8983
|
+
const gitConfig = join10(home, ".gitconfig");
|
|
8984
|
+
await writeFile8(gitConfig, gitSources.map((path) => `[include]
|
|
8667
8985
|
path = ${JSON.stringify(path)}
|
|
8668
8986
|
`).join(""), { mode: 384, flag: "wx" });
|
|
8669
|
-
const sessions = input.sessionDir ??
|
|
8987
|
+
const sessions = input.sessionDir ?? join10(input.stateDir, "sessions");
|
|
8670
8988
|
await privateDirectory(sessions);
|
|
8671
|
-
const id2 = crypto.randomUUID(), history =
|
|
8989
|
+
const id2 = crypto.randomUUID(), history = join10(sessions, `${id2}.chat.md`), inputHistory = join10(sessions, `${id2}.input`);
|
|
8672
8990
|
if (parsed.restore) {
|
|
8673
|
-
const latest =
|
|
8991
|
+
const latest = join10(sessions, "latest.json");
|
|
8674
8992
|
await historyFile(latest).catch(() => {
|
|
8675
8993
|
throw new Error("No valid completed Aider history is available for this profile.");
|
|
8676
8994
|
});
|
|
8677
|
-
const previous = JSON.parse(await
|
|
8995
|
+
const previous = JSON.parse(await readFile5(latest, "utf8"));
|
|
8678
8996
|
if (!object3(previous) || typeof previous.id !== "string" || !/^[-a-f0-9]{36}$/.test(previous.id))
|
|
8679
8997
|
throw new Error("Invalid Aider history reference.");
|
|
8680
|
-
const source =
|
|
8998
|
+
const source = join10(sessions, `${previous.id}.chat.md`);
|
|
8681
8999
|
await historyFile(source);
|
|
8682
9000
|
await copyFile(source, history, 1);
|
|
8683
9001
|
} else
|
|
8684
|
-
await
|
|
8685
|
-
const originalHistoryLength = (await
|
|
8686
|
-
await
|
|
9002
|
+
await writeFile8(history, "", { mode: 384, flag: "wx" });
|
|
9003
|
+
const originalHistoryLength = (await readFile5(history, "utf8")).length;
|
|
9004
|
+
await writeFile8(inputHistory, "", { mode: 384, flag: "wx" });
|
|
8687
9005
|
const model2 = aiderModelName(input.protocol, input.model);
|
|
8688
9006
|
const weakModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.weak ?? input.model), editorModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.editor ?? input.model);
|
|
8689
9007
|
const extra = { api_base: input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl, api_key: `os.environ/${KEY2}` };
|
|
8690
|
-
const settings2 =
|
|
9008
|
+
const settings2 = join10(input.stateDir, "aider-model-settings.json"), metadata = join10(input.stateDir, "aider-model-metadata.json"), config = join10(input.stateDir, "aider-config.json"), empty = join10(input.stateDir, "aider-empty.env");
|
|
8691
9009
|
const definitions = input.models.map((m) => ({ name: aiderModelName(input.protocol, m.id), edit_format: "whole", use_repo_map: true, weak_model_name: weakModel, editor_model_name: editorModel, extra_params: extra }));
|
|
8692
|
-
await
|
|
8693
|
-
await
|
|
9010
|
+
await writeFile8(settings2, JSON.stringify([...definitions, { name: "aider/extra_params", extra_params: extra }]), { mode: 384, flag: "wx" });
|
|
9011
|
+
await writeFile8(metadata, JSON.stringify(Object.fromEntries(input.models.map((m) => [aiderModelName(input.protocol, m.id), {
|
|
8694
9012
|
...m.contextWindow ? { max_input_tokens: m.contextWindow } : {},
|
|
8695
9013
|
...m.maxOutputTokens ? { max_output_tokens: m.maxOutputTokens, max_tokens: m.maxOutputTokens } : {},
|
|
8696
9014
|
litellm_provider: input.protocol === "anthropic-messages" ? "anthropic" : "openai",
|
|
@@ -8699,14 +9017,14 @@ async function prepareAider(input) {
|
|
|
8699
9017
|
}]))), { mode: 384, flag: "wx" });
|
|
8700
9018
|
const ignored = new Set(`model weak-model editor-model openai-api-key anthropic-api-key openai-api-base openai-api-type openai-api-version openai-api-deployment-id openai-organization-id set-env api-key alias config env-file model-settings-file model-metadata-file input-history-file chat-history-file llm-history-file restore-chat-history load analytics analytics-log analytics-posthog-host analytics-posthog-project-api-key analytics-disable check-update show-release-notes`.split(" "));
|
|
8701
9019
|
const preserved = Object.fromEntries(Object.entries(global).filter(([key]) => !ignored.has(key) && !startup.includes(key)));
|
|
8702
|
-
await
|
|
8703
|
-
await
|
|
9020
|
+
await writeFile8(config, JSON.stringify({ ...preserved, model: model2, "weak-model": weakModel, "editor-model": editorModel, "model-settings-file": settings2, "model-metadata-file": metadata, "env-file": empty, "input-history-file": inputHistory, "chat-history-file": history, "llm-history-file": "", "restore-chat-history": parsed.restore, load: "", analytics: false, "check-update": false, "show-release-notes": false, "openai-api-key": "", "anthropic-api-key": "", "openai-api-base": input.baseUrl, "openai-api-type": "", "openai-api-version": "", "openai-api-deployment-id": "", "openai-organization-id": "" }), { mode: 384, flag: "wx" });
|
|
9021
|
+
await writeFile8(empty, "", { mode: 384, flag: "wx" });
|
|
8704
9022
|
const aliases = ["--alias", `switcher-${id2}:${model2}`];
|
|
8705
9023
|
let cleaned = false;
|
|
8706
9024
|
return {
|
|
8707
9025
|
executable: input.executable ?? "aider",
|
|
8708
9026
|
args: ["--config", config, "--model", model2, "--weak-model", weakModel, "--editor-model", editorModel, "--set-env", "PYTHON_DOTENV_DISABLED=1", "--api-key", "SWITCHER_UNUSED=unused", ...aliases, ...parsed.args],
|
|
8709
|
-
env: { HOME: home, XDG_CONFIG_HOME:
|
|
9027
|
+
env: { HOME: home, XDG_CONFIG_HOME: join10(home, "config"), XDG_CACHE_HOME: join10(home, "cache"), XDG_DATA_HOME: join10(home, "data"), PYTHON_DOTENV_DISABLED: "1", LITELLM_LOCAL_MODEL_COST_MAP: "True", [KEY2]: input.credential, [input.protocol === "anthropic-messages" ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY"]: input.credential },
|
|
8710
9028
|
configPaths: [config, settings2, metadata, empty, gitConfig],
|
|
8711
9029
|
warnings: [
|
|
8712
9030
|
...input.protocol === "openai-responses" ? ["Aider 0.86.2 with LiteLLM 1.81.10 uses buffered Responses requests even when native streaming is requested; incremental upstream Responses output is unavailable through this adapter."] : [],
|
|
@@ -8720,11 +9038,11 @@ async function prepareAider(input) {
|
|
|
8720
9038
|
return;
|
|
8721
9039
|
cleaned = true;
|
|
8722
9040
|
await historyFile(history);
|
|
8723
|
-
if (!/^#### /m.test((await
|
|
9041
|
+
if (!/^#### /m.test((await readFile5(history, "utf8")).slice(originalHistoryLength)))
|
|
8724
9042
|
return;
|
|
8725
|
-
const pending =
|
|
8726
|
-
await
|
|
8727
|
-
await rename(pending,
|
|
9043
|
+
const pending = join10(sessions, `${id2}.latest.json`);
|
|
9044
|
+
await writeFile8(pending, JSON.stringify({ id: id2 }), { mode: 384, flag: "wx" });
|
|
9045
|
+
await rename(pending, join10(sessions, "latest.json"));
|
|
8728
9046
|
}
|
|
8729
9047
|
};
|
|
8730
9048
|
}
|
|
@@ -8806,9 +9124,9 @@ function validateGrokResume(args) {
|
|
|
8806
9124
|
}
|
|
8807
9125
|
|
|
8808
9126
|
// src/cline-backend.ts
|
|
8809
|
-
import { mkdir as mkdir6, writeFile as
|
|
9127
|
+
import { mkdir as mkdir6, writeFile as writeFile9 } from "fs/promises";
|
|
8810
9128
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
8811
|
-
import { isAbsolute as
|
|
9129
|
+
import { isAbsolute as isAbsolute10, join as join11 } from "path";
|
|
8812
9130
|
var ENV_BY_PROTOCOL = {
|
|
8813
9131
|
"anthropic-messages": "ANTHROPIC_API_KEY",
|
|
8814
9132
|
"openai-responses": "OPENAI_API_KEY",
|
|
@@ -8834,7 +9152,7 @@ function modelEntry(model2, protocol) {
|
|
|
8834
9152
|
};
|
|
8835
9153
|
}
|
|
8836
9154
|
async function writeJson(path, value) {
|
|
8837
|
-
await
|
|
9155
|
+
await writeFile9(path, `${JSON.stringify(value, null, 2)}
|
|
8838
9156
|
`, { mode: 384, flag: "wx" });
|
|
8839
9157
|
return path;
|
|
8840
9158
|
}
|
|
@@ -8854,18 +9172,18 @@ async function prepareClineLaunch(input) {
|
|
|
8854
9172
|
throw new Error(`Cline ${input.protocol} uses ${mapping.authStyle} authentication; use a provider with the native Cline auth contract.`);
|
|
8855
9173
|
if (input.credential && /[\r\n]/.test(input.credential))
|
|
8856
9174
|
throw new Error("Provider credential contains invalid header characters.");
|
|
8857
|
-
if (!
|
|
9175
|
+
if (!isAbsolute10(input.stateDir) || !isAbsolute10(input.cwd))
|
|
8858
9176
|
throw new Error("Launch state and working directories must be absolute.");
|
|
8859
|
-
const dataDir =
|
|
8860
|
-
const sessionDir = input.sessionDir ??
|
|
8861
|
-
const launchDir =
|
|
8862
|
-
const settingsDir =
|
|
8863
|
-
const configDir =
|
|
9177
|
+
const dataDir = join11(input.stateDir, "cline-data");
|
|
9178
|
+
const sessionDir = input.sessionDir ?? join11(dataDir, "sessions");
|
|
9179
|
+
const launchDir = join11(input.stateDir, `cline-launch-${randomUUID2()}`);
|
|
9180
|
+
const settingsDir = join11(launchDir, "settings");
|
|
9181
|
+
const configDir = join11(launchDir, "config");
|
|
8864
9182
|
await mkdir6(settingsDir, { recursive: true, mode: 448 });
|
|
8865
9183
|
await mkdir6(configDir, { recursive: true, mode: 448 });
|
|
8866
9184
|
const baseUrl = endpoint(input.baseUrl);
|
|
8867
9185
|
const providerId = mapping.providerId;
|
|
8868
|
-
const providersPath = await writeJson(
|
|
9186
|
+
const providersPath = await writeJson(join11(settingsDir, "providers.json"), {
|
|
8869
9187
|
version: 1,
|
|
8870
9188
|
lastUsedProvider: providerId,
|
|
8871
9189
|
modes: {},
|
|
@@ -8885,7 +9203,7 @@ async function prepareClineLaunch(input) {
|
|
|
8885
9203
|
}
|
|
8886
9204
|
}
|
|
8887
9205
|
});
|
|
8888
|
-
const modelsPath = await writeJson(
|
|
9206
|
+
const modelsPath = await writeJson(join11(settingsDir, "models.json"), {
|
|
8889
9207
|
version: 1,
|
|
8890
9208
|
providers: {
|
|
8891
9209
|
[providerId]: {
|
|
@@ -8934,10 +9252,10 @@ async function prepareClineLaunch(input) {
|
|
|
8934
9252
|
}
|
|
8935
9253
|
|
|
8936
9254
|
// src/opencode2-config.ts
|
|
8937
|
-
import { mkdir as mkdir7, open as open2, realpath as realpath5, readdir as readdir3, stat as stat5, writeFile as
|
|
9255
|
+
import { mkdir as mkdir7, open as open2, realpath as realpath5, readdir as readdir3, stat as stat5, writeFile as writeFile10 } from "fs/promises";
|
|
8938
9256
|
import { constants as constants4 } from "fs";
|
|
8939
|
-
import { dirname as dirname6, isAbsolute as
|
|
8940
|
-
import { homedir as
|
|
9257
|
+
import { dirname as dirname6, isAbsolute as isAbsolute11, join as join12, relative as relative4, resolve as resolve7 } from "path";
|
|
9258
|
+
import { homedir as homedir7 } from "os";
|
|
8941
9259
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
8942
9260
|
import { Database as Database2 } from "bun:sqlite";
|
|
8943
9261
|
import { parse as parse3, parseTree as parseTree3 } from "jsonc-parser";
|
|
@@ -8952,7 +9270,7 @@ var maxTotalBytes2 = 8 * 1024 * 1024;
|
|
|
8952
9270
|
var maxFiles2 = 256;
|
|
8953
9271
|
var inside2 = (root, path) => {
|
|
8954
9272
|
const rel = relative4(root, path);
|
|
8955
|
-
return rel === "" || !
|
|
9273
|
+
return rel === "" || !isAbsolute11(rel) && rel !== ".." && !rel.startsWith("../");
|
|
8956
9274
|
};
|
|
8957
9275
|
var action = (value) => ({ bash: "shell", task: "subagent", write: "edit", patch: "edit" })[value] ?? value;
|
|
8958
9276
|
function invalid2(path, field) {
|
|
@@ -9004,7 +9322,7 @@ function permissions(value, path, home) {
|
|
|
9004
9322
|
literal2(item.resource, path, "permission resource");
|
|
9005
9323
|
if (!["read", "edit", "external_directory"].includes(item.action))
|
|
9006
9324
|
return item;
|
|
9007
|
-
const resource = item.resource === "~" || item.resource === "$HOME" ? home : item.resource.startsWith("~/") ?
|
|
9325
|
+
const resource = item.resource === "~" || item.resource === "$HOME" ? home : item.resource.startsWith("~/") ? join12(home, item.resource.slice(2)) : item.resource.startsWith("$HOME/") || item.resource.startsWith("$HOME\\") ? join12(home, item.resource.slice(6)) : item.resource;
|
|
9008
9326
|
return { ...item, resource };
|
|
9009
9327
|
});
|
|
9010
9328
|
}
|
|
@@ -9032,8 +9350,8 @@ function jsonc2(text, path) {
|
|
|
9032
9350
|
return record2(value, path, "configuration object");
|
|
9033
9351
|
}
|
|
9034
9352
|
async function checkRemoteConfiguration(dataHome) {
|
|
9035
|
-
const path =
|
|
9036
|
-
const legacyAuth = await stat5(
|
|
9353
|
+
const path = join12(dataHome, "opencode", "opencode.db");
|
|
9354
|
+
const legacyAuth = await stat5(join12(dataHome, "opencode", "auth.json")).then(() => true, (error) => {
|
|
9037
9355
|
if (error.code === "ENOENT")
|
|
9038
9356
|
return false;
|
|
9039
9357
|
throw error;
|
|
@@ -9073,16 +9391,16 @@ async function checkRemoteConfiguration(dataHome) {
|
|
|
9073
9391
|
}
|
|
9074
9392
|
async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
9075
9393
|
for (const name of ["HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "OPENCODE_CONFIG_DIR"])
|
|
9076
|
-
if (env[name] && !
|
|
9394
|
+
if (env[name] && !isAbsolute11(env[name]))
|
|
9077
9395
|
throw new Error(`OpenCode 2 requires an absolute ${name} to preserve native configuration authority.`);
|
|
9078
|
-
const home = resolve7(env.HOME ||
|
|
9079
|
-
const configRoot = resolve7(env.OPENCODE_CONFIG_DIR ||
|
|
9396
|
+
const home = resolve7(env.HOME || homedir7());
|
|
9397
|
+
const configRoot = resolve7(env.OPENCODE_CONFIG_DIR || join12(env.XDG_CONFIG_HOME || join12(home, ".config"), "opencode"));
|
|
9080
9398
|
const canonicalConfigRoot = await realpath5(configRoot).catch((error) => {
|
|
9081
9399
|
if (error.code === "ENOENT")
|
|
9082
9400
|
return configRoot;
|
|
9083
9401
|
throw error;
|
|
9084
9402
|
});
|
|
9085
|
-
const dataHome = resolve7(env.XDG_DATA_HOME ||
|
|
9403
|
+
const dataHome = resolve7(env.XDG_DATA_HOME || join12(home, ".local", "share"));
|
|
9086
9404
|
await checkRemoteConfiguration(dataHome);
|
|
9087
9405
|
let files = 0, total = 0;
|
|
9088
9406
|
const paths = [];
|
|
@@ -9122,7 +9440,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
9122
9440
|
invalid2(path, "agent prompt environment reference");
|
|
9123
9441
|
let result = "", cursor = 0;
|
|
9124
9442
|
for (const match of text.matchAll(/\{file:([^}]+)\}/g)) {
|
|
9125
|
-
const requested = match[1].startsWith("~/") ?
|
|
9443
|
+
const requested = match[1].startsWith("~/") ? join12(home, match[1].slice(2)) : resolve7(dirname6(path), match[1]);
|
|
9126
9444
|
const content = (await read(requested, false)).trim();
|
|
9127
9445
|
literal2(content, requested, "nested prompt variable reference");
|
|
9128
9446
|
result += text.slice(cursor, match.index) + content;
|
|
@@ -9144,7 +9462,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
9144
9462
|
}
|
|
9145
9463
|
async function agentsDirectory(directory2) {
|
|
9146
9464
|
for (const source of ["agent", "agents", "mode", "modes"]) {
|
|
9147
|
-
const base =
|
|
9465
|
+
const base = join12(directory2, source), entries = [];
|
|
9148
9466
|
const visited = new Set;
|
|
9149
9467
|
let examined = 0;
|
|
9150
9468
|
async function walk(dir, depth) {
|
|
@@ -9163,7 +9481,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
9163
9481
|
if (depth > 16 || (examined += names.length) > maxFiles2)
|
|
9164
9482
|
throw new Error("OpenCode 2 agent policy exceeds its bounded directory limit.");
|
|
9165
9483
|
for (const name of names) {
|
|
9166
|
-
const path =
|
|
9484
|
+
const path = join12(dir, name);
|
|
9167
9485
|
const info = await stat5(path);
|
|
9168
9486
|
if (info.isDirectory()) {
|
|
9169
9487
|
if (source === "agent" || source === "agents")
|
|
@@ -9197,8 +9515,8 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
9197
9515
|
}
|
|
9198
9516
|
}
|
|
9199
9517
|
async function directory(path) {
|
|
9200
|
-
await document(
|
|
9201
|
-
await document(
|
|
9518
|
+
await document(join12(path, "opencode.json"));
|
|
9519
|
+
await document(join12(path, "opencode.jsonc"));
|
|
9202
9520
|
await agentsDirectory(path);
|
|
9203
9521
|
}
|
|
9204
9522
|
await directory(configRoot);
|
|
@@ -9213,11 +9531,11 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
9213
9531
|
const projectEnabled = !["1", "true"].includes((env.OPENCODE_CONFIG_PROJECT_DISABLE ?? env.OPENCODE_DISABLE_PROJECT_CONFIG ?? "").toLowerCase());
|
|
9214
9532
|
if (projectEnabled) {
|
|
9215
9533
|
for (const path of [...ancestors].reverse()) {
|
|
9216
|
-
await document(
|
|
9217
|
-
await document(
|
|
9534
|
+
await document(join12(path, "opencode.json"));
|
|
9535
|
+
await document(join12(path, "opencode.jsonc"));
|
|
9218
9536
|
}
|
|
9219
9537
|
for (const path of [...ancestors].reverse()) {
|
|
9220
|
-
const candidate =
|
|
9538
|
+
const candidate = join12(path, ".opencode");
|
|
9221
9539
|
const canonical = await realpath5(candidate).catch((error) => {
|
|
9222
9540
|
if (error.code === "ENOENT")
|
|
9223
9541
|
return candidate;
|
|
@@ -9228,7 +9546,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
9228
9546
|
}
|
|
9229
9547
|
}
|
|
9230
9548
|
if (env.OPENCODE_CONFIG_CONTENT)
|
|
9231
|
-
documents.push({ path:
|
|
9549
|
+
documents.push({ path: join12(cwd, "OPENCODE_CONFIG_CONTENT"), value: jsonc2(env.OPENCODE_CONFIG_CONTENT, "OPENCODE_CONFIG_CONTENT") });
|
|
9232
9550
|
const policy = [];
|
|
9233
9551
|
const agents = Object.create(null);
|
|
9234
9552
|
let defaultAgent;
|
|
@@ -9321,34 +9639,34 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
9321
9639
|
instructions.push(`Instructions from: ${path}
|
|
9322
9640
|
${content}`);
|
|
9323
9641
|
}
|
|
9324
|
-
await instruction(
|
|
9642
|
+
await instruction(join12(configRoot, "AGENTS.md"));
|
|
9325
9643
|
if (projectEnabled) {
|
|
9326
9644
|
let stop = resolve7(cwd);
|
|
9327
9645
|
if (inside2(home, resolve7(cwd)))
|
|
9328
9646
|
stop = home;
|
|
9329
9647
|
else
|
|
9330
9648
|
for (const path of ancestors) {
|
|
9331
|
-
if (await stat5(
|
|
9649
|
+
if (await stat5(join12(path, ".git")).then(() => true, () => false)) {
|
|
9332
9650
|
stop = path;
|
|
9333
9651
|
break;
|
|
9334
9652
|
}
|
|
9335
9653
|
}
|
|
9336
9654
|
for (const path of ancestors) {
|
|
9337
|
-
await instruction(
|
|
9655
|
+
await instruction(join12(path, "AGENTS.md"));
|
|
9338
9656
|
if (path === stop)
|
|
9339
9657
|
break;
|
|
9340
9658
|
}
|
|
9341
9659
|
}
|
|
9342
|
-
const privateHome =
|
|
9343
|
-
const instructionFile =
|
|
9660
|
+
const privateHome = join12(stateDir, "opencode-home"), privateConfig = join12(stateDir, "opencode-config");
|
|
9661
|
+
const instructionFile = join12(privateConfig, "opencode", "AGENTS.md");
|
|
9344
9662
|
await mkdir7(dirname6(instructionFile), { recursive: true, mode: 448 });
|
|
9345
9663
|
await mkdir7(privateHome, { recursive: true, mode: 448 });
|
|
9346
|
-
await
|
|
9664
|
+
await writeFile10(instructionFile, instructions.join(`
|
|
9347
9665
|
|
|
9348
9666
|
`), { flag: "wx", mode: 384 });
|
|
9349
9667
|
return {
|
|
9350
9668
|
config: { permissions: policy, agents, ...defaultAgent ? { default_agent: defaultAgent } : {}, experimental: { policies: [{ action: "provider.use", resource: "*", effect: "deny" }, { action: "provider.use", resource: providerID, effect: "allow" }] } },
|
|
9351
|
-
env: { HOME: privateHome, XDG_CONFIG_HOME: privateConfig, OPENCODE_CONFIG_DIR:
|
|
9669
|
+
env: { HOME: privateHome, XDG_CONFIG_HOME: privateConfig, OPENCODE_CONFIG_DIR: join12(privateConfig, "opencode"), XDG_CACHE_HOME: join12(stateDir, "opencode-cache"), XDG_STATE_HOME: join12(stateDir, "opencode-state"), XDG_DATA_HOME: dataHome, OPENCODE_DISABLE_PROJECT_CONFIG: "true", OPENCODE_CONFIG_PROJECT_DISABLE: "true", OPENCODE_DISABLE_MODELS_FETCH: "true" },
|
|
9352
9670
|
instructionFile,
|
|
9353
9671
|
sourcePaths: paths
|
|
9354
9672
|
};
|
|
@@ -9363,8 +9681,8 @@ function openCode2ConfigText(config, providerID, keyEnv) {
|
|
|
9363
9681
|
}
|
|
9364
9682
|
|
|
9365
9683
|
// src/omp-backend.ts
|
|
9366
|
-
import { mkdir as mkdir8, rm, writeFile as
|
|
9367
|
-
import { join as
|
|
9684
|
+
import { mkdir as mkdir8, rm, writeFile as writeFile11 } from "fs/promises";
|
|
9685
|
+
import { join as join13 } from "path";
|
|
9368
9686
|
var KEY3 = "SWITCHER_HARNESS_API_KEY";
|
|
9369
9687
|
var API = {
|
|
9370
9688
|
"anthropic-messages": "anthropic-messages",
|
|
@@ -9389,8 +9707,8 @@ async function prepareOmpLaunch(input) {
|
|
|
9389
9707
|
const baseUrl = endpoint(input.baseUrl);
|
|
9390
9708
|
if (input.credential && /[\r\n]/.test(input.credential))
|
|
9391
9709
|
throw new Error("Provider credential contains invalid header characters.");
|
|
9392
|
-
const agentDir =
|
|
9393
|
-
const sessionDir = input.sessionDir ??
|
|
9710
|
+
const agentDir = join13(input.stateDir, "omp-agent");
|
|
9711
|
+
const sessionDir = input.sessionDir ?? join13(input.stateDir, "sessions");
|
|
9394
9712
|
await mkdir8(agentDir, { recursive: true, mode: 448 });
|
|
9395
9713
|
await mkdir8(sessionDir, { recursive: true, mode: 448 });
|
|
9396
9714
|
const api = API[input.protocol];
|
|
@@ -9416,12 +9734,12 @@ async function prepareOmpLaunch(input) {
|
|
|
9416
9734
|
provider.apiKey = KEY3;
|
|
9417
9735
|
provider.authHeader = true;
|
|
9418
9736
|
}
|
|
9419
|
-
const modelsPath =
|
|
9420
|
-
const configPath =
|
|
9737
|
+
const modelsPath = join13(agentDir, "models.yml");
|
|
9738
|
+
const configPath = join13(agentDir, "config.yml");
|
|
9421
9739
|
const selector = `switcher/${input.model}`;
|
|
9422
|
-
await
|
|
9740
|
+
await writeFile11(modelsPath, JSON.stringify({ providers: { switcher: provider } }, null, 2) + `
|
|
9423
9741
|
`, { mode: 384, flag: "wx" });
|
|
9424
|
-
await
|
|
9742
|
+
await writeFile11(configPath, JSON.stringify({
|
|
9425
9743
|
enabledModels: ["switcher/**"],
|
|
9426
9744
|
modelRoles: { default: selector, smol: `switcher/${input.compiledPolicy?.roles.fast ?? input.model}`, slow: `switcher/${input.compiledPolicy?.roles.planning ?? input.model}`, plan: `switcher/${input.compiledPolicy?.roles.planning ?? input.model}` }
|
|
9427
9745
|
}, null, 2) + `
|
|
@@ -9494,8 +9812,8 @@ function compileHermesModelPolicy(currentModel, roles2, baseUrl, apiMode = "chat
|
|
|
9494
9812
|
|
|
9495
9813
|
// src/hermes-backend.ts
|
|
9496
9814
|
import { createHash as createHash8, timingSafeEqual as timingSafeEqual4 } from "crypto";
|
|
9497
|
-
import { mkdir as mkdir9, symlink as
|
|
9498
|
-
import { isAbsolute as
|
|
9815
|
+
import { mkdir as mkdir9, symlink as symlink3, writeFile as writeFile12 } from "fs/promises";
|
|
9816
|
+
import { isAbsolute as isAbsolute12, join as join14 } from "path";
|
|
9499
9817
|
var hermesApiMode = {
|
|
9500
9818
|
"anthropic-messages": "anthropic_messages",
|
|
9501
9819
|
"openai-responses": "codex_responses",
|
|
@@ -9639,7 +9957,7 @@ function createHermesBridge(input, timing = {}) {
|
|
|
9639
9957
|
};
|
|
9640
9958
|
}
|
|
9641
9959
|
async function prepareHermesLaunch(input) {
|
|
9642
|
-
if (!
|
|
9960
|
+
if (!isAbsolute12(input.stateDir) || !isAbsolute12(input.cwd))
|
|
9643
9961
|
throw new Error("Launch state and working directories must be absolute.");
|
|
9644
9962
|
if (input.protocol !== "anthropic-messages" && input.protocol !== "openai-responses" && input.protocol !== "openai-chat")
|
|
9645
9963
|
throw new Error("Hermes does not support this provider protocol.");
|
|
@@ -9649,12 +9967,12 @@ async function prepareHermesLaunch(input) {
|
|
|
9649
9967
|
throw new Error("Hermes cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
9650
9968
|
if (input.credential && /[\r\n]/.test(input.credential))
|
|
9651
9969
|
throw new Error("Provider credential contains invalid header characters.");
|
|
9652
|
-
const sessionDir = input.sessionDir ??
|
|
9653
|
-
const sessionsDir =
|
|
9970
|
+
const sessionDir = input.sessionDir ?? join14(input.stateDir, "hermes-session");
|
|
9971
|
+
const sessionsDir = join14(sessionDir, "sessions");
|
|
9654
9972
|
await mkdir9(input.stateDir, { recursive: true, mode: 448 });
|
|
9655
9973
|
await mkdir9(sessionsDir, { recursive: true, mode: 448 });
|
|
9656
|
-
await
|
|
9657
|
-
await
|
|
9974
|
+
await symlink3(join14(sessionDir, "state.db"), join14(input.stateDir, "state.db"));
|
|
9975
|
+
await symlink3(sessionsDir, join14(input.stateDir, "sessions"));
|
|
9658
9976
|
const bridge = createHermesBridge(input);
|
|
9659
9977
|
let policy;
|
|
9660
9978
|
try {
|
|
@@ -9682,9 +10000,9 @@ async function prepareHermesLaunch(input) {
|
|
|
9682
10000
|
}
|
|
9683
10001
|
}
|
|
9684
10002
|
};
|
|
9685
|
-
const configPath =
|
|
10003
|
+
const configPath = join14(input.stateDir, "config.yaml");
|
|
9686
10004
|
try {
|
|
9687
|
-
await
|
|
10005
|
+
await writeFile12(configPath, JSON.stringify(config, null, 2) + `
|
|
9688
10006
|
`, { mode: 384, flag: "wx" });
|
|
9689
10007
|
} catch (error) {
|
|
9690
10008
|
await bridge.cleanup();
|
|
@@ -9699,7 +10017,7 @@ async function prepareHermesLaunch(input) {
|
|
|
9699
10017
|
SWITCHER_HERMES_AUX_API_KEY: bridge.token,
|
|
9700
10018
|
OPENAI_API_KEY: bridge.token,
|
|
9701
10019
|
OPENAI_BASE_URL: bridge.baseUrl,
|
|
9702
|
-
CODEX_HOME:
|
|
10020
|
+
CODEX_HOME: join14(input.stateDir, "codex-home")
|
|
9703
10021
|
},
|
|
9704
10022
|
configPaths: [configPath],
|
|
9705
10023
|
warnings: [
|
|
@@ -9713,6 +10031,8 @@ async function prepareHermesLaunch(input) {
|
|
|
9713
10031
|
|
|
9714
10032
|
// src/harness-installation.ts
|
|
9715
10033
|
var records = {
|
|
10034
|
+
antigravity: { displayName: "Antigravity CLI", executable: "agy", versionRequirement: "1.2.5", packageOrProject: "Google Antigravity official distribution", documentationUrl: "https://antigravity.google/docs/cli/install", installationGuidance: "install the official Antigravity CLI 1.2.5 and ensure agy is on PATH, or pass the absolute binary path with --executable" },
|
|
10035
|
+
junie: { displayName: "Junie CLI", executable: "junie", versionRequirement: "build 3196.5", packageOrProject: "JetBrains Junie official distribution", documentationUrl: "https://junie.jetbrains.com/docs/quickstart.html", installationGuidance: "install official Junie build 3196.5 and ensure junie is on PATH, or pass its absolute path with --executable" },
|
|
9716
10036
|
claude: {
|
|
9717
10037
|
displayName: "Claude Code",
|
|
9718
10038
|
executable: "claude",
|
|
@@ -9841,8 +10161,8 @@ var execute2 = promisify2(execFile2);
|
|
|
9841
10161
|
var KEY4 = "SWITCHER_HARNESS_API_KEY";
|
|
9842
10162
|
var quote = (value) => JSON.stringify(value);
|
|
9843
10163
|
async function detectHarness(harness, override) {
|
|
9844
|
-
const executable = override ?? Bun.which(harness) ?? harness;
|
|
9845
10164
|
const installation = harnessInstallation(harness);
|
|
10165
|
+
const executable = override ?? Bun.which(installation.executable) ?? installation.executable;
|
|
9846
10166
|
try {
|
|
9847
10167
|
const { stdout, stderr } = await execute2(executable, ["--version"], { timeout: 8000, maxBuffer: 65536, env: childEnvironment() });
|
|
9848
10168
|
return { harness, executable, available: true, version: (stdout.trim() || stderr.trim()).slice(0, 200), installation };
|
|
@@ -9857,6 +10177,10 @@ async function validateHarnessConfiguration(harness, cwd, args = []) {
|
|
|
9857
10177
|
await validateAiderConfiguration(cwd, args);
|
|
9858
10178
|
if (harness === "gemini")
|
|
9859
10179
|
await validateGeminiConfiguration(cwd);
|
|
10180
|
+
if (harness === "antigravity")
|
|
10181
|
+
await validateAntigravityConfiguration(cwd);
|
|
10182
|
+
if (harness === "junie")
|
|
10183
|
+
await validateJunieConfiguration(cwd);
|
|
9860
10184
|
}
|
|
9861
10185
|
var versionAtLeast2 = (raw, minimum) => {
|
|
9862
10186
|
const match = raw?.match(/(\d+)\.(\d+)\.(\d+)/);
|
|
@@ -9872,6 +10196,10 @@ var versionAtLeast2 = (raw, minimum) => {
|
|
|
9872
10196
|
return true;
|
|
9873
10197
|
};
|
|
9874
10198
|
function validateHarnessVersion(harness, version) {
|
|
10199
|
+
if (harness === "antigravity" && version?.trim() !== "1.2.5")
|
|
10200
|
+
throw new Error("Antigravity CLI 1.2.5 is required by the verified native adapter.");
|
|
10201
|
+
if (harness === "junie" && !/\b3196\.5\b/.test(version ?? ""))
|
|
10202
|
+
throw new Error("Junie build 3196.5 is required by the verified custom model adapter.");
|
|
9875
10203
|
if (harness === "kilo" && !versionAtLeast2(version, [7, 5, 15]))
|
|
9876
10204
|
throw new Error("Kilo >=7.5.15 is required by this scoped provider bridge.");
|
|
9877
10205
|
if (harness === "omp" && !versionAtLeast2(version, [18, 1, 11]))
|
|
@@ -9905,8 +10233,8 @@ function validateHarnessVersion(harness, version) {
|
|
|
9905
10233
|
throw new Error("Gemini CLI 0.58.0 is required by the verified native settings and argument contract.");
|
|
9906
10234
|
}
|
|
9907
10235
|
async function jsonFile(dir, name, value) {
|
|
9908
|
-
const path =
|
|
9909
|
-
await
|
|
10236
|
+
const path = join15(dir, name);
|
|
10237
|
+
await writeFile13(path, JSON.stringify(value, null, 2) + `
|
|
9910
10238
|
`, { mode: 384, flag: "wx" });
|
|
9911
10239
|
return path;
|
|
9912
10240
|
}
|
|
@@ -9914,7 +10242,7 @@ async function projectInstructionPaths(cwd) {
|
|
|
9914
10242
|
let dir = resolve8(cwd);
|
|
9915
10243
|
while (true) {
|
|
9916
10244
|
for (const name of ["AGENTS.md", "CLAUDE.md", "CONTEXT.md"]) {
|
|
9917
|
-
const path =
|
|
10245
|
+
const path = join15(dir, name);
|
|
9918
10246
|
if (await access3(path).then(() => true, () => false))
|
|
9919
10247
|
return [path];
|
|
9920
10248
|
}
|
|
@@ -9991,7 +10319,7 @@ function expandHomePattern(value) {
|
|
|
9991
10319
|
const record3 = value;
|
|
9992
10320
|
const output = {};
|
|
9993
10321
|
for (const [key, item] of Object.entries(record3)) {
|
|
9994
|
-
const expanded = key === "~" ?
|
|
10322
|
+
const expanded = key === "~" ? homedir8() : key.startsWith("~/") ? join15(homedir8(), key.slice(2)) : key;
|
|
9995
10323
|
output[expanded] = expandHomePattern(item);
|
|
9996
10324
|
}
|
|
9997
10325
|
return output;
|
|
@@ -10047,7 +10375,7 @@ function decodePolicy(text, file) {
|
|
|
10047
10375
|
async function readPolicyFile(file) {
|
|
10048
10376
|
let text;
|
|
10049
10377
|
try {
|
|
10050
|
-
text = await
|
|
10378
|
+
text = await readFile6(file, "utf8");
|
|
10051
10379
|
} catch (error) {
|
|
10052
10380
|
if (error.code === "ENOENT")
|
|
10053
10381
|
return;
|
|
@@ -10067,7 +10395,7 @@ async function agentPolicyFiles(dir, kind) {
|
|
|
10067
10395
|
throw error;
|
|
10068
10396
|
}
|
|
10069
10397
|
for (const entry of entries) {
|
|
10070
|
-
const file =
|
|
10398
|
+
const file = join15(current, entry.name);
|
|
10071
10399
|
if (entry.isDirectory())
|
|
10072
10400
|
await visit(file, root);
|
|
10073
10401
|
else if (entry.isFile() && entry.name.endsWith(".md"))
|
|
@@ -10075,11 +10403,11 @@ async function agentPolicyFiles(dir, kind) {
|
|
|
10075
10403
|
}
|
|
10076
10404
|
};
|
|
10077
10405
|
for (const rootName of [kind, `${kind}s`])
|
|
10078
|
-
await visit(
|
|
10406
|
+
await visit(join15(dir, rootName), join15(dir, rootName));
|
|
10079
10407
|
return result.sort((a, b) => a.file.localeCompare(b.file));
|
|
10080
10408
|
}
|
|
10081
10409
|
async function readAgentPolicyFile(file, kind, root) {
|
|
10082
|
-
const text = await
|
|
10410
|
+
const text = await readFile6(file, "utf8");
|
|
10083
10411
|
const match = text.match(/^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);
|
|
10084
10412
|
if (!match)
|
|
10085
10413
|
return;
|
|
@@ -10131,9 +10459,9 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
10131
10459
|
result.mode = { ...result.mode ?? {}, [policy.name]: { permission: merged } };
|
|
10132
10460
|
}
|
|
10133
10461
|
};
|
|
10134
|
-
const originalConfig =
|
|
10462
|
+
const originalConfig = join15(process.env.XDG_CONFIG_HOME ?? join15(homedir8(), ".config"), "opencode");
|
|
10135
10463
|
for (const name of ["config.json", "opencode.json", "opencode.jsonc"])
|
|
10136
|
-
await apply(
|
|
10464
|
+
await apply(join15(originalConfig, name));
|
|
10137
10465
|
await applyMarkdown(originalConfig, "agent");
|
|
10138
10466
|
await applyMarkdown(originalConfig, "mode");
|
|
10139
10467
|
if (process.env.OPENCODE_CONFIG)
|
|
@@ -10149,22 +10477,22 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
10149
10477
|
}
|
|
10150
10478
|
for (const current of [...dirs].reverse())
|
|
10151
10479
|
for (const name of ["opencode.jsonc", "opencode.json"])
|
|
10152
|
-
await apply(
|
|
10480
|
+
await apply(join15(current, name));
|
|
10153
10481
|
for (const current of dirs) {
|
|
10154
|
-
const configDir =
|
|
10482
|
+
const configDir = join15(current, ".opencode");
|
|
10155
10483
|
for (const name of ["opencode.json", "opencode.jsonc"])
|
|
10156
|
-
await apply(
|
|
10484
|
+
await apply(join15(configDir, name));
|
|
10157
10485
|
await applyMarkdown(configDir, "agent");
|
|
10158
10486
|
await applyMarkdown(configDir, "mode");
|
|
10159
10487
|
}
|
|
10160
|
-
const homeConfig =
|
|
10488
|
+
const homeConfig = join15(homedir8(), ".opencode");
|
|
10161
10489
|
for (const name of ["opencode.json", "opencode.jsonc"])
|
|
10162
|
-
await apply(
|
|
10490
|
+
await apply(join15(homeConfig, name));
|
|
10163
10491
|
await applyMarkdown(homeConfig, "agent");
|
|
10164
10492
|
await applyMarkdown(homeConfig, "mode");
|
|
10165
10493
|
if (process.env.OPENCODE_CONFIG_DIR) {
|
|
10166
10494
|
for (const name of ["opencode.json", "opencode.jsonc"])
|
|
10167
|
-
await apply(
|
|
10495
|
+
await apply(join15(process.env.OPENCODE_CONFIG_DIR, name));
|
|
10168
10496
|
await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "agent");
|
|
10169
10497
|
await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "mode");
|
|
10170
10498
|
}
|
|
@@ -10335,20 +10663,20 @@ var PRIME_DAEMON_STARTUP_TIMEOUT_MS = 30000;
|
|
|
10335
10663
|
var PRIME_DAEMON_SHUTDOWN_TIMEOUT_MS = 5000;
|
|
10336
10664
|
function primeSocketPaths(runtimeDir) {
|
|
10337
10665
|
const basename3 = `p-${randomUUID4().replaceAll("-", "").slice(0, 8)}.sock`;
|
|
10338
|
-
const daemonSocket =
|
|
10666
|
+
const daemonSocket = join15(runtimeDir, basename3);
|
|
10339
10667
|
const uid = typeof process.getuid === "function" ? String(process.getuid()) : "user";
|
|
10340
|
-
const workerDir =
|
|
10668
|
+
const workerDir = join15(runtimeDir, `prime-agent-${uid}`);
|
|
10341
10669
|
const workerKey = createHash9("sha256").update(daemonSocket).digest("hex").slice(0, 12);
|
|
10342
|
-
const workerSocket =
|
|
10670
|
+
const workerSocket = join15(workerDir, `worker-${workerKey}-${"x".repeat(12)}.sock`);
|
|
10343
10671
|
const overlong = [daemonSocket, workerSocket].find((path) => Buffer.byteLength(path, "utf8") > PRIME_UNIX_SOCKET_LIMIT);
|
|
10344
|
-
return { daemonSocket, runtimeDir, workerDir, workerPrefix:
|
|
10672
|
+
return { daemonSocket, runtimeDir, workerDir, workerPrefix: join15(workerDir, `worker-${workerKey}-`), overlong };
|
|
10345
10673
|
}
|
|
10346
10674
|
async function primeSocketInfo() {
|
|
10347
10675
|
const requested = tmpdir();
|
|
10348
10676
|
const direct = primeSocketPaths(requested);
|
|
10349
10677
|
if (!direct.overlong)
|
|
10350
10678
|
return direct;
|
|
10351
|
-
const fallback =
|
|
10679
|
+
const fallback = join15(switcherHome(), "r");
|
|
10352
10680
|
await privateDirectory(switcherHome());
|
|
10353
10681
|
await privateDirectory(fallback);
|
|
10354
10682
|
const scoped = primeSocketPaths(fallback);
|
|
@@ -10529,7 +10857,7 @@ async function primeRemainingSockets(socketPath, workerPrefix) {
|
|
|
10529
10857
|
const workerDir = workerPrefix.slice(0, workerPrefix.lastIndexOf("/"));
|
|
10530
10858
|
const prefix = workerPrefix.slice(workerPrefix.lastIndexOf("/") + 1);
|
|
10531
10859
|
const workers = await readdir4(workerDir).then((entries) => entries.filter((entry) => entry.startsWith(prefix)), () => []);
|
|
10532
|
-
return [...daemon ? [socketPath] : [], ...workers.map((entry) =>
|
|
10860
|
+
return [...daemon ? [socketPath] : [], ...workers.map((entry) => join15(workerDir, entry))];
|
|
10533
10861
|
}
|
|
10534
10862
|
function primeModel(input, api) {
|
|
10535
10863
|
return input.models.map((model3) => ({
|
|
@@ -10547,7 +10875,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10547
10875
|
if (!compatible(input.harness, input.protocol))
|
|
10548
10876
|
throw new Error("Harness and provider protocol are incompatible.");
|
|
10549
10877
|
validateHarnessVersion(input.harness, input.version);
|
|
10550
|
-
if (!
|
|
10878
|
+
if (!isAbsolute13(input.stateDir) || !isAbsolute13(input.cwd))
|
|
10551
10879
|
throw new Error("Launch state and working directories must be absolute.");
|
|
10552
10880
|
if (!input.models.length || !input.models.some((m) => m.id === input.model))
|
|
10553
10881
|
throw new Error("Selected model is missing from the launch catalog.");
|
|
@@ -10566,6 +10894,10 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10566
10894
|
warnings.push(`${missing} catalog models have no declared context limit; native fallback limits may be inaccurate.`);
|
|
10567
10895
|
if (input.harness === "gemini")
|
|
10568
10896
|
return prepareGemini(input);
|
|
10897
|
+
if (input.harness === "antigravity")
|
|
10898
|
+
return prepareAntigravity(input);
|
|
10899
|
+
if (input.harness === "junie")
|
|
10900
|
+
return prepareJunie(input);
|
|
10569
10901
|
if (input.protocol === "gemini-generate-content")
|
|
10570
10902
|
throw new Error("Harness and provider protocol are incompatible.");
|
|
10571
10903
|
if (input.harness === "aider")
|
|
@@ -10586,8 +10918,9 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10586
10918
|
return { executable, args: ["--settings", file2, "--model", input.model, ...args], env, configPaths, warnings };
|
|
10587
10919
|
}
|
|
10588
10920
|
if (input.harness === "codex") {
|
|
10589
|
-
const rolePolicy2 = await prepareCodexModelPolicy({ cwd: input.cwd, stateDir: input.stateDir, model: input.model, policy: input.modelPolicy ? { version: 1, ...input.modelPolicy } : undefined, switcherProvider: "switcher", switcherBaseUrl: input.baseUrl });
|
|
10590
|
-
const
|
|
10921
|
+
const rolePolicy2 = await prepareCodexModelPolicy({ home: input.sharedState?.home, cwd: input.cwd, stateDir: input.stateDir, model: input.model, policy: input.modelPolicy ? { version: 1, ...input.modelPolicy } : undefined, switcherProvider: "switcher", switcherBaseUrl: input.baseUrl });
|
|
10922
|
+
const selectableModels = input.models.filter((model3) => input.compiledPolicy?.allowedModels.includes(model3.id) ?? true);
|
|
10923
|
+
const file2 = await jsonFile(input.stateDir, "codex-models.json", { models: selectableModels.map((model3, index) => codexModel(model3, index, providerBaseUrl, model3.id === input.model ? input.reasoning : undefined)) });
|
|
10591
10924
|
configPaths.push(file2);
|
|
10592
10925
|
configPaths.push(...Object.values(rolePolicy2.agentConfigPaths));
|
|
10593
10926
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
@@ -10606,6 +10939,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10606
10939
|
overrides.push("-c", `agents.${name}.config_file=${quote(path)}`);
|
|
10607
10940
|
}
|
|
10608
10941
|
overrides.push("-c", `memories.extract_model=${quote(input.model)}`, "-c", `memories.consolidation_model=${quote(input.model)}`);
|
|
10942
|
+
if (input.sharedState?.sqliteHome)
|
|
10943
|
+
overrides.push("-c", `sqlite_home=${quote(input.sharedState.sqliteHome)}`);
|
|
10609
10944
|
if (input.reasoning)
|
|
10610
10945
|
overrides.push("-c", `model_reasoning_effort=${quote(input.reasoning)}`);
|
|
10611
10946
|
if (input.dangerouslyBypassApprovalsAndSandbox)
|
|
@@ -10636,8 +10971,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10636
10971
|
throw new Error("Pi cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
10637
10972
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions", "gemini-generate-content": "gemini" }[input.protocol];
|
|
10638
10973
|
const providerId = piProviderId(input, providerBaseUrl);
|
|
10639
|
-
const agentDir =
|
|
10640
|
-
const sessionDir = input.sessionDir ??
|
|
10974
|
+
const agentDir = join15(input.stateDir, "pi-agent");
|
|
10975
|
+
const sessionDir = input.sessionDir ?? join15(input.stateDir, "sessions");
|
|
10641
10976
|
const piBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
|
|
10642
10977
|
await mkdir10(agentDir, { recursive: true, mode: 448 });
|
|
10643
10978
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
@@ -10662,9 +10997,9 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10662
10997
|
const selected = dshArguments(args);
|
|
10663
10998
|
const providerId = piProviderId(input, providerBaseUrl);
|
|
10664
10999
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
|
|
10665
|
-
const home =
|
|
10666
|
-
const sessionDir = input.sessionDir ??
|
|
10667
|
-
if (!
|
|
11000
|
+
const home = join15(input.stateDir, "dsh-home");
|
|
11001
|
+
const sessionDir = input.sessionDir ?? join15(input.stateDir, "dsh-state");
|
|
11002
|
+
if (!isAbsolute13(sessionDir))
|
|
10668
11003
|
throw new Error("DSH session directory must be absolute.");
|
|
10669
11004
|
await mkdir10(home, { recursive: true, mode: 448 });
|
|
10670
11005
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
@@ -10685,7 +11020,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10685
11020
|
}))
|
|
10686
11021
|
} } } },
|
|
10687
11022
|
{ id: "agent-default-model", config: route2 },
|
|
10688
|
-
{ id: "session-persistence-jsonl", config: { root:
|
|
11023
|
+
{ id: "session-persistence-jsonl", config: { root: join15(sessionDir, "sessions") } },
|
|
10689
11024
|
{ id: "attachment-local", config: { dshHome: sessionDir } },
|
|
10690
11025
|
...selected.profile === "acp" ? [{ id: "acp", config: route2 }] : []
|
|
10691
11026
|
];
|
|
@@ -10711,15 +11046,15 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10711
11046
|
throw new Error("Prime Agent cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
10712
11047
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
|
|
10713
11048
|
const providerId = primeProviderId(input, providerBaseUrl);
|
|
10714
|
-
const sessionDir = input.sessionDir ??
|
|
10715
|
-
const agentDir =
|
|
11049
|
+
const sessionDir = input.sessionDir ?? join15(input.stateDir, "sessions");
|
|
11050
|
+
const agentDir = join15(input.stateDir, "prime-agent");
|
|
10716
11051
|
const socketInfo = await primeSocketInfo();
|
|
10717
11052
|
const { daemonSocket, runtimeDir, workerPrefix } = socketInfo;
|
|
10718
11053
|
const primeBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
|
|
10719
11054
|
await mkdir10(agentDir, { recursive: true, mode: 448 });
|
|
10720
11055
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
10721
|
-
const file2 =
|
|
10722
|
-
await
|
|
11056
|
+
const file2 = join15(agentDir, "models.json");
|
|
11057
|
+
await writeFile13(file2, JSON.stringify({ providers: { [providerId]: {
|
|
10723
11058
|
name: "Switcher",
|
|
10724
11059
|
baseUrl: primeBaseUrl,
|
|
10725
11060
|
api,
|
|
@@ -10810,13 +11145,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10810
11145
|
const file2 = await jsonFile(input.stateDir, "opencode-legacy.json", config2);
|
|
10811
11146
|
configPaths.push(file2);
|
|
10812
11147
|
env.OPENCODE_CONFIG = file2;
|
|
10813
|
-
const sessionDir = input.sessionDir ??
|
|
11148
|
+
const sessionDir = input.sessionDir ?? join15(input.stateDir, "sessions");
|
|
10814
11149
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
10815
|
-
env.XDG_DATA_HOME =
|
|
10816
|
-
env.XDG_CONFIG_HOME =
|
|
10817
|
-
env.XDG_CACHE_HOME =
|
|
10818
|
-
env.XDG_STATE_HOME =
|
|
10819
|
-
env.HOME =
|
|
11150
|
+
env.XDG_DATA_HOME = join15(sessionDir, "data");
|
|
11151
|
+
env.XDG_CONFIG_HOME = join15(input.stateDir, "config");
|
|
11152
|
+
env.XDG_CACHE_HOME = join15(input.stateDir, "cache");
|
|
11153
|
+
env.XDG_STATE_HOME = join15(input.stateDir, "state");
|
|
11154
|
+
env.HOME = join15(input.stateDir, "home");
|
|
10820
11155
|
env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";
|
|
10821
11156
|
env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config2);
|
|
10822
11157
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
@@ -10840,8 +11175,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10840
11175
|
const rolePolicy = compileOpenCodeModelPolicy({ providerId: providerID, mainModel: input.model, roles: input.compiledPolicy?.roles, preservedAgents: Object.entries(isolated.config.agents ?? {}).map(([name, agent]) => ({ ...agent, name })) });
|
|
10841
11176
|
const modelRef = openCodeInvocationModel(args, rolePolicy, isolated.config.default_agent);
|
|
10842
11177
|
const config = { ...isolated.config, ...rolePolicy.config, providers: { [providerID]: { name: "Switcher", env: [KEY4], package: `@opencode-ai/ai/providers/${packageName}`, settings: settings2, models } } };
|
|
10843
|
-
const file =
|
|
10844
|
-
await
|
|
11178
|
+
const file = join15(input.stateDir, "opencode.json");
|
|
11179
|
+
await writeFile13(file, openCode2ConfigText(config, providerID, KEY4), { mode: 384, flag: "wx" });
|
|
10845
11180
|
configPaths.push(file, isolated.instructionFile);
|
|
10846
11181
|
Object.assign(env, isolated.env);
|
|
10847
11182
|
env.OPENCODE_CONFIG = file;
|
|
@@ -10854,7 +11189,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
10854
11189
|
return { executable, args: native, env, configPaths, warnings };
|
|
10855
11190
|
}
|
|
10856
11191
|
async function prepareTransportLaunch(input) {
|
|
10857
|
-
assertHarnessArguments(input.harness, input.args ?? []);
|
|
11192
|
+
assertHarnessArguments(input.harness, input.args ?? [], input.sharedState?.tool === "codex" ? { reservedCodexRoots: ["sqlite_home"] } : {});
|
|
10858
11193
|
if (input.harness === "kilo") {
|
|
10859
11194
|
await validateKiloConfiguration(input.cwd, [...input.args ?? []]);
|
|
10860
11195
|
if (input.protocol === "gemini-generate-content")
|
|
@@ -10919,15 +11254,17 @@ async function prepareTransportLaunch(input) {
|
|
|
10919
11254
|
}
|
|
10920
11255
|
}
|
|
10921
11256
|
async function prepareHarnessLaunch(input) {
|
|
10922
|
-
assertHarnessArguments(input.harness, input.args ?? []);
|
|
11257
|
+
assertHarnessArguments(input.harness, input.args ?? [], input.sharedState?.tool === "codex" ? { reservedCodexRoots: ["sqlite_home"] } : {});
|
|
10923
11258
|
if (input.harness === "gemini" && input.authStyle !== "x-api-key")
|
|
10924
11259
|
throw new Error("Gemini CLI requires x-api-key authentication.");
|
|
10925
11260
|
validateHarnessVersion(input.harness, input.version);
|
|
10926
11261
|
if (!compatible(input.harness, input.protocol))
|
|
10927
11262
|
throw new Error("Harness and provider protocol are incompatible.");
|
|
10928
|
-
if (!
|
|
11263
|
+
if (!isAbsolute13(input.stateDir) || !isAbsolute13(input.cwd))
|
|
10929
11264
|
throw new Error("Launch state and working directories must be absolute.");
|
|
10930
11265
|
const compiledPolicy = compileModelPolicy(input.model, input.models, input.modelPolicy);
|
|
11266
|
+
if (input.harness === "antigravity" && input.model === antigravityHelperModel && compiledPolicy.roles.fast !== input.model)
|
|
11267
|
+
throw new Error("Antigravity main and helper requests are indistinguishable for this model; the fast role must use the same model.");
|
|
10931
11268
|
input = { ...input, models: input.models.filter((model3) => !modelExpired(model3)) };
|
|
10932
11269
|
const nativePolicy = compileNativeModelPolicy({ harness: input.harness, mainModel: input.model, roles: compiledPolicy.roles, version: input.version });
|
|
10933
11270
|
const specialized = new Set(["opencode", "opencode2", "gemini", "hermes"]);
|
|
@@ -10940,7 +11277,7 @@ async function prepareHarnessLaunch(input) {
|
|
|
10940
11277
|
try {
|
|
10941
11278
|
const nativeAuth = input.protocol === "gemini-generate-content" ? "x-api-key" : input.harness === "claude" ? input.authStyle === "x-api-key" ? "x-api-key" : "bearer" : input.protocol === "anthropic-messages" ? "x-api-key" : "bearer";
|
|
10942
11279
|
const prepared = await prepareTransportLaunch({ ...input, providerBaseUrl: input.baseUrl, baseUrl: bridge.baseUrl, credential: bridge.token, authStyle: nativeAuth, compiledPolicy, nativePolicy });
|
|
10943
|
-
return { ...prepared, configPaths: [...prepared.configPaths, catalogPath], warnings: [...prepared.warnings, "Switcher injects model guidance into every managed inference request and permits only
|
|
11280
|
+
return { ...prepared, configPaths: [...prepared.configPaths, catalogPath], warnings: [...prepared.warnings, "Switcher injects model guidance into every managed inference request and permits only models authorized by the launch policy, including catalog selection when enabled. The gateway translates the selected credential to the provider authentication header. The full catalog remains discoverable."], cleanup: async () => {
|
|
10944
11281
|
try {
|
|
10945
11282
|
await prepared.cleanup?.();
|
|
10946
11283
|
} finally {
|
|
@@ -10956,9 +11293,9 @@ async function prepareHarnessLaunch(input) {
|
|
|
10956
11293
|
}
|
|
10957
11294
|
|
|
10958
11295
|
// src/ori-model-policy.ts
|
|
10959
|
-
import { isAbsolute as
|
|
11296
|
+
import { isAbsolute as isAbsolute14 } from "path";
|
|
10960
11297
|
function prepareOriModelPolicy(target, prepared) {
|
|
10961
|
-
if (!
|
|
11298
|
+
if (!isAbsolute14(prepared.executable) || /[\0\r\n]/.test(prepared.executable))
|
|
10962
11299
|
throw new Error("Ori requires an absolute verified native executable.");
|
|
10963
11300
|
const entries = Object.entries(prepared.env);
|
|
10964
11301
|
if (entries.some(([key]) => !/^[A-Z_][A-Z0-9_]*$/.test(key)))
|
|
@@ -10982,8 +11319,8 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
|
|
|
10982
11319
|
}
|
|
10983
11320
|
|
|
10984
11321
|
// src/launcher.ts
|
|
10985
|
-
import { mkdir as
|
|
10986
|
-
import { join as
|
|
11322
|
+
import { mkdir as mkdir12, mkdtemp, rm as rm6, writeFile as writeFile17 } from "fs/promises";
|
|
11323
|
+
import { join as join20, resolve as resolve11 } from "path";
|
|
10987
11324
|
|
|
10988
11325
|
// src/provider-credential-onboarding.ts
|
|
10989
11326
|
import { z as z8 } from "zod";
|
|
@@ -10993,8 +11330,8 @@ import { createInterface } from "readline/promises";
|
|
|
10993
11330
|
// src/credentials.ts
|
|
10994
11331
|
import { z as z7 } from "zod";
|
|
10995
11332
|
import { constants as constants5 } from "fs";
|
|
10996
|
-
import { open as open3, readdir as readdir5, unlink, link, lstat as
|
|
10997
|
-
import { join as
|
|
11333
|
+
import { open as open3, readdir as readdir5, unlink, link, lstat as lstat6, access as access4, stat as stat6, realpath as realpath6, readlink, rename as rename2 } from "fs/promises";
|
|
11334
|
+
import { join as join16, isAbsolute as isAbsolute15, dirname as dirname8, parse as pathParts, resolve as resolvePath, sep as sep2 } from "path";
|
|
10998
11335
|
import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
|
|
10999
11336
|
import { execFile as execFile3, spawn } from "child_process";
|
|
11000
11337
|
import { promisify as promisify3 } from "util";
|
|
@@ -11020,7 +11357,7 @@ var credentialBindingSchema = z7.object({
|
|
|
11020
11357
|
kind: z7.literal("vault"),
|
|
11021
11358
|
key: vaultKeySchema,
|
|
11022
11359
|
url: z7.string().max(2000).transform(endpoint).optional(),
|
|
11023
|
-
executable: z7.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(
|
|
11360
|
+
executable: z7.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute15, "Secrets executable must be an absolute path"),
|
|
11024
11361
|
operator
|
|
11025
11362
|
}).strict()])
|
|
11026
11363
|
}).strict().superRefine((binding, ctx) => {
|
|
@@ -11036,16 +11373,16 @@ class CredentialBindings {
|
|
|
11036
11373
|
directory;
|
|
11037
11374
|
constructor(env = process.env) {
|
|
11038
11375
|
this.env = env;
|
|
11039
|
-
this.directory =
|
|
11376
|
+
this.directory = join16(switcherHome(env), "config", "credential-bindings");
|
|
11040
11377
|
}
|
|
11041
11378
|
path(name) {
|
|
11042
|
-
return
|
|
11379
|
+
return join16(this.directory, parse2(reference, name) + ".json");
|
|
11043
11380
|
}
|
|
11044
11381
|
async readableDirectory() {
|
|
11045
|
-
for (const path of [switcherHome(this.env),
|
|
11382
|
+
for (const path of [switcherHome(this.env), join16(switcherHome(this.env), "config"), this.directory]) {
|
|
11046
11383
|
let info;
|
|
11047
11384
|
try {
|
|
11048
|
-
info = await
|
|
11385
|
+
info = await lstat6(path);
|
|
11049
11386
|
} catch (error) {
|
|
11050
11387
|
if (error.code === "ENOENT")
|
|
11051
11388
|
return false;
|
|
@@ -11111,9 +11448,9 @@ class CredentialBindings {
|
|
|
11111
11448
|
if (binding.source.kind === "vault")
|
|
11112
11449
|
await validateVaultExecutable(binding.source.executable);
|
|
11113
11450
|
await privateDirectory(switcherHome(this.env));
|
|
11114
|
-
await privateDirectory(
|
|
11451
|
+
await privateDirectory(join16(switcherHome(this.env), "config"));
|
|
11115
11452
|
await privateDirectory(this.directory);
|
|
11116
|
-
const temporary =
|
|
11453
|
+
const temporary = join16(this.directory, `.binding-${randomUUID5()}`);
|
|
11117
11454
|
const file = await open3(temporary, "wx", 384);
|
|
11118
11455
|
try {
|
|
11119
11456
|
await file.writeFile(JSON.stringify(binding, null, 2) + `
|
|
@@ -11169,13 +11506,13 @@ async function inspectVaultExecutable(path, permitWritableFile = false) {
|
|
|
11169
11506
|
for (const part of candidate.slice(prefix.length).split(sep2)) {
|
|
11170
11507
|
if (!part)
|
|
11171
11508
|
continue;
|
|
11172
|
-
prefix =
|
|
11509
|
+
prefix = join16(prefix, part);
|
|
11173
11510
|
if (seen.has(prefix))
|
|
11174
11511
|
continue;
|
|
11175
11512
|
seen.add(prefix);
|
|
11176
11513
|
if (seen.size > 256)
|
|
11177
11514
|
throw new Fault(422, "vault_exec_permissions", "The secrets executable path has too many symlink components.");
|
|
11178
|
-
const entry = await
|
|
11515
|
+
const entry = await lstat6(prefix);
|
|
11179
11516
|
const permittedFile = permitWritableFile && prefix === resolved && entry.isFile();
|
|
11180
11517
|
if (entry.uid !== 0 && entry.uid !== process.getuid?.() || !entry.isSymbolicLink() && !permittedFile && entry.mode & 18)
|
|
11181
11518
|
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.");
|
|
@@ -11200,7 +11537,7 @@ async function validateVaultExecutable(path) {
|
|
|
11200
11537
|
async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
11201
11538
|
if (!/^[a-f0-9]{64}$/.test(expectedSha256))
|
|
11202
11539
|
throw new Fault(400, "invalid_request", "--sha256 requires the SHA256 of the executable member from a verified package artifact.");
|
|
11203
|
-
if (!
|
|
11540
|
+
if (!isAbsolute15(path) || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path))
|
|
11204
11541
|
throw new Fault(400, "invalid_request", "Secrets executable must be an absolute path without control characters.");
|
|
11205
11542
|
if (process.platform === "win32")
|
|
11206
11543
|
throw new Fault(422, "vault_exec_repair_unsafe", "Executable permission repair requires POSIX file permissions.");
|
|
@@ -11238,13 +11575,13 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
11238
11575
|
await hash2();
|
|
11239
11576
|
const mode = before.mode & 511 & ~18;
|
|
11240
11577
|
const changed = mode !== (before.mode & 511);
|
|
11241
|
-
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await
|
|
11578
|
+
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat6(resolved)))
|
|
11242
11579
|
throw unsafe();
|
|
11243
11580
|
if (!changed) {
|
|
11244
11581
|
await validateVaultExecutable(path);
|
|
11245
11582
|
return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
|
|
11246
11583
|
}
|
|
11247
|
-
temporary =
|
|
11584
|
+
temporary = join16(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
|
|
11248
11585
|
const replacement = await open3(temporary, "wx", 384);
|
|
11249
11586
|
try {
|
|
11250
11587
|
await hash2(replacement);
|
|
@@ -11253,11 +11590,11 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
11253
11590
|
const ready = await replacement.stat();
|
|
11254
11591
|
if (!ready.isFile() || ready.nlink !== 1 || ready.uid !== before.uid || ready.size !== before.size)
|
|
11255
11592
|
throw unsafe();
|
|
11256
|
-
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await
|
|
11593
|
+
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat6(resolved)))
|
|
11257
11594
|
throw unsafe();
|
|
11258
11595
|
await rename2(temporary, resolved);
|
|
11259
11596
|
temporary = undefined;
|
|
11260
|
-
const installed = await
|
|
11597
|
+
const installed = await lstat6(resolved);
|
|
11261
11598
|
if (installed.dev !== ready.dev || installed.ino !== ready.ino || await validateVaultExecutable(path) !== resolved)
|
|
11262
11599
|
throw unsafe();
|
|
11263
11600
|
const directory = await open3(dirname8(resolved), constants5.O_RDONLY | constants5.O_DIRECTORY | constants5.O_NOFOLLOW);
|
|
@@ -11534,6 +11871,7 @@ async function deliverVaultCredential() {
|
|
|
11534
11871
|
|
|
11535
11872
|
// src/provider-credential-onboarding.ts
|
|
11536
11873
|
var absent = (error) => error instanceof SwitcherError && error.status === 404;
|
|
11874
|
+
var MAX_CREDENTIAL_MATCHES = 256;
|
|
11537
11875
|
var secretMetadataSchema = z8.object({
|
|
11538
11876
|
key: vaultKeySchema,
|
|
11539
11877
|
type: z8.enum(["api_key", "password", "token", "credential", "other"]),
|
|
@@ -11573,7 +11911,7 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
|
|
|
11573
11911
|
const operator2 = await resolveVaultOperatorEnvironment(provisional, env);
|
|
11574
11912
|
const entries = new Map;
|
|
11575
11913
|
for (const query of searchTerms(provider)) {
|
|
11576
|
-
const output = await runVaultCommand(provisional, ["search", query, "--json"], env, {}, {
|
|
11914
|
+
const output = await runVaultCommand(provisional, ["search", query, "--json", "--full", "--limit", String(MAX_CREDENTIAL_MATCHES + 1)], env, {}, {
|
|
11577
11915
|
captureBytes: 256 * 1024,
|
|
11578
11916
|
oversizeCode: "vault_metadata_oversized",
|
|
11579
11917
|
oversizeMessage: "Secrets returned too much credential metadata; narrow the vault naming or bind an exact key explicitly.",
|
|
@@ -11587,12 +11925,14 @@ async function discoverVaultReferences(provider, env = process.env, vaultExecuta
|
|
|
11587
11925
|
} catch {
|
|
11588
11926
|
throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned invalid credential metadata JSON.");
|
|
11589
11927
|
}
|
|
11590
|
-
|
|
11928
|
+
if (Array.isArray(parsed) && parsed.length > MAX_CREDENTIAL_MATCHES)
|
|
11929
|
+
throw new Fault(422, "credential_matches_too_many", "More than 256 credential metadata rows matched. Bind an exact vault key explicitly.");
|
|
11930
|
+
const result = secretMetadataSchema.array().max(MAX_CREDENTIAL_MATCHES).safeParse(parsed);
|
|
11591
11931
|
if (!result.success)
|
|
11592
11932
|
throw new Fault(422, "vault_metadata_invalid", "Hasna Secrets returned an unsupported credential metadata shape.");
|
|
11593
11933
|
for (const entry of result.data)
|
|
11594
11934
|
entries.set(entry.key, entry);
|
|
11595
|
-
if (entries.size >
|
|
11935
|
+
if (entries.size > MAX_CREDENTIAL_MATCHES)
|
|
11596
11936
|
throw new Fault(422, "credential_matches_too_many", "More than 256 credential references matched. Bind an exact vault key explicitly.");
|
|
11597
11937
|
}
|
|
11598
11938
|
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 } }));
|
|
@@ -11639,6 +11979,9 @@ function authenticationProbe(provider) {
|
|
|
11639
11979
|
return { url, method: provider.credentialCheck.method ?? "GET", authStyle: provider.authStyle ?? "bearer" };
|
|
11640
11980
|
}
|
|
11641
11981
|
const base = new URL(provider.baseUrl);
|
|
11982
|
+
const bedrockOrigin = bedrockMantleOrigin(provider.baseUrl);
|
|
11983
|
+
if (provider.protocol === "anthropic-messages" && bedrockOrigin)
|
|
11984
|
+
return { url: new URL("/v1/models", bedrockOrigin), method: "GET", authStyle: "bearer" };
|
|
11642
11985
|
if (provider.credentialEnv === "SWITCHER_PROVIDER_OPENROUTER" && base.origin === "https://openrouter.ai" && base.pathname.replace(/\/+$/, "") === "/api/v1")
|
|
11643
11986
|
return { url: new URL("https://openrouter.ai/api/v1/key"), method: "GET", authStyle: provider.authStyle ?? "bearer" };
|
|
11644
11987
|
return;
|
|
@@ -12312,18 +12655,19 @@ function oriLaunchWarnings(target) {
|
|
|
12312
12655
|
|
|
12313
12656
|
// src/chatgpt-launch.ts
|
|
12314
12657
|
import { createHash as createHash12 } from "crypto";
|
|
12315
|
-
import { writeFile as
|
|
12316
|
-
import { join as
|
|
12658
|
+
import { writeFile as writeFile15, rm as rm4 } from "fs/promises";
|
|
12659
|
+
import { join as join18 } from "path";
|
|
12660
|
+
import { fileURLToPath } from "url";
|
|
12317
12661
|
|
|
12318
12662
|
// src/desktop-state.ts
|
|
12319
12663
|
import { Database as Database3 } from "bun:sqlite";
|
|
12320
|
-
import { readFile as
|
|
12664
|
+
import { readFile as readFile7, writeFile as writeFile14, rm as rm3, lstat as lstat7, rename as rename3, chmod as chmod2 } from "fs/promises";
|
|
12321
12665
|
async function safeDesktopRead(path) {
|
|
12322
12666
|
try {
|
|
12323
|
-
const info = await
|
|
12667
|
+
const info = await lstat7(path);
|
|
12324
12668
|
if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
|
|
12325
12669
|
throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user.");
|
|
12326
|
-
return await
|
|
12670
|
+
return await readFile7(path, "utf8");
|
|
12327
12671
|
} catch (error) {
|
|
12328
12672
|
if (error.code === "ENOENT")
|
|
12329
12673
|
return;
|
|
@@ -12333,7 +12677,7 @@ async function safeDesktopRead(path) {
|
|
|
12333
12677
|
async function writeDesktopPrivate(path, text) {
|
|
12334
12678
|
const temporary = path + "." + crypto.randomUUID() + ".tmp";
|
|
12335
12679
|
try {
|
|
12336
|
-
await
|
|
12680
|
+
await writeFile14(temporary, text, { mode: 384, flag: "wx" });
|
|
12337
12681
|
await rename3(temporary, path);
|
|
12338
12682
|
} finally {
|
|
12339
12683
|
await rm3(temporary, { force: true });
|
|
@@ -12341,7 +12685,7 @@ async function writeDesktopPrivate(path, text) {
|
|
|
12341
12685
|
}
|
|
12342
12686
|
async function desktopLease(path) {
|
|
12343
12687
|
try {
|
|
12344
|
-
const info = await
|
|
12688
|
+
const info = await lstat7(path);
|
|
12345
12689
|
if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
|
|
12346
12690
|
throw new Fault(422, "desktop_state_permissions", "Desktop lease must be a regular file owned by this user.");
|
|
12347
12691
|
} catch (error) {
|
|
@@ -12365,6 +12709,401 @@ async function desktopLease(path) {
|
|
|
12365
12709
|
};
|
|
12366
12710
|
}
|
|
12367
12711
|
|
|
12712
|
+
// src/native-state.ts
|
|
12713
|
+
import { lstat as lstat8, mkdir as mkdir11, open as open4, opendir, readlink as readlink2, realpath as realpath7, rmdir, symlink as symlink4, unlink as unlink2 } from "fs/promises";
|
|
12714
|
+
import { constants as constants7 } from "fs";
|
|
12715
|
+
import { homedir as homedir9 } from "os";
|
|
12716
|
+
import { dirname as dirname9, isAbsolute as isAbsolute16, join as join17, relative as relative5, resolve as resolve9 } from "path";
|
|
12717
|
+
function nativeStateRequested(tool, environment = process.env, explicit = false) {
|
|
12718
|
+
const suffix = tool.toUpperCase();
|
|
12719
|
+
return explicit || environment[`HASNA_${suffix}_STATE_HOME`] !== undefined || environment[`SUBSCRIPTIONS_SHARED_HOME_${suffix}`] !== undefined;
|
|
12720
|
+
}
|
|
12721
|
+
function validateNativeStateVersion(tool, version) {
|
|
12722
|
+
if (tool !== "codex")
|
|
12723
|
+
return;
|
|
12724
|
+
const match = version?.match(/(\d+)\.(\d+)\.(\d+)/), actual = match?.slice(1).map(Number);
|
|
12725
|
+
if (!actual || actual[0] !== 0 || actual[1] < 154)
|
|
12726
|
+
throw new Fault(422, "native_state_version", "Shared Codex state requires Codex 0.154.0 or newer, whose metadata and resume protocol has been acceptance-tested by Switcher.");
|
|
12727
|
+
}
|
|
12728
|
+
var CODEX_INSTRUCTION_KEYS = [
|
|
12729
|
+
"instructions",
|
|
12730
|
+
"developer_instructions",
|
|
12731
|
+
"model_instructions_file",
|
|
12732
|
+
"compact_prompt",
|
|
12733
|
+
"experimental_compact_prompt_file",
|
|
12734
|
+
"include_permissions_instructions",
|
|
12735
|
+
"include_apps_instructions",
|
|
12736
|
+
"include_collaboration_mode_instructions",
|
|
12737
|
+
"include_environment_context",
|
|
12738
|
+
"project_doc_max_bytes",
|
|
12739
|
+
"project_doc_fallback_filenames"
|
|
12740
|
+
];
|
|
12741
|
+
var NATIVE_STATE_ENTRIES = {
|
|
12742
|
+
codex: [
|
|
12743
|
+
...["sessions", "archived_sessions", "thread-writer-locks", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
|
|
12744
|
+
...["history.jsonl", "AGENTS.md", "AGENTS.override.md"].map((name) => ({ name, kind: "file" }))
|
|
12745
|
+
],
|
|
12746
|
+
claude: [
|
|
12747
|
+
...["projects", "todos", ".hasna/instructions"].map((name) => ({ name, kind: "directory" })),
|
|
12748
|
+
...["history.jsonl", "CLAUDE.md"].map((name) => ({ name, kind: "file" }))
|
|
12749
|
+
]
|
|
12750
|
+
};
|
|
12751
|
+
async function info(path) {
|
|
12752
|
+
try {
|
|
12753
|
+
return await lstat8(path);
|
|
12754
|
+
} catch (error) {
|
|
12755
|
+
if (error.code === "ENOENT")
|
|
12756
|
+
return;
|
|
12757
|
+
throw error;
|
|
12758
|
+
}
|
|
12759
|
+
}
|
|
12760
|
+
function absolute(value) {
|
|
12761
|
+
if (!isAbsolute16(value) || value.includes("\x00"))
|
|
12762
|
+
throw new Fault(422, "native_state_path", "The shared native state directory must be an absolute path.");
|
|
12763
|
+
return resolve9(value);
|
|
12764
|
+
}
|
|
12765
|
+
function credentialOverlay(path) {
|
|
12766
|
+
return /(?:^|\/)subscriptions\/profiles\//.test(path) || /(?:^|\/)switcher\/state\/(?:desktop|desktop-claude|launch-[^/]+)\//.test(path);
|
|
12767
|
+
}
|
|
12768
|
+
async function assertSafeAncestors(path) {
|
|
12769
|
+
for (let parent = path;; parent = dirname9(parent)) {
|
|
12770
|
+
const ancestor = await lstat8(parent);
|
|
12771
|
+
const stickyRoot = ancestor.uid === 0 && (ancestor.mode & 512) !== 0;
|
|
12772
|
+
if (!ancestor.isDirectory() || ancestor.isSymbolicLink() || ![0, process.getuid?.()].includes(ancestor.uid) || (ancestor.mode & 18) !== 0 && !stickyRoot)
|
|
12773
|
+
throw new Fault(422, "native_state_permissions", "Shared native state has an unsafe ancestor directory.");
|
|
12774
|
+
if (parent === dirname9(parent))
|
|
12775
|
+
break;
|
|
12776
|
+
}
|
|
12777
|
+
}
|
|
12778
|
+
async function assertNativeStateDirectory(path) {
|
|
12779
|
+
const entry = await info(path);
|
|
12780
|
+
if (!entry || !entry.isDirectory() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || await realpath7(path) !== path)
|
|
12781
|
+
throw new Fault(422, "native_state_permissions", "Shared native state must be an owned directory without writable or symbolic-link redirection.");
|
|
12782
|
+
await assertSafeAncestors(dirname9(path));
|
|
12783
|
+
}
|
|
12784
|
+
async function ensureNativeStateDirectory(path, create = true) {
|
|
12785
|
+
if (await info(path))
|
|
12786
|
+
return assertNativeStateDirectory(path);
|
|
12787
|
+
await ensureNativeStateDirectory(dirname9(path), create);
|
|
12788
|
+
if (!create)
|
|
12789
|
+
return;
|
|
12790
|
+
await mkdir11(path, { mode: 448 }).catch((error) => {
|
|
12791
|
+
if (error.code !== "EEXIST")
|
|
12792
|
+
throw error;
|
|
12793
|
+
});
|
|
12794
|
+
await assertNativeStateDirectory(path);
|
|
12795
|
+
}
|
|
12796
|
+
async function withNativeStateLock(state, operation) {
|
|
12797
|
+
await ensureNativeStateDirectory(state.home);
|
|
12798
|
+
const path = join17(state.home, ".switcher-shared-state.lock");
|
|
12799
|
+
let handle;
|
|
12800
|
+
try {
|
|
12801
|
+
handle = await open4(path, "wx", 384);
|
|
12802
|
+
} catch (error) {
|
|
12803
|
+
if (error.code !== "EEXIST")
|
|
12804
|
+
throw error;
|
|
12805
|
+
const entry = await info(path);
|
|
12806
|
+
if (!entry?.isFile() || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 63) !== 0)
|
|
12807
|
+
throw new Fault(422, "native_state_lock", "The shared-state lock has unsafe ownership, permissions or type.");
|
|
12808
|
+
throw new Fault(409, "native_state_busy", "Another Switcher projection/import owns this corpus, or a prior operation ended before releasing its lock. Inspect native processes and the lock before retrying.");
|
|
12809
|
+
}
|
|
12810
|
+
const identity = await handle.stat();
|
|
12811
|
+
try {
|
|
12812
|
+
return await operation();
|
|
12813
|
+
} finally {
|
|
12814
|
+
await handle.close();
|
|
12815
|
+
try {
|
|
12816
|
+
const entry = await lstat8(path);
|
|
12817
|
+
if (entry.dev === identity.dev && entry.ino === identity.ino)
|
|
12818
|
+
await unlink2(path);
|
|
12819
|
+
} catch (error) {
|
|
12820
|
+
if (error.code !== "ENOENT")
|
|
12821
|
+
throw error;
|
|
12822
|
+
}
|
|
12823
|
+
}
|
|
12824
|
+
}
|
|
12825
|
+
async function assertShareableTree(path, budget = { entries: 0 }, depth = 0) {
|
|
12826
|
+
if (depth > 32)
|
|
12827
|
+
throw new Fault(422, "native_state_inventory_limit", "The shared native corpus exceeds the safe projection inventory limit.");
|
|
12828
|
+
if (depth === 0)
|
|
12829
|
+
await assertNativeStateDirectory(path);
|
|
12830
|
+
for await (const child of await opendir(path)) {
|
|
12831
|
+
if (++budget.entries > 1e5 || child.isSymbolicLink())
|
|
12832
|
+
throw new Fault(422, "native_state_entry", "A shared native state tree contains an unsupported link or exceeds the safe inventory limit.");
|
|
12833
|
+
const nested = join17(path, child.name), entry = await lstat8(nested);
|
|
12834
|
+
if (entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0)
|
|
12835
|
+
throw new Fault(422, "native_state_entry", "A shared native state entry has unsafe ownership or writable permissions.");
|
|
12836
|
+
if (child.isDirectory()) {
|
|
12837
|
+
if (!entry.isDirectory())
|
|
12838
|
+
throw new Fault(422, "native_state_entry", "A shared native state directory changed during inspection.");
|
|
12839
|
+
await assertShareableTree(nested, budget, depth + 1);
|
|
12840
|
+
continue;
|
|
12841
|
+
}
|
|
12842
|
+
if (!child.isFile() || !entry.isFile() || entry.nlink !== 1)
|
|
12843
|
+
throw new Fault(422, "native_state_entry", "A shared native state tree contains an unsupported file type or hardlink.");
|
|
12844
|
+
}
|
|
12845
|
+
}
|
|
12846
|
+
async function readCodexStateConfig(home) {
|
|
12847
|
+
const path = join17(home, "config.toml"), entry = await info(path);
|
|
12848
|
+
if (!entry)
|
|
12849
|
+
return {};
|
|
12850
|
+
if (!entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || entry.uid !== process.getuid?.() || (entry.mode & 18) !== 0 || entry.size > 1024 * 1024)
|
|
12851
|
+
throw new Fault(422, "native_state_config", "The Codex instruction configuration cannot be read safely.");
|
|
12852
|
+
const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW);
|
|
12853
|
+
let config;
|
|
12854
|
+
try {
|
|
12855
|
+
const opened = await handle.stat();
|
|
12856
|
+
if (opened.ino !== entry.ino || opened.dev !== entry.dev || opened.nlink !== 1 || opened.size > 1024 * 1024)
|
|
12857
|
+
throw new Fault(409, "native_state_config", "The Codex instruction configuration changed during preparation.");
|
|
12858
|
+
config = Bun.TOML.parse(await handle.readFile("utf8"));
|
|
12859
|
+
} catch (error) {
|
|
12860
|
+
if (error instanceof Fault)
|
|
12861
|
+
throw error;
|
|
12862
|
+
throw new Fault(422, "native_state_config", "The Codex instruction configuration is invalid.");
|
|
12863
|
+
} finally {
|
|
12864
|
+
await handle.close();
|
|
12865
|
+
}
|
|
12866
|
+
if (config.profile !== undefined || config.include !== undefined)
|
|
12867
|
+
throw new Fault(422, "native_state_config", "Codex profile/include selection is unsupported by the verified shared-state instruction contract. Resolve that effective configuration before launching; Switcher will not silently discard its instructions.");
|
|
12868
|
+
return config;
|
|
12869
|
+
}
|
|
12870
|
+
var CODEX_INSTRUCTION_FILE_KEYS = new Set(["model_instructions_file", "experimental_compact_prompt_file"]);
|
|
12871
|
+
async function codexInstructionProjection(home, config, allowedExternalFiles = {}) {
|
|
12872
|
+
const instructions = {};
|
|
12873
|
+
for (const key of CODEX_INSTRUCTION_KEYS) {
|
|
12874
|
+
const value = config[key];
|
|
12875
|
+
if (value === undefined)
|
|
12876
|
+
continue;
|
|
12877
|
+
const valid = key.startsWith("include_") ? typeof value === "boolean" : key === "project_doc_max_bytes" ? typeof value === "number" && Number.isSafeInteger(value) && value >= 0 : key === "project_doc_fallback_filenames" ? Array.isArray(value) && value.every((item2) => typeof item2 === "string" && !item2.includes("\x00")) : typeof value === "string" && !value.includes("\x00");
|
|
12878
|
+
if (!valid)
|
|
12879
|
+
throw new Fault(422, "native_state_instructions", "Codex instruction configuration has an unsupported value.");
|
|
12880
|
+
if (CODEX_INSTRUCTION_FILE_KEYS.has(key)) {
|
|
12881
|
+
const path = resolve9(home, value), entry = await info(path);
|
|
12882
|
+
const relativePath = relative5(home, path), contained = relativePath !== ".." && !relativePath.startsWith("../") && !isAbsolute16(relativePath);
|
|
12883
|
+
if (!contained && path !== allowedExternalFiles[key] || !entry || !entry.isFile() || entry.nlink !== 1 || entry.isSymbolicLink() || ![0, process.getuid?.()].includes(entry.uid) || (entry.mode & 18) !== 0 || await realpath7(path) !== path)
|
|
12884
|
+
throw new Fault(422, "native_state_instructions", "The configured instruction file is not a readable trusted file.");
|
|
12885
|
+
await assertSafeAncestors(dirname9(path));
|
|
12886
|
+
const handle = await open4(path, constants7.O_RDONLY | constants7.O_NOFOLLOW).catch(() => {
|
|
12887
|
+
throw new Fault(422, "native_state_instructions", "The configured instruction file is not readable.");
|
|
12888
|
+
});
|
|
12889
|
+
try {
|
|
12890
|
+
const opened = await handle.stat();
|
|
12891
|
+
if (opened.ino !== entry.ino || opened.dev !== entry.dev || opened.nlink !== 1)
|
|
12892
|
+
throw new Fault(409, "native_state_instructions", "The configured instruction file changed during preparation.");
|
|
12893
|
+
} finally {
|
|
12894
|
+
await handle.close();
|
|
12895
|
+
}
|
|
12896
|
+
instructions[key] = path;
|
|
12897
|
+
} else
|
|
12898
|
+
instructions[key] = value;
|
|
12899
|
+
}
|
|
12900
|
+
return instructions;
|
|
12901
|
+
}
|
|
12902
|
+
async function assertNativeInstructionOverlay(state, overlayHome) {
|
|
12903
|
+
if (state.tool !== "codex" || absolute(overlayHome) === state.home)
|
|
12904
|
+
return;
|
|
12905
|
+
await assertNativeStateDirectory(overlayHome);
|
|
12906
|
+
const config = await readCodexStateConfig(overlayHome);
|
|
12907
|
+
if (config.profiles !== undefined || config.include !== undefined)
|
|
12908
|
+
throw new Fault(422, "native_state_instruction_overlay", "Private Codex profile/include instruction overlays are not supported. Resolve their effective canonical instructions before launching.");
|
|
12909
|
+
const expected = state.instructions ?? {};
|
|
12910
|
+
const allowedExternalFiles = Object.fromEntries([...CODEX_INSTRUCTION_FILE_KEYS].flatMap((key) => typeof expected[key] === "string" ? [[key, expected[key]]] : []));
|
|
12911
|
+
const actual = await codexInstructionProjection(overlayHome, config, allowedExternalFiles);
|
|
12912
|
+
if (CODEX_INSTRUCTION_KEYS.some((key) => JSON.stringify(actual[key]) !== JSON.stringify(expected[key])))
|
|
12913
|
+
throw new Fault(409, "native_state_instruction_overlay", "This Codex authentication home has missing or conflicting canonical instructions. Refresh its instruction projection before launching; Switcher will not rewrite private account configuration.");
|
|
12914
|
+
}
|
|
12915
|
+
async function resolveNativeState(tool, environment = process.env, options = {}) {
|
|
12916
|
+
if (process.platform === "win32")
|
|
12917
|
+
throw new Fault(422, "unsupported_platform", "Shared native state currently requires POSIX ownership, no-follow and symlink semantics on Linux or macOS.");
|
|
12918
|
+
const suffix = tool.toUpperCase();
|
|
12919
|
+
const marker = `HASNA_${suffix}_STATE_HOME`, legacyMarker = `SUBSCRIPTIONS_SHARED_HOME_${suffix}`;
|
|
12920
|
+
const primary = environment[marker], legacy = environment[legacyMarker];
|
|
12921
|
+
if (primary !== undefined && legacy !== undefined && absolute(primary) !== absolute(legacy))
|
|
12922
|
+
throw new Fault(409, "native_state_identity_conflict", `The ${marker} and ${legacyMarker} corpus identities disagree. Select one exact shared native state directory before launching.`);
|
|
12923
|
+
const userHome = absolute(environment.HOME ?? homedir9());
|
|
12924
|
+
const selected = primary !== undefined ? absolute(primary) : legacy !== undefined ? absolute(legacy) : join17(userHome, `.${tool}`);
|
|
12925
|
+
if (credentialOverlay(selected))
|
|
12926
|
+
throw new Fault(422, "native_state_overlay", "An authentication profile cannot be the shared native state directory. Select its original native state directory.");
|
|
12927
|
+
await ensureNativeStateDirectory(selected, options.create !== false);
|
|
12928
|
+
if (tool === "claude")
|
|
12929
|
+
return { tool, home: selected, marker };
|
|
12930
|
+
const config = await readCodexStateConfig(selected);
|
|
12931
|
+
let sqliteHome = selected;
|
|
12932
|
+
if (config.sqlite_home !== undefined) {
|
|
12933
|
+
if (typeof config.sqlite_home !== "string")
|
|
12934
|
+
throw new Fault(422, "native_state_config", "Codex sqlite_home must be an absolute directory.");
|
|
12935
|
+
sqliteHome = absolute(config.sqlite_home);
|
|
12936
|
+
if (credentialOverlay(sqliteHome))
|
|
12937
|
+
throw new Fault(422, "native_state_overlay", "Codex SQLite state cannot belong to an authentication profile.");
|
|
12938
|
+
await ensureNativeStateDirectory(sqliteHome, options.create !== false);
|
|
12939
|
+
}
|
|
12940
|
+
const instructions = await codexInstructionProjection(selected, config);
|
|
12941
|
+
return { tool, home: selected, sqliteHome, marker, instructions };
|
|
12942
|
+
}
|
|
12943
|
+
function nativeStateEnvironment(state) {
|
|
12944
|
+
return state.tool === "codex" && state.sqliteHome ? { CODEX_SQLITE_HOME: state.sqliteHome } : {};
|
|
12945
|
+
}
|
|
12946
|
+
async function assertCodexDatabaseRedirectSafe(state, overlayHome) {
|
|
12947
|
+
if (state.tool !== "codex")
|
|
12948
|
+
return;
|
|
12949
|
+
const config = await readCodexStateConfig(overlayHome);
|
|
12950
|
+
const previous = config.sqlite_home;
|
|
12951
|
+
if (previous !== undefined && typeof previous !== "string")
|
|
12952
|
+
throw new Fault(422, "native_state_config", "The previous Codex sqlite_home must be an absolute directory.");
|
|
12953
|
+
const roots = new Set([overlayHome, ...typeof previous === "string" ? [absolute(previous)] : []]);
|
|
12954
|
+
for (const root of roots) {
|
|
12955
|
+
if (root === (state.sqliteHome ?? state.home) || !await info(root))
|
|
12956
|
+
continue;
|
|
12957
|
+
await assertNativeStateDirectory(root);
|
|
12958
|
+
const before = await lstat8(root);
|
|
12959
|
+
let inspected = 0;
|
|
12960
|
+
for await (const entry of await opendir(root)) {
|
|
12961
|
+
if (++inspected > 1e4)
|
|
12962
|
+
throw new Fault(409, "native_state_inventory_limit", "Native database inventory exceeded its bounded limit; no state was projected.");
|
|
12963
|
+
if (/^(?:state|logs|goals|memories|queue|thread_history)_\d+\.sqlite(?:-(?:wal|shm))?$/.test(entry.name))
|
|
12964
|
+
throw new Fault(409, "native_state_migration_required", "This profile retains native database metadata. Reconcile its catalog and history before redirecting shared state.");
|
|
12965
|
+
}
|
|
12966
|
+
const after = await lstat8(root);
|
|
12967
|
+
if (after.isSymbolicLink() || before.dev !== after.dev || before.ino !== after.ino || before.mtimeMs !== after.mtimeMs)
|
|
12968
|
+
throw new Fault(409, "native_state_inventory_changed", "Native database inventory changed; no state was projected.");
|
|
12969
|
+
}
|
|
12970
|
+
}
|
|
12971
|
+
async function directoryHasEntries(path) {
|
|
12972
|
+
const directory = await opendir(path);
|
|
12973
|
+
try {
|
|
12974
|
+
return Boolean(await directory.read());
|
|
12975
|
+
} finally {
|
|
12976
|
+
await directory.close();
|
|
12977
|
+
}
|
|
12978
|
+
}
|
|
12979
|
+
async function legacyNativeStateWarnings(root, state) {
|
|
12980
|
+
const directory = join17(root, state.tool === "codex" ? "desktop" : "desktop-claude");
|
|
12981
|
+
if (!await info(directory))
|
|
12982
|
+
return [];
|
|
12983
|
+
await assertNativeStateDirectory(directory);
|
|
12984
|
+
const pending = [];
|
|
12985
|
+
let inspected = 0;
|
|
12986
|
+
for await (const entry of await opendir(directory)) {
|
|
12987
|
+
if (++inspected > 1000)
|
|
12988
|
+
throw new Fault(409, "native_state_inventory_limit", "Too many legacy desktop profiles to inspect safely.");
|
|
12989
|
+
if (!entry.isDirectory() || entry.isSymbolicLink())
|
|
12990
|
+
continue;
|
|
12991
|
+
const home = join17(directory, entry.name, ...state.tool === "codex" ? ["codex"] : []);
|
|
12992
|
+
if (!await info(home))
|
|
12993
|
+
continue;
|
|
12994
|
+
await assertNativeStateDirectory(home);
|
|
12995
|
+
for (const name of [...NATIVE_STATE_ENTRIES[state.tool].map((item2) => item2.name), ...state.tool === "codex" ? ["state_5.sqlite", "session_index.jsonl"] : []]) {
|
|
12996
|
+
const path = join17(home, name), item2 = await info(path);
|
|
12997
|
+
if (!item2 || item2.isSymbolicLink())
|
|
12998
|
+
continue;
|
|
12999
|
+
if (item2.isFile() && item2.size > 0 || item2.isDirectory() && await directoryHasEntries(path)) {
|
|
13000
|
+
pending.push(home);
|
|
13001
|
+
break;
|
|
13002
|
+
}
|
|
13003
|
+
}
|
|
13004
|
+
}
|
|
13005
|
+
const display = (path) => {
|
|
13006
|
+
const value = JSON.stringify(path).replace(/[\u007f-\u009f\u061c\u200e\u200f\u2028-\u202e\u2066-\u2069]/g, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
|
|
13007
|
+
return value.length > 768 ? `${value.slice(0, 384)}...${value.slice(-381)}` : value;
|
|
13008
|
+
};
|
|
13009
|
+
const warnings = pending.slice(0, 10).map((home) => `Legacy native state is preserved at ${display(home)}; migration is pending. Inspect with switcher state import ${state.tool} --from ${display(home)}. A copied snapshot does not retire the original or migrate its SQLite/index metadata.`);
|
|
13010
|
+
if (pending.length > warnings.length)
|
|
13011
|
+
warnings.push(`${pending.length - warnings.length} additional legacy ${state.tool} state directories are pending migration; inspect the Switcher state root before launch.`);
|
|
13012
|
+
return warnings;
|
|
13013
|
+
}
|
|
13014
|
+
async function createTrackedDirectory(path, created) {
|
|
13015
|
+
try {
|
|
13016
|
+
await mkdir11(path, { mode: 448 });
|
|
13017
|
+
created.push(path);
|
|
13018
|
+
} catch (error) {
|
|
13019
|
+
if (error.code !== "EEXIST")
|
|
13020
|
+
throw error;
|
|
13021
|
+
await assertNativeStateDirectory(path);
|
|
13022
|
+
}
|
|
13023
|
+
}
|
|
13024
|
+
async function projectNativeStateUnlocked(state, overlayHome) {
|
|
13025
|
+
overlayHome = absolute(overlayHome);
|
|
13026
|
+
await assertNativeStateDirectory(state.home);
|
|
13027
|
+
await assertNativeStateDirectory(overlayHome);
|
|
13028
|
+
if (overlayHome === state.home)
|
|
13029
|
+
return;
|
|
13030
|
+
const contains = (parent, child) => {
|
|
13031
|
+
const suffix = relative5(parent, child);
|
|
13032
|
+
return suffix !== ".." && !suffix.startsWith("../") && !isAbsolute16(suffix);
|
|
13033
|
+
};
|
|
13034
|
+
if (contains(state.home, overlayHome) || contains(overlayHome, state.home))
|
|
13035
|
+
throw new Fault(422, "native_state_overlap", "The shared corpus and authentication overlay must be separate directories.");
|
|
13036
|
+
await assertCodexDatabaseRedirectSafe(state, overlayHome);
|
|
13037
|
+
for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
|
|
13038
|
+
const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
|
|
13039
|
+
await ensureNativeStateDirectory(dirname9(target), false);
|
|
13040
|
+
await ensureNativeStateDirectory(dirname9(destination), false);
|
|
13041
|
+
const source = await info(target), existing = await info(destination);
|
|
13042
|
+
if (source && (source.isSymbolicLink() || source.uid !== process.getuid?.() || (source.mode & 18) !== 0 || source.isFile() && source.nlink !== 1 || (entry.kind === "directory" ? !source.isDirectory() : !source.isFile())))
|
|
13043
|
+
throw new Fault(422, "native_state_entry", "A shared native state entry has an unsupported type, owner or permissions.");
|
|
13044
|
+
if (source?.isDirectory())
|
|
13045
|
+
await assertShareableTree(target);
|
|
13046
|
+
if (existing && (!existing.isSymbolicLink() || resolve9(dirname9(destination), await readlink2(destination)) !== target))
|
|
13047
|
+
throw new Fault(409, "native_state_migration_required", "This launch profile already contains native state. Preserve and migrate its noncredential state before linking the shared corpus.");
|
|
13048
|
+
}
|
|
13049
|
+
const createdLinks = [];
|
|
13050
|
+
const createdFiles = [], createdDirectories = [];
|
|
13051
|
+
try {
|
|
13052
|
+
for (const entry of NATIVE_STATE_ENTRIES[state.tool]) {
|
|
13053
|
+
const target = join17(state.home, entry.name), destination = join17(overlayHome, entry.name);
|
|
13054
|
+
const targetParent = dirname9(target), destinationParent = dirname9(destination);
|
|
13055
|
+
if (!await info(targetParent))
|
|
13056
|
+
await createTrackedDirectory(targetParent, createdDirectories);
|
|
13057
|
+
else
|
|
13058
|
+
await assertNativeStateDirectory(targetParent);
|
|
13059
|
+
if (!await info(destinationParent))
|
|
13060
|
+
await createTrackedDirectory(destinationParent, createdDirectories);
|
|
13061
|
+
else
|
|
13062
|
+
await assertNativeStateDirectory(destinationParent);
|
|
13063
|
+
if (entry.kind === "file" && !await info(target))
|
|
13064
|
+
continue;
|
|
13065
|
+
if (!await info(target)) {
|
|
13066
|
+
if (entry.kind === "directory")
|
|
13067
|
+
await createTrackedDirectory(target, createdDirectories);
|
|
13068
|
+
else {
|
|
13069
|
+
const file = await open4(target, "wx", 384);
|
|
13070
|
+
await file.close();
|
|
13071
|
+
createdFiles.push(target);
|
|
13072
|
+
}
|
|
13073
|
+
}
|
|
13074
|
+
if (!await info(destination)) {
|
|
13075
|
+
await symlink4(target, destination, entry.kind === "directory" ? "dir" : "file");
|
|
13076
|
+
createdLinks.push({ destination, target });
|
|
13077
|
+
}
|
|
13078
|
+
}
|
|
13079
|
+
} catch (error) {
|
|
13080
|
+
for (const item2 of createdLinks.reverse()) {
|
|
13081
|
+
try {
|
|
13082
|
+
if ((await info(item2.destination))?.isSymbolicLink() && resolve9(dirname9(item2.destination), await readlink2(item2.destination)) === item2.target)
|
|
13083
|
+
await unlink2(item2.destination);
|
|
13084
|
+
} catch {}
|
|
13085
|
+
}
|
|
13086
|
+
for (const path of createdFiles.reverse()) {
|
|
13087
|
+
try {
|
|
13088
|
+
const entry = await info(path);
|
|
13089
|
+
if (entry?.isFile() && entry.nlink === 1 && entry.size === 0)
|
|
13090
|
+
await unlink2(path);
|
|
13091
|
+
} catch {}
|
|
13092
|
+
}
|
|
13093
|
+
for (const path of [...new Set(createdDirectories)].sort((a, b) => b.length - a.length)) {
|
|
13094
|
+
try {
|
|
13095
|
+
await rmdir(path);
|
|
13096
|
+
} catch {}
|
|
13097
|
+
}
|
|
13098
|
+
throw error;
|
|
13099
|
+
}
|
|
13100
|
+
}
|
|
13101
|
+
async function projectNativeState(state, overlayHome) {
|
|
13102
|
+
if (absolute(overlayHome) === state.home)
|
|
13103
|
+
return;
|
|
13104
|
+
return withNativeStateLock(state, () => projectNativeStateUnlocked(state, overlayHome));
|
|
13105
|
+
}
|
|
13106
|
+
|
|
12368
13107
|
// src/chatgpt-launch.ts
|
|
12369
13108
|
var object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
12370
13109
|
function merge2(base, overlay) {
|
|
@@ -12373,16 +13112,41 @@ function merge2(base, overlay) {
|
|
|
12373
13112
|
result[key] = object5(value) && object5(result[key]) ? merge2(result[key], value) : value;
|
|
12374
13113
|
return result;
|
|
12375
13114
|
}
|
|
13115
|
+
function clearSwitcherModelState(config) {
|
|
13116
|
+
for (const key of [...codexRoutingKeys, "review_model", "sqlite_home", "model_reasoning_effort", "cli_auth_credentials_store", "forced_login_method", ...CODEX_INSTRUCTION_KEYS])
|
|
13117
|
+
delete config[key];
|
|
13118
|
+
if (object5(config.agents)) {
|
|
13119
|
+
for (const key of ["default_subagent_model", "default_subagent_reasoning_effort", "default_subagent_reasoning_summary"])
|
|
13120
|
+
delete config.agents[key];
|
|
13121
|
+
for (const [name, value] of Object.entries(config.agents))
|
|
13122
|
+
if (object5(value)) {
|
|
13123
|
+
for (const key of ["model", "model_provider", "provider", "config_file"])
|
|
13124
|
+
delete value[key];
|
|
13125
|
+
if (!Object.keys(value).length)
|
|
13126
|
+
delete config.agents[name];
|
|
13127
|
+
}
|
|
13128
|
+
if (!Object.keys(config.agents).length)
|
|
13129
|
+
delete config.agents;
|
|
13130
|
+
}
|
|
13131
|
+
if (object5(config.memories)) {
|
|
13132
|
+
delete config.memories.extract_model;
|
|
13133
|
+
delete config.memories.consolidation_model;
|
|
13134
|
+
if (!Object.keys(config.memories).length)
|
|
13135
|
+
delete config.memories;
|
|
13136
|
+
}
|
|
13137
|
+
}
|
|
12376
13138
|
var digest = (value) => createHash12("sha256").update(value).digest("hex");
|
|
12377
13139
|
var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
12378
|
-
async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
13140
|
+
async function prepareChatGPTLaunch(native, app, stateDir, sessionDir, sharedState) {
|
|
13141
|
+
if (sharedState && sharedState.tool !== "codex")
|
|
13142
|
+
throw new Fault(422, "native_state_tool", "ChatGPT requires the canonical Codex corpus.");
|
|
12379
13143
|
await privateDirectory(sessionDir);
|
|
12380
|
-
const home =
|
|
13144
|
+
const home = join18(sessionDir, "codex"), userData = join18(sessionDir, "electron");
|
|
12381
13145
|
await privateDirectory(home);
|
|
12382
13146
|
await privateDirectory(userData);
|
|
12383
|
-
const release = await desktopLease(
|
|
13147
|
+
const release = await desktopLease(join18(sessionDir, "launch.sqlite"));
|
|
12384
13148
|
let released = false, authText;
|
|
12385
|
-
const authPath =
|
|
13149
|
+
const authPath = join18(home, "auth.json"), receiptPath = join18(home, ".switcher-auth.sha256");
|
|
12386
13150
|
const cleanup = async () => {
|
|
12387
13151
|
if (released)
|
|
12388
13152
|
return;
|
|
@@ -12397,18 +13161,23 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
|
12397
13161
|
}
|
|
12398
13162
|
};
|
|
12399
13163
|
try {
|
|
13164
|
+
if (sharedState)
|
|
13165
|
+
await projectNativeState(sharedState, home);
|
|
12400
13166
|
const settings2 = [];
|
|
12401
13167
|
for (let i = 0;i < native.args.length; i += 2) {
|
|
12402
13168
|
if (native.args[i] !== "-c" || typeof native.args[i + 1] !== "string")
|
|
12403
13169
|
throw new Fault(400, "desktop_arguments", "Desktop launches accept provider/model settings, not native CLI commands.");
|
|
12404
|
-
|
|
13170
|
+
if (!sharedState?.sqliteHome || !native.args[i + 1].startsWith("sqlite_home="))
|
|
13171
|
+
settings2.push(native.args[i + 1]);
|
|
12405
13172
|
}
|
|
12406
13173
|
settings2.push('cli_auth_credentials_store="file"', 'forced_login_method="api"');
|
|
13174
|
+
if (sharedState?.sqliteHome)
|
|
13175
|
+
settings2.push(`sqlite_home=${JSON.stringify(sharedState.sqliteHome)}`);
|
|
12407
13176
|
if (!settings2.some((setting) => setting.startsWith("approval_policy=")))
|
|
12408
13177
|
settings2.push('approval_policy="on-request"');
|
|
12409
13178
|
if (!settings2.some((setting) => setting.startsWith("sandbox_mode=")))
|
|
12410
13179
|
settings2.push('sandbox_mode="workspace-write"');
|
|
12411
|
-
const configPath =
|
|
13180
|
+
const configPath = join18(home, "config.toml");
|
|
12412
13181
|
const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
|
|
12413
13182
|
if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
|
|
12414
13183
|
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.");
|
|
@@ -12419,6 +13188,12 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
|
12419
13188
|
if (error.code !== "ENOENT")
|
|
12420
13189
|
throw new Fault(422, "desktop_config_invalid", "The desktop profile config cannot be read safely.");
|
|
12421
13190
|
}
|
|
13191
|
+
if (sharedState) {
|
|
13192
|
+
if (["profile", "profiles", "include"].some((key2) => existing[key2] !== undefined))
|
|
13193
|
+
throw new Fault(409, "desktop_config_routing", "The private desktop overlay contains profile/include routing that cannot be reconciled with shared native state. Review the overlay before launching.");
|
|
13194
|
+
clearSwitcherModelState(existing);
|
|
13195
|
+
Object.assign(existing, sharedState.instructions);
|
|
13196
|
+
}
|
|
12422
13197
|
const config = merge2(existing, Bun.TOML.parse(settings2.join(`
|
|
12423
13198
|
`)));
|
|
12424
13199
|
await writeDesktopPrivate(configPath, renderCodexAgentToml(config));
|
|
@@ -12429,24 +13204,36 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
|
12429
13204
|
`;
|
|
12430
13205
|
await writeDesktopPrivate(receiptPath, digest(authText));
|
|
12431
13206
|
await writeDesktopPrivate(authPath, authText);
|
|
12432
|
-
const wrapper =
|
|
13207
|
+
const wrapper = join18(stateDir, "chatgpt-codex");
|
|
12433
13208
|
const overrides = settings2.flatMap((setting) => ["-c", setting]);
|
|
12434
|
-
|
|
13209
|
+
let bridge = "";
|
|
13210
|
+
if (sharedState) {
|
|
13211
|
+
const entry = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./codex-state-bridge.ts" : "../codex-state-bridge.js", import.meta.url));
|
|
13212
|
+
const ownedKeys = new Set(["model_provider", "model_providers", "model_catalog_json", "review_model", "agents", "memories", "sqlite_home"]);
|
|
13213
|
+
const routing3 = Object.fromEntries(Object.entries(config).filter(([key2]) => ownedKeys.has(key2)));
|
|
13214
|
+
if (typeof config.model !== "string")
|
|
13215
|
+
throw new Fault(500, "desktop_model_missing", "Desktop preparation did not receive its selected model.");
|
|
13216
|
+
bridge = `if [ "\${1-}" = app-server ]; then
|
|
13217
|
+
exec ${[process.execPath, entry, app.codexExecutable, config.model, JSON.stringify(routing3)].map(quote2).join(" ")} "$@" ${overrides.map(quote2).join(" ")}
|
|
13218
|
+
fi
|
|
13219
|
+
`;
|
|
13220
|
+
}
|
|
13221
|
+
await writeFile15(wrapper, `#!/bin/sh
|
|
12435
13222
|
set -eu
|
|
12436
13223
|
unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
|
|
12437
13224
|
export CODEX_HOME=${quote2(home)}
|
|
12438
13225
|
if [ "\${1-}" = sandbox ]; then
|
|
12439
13226
|
exec ${quote2(app.codexExecutable)} "$@"
|
|
12440
13227
|
fi
|
|
12441
|
-
exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
|
|
13228
|
+
${bridge}exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
|
|
12442
13229
|
`, { mode: 448, flag: "wx" });
|
|
12443
13230
|
return {
|
|
12444
13231
|
...native,
|
|
12445
13232
|
executable: app.executable,
|
|
12446
13233
|
args: [`--user-data-dir=${userData}`],
|
|
12447
|
-
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" },
|
|
13234
|
+
env: { ...native.env, ...sharedState ? nativeStateEnvironment(sharedState) : {}, 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" },
|
|
12448
13235
|
configPaths: [...native.configPaths, configPath, wrapper],
|
|
12449
|
-
warnings: [...native.warnings, `ChatGPT provider
|
|
13236
|
+
warnings: [...native.warnings, `ChatGPT provider state is isolated.${sharedState ? " Allowlisted local sessions and instructions use the explicitly selected shared corpus across providers." : ""} 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.`],
|
|
12450
13237
|
cleanup: async () => {
|
|
12451
13238
|
try {
|
|
12452
13239
|
await native.cleanup?.();
|
|
@@ -12464,15 +13251,15 @@ exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
|
|
|
12464
13251
|
// src/claude-desktop-launch.ts
|
|
12465
13252
|
import { createHash as createHash13 } from "crypto";
|
|
12466
13253
|
import { execFile as execFile5 } from "child_process";
|
|
12467
|
-
import { access as access5, rm as rm5, writeFile as
|
|
12468
|
-
import { homedir as
|
|
12469
|
-
import { join as
|
|
13254
|
+
import { access as access5, rm as rm5, writeFile as writeFile16 } from "fs/promises";
|
|
13255
|
+
import { homedir as homedir10, userInfo as userInfo2 } from "os";
|
|
13256
|
+
import { join as join19 } from "path";
|
|
12470
13257
|
import { promisify as promisify5 } from "util";
|
|
12471
13258
|
var execute4 = promisify5(execFile5);
|
|
12472
13259
|
var hash2 = (text) => createHash13("sha256").update(text).digest("hex");
|
|
12473
|
-
var claudeDesktopDataDirectory = () =>
|
|
13260
|
+
var claudeDesktopDataDirectory = () => join19(homedir10(), "Library/Application Support/Claude-3p");
|
|
12474
13261
|
async function assertAvailable(userData) {
|
|
12475
|
-
for (const path of [
|
|
13262
|
+
for (const path of [join19("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
|
|
12476
13263
|
if (await access5(path).then(() => true, () => false))
|
|
12477
13264
|
throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
|
|
12478
13265
|
let openFiles;
|
|
@@ -12496,6 +13283,8 @@ function metadata(text) {
|
|
|
12496
13283
|
async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
12497
13284
|
if (input.harness !== "claude")
|
|
12498
13285
|
throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
|
|
13286
|
+
if (input.sharedState && input.sharedState.tool !== "claude")
|
|
13287
|
+
throw new Fault(422, "native_state_tool", "Claude desktop requires the canonical Claude corpus.");
|
|
12499
13288
|
validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
|
|
12500
13289
|
if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
|
|
12501
13290
|
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.");
|
|
@@ -12506,15 +13295,15 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12506
13295
|
const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
|
|
12507
13296
|
await check2();
|
|
12508
13297
|
await privateDirectory(userData);
|
|
12509
|
-
const library =
|
|
13298
|
+
const library = join19(userData, "configLibrary");
|
|
12510
13299
|
await privateDirectory(library);
|
|
12511
|
-
const release = await desktopLease(
|
|
12512
|
-
const metaPath =
|
|
13300
|
+
const release = await desktopLease(join19(library, ".switcher-lease.sqlite"));
|
|
13301
|
+
const metaPath = join19(library, "_meta.json"), receiptPath = join19(library, ".switcher-selection.json");
|
|
12513
13302
|
let receipt, gateway, closed = false;
|
|
12514
13303
|
const restore = async (record3) => {
|
|
12515
13304
|
if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
|
|
12516
13305
|
throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
|
|
12517
|
-
const configPath =
|
|
13306
|
+
const configPath = join19(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
|
|
12518
13307
|
if (current !== undefined && hash2(current) !== record3.configHash)
|
|
12519
13308
|
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.");
|
|
12520
13309
|
const currentMeta = await safeDesktopRead(metaPath);
|
|
@@ -12543,10 +13332,12 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12543
13332
|
const recovery = await safeDesktopRead(receiptPath);
|
|
12544
13333
|
if (recovery)
|
|
12545
13334
|
await restore(JSON.parse(recovery));
|
|
12546
|
-
const localConfig = await safeDesktopRead(
|
|
13335
|
+
const localConfig = await safeDesktopRead(join19(userData, "claude_desktop_config.json"));
|
|
12547
13336
|
if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
|
|
12548
13337
|
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.");
|
|
12549
13338
|
await privateDirectory(sessionDir);
|
|
13339
|
+
if (input.sharedState)
|
|
13340
|
+
await projectNativeState(input.sharedState, sessionDir);
|
|
12550
13341
|
const roles2 = input.modelPolicy?.roles;
|
|
12551
13342
|
const targets = { sonnet: input.model, opus: roles2?.planning ?? input.model, haiku: roles2?.fast ?? input.model };
|
|
12552
13343
|
const aliases = Object.fromEntries(Object.entries(targets).map(([tier, model3]) => ["switcher/" + tier, model3]));
|
|
@@ -12554,10 +13345,10 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12554
13345
|
if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
|
|
12555
13346
|
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.");
|
|
12556
13347
|
const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
|
|
12557
|
-
const catalogPath =
|
|
12558
|
-
await
|
|
13348
|
+
const catalogPath = join19(input.stateDir, "claude-desktop-policy.json");
|
|
13349
|
+
await writeFile16(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
|
|
12559
13350
|
gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
12560
|
-
const id2 = crypto.randomUUID(), configPath =
|
|
13351
|
+
const id2 = crypto.randomUUID(), configPath = join19(library, id2 + ".json");
|
|
12561
13352
|
const config = JSON.stringify({
|
|
12562
13353
|
inferenceProvider: "gateway",
|
|
12563
13354
|
inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
|
|
@@ -12576,7 +13367,7 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12576
13367
|
return {
|
|
12577
13368
|
executable: app.executable,
|
|
12578
13369
|
args: [],
|
|
12579
|
-
env: { CLAUDE_CONFIG_DIR: sessionDir },
|
|
13370
|
+
env: { ...input.sharedState ? nativeStateEnvironment(input.sharedState) : {}, CLAUDE_CONFIG_DIR: sessionDir },
|
|
12580
13371
|
configPaths: [catalogPath, configPath],
|
|
12581
13372
|
beforeLaunch: check2,
|
|
12582
13373
|
cleanup,
|
|
@@ -12590,16 +13381,220 @@ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
|
12590
13381
|
}
|
|
12591
13382
|
}
|
|
12592
13383
|
|
|
13384
|
+
// src/codex-session-discovery.ts
|
|
13385
|
+
import { spawn as spawn3 } from "child_process";
|
|
13386
|
+
import { createInterface as createInterface2 } from "readline/promises";
|
|
13387
|
+
import { basename as basename3, resolve as resolve10 } from "path";
|
|
13388
|
+
var object6 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
13389
|
+
var unavailable = () => new Fault(422, "codex_session_discovery", "Native Codex session discovery failed. No conversation was started. Retry discovery or provide an exact session ID.");
|
|
13390
|
+
async function listCodexSessions(prepared, cwd, query) {
|
|
13391
|
+
if (!Number.isSafeInteger(query.limit) || query.limit < 1 || query.limit > 100 || query.cursor !== undefined && query.cursor.length > 4096 || query.searchTerm !== undefined && query.searchTerm.length > 1024 || cwd.length > 32768 || query.cwd !== undefined && query.cwd.length > 32768)
|
|
13392
|
+
throw unavailable();
|
|
13393
|
+
const nativeStateEnv = Object.fromEntries(Object.entries(prepared.env).filter(([name]) => ["CODEX_HOME", "CODEX_SQLITE_HOME"].includes(name)));
|
|
13394
|
+
const child = spawn3(prepared.executable, [...prepared.args, "app-server"], {
|
|
13395
|
+
cwd,
|
|
13396
|
+
env: { ...childEnvironment(), ...nativeStateEnv, SWITCHER_HARNESS_API_KEY: "switcher-metadata-no-auth" },
|
|
13397
|
+
stdio: ["pipe", "pipe", "ignore"]
|
|
13398
|
+
});
|
|
13399
|
+
let done = false, initialized = false, pending = Buffer.alloc(0), responseBytes = 0;
|
|
13400
|
+
let killTimer;
|
|
13401
|
+
let resolvePage, rejectPage;
|
|
13402
|
+
const result = new Promise((resolve11, reject2) => {
|
|
13403
|
+
resolvePage = resolve11;
|
|
13404
|
+
rejectPage = reject2;
|
|
13405
|
+
});
|
|
13406
|
+
const closed = new Promise((resolve11) => child.once("close", () => resolve11()));
|
|
13407
|
+
const stop = () => {
|
|
13408
|
+
child.stdin.destroy();
|
|
13409
|
+
child.kill("SIGTERM");
|
|
13410
|
+
killTimer ??= setTimeout(() => child.kill("SIGKILL"), 2000);
|
|
13411
|
+
killTimer.unref();
|
|
13412
|
+
};
|
|
13413
|
+
const fail = (error = unavailable()) => {
|
|
13414
|
+
if (!done) {
|
|
13415
|
+
done = true;
|
|
13416
|
+
rejectPage(error);
|
|
13417
|
+
}
|
|
13418
|
+
stop();
|
|
13419
|
+
};
|
|
13420
|
+
const interrupt = () => fail(new CommandInterrupted(130, "Session discovery was cancelled; no conversation was started."));
|
|
13421
|
+
const terminate = () => fail(new CommandInterrupted(143, "Session discovery was interrupted; no conversation was started."));
|
|
13422
|
+
process.once("SIGINT", interrupt);
|
|
13423
|
+
process.once("SIGTERM", terminate);
|
|
13424
|
+
process.once("SIGHUP", terminate);
|
|
13425
|
+
const timer = setTimeout(() => fail(), 1e4);
|
|
13426
|
+
child.once("error", () => fail());
|
|
13427
|
+
child.stdin.on("error", () => fail());
|
|
13428
|
+
child.once("close", () => {
|
|
13429
|
+
if (!done)
|
|
13430
|
+
fail();
|
|
13431
|
+
});
|
|
13432
|
+
const send = (message) => child.stdin.write(JSON.stringify(message) + `
|
|
13433
|
+
`);
|
|
13434
|
+
child.stdout.on("data", (chunk) => {
|
|
13435
|
+
if (done)
|
|
13436
|
+
return;
|
|
13437
|
+
try {
|
|
13438
|
+
responseBytes += chunk.length;
|
|
13439
|
+
if (responseBytes > 16 * 1024 * 1024 || pending.length + chunk.length > 8 * 1024 * 1024)
|
|
13440
|
+
throw unavailable();
|
|
13441
|
+
pending = Buffer.concat([pending, chunk]);
|
|
13442
|
+
let end;
|
|
13443
|
+
while ((end = pending.indexOf(10)) >= 0) {
|
|
13444
|
+
const line = pending.subarray(0, end);
|
|
13445
|
+
pending = pending.subarray(end + 1);
|
|
13446
|
+
if (!line.length)
|
|
13447
|
+
continue;
|
|
13448
|
+
const message = JSON.parse(line.toString("utf8"));
|
|
13449
|
+
if (!object6(message))
|
|
13450
|
+
throw unavailable();
|
|
13451
|
+
if (message.id === 1) {
|
|
13452
|
+
if (initialized || message.error || !object6(message.result))
|
|
13453
|
+
throw unavailable();
|
|
13454
|
+
initialized = true;
|
|
13455
|
+
send({ method: "initialized" });
|
|
13456
|
+
send({ id: 2, method: "thread/list", params: { ...query, modelProviders: [], useStateDbOnly: false, sortKey: "updated_at", sortDirection: "desc" } });
|
|
13457
|
+
} else if (message.id === 2) {
|
|
13458
|
+
const page = message.result;
|
|
13459
|
+
if (!initialized || message.error || !object6(page) || !Array.isArray(page.data) || page.data.length > query.limit || !(page.nextCursor === null || typeof page.nextCursor === "string") || typeof page.nextCursor === "string" && page.nextCursor.length > 4096)
|
|
13460
|
+
throw unavailable();
|
|
13461
|
+
const data2 = page.data.map((thread) => {
|
|
13462
|
+
if (!object6(thread) || typeof thread.id !== "string" || !/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(thread.id) || typeof thread.cwd !== "string" || thread.cwd.length > 32768 || thread.name != null && typeof thread.name !== "string" || thread.preview !== undefined && typeof thread.preview !== "string")
|
|
13463
|
+
throw unavailable();
|
|
13464
|
+
return { id: thread.id, cwd: thread.cwd, name: thread.name, preview: thread.preview };
|
|
13465
|
+
});
|
|
13466
|
+
done = true;
|
|
13467
|
+
resolvePage({ data: data2, nextCursor: page.nextCursor });
|
|
13468
|
+
stop();
|
|
13469
|
+
return;
|
|
13470
|
+
}
|
|
13471
|
+
}
|
|
13472
|
+
} catch {
|
|
13473
|
+
fail();
|
|
13474
|
+
}
|
|
13475
|
+
});
|
|
13476
|
+
send({ id: 1, method: "initialize", params: { clientInfo: { name: "switcher_session_discovery", version: "1" }, capabilities: { experimentalApi: true } } });
|
|
13477
|
+
try {
|
|
13478
|
+
return await result;
|
|
13479
|
+
} finally {
|
|
13480
|
+
clearTimeout(timer);
|
|
13481
|
+
stop();
|
|
13482
|
+
await closed;
|
|
13483
|
+
if (killTimer)
|
|
13484
|
+
clearTimeout(killTimer);
|
|
13485
|
+
process.off("SIGINT", interrupt);
|
|
13486
|
+
process.off("SIGTERM", terminate);
|
|
13487
|
+
process.off("SIGHUP", terminate);
|
|
13488
|
+
}
|
|
13489
|
+
}
|
|
13490
|
+
async function resolveCodexResumeArguments(prepared, nativeArgs, cwd, list = listCodexSessions) {
|
|
13491
|
+
const command = codexCommandIndex(nativeArgs);
|
|
13492
|
+
if (command < 0 || nativeArgs[command] !== "resume")
|
|
13493
|
+
return nativeArgs;
|
|
13494
|
+
let last = false, all2 = false, positional = false;
|
|
13495
|
+
let effectiveCwd = cwd;
|
|
13496
|
+
const remove = new Set;
|
|
13497
|
+
for (let i = 0;i < nativeArgs.length; i++) {
|
|
13498
|
+
if (i === command)
|
|
13499
|
+
continue;
|
|
13500
|
+
if (nativeArgs[i] === "--") {
|
|
13501
|
+
positional ||= i > command && Boolean(nativeArgs[i + 1]);
|
|
13502
|
+
break;
|
|
13503
|
+
}
|
|
13504
|
+
if (nativeArgs[i].startsWith("--cd="))
|
|
13505
|
+
effectiveCwd = resolve10(cwd, nativeArgs[i].slice(5));
|
|
13506
|
+
else if (nativeArgs[i].startsWith("-C") && nativeArgs[i].length > 2)
|
|
13507
|
+
effectiveCwd = resolve10(cwd, nativeArgs[i].slice(2));
|
|
13508
|
+
if (codexOptionRequestsHelp(nativeArgs[i]))
|
|
13509
|
+
return nativeArgs;
|
|
13510
|
+
if (codexOptionTakesValue(nativeArgs[i])) {
|
|
13511
|
+
if (nativeArgs[i] === "--cd" || nativeArgs[i] === "-C") {
|
|
13512
|
+
if (!nativeArgs[i + 1])
|
|
13513
|
+
throw unavailable();
|
|
13514
|
+
effectiveCwd = resolve10(cwd, nativeArgs[i + 1]);
|
|
13515
|
+
}
|
|
13516
|
+
i++;
|
|
13517
|
+
continue;
|
|
13518
|
+
}
|
|
13519
|
+
if (i > command && nativeArgs[i] === "--last") {
|
|
13520
|
+
last = true;
|
|
13521
|
+
remove.add(i);
|
|
13522
|
+
}
|
|
13523
|
+
if (i > command && nativeArgs[i] === "--all") {
|
|
13524
|
+
all2 = true;
|
|
13525
|
+
remove.add(i);
|
|
13526
|
+
}
|
|
13527
|
+
if (i > command && !nativeArgs[i].startsWith("-"))
|
|
13528
|
+
positional = true;
|
|
13529
|
+
}
|
|
13530
|
+
if (positional && !last)
|
|
13531
|
+
return nativeArgs;
|
|
13532
|
+
const query = { limit: last ? 1 : 30, ...all2 ? {} : { cwd: effectiveCwd } };
|
|
13533
|
+
if (!last && (!process.stdin.isTTY || !process.stderr.isTTY))
|
|
13534
|
+
throw new Fault(400, "codex_session_required", "Provide an exact session ID or use resume --last in noninteractive mode.");
|
|
13535
|
+
const finish = (id2) => [...nativeArgs.slice(0, command), "resume", id2, ...nativeArgs.slice(command + 1).filter((_arg, i) => !remove.has(i + command + 1))];
|
|
13536
|
+
let page = await list(prepared, effectiveCwd, query);
|
|
13537
|
+
if (last) {
|
|
13538
|
+
if (!page.data[0])
|
|
13539
|
+
throw new Fault(404, "codex_session_missing", "No Codex conversations match this workspace. Use resume --all to include other workspaces.");
|
|
13540
|
+
return finish(page.data[0].id);
|
|
13541
|
+
}
|
|
13542
|
+
const reader = createInterface2({ input: process.stdin, output: process.stderr });
|
|
13543
|
+
const controller = new AbortController;
|
|
13544
|
+
const cancel = () => controller.abort(new CommandInterrupted(130, "Session selection was cancelled."));
|
|
13545
|
+
const terminate = () => controller.abort(new CommandInterrupted(143, "Session selection was interrupted."));
|
|
13546
|
+
const hangup = () => controller.abort(new CommandInterrupted(129, "Session selection ended after terminal hangup."));
|
|
13547
|
+
reader.on("SIGINT", cancel);
|
|
13548
|
+
reader.on("close", cancel);
|
|
13549
|
+
process.on("SIGINT", cancel);
|
|
13550
|
+
process.on("SIGTERM", terminate);
|
|
13551
|
+
process.on("SIGHUP", hangup);
|
|
13552
|
+
const display = (value) => value.replace(/[\x00-\x1f\x7f-\x9f]/g, "").slice(0, 180);
|
|
13553
|
+
try {
|
|
13554
|
+
for (;; ) {
|
|
13555
|
+
console.error("Codex conversations across providers:");
|
|
13556
|
+
page.data.forEach((thread, i) => console.error(` ${i + 1}. ${display(thread.name ?? thread.id)} \u2014 workspace ${display(basename3(thread.cwd) || "unknown")}`));
|
|
13557
|
+
const answer = (await reader.question("Number, search text, or n for next page (Ctrl-C cancels): ", { signal: controller.signal }).catch((error) => {
|
|
13558
|
+
throw controller.signal.aborted ? controller.signal.reason : error;
|
|
13559
|
+
})).trim();
|
|
13560
|
+
if (answer.length > 1024)
|
|
13561
|
+
throw new Fault(400, "codex_session_search_limit", "Codex session search text must be at most 1024 characters.");
|
|
13562
|
+
if (/^[1-9]\d*$/.test(answer) && page.data[Number(answer) - 1])
|
|
13563
|
+
return finish(page.data[Number(answer) - 1].id);
|
|
13564
|
+
if (answer === "n") {
|
|
13565
|
+
if (!page.nextCursor) {
|
|
13566
|
+
console.error("No next page.");
|
|
13567
|
+
continue;
|
|
13568
|
+
}
|
|
13569
|
+
query.cursor = page.nextCursor;
|
|
13570
|
+
} else {
|
|
13571
|
+
delete query.cursor;
|
|
13572
|
+
query.searchTerm = answer;
|
|
13573
|
+
}
|
|
13574
|
+
page = await list(prepared, effectiveCwd, query);
|
|
13575
|
+
}
|
|
13576
|
+
} finally {
|
|
13577
|
+
reader.off("SIGINT", cancel);
|
|
13578
|
+
reader.off("close", cancel);
|
|
13579
|
+
process.off("SIGINT", cancel);
|
|
13580
|
+
process.off("SIGTERM", terminate);
|
|
13581
|
+
process.off("SIGHUP", hangup);
|
|
13582
|
+
reader.close();
|
|
13583
|
+
}
|
|
13584
|
+
}
|
|
13585
|
+
|
|
12593
13586
|
// src/launcher.ts
|
|
12594
13587
|
var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
|
|
12595
13588
|
async function writeOriCodexCatalog(stateDir, models) {
|
|
12596
|
-
const path =
|
|
13589
|
+
const path = join20(stateDir, "ori-codex-models.json");
|
|
12597
13590
|
const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
|
|
12598
|
-
await
|
|
13591
|
+
await writeFile17(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
|
|
12599
13592
|
`, { mode: 384, flag: "wx" });
|
|
12600
13593
|
return path;
|
|
12601
13594
|
}
|
|
12602
13595
|
function oriTarget(harness) {
|
|
13596
|
+
if (harness === "antigravity" || harness === "junie")
|
|
13597
|
+
throw new Error("This CLI is supported through the direct Switcher backend only.");
|
|
12603
13598
|
if (harness === "kilo")
|
|
12604
13599
|
throw new Error("Ori does not launch Kilo; use the direct backend.");
|
|
12605
13600
|
if (harness === "opencode")
|
|
@@ -12631,7 +13626,7 @@ async function oriRequestForPlan(plan, options = {}) {
|
|
|
12631
13626
|
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.");
|
|
12632
13627
|
if (plan.profile.harness === "grok" && policyEnvironment.GROK_FORCE_LOGIN_TEAM_ID?.trim())
|
|
12633
13628
|
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.");
|
|
12634
|
-
const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ?
|
|
13629
|
+
const contract = await inspectOri({ executable: options.oriExecutable, cwd: options.cwd ? resolve11(options.cwd) : undefined });
|
|
12635
13630
|
const native = requireOriHarness(contract, target);
|
|
12636
13631
|
if (!native.path)
|
|
12637
13632
|
throw new Error("Ori did not report the native harness executable path.");
|
|
@@ -12679,14 +13674,15 @@ async function prepareOriForPlan(plan, options) {
|
|
|
12679
13674
|
executable: detection.executable,
|
|
12680
13675
|
version: detection.version,
|
|
12681
13676
|
stateDir: options.stateDir,
|
|
12682
|
-
cwd:
|
|
12683
|
-
args: options.args ?? []
|
|
13677
|
+
cwd: resolve11(options.cwd ?? process.cwd()),
|
|
13678
|
+
args: options.args ?? [],
|
|
13679
|
+
sharedState: options.sharedState
|
|
12684
13680
|
});
|
|
12685
13681
|
try {
|
|
12686
13682
|
const shim = prepareOriModelPolicy(request.target, native);
|
|
12687
|
-
const dir =
|
|
12688
|
-
await
|
|
12689
|
-
await
|
|
13683
|
+
const dir = join20(options.stateDir, "ori-bin"), path = join20(dir, shim.name);
|
|
13684
|
+
await mkdir12(dir, { mode: 448 });
|
|
13685
|
+
await writeFile17(path, shim.script, { mode: 448, flag: "wx" });
|
|
12690
13686
|
return { contract, prepared: {
|
|
12691
13687
|
...ori,
|
|
12692
13688
|
env: { ...ori.env, ...shim.env, PATH: `${dir}:${ori.env.PATH ?? process.env.PATH ?? ""}` },
|
|
@@ -12706,9 +13702,9 @@ async function launch(client, profileId, options = {}) {
|
|
|
12706
13702
|
if ((options.reasoning || options.dangerouslyBypassApprovalsAndSandbox) && (profile.harness !== "codex" || (options.backend ?? "direct") !== "direct"))
|
|
12707
13703
|
throw new Error("Reasoning and full-access launch options require direct Codex or ChatGPT.");
|
|
12708
13704
|
assertHarnessArguments(profile.harness, options.args ?? []);
|
|
12709
|
-
if (profile.harness === "gemini")
|
|
13705
|
+
if (profile.harness === "gemini" || profile.harness === "antigravity")
|
|
12710
13706
|
validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
|
|
12711
|
-
await validateHarnessConfiguration(profile.harness,
|
|
13707
|
+
await validateHarnessConfiguration(profile.harness, resolve11(options.cwd ?? process.cwd()), options.args);
|
|
12712
13708
|
if (profile.harness === "grok" && !["", "0", "false", "no", "off"].includes((process.env.GROK_DISABLE_API_KEY_AUTH ?? "").trim().toLowerCase()))
|
|
12713
13709
|
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.");
|
|
12714
13710
|
if (profile.harness === "grok" && process.env.GROK_FORCE_LOGIN_TEAM_ID?.trim())
|
|
@@ -12717,7 +13713,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
12717
13713
|
await client.refreshModels(profile.providerId);
|
|
12718
13714
|
const plan = await client.launchPlan(profileId);
|
|
12719
13715
|
assertHarnessArguments(plan.profile.harness, options.args ?? []);
|
|
12720
|
-
await validateHarnessConfiguration(plan.profile.harness,
|
|
13716
|
+
await validateHarnessConfiguration(plan.profile.harness, resolve11(options.cwd ?? process.cwd()), options.args);
|
|
12721
13717
|
if (options.credentialPreflight && providerCredentialFingerprint(plan.provider) !== options.credentialPreflight)
|
|
12722
13718
|
throw new Fault(409, "credential_preflight_changed", "The provider authority or credential contract changed after authentication. Retry the launch; no credential was sent.");
|
|
12723
13719
|
const backend = options.backend ?? "direct";
|
|
@@ -12739,9 +13735,9 @@ async function launch(client, profileId, options = {}) {
|
|
|
12739
13735
|
validateHarnessVersion("gemini", detection?.version);
|
|
12740
13736
|
if (backend === "direct" && plan.profile.harness === "aider")
|
|
12741
13737
|
validateHarnessVersion(plan.profile.harness, detection?.version);
|
|
12742
|
-
const root =
|
|
13738
|
+
const root = resolve11(options.stateDir ?? join20(switcherHome(), "state"));
|
|
12743
13739
|
await privateDirectory(root);
|
|
12744
|
-
const stateDir = await mkdtemp(
|
|
13740
|
+
const stateDir = await mkdtemp(join20(root, "launch-"));
|
|
12745
13741
|
let credential;
|
|
12746
13742
|
if (backend === "direct") {
|
|
12747
13743
|
try {
|
|
@@ -12785,6 +13781,27 @@ async function launch(client, profileId, options = {}) {
|
|
|
12785
13781
|
return;
|
|
12786
13782
|
});
|
|
12787
13783
|
try {
|
|
13784
|
+
if (options.shareNativeState && plan.profile.harness !== "codex" && plan.profile.harness !== "claude")
|
|
13785
|
+
throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
|
|
13786
|
+
const shareRequested = (plan.profile.harness === "codex" || plan.profile.harness === "claude") && nativeStateRequested(plan.profile.harness, process.env, Boolean(options.shareNativeState));
|
|
13787
|
+
if (shareRequested && backend !== "direct")
|
|
13788
|
+
throw new Fault(400, "native_state_backend", "Shared native state currently requires the directly verified native adapter; Ori state/resume integration is not yet accepted.");
|
|
13789
|
+
if (shareRequested && plan.profile.harness === "codex") {
|
|
13790
|
+
assertHarnessArguments("codex", options.args ?? [], { reservedCodexRoots: ["sqlite_home"] });
|
|
13791
|
+
validateNativeStateVersion("codex", detection?.version);
|
|
13792
|
+
}
|
|
13793
|
+
const sharedState = shareRequested ? await resolveNativeState(plan.profile.harness) : undefined;
|
|
13794
|
+
const desktopState = profileId;
|
|
13795
|
+
const stateWarnings = sharedState ? ["Shared native state is explicitly enabled. Resumed conversation history uses this launch's selected provider and model; Switcher does not infer unverified original-provider provenance.", ...await legacyNativeStateWarnings(root, sharedState)] : [];
|
|
13796
|
+
let nativeHome2;
|
|
13797
|
+
if (sharedState && !options.desktop && !options.claudeDesktop) {
|
|
13798
|
+
const variable = sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
|
|
13799
|
+
const configured = process.env[variable] ? resolve11(process.env[variable]) : undefined;
|
|
13800
|
+
nativeHome2 = sharedState.tool === "claude" && (!configured || configured === sharedState.home) ? join20(root, "native-claude", profileId) : configured ?? sharedState.home;
|
|
13801
|
+
await privateDirectory(nativeHome2);
|
|
13802
|
+
await assertNativeInstructionOverlay(sharedState, nativeHome2);
|
|
13803
|
+
await projectNativeState(sharedState, nativeHome2);
|
|
13804
|
+
}
|
|
12788
13805
|
const input = {
|
|
12789
13806
|
harness: plan.profile.harness,
|
|
12790
13807
|
baseUrl: plan.provider.baseUrl,
|
|
@@ -12797,9 +13814,10 @@ async function launch(client, profileId, options = {}) {
|
|
|
12797
13814
|
onRoutingEvent,
|
|
12798
13815
|
credential,
|
|
12799
13816
|
stateDir,
|
|
12800
|
-
cwd:
|
|
13817
|
+
cwd: resolve11(options.cwd ?? process.cwd()),
|
|
13818
|
+
sharedState
|
|
12801
13819
|
};
|
|
12802
|
-
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop,
|
|
13820
|
+
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join20(root, "desktop-claude", desktopState)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent, sharedState })).prepared : await prepareHarnessLaunch({
|
|
12803
13821
|
harness: plan.profile.harness,
|
|
12804
13822
|
baseUrl: plan.provider.baseUrl,
|
|
12805
13823
|
protocol: plan.provider.protocol,
|
|
@@ -12815,13 +13833,26 @@ async function launch(client, profileId, options = {}) {
|
|
|
12815
13833
|
executable: nativeExecutable ?? detection?.executable,
|
|
12816
13834
|
args: options.args ?? [],
|
|
12817
13835
|
stateDir,
|
|
12818
|
-
cwd:
|
|
13836
|
+
cwd: resolve11(options.cwd ?? process.cwd()),
|
|
12819
13837
|
version: detection?.version,
|
|
12820
|
-
|
|
13838
|
+
sharedState,
|
|
13839
|
+
...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo", "antigravity", "junie"].includes(plan.profile.harness) ? { sessionDir: join20(root, "sessions", plan.profile.harness, profileId) } : {}
|
|
12821
13840
|
});
|
|
12822
13841
|
cleanup = prepared.cleanup;
|
|
13842
|
+
prepared = { ...prepared, warnings: [...prepared.warnings, ...stateWarnings] };
|
|
13843
|
+
if (sharedState)
|
|
13844
|
+
prepared = { ...prepared, env: {
|
|
13845
|
+
...prepared.env,
|
|
13846
|
+
...nativeStateEnvironment(sharedState),
|
|
13847
|
+
...nativeHome2 ? { [sharedState.tool === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR"]: nativeHome2 } : {}
|
|
13848
|
+
} };
|
|
13849
|
+
if (sharedState?.tool === "codex" && !options.desktop && backend === "direct" && options.args?.length) {
|
|
13850
|
+
const baseArgs = prepared.args.slice(0, prepared.args.length - options.args.length);
|
|
13851
|
+
const resumedArgs = await resolveCodexResumeArguments({ ...prepared, args: baseArgs }, options.args, input.cwd);
|
|
13852
|
+
prepared = { ...prepared, args: [...baseArgs, ...resumedArgs] };
|
|
13853
|
+
}
|
|
12823
13854
|
if (options.desktop) {
|
|
12824
|
-
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir,
|
|
13855
|
+
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join20(root, "desktop", desktopState), sharedState);
|
|
12825
13856
|
cleanup = prepared.cleanup;
|
|
12826
13857
|
}
|
|
12827
13858
|
for (const warning of [...plan.warnings, ...prepared.warnings])
|
|
@@ -12898,7 +13929,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
12898
13929
|
interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
|
|
12899
13930
|
throw preparationSignal;
|
|
12900
13931
|
}
|
|
12901
|
-
const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd:
|
|
13932
|
+
const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve11(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
|
|
12902
13933
|
await cleanup?.();
|
|
12903
13934
|
cleanup = undefined;
|
|
12904
13935
|
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}.`);
|
|
@@ -12915,8 +13946,8 @@ async function launch(client, profileId, options = {}) {
|
|
|
12915
13946
|
} finally {
|
|
12916
13947
|
if (lateCreateRunFinalization) {
|
|
12917
13948
|
let finalizationTimer;
|
|
12918
|
-
const finalizationTimeout = new Promise((
|
|
12919
|
-
finalizationTimer = setTimeout(
|
|
13949
|
+
const finalizationTimeout = new Promise((resolve12) => {
|
|
13950
|
+
finalizationTimer = setTimeout(resolve12, LATE_RUN_FINALIZATION_TIMEOUT_MS);
|
|
12920
13951
|
});
|
|
12921
13952
|
try {
|
|
12922
13953
|
await Promise.race([lateCreateRunFinalization, finalizationTimeout]);
|
|
@@ -12936,7 +13967,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
12936
13967
|
|
|
12937
13968
|
// src/direct-launch.ts
|
|
12938
13969
|
import { createHash as createHash14 } from "crypto";
|
|
12939
|
-
import { createInterface as
|
|
13970
|
+
import { createInterface as createInterface3 } from "readline/promises";
|
|
12940
13971
|
var absent2 = (error) => error instanceof SwitcherError && error.status === 404;
|
|
12941
13972
|
async function resolveLaunchProvider(client, selector, options = {}) {
|
|
12942
13973
|
let existing;
|
|
@@ -12981,7 +14012,7 @@ async function selectModel(models, query = "", harness) {
|
|
|
12981
14012
|
const eligible = models.filter((m) => harness ? harnessEligible(m, harness) : codingEligible(m));
|
|
12982
14013
|
if (!eligible.length)
|
|
12983
14014
|
throw new Fault(422, "model_missing", "This provider has no models eligible for coding in its current catalog.");
|
|
12984
|
-
const reader =
|
|
14015
|
+
const reader = createInterface3({ input: process.stdin, output: process.stderr });
|
|
12985
14016
|
const cancellation = new AbortController;
|
|
12986
14017
|
const cancel = () => cancellation.abort(new CommandInterrupted(130, "Model selection was cancelled; no harness was started."));
|
|
12987
14018
|
const terminate = () => cancellation.abort(new CommandInterrupted(143, "Model selection was interrupted; no harness was started."));
|
|
@@ -13013,7 +14044,8 @@ async function selectModel(models, query = "", harness) {
|
|
|
13013
14044
|
}
|
|
13014
14045
|
}
|
|
13015
14046
|
async function ensureLaunchProfile(client, provider, harness, model3, modelPolicy) {
|
|
13016
|
-
const
|
|
14047
|
+
const policy = modelPolicy ?? (harness === "codex" ? { version: 1, selection: "catalog" } : undefined);
|
|
14048
|
+
const normalizedPolicy = policy === undefined ? undefined : parse2(modelPolicySchema, policy);
|
|
13017
14049
|
const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
|
|
13018
14050
|
const hash3 = createHash14("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
|
|
13019
14051
|
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
|
|
@@ -13038,14 +14070,343 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
13038
14070
|
return existing;
|
|
13039
14071
|
}
|
|
13040
14072
|
|
|
14073
|
+
// src/native-state-import.ts
|
|
14074
|
+
import { createHash as createHash15 } from "crypto";
|
|
14075
|
+
import { constants as constants8 } from "fs";
|
|
14076
|
+
import { lstat as lstat9, open as open5, opendir as opendir2, link as link2, rmdir as rmdir2, unlink as unlink3 } from "fs/promises";
|
|
14077
|
+
import { basename as basename4, dirname as dirname10, isAbsolute as isAbsolute17, join as join21, relative as relative6, resolve as resolve12 } from "path";
|
|
14078
|
+
var MAX_FILES = 1e5;
|
|
14079
|
+
var MAX_BYTES2 = 2 * 1024 * 1024 * 1024;
|
|
14080
|
+
var refused = () => new Fault(409, "native_state_import_conflict", "Native state import found changed, unsafe or divergent data. No existing file will be replaced. Keep the original directory and resolve the conflict explicitly.");
|
|
14081
|
+
async function info2(path) {
|
|
14082
|
+
try {
|
|
14083
|
+
return await lstat9(path);
|
|
14084
|
+
} catch (error) {
|
|
14085
|
+
if (error.code === "ENOENT")
|
|
14086
|
+
return;
|
|
14087
|
+
throw error;
|
|
14088
|
+
}
|
|
14089
|
+
}
|
|
14090
|
+
var identity = (s) => ({ dev: s.dev, ino: s.ino, size: s.size, mtimeMs: s.mtimeMs, ctimeMs: s.ctimeMs });
|
|
14091
|
+
var same = (a, b) => JSON.stringify(identity(a)) === JSON.stringify(identity(b));
|
|
14092
|
+
var inside3 = (parent, child) => {
|
|
14093
|
+
const path = relative6(parent, child);
|
|
14094
|
+
return path !== ".." && !path.startsWith("../") && !isAbsolute17(path);
|
|
14095
|
+
};
|
|
14096
|
+
var SESSION_ID = /^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i;
|
|
14097
|
+
async function sessionId(path, expected) {
|
|
14098
|
+
const nameId = basename4(path).match(/([a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})\.jsonl$/i)?.[1]?.toLowerCase();
|
|
14099
|
+
const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
|
|
14100
|
+
try {
|
|
14101
|
+
const before = await handle.stat();
|
|
14102
|
+
if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || expected && !same(before, expected))
|
|
14103
|
+
throw refused();
|
|
14104
|
+
const buffer = Buffer.alloc(Math.min(before.size, 1024 * 1024));
|
|
14105
|
+
let length = 0, newline = -1;
|
|
14106
|
+
while (length < buffer.length && newline < 0) {
|
|
14107
|
+
const read = await handle.read(buffer, length, buffer.length - length, null);
|
|
14108
|
+
if (!read.bytesRead)
|
|
14109
|
+
break;
|
|
14110
|
+
length += read.bytesRead;
|
|
14111
|
+
newline = buffer.indexOf(10, 0);
|
|
14112
|
+
}
|
|
14113
|
+
const after = await handle.stat(), named = await lstat9(path);
|
|
14114
|
+
if (!same(before, after) || !same(after, named) || after.nlink !== 1 || named.nlink !== 1 || named.isSymbolicLink())
|
|
14115
|
+
throw refused();
|
|
14116
|
+
if (newline < 0 && before.size > buffer.length)
|
|
14117
|
+
throw refused();
|
|
14118
|
+
let row;
|
|
14119
|
+
try {
|
|
14120
|
+
row = JSON.parse(buffer.subarray(0, newline < 0 ? length : newline).toString("utf8"));
|
|
14121
|
+
} catch {
|
|
14122
|
+
return nameId;
|
|
14123
|
+
}
|
|
14124
|
+
if (row && typeof row === "object" && "type" in row && row.type === "session_meta") {
|
|
14125
|
+
const value = row.payload?.id;
|
|
14126
|
+
if (typeof value !== "string" || !SESSION_ID.test(value) || nameId && value.toLowerCase() !== nameId)
|
|
14127
|
+
throw refused();
|
|
14128
|
+
return value.toLowerCase();
|
|
14129
|
+
}
|
|
14130
|
+
return nameId;
|
|
14131
|
+
} finally {
|
|
14132
|
+
await handle.close();
|
|
14133
|
+
}
|
|
14134
|
+
}
|
|
14135
|
+
async function checkSessionIdentities(plan) {
|
|
14136
|
+
if (plan.state.tool !== "codex")
|
|
14137
|
+
return;
|
|
14138
|
+
const ids = new Map;
|
|
14139
|
+
for (const file of plan.files) {
|
|
14140
|
+
if (!/^(sessions|archived_sessions)\//.test(file.path) || !file.path.endsWith(".jsonl"))
|
|
14141
|
+
continue;
|
|
14142
|
+
file.sessionId = await sessionId(join21(plan.source, file.path), file.source);
|
|
14143
|
+
if (!file.sessionId)
|
|
14144
|
+
continue;
|
|
14145
|
+
const previous = ids.get(file.sessionId);
|
|
14146
|
+
if (previous?.some((other) => other.sha256 !== file.sha256))
|
|
14147
|
+
throw refused();
|
|
14148
|
+
if (previous) {
|
|
14149
|
+
file.existing = true;
|
|
14150
|
+
previous.push(file);
|
|
14151
|
+
} else
|
|
14152
|
+
ids.set(file.sessionId, [file]);
|
|
14153
|
+
}
|
|
14154
|
+
if (!ids.size)
|
|
14155
|
+
return;
|
|
14156
|
+
let seen = 0;
|
|
14157
|
+
async function scan(directory, depth = 0) {
|
|
14158
|
+
if (++seen > MAX_FILES || depth > 32)
|
|
14159
|
+
throw refused();
|
|
14160
|
+
if (!await info2(directory))
|
|
14161
|
+
return;
|
|
14162
|
+
await assertNativeStateDirectory(directory);
|
|
14163
|
+
for await (const entry of await opendir2(directory)) {
|
|
14164
|
+
if (++seen > MAX_FILES || entry.isSymbolicLink())
|
|
14165
|
+
throw refused();
|
|
14166
|
+
const path = join21(directory, entry.name);
|
|
14167
|
+
if (entry.isDirectory()) {
|
|
14168
|
+
await scan(path, depth + 1);
|
|
14169
|
+
continue;
|
|
14170
|
+
}
|
|
14171
|
+
if (!entry.isFile() || !entry.name.endsWith(".jsonl"))
|
|
14172
|
+
continue;
|
|
14173
|
+
const id2 = await sessionId(path);
|
|
14174
|
+
if (!id2 || !ids.has(id2))
|
|
14175
|
+
continue;
|
|
14176
|
+
const existing = await fingerprint2(path), importing = ids.get(id2);
|
|
14177
|
+
if (importing.some((file) => file.sha256 !== existing.sha256))
|
|
14178
|
+
throw refused();
|
|
14179
|
+
for (const file of importing)
|
|
14180
|
+
file.existing = true;
|
|
14181
|
+
}
|
|
14182
|
+
}
|
|
14183
|
+
await scan(join21(plan.state.home, "sessions"));
|
|
14184
|
+
await scan(join21(plan.state.home, "archived_sessions"));
|
|
14185
|
+
}
|
|
14186
|
+
async function fingerprint2(path, copyTo) {
|
|
14187
|
+
const handle = await open5(path, constants8.O_RDONLY | constants8.O_NOFOLLOW);
|
|
14188
|
+
let output, complete = false;
|
|
14189
|
+
try {
|
|
14190
|
+
const before = await handle.stat();
|
|
14191
|
+
if (!before.isFile() || before.nlink !== 1 || before.uid !== process.getuid?.() || before.mode & 18 || before.size > MAX_BYTES2)
|
|
14192
|
+
throw refused();
|
|
14193
|
+
if (copyTo)
|
|
14194
|
+
output = await open5(copyTo, "wx", 384);
|
|
14195
|
+
const hash3 = createHash15("sha256"), buffer = Buffer.alloc(64 * 1024);
|
|
14196
|
+
let bytes = 0;
|
|
14197
|
+
for (;; ) {
|
|
14198
|
+
const read = await handle.read(buffer, 0, buffer.length, null);
|
|
14199
|
+
if (!read.bytesRead)
|
|
14200
|
+
break;
|
|
14201
|
+
bytes += read.bytesRead;
|
|
14202
|
+
if (bytes > MAX_BYTES2)
|
|
14203
|
+
throw refused();
|
|
14204
|
+
const chunk = buffer.subarray(0, read.bytesRead);
|
|
14205
|
+
hash3.update(chunk);
|
|
14206
|
+
if (output) {
|
|
14207
|
+
let offset = 0;
|
|
14208
|
+
while (offset < chunk.length)
|
|
14209
|
+
offset += (await output.write(chunk, offset, chunk.length - offset)).bytesWritten;
|
|
14210
|
+
}
|
|
14211
|
+
}
|
|
14212
|
+
const after = await handle.stat(), named = await lstat9(path);
|
|
14213
|
+
if (named.isSymbolicLink() || after.nlink !== 1 || named.nlink !== 1 || bytes !== before.size || !same(before, after) || !same(after, named))
|
|
14214
|
+
throw refused();
|
|
14215
|
+
await output?.sync();
|
|
14216
|
+
complete = true;
|
|
14217
|
+
return { bytes, sha256: hash3.digest("hex"), source: identity(before) };
|
|
14218
|
+
} finally {
|
|
14219
|
+
await output?.close();
|
|
14220
|
+
await handle.close();
|
|
14221
|
+
if (copyTo && !complete)
|
|
14222
|
+
await unlink3(copyTo).catch(() => {
|
|
14223
|
+
return;
|
|
14224
|
+
});
|
|
14225
|
+
}
|
|
14226
|
+
}
|
|
14227
|
+
async function planNativeStateImport(state, source, selection) {
|
|
14228
|
+
if (!isAbsolute17(source) || source.includes("\x00"))
|
|
14229
|
+
throw refused();
|
|
14230
|
+
source = resolve12(source);
|
|
14231
|
+
if (inside3(source, state.home) || inside3(state.home, source))
|
|
14232
|
+
throw refused();
|
|
14233
|
+
await assertNativeStateDirectory(source);
|
|
14234
|
+
await ensureNativeStateDirectory(state.home, false);
|
|
14235
|
+
const allowed = NATIVE_STATE_ENTRIES[state.tool].filter((entry) => entry.name !== "thread-writer-locks");
|
|
14236
|
+
const entries = selection?.length ? [...new Set(selection)] : allowed.map((entry) => entry.name);
|
|
14237
|
+
if (entries.some((name) => !allowed.some((entry) => entry.name === name)))
|
|
14238
|
+
throw refused();
|
|
14239
|
+
const plan = { state, source, entries, files: [], directories: [], bytes: 0 };
|
|
14240
|
+
let seen = 0;
|
|
14241
|
+
async function visit(path, kind) {
|
|
14242
|
+
if (++seen > MAX_FILES || path.split("/").length > 32)
|
|
14243
|
+
throw refused();
|
|
14244
|
+
await ensureNativeStateDirectory(dirname10(join21(source, path)), false);
|
|
14245
|
+
await ensureNativeStateDirectory(dirname10(join21(state.home, path)), false);
|
|
14246
|
+
const from = join21(source, path), to = join21(state.home, path), entry = await info2(from), target = await info2(to);
|
|
14247
|
+
if (!entry)
|
|
14248
|
+
return;
|
|
14249
|
+
if (entry.isSymbolicLink() || entry.uid !== process.getuid?.() || entry.mode & 18 || (kind === "directory" ? !entry.isDirectory() : !entry.isFile()))
|
|
14250
|
+
throw refused();
|
|
14251
|
+
if (kind === "directory") {
|
|
14252
|
+
await assertNativeStateDirectory(from);
|
|
14253
|
+
if (target)
|
|
14254
|
+
await assertNativeStateDirectory(to);
|
|
14255
|
+
plan.directories.push(path);
|
|
14256
|
+
const directory = await opendir2(from);
|
|
14257
|
+
const children = [];
|
|
14258
|
+
for await (const child of directory) {
|
|
14259
|
+
if (children.length + seen >= MAX_FILES || child.isSymbolicLink() || !(child.isDirectory() || child.isFile()))
|
|
14260
|
+
throw refused();
|
|
14261
|
+
children.push({ name: child.name, kind: child.isDirectory() ? "directory" : "file" });
|
|
14262
|
+
}
|
|
14263
|
+
children.sort((a, b) => a.name.localeCompare(b.name));
|
|
14264
|
+
for (const child of children)
|
|
14265
|
+
await visit(join21(path, child.name), child.kind);
|
|
14266
|
+
} else {
|
|
14267
|
+
const value = await fingerprint2(from);
|
|
14268
|
+
plan.bytes += value.bytes;
|
|
14269
|
+
if (plan.bytes > MAX_BYTES2)
|
|
14270
|
+
throw refused();
|
|
14271
|
+
if (target && (target.isSymbolicLink() || !target.isFile()))
|
|
14272
|
+
throw refused();
|
|
14273
|
+
if (target) {
|
|
14274
|
+
const existing = await fingerprint2(to);
|
|
14275
|
+
if (existing.bytes !== value.bytes || existing.sha256 !== value.sha256)
|
|
14276
|
+
throw refused();
|
|
14277
|
+
}
|
|
14278
|
+
plan.files.push({ path, ...value, existing: Boolean(target) });
|
|
14279
|
+
}
|
|
14280
|
+
}
|
|
14281
|
+
for (const name of entries)
|
|
14282
|
+
await visit(name, allowed.find((entry) => entry.name === name).kind);
|
|
14283
|
+
await checkSessionIdentities(plan);
|
|
14284
|
+
return plan;
|
|
14285
|
+
}
|
|
14286
|
+
function nativeStateImportDigest(plan) {
|
|
14287
|
+
return createHash15("sha256").update(JSON.stringify({
|
|
14288
|
+
tool: plan.state.tool,
|
|
14289
|
+
source: plan.source,
|
|
14290
|
+
destination: plan.state.home,
|
|
14291
|
+
entries: plan.entries,
|
|
14292
|
+
directories: plan.directories,
|
|
14293
|
+
files: plan.files.map((file) => ({ path: file.path, bytes: file.bytes, sha256: file.sha256, source: file.source, existing: file.existing, sessionId: file.sessionId }))
|
|
14294
|
+
})).digest("hex");
|
|
14295
|
+
}
|
|
14296
|
+
function nativeStateImportSummary(plan, applied) {
|
|
14297
|
+
const newFiles = plan.files.filter((file) => !file.existing).length;
|
|
14298
|
+
return {
|
|
14299
|
+
mode: applied ? "staged-snapshot" : "dry-run",
|
|
14300
|
+
tool: plan.state.tool,
|
|
14301
|
+
entries: plan.entries,
|
|
14302
|
+
planDigest: nativeStateImportDigest(plan),
|
|
14303
|
+
files: plan.files.length,
|
|
14304
|
+
newFiles,
|
|
14305
|
+
publishedFiles: applied ? newFiles : 0,
|
|
14306
|
+
bytes: plan.bytes,
|
|
14307
|
+
originalsPreserved: true,
|
|
14308
|
+
cutoverComplete: false,
|
|
14309
|
+
sqliteCopied: false,
|
|
14310
|
+
notice: "The original can still receive writes. This copy is not a completed migration. Legacy SQLite/index metadata and login data remain in the original directory; Codex discovery repairs the catalog from copied transcripts."
|
|
14311
|
+
};
|
|
14312
|
+
}
|
|
14313
|
+
async function applyNativeStateImportUnlocked(plan) {
|
|
14314
|
+
const fresh = await planNativeStateImport(plan.state, plan.source, plan.entries);
|
|
14315
|
+
if (JSON.stringify(fresh) !== JSON.stringify(plan))
|
|
14316
|
+
throw refused();
|
|
14317
|
+
const requiredDirectories = new Set([plan.state.home]);
|
|
14318
|
+
for (const path of plan.directories) {
|
|
14319
|
+
for (let directory = join21(plan.state.home, path);inside3(plan.state.home, directory); directory = dirname10(directory)) {
|
|
14320
|
+
requiredDirectories.add(directory);
|
|
14321
|
+
if (directory === plan.state.home)
|
|
14322
|
+
break;
|
|
14323
|
+
}
|
|
14324
|
+
}
|
|
14325
|
+
for (const file of plan.files.filter((file2) => !file2.existing)) {
|
|
14326
|
+
for (let directory = dirname10(join21(plan.state.home, file.path));inside3(plan.state.home, directory); directory = dirname10(directory)) {
|
|
14327
|
+
requiredDirectories.add(directory);
|
|
14328
|
+
if (directory === plan.state.home)
|
|
14329
|
+
break;
|
|
14330
|
+
}
|
|
14331
|
+
}
|
|
14332
|
+
const directories = [...requiredDirectories].sort((a, b) => a.length - b.length), createdDirectories = [];
|
|
14333
|
+
const staged = [];
|
|
14334
|
+
let published = 0;
|
|
14335
|
+
let committed = false, cleanupFailed = false;
|
|
14336
|
+
try {
|
|
14337
|
+
for (const directory of directories) {
|
|
14338
|
+
if (!await info2(directory)) {
|
|
14339
|
+
await ensureNativeStateDirectory(directory);
|
|
14340
|
+
createdDirectories.push(directory);
|
|
14341
|
+
} else
|
|
14342
|
+
await assertNativeStateDirectory(directory);
|
|
14343
|
+
}
|
|
14344
|
+
for (const file of plan.files) {
|
|
14345
|
+
if (file.existing)
|
|
14346
|
+
continue;
|
|
14347
|
+
const target = join21(plan.state.home, file.path), temporary = join21(dirname10(target), `.switcher-import-${crypto.randomUUID()}`);
|
|
14348
|
+
staged.push({ temporary, target });
|
|
14349
|
+
const copied = await fingerprint2(join21(plan.source, file.path), temporary);
|
|
14350
|
+
if (copied.bytes !== file.bytes || copied.sha256 !== file.sha256 || !same(copied.source, file.source))
|
|
14351
|
+
throw refused();
|
|
14352
|
+
}
|
|
14353
|
+
for (const item2 of staged) {
|
|
14354
|
+
try {
|
|
14355
|
+
await link2(item2.temporary, item2.target);
|
|
14356
|
+
published++;
|
|
14357
|
+
} catch (error) {
|
|
14358
|
+
if (published)
|
|
14359
|
+
throw new Fault(409, "native_state_import_partial", `Native state import published ${published} reviewed file(s) before a racing destination appeared. Existing and published data was preserved. Run a new dry-run to reconcile the remainder.`);
|
|
14360
|
+
throw error;
|
|
14361
|
+
}
|
|
14362
|
+
}
|
|
14363
|
+
committed = true;
|
|
14364
|
+
} finally {
|
|
14365
|
+
for (const item2 of staged) {
|
|
14366
|
+
try {
|
|
14367
|
+
await unlink3(item2.temporary);
|
|
14368
|
+
} catch (error) {
|
|
14369
|
+
if (error.code !== "ENOENT")
|
|
14370
|
+
cleanupFailed = true;
|
|
14371
|
+
}
|
|
14372
|
+
}
|
|
14373
|
+
if (!committed && published === 0) {
|
|
14374
|
+
for (const directory of createdDirectories.sort((a, b) => b.length - a.length)) {
|
|
14375
|
+
try {
|
|
14376
|
+
await rmdir2(directory);
|
|
14377
|
+
} catch (error) {
|
|
14378
|
+
if (!["ENOENT", "ENOTEMPTY", "EEXIST"].includes(error.code ?? ""))
|
|
14379
|
+
cleanupFailed = true;
|
|
14380
|
+
}
|
|
14381
|
+
}
|
|
14382
|
+
}
|
|
14383
|
+
if (cleanupFailed)
|
|
14384
|
+
throw new Fault(500, "native_state_import_recovery", "Native state import cleanup was incomplete. Existing data was not intentionally replaced; inspect the destination for .switcher-import files before retrying.");
|
|
14385
|
+
}
|
|
14386
|
+
}
|
|
14387
|
+
async function applyNativeStateImport(plan) {
|
|
14388
|
+
const existed = Boolean(await info2(plan.state.home));
|
|
14389
|
+
await ensureNativeStateDirectory(plan.state.home);
|
|
14390
|
+
try {
|
|
14391
|
+
return await withNativeStateLock(plan.state, () => applyNativeStateImportUnlocked(plan));
|
|
14392
|
+
} catch (error) {
|
|
14393
|
+
if (!existed)
|
|
14394
|
+
await rmdir2(plan.state.home).catch(() => {
|
|
14395
|
+
return;
|
|
14396
|
+
});
|
|
14397
|
+
throw error;
|
|
14398
|
+
}
|
|
14399
|
+
}
|
|
14400
|
+
|
|
13041
14401
|
// src/cli.ts
|
|
13042
14402
|
var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your provider and model
|
|
13043
14403
|
|
|
13044
14404
|
switcher launch chatgpt --provider PROVIDER --model MODEL [--reasoning EFFORT]
|
|
13045
|
-
[--dangerously-bypass-approvals-and-sandbox] [--
|
|
14405
|
+
[--dangerously-bypass-approvals-and-sandbox] [--share-native-state]
|
|
14406
|
+
[--app-path /absolute/ChatGPT.app]
|
|
13046
14407
|
[--dry-run] [--cwd DIR] [--timeout SECONDS]
|
|
13047
14408
|
switcher launch claude-desktop --provider PROVIDER --model MODEL
|
|
13048
|
-
[--app-path /absolute/Claude.app] [--dry-run]
|
|
14409
|
+
[--share-native-state] [--app-path /absolute/Claude.app] [--dry-run]
|
|
13049
14410
|
switcher providers presets [ID]
|
|
13050
14411
|
switcher providers list [--search TEXT] [--limit N] [--offset N]
|
|
13051
14412
|
switcher providers add ID --url URL --protocol PROTOCOL [--credential-env NAME]
|
|
@@ -13063,8 +14424,8 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
|
|
|
13063
14424
|
switcher profiles add ID --provider ID --harness HARNESS --model MODEL [--model-policy-file FILE] [--role-model ROLE=MODEL]
|
|
13064
14425
|
switcher profiles update ID --file profile.json --version N
|
|
13065
14426
|
switcher profiles delete ID --version N
|
|
13066
|
-
switcher launch HARNESS --provider PROVIDER [--model MODEL] [--dry-run]
|
|
13067
|
-
switcher launch PROFILE [--backend direct|ori] [--cwd DIR] [--executable PATH]
|
|
14427
|
+
switcher launch HARNESS --provider PROVIDER [--model MODEL] [--share-native-state] [--dry-run]
|
|
14428
|
+
switcher launch PROFILE [--backend direct|ori] [--share-native-state] [--cwd DIR] [--executable PATH]
|
|
13068
14429
|
[--ori-executable PATH] [--state-dir DIR]
|
|
13069
14430
|
[--timeout SECONDS] -- [native harness arguments]
|
|
13070
14431
|
switcher runs list|get [ID]
|
|
@@ -13075,9 +14436,11 @@ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your p
|
|
|
13075
14436
|
switcher credentials repair-executable PRESET_OR_REFERENCE --sha256 EXPECTED
|
|
13076
14437
|
switcher credentials repair-executable --vault-cli PATH --sha256 EXPECTED
|
|
13077
14438
|
switcher doctor
|
|
14439
|
+
switcher state import codex|claude --from LEGACY_NATIVE_HOME [--entry NAME]... [--dry-run | --apply --plan-digest SHA256]
|
|
13078
14440
|
|
|
13079
|
-
HARNESS: claude, codex, grok, opencode, opencode2, pi, omp, dsh, cline, hermes, prime-agent, gemini, aider, kilo
|
|
13080
|
-
chatgpt launches the installed macOS desktop app
|
|
14441
|
+
HARNESS: claude, codex, grok, opencode, opencode2, pi, omp, dsh, cline, hermes, prime-agent, gemini, antigravity, junie, aider, kilo
|
|
14442
|
+
chatgpt launches the installed macOS desktop app with private login data.
|
|
14443
|
+
Use --share-native-state to project the canonical noncredential Codex/Claude corpus.
|
|
13081
14444
|
Its local Codex conversations use the selected Responses-compatible provider.
|
|
13082
14445
|
claude-desktop launches Claude in its separate Claude-3p gateway profile with a
|
|
13083
14446
|
Messages-compatible provider. Quit that instance before switching providers.
|
|
@@ -13163,6 +14526,11 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13163
14526
|
"app-path": { type: "string" },
|
|
13164
14527
|
reasoning: { type: "string" },
|
|
13165
14528
|
"dangerously-bypass-approvals-and-sandbox": { type: "boolean" },
|
|
14529
|
+
"share-native-state": { type: "boolean" },
|
|
14530
|
+
from: { type: "string" },
|
|
14531
|
+
entry: { type: "string", multiple: true },
|
|
14532
|
+
apply: { type: "boolean" },
|
|
14533
|
+
"plan-digest": { type: "string" },
|
|
13166
14534
|
protocol: { type: "string" },
|
|
13167
14535
|
preset: { type: "string" },
|
|
13168
14536
|
name: { type: "string" },
|
|
@@ -13208,12 +14576,30 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13208
14576
|
}
|
|
13209
14577
|
const [command, action2, id2] = positionals;
|
|
13210
14578
|
const output = (value) => console.log(JSON.stringify(value, null, 2));
|
|
14579
|
+
if (command === "state") {
|
|
14580
|
+
if (action2 !== "import" || !["codex", "claude"].includes(id2) || !values2.from || positionals.length !== 3 || nativeArgs.length || Object.keys(values2).some((key) => !["from", "entry", "apply", "plan-digest", "dry-run", "json"].includes(key)) || values2.apply && values2["dry-run"] || Boolean(values2.apply) !== Boolean(values2["plan-digest"]) || values2["plan-digest"] !== undefined && !/^[a-f0-9]{64}$/.test(values2["plan-digest"]))
|
|
14581
|
+
throw new Fault(400, "invalid_request", "Use switcher state import codex|claude --from LEGACY_NATIVE_HOME [--entry NAME]... [--dry-run | --apply --plan-digest SHA256]. The default is a read-only dry run.");
|
|
14582
|
+
const state = await resolveNativeState(id2, process.env, { create: false });
|
|
14583
|
+
const plan = await planNativeStateImport(state, values2.from, values2.entry);
|
|
14584
|
+
if (values2.apply && values2["plan-digest"] !== nativeStateImportDigest(plan))
|
|
14585
|
+
throw new Fault(409, "native_state_plan_mismatch", "The reviewed native-state plan no longer matches this source, destination or selection. Run a new dry-run and review its plan digest.");
|
|
14586
|
+
if (values2.apply)
|
|
14587
|
+
await applyNativeStateImport(plan);
|
|
14588
|
+
output(nativeStateImportSummary(plan, Boolean(values2.apply)));
|
|
14589
|
+
return;
|
|
14590
|
+
}
|
|
14591
|
+
if (values2.from !== undefined || values2.entry !== undefined || values2.apply !== undefined || values2["plan-digest"] !== undefined)
|
|
14592
|
+
throw new Fault(400, "conflicting_options", "--from, --entry, --plan-digest, --dry-run and --apply belong to switcher state import.");
|
|
14593
|
+
if (values2["share-native-state"] && command !== "launch")
|
|
14594
|
+
throw new Fault(400, "conflicting_options", "--share-native-state belongs to a Codex, ChatGPT, Claude CLI or Claude desktop launch.");
|
|
13211
14595
|
const reasoning = values2.reasoning === undefined ? undefined : parse2(reasoningEffortSchema, values2.reasoning);
|
|
13212
14596
|
const dangerouslyBypassApprovalsAndSandbox = values2["dangerously-bypass-approvals-and-sandbox"];
|
|
13213
14597
|
if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" || values2.provider && !["chatgpt", "codex"].includes(action2) || values2.backend && values2.backend !== "direct"))
|
|
13214
14598
|
throw new Fault(400, "conflicting_options", "--reasoning and --dangerously-bypass-approvals-and-sandbox require a direct Codex or ChatGPT launch.");
|
|
13215
14599
|
const chatgpt = command === "launch" && action2 === "chatgpt" && values2.provider !== undefined;
|
|
13216
14600
|
const claudeDesktop = command === "launch" && action2 === "claude-desktop" && values2.provider !== undefined;
|
|
14601
|
+
if (values2["share-native-state"] && values2.provider !== undefined && !["codex", "claude", "chatgpt", "claude-desktop"].includes(action2))
|
|
14602
|
+
throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
|
|
13217
14603
|
if (values2["app-path"] !== undefined && !chatgpt && !claudeDesktop)
|
|
13218
14604
|
throw new Fault(400, "conflicting_options", "--app-path belongs to launch chatgpt or claude-desktop --provider PROVIDER --model MODEL.");
|
|
13219
14605
|
if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 || values2.executable !== undefined || values2.backend !== undefined || values2["ori-executable"] !== undefined))
|
|
@@ -13365,7 +14751,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13365
14751
|
modelsPath: values2["models-path"]
|
|
13366
14752
|
});
|
|
13367
14753
|
if (command === "doctor") {
|
|
13368
|
-
const harnesses = await Promise.all(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"].map((h) => detectHarness(h)));
|
|
14754
|
+
const harnesses = await Promise.all(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "antigravity", "junie", "aider", "kilo"].map((h) => detectHarness(h)));
|
|
13369
14755
|
let api;
|
|
13370
14756
|
try {
|
|
13371
14757
|
api = { mode: runtime.mode, reachable: true, health: await client.health(), ready: await client.ready() };
|
|
@@ -13419,10 +14805,12 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13419
14805
|
if (values2.model || values2.protocol || values2.url || values2["credential-env"] || values2["model-policy-file"] || values2["role-model"])
|
|
13420
14806
|
throw new Error("Use --provider PROVIDER for a direct launch, or update the saved profile explicitly.");
|
|
13421
14807
|
const profile = await client.getProfile(profileId);
|
|
14808
|
+
if (values2["share-native-state"] && !["codex", "claude"].includes(profile.harness))
|
|
14809
|
+
throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
|
|
13422
14810
|
assertHarnessArguments(profile.harness, nativeArgs);
|
|
13423
14811
|
await validateHarnessConfiguration(profile.harness, values2.cwd ?? process.cwd(), nativeArgs);
|
|
13424
14812
|
const provider = await client.getProvider(profile.providerId);
|
|
13425
|
-
if (profile.harness === "gemini")
|
|
14813
|
+
if (profile.harness === "gemini" || profile.harness === "antigravity")
|
|
13426
14814
|
validateHarnessProvider(profile.harness, provider);
|
|
13427
14815
|
let prepared;
|
|
13428
14816
|
if (!values2["dry-run"]) {
|
|
@@ -13445,14 +14833,24 @@ async function main(args = process.argv.slice(2)) {
|
|
|
13445
14833
|
codexReasoning(model3, plan.provider.baseUrl, reasoning);
|
|
13446
14834
|
}
|
|
13447
14835
|
assertHarnessArguments(plan.profile.harness, nativeArgs);
|
|
14836
|
+
if (values2["share-native-state"] && !["codex", "claude"].includes(plan.profile.harness))
|
|
14837
|
+
throw new Fault(400, "native_state_harness", "--share-native-state is supported only for Codex, ChatGPT, Claude CLI and Claude desktop launches.");
|
|
14838
|
+
const sharedNativeState = ["codex", "claude"].includes(plan.profile.harness) && nativeStateRequested(plan.profile.harness, process.env, Boolean(values2["share-native-state"]));
|
|
14839
|
+
if (sharedNativeState) {
|
|
14840
|
+
if (plan.profile.harness === "codex")
|
|
14841
|
+
assertHarnessArguments("codex", nativeArgs, { reservedCodexRoots: ["sqlite_home"] });
|
|
14842
|
+
await resolveNativeState(plan.profile.harness, process.env, { create: false });
|
|
14843
|
+
}
|
|
13448
14844
|
if (backend === "ori") {
|
|
14845
|
+
if (sharedNativeState)
|
|
14846
|
+
throw new Fault(400, "native_state_backend", "Shared native state currently requires the directly verified native adapter; Ori state/resume integration is not yet accepted.");
|
|
13449
14847
|
const { contract, warnings } = await validateOriForPlan(plan, { oriExecutable: values2["ori-executable"], args: nativeArgs, cwd: values2.cwd });
|
|
13450
|
-
output({ ...plan, backend: { kind: "ori", executable: contract.executable, version: contract.version, target: plan.profile.harness, provider: "openrouter", model: plan.profile.model, warnings: [...plan.warnings, ...warnings] } });
|
|
14848
|
+
output({ ...plan, backend: { kind: "ori", executable: contract.executable, version: contract.version, target: plan.profile.harness, provider: "openrouter", model: plan.profile.model, warnings: [...plan.warnings, ...warnings] }, ...sharedNativeState ? { nativeState: { shared: true, consent: values2["share-native-state"] ? "command" : "environment" } } : {} });
|
|
13451
14849
|
} else
|
|
13452
|
-
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" } } : {} });
|
|
14850
|
+
output({ ...plan, ...desktop ? { desktop: { ...desktop, mode: sharedNativeState ? "shared-state-private-auth" : "isolated-provider", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...claudeApp ? { desktop: { ...claudeApp, mode: "claude-3p-gateway", sessionProfile: profileId, ...sharedNativeState ? { sessionIdentity: "canonical-native-corpus" } : {} } } : {}, ...sharedNativeState ? { nativeState: { shared: true, consent: values2["share-native-state"] ? "command" : "environment" } } : {}, ...reasoning ? { reasoning } : {}, ...dangerouslyBypassApprovalsAndSandbox ? { permissions: { approvalPolicy: "never", sandboxMode: "danger-full-access" } } : {} });
|
|
13453
14851
|
return;
|
|
13454
14852
|
}
|
|
13455
|
-
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)) });
|
|
14853
|
+
process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, shareNativeState: Boolean(values2["share-native-state"]), 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)) });
|
|
13456
14854
|
return;
|
|
13457
14855
|
}
|
|
13458
14856
|
if (editingModel) {
|