@hasna/switcher 0.1.7 → 0.1.9
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 +166 -4
- package/dist/chatgpt-launch.d.ts +5 -0
- package/dist/claude-desktop-launch.d.ts +11 -0
- package/dist/cli/index.js +1122 -368
- package/dist/codex-delegation.d.ts +7 -0
- package/dist/credentials.d.ts +7 -7
- package/dist/desktop-apps.d.ts +25 -0
- package/dist/desktop-state.d.ts +3 -0
- package/dist/domain.d.ts +26 -4
- package/dist/generated/api.d.ts +16 -0
- package/dist/harness-process.d.ts +1 -0
- package/dist/harness-types.d.ts +3 -0
- package/dist/harnesses.d.ts +7 -3
- package/dist/index.js +199 -69
- package/dist/inference-gateway.d.ts +2 -0
- package/dist/launcher.d.ts +6 -0
- package/dist/mcp/index.js +145 -78
- package/dist/model-policy-schema.d.ts +6 -0
- package/dist/presets.d.ts +2 -0
- package/dist/reasoning.d.ts +10 -0
- package/dist/sdk.d.ts +156 -0
- package/dist/sdk.js +199 -69
- package/dist/serve/index.js +290 -74
- package/openapi.json +210 -1
- package/package.json +3 -2
package/dist/cli/index.js
CHANGED
|
@@ -448,25 +448,39 @@ function kiloConfigText(config, providerID, keyEnv) {
|
|
|
448
448
|
}
|
|
449
449
|
|
|
450
450
|
// src/domain.ts
|
|
451
|
-
import { z as
|
|
451
|
+
import { z as z4 } from "zod";
|
|
452
452
|
|
|
453
|
-
// src/
|
|
453
|
+
// src/reasoning.ts
|
|
454
454
|
import { z as z2 } from "zod";
|
|
455
|
-
var
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
455
|
+
var reasoningEffortSchema = z2.enum(["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]);
|
|
456
|
+
function codexReasoning(model, baseUrl, selected) {
|
|
457
|
+
const deepseek = new URL(baseUrl).hostname === "api.deepseek.com" && /^deepseek-(flash|v4-(flash|pro)(-.+)?)$/.test(model.id);
|
|
458
|
+
const levels = [...model.reasoningEfforts ?? (deepseek ? ["none", "low", "high", "max"] : [])];
|
|
459
|
+
if (selected && !levels.includes(selected)) {
|
|
460
|
+
if (model.reasoningEfforts !== undefined || deepseek && selected === "ultra")
|
|
461
|
+
throw new Error("Selected reasoning effort is not supported by this model's declared capabilities.");
|
|
462
|
+
levels.push(selected);
|
|
463
|
+
}
|
|
464
|
+
return { levels, defaultEffort: selected ?? (levels.includes("high") ? "high" : levels.includes("medium") ? "medium" : levels[0] ?? null) };
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// src/model-policy-schema.ts
|
|
468
|
+
import { z as z3 } from "zod";
|
|
469
|
+
var policyModelIdSchema = z3.string().min(1).max(300).regex(/^[^\u0000-\u001f\u007f]+$/);
|
|
470
|
+
var modelPolicyRoleSchema = z3.enum(["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"]);
|
|
471
|
+
var boundedModelList = z3.array(policyModelIdSchema).max(500);
|
|
472
|
+
var aliasSchema = z3.string().regex(/^[A-Za-z0-9._/-]{1,120}$/).refine((v) => !["__proto__", "prototype", "constructor"].includes(v));
|
|
473
|
+
var boundedModelMap = z3.record(aliasSchema, policyModelIdSchema).superRefine((value, ctx) => {
|
|
460
474
|
if (Object.keys(value).length > 200)
|
|
461
475
|
ctx.addIssue({ code: "custom", message: "Model policy maps may contain at most 200 entries." });
|
|
462
476
|
});
|
|
463
|
-
var fallbacksSchema =
|
|
477
|
+
var fallbacksSchema = z3.record(policyModelIdSchema, z3.array(policyModelIdSchema).max(20)).superRefine((value, ctx) => {
|
|
464
478
|
if (Object.keys(value).length > 200)
|
|
465
479
|
ctx.addIssue({ code: "custom", message: "Model policy fallback maps may contain at most 200 entries." });
|
|
466
480
|
});
|
|
467
|
-
var modelPolicySchema =
|
|
468
|
-
version:
|
|
469
|
-
roles:
|
|
481
|
+
var modelPolicySchema = z3.object({
|
|
482
|
+
version: z3.literal(1).default(1),
|
|
483
|
+
roles: z3.object({
|
|
470
484
|
subagent: policyModelIdSchema.optional(),
|
|
471
485
|
fast: policyModelIdSchema.optional(),
|
|
472
486
|
planning: policyModelIdSchema.optional(),
|
|
@@ -480,31 +494,32 @@ var modelPolicySchema = z2.object({
|
|
|
480
494
|
aliases: boundedModelMap.optional(),
|
|
481
495
|
fallbacks: fallbacksSchema.optional()
|
|
482
496
|
}).strict();
|
|
483
|
-
var routingDecisionSchema =
|
|
484
|
-
var routingEventRoleSchema =
|
|
485
|
-
var routingEventSchema =
|
|
486
|
-
at:
|
|
487
|
-
requestId:
|
|
497
|
+
var routingDecisionSchema = z3.enum(["allow", "alias", "reject", "fallback"]);
|
|
498
|
+
var routingEventRoleSchema = z3.enum(["main", ...modelPolicyRoleSchema.options]);
|
|
499
|
+
var routingEventSchema = z3.object({
|
|
500
|
+
at: z3.string().datetime({ offset: true }),
|
|
501
|
+
requestId: z3.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/),
|
|
488
502
|
requestedModel: policyModelIdSchema,
|
|
489
503
|
resolvedModel: policyModelIdSchema.optional(),
|
|
490
504
|
reportedModel: policyModelIdSchema.optional(),
|
|
505
|
+
reasoningEffort: reasoningEffortSchema.optional(),
|
|
491
506
|
decision: routingDecisionSchema,
|
|
492
507
|
role: routingEventRoleSchema.optional(),
|
|
493
|
-
reason:
|
|
494
|
-
upstreamStatus:
|
|
508
|
+
reason: z3.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),
|
|
509
|
+
upstreamStatus: z3.number().int().min(100).max(599).optional()
|
|
495
510
|
}).strict();
|
|
496
|
-
var routingEventsSchema =
|
|
511
|
+
var routingEventsSchema = z3.array(routingEventSchema).max(1000);
|
|
497
512
|
function canonicalPolicyJSON(value) {
|
|
498
513
|
return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
499
514
|
}
|
|
500
515
|
|
|
501
516
|
// src/domain.ts
|
|
502
|
-
var VERSION = "0.1.
|
|
503
|
-
var harnessSchema =
|
|
504
|
-
var protocolSchema =
|
|
505
|
-
var idSchema =
|
|
506
|
-
var label =
|
|
507
|
-
var envRef =
|
|
517
|
+
var VERSION = "0.1.9";
|
|
518
|
+
var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
|
|
519
|
+
var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
|
|
520
|
+
var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
|
|
521
|
+
var label = z4.string().min(1).max(200);
|
|
522
|
+
var envRef = z4.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/);
|
|
508
523
|
function endpoint(value) {
|
|
509
524
|
let url;
|
|
510
525
|
try {
|
|
@@ -517,85 +532,86 @@ function endpoint(value) {
|
|
|
517
532
|
throw new Fault(400, "invalid_url", "URL must use HTTPS, contain no credentials/query/fragment, or use HTTP on loopback.");
|
|
518
533
|
return url.href.replace(/\/+$/, "");
|
|
519
534
|
}
|
|
520
|
-
var urlSchema =
|
|
535
|
+
var urlSchema = z4.string().max(2000).superRefine((v, ctx) => {
|
|
521
536
|
try {
|
|
522
537
|
endpoint(v);
|
|
523
538
|
} catch {
|
|
524
539
|
ctx.addIssue({ code: "custom", message: "Invalid endpoint URL" });
|
|
525
540
|
}
|
|
526
541
|
}).transform(endpoint);
|
|
527
|
-
var expiresOnSchema =
|
|
542
|
+
var expiresOnSchema = z4.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
|
|
528
543
|
const day = new Date(`${value}T00:00:00.000Z`);
|
|
529
544
|
return Number.isFinite(day.getTime()) && day.toISOString().slice(0, 10) === value;
|
|
530
545
|
}, "Use a real calendar date in YYYY-MM-DD format.");
|
|
531
|
-
var modelSchema =
|
|
532
|
-
id:
|
|
546
|
+
var modelSchema = z4.object({
|
|
547
|
+
id: z4.string().min(1).max(300).refine((value) => value === value.trim() && !/[\x00-\x1f\x7f-\x9f]/.test(value), "Use a nonblank model ID without surrounding whitespace or control characters."),
|
|
533
548
|
name: label,
|
|
534
|
-
description:
|
|
535
|
-
available:
|
|
549
|
+
description: z4.string().max(8000).optional(),
|
|
550
|
+
available: z4.boolean().optional(),
|
|
536
551
|
expiresOn: expiresOnSchema.optional(),
|
|
537
|
-
contextWindow:
|
|
538
|
-
maxOutputTokens:
|
|
539
|
-
inputModalities:
|
|
540
|
-
outputModalities:
|
|
541
|
-
supportedParameters:
|
|
542
|
-
|
|
552
|
+
contextWindow: z4.number().int().positive().optional(),
|
|
553
|
+
maxOutputTokens: z4.number().int().positive().optional(),
|
|
554
|
+
inputModalities: z4.array(z4.string().max(50)).max(20).optional(),
|
|
555
|
+
outputModalities: z4.array(z4.string().max(50)).max(20).optional(),
|
|
556
|
+
supportedParameters: z4.array(z4.string().max(100)).max(100).optional(),
|
|
557
|
+
reasoningEfforts: z4.array(reasoningEffortSchema).max(8).optional(),
|
|
558
|
+
supportedGenerationMethods: z4.array(z4.string().min(1).max(100)).max(100).optional()
|
|
543
559
|
}).strict();
|
|
544
|
-
var providerInputSchema =
|
|
560
|
+
var providerInputSchema = z4.object({
|
|
545
561
|
id: idSchema,
|
|
546
562
|
name: label,
|
|
547
563
|
baseUrl: urlSchema,
|
|
548
564
|
protocol: protocolSchema,
|
|
549
565
|
credentialEnv: envRef.optional(),
|
|
550
|
-
authStyle:
|
|
566
|
+
authStyle: z4.enum(["bearer", "x-api-key", "api-key"]).default("bearer"),
|
|
551
567
|
catalogBaseUrl: urlSchema.optional(),
|
|
552
|
-
catalogFormat:
|
|
553
|
-
catalogAuthStyle:
|
|
568
|
+
catalogFormat: z4.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]).optional(),
|
|
569
|
+
catalogAuthStyle: z4.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
|
|
554
570
|
catalogCredentialEnv: envRef.optional(),
|
|
555
|
-
catalogAccountId:
|
|
556
|
-
modelsPath:
|
|
557
|
-
manualModels:
|
|
558
|
-
additionalModels:
|
|
571
|
+
catalogAccountId: z4.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).optional(),
|
|
572
|
+
modelsPath: z4.string().regex(/^[a-zA-Z0-9_/-]+$/).max(200).default("models"),
|
|
573
|
+
manualModels: z4.array(modelSchema).max(1e4).default([]),
|
|
574
|
+
additionalModels: z4.array(modelSchema).max(1e4).optional()
|
|
559
575
|
}).strict().refine((p) => !p.modelsPath.split("/").includes("..") && !p.modelsPath.startsWith("/"), "modelsPath must be relative");
|
|
560
|
-
var providerPresetSchema =
|
|
576
|
+
var providerPresetSchema = z4.object({
|
|
561
577
|
id: idSchema,
|
|
562
578
|
name: label,
|
|
563
579
|
credentialEnv: envRef.optional(),
|
|
564
|
-
credentialAliases:
|
|
565
|
-
protocols:
|
|
580
|
+
credentialAliases: z4.array(z4.string().regex(/^[A-Z][A-Z0-9_]+$/)),
|
|
581
|
+
protocols: z4.array(z4.object({
|
|
566
582
|
protocol: protocolSchema,
|
|
567
583
|
baseUrl: urlSchema.optional(),
|
|
568
|
-
authStyle:
|
|
584
|
+
authStyle: z4.enum(["bearer", "x-api-key", "api-key"]),
|
|
569
585
|
catalogBaseUrl: urlSchema.optional(),
|
|
570
|
-
catalogFormat:
|
|
571
|
-
catalogAuthStyle:
|
|
572
|
-
modelsPath:
|
|
573
|
-
notes:
|
|
586
|
+
catalogFormat: z4.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]),
|
|
587
|
+
catalogAuthStyle: z4.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
|
|
588
|
+
modelsPath: z4.string(),
|
|
589
|
+
notes: z4.array(z4.string())
|
|
574
590
|
}).strict()).min(1),
|
|
575
|
-
sources:
|
|
576
|
-
verification:
|
|
591
|
+
sources: z4.array(z4.string().url()),
|
|
592
|
+
verification: z4.literal("documented")
|
|
577
593
|
}).strict();
|
|
578
|
-
var profileInputSchema =
|
|
594
|
+
var profileInputSchema = z4.object({
|
|
579
595
|
id: idSchema,
|
|
580
596
|
name: label,
|
|
581
597
|
providerId: idSchema,
|
|
582
598
|
harness: harnessSchema,
|
|
583
|
-
model:
|
|
599
|
+
model: z4.string().min(1).max(300),
|
|
584
600
|
modelPolicy: modelPolicySchema.optional()
|
|
585
601
|
}).strict();
|
|
586
|
-
var runInputSchema =
|
|
587
|
-
modelPolicyVersion:
|
|
602
|
+
var runInputSchema = z4.object({
|
|
603
|
+
modelPolicyVersion: z4.literal(1),
|
|
588
604
|
profileId: idSchema,
|
|
589
605
|
harness: harnessSchema,
|
|
590
|
-
model:
|
|
606
|
+
model: z4.string().min(1).max(300),
|
|
591
607
|
modelPolicy: modelPolicySchema.optional(),
|
|
592
|
-
planToken:
|
|
608
|
+
planToken: z4.string().regex(/^[a-f0-9]{64}$/)
|
|
593
609
|
}).strict();
|
|
594
|
-
var runUpdateSchema =
|
|
595
|
-
status:
|
|
596
|
-
exitCode:
|
|
610
|
+
var runUpdateSchema = z4.object({
|
|
611
|
+
status: z4.enum(["exited", "failed", "interrupted"]),
|
|
612
|
+
exitCode: z4.number().int().min(0).max(255),
|
|
597
613
|
routingEvents: routingEventsSchema.optional(),
|
|
598
|
-
routingEventsDropped:
|
|
614
|
+
routingEventsDropped: z4.number().int().min(0).max(1e6).optional()
|
|
599
615
|
}).strict();
|
|
600
616
|
|
|
601
617
|
class Fault extends Error {
|
|
@@ -1066,8 +1082,9 @@ var preset = (id, name, protocols, sources, alias) => parse2(providerPresetSchem
|
|
|
1066
1082
|
var providerPresets = [
|
|
1067
1083
|
preset("deepseek", "DeepSeek", [
|
|
1068
1084
|
route("openai-chat", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
1085
|
+
route("openai-responses", "https://api.deepseek.com", { catalogBaseUrl: "https://api.deepseek.com" }),
|
|
1069
1086
|
route("anthropic-messages", "https://api.deepseek.com/anthropic/v1", { catalogBaseUrl: "https://api.deepseek.com" })
|
|
1070
|
-
], ["https://api-docs.deepseek.com/guides/anthropic_api", "https://api-docs.deepseek.com/api/list-models"], "DEEPSEEK_API_KEY"),
|
|
1087
|
+
], ["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"),
|
|
1071
1088
|
preset("openrouter", "OpenRouter", ["openai-chat", "openai-responses", "anthropic-messages"].map((protocol) => route(protocol, "https://openrouter.ai/api/v1", { catalogAuthStyle: "none" })), ["https://openrouter.ai/docs/api/api-reference/models/list-all-models-and-their-properties", "https://openrouter.ai/docs/guides/overview"], "OPENROUTER_API_KEY"),
|
|
1072
1089
|
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"),
|
|
1073
1090
|
preset("gemini", "Google Gemini", [route("gemini-generate-content", "https://generativelanguage.googleapis.com/v1beta", {
|
|
@@ -1149,7 +1166,7 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
1149
1166
|
const suffix = selected.protocol === "anthropic-messages" ? "messages" : selected.protocol === "openai-responses" ? "responses" : "chat";
|
|
1150
1167
|
if (presetId === "fireworks" && !options.catalogBaseUrl && !options.catalogAccountId)
|
|
1151
1168
|
throw new Fault(400, "catalog_account_required", "Fireworks model discovery requires --catalog-account-id or an explicit --catalog-url.");
|
|
1152
|
-
if (selected.catalogFormat === "none" && options.catalogFormat && !options.catalogBaseUrl)
|
|
1169
|
+
if (selected.catalogFormat === "none" && options.catalogFormat && options.catalogFormat !== "none" && !options.catalogBaseUrl)
|
|
1153
1170
|
throw new Fault(400, "catalog_url_required", "This preset requires an explicit --catalog-url when enabling a catalog parser.");
|
|
1154
1171
|
const catalogBaseUrl = options.catalogBaseUrl ?? (presetId === "fireworks" && options.catalogAccountId ? `https://api.fireworks.ai/v1/accounts/${encodeURIComponent(options.catalogAccountId)}` : options.baseUrl ? undefined : selected.catalogBaseUrl);
|
|
1155
1172
|
return parse2(providerInputSchema, {
|
|
@@ -1166,9 +1183,11 @@ function providerFromPreset(presetId, options = {}) {
|
|
|
1166
1183
|
catalogAccountId: options.catalogAccountId,
|
|
1167
1184
|
modelsPath: options.modelsPath ?? selected.modelsPath,
|
|
1168
1185
|
additionalModels: presetId === "deepseek" && new URL(baseUrl).origin === "https://api.deepseek.com" ? [{
|
|
1169
|
-
id: "deepseek-
|
|
1170
|
-
name: "DeepSeek V4.1 Flash
|
|
1171
|
-
|
|
1186
|
+
id: "deepseek-flash",
|
|
1187
|
+
name: "DeepSeek V4.1 Flash",
|
|
1188
|
+
inputModalities: ["text", "image"],
|
|
1189
|
+
outputModalities: ["text"],
|
|
1190
|
+
supportedParameters: ["tools"]
|
|
1172
1191
|
}] : []
|
|
1173
1192
|
});
|
|
1174
1193
|
}
|
|
@@ -1184,6 +1203,98 @@ function providerCredential(provider, env = process.env) {
|
|
|
1184
1203
|
throw new Fault(422, "credential_invalid", "Provider credential contains invalid header characters.");
|
|
1185
1204
|
return value;
|
|
1186
1205
|
}
|
|
1206
|
+
// src/desktop-apps.ts
|
|
1207
|
+
import { execFile } from "child_process";
|
|
1208
|
+
import { access, stat as stat3 } from "fs/promises";
|
|
1209
|
+
import { constants as constants2 } from "fs";
|
|
1210
|
+
import { homedir as homedir2 } from "os";
|
|
1211
|
+
import { isAbsolute as isAbsolute3, join as join3 } from "path";
|
|
1212
|
+
import { promisify } from "util";
|
|
1213
|
+
var execute = promisify(execFile);
|
|
1214
|
+
var host = {
|
|
1215
|
+
platform: process.platform,
|
|
1216
|
+
home: homedir2(),
|
|
1217
|
+
async run(command, args) {
|
|
1218
|
+
const { stdout } = await execute(command, args, { encoding: "utf8", timeout: 8000, maxBuffer: 64 * 1024, env: { PATH: "/usr/bin:/bin", HOME: homedir2() } });
|
|
1219
|
+
return stdout.trim();
|
|
1220
|
+
},
|
|
1221
|
+
async executable(path) {
|
|
1222
|
+
try {
|
|
1223
|
+
await access(path, constants2.X_OK);
|
|
1224
|
+
return (await stat3(path)).isFile();
|
|
1225
|
+
} catch {
|
|
1226
|
+
return false;
|
|
1227
|
+
}
|
|
1228
|
+
},
|
|
1229
|
+
async isDirectory(path) {
|
|
1230
|
+
try {
|
|
1231
|
+
return (await stat3(path)).isDirectory();
|
|
1232
|
+
} catch {
|
|
1233
|
+
return false;
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
};
|
|
1237
|
+
async function detectChatGPTApp(appPath, system = host) {
|
|
1238
|
+
if (system.platform !== "darwin")
|
|
1239
|
+
throw new Fault(422, "unsupported_platform", "ChatGPT provider launches currently require the macOS desktop app.");
|
|
1240
|
+
let candidates;
|
|
1241
|
+
if (appPath !== undefined)
|
|
1242
|
+
candidates = [appPath];
|
|
1243
|
+
else {
|
|
1244
|
+
candidates = ["ChatGPT.app", "Codex.app"].flatMap((name) => [join3(system.home, "Applications", name), join3("/Applications", name)]);
|
|
1245
|
+
try {
|
|
1246
|
+
const found = await system.run("/usr/bin/osascript", ["-l", "JavaScript", "-e", 'ObjC.import("AppKit"); const url = $.NSWorkspace.sharedWorkspace.URLForApplicationWithBundleIdentifier("com.openai.codex"); url.isNil() ? "" : ObjC.unwrap(url.path);']);
|
|
1247
|
+
if (found)
|
|
1248
|
+
candidates.push(found);
|
|
1249
|
+
} catch {}
|
|
1250
|
+
}
|
|
1251
|
+
for (const path of new Set(candidates)) {
|
|
1252
|
+
if (!isAbsolute3(path) || !path.endsWith(".app") || !await system.isDirectory(path))
|
|
1253
|
+
continue;
|
|
1254
|
+
const plist = join3(path, "Contents/Info.plist");
|
|
1255
|
+
const field = (name) => system.run("/usr/bin/plutil", ["-extract", name, "raw", "-o", "-", plist]);
|
|
1256
|
+
try {
|
|
1257
|
+
const bundleId = await field("CFBundleIdentifier");
|
|
1258
|
+
if (bundleId !== "com.openai.codex")
|
|
1259
|
+
continue;
|
|
1260
|
+
const name = await field("CFBundleExecutable"), version = await field("CFBundleShortVersionString");
|
|
1261
|
+
if (!/^[A-Za-z0-9 _-]+$/.test(name))
|
|
1262
|
+
continue;
|
|
1263
|
+
const executable = join3(path, "Contents/MacOS", name), codexExecutable = join3(path, "Contents/Resources/codex");
|
|
1264
|
+
if (await system.executable(executable) && await system.executable(codexExecutable))
|
|
1265
|
+
return { path, executable, codexExecutable, bundleId, version };
|
|
1266
|
+
} catch {}
|
|
1267
|
+
}
|
|
1268
|
+
throw new Fault(404, "app_not_installed", "Install the current ChatGPT/Codex macOS app or use --app-path with its absolute .app path. Legacy ChatGPT Classic cannot run custom Codex providers.");
|
|
1269
|
+
}
|
|
1270
|
+
async function detectClaudeDesktopApp(appPath, system = host) {
|
|
1271
|
+
if (system.platform !== "darwin")
|
|
1272
|
+
throw new Fault(422, "unsupported_platform", "Claude desktop provider launches currently require macOS.");
|
|
1273
|
+
const candidates = appPath === undefined ? [join3(system.home, "Applications/Claude.app"), "/Applications/Claude.app"] : [appPath];
|
|
1274
|
+
if (appPath === undefined)
|
|
1275
|
+
try {
|
|
1276
|
+
const found = await system.run("/usr/bin/osascript", ["-l", "JavaScript", "-e", 'ObjC.import("AppKit"); const url = $.NSWorkspace.sharedWorkspace.URLForApplicationWithBundleIdentifier("com.anthropic.claudefordesktop"); url.isNil() ? "" : ObjC.unwrap(url.path);']);
|
|
1277
|
+
if (found)
|
|
1278
|
+
candidates.push(found);
|
|
1279
|
+
} catch {}
|
|
1280
|
+
for (const path of new Set(candidates)) {
|
|
1281
|
+
if (!isAbsolute3(path) || !path.endsWith(".app") || !await system.isDirectory(path))
|
|
1282
|
+
continue;
|
|
1283
|
+
const field = (name) => system.run("/usr/bin/plutil", ["-extract", name, "raw", "-o", "-", join3(path, "Contents/Info.plist")]);
|
|
1284
|
+
try {
|
|
1285
|
+
const bundleId = await field("CFBundleIdentifier");
|
|
1286
|
+
if (bundleId !== "com.anthropic.claudefordesktop")
|
|
1287
|
+
continue;
|
|
1288
|
+
const name = await field("CFBundleExecutable"), version = await field("CFBundleShortVersionString");
|
|
1289
|
+
if (!/^[A-Za-z0-9 _-]+$/.test(name))
|
|
1290
|
+
continue;
|
|
1291
|
+
const executable = join3(path, "Contents/MacOS", name);
|
|
1292
|
+
if (await system.executable(executable))
|
|
1293
|
+
return { path, executable, bundleId, version };
|
|
1294
|
+
} catch {}
|
|
1295
|
+
}
|
|
1296
|
+
throw new Fault(404, "app_not_installed", "Install the current Claude macOS desktop app or supply its absolute .app path with --app-path.");
|
|
1297
|
+
}
|
|
1187
1298
|
|
|
1188
1299
|
// src/sdk.ts
|
|
1189
1300
|
class SwitcherError extends Error {
|
|
@@ -1331,6 +1442,33 @@ class SwitcherClient {
|
|
|
1331
1442
|
deleteProvider(id, version, idempotencyKey) {
|
|
1332
1443
|
return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version, idempotencyKey });
|
|
1333
1444
|
}
|
|
1445
|
+
async editModel(providerId, operation, value) {
|
|
1446
|
+
const model = typeof value === "string" ? undefined : parse2(modelSchema, value);
|
|
1447
|
+
const id = model?.id ?? parse2(modelSchema.shape.id, value);
|
|
1448
|
+
const provider = await this.getProvider(providerId);
|
|
1449
|
+
const { version, updatedAt, ...input } = provider;
|
|
1450
|
+
const manual = provider.manualModels.some((item) => item.id === id);
|
|
1451
|
+
const additional = (provider.additionalModels ?? []).some((item) => item.id === id);
|
|
1452
|
+
if (operation === "add" && (manual || additional))
|
|
1453
|
+
throw new SwitcherError(409, "model_exists", "This model is already configured. Use models update to replace its metadata.");
|
|
1454
|
+
if (operation !== "add" && !manual && !additional)
|
|
1455
|
+
throw new SwitcherError(404, "model_not_configured", "This model has no saved metadata. Use models add to configure a catalog model; remote catalog entries cannot be deleted locally.");
|
|
1456
|
+
const useManual = manual || !additional && (provider.manualModels.length > 0 || provider.catalogFormat === "none");
|
|
1457
|
+
const manualModels = provider.manualModels.filter((item) => item.id !== id);
|
|
1458
|
+
const additionalModels = (provider.additionalModels ?? []).filter((item) => item.id !== id);
|
|
1459
|
+
if (operation !== "remove")
|
|
1460
|
+
(useManual ? manualModels : additionalModels).push(model);
|
|
1461
|
+
return this.updateProvider({ ...input, manualModels, additionalModels }, version);
|
|
1462
|
+
}
|
|
1463
|
+
addModel(providerId, model) {
|
|
1464
|
+
return this.editModel(providerId, "add", model);
|
|
1465
|
+
}
|
|
1466
|
+
updateModel(providerId, model) {
|
|
1467
|
+
return this.editModel(providerId, "update", model);
|
|
1468
|
+
}
|
|
1469
|
+
removeModel(providerId, modelId) {
|
|
1470
|
+
return this.editModel(providerId, "remove", modelId);
|
|
1471
|
+
}
|
|
1334
1472
|
refreshModels(id, idempotencyKey) {
|
|
1335
1473
|
return this.request("POST", `/v1/providers/${encodeURIComponent(id)}/refresh`, {}, { idempotencyKey });
|
|
1336
1474
|
}
|
|
@@ -1568,15 +1706,15 @@ function openCodeInvocationModel(args, policy, defaultAgent) {
|
|
|
1568
1706
|
|
|
1569
1707
|
// src/gemini-config.ts
|
|
1570
1708
|
import { readFile, writeFile as writeFile3, lstat as lstat2, readdir as readdir2, symlink, realpath as realpath2 } from "fs/promises";
|
|
1571
|
-
import { join as
|
|
1572
|
-
import { homedir as
|
|
1709
|
+
import { join as join5, dirname as dirname3, resolve as resolve4, isAbsolute as isAbsolute5, relative as relative2, sep } from "path";
|
|
1710
|
+
import { homedir as homedir4 } from "os";
|
|
1573
1711
|
import { parseTree as parseTree2, getNodeValue } from "jsonc-parser";
|
|
1574
1712
|
|
|
1575
1713
|
// src/runtime.ts
|
|
1576
1714
|
import { randomBytes } from "crypto";
|
|
1577
1715
|
import { mkdir as mkdir4, lstat } from "fs/promises";
|
|
1578
|
-
import { homedir as
|
|
1579
|
-
import { isAbsolute as
|
|
1716
|
+
import { homedir as homedir3 } from "os";
|
|
1717
|
+
import { isAbsolute as isAbsolute4, join as join4, resolve as resolve3 } from "path";
|
|
1580
1718
|
|
|
1581
1719
|
// src/store.ts
|
|
1582
1720
|
var {SQL } = globalThis.Bun;
|
|
@@ -1741,7 +1879,7 @@ class Store {
|
|
|
1741
1879
|
|
|
1742
1880
|
// src/service.ts
|
|
1743
1881
|
import { createHash as createHash3, timingSafeEqual } from "crypto";
|
|
1744
|
-
import { z as
|
|
1882
|
+
import { z as z5 } from "zod";
|
|
1745
1883
|
|
|
1746
1884
|
// src/auth.ts
|
|
1747
1885
|
function authHeader(style, credential) {
|
|
@@ -2178,7 +2316,7 @@ var openapi_default = {
|
|
|
2178
2316
|
openapi: "3.0.3",
|
|
2179
2317
|
info: {
|
|
2180
2318
|
title: "Switcher API",
|
|
2181
|
-
version: "0.1.
|
|
2319
|
+
version: "0.1.9",
|
|
2182
2320
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2183
2321
|
},
|
|
2184
2322
|
security: [
|
|
@@ -3617,6 +3755,23 @@ var openapi_default = {
|
|
|
3617
3755
|
},
|
|
3618
3756
|
maxItems: 100
|
|
3619
3757
|
},
|
|
3758
|
+
reasoningEfforts: {
|
|
3759
|
+
type: "array",
|
|
3760
|
+
items: {
|
|
3761
|
+
type: "string",
|
|
3762
|
+
enum: [
|
|
3763
|
+
"none",
|
|
3764
|
+
"minimal",
|
|
3765
|
+
"low",
|
|
3766
|
+
"medium",
|
|
3767
|
+
"high",
|
|
3768
|
+
"xhigh",
|
|
3769
|
+
"max",
|
|
3770
|
+
"ultra"
|
|
3771
|
+
]
|
|
3772
|
+
},
|
|
3773
|
+
maxItems: 8
|
|
3774
|
+
},
|
|
3620
3775
|
supportedGenerationMethods: {
|
|
3621
3776
|
type: "array",
|
|
3622
3777
|
items: {
|
|
@@ -3696,6 +3851,23 @@ var openapi_default = {
|
|
|
3696
3851
|
},
|
|
3697
3852
|
maxItems: 100
|
|
3698
3853
|
},
|
|
3854
|
+
reasoningEfforts: {
|
|
3855
|
+
type: "array",
|
|
3856
|
+
items: {
|
|
3857
|
+
type: "string",
|
|
3858
|
+
enum: [
|
|
3859
|
+
"none",
|
|
3860
|
+
"minimal",
|
|
3861
|
+
"low",
|
|
3862
|
+
"medium",
|
|
3863
|
+
"high",
|
|
3864
|
+
"xhigh",
|
|
3865
|
+
"max",
|
|
3866
|
+
"ultra"
|
|
3867
|
+
]
|
|
3868
|
+
},
|
|
3869
|
+
maxItems: 8
|
|
3870
|
+
},
|
|
3699
3871
|
supportedGenerationMethods: {
|
|
3700
3872
|
type: "array",
|
|
3701
3873
|
items: {
|
|
@@ -3861,6 +4033,23 @@ var openapi_default = {
|
|
|
3861
4033
|
},
|
|
3862
4034
|
maxItems: 100
|
|
3863
4035
|
},
|
|
4036
|
+
reasoningEfforts: {
|
|
4037
|
+
type: "array",
|
|
4038
|
+
items: {
|
|
4039
|
+
type: "string",
|
|
4040
|
+
enum: [
|
|
4041
|
+
"none",
|
|
4042
|
+
"minimal",
|
|
4043
|
+
"low",
|
|
4044
|
+
"medium",
|
|
4045
|
+
"high",
|
|
4046
|
+
"xhigh",
|
|
4047
|
+
"max",
|
|
4048
|
+
"ultra"
|
|
4049
|
+
]
|
|
4050
|
+
},
|
|
4051
|
+
maxItems: 8
|
|
4052
|
+
},
|
|
3864
4053
|
supportedGenerationMethods: {
|
|
3865
4054
|
type: "array",
|
|
3866
4055
|
items: {
|
|
@@ -3940,6 +4129,23 @@ var openapi_default = {
|
|
|
3940
4129
|
},
|
|
3941
4130
|
maxItems: 100
|
|
3942
4131
|
},
|
|
4132
|
+
reasoningEfforts: {
|
|
4133
|
+
type: "array",
|
|
4134
|
+
items: {
|
|
4135
|
+
type: "string",
|
|
4136
|
+
enum: [
|
|
4137
|
+
"none",
|
|
4138
|
+
"minimal",
|
|
4139
|
+
"low",
|
|
4140
|
+
"medium",
|
|
4141
|
+
"high",
|
|
4142
|
+
"xhigh",
|
|
4143
|
+
"max",
|
|
4144
|
+
"ultra"
|
|
4145
|
+
]
|
|
4146
|
+
},
|
|
4147
|
+
maxItems: 8
|
|
4148
|
+
},
|
|
3943
4149
|
supportedGenerationMethods: {
|
|
3944
4150
|
type: "array",
|
|
3945
4151
|
items: {
|
|
@@ -4343,6 +4549,23 @@ var openapi_default = {
|
|
|
4343
4549
|
},
|
|
4344
4550
|
maxItems: 100
|
|
4345
4551
|
},
|
|
4552
|
+
reasoningEfforts: {
|
|
4553
|
+
type: "array",
|
|
4554
|
+
items: {
|
|
4555
|
+
type: "string",
|
|
4556
|
+
enum: [
|
|
4557
|
+
"none",
|
|
4558
|
+
"minimal",
|
|
4559
|
+
"low",
|
|
4560
|
+
"medium",
|
|
4561
|
+
"high",
|
|
4562
|
+
"xhigh",
|
|
4563
|
+
"max",
|
|
4564
|
+
"ultra"
|
|
4565
|
+
]
|
|
4566
|
+
},
|
|
4567
|
+
maxItems: 8
|
|
4568
|
+
},
|
|
4346
4569
|
supportedGenerationMethods: {
|
|
4347
4570
|
type: "array",
|
|
4348
4571
|
items: {
|
|
@@ -4487,6 +4710,19 @@ var openapi_default = {
|
|
|
4487
4710
|
maxLength: 300,
|
|
4488
4711
|
pattern: "^[^\\u0000-\\u001f\\u007f]+$"
|
|
4489
4712
|
},
|
|
4713
|
+
reasoningEffort: {
|
|
4714
|
+
type: "string",
|
|
4715
|
+
enum: [
|
|
4716
|
+
"none",
|
|
4717
|
+
"minimal",
|
|
4718
|
+
"low",
|
|
4719
|
+
"medium",
|
|
4720
|
+
"high",
|
|
4721
|
+
"xhigh",
|
|
4722
|
+
"max",
|
|
4723
|
+
"ultra"
|
|
4724
|
+
]
|
|
4725
|
+
},
|
|
4490
4726
|
decision: {
|
|
4491
4727
|
type: "string",
|
|
4492
4728
|
enum: [
|
|
@@ -4591,6 +4827,23 @@ var openapi_default = {
|
|
|
4591
4827
|
},
|
|
4592
4828
|
maxItems: 100
|
|
4593
4829
|
},
|
|
4830
|
+
reasoningEfforts: {
|
|
4831
|
+
type: "array",
|
|
4832
|
+
items: {
|
|
4833
|
+
type: "string",
|
|
4834
|
+
enum: [
|
|
4835
|
+
"none",
|
|
4836
|
+
"minimal",
|
|
4837
|
+
"low",
|
|
4838
|
+
"medium",
|
|
4839
|
+
"high",
|
|
4840
|
+
"xhigh",
|
|
4841
|
+
"max",
|
|
4842
|
+
"ultra"
|
|
4843
|
+
]
|
|
4844
|
+
},
|
|
4845
|
+
maxItems: 8
|
|
4846
|
+
},
|
|
4594
4847
|
supportedGenerationMethods: {
|
|
4595
4848
|
type: "array",
|
|
4596
4849
|
items: {
|
|
@@ -4709,6 +4962,23 @@ var openapi_default = {
|
|
|
4709
4962
|
},
|
|
4710
4963
|
maxItems: 100
|
|
4711
4964
|
},
|
|
4965
|
+
reasoningEfforts: {
|
|
4966
|
+
type: "array",
|
|
4967
|
+
items: {
|
|
4968
|
+
type: "string",
|
|
4969
|
+
enum: [
|
|
4970
|
+
"none",
|
|
4971
|
+
"minimal",
|
|
4972
|
+
"low",
|
|
4973
|
+
"medium",
|
|
4974
|
+
"high",
|
|
4975
|
+
"xhigh",
|
|
4976
|
+
"max",
|
|
4977
|
+
"ultra"
|
|
4978
|
+
]
|
|
4979
|
+
},
|
|
4980
|
+
maxItems: 8
|
|
4981
|
+
},
|
|
4712
4982
|
supportedGenerationMethods: {
|
|
4713
4983
|
type: "array",
|
|
4714
4984
|
items: {
|
|
@@ -4885,6 +5155,23 @@ var openapi_default = {
|
|
|
4885
5155
|
},
|
|
4886
5156
|
maxItems: 100
|
|
4887
5157
|
},
|
|
5158
|
+
reasoningEfforts: {
|
|
5159
|
+
type: "array",
|
|
5160
|
+
items: {
|
|
5161
|
+
type: "string",
|
|
5162
|
+
enum: [
|
|
5163
|
+
"none",
|
|
5164
|
+
"minimal",
|
|
5165
|
+
"low",
|
|
5166
|
+
"medium",
|
|
5167
|
+
"high",
|
|
5168
|
+
"xhigh",
|
|
5169
|
+
"max",
|
|
5170
|
+
"ultra"
|
|
5171
|
+
]
|
|
5172
|
+
},
|
|
5173
|
+
maxItems: 8
|
|
5174
|
+
},
|
|
4888
5175
|
supportedGenerationMethods: {
|
|
4889
5176
|
type: "array",
|
|
4890
5177
|
items: {
|
|
@@ -4964,6 +5251,23 @@ var openapi_default = {
|
|
|
4964
5251
|
},
|
|
4965
5252
|
maxItems: 100
|
|
4966
5253
|
},
|
|
5254
|
+
reasoningEfforts: {
|
|
5255
|
+
type: "array",
|
|
5256
|
+
items: {
|
|
5257
|
+
type: "string",
|
|
5258
|
+
enum: [
|
|
5259
|
+
"none",
|
|
5260
|
+
"minimal",
|
|
5261
|
+
"low",
|
|
5262
|
+
"medium",
|
|
5263
|
+
"high",
|
|
5264
|
+
"xhigh",
|
|
5265
|
+
"max",
|
|
5266
|
+
"ultra"
|
|
5267
|
+
]
|
|
5268
|
+
},
|
|
5269
|
+
maxItems: 8
|
|
5270
|
+
},
|
|
4967
5271
|
supportedGenerationMethods: {
|
|
4968
5272
|
type: "array",
|
|
4969
5273
|
items: {
|
|
@@ -5223,6 +5527,23 @@ var openapi_default = {
|
|
|
5223
5527
|
},
|
|
5224
5528
|
maxItems: 100
|
|
5225
5529
|
},
|
|
5530
|
+
reasoningEfforts: {
|
|
5531
|
+
type: "array",
|
|
5532
|
+
items: {
|
|
5533
|
+
type: "string",
|
|
5534
|
+
enum: [
|
|
5535
|
+
"none",
|
|
5536
|
+
"minimal",
|
|
5537
|
+
"low",
|
|
5538
|
+
"medium",
|
|
5539
|
+
"high",
|
|
5540
|
+
"xhigh",
|
|
5541
|
+
"max",
|
|
5542
|
+
"ultra"
|
|
5543
|
+
]
|
|
5544
|
+
},
|
|
5545
|
+
maxItems: 8
|
|
5546
|
+
},
|
|
5226
5547
|
supportedGenerationMethods: {
|
|
5227
5548
|
type: "array",
|
|
5228
5549
|
items: {
|
|
@@ -5474,6 +5795,19 @@ var openapi_default = {
|
|
|
5474
5795
|
maxLength: 300,
|
|
5475
5796
|
pattern: "^[^\\u0000-\\u001f\\u007f]+$"
|
|
5476
5797
|
},
|
|
5798
|
+
reasoningEffort: {
|
|
5799
|
+
type: "string",
|
|
5800
|
+
enum: [
|
|
5801
|
+
"none",
|
|
5802
|
+
"minimal",
|
|
5803
|
+
"low",
|
|
5804
|
+
"medium",
|
|
5805
|
+
"high",
|
|
5806
|
+
"xhigh",
|
|
5807
|
+
"max",
|
|
5808
|
+
"ultra"
|
|
5809
|
+
]
|
|
5810
|
+
},
|
|
5477
5811
|
decision: {
|
|
5478
5812
|
type: "string",
|
|
5479
5813
|
enum: [
|
|
@@ -5744,6 +6078,19 @@ var openapi_default = {
|
|
|
5744
6078
|
maxLength: 300,
|
|
5745
6079
|
pattern: "^[^\\u0000-\\u001f\\u007f]+$"
|
|
5746
6080
|
},
|
|
6081
|
+
reasoningEffort: {
|
|
6082
|
+
type: "string",
|
|
6083
|
+
enum: [
|
|
6084
|
+
"none",
|
|
6085
|
+
"minimal",
|
|
6086
|
+
"low",
|
|
6087
|
+
"medium",
|
|
6088
|
+
"high",
|
|
6089
|
+
"xhigh",
|
|
6090
|
+
"max",
|
|
6091
|
+
"ultra"
|
|
6092
|
+
]
|
|
6093
|
+
},
|
|
5747
6094
|
decision: {
|
|
5748
6095
|
type: "string",
|
|
5749
6096
|
enum: [
|
|
@@ -5952,10 +6299,10 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5952
6299
|
const id2 = parts[2];
|
|
5953
6300
|
if (id2)
|
|
5954
6301
|
parse2(idSchema, id2);
|
|
5955
|
-
const page = () => parse2(
|
|
5956
|
-
limit:
|
|
5957
|
-
offset:
|
|
5958
|
-
search:
|
|
6302
|
+
const page = () => parse2(z5.object({
|
|
6303
|
+
limit: z5.coerce.number().int().min(1).max(1000).default(100),
|
|
6304
|
+
offset: z5.coerce.number().int().min(0).max(1e6).default(0),
|
|
6305
|
+
search: z5.string().max(200).default("")
|
|
5959
6306
|
}).strict(), Object.fromEntries(url.searchParams));
|
|
5960
6307
|
if (request.method === "GET") {
|
|
5961
6308
|
if (resource === "provider-presets" && parts.length <= 3)
|
|
@@ -5999,7 +6346,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5999
6346
|
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
|
|
6000
6347
|
let refreshed;
|
|
6001
6348
|
if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
6002
|
-
parse2(
|
|
6349
|
+
parse2(z5.object({}).strict(), body);
|
|
6003
6350
|
const provider = await store.get("providers", id2);
|
|
6004
6351
|
refreshed = { provider, catalog: await discover(provider, providerEnv, resolveCredential) };
|
|
6005
6352
|
}
|
|
@@ -6039,7 +6386,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
6039
6386
|
return store.put("catalogs", { id: id2, ...catalog }, old?.version, db);
|
|
6040
6387
|
}
|
|
6041
6388
|
if (resource === "launch-plans" && !id2 && request.method === "POST") {
|
|
6042
|
-
const { profileId } = parse2(
|
|
6389
|
+
const { profileId } = parse2(z5.object({ profileId: idSchema }).strict(), body);
|
|
6043
6390
|
const profile = await store.get("profiles", profileId, db);
|
|
6044
6391
|
const provider = await store.get("providers", profile.providerId, db);
|
|
6045
6392
|
validateHarnessProvider(profile.harness, provider);
|
|
@@ -6154,8 +6501,8 @@ async function startServer(options) {
|
|
|
6154
6501
|
import { resolveCredential as resolveClientCredential, clientTransportEnvKeys, appConfigDiskValue, keychainConfigValue } from "@hasna/contracts/client";
|
|
6155
6502
|
function switcherHome(env = process.env) {
|
|
6156
6503
|
const override = env.HASNA_HOME?.trim();
|
|
6157
|
-
const root = override &&
|
|
6158
|
-
return resolve3(env.HASNA_SWITCHER_HOME ??
|
|
6504
|
+
const root = override && isAbsolute4(override) ? override : join4(env.HOME?.trim() || homedir3(), ".hasna");
|
|
6505
|
+
return resolve3(env.HASNA_SWITCHER_HOME ?? join4(root, "switcher"));
|
|
6159
6506
|
}
|
|
6160
6507
|
async function privateDirectory(path) {
|
|
6161
6508
|
await mkdir4(path, { recursive: true, mode: 448 });
|
|
@@ -6180,7 +6527,7 @@ async function openCliRuntime(env = process.env, resolveCredential) {
|
|
|
6180
6527
|
const service = await startServer({
|
|
6181
6528
|
apiKey,
|
|
6182
6529
|
databaseUrl: env.HASNA_SWITCHER_DATABASE_URL,
|
|
6183
|
-
sqlitePath: env.HASNA_SWITCHER_SQLITE_PATH ?? (env.HASNA_SWITCHER_DATABASE_URL ? undefined :
|
|
6530
|
+
sqlitePath: env.HASNA_SWITCHER_SQLITE_PATH ?? (env.HASNA_SWITCHER_DATABASE_URL ? undefined : join4(home, "switcher.db")),
|
|
6184
6531
|
providerEnv,
|
|
6185
6532
|
resolveCredential
|
|
6186
6533
|
});
|
|
@@ -6273,8 +6620,8 @@ var nativeModels = ["gemini-3.1-flash-lite", "gemini-3.1-pro-preview", "gemini-3
|
|
|
6273
6620
|
var object2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
6274
6621
|
async function regular(path, limit = 2 * 1024 * 1024) {
|
|
6275
6622
|
try {
|
|
6276
|
-
const
|
|
6277
|
-
if (!
|
|
6623
|
+
const stat4 = await lstat2(path);
|
|
6624
|
+
if (!stat4.isFile() || stat4.size > limit)
|
|
6278
6625
|
throw new Error("unsupported");
|
|
6279
6626
|
return true;
|
|
6280
6627
|
} catch (error) {
|
|
@@ -6327,12 +6674,12 @@ function originalPaths(value, home) {
|
|
|
6327
6674
|
return result;
|
|
6328
6675
|
}
|
|
6329
6676
|
async function validateGeminiConfiguration(cwd, env = process.env) {
|
|
6330
|
-
const home = env.GEMINI_CLI_HOME ?? env.HOME ??
|
|
6331
|
-
if (!
|
|
6677
|
+
const home = env.GEMINI_CLI_HOME ?? env.HOME ?? homedir4();
|
|
6678
|
+
if (!isAbsolute5(home))
|
|
6332
6679
|
throw new Error("Gemini requires an absolute native home.");
|
|
6333
6680
|
const systemPath = env.GEMINI_CLI_SYSTEM_SETTINGS_PATH ?? (process.platform === "darwin" ? "/Library/Application Support/GeminiCli/settings.json" : process.platform === "win32" ? "C:\\ProgramData\\gemini-cli\\settings.json" : "/etc/gemini-cli/settings.json");
|
|
6334
|
-
const defaultsPath = env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ??
|
|
6335
|
-
const paths = [defaultsPath,
|
|
6681
|
+
const defaultsPath = env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ?? join5(dirname3(systemPath), "system-defaults.json");
|
|
6682
|
+
const paths = [defaultsPath, join5(home, ".gemini", "settings.json"), join5(resolve4(cwd), ".gemini", "settings.json"), systemPath];
|
|
6336
6683
|
const values2 = [];
|
|
6337
6684
|
for (const path of paths) {
|
|
6338
6685
|
const value = await settings(path);
|
|
@@ -6343,7 +6690,7 @@ async function validateGeminiConfiguration(cwd, env = process.env) {
|
|
|
6343
6690
|
if (values2[2][key]?.some?.((path) => typeof path === "string" && (path === "~" || path.startsWith("~/"))))
|
|
6344
6691
|
throw new Error("Gemini project policy paths using ~ must use an absolute path so workspace trust remains authoritative under an isolated native home.");
|
|
6345
6692
|
const contextNames = [...new Set(["GEMINI.md", ...values2.flatMap((value) => [value.context?.fileName ?? []].flat())])];
|
|
6346
|
-
return { home, defaults: originalPaths(values2[0], home), user: originalPaths(values2[1], home), system: originalPaths(values2[3], home), contextNames, trustPath: env.GEMINI_CLI_TRUSTED_FOLDERS_PATH ??
|
|
6693
|
+
return { home, defaults: originalPaths(values2[0], home), user: originalPaths(values2[1], home), system: originalPaths(values2[3], home), contextNames, trustPath: env.GEMINI_CLI_TRUSTED_FOLDERS_PATH ?? join5(home, ".gemini", "trustedFolders.json") };
|
|
6347
6694
|
}
|
|
6348
6695
|
async function snapshotFile(source, destination) {
|
|
6349
6696
|
if (await regular(source))
|
|
@@ -6352,8 +6699,8 @@ async function snapshotFile(source, destination) {
|
|
|
6352
6699
|
async function snapshotPolicies(source, destination) {
|
|
6353
6700
|
let entries;
|
|
6354
6701
|
try {
|
|
6355
|
-
const
|
|
6356
|
-
if (!
|
|
6702
|
+
const stat4 = await lstat2(source);
|
|
6703
|
+
if (!stat4.isDirectory() || stat4.isSymbolicLink())
|
|
6357
6704
|
throw new Error("Unsupported Gemini policy directory");
|
|
6358
6705
|
entries = await readdir2(source, { withFileTypes: true });
|
|
6359
6706
|
} catch (error) {
|
|
@@ -6366,12 +6713,12 @@ async function snapshotPolicies(source, destination) {
|
|
|
6366
6713
|
throw new Error("Gemini user policy directory exceeds the snapshot limit.");
|
|
6367
6714
|
for (const entry of entries) {
|
|
6368
6715
|
if (entry.name.endsWith(".toml"))
|
|
6369
|
-
await snapshotFile(
|
|
6716
|
+
await snapshotFile(join5(source, entry.name), join5(destination, entry.name));
|
|
6370
6717
|
}
|
|
6371
6718
|
}
|
|
6372
6719
|
async function snapshotContext(sourceDir, destinationDir, names) {
|
|
6373
6720
|
const root = await realpath2(sourceDir), files = new Map;
|
|
6374
|
-
const importsDir =
|
|
6721
|
+
const importsDir = join5(destinationDir, ".switcher-context");
|
|
6375
6722
|
let bytes = 0;
|
|
6376
6723
|
const copy = async (source, destination) => {
|
|
6377
6724
|
if (files.has(source))
|
|
@@ -6392,9 +6739,9 @@ async function snapshotContext(sourceDir, destinationDir, names) {
|
|
|
6392
6739
|
if (code.some(([a, b]) => start >= a && start < b))
|
|
6393
6740
|
continue;
|
|
6394
6741
|
const imported = resolve4(dirname3(source), match[2]), actual = await realpath2(imported).catch(() => imported), within = relative2(root, actual);
|
|
6395
|
-
if (within === ".." || within.startsWith(".." + sep) ||
|
|
6742
|
+
if (within === ".." || within.startsWith(".." + sep) || isAbsolute5(within))
|
|
6396
6743
|
throw new Error("Gemini global context imports outside the original context directory require a supported explicit context location.");
|
|
6397
|
-
const target = files.get(imported) ??
|
|
6744
|
+
const target = files.get(imported) ?? join5(importsDir, `${files.size}.md`);
|
|
6398
6745
|
await privateDirectory(importsDir);
|
|
6399
6746
|
await copy(imported, target);
|
|
6400
6747
|
output += text.slice(last, start) + "@./" + relative2(dirname3(destination), target).split(sep).join("/");
|
|
@@ -6403,30 +6750,30 @@ async function snapshotContext(sourceDir, destinationDir, names) {
|
|
|
6403
6750
|
await writeFile3(destination, output + text.slice(last), { mode: 384, flag: "wx" });
|
|
6404
6751
|
};
|
|
6405
6752
|
for (const name of names)
|
|
6406
|
-
if (await regular(
|
|
6407
|
-
await copy(
|
|
6753
|
+
if (await regular(join5(sourceDir, name)))
|
|
6754
|
+
await copy(join5(sourceDir, name), join5(destinationDir, name));
|
|
6408
6755
|
}
|
|
6409
6756
|
async function prepareGemini(input) {
|
|
6410
6757
|
const original = await validateGeminiConfiguration(input.cwd);
|
|
6411
|
-
const home =
|
|
6758
|
+
const home = join5(input.stateDir, "gemini-home"), dir = join5(home, ".gemini");
|
|
6412
6759
|
await privateDirectory(home);
|
|
6413
6760
|
await privateDirectory(dir);
|
|
6414
|
-
const durable =
|
|
6761
|
+
const durable = join5(input.sessionDir ?? join5(input.stateDir, "sessions"), "gemini-home", ".gemini");
|
|
6415
6762
|
await privateDirectory(durable);
|
|
6416
6763
|
for (const name of ["tmp", "history"]) {
|
|
6417
|
-
const target =
|
|
6764
|
+
const target = join5(durable, name);
|
|
6418
6765
|
await privateDirectory(target);
|
|
6419
|
-
await symlink(target,
|
|
6766
|
+
await symlink(target, join5(dir, name), "dir");
|
|
6420
6767
|
}
|
|
6421
|
-
await snapshotFile(original.trustPath,
|
|
6422
|
-
await snapshotPolicies(
|
|
6768
|
+
await snapshotFile(original.trustPath, join5(dir, "trustedFolders.json"));
|
|
6769
|
+
await snapshotPolicies(join5(original.home, ".gemini", "policies"), join5(dir, "policies"));
|
|
6423
6770
|
try {
|
|
6424
|
-
await snapshotContext(
|
|
6771
|
+
await snapshotContext(join5(original.home, ".gemini"), dir, original.contextNames);
|
|
6425
6772
|
} catch (error) {
|
|
6426
6773
|
if (error.code !== "ENOENT")
|
|
6427
6774
|
throw error;
|
|
6428
6775
|
}
|
|
6429
|
-
const defaults =
|
|
6776
|
+
const defaults = join5(input.stateDir, "gemini-system-defaults.json"), system = join5(input.stateDir, "gemini-system.json"), user = join5(dir, "settings.json");
|
|
6430
6777
|
const modelPolicy = compileGeminiModelPolicy(input.model, input.models, input.compiledPolicy ?? compileModelPolicy(input.model, input.models, input.modelPolicy));
|
|
6431
6778
|
const modelDefinitions = { ...Object.fromEntries(nativeModels.map((id2) => [id2, { isVisible: false }])), ...modelPolicy.modelConfigs.modelDefinitions };
|
|
6432
6779
|
const enforced = { ...original.system, security: { ...original.system.security, auth: { ...original.system.security?.auth, selectedType: "gemini-api-key" } }, model: { ...original.system.model, name: input.model }, modelConfigs: { ...modelPolicy.modelConfigs, modelDefinitions }, agents: { ...original.system.agents, overrides: { ...original.system.agents?.overrides, ...modelPolicy.agents?.overrides } }, experimental: { ...original.system.experimental, dynamicModelConfiguration: true } };
|
|
@@ -6441,7 +6788,7 @@ async function prepareGemini(input) {
|
|
|
6441
6788
|
GEMINI_CLI_HOME: home,
|
|
6442
6789
|
GEMINI_CLI_SYSTEM_SETTINGS_PATH: system,
|
|
6443
6790
|
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: defaults,
|
|
6444
|
-
GEMINI_CLI_TRUSTED_FOLDERS_PATH:
|
|
6791
|
+
GEMINI_CLI_TRUSTED_FOLDERS_PATH: join5(dir, "trustedFolders.json"),
|
|
6445
6792
|
GEMINI_API_KEY: input.credential,
|
|
6446
6793
|
GOOGLE_API_KEY: "",
|
|
6447
6794
|
GOOGLE_GEMINI_BASE_URL: input.baseUrl.replace(/\/v1beta\/?$/i, ""),
|
|
@@ -6679,6 +7026,20 @@ async function isContextOverflow(response) {
|
|
|
6679
7026
|
}
|
|
6680
7027
|
}
|
|
6681
7028
|
|
|
7029
|
+
// src/codex-delegation.ts
|
|
7030
|
+
function normalizeCodexDelegation(body) {
|
|
7031
|
+
if (!Array.isArray(body.input))
|
|
7032
|
+
return body;
|
|
7033
|
+
return { ...body, input: body.input.map((item) => {
|
|
7034
|
+
if (item?.type !== "function_call_output" || item.namespace !== "codex_app" || item.call_id != null)
|
|
7035
|
+
return item;
|
|
7036
|
+
const content = typeof item.output === "string" ? [{ type: "input_text", text: item.output }] : item.output;
|
|
7037
|
+
if (!Array.isArray(content) || !content.length || !content.every((part) => part && (part.type === "input_text" && typeof part.text === "string" || part.type === "input_image" && (typeof part.image_url === "string" || typeof part.file_id === "string"))))
|
|
7038
|
+
throw new Fault(400, "unsupported_task_message_content", "The task message contains content this provider route cannot represent.");
|
|
7039
|
+
return { type: "message", role: "user", content };
|
|
7040
|
+
}) };
|
|
7041
|
+
}
|
|
7042
|
+
|
|
6682
7043
|
// src/inference-gateway.ts
|
|
6683
7044
|
import { createHash as createHash5, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
6684
7045
|
var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
|
|
@@ -6727,6 +7088,9 @@ function createInferenceGateway(input) {
|
|
|
6727
7088
|
}
|
|
6728
7089
|
const requestId = crypto.randomUUID();
|
|
6729
7090
|
const event = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), decision: "reject" };
|
|
7091
|
+
const effort = reasoningEffortSchema.safeParse(body.reasoning?.effort);
|
|
7092
|
+
if (effort.success)
|
|
7093
|
+
event.reasoningEffort = effort.data;
|
|
6730
7094
|
const emit = () => input.onRoutingEvent?.(event);
|
|
6731
7095
|
let resolved;
|
|
6732
7096
|
try {
|
|
@@ -6790,7 +7154,7 @@ function createInferenceGateway(input) {
|
|
|
6790
7154
|
throw new Fault(422, "model_expired", "Selected model has expired.");
|
|
6791
7155
|
if (attempt) {
|
|
6792
7156
|
flush();
|
|
6793
|
-
current = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), resolvedModel: model, decision: "fallback", reason: "explicit_transient_fallback" };
|
|
7157
|
+
current = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), resolvedModel: model, decision: "fallback", reason: "explicit_transient_fallback", ...effort.success ? { reasoningEffort: effort.data } : {} };
|
|
6794
7158
|
}
|
|
6795
7159
|
const payload = structuredClone(body);
|
|
6796
7160
|
if (gemini) {
|
|
@@ -6801,7 +7165,8 @@ function createInferenceGateway(input) {
|
|
|
6801
7165
|
} else
|
|
6802
7166
|
payload.model = model;
|
|
6803
7167
|
const guidance = renderModelGuidance({ harness: input.harness, providerId: input.providerId, baseUrl: input.baseUrl, model, compiled: policy, catalogPath: input.catalogPath });
|
|
6804
|
-
const
|
|
7168
|
+
const compatible2 = input.harness === "codex" && input.protocol === "openai-responses" && new URL(input.baseUrl).hostname !== "api.openai.com" ? normalizeCodexDelegation(payload) : payload;
|
|
7169
|
+
const outgoing = injectModelGuidance(input.protocol, compatible2, guidance, match?.[2]);
|
|
6805
7170
|
const path = gemini ? `/models/${encodeURIComponent(model)}:${match[2]}${url.search}` : suffix + (betaQuery ? "?beta=true" : "");
|
|
6806
7171
|
try {
|
|
6807
7172
|
response = await fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(outgoing), redirect: "manual", signal });
|
|
@@ -6894,8 +7259,8 @@ function createInferenceGateway(input) {
|
|
|
6894
7259
|
}
|
|
6895
7260
|
|
|
6896
7261
|
// src/codex-model-policy.ts
|
|
6897
|
-
import { mkdir as mkdir5, readFile as readFile2, realpath as realpath3, stat as
|
|
6898
|
-
import { dirname as dirname4, isAbsolute as
|
|
7262
|
+
import { mkdir as mkdir5, readFile as readFile2, realpath as realpath3, stat as stat4, writeFile as writeFile4 } from "fs/promises";
|
|
7263
|
+
import { dirname as dirname4, isAbsolute as isAbsolute6, join as join6, resolve as resolve5 } from "path";
|
|
6899
7264
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
6900
7265
|
import { createHash as createHash6 } from "crypto";
|
|
6901
7266
|
var dict = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
@@ -6915,7 +7280,7 @@ function codexAgentsFromEffectiveConfig(config, trustedProject = true, baseDir)
|
|
|
6915
7280
|
const rawConfigFile = value.config_file;
|
|
6916
7281
|
if (rawConfigFile !== undefined && typeof rawConfigFile !== "string")
|
|
6917
7282
|
throw new Error(`Codex agents.${name}.config_file must be a string.`);
|
|
6918
|
-
const configFile = rawConfigFile === undefined ? undefined :
|
|
7283
|
+
const configFile = rawConfigFile === undefined ? undefined : isAbsolute6(rawConfigFile) ? rawConfigFile : baseDir ? resolve5(baseDir, rawConfigFile) : undefined;
|
|
6919
7284
|
if (rawConfigFile !== undefined && !configFile)
|
|
6920
7285
|
throw new Error(`Codex agents.${name}.config_file must be absolute after precedence resolution.`);
|
|
6921
7286
|
const definition = { trusted: trustedProject, config_file: configFile };
|
|
@@ -7044,20 +7409,20 @@ async function writeCodexAgentOverrides(result, stateDir) {
|
|
|
7044
7409
|
const paths = {};
|
|
7045
7410
|
for (const agent of result.agents) {
|
|
7046
7411
|
const digest = createHash6("sha256").update(agent.name).digest("hex").slice(0, 16);
|
|
7047
|
-
const path =
|
|
7412
|
+
const path = join6(root, `agent-${digest}.toml`);
|
|
7048
7413
|
await writeFile4(path, renderCodexAgentToml(agent.config), { encoding: "utf8", mode: 384, flag: "wx" });
|
|
7049
7414
|
paths[agent.name] = path;
|
|
7050
7415
|
}
|
|
7051
7416
|
return paths;
|
|
7052
7417
|
}
|
|
7053
7418
|
async function prepareCodexModelPolicy(input) {
|
|
7054
|
-
const home = resolve5(input.home ?? process.env.CODEX_HOME ??
|
|
7419
|
+
const home = resolve5(input.home ?? process.env.CODEX_HOME ?? join6(process.env.HOME ?? "/", ".codex"));
|
|
7055
7420
|
const cwd = resolve5(input.cwd);
|
|
7056
|
-
const globalPath =
|
|
7421
|
+
const globalPath = join6(home, "config.toml");
|
|
7057
7422
|
const readConfig = async (path) => {
|
|
7058
7423
|
let info;
|
|
7059
7424
|
try {
|
|
7060
|
-
info = await
|
|
7425
|
+
info = await stat4(path);
|
|
7061
7426
|
} catch (error) {
|
|
7062
7427
|
if (error.code === "ENOENT")
|
|
7063
7428
|
return;
|
|
@@ -7077,7 +7442,7 @@ async function prepareCodexModelPolicy(input) {
|
|
|
7077
7442
|
const global = await readConfig(globalPath) ?? {};
|
|
7078
7443
|
const projects = dict(global.projects) ? global.projects : {};
|
|
7079
7444
|
const markers = global.project_root_markers ?? [".git"];
|
|
7080
|
-
if (!Array.isArray(markers) || markers.some((m) => typeof m !== "string" ||
|
|
7445
|
+
if (!Array.isArray(markers) || markers.some((m) => typeof m !== "string" || isAbsolute6(m) || m.includes("..")))
|
|
7081
7446
|
throw new Error("Unsupported Codex project root markers.");
|
|
7082
7447
|
const ancestorDirs = [];
|
|
7083
7448
|
for (let dir = cwd;; dir = dirname4(dir)) {
|
|
@@ -7090,9 +7455,9 @@ async function prepareCodexModelPolicy(input) {
|
|
|
7090
7455
|
for (const dir of ancestorDirs)
|
|
7091
7456
|
for (const marker of markers) {
|
|
7092
7457
|
try {
|
|
7093
|
-
const info = await
|
|
7458
|
+
const info = await stat4(join6(dir, marker));
|
|
7094
7459
|
if (marker === ".git" && info.isDirectory())
|
|
7095
|
-
await
|
|
7460
|
+
await stat4(join6(dir, marker, "HEAD"));
|
|
7096
7461
|
projectRoot = dir;
|
|
7097
7462
|
break findRoot;
|
|
7098
7463
|
} catch {}
|
|
@@ -7117,7 +7482,7 @@ async function prepareCodexModelPolicy(input) {
|
|
|
7117
7482
|
const layers = [{ path: globalPath, config: global }];
|
|
7118
7483
|
const projectDirs = ancestorDirs.slice(0, ancestorDirs.indexOf(projectRoot) + 1).reverse();
|
|
7119
7484
|
for (const dir of projectDirs) {
|
|
7120
|
-
const path =
|
|
7485
|
+
const path = join6(dir, ".codex", "config.toml");
|
|
7121
7486
|
if (path === globalPath)
|
|
7122
7487
|
continue;
|
|
7123
7488
|
const decision = await trust(dir) ?? projectTrust ?? repoTrust;
|
|
@@ -7146,10 +7511,10 @@ async function prepareCodexModelPolicy(input) {
|
|
|
7146
7511
|
return { ...result, agentConfigPaths: await writeCodexAgentOverrides(result, input.stateDir), configPaths: loaded };
|
|
7147
7512
|
}
|
|
7148
7513
|
async function readCodexAgentConfig(path) {
|
|
7149
|
-
if (!
|
|
7514
|
+
if (!isAbsolute6(path))
|
|
7150
7515
|
throw new Error("Codex agent config_file must be absolute before launch.");
|
|
7151
7516
|
const canonical = await realpath3(path);
|
|
7152
|
-
const info = await
|
|
7517
|
+
const info = await stat4(canonical);
|
|
7153
7518
|
if (!info.isFile() || info.size > 1024 * 1024)
|
|
7154
7519
|
throw new Error(`Codex agent config must be a regular file no larger than 1 MiB: ${path}`);
|
|
7155
7520
|
const text = await readFile2(canonical, "utf8");
|
|
@@ -7161,27 +7526,27 @@ async function readCodexAgentConfig(path) {
|
|
|
7161
7526
|
}
|
|
7162
7527
|
|
|
7163
7528
|
// src/harnesses.ts
|
|
7164
|
-
import { access as
|
|
7165
|
-
import { basename as basename2, dirname as dirname7, join as
|
|
7166
|
-
import { homedir as
|
|
7529
|
+
import { access as access3, mkdir as mkdir10, readFile as readFile4, readdir as readdir4, writeFile as writeFile10, rm as rm2 } from "fs/promises";
|
|
7530
|
+
import { basename as basename2, dirname as dirname7, join as join12, isAbsolute as isAbsolute11, resolve as resolve8 } from "path";
|
|
7531
|
+
import { homedir as homedir7, tmpdir } from "os";
|
|
7167
7532
|
import { createHash as createHash8, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual5 } from "crypto";
|
|
7168
|
-
import { execFile } from "child_process";
|
|
7169
|
-
import { promisify } from "util";
|
|
7533
|
+
import { execFile as execFile2 } from "child_process";
|
|
7534
|
+
import { promisify as promisify2 } from "util";
|
|
7170
7535
|
import { createConnection } from "net";
|
|
7171
7536
|
|
|
7172
7537
|
// src/aider-config.ts
|
|
7173
|
-
import { readFile as readFile3, writeFile as writeFile5, lstat as lstat3, copyFile, rename, realpath as realpath4, access } from "fs/promises";
|
|
7174
|
-
import { constants as
|
|
7175
|
-
import { dirname as dirname5, basename, join as
|
|
7176
|
-
import { homedir as
|
|
7538
|
+
import { readFile as readFile3, writeFile as writeFile5, lstat as lstat3, copyFile, rename, realpath as realpath4, access as access2 } from "fs/promises";
|
|
7539
|
+
import { constants as constants3 } from "fs";
|
|
7540
|
+
import { dirname as dirname5, basename, join as join7, resolve as resolve6, isAbsolute as isAbsolute7 } from "path";
|
|
7541
|
+
import { homedir as homedir5 } from "os";
|
|
7177
7542
|
import { parseDocument as parseDocument2 } from "yaml";
|
|
7178
7543
|
var KEY2 = "SWITCHER_HARNESS_API_KEY";
|
|
7179
7544
|
var object3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
7180
7545
|
async function data(path) {
|
|
7181
7546
|
let text;
|
|
7182
7547
|
try {
|
|
7183
|
-
const
|
|
7184
|
-
if (!
|
|
7548
|
+
const stat5 = await lstat3(path);
|
|
7549
|
+
if (!stat5.isFile() || stat5.size > 1024 * 1024)
|
|
7185
7550
|
throw new Error("unsupported");
|
|
7186
7551
|
text = await readFile3(path, "utf8");
|
|
7187
7552
|
} catch (error) {
|
|
@@ -7214,9 +7579,9 @@ async function gitRoot(path) {
|
|
|
7214
7579
|
parent = dirname5(parent);
|
|
7215
7580
|
}
|
|
7216
7581
|
}
|
|
7217
|
-
for (let dir =
|
|
7582
|
+
for (let dir = join7(parent, ...missing);; dir = dirname5(dir)) {
|
|
7218
7583
|
try {
|
|
7219
|
-
await lstat3(
|
|
7584
|
+
await lstat3(join7(dir, ".git"));
|
|
7220
7585
|
return dir;
|
|
7221
7586
|
} catch (error) {
|
|
7222
7587
|
if (!["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
|
|
@@ -7229,9 +7594,9 @@ async function gitRoot(path) {
|
|
|
7229
7594
|
var falseValue = (v) => v === undefined || v === null || v === false || v === 0 || typeof v === "string" && ["", "false", "no", "off", "0"].includes(v.toLowerCase());
|
|
7230
7595
|
var startup = `yes-always gui browser upgrade install-main-branch just-check-update apply-clipboard-edits test lint commit`.split(" ");
|
|
7231
7596
|
var safeParameters = new Set(`max_tokens temperature top_p top_k min_p stop seed reasoning_effort thinking`.split(" "));
|
|
7232
|
-
var expandHome = (path, home) => path === "~" ? home : path.startsWith("~/") ?
|
|
7233
|
-
async function validateAiderConfiguration(cwd, args = [], home = process.env.HOME ??
|
|
7234
|
-
if (!
|
|
7597
|
+
var expandHome = (path, home) => path === "~" ? home : path.startsWith("~/") ? join7(home, path.slice(2)) : path;
|
|
7598
|
+
async function validateAiderConfiguration(cwd, args = [], home = process.env.HOME ?? homedir5()) {
|
|
7599
|
+
if (!isAbsolute7(home))
|
|
7235
7600
|
throw new Error("Aider requires an absolute HOME to preserve native instruction paths.");
|
|
7236
7601
|
const parsed = aiderArguments(args), cwdRoot = await gitRoot(cwd);
|
|
7237
7602
|
const roots = new Set([resolve6(home), ...cwdRoot ? [cwdRoot] : [], resolve6(cwd)]);
|
|
@@ -7242,7 +7607,7 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
7242
7607
|
}
|
|
7243
7608
|
let effective = {};
|
|
7244
7609
|
for (const root of roots) {
|
|
7245
|
-
const path =
|
|
7610
|
+
const path = join7(root, ".aider.conf.yml"), value = await data(path);
|
|
7246
7611
|
if (value !== undefined) {
|
|
7247
7612
|
if (!object3(value))
|
|
7248
7613
|
throw new Error(`Aider configuration must be a mapping: ${path}`);
|
|
@@ -7267,13 +7632,13 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
7267
7632
|
}
|
|
7268
7633
|
effective = { ...effective, ...normalized };
|
|
7269
7634
|
}
|
|
7270
|
-
const settings2 = await data(
|
|
7635
|
+
const settings2 = await data(join7(root, ".aider.model.settings.yml"));
|
|
7271
7636
|
if (settings2 !== undefined) {
|
|
7272
7637
|
if (!Array.isArray(settings2))
|
|
7273
7638
|
throw new Error("Aider model settings must be a list.");
|
|
7274
7639
|
for (const entry of settings2)
|
|
7275
7640
|
if (!object3(entry) || entry.extra_params !== undefined && (!object3(entry.extra_params) || Object.keys(entry.extra_params).some((key) => !safeParameters.has(key))))
|
|
7276
|
-
throw new Error(`Aider custom transport or callback model settings cannot be preserved safely: ${
|
|
7641
|
+
throw new Error(`Aider custom transport or callback model settings cannot be preserved safely: ${join7(root, ".aider.model.settings.yml")}`);
|
|
7277
7642
|
}
|
|
7278
7643
|
}
|
|
7279
7644
|
if (effective.read !== undefined && !(typeof effective.read === "string" || Array.isArray(effective.read) && effective.read.every((v) => typeof v === "string")))
|
|
@@ -7281,7 +7646,7 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
7281
7646
|
const reads = parsed.reads.length ? parsed.reads : typeof effective.read === "string" ? [effective.read] : effective.read ?? [];
|
|
7282
7647
|
for (const path of reads) {
|
|
7283
7648
|
try {
|
|
7284
|
-
await
|
|
7649
|
+
await access2(resolve6(cwd, expandHome(path, home)), constants3.R_OK);
|
|
7285
7650
|
} catch {
|
|
7286
7651
|
throw new Error(`Aider read-only instruction file is not readable: ${path}`);
|
|
7287
7652
|
}
|
|
@@ -7294,8 +7659,8 @@ function aiderModelName(protocol, id2) {
|
|
|
7294
7659
|
return `${protocol === "anthropic-messages" ? "anthropic" : protocol === "openai-responses" ? "openai/responses" : "openai"}/${id2}`;
|
|
7295
7660
|
}
|
|
7296
7661
|
async function historyFile(path) {
|
|
7297
|
-
const
|
|
7298
|
-
if (!
|
|
7662
|
+
const stat5 = await lstat3(path);
|
|
7663
|
+
if (!stat5.isFile() || stat5.isSymbolicLink() || stat5.size > 64 * 1024 * 1024 || process.platform !== "win32" && ((stat5.mode & 63) !== 0 || stat5.uid !== process.getuid?.()))
|
|
7299
7664
|
throw new Error("Aider history must be an owner-only regular file smaller than 64 MiB.");
|
|
7300
7665
|
}
|
|
7301
7666
|
async function prepareAider(input) {
|
|
@@ -7309,7 +7674,7 @@ async function prepareAider(input) {
|
|
|
7309
7674
|
const files = parsed.args.splice(literal2).slice(1);
|
|
7310
7675
|
parsed.args.push(...files.map((path) => resolve6(input.cwd, path)));
|
|
7311
7676
|
}
|
|
7312
|
-
const sourceHome = process.env.HOME ??
|
|
7677
|
+
const sourceHome = process.env.HOME ?? homedir5();
|
|
7313
7678
|
for (let i = 0;i < parsed.args.length; i++) {
|
|
7314
7679
|
if (parsed.args[i] === "--read") {
|
|
7315
7680
|
i++;
|
|
@@ -7317,26 +7682,26 @@ async function prepareAider(input) {
|
|
|
7317
7682
|
} else if (parsed.args[i].startsWith("--read="))
|
|
7318
7683
|
parsed.args[i] = "--read=" + expandHome(parsed.args[i].slice(7), sourceHome);
|
|
7319
7684
|
}
|
|
7320
|
-
const home =
|
|
7685
|
+
const home = join7(input.stateDir, "aider-home");
|
|
7321
7686
|
await privateDirectory(home);
|
|
7322
|
-
const originalHome = process.env.HOME ??
|
|
7323
|
-
const gitSources = process.env.GIT_CONFIG_GLOBAL ? [resolve6(process.env.GIT_CONFIG_GLOBAL)] : [
|
|
7324
|
-
const gitConfig =
|
|
7687
|
+
const originalHome = process.env.HOME ?? homedir5();
|
|
7688
|
+
const gitSources = process.env.GIT_CONFIG_GLOBAL ? [resolve6(process.env.GIT_CONFIG_GLOBAL)] : [join7(process.env.XDG_CONFIG_HOME ?? join7(originalHome, ".config"), "git", "config"), join7(originalHome, ".gitconfig")];
|
|
7689
|
+
const gitConfig = join7(home, ".gitconfig");
|
|
7325
7690
|
await writeFile5(gitConfig, gitSources.map((path) => `[include]
|
|
7326
7691
|
path = ${JSON.stringify(path)}
|
|
7327
7692
|
`).join(""), { mode: 384, flag: "wx" });
|
|
7328
|
-
const sessions = input.sessionDir ??
|
|
7693
|
+
const sessions = input.sessionDir ?? join7(input.stateDir, "sessions");
|
|
7329
7694
|
await privateDirectory(sessions);
|
|
7330
|
-
const id2 = crypto.randomUUID(), history =
|
|
7695
|
+
const id2 = crypto.randomUUID(), history = join7(sessions, `${id2}.chat.md`), inputHistory = join7(sessions, `${id2}.input`);
|
|
7331
7696
|
if (parsed.restore) {
|
|
7332
|
-
const latest =
|
|
7697
|
+
const latest = join7(sessions, "latest.json");
|
|
7333
7698
|
await historyFile(latest).catch(() => {
|
|
7334
7699
|
throw new Error("No valid completed Aider history is available for this profile.");
|
|
7335
7700
|
});
|
|
7336
7701
|
const previous = JSON.parse(await readFile3(latest, "utf8"));
|
|
7337
7702
|
if (!object3(previous) || typeof previous.id !== "string" || !/^[-a-f0-9]{36}$/.test(previous.id))
|
|
7338
7703
|
throw new Error("Invalid Aider history reference.");
|
|
7339
|
-
const source =
|
|
7704
|
+
const source = join7(sessions, `${previous.id}.chat.md`);
|
|
7340
7705
|
await historyFile(source);
|
|
7341
7706
|
await copyFile(source, history, 1);
|
|
7342
7707
|
} else
|
|
@@ -7346,7 +7711,7 @@ async function prepareAider(input) {
|
|
|
7346
7711
|
const model2 = aiderModelName(input.protocol, input.model);
|
|
7347
7712
|
const weakModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.weak ?? input.model), editorModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.editor ?? input.model);
|
|
7348
7713
|
const extra = { api_base: input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl, api_key: `os.environ/${KEY2}` };
|
|
7349
|
-
const settings2 =
|
|
7714
|
+
const settings2 = join7(input.stateDir, "aider-model-settings.json"), metadata = join7(input.stateDir, "aider-model-metadata.json"), config = join7(input.stateDir, "aider-config.json"), empty = join7(input.stateDir, "aider-empty.env");
|
|
7350
7715
|
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 }));
|
|
7351
7716
|
await writeFile5(settings2, JSON.stringify([...definitions, { name: "aider/extra_params", extra_params: extra }]), { mode: 384, flag: "wx" });
|
|
7352
7717
|
await writeFile5(metadata, JSON.stringify(Object.fromEntries(input.models.map((m) => [aiderModelName(input.protocol, m.id), {
|
|
@@ -7365,7 +7730,7 @@ async function prepareAider(input) {
|
|
|
7365
7730
|
return {
|
|
7366
7731
|
executable: input.executable ?? "aider",
|
|
7367
7732
|
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],
|
|
7368
|
-
env: { HOME: home, XDG_CONFIG_HOME:
|
|
7733
|
+
env: { HOME: home, XDG_CONFIG_HOME: join7(home, "config"), XDG_CACHE_HOME: join7(home, "cache"), XDG_DATA_HOME: join7(home, "data"), PYTHON_DOTENV_DISABLED: "1", LITELLM_LOCAL_MODEL_COST_MAP: "True", [KEY2]: input.credential, [input.protocol === "anthropic-messages" ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY"]: input.credential },
|
|
7369
7734
|
configPaths: [config, settings2, metadata, empty, gitConfig],
|
|
7370
7735
|
warnings: [
|
|
7371
7736
|
...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."] : [],
|
|
@@ -7381,9 +7746,9 @@ async function prepareAider(input) {
|
|
|
7381
7746
|
await historyFile(history);
|
|
7382
7747
|
if (!/^#### /m.test((await readFile3(history, "utf8")).slice(originalHistoryLength)))
|
|
7383
7748
|
return;
|
|
7384
|
-
const pending =
|
|
7749
|
+
const pending = join7(sessions, `${id2}.latest.json`);
|
|
7385
7750
|
await writeFile5(pending, JSON.stringify({ id: id2 }), { mode: 384, flag: "wx" });
|
|
7386
|
-
await rename(pending,
|
|
7751
|
+
await rename(pending, join7(sessions, "latest.json"));
|
|
7387
7752
|
}
|
|
7388
7753
|
};
|
|
7389
7754
|
}
|
|
@@ -7467,7 +7832,7 @@ function validateGrokResume(args) {
|
|
|
7467
7832
|
// src/cline-backend.ts
|
|
7468
7833
|
import { mkdir as mkdir6, writeFile as writeFile6 } from "fs/promises";
|
|
7469
7834
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
7470
|
-
import { isAbsolute as
|
|
7835
|
+
import { isAbsolute as isAbsolute8, join as join8 } from "path";
|
|
7471
7836
|
var ENV_BY_PROTOCOL = {
|
|
7472
7837
|
"anthropic-messages": "ANTHROPIC_API_KEY",
|
|
7473
7838
|
"openai-responses": "OPENAI_API_KEY",
|
|
@@ -7513,18 +7878,18 @@ async function prepareClineLaunch(input) {
|
|
|
7513
7878
|
throw new Error(`Cline ${input.protocol} uses ${mapping.authStyle} authentication; use a provider with the native Cline auth contract.`);
|
|
7514
7879
|
if (input.credential && /[\r\n]/.test(input.credential))
|
|
7515
7880
|
throw new Error("Provider credential contains invalid header characters.");
|
|
7516
|
-
if (!
|
|
7881
|
+
if (!isAbsolute8(input.stateDir) || !isAbsolute8(input.cwd))
|
|
7517
7882
|
throw new Error("Launch state and working directories must be absolute.");
|
|
7518
|
-
const dataDir =
|
|
7519
|
-
const sessionDir = input.sessionDir ??
|
|
7520
|
-
const launchDir =
|
|
7521
|
-
const settingsDir =
|
|
7522
|
-
const configDir =
|
|
7883
|
+
const dataDir = join8(input.stateDir, "cline-data");
|
|
7884
|
+
const sessionDir = input.sessionDir ?? join8(dataDir, "sessions");
|
|
7885
|
+
const launchDir = join8(input.stateDir, `cline-launch-${randomUUID2()}`);
|
|
7886
|
+
const settingsDir = join8(launchDir, "settings");
|
|
7887
|
+
const configDir = join8(launchDir, "config");
|
|
7523
7888
|
await mkdir6(settingsDir, { recursive: true, mode: 448 });
|
|
7524
7889
|
await mkdir6(configDir, { recursive: true, mode: 448 });
|
|
7525
7890
|
const baseUrl = endpoint(input.baseUrl);
|
|
7526
7891
|
const providerId = mapping.providerId;
|
|
7527
|
-
const providersPath = await writeJson(
|
|
7892
|
+
const providersPath = await writeJson(join8(settingsDir, "providers.json"), {
|
|
7528
7893
|
version: 1,
|
|
7529
7894
|
lastUsedProvider: providerId,
|
|
7530
7895
|
modes: {},
|
|
@@ -7544,7 +7909,7 @@ async function prepareClineLaunch(input) {
|
|
|
7544
7909
|
}
|
|
7545
7910
|
}
|
|
7546
7911
|
});
|
|
7547
|
-
const modelsPath = await writeJson(
|
|
7912
|
+
const modelsPath = await writeJson(join8(settingsDir, "models.json"), {
|
|
7548
7913
|
version: 1,
|
|
7549
7914
|
providers: {
|
|
7550
7915
|
[providerId]: {
|
|
@@ -7593,17 +7958,17 @@ async function prepareClineLaunch(input) {
|
|
|
7593
7958
|
}
|
|
7594
7959
|
|
|
7595
7960
|
// src/opencode2-config.ts
|
|
7596
|
-
import { mkdir as mkdir7, open as open2, realpath as realpath5, readdir as readdir3, stat as
|
|
7597
|
-
import { constants as
|
|
7598
|
-
import { dirname as dirname6, isAbsolute as
|
|
7599
|
-
import { homedir as
|
|
7961
|
+
import { mkdir as mkdir7, open as open2, realpath as realpath5, readdir as readdir3, stat as stat5, writeFile as writeFile7 } from "fs/promises";
|
|
7962
|
+
import { constants as constants4 } from "fs";
|
|
7963
|
+
import { dirname as dirname6, isAbsolute as isAbsolute9, join as join9, relative as relative4, resolve as resolve7 } from "path";
|
|
7964
|
+
import { homedir as homedir6 } from "os";
|
|
7600
7965
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
7601
7966
|
import { Database as Database2 } from "bun:sqlite";
|
|
7602
7967
|
import { parse as parse3, parseTree as parseTree3 } from "jsonc-parser";
|
|
7603
7968
|
import { parseDocument as parseDocument3 } from "yaml";
|
|
7604
|
-
import { z as
|
|
7605
|
-
var effect =
|
|
7606
|
-
var rule =
|
|
7969
|
+
import { z as z6 } from "zod";
|
|
7970
|
+
var effect = z6.enum(["allow", "deny", "ask"]);
|
|
7971
|
+
var rule = z6.object({ action: z6.string(), resource: z6.string(), effect }).strict();
|
|
7607
7972
|
var object4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
7608
7973
|
var own2 = (value, key) => Object.hasOwn(value, key);
|
|
7609
7974
|
var maxFileBytes2 = 1024 * 1024;
|
|
@@ -7611,7 +7976,7 @@ var maxTotalBytes2 = 8 * 1024 * 1024;
|
|
|
7611
7976
|
var maxFiles2 = 256;
|
|
7612
7977
|
var inside2 = (root, path) => {
|
|
7613
7978
|
const rel = relative4(root, path);
|
|
7614
|
-
return rel === "" || !
|
|
7979
|
+
return rel === "" || !isAbsolute9(rel) && rel !== ".." && !rel.startsWith("../");
|
|
7615
7980
|
};
|
|
7616
7981
|
var action = (value) => ({ bash: "shell", task: "subagent", write: "edit", patch: "edit" })[value] ?? value;
|
|
7617
7982
|
function invalid2(path, field) {
|
|
@@ -7653,7 +8018,7 @@ function permissions(value, path, home) {
|
|
|
7653
8018
|
}
|
|
7654
8019
|
}
|
|
7655
8020
|
if (own2(value, "permissions")) {
|
|
7656
|
-
const parsed =
|
|
8021
|
+
const parsed = z6.array(rule).safeParse(value.permissions);
|
|
7657
8022
|
if (!parsed.success)
|
|
7658
8023
|
invalid2(path, "permissions");
|
|
7659
8024
|
result.push(...parsed.data);
|
|
@@ -7663,7 +8028,7 @@ function permissions(value, path, home) {
|
|
|
7663
8028
|
literal2(item.resource, path, "permission resource");
|
|
7664
8029
|
if (!["read", "edit", "external_directory"].includes(item.action))
|
|
7665
8030
|
return item;
|
|
7666
|
-
const resource = item.resource === "~" || item.resource === "$HOME" ? home : item.resource.startsWith("~/") ?
|
|
8031
|
+
const resource = item.resource === "~" || item.resource === "$HOME" ? home : item.resource.startsWith("~/") ? join9(home, item.resource.slice(2)) : item.resource.startsWith("$HOME/") || item.resource.startsWith("$HOME\\") ? join9(home, item.resource.slice(6)) : item.resource;
|
|
7667
8032
|
return { ...item, resource };
|
|
7668
8033
|
});
|
|
7669
8034
|
}
|
|
@@ -7691,14 +8056,14 @@ function jsonc2(text, path) {
|
|
|
7691
8056
|
return record2(value, path, "configuration object");
|
|
7692
8057
|
}
|
|
7693
8058
|
async function checkRemoteConfiguration(dataHome) {
|
|
7694
|
-
const path =
|
|
7695
|
-
const legacyAuth = await
|
|
8059
|
+
const path = join9(dataHome, "opencode", "opencode.db");
|
|
8060
|
+
const legacyAuth = await stat5(join9(dataHome, "opencode", "auth.json")).then(() => true, (error) => {
|
|
7696
8061
|
if (error.code === "ENOENT")
|
|
7697
8062
|
return false;
|
|
7698
8063
|
throw error;
|
|
7699
8064
|
});
|
|
7700
8065
|
try {
|
|
7701
|
-
await
|
|
8066
|
+
await stat5(path);
|
|
7702
8067
|
} catch (error) {
|
|
7703
8068
|
if (error.code === "ENOENT") {
|
|
7704
8069
|
if (legacyAuth)
|
|
@@ -7732,23 +8097,23 @@ async function checkRemoteConfiguration(dataHome) {
|
|
|
7732
8097
|
}
|
|
7733
8098
|
async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
7734
8099
|
for (const name of ["HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "OPENCODE_CONFIG_DIR"])
|
|
7735
|
-
if (env[name] && !
|
|
8100
|
+
if (env[name] && !isAbsolute9(env[name]))
|
|
7736
8101
|
throw new Error(`OpenCode 2 requires an absolute ${name} to preserve native configuration authority.`);
|
|
7737
|
-
const home = resolve7(env.HOME ||
|
|
7738
|
-
const configRoot = resolve7(env.OPENCODE_CONFIG_DIR ||
|
|
8102
|
+
const home = resolve7(env.HOME || homedir6());
|
|
8103
|
+
const configRoot = resolve7(env.OPENCODE_CONFIG_DIR || join9(env.XDG_CONFIG_HOME || join9(home, ".config"), "opencode"));
|
|
7739
8104
|
const canonicalConfigRoot = await realpath5(configRoot).catch((error) => {
|
|
7740
8105
|
if (error.code === "ENOENT")
|
|
7741
8106
|
return configRoot;
|
|
7742
8107
|
throw error;
|
|
7743
8108
|
});
|
|
7744
|
-
const dataHome = resolve7(env.XDG_DATA_HOME ||
|
|
8109
|
+
const dataHome = resolve7(env.XDG_DATA_HOME || join9(home, ".local", "share"));
|
|
7745
8110
|
await checkRemoteConfiguration(dataHome);
|
|
7746
8111
|
let files = 0, total = 0;
|
|
7747
8112
|
const paths = [];
|
|
7748
8113
|
async function read(path, optional = true) {
|
|
7749
8114
|
let handle;
|
|
7750
8115
|
try {
|
|
7751
|
-
handle = await open2(path,
|
|
8116
|
+
handle = await open2(path, constants4.O_RDONLY | constants4.O_NONBLOCK);
|
|
7752
8117
|
} catch (error) {
|
|
7753
8118
|
if (optional && error.code === "ENOENT")
|
|
7754
8119
|
return;
|
|
@@ -7781,7 +8146,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7781
8146
|
invalid2(path, "agent prompt environment reference");
|
|
7782
8147
|
let result = "", cursor = 0;
|
|
7783
8148
|
for (const match of text.matchAll(/\{file:([^}]+)\}/g)) {
|
|
7784
|
-
const requested = match[1].startsWith("~/") ?
|
|
8149
|
+
const requested = match[1].startsWith("~/") ? join9(home, match[1].slice(2)) : resolve7(dirname6(path), match[1]);
|
|
7785
8150
|
const content = (await read(requested, false)).trim();
|
|
7786
8151
|
literal2(content, requested, "nested prompt variable reference");
|
|
7787
8152
|
result += text.slice(cursor, match.index) + content;
|
|
@@ -7803,7 +8168,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7803
8168
|
}
|
|
7804
8169
|
async function agentsDirectory(directory2) {
|
|
7805
8170
|
for (const source of ["agent", "agents", "mode", "modes"]) {
|
|
7806
|
-
const base =
|
|
8171
|
+
const base = join9(directory2, source), entries = [];
|
|
7807
8172
|
const visited = new Set;
|
|
7808
8173
|
let examined = 0;
|
|
7809
8174
|
async function walk(dir, depth) {
|
|
@@ -7822,8 +8187,8 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7822
8187
|
if (depth > 16 || (examined += names.length) > maxFiles2)
|
|
7823
8188
|
throw new Error("OpenCode 2 agent policy exceeds its bounded directory limit.");
|
|
7824
8189
|
for (const name of names) {
|
|
7825
|
-
const path =
|
|
7826
|
-
const info = await
|
|
8190
|
+
const path = join9(dir, name);
|
|
8191
|
+
const info = await stat5(path);
|
|
7827
8192
|
if (info.isDirectory()) {
|
|
7828
8193
|
if (source === "agent" || source === "agents")
|
|
7829
8194
|
await walk(path, depth + 1);
|
|
@@ -7856,8 +8221,8 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7856
8221
|
}
|
|
7857
8222
|
}
|
|
7858
8223
|
async function directory(path) {
|
|
7859
|
-
await document(
|
|
7860
|
-
await document(
|
|
8224
|
+
await document(join9(path, "opencode.json"));
|
|
8225
|
+
await document(join9(path, "opencode.jsonc"));
|
|
7861
8226
|
await agentsDirectory(path);
|
|
7862
8227
|
}
|
|
7863
8228
|
await directory(configRoot);
|
|
@@ -7872,11 +8237,11 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7872
8237
|
const projectEnabled = !["1", "true"].includes((env.OPENCODE_CONFIG_PROJECT_DISABLE ?? env.OPENCODE_DISABLE_PROJECT_CONFIG ?? "").toLowerCase());
|
|
7873
8238
|
if (projectEnabled) {
|
|
7874
8239
|
for (const path of [...ancestors].reverse()) {
|
|
7875
|
-
await document(
|
|
7876
|
-
await document(
|
|
8240
|
+
await document(join9(path, "opencode.json"));
|
|
8241
|
+
await document(join9(path, "opencode.jsonc"));
|
|
7877
8242
|
}
|
|
7878
8243
|
for (const path of [...ancestors].reverse()) {
|
|
7879
|
-
const candidate =
|
|
8244
|
+
const candidate = join9(path, ".opencode");
|
|
7880
8245
|
const canonical = await realpath5(candidate).catch((error) => {
|
|
7881
8246
|
if (error.code === "ENOENT")
|
|
7882
8247
|
return candidate;
|
|
@@ -7887,7 +8252,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7887
8252
|
}
|
|
7888
8253
|
}
|
|
7889
8254
|
if (env.OPENCODE_CONFIG_CONTENT)
|
|
7890
|
-
documents.push({ path:
|
|
8255
|
+
documents.push({ path: join9(cwd, "OPENCODE_CONFIG_CONTENT"), value: jsonc2(env.OPENCODE_CONFIG_CONTENT, "OPENCODE_CONFIG_CONTENT") });
|
|
7891
8256
|
const policy = [];
|
|
7892
8257
|
const agents = Object.create(null);
|
|
7893
8258
|
let defaultAgent;
|
|
@@ -7898,19 +8263,19 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7898
8263
|
defaultAgent = literal2(string2(value.default_agent, path, "default_agent"), path, "default_agent");
|
|
7899
8264
|
const policies = [];
|
|
7900
8265
|
if (own2(value, "enabled_providers")) {
|
|
7901
|
-
const names =
|
|
8266
|
+
const names = z6.array(z6.string()).safeParse(value.enabled_providers);
|
|
7902
8267
|
if (!names.success)
|
|
7903
8268
|
invalid2(path, "provider policy");
|
|
7904
8269
|
policies.push({ action: "provider.use", resource: "*", effect: "deny" }, ...names.data.map((resource) => ({ action: "provider.use", resource, effect: "allow" })));
|
|
7905
8270
|
}
|
|
7906
8271
|
if (own2(value, "disabled_providers")) {
|
|
7907
|
-
const names =
|
|
8272
|
+
const names = z6.array(z6.string()).safeParse(value.disabled_providers);
|
|
7908
8273
|
if (!names.success)
|
|
7909
8274
|
invalid2(path, "provider policy");
|
|
7910
8275
|
policies.push(...names.data.map((resource) => ({ action: "provider.use", resource, effect: "deny" })));
|
|
7911
8276
|
}
|
|
7912
8277
|
if (object4(value.experimental) && own2(value.experimental, "policies")) {
|
|
7913
|
-
const parsed =
|
|
8278
|
+
const parsed = z6.array(z6.object({ action: z6.literal("provider.use"), resource: z6.string(), effect: z6.enum(["allow", "deny"]) }).strict()).safeParse(value.experimental.policies);
|
|
7914
8279
|
if (!parsed.success)
|
|
7915
8280
|
invalid2(path, "provider policy");
|
|
7916
8281
|
policies.push(...parsed.data);
|
|
@@ -7934,7 +8299,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7934
8299
|
if (own2(item, "description"))
|
|
7935
8300
|
target.description = string2(item.description, path, "agent description");
|
|
7936
8301
|
if (own2(item, "mode")) {
|
|
7937
|
-
const parsed =
|
|
8302
|
+
const parsed = z6.enum(["primary", "subagent", "all"]).safeParse(item.mode);
|
|
7938
8303
|
if (!parsed.success)
|
|
7939
8304
|
invalid2(path, "agent mode");
|
|
7940
8305
|
target.mode = parsed.data;
|
|
@@ -7980,26 +8345,26 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7980
8345
|
instructions.push(`Instructions from: ${path}
|
|
7981
8346
|
${content}`);
|
|
7982
8347
|
}
|
|
7983
|
-
await instruction(
|
|
8348
|
+
await instruction(join9(configRoot, "AGENTS.md"));
|
|
7984
8349
|
if (projectEnabled) {
|
|
7985
8350
|
let stop = resolve7(cwd);
|
|
7986
8351
|
if (inside2(home, resolve7(cwd)))
|
|
7987
8352
|
stop = home;
|
|
7988
8353
|
else
|
|
7989
8354
|
for (const path of ancestors) {
|
|
7990
|
-
if (await
|
|
8355
|
+
if (await stat5(join9(path, ".git")).then(() => true, () => false)) {
|
|
7991
8356
|
stop = path;
|
|
7992
8357
|
break;
|
|
7993
8358
|
}
|
|
7994
8359
|
}
|
|
7995
8360
|
for (const path of ancestors) {
|
|
7996
|
-
await instruction(
|
|
8361
|
+
await instruction(join9(path, "AGENTS.md"));
|
|
7997
8362
|
if (path === stop)
|
|
7998
8363
|
break;
|
|
7999
8364
|
}
|
|
8000
8365
|
}
|
|
8001
|
-
const privateHome =
|
|
8002
|
-
const instructionFile =
|
|
8366
|
+
const privateHome = join9(stateDir, "opencode-home"), privateConfig = join9(stateDir, "opencode-config");
|
|
8367
|
+
const instructionFile = join9(privateConfig, "opencode", "AGENTS.md");
|
|
8003
8368
|
await mkdir7(dirname6(instructionFile), { recursive: true, mode: 448 });
|
|
8004
8369
|
await mkdir7(privateHome, { recursive: true, mode: 448 });
|
|
8005
8370
|
await writeFile7(instructionFile, instructions.join(`
|
|
@@ -8007,7 +8372,7 @@ ${content}`);
|
|
|
8007
8372
|
`), { flag: "wx", mode: 384 });
|
|
8008
8373
|
return {
|
|
8009
8374
|
config: { permissions: policy, agents, ...defaultAgent ? { default_agent: defaultAgent } : {}, experimental: { policies: [{ action: "provider.use", resource: "*", effect: "deny" }, { action: "provider.use", resource: providerID, effect: "allow" }] } },
|
|
8010
|
-
env: { HOME: privateHome, XDG_CONFIG_HOME: privateConfig, OPENCODE_CONFIG_DIR:
|
|
8375
|
+
env: { HOME: privateHome, XDG_CONFIG_HOME: privateConfig, OPENCODE_CONFIG_DIR: join9(privateConfig, "opencode"), XDG_CACHE_HOME: join9(stateDir, "opencode-cache"), XDG_STATE_HOME: join9(stateDir, "opencode-state"), XDG_DATA_HOME: dataHome, OPENCODE_DISABLE_PROJECT_CONFIG: "true", OPENCODE_CONFIG_PROJECT_DISABLE: "true", OPENCODE_DISABLE_MODELS_FETCH: "true" },
|
|
8011
8376
|
instructionFile,
|
|
8012
8377
|
sourcePaths: paths
|
|
8013
8378
|
};
|
|
@@ -8023,7 +8388,7 @@ function openCode2ConfigText(config, providerID, keyEnv) {
|
|
|
8023
8388
|
|
|
8024
8389
|
// src/omp-backend.ts
|
|
8025
8390
|
import { mkdir as mkdir8, rm, writeFile as writeFile8 } from "fs/promises";
|
|
8026
|
-
import { join as
|
|
8391
|
+
import { join as join10 } from "path";
|
|
8027
8392
|
var KEY3 = "SWITCHER_HARNESS_API_KEY";
|
|
8028
8393
|
var API = {
|
|
8029
8394
|
"anthropic-messages": "anthropic-messages",
|
|
@@ -8048,8 +8413,8 @@ async function prepareOmpLaunch(input) {
|
|
|
8048
8413
|
const baseUrl = endpoint(input.baseUrl);
|
|
8049
8414
|
if (input.credential && /[\r\n]/.test(input.credential))
|
|
8050
8415
|
throw new Error("Provider credential contains invalid header characters.");
|
|
8051
|
-
const agentDir =
|
|
8052
|
-
const sessionDir = input.sessionDir ??
|
|
8416
|
+
const agentDir = join10(input.stateDir, "omp-agent");
|
|
8417
|
+
const sessionDir = input.sessionDir ?? join10(input.stateDir, "sessions");
|
|
8053
8418
|
await mkdir8(agentDir, { recursive: true, mode: 448 });
|
|
8054
8419
|
await mkdir8(sessionDir, { recursive: true, mode: 448 });
|
|
8055
8420
|
const api = API[input.protocol];
|
|
@@ -8075,8 +8440,8 @@ async function prepareOmpLaunch(input) {
|
|
|
8075
8440
|
provider.apiKey = KEY3;
|
|
8076
8441
|
provider.authHeader = true;
|
|
8077
8442
|
}
|
|
8078
|
-
const modelsPath =
|
|
8079
|
-
const configPath =
|
|
8443
|
+
const modelsPath = join10(agentDir, "models.yml");
|
|
8444
|
+
const configPath = join10(agentDir, "config.yml");
|
|
8080
8445
|
const selector = `switcher/${input.model}`;
|
|
8081
8446
|
await writeFile8(modelsPath, JSON.stringify({ providers: { switcher: provider } }, null, 2) + `
|
|
8082
8447
|
`, { mode: 384, flag: "wx" });
|
|
@@ -8154,7 +8519,7 @@ function compileHermesModelPolicy(currentModel, roles2, baseUrl, apiMode = "chat
|
|
|
8154
8519
|
// src/hermes-backend.ts
|
|
8155
8520
|
import { createHash as createHash7, timingSafeEqual as timingSafeEqual4 } from "crypto";
|
|
8156
8521
|
import { mkdir as mkdir9, symlink as symlink2, writeFile as writeFile9 } from "fs/promises";
|
|
8157
|
-
import { isAbsolute as
|
|
8522
|
+
import { isAbsolute as isAbsolute10, join as join11 } from "path";
|
|
8158
8523
|
var hermesApiMode = {
|
|
8159
8524
|
"anthropic-messages": "anthropic_messages",
|
|
8160
8525
|
"openai-responses": "codex_responses",
|
|
@@ -8293,7 +8658,7 @@ function createHermesBridge(input) {
|
|
|
8293
8658
|
};
|
|
8294
8659
|
}
|
|
8295
8660
|
async function prepareHermesLaunch(input) {
|
|
8296
|
-
if (!
|
|
8661
|
+
if (!isAbsolute10(input.stateDir) || !isAbsolute10(input.cwd))
|
|
8297
8662
|
throw new Error("Launch state and working directories must be absolute.");
|
|
8298
8663
|
if (input.protocol !== "anthropic-messages" && input.protocol !== "openai-responses" && input.protocol !== "openai-chat")
|
|
8299
8664
|
throw new Error("Hermes does not support this provider protocol.");
|
|
@@ -8303,12 +8668,12 @@ async function prepareHermesLaunch(input) {
|
|
|
8303
8668
|
throw new Error("Hermes cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
8304
8669
|
if (input.credential && /[\r\n]/.test(input.credential))
|
|
8305
8670
|
throw new Error("Provider credential contains invalid header characters.");
|
|
8306
|
-
const sessionDir = input.sessionDir ??
|
|
8307
|
-
const sessionsDir =
|
|
8671
|
+
const sessionDir = input.sessionDir ?? join11(input.stateDir, "hermes-session");
|
|
8672
|
+
const sessionsDir = join11(sessionDir, "sessions");
|
|
8308
8673
|
await mkdir9(input.stateDir, { recursive: true, mode: 448 });
|
|
8309
8674
|
await mkdir9(sessionsDir, { recursive: true, mode: 448 });
|
|
8310
|
-
await symlink2(
|
|
8311
|
-
await symlink2(sessionsDir,
|
|
8675
|
+
await symlink2(join11(sessionDir, "state.db"), join11(input.stateDir, "state.db"));
|
|
8676
|
+
await symlink2(sessionsDir, join11(input.stateDir, "sessions"));
|
|
8312
8677
|
const bridge = createHermesBridge(input);
|
|
8313
8678
|
let policy;
|
|
8314
8679
|
try {
|
|
@@ -8336,7 +8701,7 @@ async function prepareHermesLaunch(input) {
|
|
|
8336
8701
|
}
|
|
8337
8702
|
}
|
|
8338
8703
|
};
|
|
8339
|
-
const configPath =
|
|
8704
|
+
const configPath = join11(input.stateDir, "config.yaml");
|
|
8340
8705
|
try {
|
|
8341
8706
|
await writeFile9(configPath, JSON.stringify(config, null, 2) + `
|
|
8342
8707
|
`, { mode: 384, flag: "wx" });
|
|
@@ -8353,7 +8718,7 @@ async function prepareHermesLaunch(input) {
|
|
|
8353
8718
|
SWITCHER_HERMES_AUX_API_KEY: bridge.token,
|
|
8354
8719
|
OPENAI_API_KEY: bridge.token,
|
|
8355
8720
|
OPENAI_BASE_URL: bridge.baseUrl,
|
|
8356
|
-
CODEX_HOME:
|
|
8721
|
+
CODEX_HOME: join11(input.stateDir, "codex-home")
|
|
8357
8722
|
},
|
|
8358
8723
|
configPaths: [configPath],
|
|
8359
8724
|
warnings: [
|
|
@@ -8491,14 +8856,14 @@ function harnessInstallationMessage(harness, executable, explicitOverride) {
|
|
|
8491
8856
|
}
|
|
8492
8857
|
|
|
8493
8858
|
// src/harnesses.ts
|
|
8494
|
-
var
|
|
8859
|
+
var execute2 = promisify2(execFile2);
|
|
8495
8860
|
var KEY4 = "SWITCHER_HARNESS_API_KEY";
|
|
8496
8861
|
var quote = (value) => JSON.stringify(value);
|
|
8497
8862
|
async function detectHarness(harness, override) {
|
|
8498
8863
|
const executable = override ?? Bun.which(harness) ?? harness;
|
|
8499
8864
|
const installation = harnessInstallation(harness);
|
|
8500
8865
|
try {
|
|
8501
|
-
const { stdout, stderr } = await
|
|
8866
|
+
const { stdout, stderr } = await execute2(executable, ["--version"], { timeout: 8000, maxBuffer: 65536, env: childEnvironment() });
|
|
8502
8867
|
return { harness, executable, available: true, version: (stdout.trim() || stderr.trim()).slice(0, 200), installation };
|
|
8503
8868
|
} catch {
|
|
8504
8869
|
return { harness, executable, available: false, version: undefined, installation };
|
|
@@ -8559,7 +8924,7 @@ function validateHarnessVersion(harness, version) {
|
|
|
8559
8924
|
throw new Error("Gemini CLI 0.58.0 is required by the verified native settings and argument contract.");
|
|
8560
8925
|
}
|
|
8561
8926
|
async function jsonFile(dir, name, value) {
|
|
8562
|
-
const path =
|
|
8927
|
+
const path = join12(dir, name);
|
|
8563
8928
|
await writeFile10(path, JSON.stringify(value, null, 2) + `
|
|
8564
8929
|
`, { mode: 384, flag: "wx" });
|
|
8565
8930
|
return path;
|
|
@@ -8568,8 +8933,8 @@ async function projectInstructionPaths(cwd) {
|
|
|
8568
8933
|
let dir = resolve8(cwd);
|
|
8569
8934
|
while (true) {
|
|
8570
8935
|
for (const name of ["AGENTS.md", "CLAUDE.md", "CONTEXT.md"]) {
|
|
8571
|
-
const path =
|
|
8572
|
-
if (await
|
|
8936
|
+
const path = join12(dir, name);
|
|
8937
|
+
if (await access3(path).then(() => true, () => false))
|
|
8573
8938
|
return [path];
|
|
8574
8939
|
}
|
|
8575
8940
|
const parent = dirname7(dir);
|
|
@@ -8645,7 +9010,7 @@ function expandHomePattern(value) {
|
|
|
8645
9010
|
const record3 = value;
|
|
8646
9011
|
const output = {};
|
|
8647
9012
|
for (const [key, item] of Object.entries(record3)) {
|
|
8648
|
-
const expanded = key === "~" ?
|
|
9013
|
+
const expanded = key === "~" ? homedir7() : key.startsWith("~/") ? join12(homedir7(), key.slice(2)) : key;
|
|
8649
9014
|
output[expanded] = expandHomePattern(item);
|
|
8650
9015
|
}
|
|
8651
9016
|
return output;
|
|
@@ -8721,7 +9086,7 @@ async function agentPolicyFiles(dir, kind) {
|
|
|
8721
9086
|
throw error;
|
|
8722
9087
|
}
|
|
8723
9088
|
for (const entry of entries) {
|
|
8724
|
-
const file =
|
|
9089
|
+
const file = join12(current, entry.name);
|
|
8725
9090
|
if (entry.isDirectory())
|
|
8726
9091
|
await visit(file, root);
|
|
8727
9092
|
else if (entry.isFile() && entry.name.endsWith(".md"))
|
|
@@ -8729,7 +9094,7 @@ async function agentPolicyFiles(dir, kind) {
|
|
|
8729
9094
|
}
|
|
8730
9095
|
};
|
|
8731
9096
|
for (const rootName of [kind, `${kind}s`])
|
|
8732
|
-
await visit(
|
|
9097
|
+
await visit(join12(dir, rootName), join12(dir, rootName));
|
|
8733
9098
|
return result.sort((a, b) => a.file.localeCompare(b.file));
|
|
8734
9099
|
}
|
|
8735
9100
|
async function readAgentPolicyFile(file, kind, root) {
|
|
@@ -8785,9 +9150,9 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
8785
9150
|
result.mode = { ...result.mode ?? {}, [policy.name]: { permission: merged } };
|
|
8786
9151
|
}
|
|
8787
9152
|
};
|
|
8788
|
-
const originalConfig =
|
|
9153
|
+
const originalConfig = join12(process.env.XDG_CONFIG_HOME ?? join12(homedir7(), ".config"), "opencode");
|
|
8789
9154
|
for (const name of ["config.json", "opencode.json", "opencode.jsonc"])
|
|
8790
|
-
await apply(
|
|
9155
|
+
await apply(join12(originalConfig, name));
|
|
8791
9156
|
await applyMarkdown(originalConfig, "agent");
|
|
8792
9157
|
await applyMarkdown(originalConfig, "mode");
|
|
8793
9158
|
if (process.env.OPENCODE_CONFIG)
|
|
@@ -8803,22 +9168,22 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
8803
9168
|
}
|
|
8804
9169
|
for (const current of [...dirs].reverse())
|
|
8805
9170
|
for (const name of ["opencode.jsonc", "opencode.json"])
|
|
8806
|
-
await apply(
|
|
9171
|
+
await apply(join12(current, name));
|
|
8807
9172
|
for (const current of dirs) {
|
|
8808
|
-
const configDir =
|
|
9173
|
+
const configDir = join12(current, ".opencode");
|
|
8809
9174
|
for (const name of ["opencode.json", "opencode.jsonc"])
|
|
8810
|
-
await apply(
|
|
9175
|
+
await apply(join12(configDir, name));
|
|
8811
9176
|
await applyMarkdown(configDir, "agent");
|
|
8812
9177
|
await applyMarkdown(configDir, "mode");
|
|
8813
9178
|
}
|
|
8814
|
-
const homeConfig =
|
|
9179
|
+
const homeConfig = join12(homedir7(), ".opencode");
|
|
8815
9180
|
for (const name of ["opencode.json", "opencode.jsonc"])
|
|
8816
|
-
await apply(
|
|
9181
|
+
await apply(join12(homeConfig, name));
|
|
8817
9182
|
await applyMarkdown(homeConfig, "agent");
|
|
8818
9183
|
await applyMarkdown(homeConfig, "mode");
|
|
8819
9184
|
if (process.env.OPENCODE_CONFIG_DIR) {
|
|
8820
9185
|
for (const name of ["opencode.json", "opencode.jsonc"])
|
|
8821
|
-
await apply(
|
|
9186
|
+
await apply(join12(process.env.OPENCODE_CONFIG_DIR, name));
|
|
8822
9187
|
await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "agent");
|
|
8823
9188
|
await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "mode");
|
|
8824
9189
|
}
|
|
@@ -8838,7 +9203,8 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
8838
9203
|
result.permission = mergePolicyValue(toolsPermission(result.tools, "OpenCode tools policy"), result.permission);
|
|
8839
9204
|
return result;
|
|
8840
9205
|
}
|
|
8841
|
-
function codexModel(model3, priority) {
|
|
9206
|
+
function codexModel(model3, priority, baseUrl = "https://provider.invalid", selectedReasoning) {
|
|
9207
|
+
const reasoning = codexReasoning(model3, baseUrl, selectedReasoning);
|
|
8842
9208
|
return {
|
|
8843
9209
|
slug: model3.id,
|
|
8844
9210
|
display_name: model3.name,
|
|
@@ -8847,8 +9213,8 @@ function codexModel(model3, priority) {
|
|
|
8847
9213
|
visibility: "list",
|
|
8848
9214
|
supported_in_api: true,
|
|
8849
9215
|
priority,
|
|
8850
|
-
supported_reasoning_levels:
|
|
8851
|
-
default_reasoning_level:
|
|
9216
|
+
supported_reasoning_levels: reasoning.levels.map((effort) => ({ effort, description: effort === "none" ? "Disable reasoning" : `${effort} reasoning effort` })),
|
|
9217
|
+
default_reasoning_level: reasoning.defaultEffort,
|
|
8852
9218
|
support_verbosity: false,
|
|
8853
9219
|
supports_reasoning_summary_parameter: false,
|
|
8854
9220
|
default_verbosity: null,
|
|
@@ -8983,20 +9349,20 @@ var PRIME_DAEMON_STARTUP_TIMEOUT_MS = 30000;
|
|
|
8983
9349
|
var PRIME_DAEMON_SHUTDOWN_TIMEOUT_MS = 5000;
|
|
8984
9350
|
function primeSocketPaths(runtimeDir) {
|
|
8985
9351
|
const basename3 = `p-${randomUUID4().replaceAll("-", "").slice(0, 8)}.sock`;
|
|
8986
|
-
const daemonSocket =
|
|
9352
|
+
const daemonSocket = join12(runtimeDir, basename3);
|
|
8987
9353
|
const uid = typeof process.getuid === "function" ? String(process.getuid()) : "user";
|
|
8988
|
-
const workerDir =
|
|
9354
|
+
const workerDir = join12(runtimeDir, `prime-agent-${uid}`);
|
|
8989
9355
|
const workerKey = createHash8("sha256").update(daemonSocket).digest("hex").slice(0, 12);
|
|
8990
|
-
const workerSocket =
|
|
9356
|
+
const workerSocket = join12(workerDir, `worker-${workerKey}-${"x".repeat(12)}.sock`);
|
|
8991
9357
|
const overlong = [daemonSocket, workerSocket].find((path) => Buffer.byteLength(path, "utf8") > PRIME_UNIX_SOCKET_LIMIT);
|
|
8992
|
-
return { daemonSocket, runtimeDir, workerDir, workerPrefix:
|
|
9358
|
+
return { daemonSocket, runtimeDir, workerDir, workerPrefix: join12(workerDir, `worker-${workerKey}-`), overlong };
|
|
8993
9359
|
}
|
|
8994
9360
|
async function primeSocketInfo() {
|
|
8995
9361
|
const requested = tmpdir();
|
|
8996
9362
|
const direct = primeSocketPaths(requested);
|
|
8997
9363
|
if (!direct.overlong)
|
|
8998
9364
|
return direct;
|
|
8999
|
-
const fallback =
|
|
9365
|
+
const fallback = join12(switcherHome(), "r");
|
|
9000
9366
|
await privateDirectory(switcherHome());
|
|
9001
9367
|
await privateDirectory(fallback);
|
|
9002
9368
|
const scoped = primeSocketPaths(fallback);
|
|
@@ -9093,7 +9459,7 @@ async function primeStartSupervisor(input, executable, socketPath, env, onSpawn)
|
|
|
9093
9459
|
}
|
|
9094
9460
|
}
|
|
9095
9461
|
async function primeOwnedShutdown(socketPath, workerPrefix) {
|
|
9096
|
-
const exists = () =>
|
|
9462
|
+
const exists = () => access3(socketPath).then(() => true, () => false);
|
|
9097
9463
|
const workerEntries = () => readdir4(workerPrefix.slice(0, workerPrefix.lastIndexOf("/"))).then((entries) => entries.filter((entry) => entry.startsWith(workerPrefix.slice(workerPrefix.lastIndexOf("/") + 1))), () => []);
|
|
9098
9464
|
if (!await exists())
|
|
9099
9465
|
throw new Error(`Prime Agent owned daemon socket disappeared before cleanup (${socketPath}).`);
|
|
@@ -9173,11 +9539,11 @@ async function primeWaitExit(supervisor, timeout) {
|
|
|
9173
9539
|
return await Promise.race([supervisor.exited.then(() => true), new Promise((resolve9) => setTimeout(() => resolve9(false), timeout))]);
|
|
9174
9540
|
}
|
|
9175
9541
|
async function primeRemainingSockets(socketPath, workerPrefix) {
|
|
9176
|
-
const daemon = await
|
|
9542
|
+
const daemon = await access3(socketPath).then(() => true, () => false);
|
|
9177
9543
|
const workerDir = workerPrefix.slice(0, workerPrefix.lastIndexOf("/"));
|
|
9178
9544
|
const prefix = workerPrefix.slice(workerPrefix.lastIndexOf("/") + 1);
|
|
9179
9545
|
const workers = await readdir4(workerDir).then((entries) => entries.filter((entry) => entry.startsWith(prefix)), () => []);
|
|
9180
|
-
return [...daemon ? [socketPath] : [], ...workers.map((entry) =>
|
|
9546
|
+
return [...daemon ? [socketPath] : [], ...workers.map((entry) => join12(workerDir, entry))];
|
|
9181
9547
|
}
|
|
9182
9548
|
function primeModel(input, api) {
|
|
9183
9549
|
return input.models.map((model3) => ({
|
|
@@ -9195,7 +9561,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9195
9561
|
if (!compatible(input.harness, input.protocol))
|
|
9196
9562
|
throw new Error("Harness and provider protocol are incompatible.");
|
|
9197
9563
|
validateHarnessVersion(input.harness, input.version);
|
|
9198
|
-
if (!
|
|
9564
|
+
if (!isAbsolute11(input.stateDir) || !isAbsolute11(input.cwd))
|
|
9199
9565
|
throw new Error("Launch state and working directories must be absolute.");
|
|
9200
9566
|
if (!input.models.length || !input.models.some((m) => m.id === input.model))
|
|
9201
9567
|
throw new Error("Selected model is missing from the launch catalog.");
|
|
@@ -9233,7 +9599,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9233
9599
|
}
|
|
9234
9600
|
if (input.harness === "codex") {
|
|
9235
9601
|
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 });
|
|
9236
|
-
const file2 = await jsonFile(input.stateDir, "codex-models.json", { models: input.models.map(codexModel) });
|
|
9602
|
+
const file2 = await jsonFile(input.stateDir, "codex-models.json", { models: input.models.map((model3, index) => codexModel(model3, index, providerBaseUrl, model3.id === input.model ? input.reasoning : undefined)) });
|
|
9237
9603
|
configPaths.push(file2);
|
|
9238
9604
|
configPaths.push(...Object.values(rolePolicy2.agentConfigPaths));
|
|
9239
9605
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
@@ -9252,7 +9618,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9252
9618
|
overrides.push("-c", `agents.${name}.config_file=${quote(path)}`);
|
|
9253
9619
|
}
|
|
9254
9620
|
overrides.push("-c", `memories.extract_model=${quote(input.model)}`, "-c", `memories.consolidation_model=${quote(input.model)}`);
|
|
9255
|
-
|
|
9621
|
+
if (input.reasoning)
|
|
9622
|
+
overrides.push("-c", `model_reasoning_effort=${quote(input.reasoning)}`);
|
|
9623
|
+
if (input.dangerouslyBypassApprovalsAndSandbox)
|
|
9624
|
+
overrides.push("-c", 'approval_policy="never"', "-c", 'sandbox_mode="danger-full-access"');
|
|
9625
|
+
warnings.push("Codex catalog uses conservative generic tool metadata and a model-neutral coding prompt; reasoning controls come from declared capabilities, documented provider support or an explicit --reasoning selection.");
|
|
9626
|
+
if (input.dangerouslyBypassApprovalsAndSandbox)
|
|
9627
|
+
warnings.push("Full access: approval prompts and command sandboxing are disabled for this launch.");
|
|
9256
9628
|
return { executable, args: [...overrides, ...args], env, configPaths, warnings };
|
|
9257
9629
|
}
|
|
9258
9630
|
if (input.harness === "grok") {
|
|
@@ -9276,8 +9648,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9276
9648
|
throw new Error("Pi cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
9277
9649
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions", "gemini-generate-content": "gemini" }[input.protocol];
|
|
9278
9650
|
const providerId = piProviderId(input, providerBaseUrl);
|
|
9279
|
-
const agentDir =
|
|
9280
|
-
const sessionDir = input.sessionDir ??
|
|
9651
|
+
const agentDir = join12(input.stateDir, "pi-agent");
|
|
9652
|
+
const sessionDir = input.sessionDir ?? join12(input.stateDir, "sessions");
|
|
9281
9653
|
const piBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
|
|
9282
9654
|
await mkdir10(agentDir, { recursive: true, mode: 448 });
|
|
9283
9655
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
@@ -9302,9 +9674,9 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9302
9674
|
const selected = dshArguments(args);
|
|
9303
9675
|
const providerId = piProviderId(input, providerBaseUrl);
|
|
9304
9676
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
|
|
9305
|
-
const home =
|
|
9306
|
-
const sessionDir = input.sessionDir ??
|
|
9307
|
-
if (!
|
|
9677
|
+
const home = join12(input.stateDir, "dsh-home");
|
|
9678
|
+
const sessionDir = input.sessionDir ?? join12(input.stateDir, "dsh-state");
|
|
9679
|
+
if (!isAbsolute11(sessionDir))
|
|
9308
9680
|
throw new Error("DSH session directory must be absolute.");
|
|
9309
9681
|
await mkdir10(home, { recursive: true, mode: 448 });
|
|
9310
9682
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
@@ -9325,7 +9697,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9325
9697
|
}))
|
|
9326
9698
|
} } } },
|
|
9327
9699
|
{ id: "agent-default-model", config: route2 },
|
|
9328
|
-
{ id: "session-persistence-jsonl", config: { root:
|
|
9700
|
+
{ id: "session-persistence-jsonl", config: { root: join12(sessionDir, "sessions") } },
|
|
9329
9701
|
{ id: "attachment-local", config: { dshHome: sessionDir } },
|
|
9330
9702
|
...selected.profile === "acp" ? [{ id: "acp", config: route2 }] : []
|
|
9331
9703
|
];
|
|
@@ -9351,14 +9723,14 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9351
9723
|
throw new Error("Prime Agent cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
9352
9724
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
|
|
9353
9725
|
const providerId = primeProviderId(input, providerBaseUrl);
|
|
9354
|
-
const sessionDir = input.sessionDir ??
|
|
9355
|
-
const agentDir =
|
|
9726
|
+
const sessionDir = input.sessionDir ?? join12(input.stateDir, "sessions");
|
|
9727
|
+
const agentDir = join12(input.stateDir, "prime-agent");
|
|
9356
9728
|
const socketInfo = await primeSocketInfo();
|
|
9357
9729
|
const { daemonSocket, runtimeDir, workerPrefix } = socketInfo;
|
|
9358
9730
|
const primeBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
|
|
9359
9731
|
await mkdir10(agentDir, { recursive: true, mode: 448 });
|
|
9360
9732
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
9361
|
-
const file2 =
|
|
9733
|
+
const file2 = join12(agentDir, "models.json");
|
|
9362
9734
|
await writeFile10(file2, JSON.stringify({ providers: { [providerId]: {
|
|
9363
9735
|
name: "Switcher",
|
|
9364
9736
|
baseUrl: primeBaseUrl,
|
|
@@ -9450,13 +9822,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9450
9822
|
const file2 = await jsonFile(input.stateDir, "opencode-legacy.json", config2);
|
|
9451
9823
|
configPaths.push(file2);
|
|
9452
9824
|
env.OPENCODE_CONFIG = file2;
|
|
9453
|
-
const sessionDir = input.sessionDir ??
|
|
9825
|
+
const sessionDir = input.sessionDir ?? join12(input.stateDir, "sessions");
|
|
9454
9826
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
9455
|
-
env.XDG_DATA_HOME =
|
|
9456
|
-
env.XDG_CONFIG_HOME =
|
|
9457
|
-
env.XDG_CACHE_HOME =
|
|
9458
|
-
env.XDG_STATE_HOME =
|
|
9459
|
-
env.HOME =
|
|
9827
|
+
env.XDG_DATA_HOME = join12(sessionDir, "data");
|
|
9828
|
+
env.XDG_CONFIG_HOME = join12(input.stateDir, "config");
|
|
9829
|
+
env.XDG_CACHE_HOME = join12(input.stateDir, "cache");
|
|
9830
|
+
env.XDG_STATE_HOME = join12(input.stateDir, "state");
|
|
9831
|
+
env.HOME = join12(input.stateDir, "home");
|
|
9460
9832
|
env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";
|
|
9461
9833
|
env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config2);
|
|
9462
9834
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
@@ -9480,7 +9852,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9480
9852
|
const rolePolicy = compileOpenCodeModelPolicy({ providerId: providerID, mainModel: input.model, roles: input.compiledPolicy?.roles, preservedAgents: Object.entries(isolated.config.agents ?? {}).map(([name, agent]) => ({ ...agent, name })) });
|
|
9481
9853
|
const modelRef = openCodeInvocationModel(args, rolePolicy, isolated.config.default_agent);
|
|
9482
9854
|
const config = { ...isolated.config, ...rolePolicy.config, providers: { [providerID]: { name: "Switcher", env: [KEY4], package: `@opencode-ai/ai/providers/${packageName}`, settings: settings2, models } } };
|
|
9483
|
-
const file =
|
|
9855
|
+
const file = join12(input.stateDir, "opencode.json");
|
|
9484
9856
|
await writeFile10(file, openCode2ConfigText(config, providerID, KEY4), { mode: 384, flag: "wx" });
|
|
9485
9857
|
configPaths.push(file, isolated.instructionFile);
|
|
9486
9858
|
Object.assign(env, isolated.env);
|
|
@@ -9565,7 +9937,7 @@ async function prepareHarnessLaunch(input) {
|
|
|
9565
9937
|
validateHarnessVersion(input.harness, input.version);
|
|
9566
9938
|
if (!compatible(input.harness, input.protocol))
|
|
9567
9939
|
throw new Error("Harness and provider protocol are incompatible.");
|
|
9568
|
-
if (!
|
|
9940
|
+
if (!isAbsolute11(input.stateDir) || !isAbsolute11(input.cwd))
|
|
9569
9941
|
throw new Error("Launch state and working directories must be absolute.");
|
|
9570
9942
|
const compiledPolicy = compileModelPolicy(input.model, input.models, input.modelPolicy);
|
|
9571
9943
|
input = { ...input, models: input.models.filter((model3) => !modelExpired(model3)) };
|
|
@@ -9596,9 +9968,9 @@ async function prepareHarnessLaunch(input) {
|
|
|
9596
9968
|
}
|
|
9597
9969
|
|
|
9598
9970
|
// src/ori-model-policy.ts
|
|
9599
|
-
import { isAbsolute as
|
|
9971
|
+
import { isAbsolute as isAbsolute12 } from "path";
|
|
9600
9972
|
function prepareOriModelPolicy(target, prepared) {
|
|
9601
|
-
if (!
|
|
9973
|
+
if (!isAbsolute12(prepared.executable) || /[\0\r\n]/.test(prepared.executable))
|
|
9602
9974
|
throw new Error("Ori requires an absolute verified native executable.");
|
|
9603
9975
|
const entries = Object.entries(prepared.env);
|
|
9604
9976
|
if (entries.some(([key]) => !/^[A-Z_][A-Z0-9_]*$/.test(key)))
|
|
@@ -9622,13 +9994,13 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
|
|
|
9622
9994
|
}
|
|
9623
9995
|
|
|
9624
9996
|
// src/launcher.ts
|
|
9625
|
-
import { mkdir as mkdir11, mkdtemp, rm as
|
|
9626
|
-
import { join as
|
|
9997
|
+
import { mkdir as mkdir11, mkdtemp, rm as rm6, writeFile as writeFile14 } from "fs/promises";
|
|
9998
|
+
import { join as join15, resolve as resolve9 } from "path";
|
|
9627
9999
|
|
|
9628
10000
|
// src/harness-process.ts
|
|
9629
10001
|
import { spawn, spawnSync } from "child_process";
|
|
9630
10002
|
import { EventEmitter } from "events";
|
|
9631
|
-
import { existsSync, openSync, closeSync, writeSync, readSync, constants as
|
|
10003
|
+
import { existsSync, openSync, closeSync, writeSync, readSync, constants as constants5 } from "fs";
|
|
9632
10004
|
|
|
9633
10005
|
// src/terminal-descriptors.ts
|
|
9634
10006
|
async function terminalDescriptorDuplicator() {
|
|
@@ -9651,7 +10023,7 @@ async function terminalDescriptorDuplicator() {
|
|
|
9651
10023
|
// src/harness-process.ts
|
|
9652
10024
|
async function runHarnessProcess(options) {
|
|
9653
10025
|
const tty = [Boolean(process.stdin.isTTY), Boolean(process.stdout.isTTY), Boolean(process.stderr.isTTY)];
|
|
9654
|
-
const grouped = process.platform !== "win32", interactive = grouped && tty.some(Boolean);
|
|
10026
|
+
const grouped = process.platform !== "win32", interactive = !options.silent && grouped && tty.some(Boolean);
|
|
9655
10027
|
const redirects = interactive ? tty.flatMap((value, index) => value ? [] : [index]) : [];
|
|
9656
10028
|
const duplicator = redirects.length ? await terminalDescriptorDuplicator() : undefined;
|
|
9657
10029
|
return new Promise((resolveResult, reject2) => {
|
|
@@ -9678,7 +10050,7 @@ async function runHarnessProcess(options) {
|
|
|
9678
10050
|
let resize;
|
|
9679
10051
|
const child = (() => {
|
|
9680
10052
|
if (!interactive)
|
|
9681
|
-
return spawn(options.executable, options.args, { cwd: options.cwd, env: options.env, stdio: "inherit", shell: false, detached: grouped });
|
|
10053
|
+
return spawn(options.executable, options.args, { cwd: options.cwd, env: options.env, stdio: options.silent ? "ignore" : "inherit", shell: false, detached: grouped });
|
|
9682
10054
|
const duplicates = [];
|
|
9683
10055
|
let native;
|
|
9684
10056
|
try {
|
|
@@ -9884,7 +10256,7 @@ async function runHarnessProcess(options) {
|
|
|
9884
10256
|
process.stdin.on("data", relay);
|
|
9885
10257
|
process.stdin.resume();
|
|
9886
10258
|
} else {
|
|
9887
|
-
controllingInput = openSync("/dev/tty",
|
|
10259
|
+
controllingInput = openSync("/dev/tty", constants5.O_RDONLY | constants5.O_NONBLOCK);
|
|
9888
10260
|
stty(["raw", "-echo"]);
|
|
9889
10261
|
const buffer = Buffer.alloc(4096);
|
|
9890
10262
|
inputTimer = setInterval(() => {
|
|
@@ -9915,9 +10287,9 @@ async function runHarnessProcess(options) {
|
|
|
9915
10287
|
}
|
|
9916
10288
|
|
|
9917
10289
|
// src/ori-backend.ts
|
|
9918
|
-
import { execFile as
|
|
9919
|
-
import { promisify as
|
|
9920
|
-
var exec =
|
|
10290
|
+
import { execFile as execFile3 } from "child_process";
|
|
10291
|
+
import { promisify as promisify3 } from "util";
|
|
10292
|
+
var exec = promisify3(execFile3);
|
|
9921
10293
|
var oriProviderCatalog = Object.freeze([{
|
|
9922
10294
|
id: "openrouter",
|
|
9923
10295
|
displayName: "OpenRouter",
|
|
@@ -10149,12 +10521,289 @@ function oriLaunchWarnings(target) {
|
|
|
10149
10521
|
return target === "grok" ? ["Ori supplies Grok's account-entitled OpenRouter catalog; it is not the Switcher-filtered catalog snapshot."] : [];
|
|
10150
10522
|
}
|
|
10151
10523
|
|
|
10524
|
+
// src/chatgpt-launch.ts
|
|
10525
|
+
import { createHash as createHash9 } from "crypto";
|
|
10526
|
+
import { writeFile as writeFile12, rm as rm4 } from "fs/promises";
|
|
10527
|
+
import { join as join13 } from "path";
|
|
10528
|
+
|
|
10529
|
+
// src/desktop-state.ts
|
|
10530
|
+
import { Database as Database3 } from "bun:sqlite";
|
|
10531
|
+
import { readFile as readFile5, writeFile as writeFile11, rm as rm3, lstat as lstat4, rename as rename2, chmod as chmod2 } from "fs/promises";
|
|
10532
|
+
async function safeDesktopRead(path) {
|
|
10533
|
+
try {
|
|
10534
|
+
const info = await lstat4(path);
|
|
10535
|
+
if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
|
|
10536
|
+
throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user.");
|
|
10537
|
+
return await readFile5(path, "utf8");
|
|
10538
|
+
} catch (error) {
|
|
10539
|
+
if (error.code === "ENOENT")
|
|
10540
|
+
return;
|
|
10541
|
+
throw error;
|
|
10542
|
+
}
|
|
10543
|
+
}
|
|
10544
|
+
async function writeDesktopPrivate(path, text) {
|
|
10545
|
+
const temporary = path + "." + crypto.randomUUID() + ".tmp";
|
|
10546
|
+
try {
|
|
10547
|
+
await writeFile11(temporary, text, { mode: 384, flag: "wx" });
|
|
10548
|
+
await rename2(temporary, path);
|
|
10549
|
+
} finally {
|
|
10550
|
+
await rm3(temporary, { force: true });
|
|
10551
|
+
}
|
|
10552
|
+
}
|
|
10553
|
+
async function desktopLease(path) {
|
|
10554
|
+
try {
|
|
10555
|
+
const info = await lstat4(path);
|
|
10556
|
+
if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
|
|
10557
|
+
throw new Fault(422, "desktop_state_permissions", "Desktop lease must be a regular file owned by this user.");
|
|
10558
|
+
} catch (error) {
|
|
10559
|
+
if (error.code !== "ENOENT")
|
|
10560
|
+
throw error;
|
|
10561
|
+
}
|
|
10562
|
+
const lease = new Database3(path);
|
|
10563
|
+
try {
|
|
10564
|
+
await chmod2(path, 384);
|
|
10565
|
+
lease.exec("PRAGMA busy_timeout=0; CREATE TABLE IF NOT EXISTS lease (id INTEGER PRIMARY KEY); BEGIN EXCLUSIVE;");
|
|
10566
|
+
} catch {
|
|
10567
|
+
lease.close();
|
|
10568
|
+
throw new Fault(409, "desktop_busy", "This desktop provider profile is already running. Quit that instance before launching it again.");
|
|
10569
|
+
}
|
|
10570
|
+
let closed = false;
|
|
10571
|
+
return () => {
|
|
10572
|
+
if (!closed) {
|
|
10573
|
+
closed = true;
|
|
10574
|
+
lease.close();
|
|
10575
|
+
}
|
|
10576
|
+
};
|
|
10577
|
+
}
|
|
10578
|
+
|
|
10579
|
+
// src/chatgpt-launch.ts
|
|
10580
|
+
var object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
10581
|
+
function merge2(base, overlay) {
|
|
10582
|
+
const result = { ...base };
|
|
10583
|
+
for (const [key, value] of Object.entries(overlay))
|
|
10584
|
+
result[key] = object5(value) && object5(result[key]) ? merge2(result[key], value) : value;
|
|
10585
|
+
return result;
|
|
10586
|
+
}
|
|
10587
|
+
var digest = (value) => createHash9("sha256").update(value).digest("hex");
|
|
10588
|
+
var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
10589
|
+
async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
10590
|
+
await privateDirectory(sessionDir);
|
|
10591
|
+
const home = join13(sessionDir, "codex"), userData = join13(sessionDir, "electron");
|
|
10592
|
+
await privateDirectory(home);
|
|
10593
|
+
await privateDirectory(userData);
|
|
10594
|
+
const release = await desktopLease(join13(sessionDir, "launch.sqlite"));
|
|
10595
|
+
let released = false, authText;
|
|
10596
|
+
const authPath = join13(home, "auth.json"), receiptPath = join13(home, ".switcher-auth.sha256");
|
|
10597
|
+
const cleanup = async () => {
|
|
10598
|
+
if (released)
|
|
10599
|
+
return;
|
|
10600
|
+
released = true;
|
|
10601
|
+
try {
|
|
10602
|
+
if (authText !== undefined && await safeDesktopRead(authPath) === authText) {
|
|
10603
|
+
await rm4(authPath, { force: true });
|
|
10604
|
+
await rm4(receiptPath, { force: true });
|
|
10605
|
+
}
|
|
10606
|
+
} finally {
|
|
10607
|
+
release();
|
|
10608
|
+
}
|
|
10609
|
+
};
|
|
10610
|
+
try {
|
|
10611
|
+
const settings2 = [];
|
|
10612
|
+
for (let i = 0;i < native.args.length; i += 2) {
|
|
10613
|
+
if (native.args[i] !== "-c" || typeof native.args[i + 1] !== "string")
|
|
10614
|
+
throw new Fault(400, "desktop_arguments", "Desktop launches accept provider/model settings, not native CLI commands.");
|
|
10615
|
+
settings2.push(native.args[i + 1]);
|
|
10616
|
+
}
|
|
10617
|
+
settings2.push('cli_auth_credentials_store="file"', 'forced_login_method="api"');
|
|
10618
|
+
if (!settings2.some((setting) => setting.startsWith("approval_policy=")))
|
|
10619
|
+
settings2.push('approval_policy="on-request"');
|
|
10620
|
+
if (!settings2.some((setting) => setting.startsWith("sandbox_mode=")))
|
|
10621
|
+
settings2.push('sandbox_mode="workspace-write"');
|
|
10622
|
+
const configPath = join13(home, "config.toml");
|
|
10623
|
+
const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
|
|
10624
|
+
if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
|
|
10625
|
+
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.");
|
|
10626
|
+
let existing = {};
|
|
10627
|
+
try {
|
|
10628
|
+
existing = Bun.TOML.parse(await safeDesktopRead(configPath) ?? "");
|
|
10629
|
+
} catch (error) {
|
|
10630
|
+
if (error.code !== "ENOENT")
|
|
10631
|
+
throw new Fault(422, "desktop_config_invalid", "The desktop profile config cannot be read safely.");
|
|
10632
|
+
}
|
|
10633
|
+
const config = merge2(existing, Bun.TOML.parse(settings2.join(`
|
|
10634
|
+
`)));
|
|
10635
|
+
await writeDesktopPrivate(configPath, renderCodexAgentToml(config));
|
|
10636
|
+
const key = native.env.SWITCHER_HARNESS_API_KEY;
|
|
10637
|
+
if (!key)
|
|
10638
|
+
throw new Fault(500, "desktop_auth_missing", "Desktop preparation did not receive a scoped gateway credential.");
|
|
10639
|
+
authText = JSON.stringify({ OPENAI_API_KEY: key }) + `
|
|
10640
|
+
`;
|
|
10641
|
+
await writeDesktopPrivate(receiptPath, digest(authText));
|
|
10642
|
+
await writeDesktopPrivate(authPath, authText);
|
|
10643
|
+
const wrapper = join13(stateDir, "chatgpt-codex");
|
|
10644
|
+
const overrides = settings2.flatMap((setting) => ["-c", setting]);
|
|
10645
|
+
await writeFile12(wrapper, `#!/bin/sh
|
|
10646
|
+
set -eu
|
|
10647
|
+
unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
|
|
10648
|
+
export CODEX_HOME=${quote2(home)}
|
|
10649
|
+
exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
|
|
10650
|
+
`, { mode: 448, flag: "wx" });
|
|
10651
|
+
return {
|
|
10652
|
+
...native,
|
|
10653
|
+
executable: app.executable,
|
|
10654
|
+
args: [`--user-data-dir=${userData}`],
|
|
10655
|
+
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" },
|
|
10656
|
+
configPaths: [...native.configPaths, configPath, wrapper],
|
|
10657
|
+
warnings: [...native.warnings, `ChatGPT provider profile: ${sessionDir}. Local Codex conversations use this provider; ChatGPT cloud Chat/Work and account-only features are not redirected. Keep Switcher running until you quit this app instance.`],
|
|
10658
|
+
cleanup: async () => {
|
|
10659
|
+
try {
|
|
10660
|
+
await native.cleanup?.();
|
|
10661
|
+
} finally {
|
|
10662
|
+
await cleanup();
|
|
10663
|
+
}
|
|
10664
|
+
}
|
|
10665
|
+
};
|
|
10666
|
+
} catch (error) {
|
|
10667
|
+
await cleanup();
|
|
10668
|
+
throw error;
|
|
10669
|
+
}
|
|
10670
|
+
}
|
|
10671
|
+
|
|
10672
|
+
// src/claude-desktop-launch.ts
|
|
10673
|
+
import { createHash as createHash10 } from "crypto";
|
|
10674
|
+
import { execFile as execFile4 } from "child_process";
|
|
10675
|
+
import { access as access4, rm as rm5, writeFile as writeFile13 } from "fs/promises";
|
|
10676
|
+
import { homedir as homedir8, userInfo as userInfo2 } from "os";
|
|
10677
|
+
import { join as join14 } from "path";
|
|
10678
|
+
import { promisify as promisify4 } from "util";
|
|
10679
|
+
var execute3 = promisify4(execFile4);
|
|
10680
|
+
var hash2 = (text) => createHash10("sha256").update(text).digest("hex");
|
|
10681
|
+
var claudeDesktopDataDirectory = () => join14(homedir8(), "Library/Application Support/Claude-3p");
|
|
10682
|
+
async function assertAvailable(userData) {
|
|
10683
|
+
for (const path of [join14("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
|
|
10684
|
+
if (await access4(path).then(() => true, () => false))
|
|
10685
|
+
throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
|
|
10686
|
+
let openFiles;
|
|
10687
|
+
try {
|
|
10688
|
+
openFiles = (await execute3("/usr/sbin/lsof", ["-n", "-P", "-Fpn", "-a", "-u", String(process.getuid?.()), "-c", "Claude"], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, timeout: 8000 })).stdout;
|
|
10689
|
+
} catch (error) {
|
|
10690
|
+
if (error.code === 1)
|
|
10691
|
+
return;
|
|
10692
|
+
throw new Fault(409, "desktop_process_check", "Could not check whether Claude's third-party profile is already running.");
|
|
10693
|
+
}
|
|
10694
|
+
if (openFiles.split(`
|
|
10695
|
+
`).some((line) => line.startsWith("n" + userData + "/")))
|
|
10696
|
+
throw new Fault(409, "desktop_busy", "Claude's third-party instance is already running. Quit that instance before changing its provider; the normal Claude instance can stay open.");
|
|
10697
|
+
}
|
|
10698
|
+
function metadata(text) {
|
|
10699
|
+
const value = text === undefined ? { entries: [] } : JSON.parse(text);
|
|
10700
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((item) => !item || typeof item !== "object" || Array.isArray(item)))
|
|
10701
|
+
throw new Fault(422, "desktop_config_invalid", "Claude's configuration library metadata is invalid.");
|
|
10702
|
+
return value;
|
|
10703
|
+
}
|
|
10704
|
+
async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
10705
|
+
if (input.harness !== "claude")
|
|
10706
|
+
throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
|
|
10707
|
+
validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
|
|
10708
|
+
if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
|
|
10709
|
+
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.");
|
|
10710
|
+
const version = app.version.split(".").map(Number);
|
|
10711
|
+
if (version.length < 3 || version.some((n) => !Number.isSafeInteger(n)) || version[0] < 1 || version[0] === 1 && version[1] < 52386)
|
|
10712
|
+
throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
|
|
10713
|
+
const userData = system?.userData ?? claudeDesktopDataDirectory();
|
|
10714
|
+
const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
|
|
10715
|
+
await check2();
|
|
10716
|
+
await privateDirectory(userData);
|
|
10717
|
+
const library = join14(userData, "configLibrary");
|
|
10718
|
+
await privateDirectory(library);
|
|
10719
|
+
const release = await desktopLease(join14(library, ".switcher-lease.sqlite"));
|
|
10720
|
+
const metaPath = join14(library, "_meta.json"), receiptPath = join14(library, ".switcher-selection.json");
|
|
10721
|
+
let receipt, gateway, closed = false;
|
|
10722
|
+
const restore = async (record3) => {
|
|
10723
|
+
if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
|
|
10724
|
+
throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
|
|
10725
|
+
const configPath = join14(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
|
|
10726
|
+
if (current !== undefined && hash2(current) !== record3.configHash)
|
|
10727
|
+
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.");
|
|
10728
|
+
const currentMeta = await safeDesktopRead(metaPath);
|
|
10729
|
+
if (currentMeta !== record3.appliedMeta && currentMeta !== (record3.previousMeta ?? undefined))
|
|
10730
|
+
throw new Fault(409, "desktop_config_changed", "Claude's selected configuration changed during this launch. Switcher will preserve the changed selection; review its configuration library before relaunching.");
|
|
10731
|
+
if (record3.previousMeta === null)
|
|
10732
|
+
await rm5(metaPath, { force: true });
|
|
10733
|
+
else
|
|
10734
|
+
await writeDesktopPrivate(metaPath, record3.previousMeta);
|
|
10735
|
+
await rm5(configPath, { force: true });
|
|
10736
|
+
await rm5(receiptPath, { force: true });
|
|
10737
|
+
};
|
|
10738
|
+
const cleanup = async () => {
|
|
10739
|
+
if (closed)
|
|
10740
|
+
return;
|
|
10741
|
+
closed = true;
|
|
10742
|
+
try {
|
|
10743
|
+
await gateway?.cleanup();
|
|
10744
|
+
if (receipt)
|
|
10745
|
+
await restore(receipt);
|
|
10746
|
+
} finally {
|
|
10747
|
+
release();
|
|
10748
|
+
}
|
|
10749
|
+
};
|
|
10750
|
+
try {
|
|
10751
|
+
const recovery = await safeDesktopRead(receiptPath);
|
|
10752
|
+
if (recovery)
|
|
10753
|
+
await restore(JSON.parse(recovery));
|
|
10754
|
+
const localConfig = await safeDesktopRead(join14(userData, "claude_desktop_config.json"));
|
|
10755
|
+
if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
|
|
10756
|
+
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.");
|
|
10757
|
+
await privateDirectory(sessionDir);
|
|
10758
|
+
const roles2 = input.modelPolicy?.roles;
|
|
10759
|
+
const targets = { sonnet: input.model, opus: roles2?.planning ?? input.model, haiku: roles2?.fast ?? input.model };
|
|
10760
|
+
const aliases = Object.fromEntries(Object.entries(targets).map(([tier, model3]) => ["switcher/" + tier, model3]));
|
|
10761
|
+
for (const [alias, target] of Object.entries(aliases))
|
|
10762
|
+
if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
|
|
10763
|
+
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.");
|
|
10764
|
+
const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
|
|
10765
|
+
const catalogPath = join14(input.stateDir, "claude-desktop-policy.json");
|
|
10766
|
+
await writeFile13(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
|
|
10767
|
+
gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
10768
|
+
const id2 = crypto.randomUUID(), configPath = join14(library, id2 + ".json");
|
|
10769
|
+
const config = JSON.stringify({
|
|
10770
|
+
inferenceProvider: "gateway",
|
|
10771
|
+
inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
|
|
10772
|
+
inferenceGatewayApiKey: gateway.token,
|
|
10773
|
+
inferenceGatewayAuthScheme: "bearer",
|
|
10774
|
+
modelDiscoveryEnabled: false,
|
|
10775
|
+
inferenceModels: Object.entries(targets).map(([tier, model3]) => ({ name: "switcher/" + tier, labelOverride: model3, anthropicFamilyTier: tier, isFamilyDefault: true }))
|
|
10776
|
+
});
|
|
10777
|
+
const previousMeta = await safeDesktopRead(metaPath);
|
|
10778
|
+
const meta = metadata(previousMeta);
|
|
10779
|
+
const appliedMeta = JSON.stringify({ ...meta, appliedId: id2, entries: [...meta.entries, { id: id2, name: `Switcher: ${input.providerId ?? "provider"} / ${input.model}` }] });
|
|
10780
|
+
receipt = { id: id2, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
|
|
10781
|
+
await writeDesktopPrivate(configPath, config);
|
|
10782
|
+
await writeDesktopPrivate(receiptPath, JSON.stringify(receipt));
|
|
10783
|
+
await writeDesktopPrivate(metaPath, appliedMeta);
|
|
10784
|
+
return {
|
|
10785
|
+
executable: app.executable,
|
|
10786
|
+
args: [],
|
|
10787
|
+
env: { CLAUDE_CONFIG_DIR: sessionDir },
|
|
10788
|
+
configPaths: [catalogPath, configPath],
|
|
10789
|
+
beforeLaunch: check2,
|
|
10790
|
+
cleanup,
|
|
10791
|
+
warnings: [`Claude desktop gateway: ${input.providerId ?? "provider"} / ${input.model}. Uses the shared Claude-3p profile, separate from the normal Claude account. Quit this instance before switching providers; keep Switcher running until then. The previous configuration selection is restored on exit. Managed settings and native permissions remain authoritative.`]
|
|
10792
|
+
};
|
|
10793
|
+
} catch (error) {
|
|
10794
|
+
try {
|
|
10795
|
+
await cleanup();
|
|
10796
|
+
} catch {}
|
|
10797
|
+
throw error;
|
|
10798
|
+
}
|
|
10799
|
+
}
|
|
10800
|
+
|
|
10152
10801
|
// src/launcher.ts
|
|
10153
10802
|
var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
|
|
10154
10803
|
async function writeOriCodexCatalog(stateDir, models) {
|
|
10155
|
-
const path =
|
|
10156
|
-
const nativeModels2 = models.filter(codingEligible).map(codexModel);
|
|
10157
|
-
await
|
|
10804
|
+
const path = join15(stateDir, "ori-codex-models.json");
|
|
10805
|
+
const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
|
|
10806
|
+
await writeFile14(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
|
|
10158
10807
|
`, { mode: 384, flag: "wx" });
|
|
10159
10808
|
return path;
|
|
10160
10809
|
}
|
|
@@ -10243,9 +10892,9 @@ async function prepareOriForPlan(plan, options) {
|
|
|
10243
10892
|
});
|
|
10244
10893
|
try {
|
|
10245
10894
|
const shim = prepareOriModelPolicy(request.target, native);
|
|
10246
|
-
const dir =
|
|
10895
|
+
const dir = join15(options.stateDir, "ori-bin"), path = join15(dir, shim.name);
|
|
10247
10896
|
await mkdir11(dir, { mode: 448 });
|
|
10248
|
-
await
|
|
10897
|
+
await writeFile14(path, shim.script, { mode: 448, flag: "wx" });
|
|
10249
10898
|
return { contract, prepared: {
|
|
10250
10899
|
...ori,
|
|
10251
10900
|
env: { ...ori.env, ...shim.env, PATH: `${dir}:${ori.env.PATH ?? process.env.PATH ?? ""}` },
|
|
@@ -10262,6 +10911,8 @@ async function prepareOriForPlan(plan, options) {
|
|
|
10262
10911
|
async function launch(client, profileId, options = {}) {
|
|
10263
10912
|
const launchDeadline = options.timeoutMs === undefined ? undefined : Date.now() + options.timeoutMs;
|
|
10264
10913
|
const profile = await client.getProfile(profileId);
|
|
10914
|
+
if ((options.reasoning || options.dangerouslyBypassApprovalsAndSandbox) && (profile.harness !== "codex" || (options.backend ?? "direct") !== "direct"))
|
|
10915
|
+
throw new Error("Reasoning and full-access launch options require direct Codex or ChatGPT.");
|
|
10265
10916
|
assertHarnessArguments(profile.harness, options.args ?? []);
|
|
10266
10917
|
if (profile.harness === "gemini")
|
|
10267
10918
|
validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
|
|
@@ -10282,16 +10933,21 @@ async function launch(client, profileId, options = {}) {
|
|
|
10282
10933
|
throw new Error("--executable is ambiguous with --backend ori; use --ori-executable PATH.");
|
|
10283
10934
|
if (backend === "direct" && options.oriExecutable)
|
|
10284
10935
|
throw new Error("--ori-executable requires --backend ori.");
|
|
10285
|
-
|
|
10286
|
-
|
|
10936
|
+
if (options.desktop && (plan.profile.harness !== "codex" || backend !== "direct"))
|
|
10937
|
+
throw new Error("ChatGPT requires the direct Codex provider adapter.");
|
|
10938
|
+
if (options.claudeDesktop && (options.desktop || plan.profile.harness !== "claude" || backend !== "direct" || options.executable || options.args?.length))
|
|
10939
|
+
throw new Error("Claude desktop requires its direct Messages gateway adapter without native CLI overrides.");
|
|
10940
|
+
const nativeExecutable = options.desktop?.codexExecutable ?? options.executable;
|
|
10941
|
+
const detection = backend === "direct" && !options.claudeDesktop ? await detectHarness(plan.profile.harness, nativeExecutable) : undefined;
|
|
10942
|
+
if (backend === "direct" && !options.claudeDesktop && !detection?.available)
|
|
10287
10943
|
throw new Error(harnessInstallationMessage(plan.profile.harness, detection?.executable ?? plan.profile.harness, Boolean(options.executable)));
|
|
10288
10944
|
if (backend === "direct" && plan.profile.harness === "gemini")
|
|
10289
10945
|
validateHarnessVersion("gemini", detection?.version);
|
|
10290
10946
|
if (backend === "direct" && plan.profile.harness === "aider")
|
|
10291
10947
|
validateHarnessVersion(plan.profile.harness, detection?.version);
|
|
10292
|
-
const root = resolve9(options.stateDir ??
|
|
10948
|
+
const root = resolve9(options.stateDir ?? join15(switcherHome(), "state"));
|
|
10293
10949
|
await privateDirectory(root);
|
|
10294
|
-
const stateDir = await mkdtemp(
|
|
10950
|
+
const stateDir = await mkdtemp(join15(root, "launch-"));
|
|
10295
10951
|
let credential;
|
|
10296
10952
|
if (backend === "direct") {
|
|
10297
10953
|
try {
|
|
@@ -10299,7 +10955,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
10299
10955
|
if (plan.provider.credentialEnv && !credential)
|
|
10300
10956
|
throw new Error("Provider credential environment reference is not available in this local launcher process.");
|
|
10301
10957
|
} catch (error) {
|
|
10302
|
-
await
|
|
10958
|
+
await rm6(stateDir, { recursive: true, force: true });
|
|
10303
10959
|
throw error;
|
|
10304
10960
|
}
|
|
10305
10961
|
}
|
|
@@ -10335,7 +10991,21 @@ async function launch(client, profileId, options = {}) {
|
|
|
10335
10991
|
return;
|
|
10336
10992
|
});
|
|
10337
10993
|
try {
|
|
10338
|
-
const
|
|
10994
|
+
const input = {
|
|
10995
|
+
harness: plan.profile.harness,
|
|
10996
|
+
baseUrl: plan.provider.baseUrl,
|
|
10997
|
+
protocol: plan.provider.protocol,
|
|
10998
|
+
authStyle: plan.provider.authStyle,
|
|
10999
|
+
model: plan.profile.model,
|
|
11000
|
+
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
11001
|
+
modelPolicy: plan.profile.modelPolicy,
|
|
11002
|
+
providerId: plan.provider.id,
|
|
11003
|
+
onRoutingEvent,
|
|
11004
|
+
credential,
|
|
11005
|
+
stateDir,
|
|
11006
|
+
cwd: resolve9(options.cwd ?? process.cwd())
|
|
11007
|
+
};
|
|
11008
|
+
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join15(root, "desktop-claude", profileId)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent })).prepared : await prepareHarnessLaunch({
|
|
10339
11009
|
harness: plan.profile.harness,
|
|
10340
11010
|
baseUrl: plan.provider.baseUrl,
|
|
10341
11011
|
protocol: plan.provider.protocol,
|
|
@@ -10344,16 +11014,22 @@ async function launch(client, profileId, options = {}) {
|
|
|
10344
11014
|
modelPolicy: plan.profile.modelPolicy,
|
|
10345
11015
|
providerId: plan.provider.id,
|
|
10346
11016
|
onRoutingEvent,
|
|
11017
|
+
reasoning: options.reasoning,
|
|
11018
|
+
dangerouslyBypassApprovalsAndSandbox: options.dangerouslyBypassApprovalsAndSandbox,
|
|
10347
11019
|
credential,
|
|
10348
11020
|
authStyle: plan.provider.authStyle,
|
|
10349
|
-
executable:
|
|
11021
|
+
executable: nativeExecutable ?? detection?.executable,
|
|
10350
11022
|
args: options.args ?? [],
|
|
10351
11023
|
stateDir,
|
|
10352
11024
|
cwd: resolve9(options.cwd ?? process.cwd()),
|
|
10353
11025
|
version: detection?.version,
|
|
10354
|
-
...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo"].includes(plan.profile.harness) ? { sessionDir:
|
|
11026
|
+
...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo"].includes(plan.profile.harness) ? { sessionDir: join15(root, "sessions", plan.profile.harness, profileId) } : {}
|
|
10355
11027
|
});
|
|
10356
11028
|
cleanup = prepared.cleanup;
|
|
11029
|
+
if (options.desktop) {
|
|
11030
|
+
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join15(root, "desktop", profileId));
|
|
11031
|
+
cleanup = prepared.cleanup;
|
|
11032
|
+
}
|
|
10357
11033
|
for (const warning of [...plan.warnings, ...prepared.warnings])
|
|
10358
11034
|
console.error(`switcher: ${warning}`);
|
|
10359
11035
|
const interruptPreparation = (error, cancel = true) => {
|
|
@@ -10428,7 +11104,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
10428
11104
|
interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
|
|
10429
11105
|
throw preparationSignal;
|
|
10430
11106
|
}
|
|
10431
|
-
const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve9(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, timeoutMs: remainingRuntime });
|
|
11107
|
+
const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve9(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
|
|
10432
11108
|
await cleanup?.();
|
|
10433
11109
|
cleanup = undefined;
|
|
10434
11110
|
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}.`);
|
|
@@ -10459,13 +11135,13 @@ async function launch(client, profileId, options = {}) {
|
|
|
10459
11135
|
try {
|
|
10460
11136
|
await cleanup?.();
|
|
10461
11137
|
} finally {
|
|
10462
|
-
await
|
|
11138
|
+
await rm6(stateDir, { recursive: true, force: true });
|
|
10463
11139
|
}
|
|
10464
11140
|
}
|
|
10465
11141
|
}
|
|
10466
11142
|
|
|
10467
11143
|
// src/direct-launch.ts
|
|
10468
|
-
import { createHash as
|
|
11144
|
+
import { createHash as createHash11 } from "crypto";
|
|
10469
11145
|
import { createInterface } from "readline/promises";
|
|
10470
11146
|
var absent = (error) => error instanceof SwitcherError && error.status === 404;
|
|
10471
11147
|
async function resolveLaunchProvider(client, selector, options = {}) {
|
|
@@ -10545,8 +11221,8 @@ async function selectModel(models, query = "", harness) {
|
|
|
10545
11221
|
async function ensureLaunchProfile(client, provider, harness, model3, modelPolicy) {
|
|
10546
11222
|
const normalizedPolicy = modelPolicy === undefined ? undefined : parse2(modelPolicySchema, modelPolicy);
|
|
10547
11223
|
const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
|
|
10548
|
-
const
|
|
10549
|
-
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${
|
|
11224
|
+
const hash3 = createHash11("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
|
|
11225
|
+
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
|
|
10550
11226
|
let existing;
|
|
10551
11227
|
try {
|
|
10552
11228
|
existing = await client.getProfile(desired.id);
|
|
@@ -10569,57 +11245,57 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
10569
11245
|
}
|
|
10570
11246
|
|
|
10571
11247
|
// src/credentials.ts
|
|
10572
|
-
import { z as
|
|
10573
|
-
import { constants as
|
|
10574
|
-
import { open as open3, readdir as readdir5, unlink, link, lstat as
|
|
10575
|
-
import { join as
|
|
10576
|
-
import { createHash as
|
|
10577
|
-
import { execFile as
|
|
10578
|
-
import { promisify as
|
|
11248
|
+
import { z as z7 } from "zod";
|
|
11249
|
+
import { constants as constants6 } from "fs";
|
|
11250
|
+
import { open as open3, readdir as readdir5, unlink, link, lstat as lstat5, access as access5, stat as stat6, realpath as realpath6, readlink, rename as rename3 } from "fs/promises";
|
|
11251
|
+
import { join as join16, isAbsolute as isAbsolute13, dirname as dirname8, parse as pathParts, resolve as resolvePath, sep as sep2 } from "path";
|
|
11252
|
+
import { createHash as createHash12, randomUUID as randomUUID5 } from "crypto";
|
|
11253
|
+
import { execFile as execFile5, spawn as spawn2 } from "child_process";
|
|
11254
|
+
import { promisify as promisify5 } from "util";
|
|
10579
11255
|
import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys2, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
|
|
10580
|
-
var
|
|
10581
|
-
var reference =
|
|
10582
|
-
var item =
|
|
10583
|
-
var vaultKey =
|
|
10584
|
-
var keychain =
|
|
10585
|
-
var operator =
|
|
10586
|
-
|
|
10587
|
-
|
|
10588
|
-
|
|
11256
|
+
var execute4 = promisify5(execFile5);
|
|
11257
|
+
var reference = z7.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
|
|
11258
|
+
var item = z7.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
|
|
11259
|
+
var vaultKey = z7.string().max(500).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*)*$/, "Use a vault key path, not an option or secret value");
|
|
11260
|
+
var keychain = z7.object({ kind: z7.literal("keychain"), service: item, account: item }).strict();
|
|
11261
|
+
var operator = z7.discriminatedUnion("kind", [
|
|
11262
|
+
z7.object({ kind: z7.literal("contracts") }).strict(),
|
|
11263
|
+
z7.object({ kind: z7.literal("env") }).strict(),
|
|
11264
|
+
z7.object({ kind: z7.literal("keychain"), account: item.refine((value) => value.trim().length > 0 && value === value.trim(), "Vault account must be nonblank without surrounding whitespace") }).strict()
|
|
10589
11265
|
]);
|
|
10590
|
-
var origin =
|
|
10591
|
-
var credentialBindingSchema =
|
|
10592
|
-
schema:
|
|
11266
|
+
var origin = z7.string().transform((value) => new URL(endpoint(value)).origin);
|
|
11267
|
+
var credentialBindingSchema = z7.object({
|
|
11268
|
+
schema: z7.literal(1),
|
|
10593
11269
|
credentialEnv: reference,
|
|
10594
|
-
origins:
|
|
10595
|
-
source:
|
|
10596
|
-
kind:
|
|
11270
|
+
origins: z7.array(origin).min(1).max(30),
|
|
11271
|
+
source: z7.discriminatedUnion("kind", [keychain, z7.object({
|
|
11272
|
+
kind: z7.literal("vault"),
|
|
10597
11273
|
key: vaultKey,
|
|
10598
|
-
url:
|
|
10599
|
-
executable:
|
|
11274
|
+
url: z7.string().max(2000).transform(endpoint).optional(),
|
|
11275
|
+
executable: z7.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute13, "Secrets executable must be an absolute path"),
|
|
10600
11276
|
operator
|
|
10601
11277
|
}).strict()])
|
|
10602
11278
|
}).strict().superRefine((binding, ctx) => {
|
|
10603
11279
|
if (binding.source.kind === "vault" && binding.source.operator.kind !== "contracts" && !binding.source.url)
|
|
10604
11280
|
ctx.addIssue({ code: "custom", path: ["source", "url"], message: "An explicit env or Keychain operator binding requires a vault URL." });
|
|
10605
11281
|
});
|
|
10606
|
-
var fingerprint = (binding) =>
|
|
11282
|
+
var fingerprint = (binding) => createHash12("sha256").update(JSON.stringify(binding)).digest("hex");
|
|
10607
11283
|
|
|
10608
11284
|
class CredentialBindings {
|
|
10609
11285
|
env;
|
|
10610
11286
|
directory;
|
|
10611
11287
|
constructor(env = process.env) {
|
|
10612
11288
|
this.env = env;
|
|
10613
|
-
this.directory =
|
|
11289
|
+
this.directory = join16(switcherHome(env), "config", "credential-bindings");
|
|
10614
11290
|
}
|
|
10615
11291
|
path(name) {
|
|
10616
|
-
return
|
|
11292
|
+
return join16(this.directory, parse2(reference, name) + ".json");
|
|
10617
11293
|
}
|
|
10618
11294
|
async readableDirectory() {
|
|
10619
|
-
for (const path of [switcherHome(this.env),
|
|
11295
|
+
for (const path of [switcherHome(this.env), join16(switcherHome(this.env), "config"), this.directory]) {
|
|
10620
11296
|
let info;
|
|
10621
11297
|
try {
|
|
10622
|
-
info = await
|
|
11298
|
+
info = await lstat5(path);
|
|
10623
11299
|
} catch (error) {
|
|
10624
11300
|
if (error.code === "ENOENT")
|
|
10625
11301
|
return false;
|
|
@@ -10636,7 +11312,7 @@ class CredentialBindings {
|
|
|
10636
11312
|
return;
|
|
10637
11313
|
let file;
|
|
10638
11314
|
try {
|
|
10639
|
-
file = await open3(path,
|
|
11315
|
+
file = await open3(path, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
10640
11316
|
} catch (error) {
|
|
10641
11317
|
if (error.code === "ENOENT")
|
|
10642
11318
|
return;
|
|
@@ -10685,9 +11361,9 @@ class CredentialBindings {
|
|
|
10685
11361
|
if (binding.source.kind === "vault")
|
|
10686
11362
|
await validateVaultExecutable(binding.source.executable);
|
|
10687
11363
|
await privateDirectory(switcherHome(this.env));
|
|
10688
|
-
await privateDirectory(
|
|
11364
|
+
await privateDirectory(join16(switcherHome(this.env), "config"));
|
|
10689
11365
|
await privateDirectory(this.directory);
|
|
10690
|
-
const temporary =
|
|
11366
|
+
const temporary = join16(this.directory, `.binding-${randomUUID5()}`);
|
|
10691
11367
|
const file = await open3(temporary, "wx", 384);
|
|
10692
11368
|
try {
|
|
10693
11369
|
await file.writeFile(JSON.stringify(binding, null, 2) + `
|
|
@@ -10727,8 +11403,8 @@ async function inspectVaultExecutable(path, permitWritableFile = false) {
|
|
|
10727
11403
|
let info, resolved;
|
|
10728
11404
|
try {
|
|
10729
11405
|
resolved = await realpath6(path);
|
|
10730
|
-
await
|
|
10731
|
-
info = await
|
|
11406
|
+
await access5(resolved, constants6.X_OK);
|
|
11407
|
+
info = await stat6(resolved);
|
|
10732
11408
|
if (!info.isFile())
|
|
10733
11409
|
throw new Error;
|
|
10734
11410
|
} catch {
|
|
@@ -10743,13 +11419,13 @@ async function inspectVaultExecutable(path, permitWritableFile = false) {
|
|
|
10743
11419
|
for (const part of candidate.slice(prefix.length).split(sep2)) {
|
|
10744
11420
|
if (!part)
|
|
10745
11421
|
continue;
|
|
10746
|
-
prefix =
|
|
11422
|
+
prefix = join16(prefix, part);
|
|
10747
11423
|
if (seen.has(prefix))
|
|
10748
11424
|
continue;
|
|
10749
11425
|
seen.add(prefix);
|
|
10750
11426
|
if (seen.size > 256)
|
|
10751
11427
|
throw new Fault(422, "vault_exec_permissions", "The secrets executable path has too many symlink components.");
|
|
10752
|
-
const entry = await
|
|
11428
|
+
const entry = await lstat5(prefix);
|
|
10753
11429
|
const permittedFile = permitWritableFile && prefix === resolved && entry.isFile();
|
|
10754
11430
|
if (entry.uid !== 0 && entry.uid !== process.getuid?.() || !entry.isSymbolicLink() && !permittedFile && entry.mode & 18)
|
|
10755
11431
|
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.");
|
|
@@ -10774,12 +11450,12 @@ async function validateVaultExecutable(path) {
|
|
|
10774
11450
|
async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
10775
11451
|
if (!/^[a-f0-9]{64}$/.test(expectedSha256))
|
|
10776
11452
|
throw new Fault(400, "invalid_request", "--sha256 requires the SHA256 of the executable member from a verified package artifact.");
|
|
10777
|
-
if (!
|
|
11453
|
+
if (!isAbsolute13(path) || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path))
|
|
10778
11454
|
throw new Fault(400, "invalid_request", "Secrets executable must be an absolute path without control characters.");
|
|
10779
11455
|
if (process.platform === "win32")
|
|
10780
11456
|
throw new Fault(422, "vault_exec_repair_unsafe", "Executable permission repair requires POSIX file permissions.");
|
|
10781
11457
|
const resolved = await inspectVaultExecutable(path, true);
|
|
10782
|
-
const file = await open3(resolved,
|
|
11458
|
+
const file = await open3(resolved, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
10783
11459
|
const unsafe = () => new Fault(422, "vault_exec_repair_unsafe", "Executable ownership, type, links or contents changed; no trusted repair can be confirmed.");
|
|
10784
11460
|
let temporary;
|
|
10785
11461
|
try {
|
|
@@ -10788,8 +11464,8 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
10788
11464
|
if (!before.isFile() || before.uid !== process.getuid?.() || before.size > limit || before.mode & 3584)
|
|
10789
11465
|
throw unsafe();
|
|
10790
11466
|
const sameFile = (info) => info.dev === before.dev && info.ino === before.ino && info.size === before.size && info.uid === before.uid && info.nlink === before.nlink && info.mode === before.mode && info.mtimeMs === before.mtimeMs && info.ctimeMs === before.ctimeMs;
|
|
10791
|
-
const
|
|
10792
|
-
const
|
|
11467
|
+
const hash3 = async (target) => {
|
|
11468
|
+
const digest2 = createHash12("sha256");
|
|
10793
11469
|
const buffer = Buffer.alloc(1024 * 1024);
|
|
10794
11470
|
let position = 0;
|
|
10795
11471
|
while (true) {
|
|
@@ -10800,41 +11476,41 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
10800
11476
|
if (position > limit)
|
|
10801
11477
|
throw unsafe();
|
|
10802
11478
|
const bytes = buffer.subarray(0, bytesRead);
|
|
10803
|
-
|
|
11479
|
+
digest2.update(bytes);
|
|
10804
11480
|
if (target)
|
|
10805
11481
|
await target.writeFile(bytes);
|
|
10806
11482
|
}
|
|
10807
11483
|
if (position !== before.size || !sameFile(await file.stat()))
|
|
10808
11484
|
throw unsafe();
|
|
10809
|
-
if (
|
|
11485
|
+
if (digest2.digest("hex") !== expectedSha256)
|
|
10810
11486
|
throw new Fault(422, "vault_exec_digest_mismatch", "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed.");
|
|
10811
11487
|
};
|
|
10812
|
-
await
|
|
11488
|
+
await hash3();
|
|
10813
11489
|
const mode = before.mode & 511 & ~18;
|
|
10814
11490
|
const changed = mode !== (before.mode & 511);
|
|
10815
|
-
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await
|
|
11491
|
+
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat5(resolved)))
|
|
10816
11492
|
throw unsafe();
|
|
10817
11493
|
if (!changed) {
|
|
10818
11494
|
await validateVaultExecutable(path);
|
|
10819
11495
|
return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
|
|
10820
11496
|
}
|
|
10821
|
-
temporary =
|
|
11497
|
+
temporary = join16(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
|
|
10822
11498
|
const replacement = await open3(temporary, "wx", 384);
|
|
10823
11499
|
try {
|
|
10824
|
-
await
|
|
11500
|
+
await hash3(replacement);
|
|
10825
11501
|
await replacement.chmod(mode);
|
|
10826
11502
|
await replacement.sync();
|
|
10827
11503
|
const ready = await replacement.stat();
|
|
10828
11504
|
if (!ready.isFile() || ready.nlink !== 1 || ready.uid !== before.uid || ready.size !== before.size)
|
|
10829
11505
|
throw unsafe();
|
|
10830
|
-
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await
|
|
11506
|
+
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat5(resolved)))
|
|
10831
11507
|
throw unsafe();
|
|
10832
|
-
await
|
|
11508
|
+
await rename3(temporary, resolved);
|
|
10833
11509
|
temporary = undefined;
|
|
10834
|
-
const installed = await
|
|
11510
|
+
const installed = await lstat5(resolved);
|
|
10835
11511
|
if (installed.dev !== ready.dev || installed.ino !== ready.ino || await validateVaultExecutable(path) !== resolved)
|
|
10836
11512
|
throw unsafe();
|
|
10837
|
-
const directory = await open3(dirname8(resolved),
|
|
11513
|
+
const directory = await open3(dirname8(resolved), constants6.O_RDONLY | constants6.O_DIRECTORY | constants6.O_NOFOLLOW);
|
|
10838
11514
|
try {
|
|
10839
11515
|
await directory.sync();
|
|
10840
11516
|
} finally {
|
|
@@ -10871,7 +11547,7 @@ async function readKeychain(source) {
|
|
|
10871
11547
|
if (process.platform !== "darwin")
|
|
10872
11548
|
throw new Fault(422, "keychain_unavailable", "This binding requires macOS Keychain. Use a supported vault binding or runtime environment on this station.");
|
|
10873
11549
|
try {
|
|
10874
|
-
const { stdout } = await
|
|
11550
|
+
const { stdout } = await execute4("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 });
|
|
10875
11551
|
const value = stdout.replace(/\r?\n$/, "");
|
|
10876
11552
|
if (!value || /[\x00-\x1f\x7f]/.test(value))
|
|
10877
11553
|
throw new Error("Invalid credential");
|
|
@@ -10914,7 +11590,7 @@ class CredentialResolver {
|
|
|
10914
11590
|
return { credentialEnv: name, source: "vault", available: true, length: Number(match[1]), sha256: match[2], providerAuthentication: "not tested" };
|
|
10915
11591
|
}
|
|
10916
11592
|
const value = await this.keychainRead(binding.source);
|
|
10917
|
-
return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256:
|
|
11593
|
+
return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash12("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
|
|
10918
11594
|
}
|
|
10919
11595
|
}
|
|
10920
11596
|
var DELIVERY_URL = "SWITCHER_CREDENTIAL_DELIVERY_URL";
|
|
@@ -11093,17 +11769,26 @@ async function deliverVaultCredential() {
|
|
|
11093
11769
|
}
|
|
11094
11770
|
|
|
11095
11771
|
// src/cli.ts
|
|
11096
|
-
var HELP = `switcher \u2014 launch
|
|
11772
|
+
var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your provider and model
|
|
11097
11773
|
|
|
11774
|
+
switcher launch chatgpt --provider PROVIDER --model MODEL [--reasoning EFFORT]
|
|
11775
|
+
[--dangerously-bypass-approvals-and-sandbox] [--app-path /absolute/ChatGPT.app]
|
|
11776
|
+
[--dry-run] [--cwd DIR] [--timeout SECONDS]
|
|
11777
|
+
switcher launch claude-desktop --provider PROVIDER --model MODEL
|
|
11778
|
+
[--app-path /absolute/Claude.app] [--dry-run]
|
|
11098
11779
|
switcher providers presets [ID]
|
|
11099
11780
|
switcher providers list [--search TEXT] [--limit N] [--offset N]
|
|
11100
11781
|
switcher providers add ID --url URL --protocol PROTOCOL [--credential-env NAME]
|
|
11782
|
+
[--model MODEL | --models-file FILE] [--catalog-format none]
|
|
11101
11783
|
switcher providers add ID --preset PRESET [--protocol PROTOCOL] [--catalog-account-id ID]
|
|
11102
11784
|
switcher providers get|refresh ID
|
|
11103
11785
|
switcher providers update ID --file provider.json --version N
|
|
11104
11786
|
switcher providers delete ID --version N
|
|
11105
11787
|
switcher models PROVIDER [--refresh] [--search TEXT] [--limit N]
|
|
11106
|
-
switcher models
|
|
11788
|
+
switcher models list PROVIDER [--refresh] [--search TEXT] [--limit N]
|
|
11789
|
+
switcher models add|update PROVIDER MODEL [--file model.json | --name NAME --expires-on YYYY-MM-DD]
|
|
11790
|
+
switcher models remove PROVIDER MODEL
|
|
11791
|
+
switcher models config PROVIDER
|
|
11107
11792
|
switcher profiles list|get [ID]
|
|
11108
11793
|
switcher profiles add ID --provider ID --harness HARNESS --model MODEL [--model-policy-file FILE] [--role-model ROLE=MODEL]
|
|
11109
11794
|
switcher profiles update ID --file profile.json --version N
|
|
@@ -11122,6 +11807,13 @@ var HELP = `switcher \u2014 launch a coding harness with a provider and its mode
|
|
|
11122
11807
|
switcher doctor
|
|
11123
11808
|
|
|
11124
11809
|
HARNESS: claude, codex, grok, opencode, opencode2, pi, omp, dsh, cline, hermes, prime-agent, gemini, aider, kilo
|
|
11810
|
+
chatgpt launches the installed macOS desktop app in an isolated provider profile.
|
|
11811
|
+
Its local Codex conversations use the selected Responses-compatible provider.
|
|
11812
|
+
claude-desktop launches Claude in its separate Claude-3p gateway profile with a
|
|
11813
|
+
Messages-compatible provider. Quit that instance before switching providers.
|
|
11814
|
+
Keep Switcher running while using the app; quit that app instance to end the launch.
|
|
11815
|
+
--reasoning: none, minimal, low, medium, high, xhigh, max, ultra (provider support required).
|
|
11816
|
+
--dangerously-bypass-approvals-and-sandbox: full access without prompts or command sandboxing.
|
|
11125
11817
|
PROTOCOL: anthropic-messages, openai-responses, openai-chat, gemini-generate-content
|
|
11126
11818
|
Without remote API configuration, the CLI owns a local authenticated API and
|
|
11127
11819
|
stores data in ~/.hasna/switcher (override HASNA_SWITCHER_HOME).
|
|
@@ -11129,6 +11821,10 @@ Remote API URL/key resolve through @hasna/contracts: overrides, Keychain,
|
|
|
11129
11821
|
~/.hasna/switcher/config/credentials, then environment. A key alone uses the gateway.
|
|
11130
11822
|
A configured remote API never falls back to local data.
|
|
11131
11823
|
Provider credential references must start SWITCHER_PROVIDER_.
|
|
11824
|
+
--models-file accepts a JSON array of model metadata; --model adds one starter.
|
|
11825
|
+
Use --catalog-format none for a manual catalog; otherwise discovery stays active.
|
|
11826
|
+
models update replaces saved metadata; omit expiry in its JSON to clear it.
|
|
11827
|
+
models remove removes saved metadata, not entries in an upstream catalog.
|
|
11132
11828
|
Credential bindings contain references only. Custom destinations require --origin URL.
|
|
11133
11829
|
Vault bindings use the installed secrets CLI and its canonical Contracts URL/key
|
|
11134
11830
|
by default. --vault-account pins a Keychain account; --vault-operator env requires
|
|
@@ -11181,10 +11877,14 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11181
11877
|
json: { type: "boolean" },
|
|
11182
11878
|
url: { type: "string" },
|
|
11183
11879
|
sha256: { type: "string" },
|
|
11880
|
+
"app-path": { type: "string" },
|
|
11881
|
+
reasoning: { type: "string" },
|
|
11882
|
+
"dangerously-bypass-approvals-and-sandbox": { type: "boolean" },
|
|
11184
11883
|
protocol: { type: "string" },
|
|
11185
11884
|
preset: { type: "string" },
|
|
11186
11885
|
name: { type: "string" },
|
|
11187
11886
|
file: { type: "string" },
|
|
11887
|
+
"models-file": { type: "string" },
|
|
11188
11888
|
"credential-env": { type: "string" },
|
|
11189
11889
|
"auth-style": { type: "string" },
|
|
11190
11890
|
"catalog-url": { type: "string" },
|
|
@@ -11225,16 +11925,53 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11225
11925
|
}
|
|
11226
11926
|
const [command, action2, id2] = positionals;
|
|
11227
11927
|
const output = (value) => console.log(JSON.stringify(value, null, 2));
|
|
11928
|
+
const reasoning = values2.reasoning === undefined ? undefined : parse2(reasoningEffortSchema, values2.reasoning);
|
|
11929
|
+
const dangerouslyBypassApprovalsAndSandbox = values2["dangerously-bypass-approvals-and-sandbox"];
|
|
11930
|
+
if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" || values2.provider && !["chatgpt", "codex"].includes(action2) || values2.backend && values2.backend !== "direct"))
|
|
11931
|
+
throw new Fault(400, "conflicting_options", "--reasoning and --dangerously-bypass-approvals-and-sandbox require a direct Codex or ChatGPT launch.");
|
|
11932
|
+
const chatgpt = command === "launch" && action2 === "chatgpt" && values2.provider !== undefined;
|
|
11933
|
+
const claudeDesktop = command === "launch" && action2 === "claude-desktop" && values2.provider !== undefined;
|
|
11934
|
+
if (values2["app-path"] !== undefined && !chatgpt && !claudeDesktop)
|
|
11935
|
+
throw new Fault(400, "conflicting_options", "--app-path belongs to launch chatgpt or claude-desktop --provider PROVIDER --model MODEL.");
|
|
11936
|
+
if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 || values2.executable !== undefined || values2.backend !== undefined || values2["ori-executable"] !== undefined))
|
|
11937
|
+
throw new Fault(400, "conflicting_options", "Desktop apps use their own runtime; native CLI arguments, --executable and --backend are not accepted.");
|
|
11938
|
+
const desktop = chatgpt ? await detectChatGPTApp(values2["app-path"]) : undefined;
|
|
11939
|
+
const claudeApp = claudeDesktop ? await detectClaudeDesktopApp(values2["app-path"]) : undefined;
|
|
11228
11940
|
if (!["doctor", "launch", "models", "runs", "providers", "profiles", "credentials"].includes(command))
|
|
11229
11941
|
throw new Error("Unknown command. Run switcher --help.");
|
|
11230
11942
|
const providerFlags = ["url", "protocol", "preset", "credential-env", "auth-style", "catalog-url", "catalog-format", "catalog-auth-style", "catalog-credential-env", "catalog-account-id", "models-path"];
|
|
11231
11943
|
const provided = (names) => names.some((name) => values2[name] !== undefined);
|
|
11232
|
-
const
|
|
11233
|
-
|
|
11234
|
-
|
|
11235
|
-
if (
|
|
11236
|
-
throw new Fault(400, "invalid_request", "Use models
|
|
11237
|
-
|
|
11944
|
+
const editingModel = command === "models" && positionals.length > 2 && ["add", "update", "remove"].includes(action2);
|
|
11945
|
+
const configuringModels = command === "models" && positionals.length > 2 && action2 === "config";
|
|
11946
|
+
const listingModels = command === "models" && positionals.length > 2 && action2 === "list";
|
|
11947
|
+
if (listingModels && (positionals.length !== 3 || nativeArgs.length || Object.keys(values2).some((name) => !["refresh", "search", "limit", "offset", "json"].includes(name))))
|
|
11948
|
+
throw new Fault(400, "invalid_request", "Use models list PROVIDER with optional --refresh, --search, --limit and --offset.");
|
|
11949
|
+
if (values2["expires-on"] !== undefined && (!editingModel || action2 === "remove"))
|
|
11950
|
+
throw new Fault(400, "conflicting_options", "--expires-on belongs to models add/update.");
|
|
11951
|
+
if (editingModel && (positionals.length !== 4 || nativeArgs.length || Object.keys(values2).some((name) => !(action2 === "remove" ? ["json"] : ["name", "expires-on", "file", "json"]).includes(name))))
|
|
11952
|
+
throw new Fault(400, "invalid_request", "Use models add/update PROVIDER MODEL with --file or --name/--expires-on; models remove accepts only PROVIDER MODEL.");
|
|
11953
|
+
if (configuringModels && (positionals.length !== 3 || nativeArgs.length || Object.keys(values2).some((name) => name !== "json")))
|
|
11954
|
+
throw new Fault(400, "invalid_request", "Use models config PROVIDER without other settings.");
|
|
11955
|
+
if (editingModel && values2.file !== undefined && (values2.name !== undefined || values2["expires-on"] !== undefined))
|
|
11956
|
+
throw new Fault(400, "conflicting_options", "Use --file by itself for model metadata.");
|
|
11957
|
+
const modelInput = editingModel && action2 !== "remove" ? parse2(modelSchema, values2.file !== undefined ? await readInput(values2.file) : { id: positionals[3], name: values2.name ?? positionals[3], expiresOn: values2["expires-on"] }) : undefined;
|
|
11958
|
+
if (modelInput && modelInput.id !== positionals[3])
|
|
11959
|
+
throw new Fault(400, "id_mismatch", "Model file id must match the command model ID.");
|
|
11960
|
+
if (editingModel && action2 === "remove")
|
|
11961
|
+
parse2(modelSchema.shape.id, positionals[3]);
|
|
11962
|
+
const seedingProvider = command === "providers" && action2 === "add";
|
|
11963
|
+
if (values2["models-file"] !== undefined && !seedingProvider)
|
|
11964
|
+
throw new Fault(400, "conflicting_options", "--models-file belongs to providers add.");
|
|
11965
|
+
if (command === "providers" && values2.model !== undefined && !seedingProvider)
|
|
11966
|
+
throw new Fault(400, "conflicting_options", "Provider --model belongs to providers add. Use models add/update/remove for saved providers.");
|
|
11967
|
+
if (seedingProvider && values2["models-file"] !== undefined && values2.model !== undefined)
|
|
11968
|
+
throw new Fault(400, "conflicting_options", "Use --model or --models-file, not both.");
|
|
11969
|
+
let starterModels;
|
|
11970
|
+
if (seedingProvider && (values2.model !== undefined || values2["models-file"] !== undefined)) {
|
|
11971
|
+
starterModels = parse2(modelSchema.array().min(1).max(1e4), values2["models-file"] !== undefined ? await readInput(values2["models-file"]) : [{ id: values2.model, name: values2.model }]);
|
|
11972
|
+
if (new Set(starterModels.map((model3) => model3.id)).size !== starterModels.length)
|
|
11973
|
+
throw new Fault(400, "duplicate_model", "Model IDs must be unique.");
|
|
11974
|
+
}
|
|
11238
11975
|
const credentialFlags = ["vault-key", "vault-url", "vault-cli", "vault-account", "vault-operator", "keychain-service", "keychain-account", "origin"];
|
|
11239
11976
|
const credentials = new CredentialResolver;
|
|
11240
11977
|
if (values2.sha256 !== undefined && !(command === "credentials" && action2 === "repair-executable"))
|
|
@@ -11303,7 +12040,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11303
12040
|
if (command === "launch" && backend === "direct" && values2["ori-executable"] !== undefined)
|
|
11304
12041
|
throw new Fault(400, "conflicting_options", "--ori-executable requires --backend ori.");
|
|
11305
12042
|
const mutation = (command === "providers" || command === "profiles") && ["add", "update"].includes(action2);
|
|
11306
|
-
if (values2.file && (!mutation || provided([...providerFlags, "name", "provider", "harness", "model", "model-policy-file", "role-model"])))
|
|
12043
|
+
if (values2.file && !editingModel && (!mutation || provided([...providerFlags, "name", "provider", "harness", "model", "models-file", "model-policy-file", "role-model"])))
|
|
11307
12044
|
throw new Fault(400, "conflicting_options", "Use --file by itself for provider/profile settings; inline settings cannot override an input file.");
|
|
11308
12045
|
if (command === "launch" && !values2.provider && provided([...providerFlags, "name", "harness", "model", "search", "model-policy-file", "role-model"]))
|
|
11309
12046
|
throw new Fault(400, "conflicting_options", "Use --provider PROVIDER for direct launch settings, or update the saved profile explicitly.");
|
|
@@ -11316,7 +12053,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11316
12053
|
if (command === "launch" && provided(["name", "harness", "file"]))
|
|
11317
12054
|
throw new Fault(400, "conflicting_options", "Launch takes its harness from the positional argument or saved profile; edit named records through providers/profiles.");
|
|
11318
12055
|
if (command === "launch" && values2.provider) {
|
|
11319
|
-
const harness = parse2(harnessSchema, action2);
|
|
12056
|
+
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action2);
|
|
11320
12057
|
assertHarnessArguments(harness, nativeArgs);
|
|
11321
12058
|
await validateHarnessConfiguration(harness, values2.cwd ?? process.cwd(), nativeArgs);
|
|
11322
12059
|
}
|
|
@@ -11362,7 +12099,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11362
12099
|
throw new Error("--timeout must be positive seconds.");
|
|
11363
12100
|
let profileId = action2;
|
|
11364
12101
|
if (values2.provider) {
|
|
11365
|
-
const harness = parse2(harnessSchema, action2);
|
|
12102
|
+
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action2);
|
|
11366
12103
|
const modelPolicy = await readModelPolicy(values2["model-policy-file"], values2["role-model"]);
|
|
11367
12104
|
const provider = await resolveLaunchProvider(client, values2.provider, { ...presetOptions(), harness });
|
|
11368
12105
|
validateHarnessProvider(harness, provider);
|
|
@@ -11375,6 +12112,8 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11375
12112
|
throw new Fault(422, "model_expired", "Selected model has passed its configured expiry date. Select an unexpired model.");
|
|
11376
12113
|
if (!harnessEligible(selected, harness))
|
|
11377
12114
|
throw new Fault(422, "model_ineligible", "Selected model explicitly lacks text output or tool support.");
|
|
12115
|
+
if (harness === "codex")
|
|
12116
|
+
codexReasoning(selected, provider.baseUrl, reasoning);
|
|
11378
12117
|
profileId = (await ensureLaunchProfile(client, provider, harness, model3, modelPolicy)).id;
|
|
11379
12118
|
} else {
|
|
11380
12119
|
if (values2.model || values2.protocol || values2.url || values2["credential-env"] || values2["model-policy-file"] || values2["role-model"])
|
|
@@ -11388,28 +12127,36 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11388
12127
|
}
|
|
11389
12128
|
if (values2["dry-run"]) {
|
|
11390
12129
|
const plan = await client.launchPlan(profileId);
|
|
12130
|
+
if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && plan.profile.harness !== "codex")
|
|
12131
|
+
throw new Fault(400, "conflicting_options", "Reasoning and full-access options require Codex or ChatGPT.");
|
|
12132
|
+
if (reasoning) {
|
|
12133
|
+
const model3 = plan.catalog.models.find((model4) => model4.id === plan.profile.model);
|
|
12134
|
+
if (model3)
|
|
12135
|
+
codexReasoning(model3, plan.provider.baseUrl, reasoning);
|
|
12136
|
+
}
|
|
11391
12137
|
assertHarnessArguments(plan.profile.harness, nativeArgs);
|
|
11392
12138
|
if (backend === "ori") {
|
|
11393
12139
|
const { contract, warnings } = await validateOriForPlan(plan, { oriExecutable: values2["ori-executable"], args: nativeArgs, cwd: values2.cwd });
|
|
11394
12140
|
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] } });
|
|
11395
12141
|
} else
|
|
11396
|
-
output(plan);
|
|
12142
|
+
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" } } : {} });
|
|
11397
12143
|
return;
|
|
11398
12144
|
}
|
|
11399
|
-
process.exitCode = await launch(client, profileId, { backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, resolveCredential: (provider) => credentials.resolve(provider) });
|
|
12145
|
+
process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, resolveCredential: (provider) => credentials.resolve(provider) });
|
|
11400
12146
|
return;
|
|
11401
12147
|
}
|
|
11402
|
-
if (
|
|
12148
|
+
if (editingModel) {
|
|
12149
|
+
const saved = action2 === "add" ? await client.addModel(id2, modelInput) : action2 === "update" ? await client.updateModel(id2, modelInput) : await client.removeModel(id2, positionals[3]);
|
|
12150
|
+
output({ providerId: saved.id, version: saved.version, ...modelInput ? { model: modelInput, expired: modelExpired(modelInput) } : { removed: positionals[3] } });
|
|
12151
|
+
return;
|
|
12152
|
+
}
|
|
12153
|
+
if (configuringModels) {
|
|
11403
12154
|
const provider = await client.getProvider(id2);
|
|
11404
|
-
|
|
11405
|
-
if ((provider.additionalModels ?? []).some((model3) => model3.id === modelAddition.id))
|
|
11406
|
-
throw new Fault(409, "model_exists", "This additional model already exists. Use providers update --file to edit its metadata.");
|
|
11407
|
-
await client.updateProvider({ ...input, additionalModels: [...provider.additionalModels ?? [], modelAddition] }, version);
|
|
11408
|
-
output({ providerId: provider.id, model: modelAddition, expired: modelExpired(modelAddition) });
|
|
12155
|
+
output({ providerId: provider.id, version: provider.version, manualModels: provider.manualModels, additionalModels: provider.additionalModels ?? [] });
|
|
11409
12156
|
return;
|
|
11410
12157
|
}
|
|
11411
12158
|
if (command === "models" && action2) {
|
|
11412
|
-
const provider = await resolveLaunchProvider(client, action2, presetOptions());
|
|
12159
|
+
const provider = await resolveLaunchProvider(client, listingModels ? id2 : action2, presetOptions());
|
|
11413
12160
|
if (values2.refresh)
|
|
11414
12161
|
await client.refreshModels(provider.id);
|
|
11415
12162
|
try {
|
|
@@ -11450,7 +12197,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11450
12197
|
return;
|
|
11451
12198
|
}
|
|
11452
12199
|
if (["add", "update"].includes(action2) && id2) {
|
|
11453
|
-
|
|
12200
|
+
let input = parse2(providerInputSchema, values2.file ? await readInput(values2.file) : values2.preset ? { ...providerFromPreset(values2.preset, { ...presetOptions(), id: id2 }), ...values2.name ? { name: values2.name } : {} } : {
|
|
11454
12201
|
id: id2,
|
|
11455
12202
|
name: values2.name ?? id2,
|
|
11456
12203
|
baseUrl: values2.url,
|
|
@@ -11464,6 +12211,13 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11464
12211
|
catalogAccountId: values2["catalog-account-id"],
|
|
11465
12212
|
modelsPath: values2["models-path"]
|
|
11466
12213
|
});
|
|
12214
|
+
if (starterModels) {
|
|
12215
|
+
const field = input.catalogFormat === "none" ? "manualModels" : "additionalModels";
|
|
12216
|
+
const models = new Map((input[field] ?? []).map((model3) => [model3.id, model3]));
|
|
12217
|
+
for (const model3 of starterModels)
|
|
12218
|
+
models.set(model3.id, model3);
|
|
12219
|
+
input = parse2(providerInputSchema, { ...input, [field]: [...models.values()] });
|
|
12220
|
+
}
|
|
11467
12221
|
if (input.id !== id2)
|
|
11468
12222
|
throw new Error("File id must match the command id.");
|
|
11469
12223
|
output(action2 === "add" ? await client.createProvider(input) : await client.updateProvider(input, currentVersion()));
|