@hasna/switcher 0.1.8 → 0.2.0
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 +161 -3
- package/dist/chatgpt-launch.d.ts +5 -0
- package/dist/claude-desktop-launch.d.ts +11 -0
- package/dist/cli/index.js +1232 -403
- 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 +23 -1
- package/dist/gemini-bridge.d.ts +2 -1
- 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 +13 -3
- package/dist/hermes-backend.d.ts +2 -1
- package/dist/index.js +164 -64
- package/dist/inference-gateway.d.ts +4 -1
- package/dist/launcher.d.ts +6 -0
- package/dist/lib/local-opt-in.d.ts +30 -0
- package/dist/mcp/index.js +4960 -89
- package/dist/model-policy-schema.d.ts +6 -0
- package/dist/presets.d.ts +2 -0
- package/dist/provider-request.d.ts +15 -0
- package/dist/provider-stream.d.ts +3 -1
- package/dist/reasoning.d.ts +10 -0
- package/dist/runtime.d.ts +2 -0
- package/dist/sdk.d.ts +25 -0
- package/dist/sdk.js +164 -64
- package/dist/serve/index.js +288 -73
- package/openapi.json +210 -1
- package/package.json +5 -3
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.
|
|
503
|
-
var harnessSchema =
|
|
504
|
-
var protocolSchema =
|
|
505
|
-
var idSchema =
|
|
506
|
-
var label =
|
|
507
|
-
var envRef =
|
|
517
|
+
var VERSION = "0.2.0";
|
|
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 {
|
|
@@ -1187,6 +1203,98 @@ function providerCredential(provider, env = process.env) {
|
|
|
1187
1203
|
throw new Fault(422, "credential_invalid", "Provider credential contains invalid header characters.");
|
|
1188
1204
|
return value;
|
|
1189
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
|
+
}
|
|
1190
1298
|
|
|
1191
1299
|
// src/sdk.ts
|
|
1192
1300
|
class SwitcherError extends Error {
|
|
@@ -1458,6 +1566,7 @@ function proxyProviderStream(input) {
|
|
|
1458
1566
|
if (ended)
|
|
1459
1567
|
return;
|
|
1460
1568
|
ended = true;
|
|
1569
|
+
input.activity?.finish();
|
|
1461
1570
|
try {
|
|
1462
1571
|
if (error)
|
|
1463
1572
|
output.error(error);
|
|
@@ -1468,9 +1577,9 @@ function proxyProviderStream(input) {
|
|
|
1468
1577
|
};
|
|
1469
1578
|
const cancelReader = async () => {
|
|
1470
1579
|
input.abort.abort();
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
}
|
|
1580
|
+
reader.cancel().catch(() => {
|
|
1581
|
+
return;
|
|
1582
|
+
});
|
|
1474
1583
|
};
|
|
1475
1584
|
const stream = new ReadableStream({
|
|
1476
1585
|
start(controller) {
|
|
@@ -1478,7 +1587,7 @@ function proxyProviderStream(input) {
|
|
|
1478
1587
|
},
|
|
1479
1588
|
async pull(controller) {
|
|
1480
1589
|
try {
|
|
1481
|
-
const chunk = await reader.read();
|
|
1590
|
+
const chunk = await (input.activity ? input.activity.run(() => reader.read()) : reader.read());
|
|
1482
1591
|
if (ended)
|
|
1483
1592
|
return;
|
|
1484
1593
|
if (chunk.done) {
|
|
@@ -1496,17 +1605,22 @@ function proxyProviderStream(input) {
|
|
|
1496
1605
|
} catch {
|
|
1497
1606
|
if (ended)
|
|
1498
1607
|
return;
|
|
1499
|
-
if (input.
|
|
1608
|
+
if (input.activity?.timedOut()) {
|
|
1609
|
+
input.interrupted?.("provider_idle_timeout");
|
|
1610
|
+
end(new Error("Provider stream timed out waiting for activity"));
|
|
1611
|
+
} else if (input.requestSignal.aborted || input.abort.signal.aborted || input.closing())
|
|
1500
1612
|
end();
|
|
1501
1613
|
else {
|
|
1502
|
-
input.interrupted?.();
|
|
1614
|
+
input.interrupted?.("stream_interrupted");
|
|
1503
1615
|
end(new Error("Provider stream ended unexpectedly"));
|
|
1504
1616
|
}
|
|
1617
|
+
await cancelReader();
|
|
1505
1618
|
}
|
|
1506
1619
|
},
|
|
1507
1620
|
async cancel() {
|
|
1508
1621
|
if (!ended) {
|
|
1509
1622
|
ended = true;
|
|
1623
|
+
input.activity?.finish();
|
|
1510
1624
|
input.release();
|
|
1511
1625
|
}
|
|
1512
1626
|
await cancelReader();
|
|
@@ -1518,6 +1632,58 @@ function proxyProviderStream(input) {
|
|
|
1518
1632
|
} };
|
|
1519
1633
|
}
|
|
1520
1634
|
|
|
1635
|
+
// src/provider-request.ts
|
|
1636
|
+
function createProviderRequest(requestSignal, abortSignal, timing = {}) {
|
|
1637
|
+
const idleTimeoutMs = timing.idleTimeoutMs ?? 240000;
|
|
1638
|
+
if (!Number.isFinite(idleTimeoutMs) || idleTimeoutMs <= 0)
|
|
1639
|
+
throw new Error("Invalid provider idle timeout.");
|
|
1640
|
+
const idle = new AbortController;
|
|
1641
|
+
const signal = AbortSignal.any([requestSignal, abortSignal, idle.signal]);
|
|
1642
|
+
let timer, finished = false, timedOut = false;
|
|
1643
|
+
const received = () => {
|
|
1644
|
+
clearTimeout(timer);
|
|
1645
|
+
timer = undefined;
|
|
1646
|
+
};
|
|
1647
|
+
const finish = () => {
|
|
1648
|
+
finished = true;
|
|
1649
|
+
received();
|
|
1650
|
+
signal.removeEventListener("abort", finish);
|
|
1651
|
+
};
|
|
1652
|
+
const waiting = () => {
|
|
1653
|
+
if (finished || signal.aborted || timer !== undefined)
|
|
1654
|
+
return;
|
|
1655
|
+
timer = setTimeout(() => {
|
|
1656
|
+
timedOut = true;
|
|
1657
|
+
idle.abort(new DOMException("Provider response idle timeout", "TimeoutError"));
|
|
1658
|
+
}, idleTimeoutMs);
|
|
1659
|
+
};
|
|
1660
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
1661
|
+
waiting();
|
|
1662
|
+
const run = async (operation) => {
|
|
1663
|
+
waiting();
|
|
1664
|
+
let onAbort;
|
|
1665
|
+
try {
|
|
1666
|
+
if (signal.aborted)
|
|
1667
|
+
throw signal.reason;
|
|
1668
|
+
const aborted = new Promise((_, reject) => {
|
|
1669
|
+
onAbort = () => reject(signal.reason);
|
|
1670
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
1671
|
+
});
|
|
1672
|
+
return await Promise.race([operation(), aborted]);
|
|
1673
|
+
} finally {
|
|
1674
|
+
if (onAbort)
|
|
1675
|
+
signal.removeEventListener("abort", onAbort);
|
|
1676
|
+
received();
|
|
1677
|
+
}
|
|
1678
|
+
};
|
|
1679
|
+
return {
|
|
1680
|
+
fetchOptions: { signal, timeout: false },
|
|
1681
|
+
run,
|
|
1682
|
+
finish,
|
|
1683
|
+
timedOut: () => timedOut
|
|
1684
|
+
};
|
|
1685
|
+
}
|
|
1686
|
+
|
|
1521
1687
|
// src/claude-context.ts
|
|
1522
1688
|
function claudeContextEnvironment(providerBaseUrl, environment = process.env) {
|
|
1523
1689
|
const explicit = environment.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
|
|
@@ -1598,15 +1764,15 @@ function openCodeInvocationModel(args, policy, defaultAgent) {
|
|
|
1598
1764
|
|
|
1599
1765
|
// src/gemini-config.ts
|
|
1600
1766
|
import { readFile, writeFile as writeFile3, lstat as lstat2, readdir as readdir2, symlink, realpath as realpath2 } from "fs/promises";
|
|
1601
|
-
import { join as
|
|
1602
|
-
import { homedir as
|
|
1767
|
+
import { join as join5, dirname as dirname3, resolve as resolve4, isAbsolute as isAbsolute5, relative as relative2, sep } from "path";
|
|
1768
|
+
import { homedir as homedir4 } from "os";
|
|
1603
1769
|
import { parseTree as parseTree2, getNodeValue } from "jsonc-parser";
|
|
1604
1770
|
|
|
1605
1771
|
// src/runtime.ts
|
|
1606
1772
|
import { randomBytes } from "crypto";
|
|
1607
1773
|
import { mkdir as mkdir4, lstat } from "fs/promises";
|
|
1608
|
-
import { homedir as
|
|
1609
|
-
import { isAbsolute as
|
|
1774
|
+
import { homedir as homedir3 } from "os";
|
|
1775
|
+
import { isAbsolute as isAbsolute4, join as join4, resolve as resolve3 } from "path";
|
|
1610
1776
|
|
|
1611
1777
|
// src/store.ts
|
|
1612
1778
|
var {SQL } = globalThis.Bun;
|
|
@@ -1771,7 +1937,7 @@ class Store {
|
|
|
1771
1937
|
|
|
1772
1938
|
// src/service.ts
|
|
1773
1939
|
import { createHash as createHash3, timingSafeEqual } from "crypto";
|
|
1774
|
-
import { z as
|
|
1940
|
+
import { z as z5 } from "zod";
|
|
1775
1941
|
|
|
1776
1942
|
// src/auth.ts
|
|
1777
1943
|
function authHeader(style, credential) {
|
|
@@ -2208,7 +2374,7 @@ var openapi_default = {
|
|
|
2208
2374
|
openapi: "3.0.3",
|
|
2209
2375
|
info: {
|
|
2210
2376
|
title: "Switcher API",
|
|
2211
|
-
version: "0.
|
|
2377
|
+
version: "0.2.0",
|
|
2212
2378
|
description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
|
|
2213
2379
|
},
|
|
2214
2380
|
security: [
|
|
@@ -3647,6 +3813,23 @@ var openapi_default = {
|
|
|
3647
3813
|
},
|
|
3648
3814
|
maxItems: 100
|
|
3649
3815
|
},
|
|
3816
|
+
reasoningEfforts: {
|
|
3817
|
+
type: "array",
|
|
3818
|
+
items: {
|
|
3819
|
+
type: "string",
|
|
3820
|
+
enum: [
|
|
3821
|
+
"none",
|
|
3822
|
+
"minimal",
|
|
3823
|
+
"low",
|
|
3824
|
+
"medium",
|
|
3825
|
+
"high",
|
|
3826
|
+
"xhigh",
|
|
3827
|
+
"max",
|
|
3828
|
+
"ultra"
|
|
3829
|
+
]
|
|
3830
|
+
},
|
|
3831
|
+
maxItems: 8
|
|
3832
|
+
},
|
|
3650
3833
|
supportedGenerationMethods: {
|
|
3651
3834
|
type: "array",
|
|
3652
3835
|
items: {
|
|
@@ -3726,6 +3909,23 @@ var openapi_default = {
|
|
|
3726
3909
|
},
|
|
3727
3910
|
maxItems: 100
|
|
3728
3911
|
},
|
|
3912
|
+
reasoningEfforts: {
|
|
3913
|
+
type: "array",
|
|
3914
|
+
items: {
|
|
3915
|
+
type: "string",
|
|
3916
|
+
enum: [
|
|
3917
|
+
"none",
|
|
3918
|
+
"minimal",
|
|
3919
|
+
"low",
|
|
3920
|
+
"medium",
|
|
3921
|
+
"high",
|
|
3922
|
+
"xhigh",
|
|
3923
|
+
"max",
|
|
3924
|
+
"ultra"
|
|
3925
|
+
]
|
|
3926
|
+
},
|
|
3927
|
+
maxItems: 8
|
|
3928
|
+
},
|
|
3729
3929
|
supportedGenerationMethods: {
|
|
3730
3930
|
type: "array",
|
|
3731
3931
|
items: {
|
|
@@ -3891,6 +4091,23 @@ var openapi_default = {
|
|
|
3891
4091
|
},
|
|
3892
4092
|
maxItems: 100
|
|
3893
4093
|
},
|
|
4094
|
+
reasoningEfforts: {
|
|
4095
|
+
type: "array",
|
|
4096
|
+
items: {
|
|
4097
|
+
type: "string",
|
|
4098
|
+
enum: [
|
|
4099
|
+
"none",
|
|
4100
|
+
"minimal",
|
|
4101
|
+
"low",
|
|
4102
|
+
"medium",
|
|
4103
|
+
"high",
|
|
4104
|
+
"xhigh",
|
|
4105
|
+
"max",
|
|
4106
|
+
"ultra"
|
|
4107
|
+
]
|
|
4108
|
+
},
|
|
4109
|
+
maxItems: 8
|
|
4110
|
+
},
|
|
3894
4111
|
supportedGenerationMethods: {
|
|
3895
4112
|
type: "array",
|
|
3896
4113
|
items: {
|
|
@@ -3970,6 +4187,23 @@ var openapi_default = {
|
|
|
3970
4187
|
},
|
|
3971
4188
|
maxItems: 100
|
|
3972
4189
|
},
|
|
4190
|
+
reasoningEfforts: {
|
|
4191
|
+
type: "array",
|
|
4192
|
+
items: {
|
|
4193
|
+
type: "string",
|
|
4194
|
+
enum: [
|
|
4195
|
+
"none",
|
|
4196
|
+
"minimal",
|
|
4197
|
+
"low",
|
|
4198
|
+
"medium",
|
|
4199
|
+
"high",
|
|
4200
|
+
"xhigh",
|
|
4201
|
+
"max",
|
|
4202
|
+
"ultra"
|
|
4203
|
+
]
|
|
4204
|
+
},
|
|
4205
|
+
maxItems: 8
|
|
4206
|
+
},
|
|
3973
4207
|
supportedGenerationMethods: {
|
|
3974
4208
|
type: "array",
|
|
3975
4209
|
items: {
|
|
@@ -4373,6 +4607,23 @@ var openapi_default = {
|
|
|
4373
4607
|
},
|
|
4374
4608
|
maxItems: 100
|
|
4375
4609
|
},
|
|
4610
|
+
reasoningEfforts: {
|
|
4611
|
+
type: "array",
|
|
4612
|
+
items: {
|
|
4613
|
+
type: "string",
|
|
4614
|
+
enum: [
|
|
4615
|
+
"none",
|
|
4616
|
+
"minimal",
|
|
4617
|
+
"low",
|
|
4618
|
+
"medium",
|
|
4619
|
+
"high",
|
|
4620
|
+
"xhigh",
|
|
4621
|
+
"max",
|
|
4622
|
+
"ultra"
|
|
4623
|
+
]
|
|
4624
|
+
},
|
|
4625
|
+
maxItems: 8
|
|
4626
|
+
},
|
|
4376
4627
|
supportedGenerationMethods: {
|
|
4377
4628
|
type: "array",
|
|
4378
4629
|
items: {
|
|
@@ -4517,6 +4768,19 @@ var openapi_default = {
|
|
|
4517
4768
|
maxLength: 300,
|
|
4518
4769
|
pattern: "^[^\\u0000-\\u001f\\u007f]+$"
|
|
4519
4770
|
},
|
|
4771
|
+
reasoningEffort: {
|
|
4772
|
+
type: "string",
|
|
4773
|
+
enum: [
|
|
4774
|
+
"none",
|
|
4775
|
+
"minimal",
|
|
4776
|
+
"low",
|
|
4777
|
+
"medium",
|
|
4778
|
+
"high",
|
|
4779
|
+
"xhigh",
|
|
4780
|
+
"max",
|
|
4781
|
+
"ultra"
|
|
4782
|
+
]
|
|
4783
|
+
},
|
|
4520
4784
|
decision: {
|
|
4521
4785
|
type: "string",
|
|
4522
4786
|
enum: [
|
|
@@ -4621,6 +4885,23 @@ var openapi_default = {
|
|
|
4621
4885
|
},
|
|
4622
4886
|
maxItems: 100
|
|
4623
4887
|
},
|
|
4888
|
+
reasoningEfforts: {
|
|
4889
|
+
type: "array",
|
|
4890
|
+
items: {
|
|
4891
|
+
type: "string",
|
|
4892
|
+
enum: [
|
|
4893
|
+
"none",
|
|
4894
|
+
"minimal",
|
|
4895
|
+
"low",
|
|
4896
|
+
"medium",
|
|
4897
|
+
"high",
|
|
4898
|
+
"xhigh",
|
|
4899
|
+
"max",
|
|
4900
|
+
"ultra"
|
|
4901
|
+
]
|
|
4902
|
+
},
|
|
4903
|
+
maxItems: 8
|
|
4904
|
+
},
|
|
4624
4905
|
supportedGenerationMethods: {
|
|
4625
4906
|
type: "array",
|
|
4626
4907
|
items: {
|
|
@@ -4739,6 +5020,23 @@ var openapi_default = {
|
|
|
4739
5020
|
},
|
|
4740
5021
|
maxItems: 100
|
|
4741
5022
|
},
|
|
5023
|
+
reasoningEfforts: {
|
|
5024
|
+
type: "array",
|
|
5025
|
+
items: {
|
|
5026
|
+
type: "string",
|
|
5027
|
+
enum: [
|
|
5028
|
+
"none",
|
|
5029
|
+
"minimal",
|
|
5030
|
+
"low",
|
|
5031
|
+
"medium",
|
|
5032
|
+
"high",
|
|
5033
|
+
"xhigh",
|
|
5034
|
+
"max",
|
|
5035
|
+
"ultra"
|
|
5036
|
+
]
|
|
5037
|
+
},
|
|
5038
|
+
maxItems: 8
|
|
5039
|
+
},
|
|
4742
5040
|
supportedGenerationMethods: {
|
|
4743
5041
|
type: "array",
|
|
4744
5042
|
items: {
|
|
@@ -4915,6 +5213,23 @@ var openapi_default = {
|
|
|
4915
5213
|
},
|
|
4916
5214
|
maxItems: 100
|
|
4917
5215
|
},
|
|
5216
|
+
reasoningEfforts: {
|
|
5217
|
+
type: "array",
|
|
5218
|
+
items: {
|
|
5219
|
+
type: "string",
|
|
5220
|
+
enum: [
|
|
5221
|
+
"none",
|
|
5222
|
+
"minimal",
|
|
5223
|
+
"low",
|
|
5224
|
+
"medium",
|
|
5225
|
+
"high",
|
|
5226
|
+
"xhigh",
|
|
5227
|
+
"max",
|
|
5228
|
+
"ultra"
|
|
5229
|
+
]
|
|
5230
|
+
},
|
|
5231
|
+
maxItems: 8
|
|
5232
|
+
},
|
|
4918
5233
|
supportedGenerationMethods: {
|
|
4919
5234
|
type: "array",
|
|
4920
5235
|
items: {
|
|
@@ -4994,6 +5309,23 @@ var openapi_default = {
|
|
|
4994
5309
|
},
|
|
4995
5310
|
maxItems: 100
|
|
4996
5311
|
},
|
|
5312
|
+
reasoningEfforts: {
|
|
5313
|
+
type: "array",
|
|
5314
|
+
items: {
|
|
5315
|
+
type: "string",
|
|
5316
|
+
enum: [
|
|
5317
|
+
"none",
|
|
5318
|
+
"minimal",
|
|
5319
|
+
"low",
|
|
5320
|
+
"medium",
|
|
5321
|
+
"high",
|
|
5322
|
+
"xhigh",
|
|
5323
|
+
"max",
|
|
5324
|
+
"ultra"
|
|
5325
|
+
]
|
|
5326
|
+
},
|
|
5327
|
+
maxItems: 8
|
|
5328
|
+
},
|
|
4997
5329
|
supportedGenerationMethods: {
|
|
4998
5330
|
type: "array",
|
|
4999
5331
|
items: {
|
|
@@ -5253,6 +5585,23 @@ var openapi_default = {
|
|
|
5253
5585
|
},
|
|
5254
5586
|
maxItems: 100
|
|
5255
5587
|
},
|
|
5588
|
+
reasoningEfforts: {
|
|
5589
|
+
type: "array",
|
|
5590
|
+
items: {
|
|
5591
|
+
type: "string",
|
|
5592
|
+
enum: [
|
|
5593
|
+
"none",
|
|
5594
|
+
"minimal",
|
|
5595
|
+
"low",
|
|
5596
|
+
"medium",
|
|
5597
|
+
"high",
|
|
5598
|
+
"xhigh",
|
|
5599
|
+
"max",
|
|
5600
|
+
"ultra"
|
|
5601
|
+
]
|
|
5602
|
+
},
|
|
5603
|
+
maxItems: 8
|
|
5604
|
+
},
|
|
5256
5605
|
supportedGenerationMethods: {
|
|
5257
5606
|
type: "array",
|
|
5258
5607
|
items: {
|
|
@@ -5504,6 +5853,19 @@ var openapi_default = {
|
|
|
5504
5853
|
maxLength: 300,
|
|
5505
5854
|
pattern: "^[^\\u0000-\\u001f\\u007f]+$"
|
|
5506
5855
|
},
|
|
5856
|
+
reasoningEffort: {
|
|
5857
|
+
type: "string",
|
|
5858
|
+
enum: [
|
|
5859
|
+
"none",
|
|
5860
|
+
"minimal",
|
|
5861
|
+
"low",
|
|
5862
|
+
"medium",
|
|
5863
|
+
"high",
|
|
5864
|
+
"xhigh",
|
|
5865
|
+
"max",
|
|
5866
|
+
"ultra"
|
|
5867
|
+
]
|
|
5868
|
+
},
|
|
5507
5869
|
decision: {
|
|
5508
5870
|
type: "string",
|
|
5509
5871
|
enum: [
|
|
@@ -5774,6 +6136,19 @@ var openapi_default = {
|
|
|
5774
6136
|
maxLength: 300,
|
|
5775
6137
|
pattern: "^[^\\u0000-\\u001f\\u007f]+$"
|
|
5776
6138
|
},
|
|
6139
|
+
reasoningEffort: {
|
|
6140
|
+
type: "string",
|
|
6141
|
+
enum: [
|
|
6142
|
+
"none",
|
|
6143
|
+
"minimal",
|
|
6144
|
+
"low",
|
|
6145
|
+
"medium",
|
|
6146
|
+
"high",
|
|
6147
|
+
"xhigh",
|
|
6148
|
+
"max",
|
|
6149
|
+
"ultra"
|
|
6150
|
+
]
|
|
6151
|
+
},
|
|
5777
6152
|
decision: {
|
|
5778
6153
|
type: "string",
|
|
5779
6154
|
enum: [
|
|
@@ -5982,10 +6357,10 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
5982
6357
|
const id2 = parts[2];
|
|
5983
6358
|
if (id2)
|
|
5984
6359
|
parse2(idSchema, id2);
|
|
5985
|
-
const page = () => parse2(
|
|
5986
|
-
limit:
|
|
5987
|
-
offset:
|
|
5988
|
-
search:
|
|
6360
|
+
const page = () => parse2(z5.object({
|
|
6361
|
+
limit: z5.coerce.number().int().min(1).max(1000).default(100),
|
|
6362
|
+
offset: z5.coerce.number().int().min(0).max(1e6).default(0),
|
|
6363
|
+
search: z5.string().max(200).default("")
|
|
5989
6364
|
}).strict(), Object.fromEntries(url.searchParams));
|
|
5990
6365
|
if (request.method === "GET") {
|
|
5991
6366
|
if (resource === "provider-presets" && parts.length <= 3)
|
|
@@ -6029,7 +6404,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
6029
6404
|
return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
|
|
6030
6405
|
let refreshed;
|
|
6031
6406
|
if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
|
|
6032
|
-
parse2(
|
|
6407
|
+
parse2(z5.object({}).strict(), body);
|
|
6033
6408
|
const provider = await store.get("providers", id2);
|
|
6034
6409
|
refreshed = { provider, catalog: await discover(provider, providerEnv, resolveCredential) };
|
|
6035
6410
|
}
|
|
@@ -6069,7 +6444,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
|
|
|
6069
6444
|
return store.put("catalogs", { id: id2, ...catalog }, old?.version, db);
|
|
6070
6445
|
}
|
|
6071
6446
|
if (resource === "launch-plans" && !id2 && request.method === "POST") {
|
|
6072
|
-
const { profileId } = parse2(
|
|
6447
|
+
const { profileId } = parse2(z5.object({ profileId: idSchema }).strict(), body);
|
|
6073
6448
|
const profile = await store.get("profiles", profileId, db);
|
|
6074
6449
|
const provider = await store.get("providers", profile.providerId, db);
|
|
6075
6450
|
validateHarnessProvider(profile.harness, provider);
|
|
@@ -6181,11 +6556,63 @@ async function startServer(options) {
|
|
|
6181
6556
|
}
|
|
6182
6557
|
|
|
6183
6558
|
// src/runtime.ts
|
|
6184
|
-
import { resolveCredential as resolveClientCredential, clientTransportEnvKeys, appConfigDiskValue, keychainConfigValue } from "@hasna/contracts/client";
|
|
6559
|
+
import { resolveCredential as resolveClientCredential, clientTransportEnvKeys as clientTransportEnvKeys2, appConfigDiskValue, keychainConfigValue } from "@hasna/contracts/client";
|
|
6560
|
+
|
|
6561
|
+
// src/lib/local-opt-in.ts
|
|
6562
|
+
import {
|
|
6563
|
+
clientTransportEnvKeys,
|
|
6564
|
+
credentialDiskSources,
|
|
6565
|
+
credentialOverrideEnvKey,
|
|
6566
|
+
credentialPointerEnvKey,
|
|
6567
|
+
CREDENTIAL_PROFILE_ENV_KEY
|
|
6568
|
+
} from "@hasna/contracts/client";
|
|
6569
|
+
var SWITCHER_LOCAL_OPT_IN_ENV_KEYS = ["HASNA_SWITCHER_LOCAL", "SWITCHER_LOCAL"];
|
|
6570
|
+
var SWITCHER_KEYCHAIN_ITEM = "hasna.credentials.switcher.api-key";
|
|
6571
|
+
var SWITCHER_CREDENTIALS_FILE = "~/.hasna/switcher/config/credentials";
|
|
6572
|
+
function isSwitcherLocalOptIn(env = process.env) {
|
|
6573
|
+
return SWITCHER_LOCAL_OPT_IN_ENV_KEYS.some((key) => (env[key] ?? "").trim() !== "");
|
|
6574
|
+
}
|
|
6575
|
+
function switcherAuthorityEnvKeys() {
|
|
6576
|
+
const keys = clientTransportEnvKeys("switcher");
|
|
6577
|
+
return [
|
|
6578
|
+
...keys.apiUrlKeys,
|
|
6579
|
+
...keys.apiKeyKeys,
|
|
6580
|
+
credentialOverrideEnvKey("switcher"),
|
|
6581
|
+
credentialPointerEnvKey("switcher"),
|
|
6582
|
+
CREDENTIAL_PROFILE_ENV_KEY
|
|
6583
|
+
];
|
|
6584
|
+
}
|
|
6585
|
+
function hasSwitcherEnvAuthorityIntent(env = process.env) {
|
|
6586
|
+
return switcherAuthorityEnvKeys().some((key) => env[key] !== undefined);
|
|
6587
|
+
}
|
|
6588
|
+
function switcherCredentialSources(env = process.env) {
|
|
6589
|
+
const disk = credentialDiskSources("switcher", env)[0];
|
|
6590
|
+
return [
|
|
6591
|
+
`Keychain item ${SWITCHER_KEYCHAIN_ITEM}`,
|
|
6592
|
+
disk ? `${SWITCHER_CREDENTIALS_FILE} (${disk})` : SWITCHER_CREDENTIALS_FILE,
|
|
6593
|
+
`${clientTransportEnvKeys("switcher").apiKeyKeys[0] ?? "HASNA_SWITCHER_API_KEY"} in the environment`
|
|
6594
|
+
];
|
|
6595
|
+
}
|
|
6596
|
+
function remoteConfigMissingMessage(env = process.env) {
|
|
6597
|
+
return `No Switcher API credential is configured; consulted ${switcherCredentialSources(env).join(", ")}. ` + `Configure one of them, or set ${SWITCHER_LOCAL_OPT_IN_ENV_KEYS[0]}=1 (alias ${SWITCHER_LOCAL_OPT_IN_ENV_KEYS[1]}=1) to deliberately use the on-box local store. Nothing was read or created locally.`;
|
|
6598
|
+
}
|
|
6599
|
+
var announced = false;
|
|
6600
|
+
function announceSwitcherLocalMode(home, write = (line) => {
|
|
6601
|
+
process.stderr.write(line);
|
|
6602
|
+
}) {
|
|
6603
|
+
if (announced)
|
|
6604
|
+
return;
|
|
6605
|
+
announced = true;
|
|
6606
|
+
write(`switcher: LOCAL mode \u2014 using the on-box store under ${home} behind an owned per-process loopback API, not a hosted Switcher API (${SWITCHER_LOCAL_OPT_IN_ENV_KEYS[0]} is set; a configured API URL or key would outrank it).
|
|
6607
|
+
`);
|
|
6608
|
+
}
|
|
6609
|
+
|
|
6610
|
+
// src/runtime.ts
|
|
6611
|
+
var REMOTE_API_CONFIG_MISSING = "remote_api_config_missing";
|
|
6185
6612
|
function switcherHome(env = process.env) {
|
|
6186
6613
|
const override = env.HASNA_HOME?.trim();
|
|
6187
|
-
const root = override &&
|
|
6188
|
-
return resolve3(env.HASNA_SWITCHER_HOME ??
|
|
6614
|
+
const root = override && isAbsolute4(override) ? override : join4(env.HOME?.trim() || homedir3(), ".hasna");
|
|
6615
|
+
return resolve3(env.HASNA_SWITCHER_HOME ?? join4(root, "switcher"));
|
|
6189
6616
|
}
|
|
6190
6617
|
async function privateDirectory(path) {
|
|
6191
6618
|
await mkdir4(path, { recursive: true, mode: 448 });
|
|
@@ -6197,20 +6624,25 @@ async function privateDirectory(path) {
|
|
|
6197
6624
|
}
|
|
6198
6625
|
async function openCliRuntime(env = process.env, resolveCredential) {
|
|
6199
6626
|
const providerEnv = Object.fromEntries(Object.entries(env).filter(([name]) => name.startsWith("SWITCHER_PROVIDER_")));
|
|
6200
|
-
const
|
|
6201
|
-
|
|
6202
|
-
|
|
6203
|
-
if (
|
|
6204
|
-
|
|
6627
|
+
const remote = () => ({ client: clientFromEnv(env), mode: "remote", providerEnv, close: async () => {} });
|
|
6628
|
+
if (hasSwitcherEnvAuthorityIntent(env))
|
|
6629
|
+
return remote();
|
|
6630
|
+
if (!isSwitcherLocalOptIn(env)) {
|
|
6631
|
+
const keys = clientTransportEnvKeys2("switcher");
|
|
6632
|
+
const configured = resolveClientCredential("switcher", env) || keychainConfigValue("switcher", env) || appConfigDiskValue("switcher", env, keys.apiUrlKeys);
|
|
6633
|
+
if (configured)
|
|
6634
|
+
return remote();
|
|
6635
|
+
throw new Fault(401, REMOTE_API_CONFIG_MISSING, remoteConfigMissingMessage(env));
|
|
6205
6636
|
}
|
|
6206
6637
|
const home = switcherHome(env);
|
|
6638
|
+
announceSwitcherLocalMode(home);
|
|
6207
6639
|
if (!env.HASNA_SWITCHER_DATABASE_URL && !env.HASNA_SWITCHER_SQLITE_PATH)
|
|
6208
6640
|
await privateDirectory(home);
|
|
6209
6641
|
const apiKey = randomBytes(32).toString("base64url");
|
|
6210
6642
|
const service = await startServer({
|
|
6211
6643
|
apiKey,
|
|
6212
6644
|
databaseUrl: env.HASNA_SWITCHER_DATABASE_URL,
|
|
6213
|
-
sqlitePath: env.HASNA_SWITCHER_SQLITE_PATH ?? (env.HASNA_SWITCHER_DATABASE_URL ? undefined :
|
|
6645
|
+
sqlitePath: env.HASNA_SWITCHER_SQLITE_PATH ?? (env.HASNA_SWITCHER_DATABASE_URL ? undefined : join4(home, "switcher.db")),
|
|
6214
6646
|
providerEnv,
|
|
6215
6647
|
resolveCredential
|
|
6216
6648
|
});
|
|
@@ -6303,8 +6735,8 @@ var nativeModels = ["gemini-3.1-flash-lite", "gemini-3.1-pro-preview", "gemini-3
|
|
|
6303
6735
|
var object2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
6304
6736
|
async function regular(path, limit = 2 * 1024 * 1024) {
|
|
6305
6737
|
try {
|
|
6306
|
-
const
|
|
6307
|
-
if (!
|
|
6738
|
+
const stat4 = await lstat2(path);
|
|
6739
|
+
if (!stat4.isFile() || stat4.size > limit)
|
|
6308
6740
|
throw new Error("unsupported");
|
|
6309
6741
|
return true;
|
|
6310
6742
|
} catch (error) {
|
|
@@ -6357,12 +6789,12 @@ function originalPaths(value, home) {
|
|
|
6357
6789
|
return result;
|
|
6358
6790
|
}
|
|
6359
6791
|
async function validateGeminiConfiguration(cwd, env = process.env) {
|
|
6360
|
-
const home = env.GEMINI_CLI_HOME ?? env.HOME ??
|
|
6361
|
-
if (!
|
|
6792
|
+
const home = env.GEMINI_CLI_HOME ?? env.HOME ?? homedir4();
|
|
6793
|
+
if (!isAbsolute5(home))
|
|
6362
6794
|
throw new Error("Gemini requires an absolute native home.");
|
|
6363
6795
|
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");
|
|
6364
|
-
const defaultsPath = env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ??
|
|
6365
|
-
const paths = [defaultsPath,
|
|
6796
|
+
const defaultsPath = env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ?? join5(dirname3(systemPath), "system-defaults.json");
|
|
6797
|
+
const paths = [defaultsPath, join5(home, ".gemini", "settings.json"), join5(resolve4(cwd), ".gemini", "settings.json"), systemPath];
|
|
6366
6798
|
const values2 = [];
|
|
6367
6799
|
for (const path of paths) {
|
|
6368
6800
|
const value = await settings(path);
|
|
@@ -6373,7 +6805,7 @@ async function validateGeminiConfiguration(cwd, env = process.env) {
|
|
|
6373
6805
|
if (values2[2][key]?.some?.((path) => typeof path === "string" && (path === "~" || path.startsWith("~/"))))
|
|
6374
6806
|
throw new Error("Gemini project policy paths using ~ must use an absolute path so workspace trust remains authoritative under an isolated native home.");
|
|
6375
6807
|
const contextNames = [...new Set(["GEMINI.md", ...values2.flatMap((value) => [value.context?.fileName ?? []].flat())])];
|
|
6376
|
-
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 ??
|
|
6808
|
+
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") };
|
|
6377
6809
|
}
|
|
6378
6810
|
async function snapshotFile(source, destination) {
|
|
6379
6811
|
if (await regular(source))
|
|
@@ -6382,8 +6814,8 @@ async function snapshotFile(source, destination) {
|
|
|
6382
6814
|
async function snapshotPolicies(source, destination) {
|
|
6383
6815
|
let entries;
|
|
6384
6816
|
try {
|
|
6385
|
-
const
|
|
6386
|
-
if (!
|
|
6817
|
+
const stat4 = await lstat2(source);
|
|
6818
|
+
if (!stat4.isDirectory() || stat4.isSymbolicLink())
|
|
6387
6819
|
throw new Error("Unsupported Gemini policy directory");
|
|
6388
6820
|
entries = await readdir2(source, { withFileTypes: true });
|
|
6389
6821
|
} catch (error) {
|
|
@@ -6396,12 +6828,12 @@ async function snapshotPolicies(source, destination) {
|
|
|
6396
6828
|
throw new Error("Gemini user policy directory exceeds the snapshot limit.");
|
|
6397
6829
|
for (const entry of entries) {
|
|
6398
6830
|
if (entry.name.endsWith(".toml"))
|
|
6399
|
-
await snapshotFile(
|
|
6831
|
+
await snapshotFile(join5(source, entry.name), join5(destination, entry.name));
|
|
6400
6832
|
}
|
|
6401
6833
|
}
|
|
6402
6834
|
async function snapshotContext(sourceDir, destinationDir, names) {
|
|
6403
6835
|
const root = await realpath2(sourceDir), files = new Map;
|
|
6404
|
-
const importsDir =
|
|
6836
|
+
const importsDir = join5(destinationDir, ".switcher-context");
|
|
6405
6837
|
let bytes = 0;
|
|
6406
6838
|
const copy = async (source, destination) => {
|
|
6407
6839
|
if (files.has(source))
|
|
@@ -6422,9 +6854,9 @@ async function snapshotContext(sourceDir, destinationDir, names) {
|
|
|
6422
6854
|
if (code.some(([a, b]) => start >= a && start < b))
|
|
6423
6855
|
continue;
|
|
6424
6856
|
const imported = resolve4(dirname3(source), match[2]), actual = await realpath2(imported).catch(() => imported), within = relative2(root, actual);
|
|
6425
|
-
if (within === ".." || within.startsWith(".." + sep) ||
|
|
6857
|
+
if (within === ".." || within.startsWith(".." + sep) || isAbsolute5(within))
|
|
6426
6858
|
throw new Error("Gemini global context imports outside the original context directory require a supported explicit context location.");
|
|
6427
|
-
const target = files.get(imported) ??
|
|
6859
|
+
const target = files.get(imported) ?? join5(importsDir, `${files.size}.md`);
|
|
6428
6860
|
await privateDirectory(importsDir);
|
|
6429
6861
|
await copy(imported, target);
|
|
6430
6862
|
output += text.slice(last, start) + "@./" + relative2(dirname3(destination), target).split(sep).join("/");
|
|
@@ -6433,30 +6865,30 @@ async function snapshotContext(sourceDir, destinationDir, names) {
|
|
|
6433
6865
|
await writeFile3(destination, output + text.slice(last), { mode: 384, flag: "wx" });
|
|
6434
6866
|
};
|
|
6435
6867
|
for (const name of names)
|
|
6436
|
-
if (await regular(
|
|
6437
|
-
await copy(
|
|
6868
|
+
if (await regular(join5(sourceDir, name)))
|
|
6869
|
+
await copy(join5(sourceDir, name), join5(destinationDir, name));
|
|
6438
6870
|
}
|
|
6439
6871
|
async function prepareGemini(input) {
|
|
6440
6872
|
const original = await validateGeminiConfiguration(input.cwd);
|
|
6441
|
-
const home =
|
|
6873
|
+
const home = join5(input.stateDir, "gemini-home"), dir = join5(home, ".gemini");
|
|
6442
6874
|
await privateDirectory(home);
|
|
6443
6875
|
await privateDirectory(dir);
|
|
6444
|
-
const durable =
|
|
6876
|
+
const durable = join5(input.sessionDir ?? join5(input.stateDir, "sessions"), "gemini-home", ".gemini");
|
|
6445
6877
|
await privateDirectory(durable);
|
|
6446
6878
|
for (const name of ["tmp", "history"]) {
|
|
6447
|
-
const target =
|
|
6879
|
+
const target = join5(durable, name);
|
|
6448
6880
|
await privateDirectory(target);
|
|
6449
|
-
await symlink(target,
|
|
6881
|
+
await symlink(target, join5(dir, name), "dir");
|
|
6450
6882
|
}
|
|
6451
|
-
await snapshotFile(original.trustPath,
|
|
6452
|
-
await snapshotPolicies(
|
|
6883
|
+
await snapshotFile(original.trustPath, join5(dir, "trustedFolders.json"));
|
|
6884
|
+
await snapshotPolicies(join5(original.home, ".gemini", "policies"), join5(dir, "policies"));
|
|
6453
6885
|
try {
|
|
6454
|
-
await snapshotContext(
|
|
6886
|
+
await snapshotContext(join5(original.home, ".gemini"), dir, original.contextNames);
|
|
6455
6887
|
} catch (error) {
|
|
6456
6888
|
if (error.code !== "ENOENT")
|
|
6457
6889
|
throw error;
|
|
6458
6890
|
}
|
|
6459
|
-
const defaults =
|
|
6891
|
+
const defaults = join5(input.stateDir, "gemini-system-defaults.json"), system = join5(input.stateDir, "gemini-system.json"), user = join5(dir, "settings.json");
|
|
6460
6892
|
const modelPolicy = compileGeminiModelPolicy(input.model, input.models, input.compiledPolicy ?? compileModelPolicy(input.model, input.models, input.modelPolicy));
|
|
6461
6893
|
const modelDefinitions = { ...Object.fromEntries(nativeModels.map((id2) => [id2, { isVisible: false }])), ...modelPolicy.modelConfigs.modelDefinitions };
|
|
6462
6894
|
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 } };
|
|
@@ -6471,7 +6903,7 @@ async function prepareGemini(input) {
|
|
|
6471
6903
|
GEMINI_CLI_HOME: home,
|
|
6472
6904
|
GEMINI_CLI_SYSTEM_SETTINGS_PATH: system,
|
|
6473
6905
|
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: defaults,
|
|
6474
|
-
GEMINI_CLI_TRUSTED_FOLDERS_PATH:
|
|
6906
|
+
GEMINI_CLI_TRUSTED_FOLDERS_PATH: join5(dir, "trustedFolders.json"),
|
|
6475
6907
|
GEMINI_API_KEY: input.credential,
|
|
6476
6908
|
GOOGLE_API_KEY: "",
|
|
6477
6909
|
GOOGLE_GEMINI_BASE_URL: input.baseUrl.replace(/\/v1beta\/?$/i, ""),
|
|
@@ -6499,12 +6931,12 @@ async function prepareGemini(input) {
|
|
|
6499
6931
|
|
|
6500
6932
|
// src/gemini-bridge.ts
|
|
6501
6933
|
import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
6502
|
-
function geminiBridge(input) {
|
|
6934
|
+
function geminiBridge(input, timing = {}) {
|
|
6503
6935
|
const token = crypto.randomUUID() + crypto.randomUUID(), digest = (value) => createHash4("sha256").update(value).digest(), expected = digest(token);
|
|
6504
6936
|
const models = new Set(input.models.map((model) => model.id));
|
|
6505
6937
|
let closing = false, stopped;
|
|
6506
6938
|
const active = new Set;
|
|
6507
|
-
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request) {
|
|
6939
|
+
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
|
|
6508
6940
|
const fail = (status, message) => Response.json({ error: { code: status, message } }, { status });
|
|
6509
6941
|
if (closing)
|
|
6510
6942
|
return fail(503, "Bridge is closing");
|
|
@@ -6544,15 +6976,20 @@ function geminiBridge(input) {
|
|
|
6544
6976
|
const record2 = { abort: new AbortController, done: new Promise((resolve5) => {
|
|
6545
6977
|
complete = resolve5;
|
|
6546
6978
|
}) };
|
|
6979
|
+
const activity = createProviderRequest(request.signal, record2.abort.signal, timing);
|
|
6547
6980
|
const release = () => {
|
|
6981
|
+
activity.finish();
|
|
6548
6982
|
active.delete(record2);
|
|
6549
6983
|
complete();
|
|
6550
6984
|
};
|
|
6551
6985
|
active.add(record2);
|
|
6986
|
+
server2.timeout(request, 0);
|
|
6552
6987
|
try {
|
|
6553
|
-
const response = await fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual",
|
|
6988
|
+
const response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
|
|
6554
6989
|
if (!response.ok) {
|
|
6555
|
-
|
|
6990
|
+
response.body?.cancel().catch(() => {
|
|
6991
|
+
return;
|
|
6992
|
+
});
|
|
6556
6993
|
release();
|
|
6557
6994
|
return fail(response.status >= 300 && response.status < 400 ? 502 : response.status, `Provider returned HTTP ${response.status}`);
|
|
6558
6995
|
}
|
|
@@ -6560,12 +6997,12 @@ function geminiBridge(input) {
|
|
|
6560
6997
|
release();
|
|
6561
6998
|
return new Response(null, { status: response.status });
|
|
6562
6999
|
}
|
|
6563
|
-
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record2.abort, closing: () => closing, release });
|
|
7000
|
+
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record2.abort, closing: () => closing, release, activity });
|
|
6564
7001
|
record2.cancel = cancel;
|
|
6565
7002
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
6566
7003
|
} catch {
|
|
6567
7004
|
release();
|
|
6568
|
-
return fail(502, "Provider request failed");
|
|
7005
|
+
return fail(activity.timedOut() ? 504 : 502, activity.timedOut() ? "Provider request timed out waiting for activity" : "Provider request failed");
|
|
6569
7006
|
}
|
|
6570
7007
|
} });
|
|
6571
7008
|
return { baseUrl: new URL("v1beta", server.url).href, token, cleanup: () => stopped ??= (async () => {
|
|
@@ -6709,10 +7146,24 @@ async function isContextOverflow(response) {
|
|
|
6709
7146
|
}
|
|
6710
7147
|
}
|
|
6711
7148
|
|
|
7149
|
+
// src/codex-delegation.ts
|
|
7150
|
+
function normalizeCodexDelegation(body) {
|
|
7151
|
+
if (!Array.isArray(body.input))
|
|
7152
|
+
return body;
|
|
7153
|
+
return { ...body, input: body.input.map((item) => {
|
|
7154
|
+
if (item?.type !== "function_call_output" || item.namespace !== "codex_app" || item.call_id != null)
|
|
7155
|
+
return item;
|
|
7156
|
+
const content = typeof item.output === "string" ? [{ type: "input_text", text: item.output }] : item.output;
|
|
7157
|
+
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"))))
|
|
7158
|
+
throw new Fault(400, "unsupported_task_message_content", "The task message contains content this provider route cannot represent.");
|
|
7159
|
+
return { type: "message", role: "user", content };
|
|
7160
|
+
}) };
|
|
7161
|
+
}
|
|
7162
|
+
|
|
6712
7163
|
// src/inference-gateway.ts
|
|
6713
7164
|
import { createHash as createHash5, timingSafeEqual as timingSafeEqual3 } from "crypto";
|
|
6714
7165
|
var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
|
|
6715
|
-
function createInferenceGateway(input) {
|
|
7166
|
+
function createInferenceGateway(input, timing = {}) {
|
|
6716
7167
|
const token = crypto.randomUUID() + crypto.randomUUID();
|
|
6717
7168
|
const digest = (value) => createHash5("sha256").update(value).digest();
|
|
6718
7169
|
const expected = digest(token), policy = input.compiledPolicy;
|
|
@@ -6721,7 +7172,7 @@ function createInferenceGateway(input) {
|
|
|
6721
7172
|
const fail = (status, code) => Response.json({ error: { type: "switcher_model_policy", code, message: code === "model_not_allowed" ? "This model is outside the launch policy. Select it with switcher launch --model or explicitly assign an allowed role model." : `Switcher inference gateway: ${code}.` } }, { status });
|
|
6722
7173
|
let closing = false, stopped;
|
|
6723
7174
|
const active = new Set;
|
|
6724
|
-
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request) {
|
|
7175
|
+
const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
|
|
6725
7176
|
if (closing)
|
|
6726
7177
|
return fail(503, "closing");
|
|
6727
7178
|
const credential = request.headers.get("x-goog-api-key") ?? request.headers.get("x-api-key") ?? request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
|
|
@@ -6757,6 +7208,9 @@ function createInferenceGateway(input) {
|
|
|
6757
7208
|
}
|
|
6758
7209
|
const requestId = crypto.randomUUID();
|
|
6759
7210
|
const event = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), decision: "reject" };
|
|
7211
|
+
const effort = reasoningEffortSchema.safeParse(body.reasoning?.effort);
|
|
7212
|
+
if (effort.success)
|
|
7213
|
+
event.reasoningEffort = effort.data;
|
|
6760
7214
|
const emit = () => input.onRoutingEvent?.(event);
|
|
6761
7215
|
let resolved;
|
|
6762
7216
|
try {
|
|
@@ -6791,13 +7245,16 @@ function createInferenceGateway(input) {
|
|
|
6791
7245
|
const abort = new AbortController;
|
|
6792
7246
|
let complete;
|
|
6793
7247
|
const record2 = { abort, done: new Promise((r) => complete = r) };
|
|
7248
|
+
const activity = createProviderRequest(request.signal, abort.signal, timing);
|
|
6794
7249
|
const release = () => {
|
|
7250
|
+
activity.finish();
|
|
6795
7251
|
flush();
|
|
6796
7252
|
active.delete(record2);
|
|
6797
7253
|
complete();
|
|
6798
7254
|
};
|
|
6799
7255
|
active.add(record2);
|
|
6800
|
-
const signal =
|
|
7256
|
+
const signal = activity.fetchOptions.signal;
|
|
7257
|
+
server2.timeout(request, 0);
|
|
6801
7258
|
const headers = { "content-type": "application/json" };
|
|
6802
7259
|
if (input.credential) {
|
|
6803
7260
|
const [name, value] = gemini ? ["x-goog-api-key", input.credential] : authHeader(input.authStyle ?? "bearer", input.credential);
|
|
@@ -6820,7 +7277,7 @@ function createInferenceGateway(input) {
|
|
|
6820
7277
|
throw new Fault(422, "model_expired", "Selected model has expired.");
|
|
6821
7278
|
if (attempt) {
|
|
6822
7279
|
flush();
|
|
6823
|
-
current = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), resolvedModel: model, decision: "fallback", reason: "explicit_transient_fallback" };
|
|
7280
|
+
current = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), resolvedModel: model, decision: "fallback", reason: "explicit_transient_fallback", ...effort.success ? { reasoningEffort: effort.data } : {} };
|
|
6824
7281
|
}
|
|
6825
7282
|
const payload = structuredClone(body);
|
|
6826
7283
|
if (gemini) {
|
|
@@ -6831,19 +7288,22 @@ function createInferenceGateway(input) {
|
|
|
6831
7288
|
} else
|
|
6832
7289
|
payload.model = model;
|
|
6833
7290
|
const guidance = renderModelGuidance({ harness: input.harness, providerId: input.providerId, baseUrl: input.baseUrl, model, compiled: policy, catalogPath: input.catalogPath });
|
|
6834
|
-
const
|
|
7291
|
+
const compatible2 = input.harness === "codex" && input.protocol === "openai-responses" && new URL(input.baseUrl).hostname !== "api.openai.com" ? normalizeCodexDelegation(payload) : payload;
|
|
7292
|
+
const outgoing = injectModelGuidance(input.protocol, compatible2, guidance, match?.[2]);
|
|
6835
7293
|
const path = gemini ? `/models/${encodeURIComponent(model)}:${match[2]}${url.search}` : suffix + (betaQuery ? "?beta=true" : "");
|
|
6836
7294
|
try {
|
|
6837
|
-
response = await fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(outgoing), redirect: "manual",
|
|
7295
|
+
response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(outgoing), redirect: "manual", ...activity.fetchOptions }));
|
|
6838
7296
|
} catch {
|
|
6839
|
-
current.reason = signal.aborted ? "request_cancelled" : "network_error";
|
|
7297
|
+
current.reason = activity.timedOut() ? "provider_idle_timeout" : signal.aborted ? "request_cancelled" : "network_error";
|
|
6840
7298
|
if (!signal.aborted && attempt + 1 < candidates.length)
|
|
6841
7299
|
continue;
|
|
6842
7300
|
throw new Error("provider_request_failed");
|
|
6843
7301
|
}
|
|
6844
7302
|
current.upstreamStatus = response.status;
|
|
6845
7303
|
if ((response.status === 429 || response.status >= 500) && attempt + 1 < candidates.length) {
|
|
6846
|
-
|
|
7304
|
+
response.body?.cancel().catch(() => {
|
|
7305
|
+
return;
|
|
7306
|
+
});
|
|
6847
7307
|
response = undefined;
|
|
6848
7308
|
continue;
|
|
6849
7309
|
}
|
|
@@ -6898,16 +7358,18 @@ function createInferenceGateway(input) {
|
|
|
6898
7358
|
if (done && buffer)
|
|
6899
7359
|
observe(buffer);
|
|
6900
7360
|
};
|
|
6901
|
-
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort, closing: () => closing, release, inspect, interrupted: () => {
|
|
6902
|
-
current.reason =
|
|
7361
|
+
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort, closing: () => closing, release, activity, inspect, interrupted: (reason) => {
|
|
7362
|
+
current.reason = reason;
|
|
6903
7363
|
} });
|
|
6904
7364
|
record2.cancel = cancel;
|
|
6905
7365
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
6906
7366
|
} catch (error) {
|
|
6907
7367
|
if (error instanceof Fault)
|
|
6908
7368
|
current.reason = error.code;
|
|
7369
|
+
else if (activity.timedOut())
|
|
7370
|
+
current.reason = "provider_idle_timeout";
|
|
6909
7371
|
release();
|
|
6910
|
-
return fail(error instanceof Fault ? error.status : 502, error instanceof Fault ? error.code : "provider_request_failed");
|
|
7372
|
+
return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : "provider_request_failed");
|
|
6911
7373
|
}
|
|
6912
7374
|
} });
|
|
6913
7375
|
return { baseUrl: new URL(input.protocol === "gemini-generate-content" ? "v1beta" : "v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
|
|
@@ -6924,8 +7386,8 @@ function createInferenceGateway(input) {
|
|
|
6924
7386
|
}
|
|
6925
7387
|
|
|
6926
7388
|
// src/codex-model-policy.ts
|
|
6927
|
-
import { mkdir as mkdir5, readFile as readFile2, realpath as realpath3, stat as
|
|
6928
|
-
import { dirname as dirname4, isAbsolute as
|
|
7389
|
+
import { mkdir as mkdir5, readFile as readFile2, realpath as realpath3, stat as stat4, writeFile as writeFile4 } from "fs/promises";
|
|
7390
|
+
import { dirname as dirname4, isAbsolute as isAbsolute6, join as join6, resolve as resolve5 } from "path";
|
|
6929
7391
|
import { execFileSync as execFileSync2 } from "child_process";
|
|
6930
7392
|
import { createHash as createHash6 } from "crypto";
|
|
6931
7393
|
var dict = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
@@ -6945,7 +7407,7 @@ function codexAgentsFromEffectiveConfig(config, trustedProject = true, baseDir)
|
|
|
6945
7407
|
const rawConfigFile = value.config_file;
|
|
6946
7408
|
if (rawConfigFile !== undefined && typeof rawConfigFile !== "string")
|
|
6947
7409
|
throw new Error(`Codex agents.${name}.config_file must be a string.`);
|
|
6948
|
-
const configFile = rawConfigFile === undefined ? undefined :
|
|
7410
|
+
const configFile = rawConfigFile === undefined ? undefined : isAbsolute6(rawConfigFile) ? rawConfigFile : baseDir ? resolve5(baseDir, rawConfigFile) : undefined;
|
|
6949
7411
|
if (rawConfigFile !== undefined && !configFile)
|
|
6950
7412
|
throw new Error(`Codex agents.${name}.config_file must be absolute after precedence resolution.`);
|
|
6951
7413
|
const definition = { trusted: trustedProject, config_file: configFile };
|
|
@@ -7074,20 +7536,20 @@ async function writeCodexAgentOverrides(result, stateDir) {
|
|
|
7074
7536
|
const paths = {};
|
|
7075
7537
|
for (const agent of result.agents) {
|
|
7076
7538
|
const digest = createHash6("sha256").update(agent.name).digest("hex").slice(0, 16);
|
|
7077
|
-
const path =
|
|
7539
|
+
const path = join6(root, `agent-${digest}.toml`);
|
|
7078
7540
|
await writeFile4(path, renderCodexAgentToml(agent.config), { encoding: "utf8", mode: 384, flag: "wx" });
|
|
7079
7541
|
paths[agent.name] = path;
|
|
7080
7542
|
}
|
|
7081
7543
|
return paths;
|
|
7082
7544
|
}
|
|
7083
7545
|
async function prepareCodexModelPolicy(input) {
|
|
7084
|
-
const home = resolve5(input.home ?? process.env.CODEX_HOME ??
|
|
7546
|
+
const home = resolve5(input.home ?? process.env.CODEX_HOME ?? join6(process.env.HOME ?? "/", ".codex"));
|
|
7085
7547
|
const cwd = resolve5(input.cwd);
|
|
7086
|
-
const globalPath =
|
|
7548
|
+
const globalPath = join6(home, "config.toml");
|
|
7087
7549
|
const readConfig = async (path) => {
|
|
7088
7550
|
let info;
|
|
7089
7551
|
try {
|
|
7090
|
-
info = await
|
|
7552
|
+
info = await stat4(path);
|
|
7091
7553
|
} catch (error) {
|
|
7092
7554
|
if (error.code === "ENOENT")
|
|
7093
7555
|
return;
|
|
@@ -7107,7 +7569,7 @@ async function prepareCodexModelPolicy(input) {
|
|
|
7107
7569
|
const global = await readConfig(globalPath) ?? {};
|
|
7108
7570
|
const projects = dict(global.projects) ? global.projects : {};
|
|
7109
7571
|
const markers = global.project_root_markers ?? [".git"];
|
|
7110
|
-
if (!Array.isArray(markers) || markers.some((m) => typeof m !== "string" ||
|
|
7572
|
+
if (!Array.isArray(markers) || markers.some((m) => typeof m !== "string" || isAbsolute6(m) || m.includes("..")))
|
|
7111
7573
|
throw new Error("Unsupported Codex project root markers.");
|
|
7112
7574
|
const ancestorDirs = [];
|
|
7113
7575
|
for (let dir = cwd;; dir = dirname4(dir)) {
|
|
@@ -7120,9 +7582,9 @@ async function prepareCodexModelPolicy(input) {
|
|
|
7120
7582
|
for (const dir of ancestorDirs)
|
|
7121
7583
|
for (const marker of markers) {
|
|
7122
7584
|
try {
|
|
7123
|
-
const info = await
|
|
7585
|
+
const info = await stat4(join6(dir, marker));
|
|
7124
7586
|
if (marker === ".git" && info.isDirectory())
|
|
7125
|
-
await
|
|
7587
|
+
await stat4(join6(dir, marker, "HEAD"));
|
|
7126
7588
|
projectRoot = dir;
|
|
7127
7589
|
break findRoot;
|
|
7128
7590
|
} catch {}
|
|
@@ -7147,7 +7609,7 @@ async function prepareCodexModelPolicy(input) {
|
|
|
7147
7609
|
const layers = [{ path: globalPath, config: global }];
|
|
7148
7610
|
const projectDirs = ancestorDirs.slice(0, ancestorDirs.indexOf(projectRoot) + 1).reverse();
|
|
7149
7611
|
for (const dir of projectDirs) {
|
|
7150
|
-
const path =
|
|
7612
|
+
const path = join6(dir, ".codex", "config.toml");
|
|
7151
7613
|
if (path === globalPath)
|
|
7152
7614
|
continue;
|
|
7153
7615
|
const decision = await trust(dir) ?? projectTrust ?? repoTrust;
|
|
@@ -7176,10 +7638,10 @@ async function prepareCodexModelPolicy(input) {
|
|
|
7176
7638
|
return { ...result, agentConfigPaths: await writeCodexAgentOverrides(result, input.stateDir), configPaths: loaded };
|
|
7177
7639
|
}
|
|
7178
7640
|
async function readCodexAgentConfig(path) {
|
|
7179
|
-
if (!
|
|
7641
|
+
if (!isAbsolute6(path))
|
|
7180
7642
|
throw new Error("Codex agent config_file must be absolute before launch.");
|
|
7181
7643
|
const canonical = await realpath3(path);
|
|
7182
|
-
const info = await
|
|
7644
|
+
const info = await stat4(canonical);
|
|
7183
7645
|
if (!info.isFile() || info.size > 1024 * 1024)
|
|
7184
7646
|
throw new Error(`Codex agent config must be a regular file no larger than 1 MiB: ${path}`);
|
|
7185
7647
|
const text = await readFile2(canonical, "utf8");
|
|
@@ -7191,27 +7653,27 @@ async function readCodexAgentConfig(path) {
|
|
|
7191
7653
|
}
|
|
7192
7654
|
|
|
7193
7655
|
// src/harnesses.ts
|
|
7194
|
-
import { access as
|
|
7195
|
-
import { basename as basename2, dirname as dirname7, join as
|
|
7196
|
-
import { homedir as
|
|
7656
|
+
import { access as access3, mkdir as mkdir10, readFile as readFile4, readdir as readdir4, writeFile as writeFile10, rm as rm2 } from "fs/promises";
|
|
7657
|
+
import { basename as basename2, dirname as dirname7, join as join12, isAbsolute as isAbsolute11, resolve as resolve8 } from "path";
|
|
7658
|
+
import { homedir as homedir7, tmpdir } from "os";
|
|
7197
7659
|
import { createHash as createHash8, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual5 } from "crypto";
|
|
7198
|
-
import { execFile } from "child_process";
|
|
7199
|
-
import { promisify } from "util";
|
|
7660
|
+
import { execFile as execFile2 } from "child_process";
|
|
7661
|
+
import { promisify as promisify2 } from "util";
|
|
7200
7662
|
import { createConnection } from "net";
|
|
7201
7663
|
|
|
7202
7664
|
// src/aider-config.ts
|
|
7203
|
-
import { readFile as readFile3, writeFile as writeFile5, lstat as lstat3, copyFile, rename, realpath as realpath4, access } from "fs/promises";
|
|
7204
|
-
import { constants as
|
|
7205
|
-
import { dirname as dirname5, basename, join as
|
|
7206
|
-
import { homedir as
|
|
7665
|
+
import { readFile as readFile3, writeFile as writeFile5, lstat as lstat3, copyFile, rename, realpath as realpath4, access as access2 } from "fs/promises";
|
|
7666
|
+
import { constants as constants3 } from "fs";
|
|
7667
|
+
import { dirname as dirname5, basename, join as join7, resolve as resolve6, isAbsolute as isAbsolute7 } from "path";
|
|
7668
|
+
import { homedir as homedir5 } from "os";
|
|
7207
7669
|
import { parseDocument as parseDocument2 } from "yaml";
|
|
7208
7670
|
var KEY2 = "SWITCHER_HARNESS_API_KEY";
|
|
7209
7671
|
var object3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
|
7210
7672
|
async function data(path) {
|
|
7211
7673
|
let text;
|
|
7212
7674
|
try {
|
|
7213
|
-
const
|
|
7214
|
-
if (!
|
|
7675
|
+
const stat5 = await lstat3(path);
|
|
7676
|
+
if (!stat5.isFile() || stat5.size > 1024 * 1024)
|
|
7215
7677
|
throw new Error("unsupported");
|
|
7216
7678
|
text = await readFile3(path, "utf8");
|
|
7217
7679
|
} catch (error) {
|
|
@@ -7244,9 +7706,9 @@ async function gitRoot(path) {
|
|
|
7244
7706
|
parent = dirname5(parent);
|
|
7245
7707
|
}
|
|
7246
7708
|
}
|
|
7247
|
-
for (let dir =
|
|
7709
|
+
for (let dir = join7(parent, ...missing);; dir = dirname5(dir)) {
|
|
7248
7710
|
try {
|
|
7249
|
-
await lstat3(
|
|
7711
|
+
await lstat3(join7(dir, ".git"));
|
|
7250
7712
|
return dir;
|
|
7251
7713
|
} catch (error) {
|
|
7252
7714
|
if (!["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
|
|
@@ -7259,9 +7721,9 @@ async function gitRoot(path) {
|
|
|
7259
7721
|
var falseValue = (v) => v === undefined || v === null || v === false || v === 0 || typeof v === "string" && ["", "false", "no", "off", "0"].includes(v.toLowerCase());
|
|
7260
7722
|
var startup = `yes-always gui browser upgrade install-main-branch just-check-update apply-clipboard-edits test lint commit`.split(" ");
|
|
7261
7723
|
var safeParameters = new Set(`max_tokens temperature top_p top_k min_p stop seed reasoning_effort thinking`.split(" "));
|
|
7262
|
-
var expandHome = (path, home) => path === "~" ? home : path.startsWith("~/") ?
|
|
7263
|
-
async function validateAiderConfiguration(cwd, args = [], home = process.env.HOME ??
|
|
7264
|
-
if (!
|
|
7724
|
+
var expandHome = (path, home) => path === "~" ? home : path.startsWith("~/") ? join7(home, path.slice(2)) : path;
|
|
7725
|
+
async function validateAiderConfiguration(cwd, args = [], home = process.env.HOME ?? homedir5()) {
|
|
7726
|
+
if (!isAbsolute7(home))
|
|
7265
7727
|
throw new Error("Aider requires an absolute HOME to preserve native instruction paths.");
|
|
7266
7728
|
const parsed = aiderArguments(args), cwdRoot = await gitRoot(cwd);
|
|
7267
7729
|
const roots = new Set([resolve6(home), ...cwdRoot ? [cwdRoot] : [], resolve6(cwd)]);
|
|
@@ -7272,7 +7734,7 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
7272
7734
|
}
|
|
7273
7735
|
let effective = {};
|
|
7274
7736
|
for (const root of roots) {
|
|
7275
|
-
const path =
|
|
7737
|
+
const path = join7(root, ".aider.conf.yml"), value = await data(path);
|
|
7276
7738
|
if (value !== undefined) {
|
|
7277
7739
|
if (!object3(value))
|
|
7278
7740
|
throw new Error(`Aider configuration must be a mapping: ${path}`);
|
|
@@ -7297,13 +7759,13 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
7297
7759
|
}
|
|
7298
7760
|
effective = { ...effective, ...normalized };
|
|
7299
7761
|
}
|
|
7300
|
-
const settings2 = await data(
|
|
7762
|
+
const settings2 = await data(join7(root, ".aider.model.settings.yml"));
|
|
7301
7763
|
if (settings2 !== undefined) {
|
|
7302
7764
|
if (!Array.isArray(settings2))
|
|
7303
7765
|
throw new Error("Aider model settings must be a list.");
|
|
7304
7766
|
for (const entry of settings2)
|
|
7305
7767
|
if (!object3(entry) || entry.extra_params !== undefined && (!object3(entry.extra_params) || Object.keys(entry.extra_params).some((key) => !safeParameters.has(key))))
|
|
7306
|
-
throw new Error(`Aider custom transport or callback model settings cannot be preserved safely: ${
|
|
7768
|
+
throw new Error(`Aider custom transport or callback model settings cannot be preserved safely: ${join7(root, ".aider.model.settings.yml")}`);
|
|
7307
7769
|
}
|
|
7308
7770
|
}
|
|
7309
7771
|
if (effective.read !== undefined && !(typeof effective.read === "string" || Array.isArray(effective.read) && effective.read.every((v) => typeof v === "string")))
|
|
@@ -7311,7 +7773,7 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
|
|
|
7311
7773
|
const reads = parsed.reads.length ? parsed.reads : typeof effective.read === "string" ? [effective.read] : effective.read ?? [];
|
|
7312
7774
|
for (const path of reads) {
|
|
7313
7775
|
try {
|
|
7314
|
-
await
|
|
7776
|
+
await access2(resolve6(cwd, expandHome(path, home)), constants3.R_OK);
|
|
7315
7777
|
} catch {
|
|
7316
7778
|
throw new Error(`Aider read-only instruction file is not readable: ${path}`);
|
|
7317
7779
|
}
|
|
@@ -7324,8 +7786,8 @@ function aiderModelName(protocol, id2) {
|
|
|
7324
7786
|
return `${protocol === "anthropic-messages" ? "anthropic" : protocol === "openai-responses" ? "openai/responses" : "openai"}/${id2}`;
|
|
7325
7787
|
}
|
|
7326
7788
|
async function historyFile(path) {
|
|
7327
|
-
const
|
|
7328
|
-
if (!
|
|
7789
|
+
const stat5 = await lstat3(path);
|
|
7790
|
+
if (!stat5.isFile() || stat5.isSymbolicLink() || stat5.size > 64 * 1024 * 1024 || process.platform !== "win32" && ((stat5.mode & 63) !== 0 || stat5.uid !== process.getuid?.()))
|
|
7329
7791
|
throw new Error("Aider history must be an owner-only regular file smaller than 64 MiB.");
|
|
7330
7792
|
}
|
|
7331
7793
|
async function prepareAider(input) {
|
|
@@ -7339,7 +7801,7 @@ async function prepareAider(input) {
|
|
|
7339
7801
|
const files = parsed.args.splice(literal2).slice(1);
|
|
7340
7802
|
parsed.args.push(...files.map((path) => resolve6(input.cwd, path)));
|
|
7341
7803
|
}
|
|
7342
|
-
const sourceHome = process.env.HOME ??
|
|
7804
|
+
const sourceHome = process.env.HOME ?? homedir5();
|
|
7343
7805
|
for (let i = 0;i < parsed.args.length; i++) {
|
|
7344
7806
|
if (parsed.args[i] === "--read") {
|
|
7345
7807
|
i++;
|
|
@@ -7347,26 +7809,26 @@ async function prepareAider(input) {
|
|
|
7347
7809
|
} else if (parsed.args[i].startsWith("--read="))
|
|
7348
7810
|
parsed.args[i] = "--read=" + expandHome(parsed.args[i].slice(7), sourceHome);
|
|
7349
7811
|
}
|
|
7350
|
-
const home =
|
|
7812
|
+
const home = join7(input.stateDir, "aider-home");
|
|
7351
7813
|
await privateDirectory(home);
|
|
7352
|
-
const originalHome = process.env.HOME ??
|
|
7353
|
-
const gitSources = process.env.GIT_CONFIG_GLOBAL ? [resolve6(process.env.GIT_CONFIG_GLOBAL)] : [
|
|
7354
|
-
const gitConfig =
|
|
7814
|
+
const originalHome = process.env.HOME ?? homedir5();
|
|
7815
|
+
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")];
|
|
7816
|
+
const gitConfig = join7(home, ".gitconfig");
|
|
7355
7817
|
await writeFile5(gitConfig, gitSources.map((path) => `[include]
|
|
7356
7818
|
path = ${JSON.stringify(path)}
|
|
7357
7819
|
`).join(""), { mode: 384, flag: "wx" });
|
|
7358
|
-
const sessions = input.sessionDir ??
|
|
7820
|
+
const sessions = input.sessionDir ?? join7(input.stateDir, "sessions");
|
|
7359
7821
|
await privateDirectory(sessions);
|
|
7360
|
-
const id2 = crypto.randomUUID(), history =
|
|
7822
|
+
const id2 = crypto.randomUUID(), history = join7(sessions, `${id2}.chat.md`), inputHistory = join7(sessions, `${id2}.input`);
|
|
7361
7823
|
if (parsed.restore) {
|
|
7362
|
-
const latest =
|
|
7824
|
+
const latest = join7(sessions, "latest.json");
|
|
7363
7825
|
await historyFile(latest).catch(() => {
|
|
7364
7826
|
throw new Error("No valid completed Aider history is available for this profile.");
|
|
7365
7827
|
});
|
|
7366
7828
|
const previous = JSON.parse(await readFile3(latest, "utf8"));
|
|
7367
7829
|
if (!object3(previous) || typeof previous.id !== "string" || !/^[-a-f0-9]{36}$/.test(previous.id))
|
|
7368
7830
|
throw new Error("Invalid Aider history reference.");
|
|
7369
|
-
const source =
|
|
7831
|
+
const source = join7(sessions, `${previous.id}.chat.md`);
|
|
7370
7832
|
await historyFile(source);
|
|
7371
7833
|
await copyFile(source, history, 1);
|
|
7372
7834
|
} else
|
|
@@ -7376,7 +7838,7 @@ async function prepareAider(input) {
|
|
|
7376
7838
|
const model2 = aiderModelName(input.protocol, input.model);
|
|
7377
7839
|
const weakModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.weak ?? input.model), editorModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.editor ?? input.model);
|
|
7378
7840
|
const extra = { api_base: input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl, api_key: `os.environ/${KEY2}` };
|
|
7379
|
-
const settings2 =
|
|
7841
|
+
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");
|
|
7380
7842
|
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 }));
|
|
7381
7843
|
await writeFile5(settings2, JSON.stringify([...definitions, { name: "aider/extra_params", extra_params: extra }]), { mode: 384, flag: "wx" });
|
|
7382
7844
|
await writeFile5(metadata, JSON.stringify(Object.fromEntries(input.models.map((m) => [aiderModelName(input.protocol, m.id), {
|
|
@@ -7395,7 +7857,7 @@ async function prepareAider(input) {
|
|
|
7395
7857
|
return {
|
|
7396
7858
|
executable: input.executable ?? "aider",
|
|
7397
7859
|
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],
|
|
7398
|
-
env: { HOME: home, XDG_CONFIG_HOME:
|
|
7860
|
+
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 },
|
|
7399
7861
|
configPaths: [config, settings2, metadata, empty, gitConfig],
|
|
7400
7862
|
warnings: [
|
|
7401
7863
|
...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."] : [],
|
|
@@ -7411,9 +7873,9 @@ async function prepareAider(input) {
|
|
|
7411
7873
|
await historyFile(history);
|
|
7412
7874
|
if (!/^#### /m.test((await readFile3(history, "utf8")).slice(originalHistoryLength)))
|
|
7413
7875
|
return;
|
|
7414
|
-
const pending =
|
|
7876
|
+
const pending = join7(sessions, `${id2}.latest.json`);
|
|
7415
7877
|
await writeFile5(pending, JSON.stringify({ id: id2 }), { mode: 384, flag: "wx" });
|
|
7416
|
-
await rename(pending,
|
|
7878
|
+
await rename(pending, join7(sessions, "latest.json"));
|
|
7417
7879
|
}
|
|
7418
7880
|
};
|
|
7419
7881
|
}
|
|
@@ -7497,7 +7959,7 @@ function validateGrokResume(args) {
|
|
|
7497
7959
|
// src/cline-backend.ts
|
|
7498
7960
|
import { mkdir as mkdir6, writeFile as writeFile6 } from "fs/promises";
|
|
7499
7961
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
7500
|
-
import { isAbsolute as
|
|
7962
|
+
import { isAbsolute as isAbsolute8, join as join8 } from "path";
|
|
7501
7963
|
var ENV_BY_PROTOCOL = {
|
|
7502
7964
|
"anthropic-messages": "ANTHROPIC_API_KEY",
|
|
7503
7965
|
"openai-responses": "OPENAI_API_KEY",
|
|
@@ -7543,18 +8005,18 @@ async function prepareClineLaunch(input) {
|
|
|
7543
8005
|
throw new Error(`Cline ${input.protocol} uses ${mapping.authStyle} authentication; use a provider with the native Cline auth contract.`);
|
|
7544
8006
|
if (input.credential && /[\r\n]/.test(input.credential))
|
|
7545
8007
|
throw new Error("Provider credential contains invalid header characters.");
|
|
7546
|
-
if (!
|
|
8008
|
+
if (!isAbsolute8(input.stateDir) || !isAbsolute8(input.cwd))
|
|
7547
8009
|
throw new Error("Launch state and working directories must be absolute.");
|
|
7548
|
-
const dataDir =
|
|
7549
|
-
const sessionDir = input.sessionDir ??
|
|
7550
|
-
const launchDir =
|
|
7551
|
-
const settingsDir =
|
|
7552
|
-
const configDir =
|
|
8010
|
+
const dataDir = join8(input.stateDir, "cline-data");
|
|
8011
|
+
const sessionDir = input.sessionDir ?? join8(dataDir, "sessions");
|
|
8012
|
+
const launchDir = join8(input.stateDir, `cline-launch-${randomUUID2()}`);
|
|
8013
|
+
const settingsDir = join8(launchDir, "settings");
|
|
8014
|
+
const configDir = join8(launchDir, "config");
|
|
7553
8015
|
await mkdir6(settingsDir, { recursive: true, mode: 448 });
|
|
7554
8016
|
await mkdir6(configDir, { recursive: true, mode: 448 });
|
|
7555
8017
|
const baseUrl = endpoint(input.baseUrl);
|
|
7556
8018
|
const providerId = mapping.providerId;
|
|
7557
|
-
const providersPath = await writeJson(
|
|
8019
|
+
const providersPath = await writeJson(join8(settingsDir, "providers.json"), {
|
|
7558
8020
|
version: 1,
|
|
7559
8021
|
lastUsedProvider: providerId,
|
|
7560
8022
|
modes: {},
|
|
@@ -7574,7 +8036,7 @@ async function prepareClineLaunch(input) {
|
|
|
7574
8036
|
}
|
|
7575
8037
|
}
|
|
7576
8038
|
});
|
|
7577
|
-
const modelsPath = await writeJson(
|
|
8039
|
+
const modelsPath = await writeJson(join8(settingsDir, "models.json"), {
|
|
7578
8040
|
version: 1,
|
|
7579
8041
|
providers: {
|
|
7580
8042
|
[providerId]: {
|
|
@@ -7623,17 +8085,17 @@ async function prepareClineLaunch(input) {
|
|
|
7623
8085
|
}
|
|
7624
8086
|
|
|
7625
8087
|
// src/opencode2-config.ts
|
|
7626
|
-
import { mkdir as mkdir7, open as open2, realpath as realpath5, readdir as readdir3, stat as
|
|
7627
|
-
import { constants as
|
|
7628
|
-
import { dirname as dirname6, isAbsolute as
|
|
7629
|
-
import { homedir as
|
|
8088
|
+
import { mkdir as mkdir7, open as open2, realpath as realpath5, readdir as readdir3, stat as stat5, writeFile as writeFile7 } from "fs/promises";
|
|
8089
|
+
import { constants as constants4 } from "fs";
|
|
8090
|
+
import { dirname as dirname6, isAbsolute as isAbsolute9, join as join9, relative as relative4, resolve as resolve7 } from "path";
|
|
8091
|
+
import { homedir as homedir6 } from "os";
|
|
7630
8092
|
import { randomUUID as randomUUID3 } from "crypto";
|
|
7631
8093
|
import { Database as Database2 } from "bun:sqlite";
|
|
7632
8094
|
import { parse as parse3, parseTree as parseTree3 } from "jsonc-parser";
|
|
7633
8095
|
import { parseDocument as parseDocument3 } from "yaml";
|
|
7634
|
-
import { z as
|
|
7635
|
-
var effect =
|
|
7636
|
-
var rule =
|
|
8096
|
+
import { z as z6 } from "zod";
|
|
8097
|
+
var effect = z6.enum(["allow", "deny", "ask"]);
|
|
8098
|
+
var rule = z6.object({ action: z6.string(), resource: z6.string(), effect }).strict();
|
|
7637
8099
|
var object4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
7638
8100
|
var own2 = (value, key) => Object.hasOwn(value, key);
|
|
7639
8101
|
var maxFileBytes2 = 1024 * 1024;
|
|
@@ -7641,7 +8103,7 @@ var maxTotalBytes2 = 8 * 1024 * 1024;
|
|
|
7641
8103
|
var maxFiles2 = 256;
|
|
7642
8104
|
var inside2 = (root, path) => {
|
|
7643
8105
|
const rel = relative4(root, path);
|
|
7644
|
-
return rel === "" || !
|
|
8106
|
+
return rel === "" || !isAbsolute9(rel) && rel !== ".." && !rel.startsWith("../");
|
|
7645
8107
|
};
|
|
7646
8108
|
var action = (value) => ({ bash: "shell", task: "subagent", write: "edit", patch: "edit" })[value] ?? value;
|
|
7647
8109
|
function invalid2(path, field) {
|
|
@@ -7683,7 +8145,7 @@ function permissions(value, path, home) {
|
|
|
7683
8145
|
}
|
|
7684
8146
|
}
|
|
7685
8147
|
if (own2(value, "permissions")) {
|
|
7686
|
-
const parsed =
|
|
8148
|
+
const parsed = z6.array(rule).safeParse(value.permissions);
|
|
7687
8149
|
if (!parsed.success)
|
|
7688
8150
|
invalid2(path, "permissions");
|
|
7689
8151
|
result.push(...parsed.data);
|
|
@@ -7693,7 +8155,7 @@ function permissions(value, path, home) {
|
|
|
7693
8155
|
literal2(item.resource, path, "permission resource");
|
|
7694
8156
|
if (!["read", "edit", "external_directory"].includes(item.action))
|
|
7695
8157
|
return item;
|
|
7696
|
-
const resource = item.resource === "~" || item.resource === "$HOME" ? home : item.resource.startsWith("~/") ?
|
|
8158
|
+
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;
|
|
7697
8159
|
return { ...item, resource };
|
|
7698
8160
|
});
|
|
7699
8161
|
}
|
|
@@ -7721,14 +8183,14 @@ function jsonc2(text, path) {
|
|
|
7721
8183
|
return record2(value, path, "configuration object");
|
|
7722
8184
|
}
|
|
7723
8185
|
async function checkRemoteConfiguration(dataHome) {
|
|
7724
|
-
const path =
|
|
7725
|
-
const legacyAuth = await
|
|
8186
|
+
const path = join9(dataHome, "opencode", "opencode.db");
|
|
8187
|
+
const legacyAuth = await stat5(join9(dataHome, "opencode", "auth.json")).then(() => true, (error) => {
|
|
7726
8188
|
if (error.code === "ENOENT")
|
|
7727
8189
|
return false;
|
|
7728
8190
|
throw error;
|
|
7729
8191
|
});
|
|
7730
8192
|
try {
|
|
7731
|
-
await
|
|
8193
|
+
await stat5(path);
|
|
7732
8194
|
} catch (error) {
|
|
7733
8195
|
if (error.code === "ENOENT") {
|
|
7734
8196
|
if (legacyAuth)
|
|
@@ -7762,23 +8224,23 @@ async function checkRemoteConfiguration(dataHome) {
|
|
|
7762
8224
|
}
|
|
7763
8225
|
async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
7764
8226
|
for (const name of ["HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "OPENCODE_CONFIG_DIR"])
|
|
7765
|
-
if (env[name] && !
|
|
8227
|
+
if (env[name] && !isAbsolute9(env[name]))
|
|
7766
8228
|
throw new Error(`OpenCode 2 requires an absolute ${name} to preserve native configuration authority.`);
|
|
7767
|
-
const home = resolve7(env.HOME ||
|
|
7768
|
-
const configRoot = resolve7(env.OPENCODE_CONFIG_DIR ||
|
|
8229
|
+
const home = resolve7(env.HOME || homedir6());
|
|
8230
|
+
const configRoot = resolve7(env.OPENCODE_CONFIG_DIR || join9(env.XDG_CONFIG_HOME || join9(home, ".config"), "opencode"));
|
|
7769
8231
|
const canonicalConfigRoot = await realpath5(configRoot).catch((error) => {
|
|
7770
8232
|
if (error.code === "ENOENT")
|
|
7771
8233
|
return configRoot;
|
|
7772
8234
|
throw error;
|
|
7773
8235
|
});
|
|
7774
|
-
const dataHome = resolve7(env.XDG_DATA_HOME ||
|
|
8236
|
+
const dataHome = resolve7(env.XDG_DATA_HOME || join9(home, ".local", "share"));
|
|
7775
8237
|
await checkRemoteConfiguration(dataHome);
|
|
7776
8238
|
let files = 0, total = 0;
|
|
7777
8239
|
const paths = [];
|
|
7778
8240
|
async function read(path, optional = true) {
|
|
7779
8241
|
let handle;
|
|
7780
8242
|
try {
|
|
7781
|
-
handle = await open2(path,
|
|
8243
|
+
handle = await open2(path, constants4.O_RDONLY | constants4.O_NONBLOCK);
|
|
7782
8244
|
} catch (error) {
|
|
7783
8245
|
if (optional && error.code === "ENOENT")
|
|
7784
8246
|
return;
|
|
@@ -7811,7 +8273,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7811
8273
|
invalid2(path, "agent prompt environment reference");
|
|
7812
8274
|
let result = "", cursor = 0;
|
|
7813
8275
|
for (const match of text.matchAll(/\{file:([^}]+)\}/g)) {
|
|
7814
|
-
const requested = match[1].startsWith("~/") ?
|
|
8276
|
+
const requested = match[1].startsWith("~/") ? join9(home, match[1].slice(2)) : resolve7(dirname6(path), match[1]);
|
|
7815
8277
|
const content = (await read(requested, false)).trim();
|
|
7816
8278
|
literal2(content, requested, "nested prompt variable reference");
|
|
7817
8279
|
result += text.slice(cursor, match.index) + content;
|
|
@@ -7833,7 +8295,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7833
8295
|
}
|
|
7834
8296
|
async function agentsDirectory(directory2) {
|
|
7835
8297
|
for (const source of ["agent", "agents", "mode", "modes"]) {
|
|
7836
|
-
const base =
|
|
8298
|
+
const base = join9(directory2, source), entries = [];
|
|
7837
8299
|
const visited = new Set;
|
|
7838
8300
|
let examined = 0;
|
|
7839
8301
|
async function walk(dir, depth) {
|
|
@@ -7852,8 +8314,8 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7852
8314
|
if (depth > 16 || (examined += names.length) > maxFiles2)
|
|
7853
8315
|
throw new Error("OpenCode 2 agent policy exceeds its bounded directory limit.");
|
|
7854
8316
|
for (const name of names) {
|
|
7855
|
-
const path =
|
|
7856
|
-
const info = await
|
|
8317
|
+
const path = join9(dir, name);
|
|
8318
|
+
const info = await stat5(path);
|
|
7857
8319
|
if (info.isDirectory()) {
|
|
7858
8320
|
if (source === "agent" || source === "agents")
|
|
7859
8321
|
await walk(path, depth + 1);
|
|
@@ -7886,8 +8348,8 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7886
8348
|
}
|
|
7887
8349
|
}
|
|
7888
8350
|
async function directory(path) {
|
|
7889
|
-
await document(
|
|
7890
|
-
await document(
|
|
8351
|
+
await document(join9(path, "opencode.json"));
|
|
8352
|
+
await document(join9(path, "opencode.jsonc"));
|
|
7891
8353
|
await agentsDirectory(path);
|
|
7892
8354
|
}
|
|
7893
8355
|
await directory(configRoot);
|
|
@@ -7902,11 +8364,11 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7902
8364
|
const projectEnabled = !["1", "true"].includes((env.OPENCODE_CONFIG_PROJECT_DISABLE ?? env.OPENCODE_DISABLE_PROJECT_CONFIG ?? "").toLowerCase());
|
|
7903
8365
|
if (projectEnabled) {
|
|
7904
8366
|
for (const path of [...ancestors].reverse()) {
|
|
7905
|
-
await document(
|
|
7906
|
-
await document(
|
|
8367
|
+
await document(join9(path, "opencode.json"));
|
|
8368
|
+
await document(join9(path, "opencode.jsonc"));
|
|
7907
8369
|
}
|
|
7908
8370
|
for (const path of [...ancestors].reverse()) {
|
|
7909
|
-
const candidate =
|
|
8371
|
+
const candidate = join9(path, ".opencode");
|
|
7910
8372
|
const canonical = await realpath5(candidate).catch((error) => {
|
|
7911
8373
|
if (error.code === "ENOENT")
|
|
7912
8374
|
return candidate;
|
|
@@ -7917,7 +8379,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7917
8379
|
}
|
|
7918
8380
|
}
|
|
7919
8381
|
if (env.OPENCODE_CONFIG_CONTENT)
|
|
7920
|
-
documents.push({ path:
|
|
8382
|
+
documents.push({ path: join9(cwd, "OPENCODE_CONFIG_CONTENT"), value: jsonc2(env.OPENCODE_CONFIG_CONTENT, "OPENCODE_CONFIG_CONTENT") });
|
|
7921
8383
|
const policy = [];
|
|
7922
8384
|
const agents = Object.create(null);
|
|
7923
8385
|
let defaultAgent;
|
|
@@ -7928,19 +8390,19 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7928
8390
|
defaultAgent = literal2(string2(value.default_agent, path, "default_agent"), path, "default_agent");
|
|
7929
8391
|
const policies = [];
|
|
7930
8392
|
if (own2(value, "enabled_providers")) {
|
|
7931
|
-
const names =
|
|
8393
|
+
const names = z6.array(z6.string()).safeParse(value.enabled_providers);
|
|
7932
8394
|
if (!names.success)
|
|
7933
8395
|
invalid2(path, "provider policy");
|
|
7934
8396
|
policies.push({ action: "provider.use", resource: "*", effect: "deny" }, ...names.data.map((resource) => ({ action: "provider.use", resource, effect: "allow" })));
|
|
7935
8397
|
}
|
|
7936
8398
|
if (own2(value, "disabled_providers")) {
|
|
7937
|
-
const names =
|
|
8399
|
+
const names = z6.array(z6.string()).safeParse(value.disabled_providers);
|
|
7938
8400
|
if (!names.success)
|
|
7939
8401
|
invalid2(path, "provider policy");
|
|
7940
8402
|
policies.push(...names.data.map((resource) => ({ action: "provider.use", resource, effect: "deny" })));
|
|
7941
8403
|
}
|
|
7942
8404
|
if (object4(value.experimental) && own2(value.experimental, "policies")) {
|
|
7943
|
-
const parsed =
|
|
8405
|
+
const parsed = z6.array(z6.object({ action: z6.literal("provider.use"), resource: z6.string(), effect: z6.enum(["allow", "deny"]) }).strict()).safeParse(value.experimental.policies);
|
|
7944
8406
|
if (!parsed.success)
|
|
7945
8407
|
invalid2(path, "provider policy");
|
|
7946
8408
|
policies.push(...parsed.data);
|
|
@@ -7964,7 +8426,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
7964
8426
|
if (own2(item, "description"))
|
|
7965
8427
|
target.description = string2(item.description, path, "agent description");
|
|
7966
8428
|
if (own2(item, "mode")) {
|
|
7967
|
-
const parsed =
|
|
8429
|
+
const parsed = z6.enum(["primary", "subagent", "all"]).safeParse(item.mode);
|
|
7968
8430
|
if (!parsed.success)
|
|
7969
8431
|
invalid2(path, "agent mode");
|
|
7970
8432
|
target.mode = parsed.data;
|
|
@@ -8010,26 +8472,26 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
|
|
|
8010
8472
|
instructions.push(`Instructions from: ${path}
|
|
8011
8473
|
${content}`);
|
|
8012
8474
|
}
|
|
8013
|
-
await instruction(
|
|
8475
|
+
await instruction(join9(configRoot, "AGENTS.md"));
|
|
8014
8476
|
if (projectEnabled) {
|
|
8015
8477
|
let stop = resolve7(cwd);
|
|
8016
8478
|
if (inside2(home, resolve7(cwd)))
|
|
8017
8479
|
stop = home;
|
|
8018
8480
|
else
|
|
8019
8481
|
for (const path of ancestors) {
|
|
8020
|
-
if (await
|
|
8482
|
+
if (await stat5(join9(path, ".git")).then(() => true, () => false)) {
|
|
8021
8483
|
stop = path;
|
|
8022
8484
|
break;
|
|
8023
8485
|
}
|
|
8024
8486
|
}
|
|
8025
8487
|
for (const path of ancestors) {
|
|
8026
|
-
await instruction(
|
|
8488
|
+
await instruction(join9(path, "AGENTS.md"));
|
|
8027
8489
|
if (path === stop)
|
|
8028
8490
|
break;
|
|
8029
8491
|
}
|
|
8030
8492
|
}
|
|
8031
|
-
const privateHome =
|
|
8032
|
-
const instructionFile =
|
|
8493
|
+
const privateHome = join9(stateDir, "opencode-home"), privateConfig = join9(stateDir, "opencode-config");
|
|
8494
|
+
const instructionFile = join9(privateConfig, "opencode", "AGENTS.md");
|
|
8033
8495
|
await mkdir7(dirname6(instructionFile), { recursive: true, mode: 448 });
|
|
8034
8496
|
await mkdir7(privateHome, { recursive: true, mode: 448 });
|
|
8035
8497
|
await writeFile7(instructionFile, instructions.join(`
|
|
@@ -8037,7 +8499,7 @@ ${content}`);
|
|
|
8037
8499
|
`), { flag: "wx", mode: 384 });
|
|
8038
8500
|
return {
|
|
8039
8501
|
config: { permissions: policy, agents, ...defaultAgent ? { default_agent: defaultAgent } : {}, experimental: { policies: [{ action: "provider.use", resource: "*", effect: "deny" }, { action: "provider.use", resource: providerID, effect: "allow" }] } },
|
|
8040
|
-
env: { HOME: privateHome, XDG_CONFIG_HOME: privateConfig, OPENCODE_CONFIG_DIR:
|
|
8502
|
+
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" },
|
|
8041
8503
|
instructionFile,
|
|
8042
8504
|
sourcePaths: paths
|
|
8043
8505
|
};
|
|
@@ -8053,7 +8515,7 @@ function openCode2ConfigText(config, providerID, keyEnv) {
|
|
|
8053
8515
|
|
|
8054
8516
|
// src/omp-backend.ts
|
|
8055
8517
|
import { mkdir as mkdir8, rm, writeFile as writeFile8 } from "fs/promises";
|
|
8056
|
-
import { join as
|
|
8518
|
+
import { join as join10 } from "path";
|
|
8057
8519
|
var KEY3 = "SWITCHER_HARNESS_API_KEY";
|
|
8058
8520
|
var API = {
|
|
8059
8521
|
"anthropic-messages": "anthropic-messages",
|
|
@@ -8078,8 +8540,8 @@ async function prepareOmpLaunch(input) {
|
|
|
8078
8540
|
const baseUrl = endpoint(input.baseUrl);
|
|
8079
8541
|
if (input.credential && /[\r\n]/.test(input.credential))
|
|
8080
8542
|
throw new Error("Provider credential contains invalid header characters.");
|
|
8081
|
-
const agentDir =
|
|
8082
|
-
const sessionDir = input.sessionDir ??
|
|
8543
|
+
const agentDir = join10(input.stateDir, "omp-agent");
|
|
8544
|
+
const sessionDir = input.sessionDir ?? join10(input.stateDir, "sessions");
|
|
8083
8545
|
await mkdir8(agentDir, { recursive: true, mode: 448 });
|
|
8084
8546
|
await mkdir8(sessionDir, { recursive: true, mode: 448 });
|
|
8085
8547
|
const api = API[input.protocol];
|
|
@@ -8105,8 +8567,8 @@ async function prepareOmpLaunch(input) {
|
|
|
8105
8567
|
provider.apiKey = KEY3;
|
|
8106
8568
|
provider.authHeader = true;
|
|
8107
8569
|
}
|
|
8108
|
-
const modelsPath =
|
|
8109
|
-
const configPath =
|
|
8570
|
+
const modelsPath = join10(agentDir, "models.yml");
|
|
8571
|
+
const configPath = join10(agentDir, "config.yml");
|
|
8110
8572
|
const selector = `switcher/${input.model}`;
|
|
8111
8573
|
await writeFile8(modelsPath, JSON.stringify({ providers: { switcher: provider } }, null, 2) + `
|
|
8112
8574
|
`, { mode: 384, flag: "wx" });
|
|
@@ -8184,7 +8646,7 @@ function compileHermesModelPolicy(currentModel, roles2, baseUrl, apiMode = "chat
|
|
|
8184
8646
|
// src/hermes-backend.ts
|
|
8185
8647
|
import { createHash as createHash7, timingSafeEqual as timingSafeEqual4 } from "crypto";
|
|
8186
8648
|
import { mkdir as mkdir9, symlink as symlink2, writeFile as writeFile9 } from "fs/promises";
|
|
8187
|
-
import { isAbsolute as
|
|
8649
|
+
import { isAbsolute as isAbsolute10, join as join11 } from "path";
|
|
8188
8650
|
var hermesApiMode = {
|
|
8189
8651
|
"anthropic-messages": "anthropic_messages",
|
|
8190
8652
|
"openai-responses": "codex_responses",
|
|
@@ -8196,7 +8658,7 @@ var routePath = {
|
|
|
8196
8658
|
"openai-chat": "/v1/chat/completions"
|
|
8197
8659
|
};
|
|
8198
8660
|
var apiMode = hermesApiMode;
|
|
8199
|
-
function createHermesBridge(input) {
|
|
8661
|
+
function createHermesBridge(input, timing = {}) {
|
|
8200
8662
|
const protocol = input.protocol;
|
|
8201
8663
|
const token = crypto.randomUUID() + crypto.randomUUID();
|
|
8202
8664
|
const modelIds = new Set(input.models.map((model3) => model3.id));
|
|
@@ -8209,7 +8671,7 @@ function createHermesBridge(input) {
|
|
|
8209
8671
|
port: 0,
|
|
8210
8672
|
maxRequestBodySize: 4 * 1024 * 1024,
|
|
8211
8673
|
idleTimeout: 255,
|
|
8212
|
-
async fetch(request) {
|
|
8674
|
+
async fetch(request, server2) {
|
|
8213
8675
|
if (closing)
|
|
8214
8676
|
return Response.json({ error: { message: "Hermes bridge is closing" } }, { status: 503 });
|
|
8215
8677
|
const nativeHeader = protocol === "anthropic-messages" ? "x-api-key" : "authorization";
|
|
@@ -8254,7 +8716,9 @@ function createHermesBridge(input) {
|
|
|
8254
8716
|
complete = resolve8;
|
|
8255
8717
|
})
|
|
8256
8718
|
};
|
|
8719
|
+
const activity = createProviderRequest(request.signal, abortController.signal, timing);
|
|
8257
8720
|
const release = () => {
|
|
8721
|
+
activity.finish();
|
|
8258
8722
|
active.delete(record3);
|
|
8259
8723
|
complete();
|
|
8260
8724
|
};
|
|
@@ -8274,16 +8738,19 @@ function createHermesBridge(input) {
|
|
|
8274
8738
|
if (beta)
|
|
8275
8739
|
headers["anthropic-beta"] = beta;
|
|
8276
8740
|
}
|
|
8741
|
+
server2.timeout(request, 0);
|
|
8277
8742
|
try {
|
|
8278
|
-
const upstream = await fetch(`${input.baseUrl}${routePath[protocol].replace(/^\/v1/, "")}`, {
|
|
8743
|
+
const upstream = await activity.run(() => fetch(`${input.baseUrl}${routePath[protocol].replace(/^\/v1/, "")}`, {
|
|
8279
8744
|
method: "POST",
|
|
8280
8745
|
headers,
|
|
8281
8746
|
body: JSON.stringify(body),
|
|
8282
8747
|
redirect: "manual",
|
|
8283
|
-
|
|
8284
|
-
});
|
|
8748
|
+
...activity.fetchOptions
|
|
8749
|
+
}));
|
|
8285
8750
|
if (!upstream.ok) {
|
|
8286
|
-
|
|
8751
|
+
upstream.body?.cancel().catch(() => {
|
|
8752
|
+
return;
|
|
8753
|
+
});
|
|
8287
8754
|
release();
|
|
8288
8755
|
return Response.json({ error: { message: `Provider returned HTTP ${upstream.status}` } }, { status: upstream.status });
|
|
8289
8756
|
}
|
|
@@ -8291,7 +8758,7 @@ function createHermesBridge(input) {
|
|
|
8291
8758
|
release();
|
|
8292
8759
|
return new Response(null, { status: upstream.status });
|
|
8293
8760
|
}
|
|
8294
|
-
const { stream, cancel } = proxyProviderStream({ response: upstream, protocol: input.protocol, requestSignal: request.signal, abort: abortController, closing: () => closing, release });
|
|
8761
|
+
const { stream, cancel } = proxyProviderStream({ response: upstream, protocol: input.protocol, requestSignal: request.signal, abort: abortController, closing: () => closing, release, activity });
|
|
8295
8762
|
record3.cancel = cancel;
|
|
8296
8763
|
return new Response(stream, {
|
|
8297
8764
|
status: upstream.status,
|
|
@@ -8302,7 +8769,7 @@ function createHermesBridge(input) {
|
|
|
8302
8769
|
});
|
|
8303
8770
|
} catch {
|
|
8304
8771
|
release();
|
|
8305
|
-
return Response.json({ error: { message: "Provider request failed" } }, { status: 502 });
|
|
8772
|
+
return Response.json({ error: { message: activity.timedOut() ? "Provider request timed out waiting for activity" : "Provider request failed" } }, { status: activity.timedOut() ? 504 : 502 });
|
|
8306
8773
|
}
|
|
8307
8774
|
}
|
|
8308
8775
|
});
|
|
@@ -8323,7 +8790,7 @@ function createHermesBridge(input) {
|
|
|
8323
8790
|
};
|
|
8324
8791
|
}
|
|
8325
8792
|
async function prepareHermesLaunch(input) {
|
|
8326
|
-
if (!
|
|
8793
|
+
if (!isAbsolute10(input.stateDir) || !isAbsolute10(input.cwd))
|
|
8327
8794
|
throw new Error("Launch state and working directories must be absolute.");
|
|
8328
8795
|
if (input.protocol !== "anthropic-messages" && input.protocol !== "openai-responses" && input.protocol !== "openai-chat")
|
|
8329
8796
|
throw new Error("Hermes does not support this provider protocol.");
|
|
@@ -8333,12 +8800,12 @@ async function prepareHermesLaunch(input) {
|
|
|
8333
8800
|
throw new Error("Hermes cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
8334
8801
|
if (input.credential && /[\r\n]/.test(input.credential))
|
|
8335
8802
|
throw new Error("Provider credential contains invalid header characters.");
|
|
8336
|
-
const sessionDir = input.sessionDir ??
|
|
8337
|
-
const sessionsDir =
|
|
8803
|
+
const sessionDir = input.sessionDir ?? join11(input.stateDir, "hermes-session");
|
|
8804
|
+
const sessionsDir = join11(sessionDir, "sessions");
|
|
8338
8805
|
await mkdir9(input.stateDir, { recursive: true, mode: 448 });
|
|
8339
8806
|
await mkdir9(sessionsDir, { recursive: true, mode: 448 });
|
|
8340
|
-
await symlink2(
|
|
8341
|
-
await symlink2(sessionsDir,
|
|
8807
|
+
await symlink2(join11(sessionDir, "state.db"), join11(input.stateDir, "state.db"));
|
|
8808
|
+
await symlink2(sessionsDir, join11(input.stateDir, "sessions"));
|
|
8342
8809
|
const bridge = createHermesBridge(input);
|
|
8343
8810
|
let policy;
|
|
8344
8811
|
try {
|
|
@@ -8366,7 +8833,7 @@ async function prepareHermesLaunch(input) {
|
|
|
8366
8833
|
}
|
|
8367
8834
|
}
|
|
8368
8835
|
};
|
|
8369
|
-
const configPath =
|
|
8836
|
+
const configPath = join11(input.stateDir, "config.yaml");
|
|
8370
8837
|
try {
|
|
8371
8838
|
await writeFile9(configPath, JSON.stringify(config, null, 2) + `
|
|
8372
8839
|
`, { mode: 384, flag: "wx" });
|
|
@@ -8383,7 +8850,7 @@ async function prepareHermesLaunch(input) {
|
|
|
8383
8850
|
SWITCHER_HERMES_AUX_API_KEY: bridge.token,
|
|
8384
8851
|
OPENAI_API_KEY: bridge.token,
|
|
8385
8852
|
OPENAI_BASE_URL: bridge.baseUrl,
|
|
8386
|
-
CODEX_HOME:
|
|
8853
|
+
CODEX_HOME: join11(input.stateDir, "codex-home")
|
|
8387
8854
|
},
|
|
8388
8855
|
configPaths: [configPath],
|
|
8389
8856
|
warnings: [
|
|
@@ -8521,14 +8988,14 @@ function harnessInstallationMessage(harness, executable, explicitOverride) {
|
|
|
8521
8988
|
}
|
|
8522
8989
|
|
|
8523
8990
|
// src/harnesses.ts
|
|
8524
|
-
var
|
|
8991
|
+
var execute2 = promisify2(execFile2);
|
|
8525
8992
|
var KEY4 = "SWITCHER_HARNESS_API_KEY";
|
|
8526
8993
|
var quote = (value) => JSON.stringify(value);
|
|
8527
8994
|
async function detectHarness(harness, override) {
|
|
8528
8995
|
const executable = override ?? Bun.which(harness) ?? harness;
|
|
8529
8996
|
const installation = harnessInstallation(harness);
|
|
8530
8997
|
try {
|
|
8531
|
-
const { stdout, stderr } = await
|
|
8998
|
+
const { stdout, stderr } = await execute2(executable, ["--version"], { timeout: 8000, maxBuffer: 65536, env: childEnvironment() });
|
|
8532
8999
|
return { harness, executable, available: true, version: (stdout.trim() || stderr.trim()).slice(0, 200), installation };
|
|
8533
9000
|
} catch {
|
|
8534
9001
|
return { harness, executable, available: false, version: undefined, installation };
|
|
@@ -8589,7 +9056,7 @@ function validateHarnessVersion(harness, version) {
|
|
|
8589
9056
|
throw new Error("Gemini CLI 0.58.0 is required by the verified native settings and argument contract.");
|
|
8590
9057
|
}
|
|
8591
9058
|
async function jsonFile(dir, name, value) {
|
|
8592
|
-
const path =
|
|
9059
|
+
const path = join12(dir, name);
|
|
8593
9060
|
await writeFile10(path, JSON.stringify(value, null, 2) + `
|
|
8594
9061
|
`, { mode: 384, flag: "wx" });
|
|
8595
9062
|
return path;
|
|
@@ -8598,8 +9065,8 @@ async function projectInstructionPaths(cwd) {
|
|
|
8598
9065
|
let dir = resolve8(cwd);
|
|
8599
9066
|
while (true) {
|
|
8600
9067
|
for (const name of ["AGENTS.md", "CLAUDE.md", "CONTEXT.md"]) {
|
|
8601
|
-
const path =
|
|
8602
|
-
if (await
|
|
9068
|
+
const path = join12(dir, name);
|
|
9069
|
+
if (await access3(path).then(() => true, () => false))
|
|
8603
9070
|
return [path];
|
|
8604
9071
|
}
|
|
8605
9072
|
const parent = dirname7(dir);
|
|
@@ -8675,7 +9142,7 @@ function expandHomePattern(value) {
|
|
|
8675
9142
|
const record3 = value;
|
|
8676
9143
|
const output = {};
|
|
8677
9144
|
for (const [key, item] of Object.entries(record3)) {
|
|
8678
|
-
const expanded = key === "~" ?
|
|
9145
|
+
const expanded = key === "~" ? homedir7() : key.startsWith("~/") ? join12(homedir7(), key.slice(2)) : key;
|
|
8679
9146
|
output[expanded] = expandHomePattern(item);
|
|
8680
9147
|
}
|
|
8681
9148
|
return output;
|
|
@@ -8751,7 +9218,7 @@ async function agentPolicyFiles(dir, kind) {
|
|
|
8751
9218
|
throw error;
|
|
8752
9219
|
}
|
|
8753
9220
|
for (const entry of entries) {
|
|
8754
|
-
const file =
|
|
9221
|
+
const file = join12(current, entry.name);
|
|
8755
9222
|
if (entry.isDirectory())
|
|
8756
9223
|
await visit(file, root);
|
|
8757
9224
|
else if (entry.isFile() && entry.name.endsWith(".md"))
|
|
@@ -8759,7 +9226,7 @@ async function agentPolicyFiles(dir, kind) {
|
|
|
8759
9226
|
}
|
|
8760
9227
|
};
|
|
8761
9228
|
for (const rootName of [kind, `${kind}s`])
|
|
8762
|
-
await visit(
|
|
9229
|
+
await visit(join12(dir, rootName), join12(dir, rootName));
|
|
8763
9230
|
return result.sort((a, b) => a.file.localeCompare(b.file));
|
|
8764
9231
|
}
|
|
8765
9232
|
async function readAgentPolicyFile(file, kind, root) {
|
|
@@ -8815,9 +9282,9 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
8815
9282
|
result.mode = { ...result.mode ?? {}, [policy.name]: { permission: merged } };
|
|
8816
9283
|
}
|
|
8817
9284
|
};
|
|
8818
|
-
const originalConfig =
|
|
9285
|
+
const originalConfig = join12(process.env.XDG_CONFIG_HOME ?? join12(homedir7(), ".config"), "opencode");
|
|
8819
9286
|
for (const name of ["config.json", "opencode.json", "opencode.jsonc"])
|
|
8820
|
-
await apply(
|
|
9287
|
+
await apply(join12(originalConfig, name));
|
|
8821
9288
|
await applyMarkdown(originalConfig, "agent");
|
|
8822
9289
|
await applyMarkdown(originalConfig, "mode");
|
|
8823
9290
|
if (process.env.OPENCODE_CONFIG)
|
|
@@ -8833,22 +9300,22 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
8833
9300
|
}
|
|
8834
9301
|
for (const current of [...dirs].reverse())
|
|
8835
9302
|
for (const name of ["opencode.jsonc", "opencode.json"])
|
|
8836
|
-
await apply(
|
|
9303
|
+
await apply(join12(current, name));
|
|
8837
9304
|
for (const current of dirs) {
|
|
8838
|
-
const configDir =
|
|
9305
|
+
const configDir = join12(current, ".opencode");
|
|
8839
9306
|
for (const name of ["opencode.json", "opencode.jsonc"])
|
|
8840
|
-
await apply(
|
|
9307
|
+
await apply(join12(configDir, name));
|
|
8841
9308
|
await applyMarkdown(configDir, "agent");
|
|
8842
9309
|
await applyMarkdown(configDir, "mode");
|
|
8843
9310
|
}
|
|
8844
|
-
const homeConfig =
|
|
9311
|
+
const homeConfig = join12(homedir7(), ".opencode");
|
|
8845
9312
|
for (const name of ["opencode.json", "opencode.jsonc"])
|
|
8846
|
-
await apply(
|
|
9313
|
+
await apply(join12(homeConfig, name));
|
|
8847
9314
|
await applyMarkdown(homeConfig, "agent");
|
|
8848
9315
|
await applyMarkdown(homeConfig, "mode");
|
|
8849
9316
|
if (process.env.OPENCODE_CONFIG_DIR) {
|
|
8850
9317
|
for (const name of ["opencode.json", "opencode.jsonc"])
|
|
8851
|
-
await apply(
|
|
9318
|
+
await apply(join12(process.env.OPENCODE_CONFIG_DIR, name));
|
|
8852
9319
|
await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "agent");
|
|
8853
9320
|
await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "mode");
|
|
8854
9321
|
}
|
|
@@ -8868,7 +9335,8 @@ async function preservedOpenCodePolicy(cwd) {
|
|
|
8868
9335
|
result.permission = mergePolicyValue(toolsPermission(result.tools, "OpenCode tools policy"), result.permission);
|
|
8869
9336
|
return result;
|
|
8870
9337
|
}
|
|
8871
|
-
function codexModel(model3, priority) {
|
|
9338
|
+
function codexModel(model3, priority, baseUrl = "https://provider.invalid", selectedReasoning) {
|
|
9339
|
+
const reasoning = codexReasoning(model3, baseUrl, selectedReasoning);
|
|
8872
9340
|
return {
|
|
8873
9341
|
slug: model3.id,
|
|
8874
9342
|
display_name: model3.name,
|
|
@@ -8877,8 +9345,8 @@ function codexModel(model3, priority) {
|
|
|
8877
9345
|
visibility: "list",
|
|
8878
9346
|
supported_in_api: true,
|
|
8879
9347
|
priority,
|
|
8880
|
-
supported_reasoning_levels:
|
|
8881
|
-
default_reasoning_level:
|
|
9348
|
+
supported_reasoning_levels: reasoning.levels.map((effort) => ({ effort, description: effort === "none" ? "Disable reasoning" : `${effort} reasoning effort` })),
|
|
9349
|
+
default_reasoning_level: reasoning.defaultEffort,
|
|
8882
9350
|
support_verbosity: false,
|
|
8883
9351
|
supports_reasoning_summary_parameter: false,
|
|
8884
9352
|
default_verbosity: null,
|
|
@@ -8894,7 +9362,7 @@ function codexModel(model3, priority) {
|
|
|
8894
9362
|
model_messages: { instructions_template: "You are Codex, a coding assistant. Help the user with their requested work. Follow the user and developer instructions, use the available tools when appropriate, preserve unrelated changes, and report actual results and remaining limitations.", instructions_variables: null }
|
|
8895
9363
|
};
|
|
8896
9364
|
}
|
|
8897
|
-
function grokBridge(input) {
|
|
9365
|
+
function grokBridge(input, timing = {}) {
|
|
8898
9366
|
const token = crypto.randomUUID() + crypto.randomUUID();
|
|
8899
9367
|
const expected = createHash8("sha256").update(`Bearer ${token}`).digest();
|
|
8900
9368
|
const models = new Map(input.models.flatMap((m) => [[m.id, m.id], [grokAlias(input, m.id), m.id]]));
|
|
@@ -8904,7 +9372,7 @@ function grokBridge(input) {
|
|
|
8904
9372
|
const active = new Set;
|
|
8905
9373
|
const apiBackend = { "anthropic-messages": "messages", "openai-responses": "responses", "openai-chat": "chat_completions", "gemini-generate-content": "generate_content" }[input.protocol];
|
|
8906
9374
|
const apiPath = { "anthropic-messages": "/messages", "openai-responses": "/responses", "openai-chat": "/chat/completions", "gemini-generate-content": "/generateContent" }[input.protocol];
|
|
8907
|
-
server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request) {
|
|
9375
|
+
server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
|
|
8908
9376
|
if (closing)
|
|
8909
9377
|
return Response.json({ error: { message: "Bridge is closing" } }, { status: 503 });
|
|
8910
9378
|
const auth = request.headers.get("authorization") ?? (request.headers.has("x-api-key") ? `Bearer ${request.headers.get("x-api-key")}` : "");
|
|
@@ -8919,7 +9387,7 @@ function grokBridge(input) {
|
|
|
8919
9387
|
model: m.id,
|
|
8920
9388
|
name: m.name,
|
|
8921
9389
|
description: m.description,
|
|
8922
|
-
base_url: new URL("v1",
|
|
9390
|
+
base_url: new URL("v1", server2.url).href,
|
|
8923
9391
|
context_window: m.contextWindow,
|
|
8924
9392
|
max_completion_tokens: m.maxOutputTokens,
|
|
8925
9393
|
api_backend: apiBackend,
|
|
@@ -8952,15 +9420,20 @@ function grokBridge(input) {
|
|
|
8952
9420
|
const record3 = { abort: new AbortController, done: new Promise((resolve9) => {
|
|
8953
9421
|
complete = resolve9;
|
|
8954
9422
|
}) };
|
|
9423
|
+
const activity = createProviderRequest(request.signal, record3.abort.signal, timing);
|
|
8955
9424
|
const release = () => {
|
|
9425
|
+
activity.finish();
|
|
8956
9426
|
active.delete(record3);
|
|
8957
9427
|
complete();
|
|
8958
9428
|
};
|
|
8959
9429
|
active.add(record3);
|
|
9430
|
+
server2.timeout(request, 0);
|
|
8960
9431
|
try {
|
|
8961
|
-
const response = await fetch(`${input.baseUrl}${apiPath}`, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual",
|
|
9432
|
+
const response = await activity.run(() => fetch(`${input.baseUrl}${apiPath}`, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
|
|
8962
9433
|
if (!response.ok) {
|
|
8963
|
-
|
|
9434
|
+
response.body?.cancel().catch(() => {
|
|
9435
|
+
return;
|
|
9436
|
+
});
|
|
8964
9437
|
release();
|
|
8965
9438
|
return Response.json({ error: { message: `Provider returned HTTP ${response.status}` } }, { status: response.status >= 300 && response.status < 400 ? 502 : response.status });
|
|
8966
9439
|
}
|
|
@@ -8968,12 +9441,12 @@ function grokBridge(input) {
|
|
|
8968
9441
|
release();
|
|
8969
9442
|
return new Response(null, { status: response.status });
|
|
8970
9443
|
}
|
|
8971
|
-
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record3.abort, closing: () => closing, release });
|
|
9444
|
+
const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record3.abort, closing: () => closing, release, activity });
|
|
8972
9445
|
record3.cancel = cancel;
|
|
8973
9446
|
return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
|
|
8974
9447
|
} catch {
|
|
8975
9448
|
release();
|
|
8976
|
-
return Response.json({ error: { message: "Provider request failed" } }, { status: 502 });
|
|
9449
|
+
return Response.json({ error: { message: activity.timedOut() ? "Provider request timed out waiting for activity" : "Provider request failed" } }, { status: activity.timedOut() ? 504 : 502 });
|
|
8977
9450
|
}
|
|
8978
9451
|
} });
|
|
8979
9452
|
return { baseUrl: new URL("v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
|
|
@@ -9013,20 +9486,20 @@ var PRIME_DAEMON_STARTUP_TIMEOUT_MS = 30000;
|
|
|
9013
9486
|
var PRIME_DAEMON_SHUTDOWN_TIMEOUT_MS = 5000;
|
|
9014
9487
|
function primeSocketPaths(runtimeDir) {
|
|
9015
9488
|
const basename3 = `p-${randomUUID4().replaceAll("-", "").slice(0, 8)}.sock`;
|
|
9016
|
-
const daemonSocket =
|
|
9489
|
+
const daemonSocket = join12(runtimeDir, basename3);
|
|
9017
9490
|
const uid = typeof process.getuid === "function" ? String(process.getuid()) : "user";
|
|
9018
|
-
const workerDir =
|
|
9491
|
+
const workerDir = join12(runtimeDir, `prime-agent-${uid}`);
|
|
9019
9492
|
const workerKey = createHash8("sha256").update(daemonSocket).digest("hex").slice(0, 12);
|
|
9020
|
-
const workerSocket =
|
|
9493
|
+
const workerSocket = join12(workerDir, `worker-${workerKey}-${"x".repeat(12)}.sock`);
|
|
9021
9494
|
const overlong = [daemonSocket, workerSocket].find((path) => Buffer.byteLength(path, "utf8") > PRIME_UNIX_SOCKET_LIMIT);
|
|
9022
|
-
return { daemonSocket, runtimeDir, workerDir, workerPrefix:
|
|
9495
|
+
return { daemonSocket, runtimeDir, workerDir, workerPrefix: join12(workerDir, `worker-${workerKey}-`), overlong };
|
|
9023
9496
|
}
|
|
9024
9497
|
async function primeSocketInfo() {
|
|
9025
9498
|
const requested = tmpdir();
|
|
9026
9499
|
const direct = primeSocketPaths(requested);
|
|
9027
9500
|
if (!direct.overlong)
|
|
9028
9501
|
return direct;
|
|
9029
|
-
const fallback =
|
|
9502
|
+
const fallback = join12(switcherHome(), "r");
|
|
9030
9503
|
await privateDirectory(switcherHome());
|
|
9031
9504
|
await privateDirectory(fallback);
|
|
9032
9505
|
const scoped = primeSocketPaths(fallback);
|
|
@@ -9123,7 +9596,7 @@ async function primeStartSupervisor(input, executable, socketPath, env, onSpawn)
|
|
|
9123
9596
|
}
|
|
9124
9597
|
}
|
|
9125
9598
|
async function primeOwnedShutdown(socketPath, workerPrefix) {
|
|
9126
|
-
const exists = () =>
|
|
9599
|
+
const exists = () => access3(socketPath).then(() => true, () => false);
|
|
9127
9600
|
const workerEntries = () => readdir4(workerPrefix.slice(0, workerPrefix.lastIndexOf("/"))).then((entries) => entries.filter((entry) => entry.startsWith(workerPrefix.slice(workerPrefix.lastIndexOf("/") + 1))), () => []);
|
|
9128
9601
|
if (!await exists())
|
|
9129
9602
|
throw new Error(`Prime Agent owned daemon socket disappeared before cleanup (${socketPath}).`);
|
|
@@ -9203,11 +9676,11 @@ async function primeWaitExit(supervisor, timeout) {
|
|
|
9203
9676
|
return await Promise.race([supervisor.exited.then(() => true), new Promise((resolve9) => setTimeout(() => resolve9(false), timeout))]);
|
|
9204
9677
|
}
|
|
9205
9678
|
async function primeRemainingSockets(socketPath, workerPrefix) {
|
|
9206
|
-
const daemon = await
|
|
9679
|
+
const daemon = await access3(socketPath).then(() => true, () => false);
|
|
9207
9680
|
const workerDir = workerPrefix.slice(0, workerPrefix.lastIndexOf("/"));
|
|
9208
9681
|
const prefix = workerPrefix.slice(workerPrefix.lastIndexOf("/") + 1);
|
|
9209
9682
|
const workers = await readdir4(workerDir).then((entries) => entries.filter((entry) => entry.startsWith(prefix)), () => []);
|
|
9210
|
-
return [...daemon ? [socketPath] : [], ...workers.map((entry) =>
|
|
9683
|
+
return [...daemon ? [socketPath] : [], ...workers.map((entry) => join12(workerDir, entry))];
|
|
9211
9684
|
}
|
|
9212
9685
|
function primeModel(input, api) {
|
|
9213
9686
|
return input.models.map((model3) => ({
|
|
@@ -9225,7 +9698,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9225
9698
|
if (!compatible(input.harness, input.protocol))
|
|
9226
9699
|
throw new Error("Harness and provider protocol are incompatible.");
|
|
9227
9700
|
validateHarnessVersion(input.harness, input.version);
|
|
9228
|
-
if (!
|
|
9701
|
+
if (!isAbsolute11(input.stateDir) || !isAbsolute11(input.cwd))
|
|
9229
9702
|
throw new Error("Launch state and working directories must be absolute.");
|
|
9230
9703
|
if (!input.models.length || !input.models.some((m) => m.id === input.model))
|
|
9231
9704
|
throw new Error("Selected model is missing from the launch catalog.");
|
|
@@ -9263,7 +9736,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9263
9736
|
}
|
|
9264
9737
|
if (input.harness === "codex") {
|
|
9265
9738
|
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 });
|
|
9266
|
-
const file2 = await jsonFile(input.stateDir, "codex-models.json", { models: input.models.map(codexModel) });
|
|
9739
|
+
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)) });
|
|
9267
9740
|
configPaths.push(file2);
|
|
9268
9741
|
configPaths.push(...Object.values(rolePolicy2.agentConfigPaths));
|
|
9269
9742
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
@@ -9282,7 +9755,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9282
9755
|
overrides.push("-c", `agents.${name}.config_file=${quote(path)}`);
|
|
9283
9756
|
}
|
|
9284
9757
|
overrides.push("-c", `memories.extract_model=${quote(input.model)}`, "-c", `memories.consolidation_model=${quote(input.model)}`);
|
|
9285
|
-
|
|
9758
|
+
if (input.reasoning)
|
|
9759
|
+
overrides.push("-c", `model_reasoning_effort=${quote(input.reasoning)}`);
|
|
9760
|
+
if (input.dangerouslyBypassApprovalsAndSandbox)
|
|
9761
|
+
overrides.push("-c", 'approval_policy="never"', "-c", 'sandbox_mode="danger-full-access"');
|
|
9762
|
+
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.");
|
|
9763
|
+
if (input.dangerouslyBypassApprovalsAndSandbox)
|
|
9764
|
+
warnings.push("Full access: approval prompts and command sandboxing are disabled for this launch.");
|
|
9286
9765
|
return { executable, args: [...overrides, ...args], env, configPaths, warnings };
|
|
9287
9766
|
}
|
|
9288
9767
|
if (input.harness === "grok") {
|
|
@@ -9306,8 +9785,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9306
9785
|
throw new Error("Pi cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
9307
9786
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions", "gemini-generate-content": "gemini" }[input.protocol];
|
|
9308
9787
|
const providerId = piProviderId(input, providerBaseUrl);
|
|
9309
|
-
const agentDir =
|
|
9310
|
-
const sessionDir = input.sessionDir ??
|
|
9788
|
+
const agentDir = join12(input.stateDir, "pi-agent");
|
|
9789
|
+
const sessionDir = input.sessionDir ?? join12(input.stateDir, "sessions");
|
|
9311
9790
|
const piBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
|
|
9312
9791
|
await mkdir10(agentDir, { recursive: true, mode: 448 });
|
|
9313
9792
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
@@ -9332,9 +9811,9 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9332
9811
|
const selected = dshArguments(args);
|
|
9333
9812
|
const providerId = piProviderId(input, providerBaseUrl);
|
|
9334
9813
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
|
|
9335
|
-
const home =
|
|
9336
|
-
const sessionDir = input.sessionDir ??
|
|
9337
|
-
if (!
|
|
9814
|
+
const home = join12(input.stateDir, "dsh-home");
|
|
9815
|
+
const sessionDir = input.sessionDir ?? join12(input.stateDir, "dsh-state");
|
|
9816
|
+
if (!isAbsolute11(sessionDir))
|
|
9338
9817
|
throw new Error("DSH session directory must be absolute.");
|
|
9339
9818
|
await mkdir10(home, { recursive: true, mode: 448 });
|
|
9340
9819
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
@@ -9355,7 +9834,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9355
9834
|
}))
|
|
9356
9835
|
} } } },
|
|
9357
9836
|
{ id: "agent-default-model", config: route2 },
|
|
9358
|
-
{ id: "session-persistence-jsonl", config: { root:
|
|
9837
|
+
{ id: "session-persistence-jsonl", config: { root: join12(sessionDir, "sessions") } },
|
|
9359
9838
|
{ id: "attachment-local", config: { dshHome: sessionDir } },
|
|
9360
9839
|
...selected.profile === "acp" ? [{ id: "acp", config: route2 }] : []
|
|
9361
9840
|
];
|
|
@@ -9381,14 +9860,14 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9381
9860
|
throw new Error("Prime Agent cannot safely select model IDs that differ only by letter case; update the provider catalog.");
|
|
9382
9861
|
const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
|
|
9383
9862
|
const providerId = primeProviderId(input, providerBaseUrl);
|
|
9384
|
-
const sessionDir = input.sessionDir ??
|
|
9385
|
-
const agentDir =
|
|
9863
|
+
const sessionDir = input.sessionDir ?? join12(input.stateDir, "sessions");
|
|
9864
|
+
const agentDir = join12(input.stateDir, "prime-agent");
|
|
9386
9865
|
const socketInfo = await primeSocketInfo();
|
|
9387
9866
|
const { daemonSocket, runtimeDir, workerPrefix } = socketInfo;
|
|
9388
9867
|
const primeBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
|
|
9389
9868
|
await mkdir10(agentDir, { recursive: true, mode: 448 });
|
|
9390
9869
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
9391
|
-
const file2 =
|
|
9870
|
+
const file2 = join12(agentDir, "models.json");
|
|
9392
9871
|
await writeFile10(file2, JSON.stringify({ providers: { [providerId]: {
|
|
9393
9872
|
name: "Switcher",
|
|
9394
9873
|
baseUrl: primeBaseUrl,
|
|
@@ -9480,13 +9959,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9480
9959
|
const file2 = await jsonFile(input.stateDir, "opencode-legacy.json", config2);
|
|
9481
9960
|
configPaths.push(file2);
|
|
9482
9961
|
env.OPENCODE_CONFIG = file2;
|
|
9483
|
-
const sessionDir = input.sessionDir ??
|
|
9962
|
+
const sessionDir = input.sessionDir ?? join12(input.stateDir, "sessions");
|
|
9484
9963
|
await mkdir10(sessionDir, { recursive: true, mode: 448 });
|
|
9485
|
-
env.XDG_DATA_HOME =
|
|
9486
|
-
env.XDG_CONFIG_HOME =
|
|
9487
|
-
env.XDG_CACHE_HOME =
|
|
9488
|
-
env.XDG_STATE_HOME =
|
|
9489
|
-
env.HOME =
|
|
9964
|
+
env.XDG_DATA_HOME = join12(sessionDir, "data");
|
|
9965
|
+
env.XDG_CONFIG_HOME = join12(input.stateDir, "config");
|
|
9966
|
+
env.XDG_CACHE_HOME = join12(input.stateDir, "cache");
|
|
9967
|
+
env.XDG_STATE_HOME = join12(input.stateDir, "state");
|
|
9968
|
+
env.HOME = join12(input.stateDir, "home");
|
|
9490
9969
|
env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";
|
|
9491
9970
|
env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config2);
|
|
9492
9971
|
env[KEY4] = input.credential ?? "switcher-local-no-auth";
|
|
@@ -9510,7 +9989,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
|
|
|
9510
9989
|
const rolePolicy = compileOpenCodeModelPolicy({ providerId: providerID, mainModel: input.model, roles: input.compiledPolicy?.roles, preservedAgents: Object.entries(isolated.config.agents ?? {}).map(([name, agent]) => ({ ...agent, name })) });
|
|
9511
9990
|
const modelRef = openCodeInvocationModel(args, rolePolicy, isolated.config.default_agent);
|
|
9512
9991
|
const config = { ...isolated.config, ...rolePolicy.config, providers: { [providerID]: { name: "Switcher", env: [KEY4], package: `@opencode-ai/ai/providers/${packageName}`, settings: settings2, models } } };
|
|
9513
|
-
const file =
|
|
9992
|
+
const file = join12(input.stateDir, "opencode.json");
|
|
9514
9993
|
await writeFile10(file, openCode2ConfigText(config, providerID, KEY4), { mode: 384, flag: "wx" });
|
|
9515
9994
|
configPaths.push(file, isolated.instructionFile);
|
|
9516
9995
|
Object.assign(env, isolated.env);
|
|
@@ -9595,7 +10074,7 @@ async function prepareHarnessLaunch(input) {
|
|
|
9595
10074
|
validateHarnessVersion(input.harness, input.version);
|
|
9596
10075
|
if (!compatible(input.harness, input.protocol))
|
|
9597
10076
|
throw new Error("Harness and provider protocol are incompatible.");
|
|
9598
|
-
if (!
|
|
10077
|
+
if (!isAbsolute11(input.stateDir) || !isAbsolute11(input.cwd))
|
|
9599
10078
|
throw new Error("Launch state and working directories must be absolute.");
|
|
9600
10079
|
const compiledPolicy = compileModelPolicy(input.model, input.models, input.modelPolicy);
|
|
9601
10080
|
input = { ...input, models: input.models.filter((model3) => !modelExpired(model3)) };
|
|
@@ -9626,9 +10105,9 @@ async function prepareHarnessLaunch(input) {
|
|
|
9626
10105
|
}
|
|
9627
10106
|
|
|
9628
10107
|
// src/ori-model-policy.ts
|
|
9629
|
-
import { isAbsolute as
|
|
10108
|
+
import { isAbsolute as isAbsolute12 } from "path";
|
|
9630
10109
|
function prepareOriModelPolicy(target, prepared) {
|
|
9631
|
-
if (!
|
|
10110
|
+
if (!isAbsolute12(prepared.executable) || /[\0\r\n]/.test(prepared.executable))
|
|
9632
10111
|
throw new Error("Ori requires an absolute verified native executable.");
|
|
9633
10112
|
const entries = Object.entries(prepared.env);
|
|
9634
10113
|
if (entries.some(([key]) => !/^[A-Z_][A-Z0-9_]*$/.test(key)))
|
|
@@ -9652,13 +10131,13 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
|
|
|
9652
10131
|
}
|
|
9653
10132
|
|
|
9654
10133
|
// src/launcher.ts
|
|
9655
|
-
import { mkdir as mkdir11, mkdtemp, rm as
|
|
9656
|
-
import { join as
|
|
10134
|
+
import { mkdir as mkdir11, mkdtemp, rm as rm6, writeFile as writeFile14 } from "fs/promises";
|
|
10135
|
+
import { join as join15, resolve as resolve9 } from "path";
|
|
9657
10136
|
|
|
9658
10137
|
// src/harness-process.ts
|
|
9659
10138
|
import { spawn, spawnSync } from "child_process";
|
|
9660
10139
|
import { EventEmitter } from "events";
|
|
9661
|
-
import { existsSync, openSync, closeSync, writeSync, readSync, constants as
|
|
10140
|
+
import { existsSync, openSync, closeSync, writeSync, readSync, constants as constants5 } from "fs";
|
|
9662
10141
|
|
|
9663
10142
|
// src/terminal-descriptors.ts
|
|
9664
10143
|
async function terminalDescriptorDuplicator() {
|
|
@@ -9681,7 +10160,7 @@ async function terminalDescriptorDuplicator() {
|
|
|
9681
10160
|
// src/harness-process.ts
|
|
9682
10161
|
async function runHarnessProcess(options) {
|
|
9683
10162
|
const tty = [Boolean(process.stdin.isTTY), Boolean(process.stdout.isTTY), Boolean(process.stderr.isTTY)];
|
|
9684
|
-
const grouped = process.platform !== "win32", interactive = grouped && tty.some(Boolean);
|
|
10163
|
+
const grouped = process.platform !== "win32", interactive = !options.silent && grouped && tty.some(Boolean);
|
|
9685
10164
|
const redirects = interactive ? tty.flatMap((value, index) => value ? [] : [index]) : [];
|
|
9686
10165
|
const duplicator = redirects.length ? await terminalDescriptorDuplicator() : undefined;
|
|
9687
10166
|
return new Promise((resolveResult, reject2) => {
|
|
@@ -9708,7 +10187,7 @@ async function runHarnessProcess(options) {
|
|
|
9708
10187
|
let resize;
|
|
9709
10188
|
const child = (() => {
|
|
9710
10189
|
if (!interactive)
|
|
9711
|
-
return spawn(options.executable, options.args, { cwd: options.cwd, env: options.env, stdio: "inherit", shell: false, detached: grouped });
|
|
10190
|
+
return spawn(options.executable, options.args, { cwd: options.cwd, env: options.env, stdio: options.silent ? "ignore" : "inherit", shell: false, detached: grouped });
|
|
9712
10191
|
const duplicates = [];
|
|
9713
10192
|
let native;
|
|
9714
10193
|
try {
|
|
@@ -9914,7 +10393,7 @@ async function runHarnessProcess(options) {
|
|
|
9914
10393
|
process.stdin.on("data", relay);
|
|
9915
10394
|
process.stdin.resume();
|
|
9916
10395
|
} else {
|
|
9917
|
-
controllingInput = openSync("/dev/tty",
|
|
10396
|
+
controllingInput = openSync("/dev/tty", constants5.O_RDONLY | constants5.O_NONBLOCK);
|
|
9918
10397
|
stty(["raw", "-echo"]);
|
|
9919
10398
|
const buffer = Buffer.alloc(4096);
|
|
9920
10399
|
inputTimer = setInterval(() => {
|
|
@@ -9945,9 +10424,9 @@ async function runHarnessProcess(options) {
|
|
|
9945
10424
|
}
|
|
9946
10425
|
|
|
9947
10426
|
// src/ori-backend.ts
|
|
9948
|
-
import { execFile as
|
|
9949
|
-
import { promisify as
|
|
9950
|
-
var exec =
|
|
10427
|
+
import { execFile as execFile3 } from "child_process";
|
|
10428
|
+
import { promisify as promisify3 } from "util";
|
|
10429
|
+
var exec = promisify3(execFile3);
|
|
9951
10430
|
var oriProviderCatalog = Object.freeze([{
|
|
9952
10431
|
id: "openrouter",
|
|
9953
10432
|
displayName: "OpenRouter",
|
|
@@ -10179,12 +10658,292 @@ function oriLaunchWarnings(target) {
|
|
|
10179
10658
|
return target === "grok" ? ["Ori supplies Grok's account-entitled OpenRouter catalog; it is not the Switcher-filtered catalog snapshot."] : [];
|
|
10180
10659
|
}
|
|
10181
10660
|
|
|
10661
|
+
// src/chatgpt-launch.ts
|
|
10662
|
+
import { createHash as createHash9 } from "crypto";
|
|
10663
|
+
import { writeFile as writeFile12, rm as rm4 } from "fs/promises";
|
|
10664
|
+
import { join as join13 } from "path";
|
|
10665
|
+
|
|
10666
|
+
// src/desktop-state.ts
|
|
10667
|
+
import { Database as Database3 } from "bun:sqlite";
|
|
10668
|
+
import { readFile as readFile5, writeFile as writeFile11, rm as rm3, lstat as lstat4, rename as rename2, chmod as chmod2 } from "fs/promises";
|
|
10669
|
+
async function safeDesktopRead(path) {
|
|
10670
|
+
try {
|
|
10671
|
+
const info = await lstat4(path);
|
|
10672
|
+
if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
|
|
10673
|
+
throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user.");
|
|
10674
|
+
return await readFile5(path, "utf8");
|
|
10675
|
+
} catch (error) {
|
|
10676
|
+
if (error.code === "ENOENT")
|
|
10677
|
+
return;
|
|
10678
|
+
throw error;
|
|
10679
|
+
}
|
|
10680
|
+
}
|
|
10681
|
+
async function writeDesktopPrivate(path, text) {
|
|
10682
|
+
const temporary = path + "." + crypto.randomUUID() + ".tmp";
|
|
10683
|
+
try {
|
|
10684
|
+
await writeFile11(temporary, text, { mode: 384, flag: "wx" });
|
|
10685
|
+
await rename2(temporary, path);
|
|
10686
|
+
} finally {
|
|
10687
|
+
await rm3(temporary, { force: true });
|
|
10688
|
+
}
|
|
10689
|
+
}
|
|
10690
|
+
async function desktopLease(path) {
|
|
10691
|
+
try {
|
|
10692
|
+
const info = await lstat4(path);
|
|
10693
|
+
if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
|
|
10694
|
+
throw new Fault(422, "desktop_state_permissions", "Desktop lease must be a regular file owned by this user.");
|
|
10695
|
+
} catch (error) {
|
|
10696
|
+
if (error.code !== "ENOENT")
|
|
10697
|
+
throw error;
|
|
10698
|
+
}
|
|
10699
|
+
const lease = new Database3(path);
|
|
10700
|
+
try {
|
|
10701
|
+
await chmod2(path, 384);
|
|
10702
|
+
lease.exec("PRAGMA busy_timeout=0; CREATE TABLE IF NOT EXISTS lease (id INTEGER PRIMARY KEY); BEGIN EXCLUSIVE;");
|
|
10703
|
+
} catch {
|
|
10704
|
+
lease.close();
|
|
10705
|
+
throw new Fault(409, "desktop_busy", "This desktop provider profile is already running. Quit that instance before launching it again.");
|
|
10706
|
+
}
|
|
10707
|
+
let closed = false;
|
|
10708
|
+
return () => {
|
|
10709
|
+
if (!closed) {
|
|
10710
|
+
closed = true;
|
|
10711
|
+
lease.close();
|
|
10712
|
+
}
|
|
10713
|
+
};
|
|
10714
|
+
}
|
|
10715
|
+
|
|
10716
|
+
// src/chatgpt-launch.ts
|
|
10717
|
+
var object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
10718
|
+
function merge2(base, overlay) {
|
|
10719
|
+
const result = { ...base };
|
|
10720
|
+
for (const [key, value] of Object.entries(overlay))
|
|
10721
|
+
result[key] = object5(value) && object5(result[key]) ? merge2(result[key], value) : value;
|
|
10722
|
+
return result;
|
|
10723
|
+
}
|
|
10724
|
+
var digest = (value) => createHash9("sha256").update(value).digest("hex");
|
|
10725
|
+
var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
|
|
10726
|
+
async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
|
|
10727
|
+
await privateDirectory(sessionDir);
|
|
10728
|
+
const home = join13(sessionDir, "codex"), userData = join13(sessionDir, "electron");
|
|
10729
|
+
await privateDirectory(home);
|
|
10730
|
+
await privateDirectory(userData);
|
|
10731
|
+
const release = await desktopLease(join13(sessionDir, "launch.sqlite"));
|
|
10732
|
+
let released = false, authText;
|
|
10733
|
+
const authPath = join13(home, "auth.json"), receiptPath = join13(home, ".switcher-auth.sha256");
|
|
10734
|
+
const cleanup = async () => {
|
|
10735
|
+
if (released)
|
|
10736
|
+
return;
|
|
10737
|
+
released = true;
|
|
10738
|
+
try {
|
|
10739
|
+
if (authText !== undefined && await safeDesktopRead(authPath) === authText) {
|
|
10740
|
+
await rm4(authPath, { force: true });
|
|
10741
|
+
await rm4(receiptPath, { force: true });
|
|
10742
|
+
}
|
|
10743
|
+
} finally {
|
|
10744
|
+
release();
|
|
10745
|
+
}
|
|
10746
|
+
};
|
|
10747
|
+
try {
|
|
10748
|
+
const settings2 = [];
|
|
10749
|
+
for (let i = 0;i < native.args.length; i += 2) {
|
|
10750
|
+
if (native.args[i] !== "-c" || typeof native.args[i + 1] !== "string")
|
|
10751
|
+
throw new Fault(400, "desktop_arguments", "Desktop launches accept provider/model settings, not native CLI commands.");
|
|
10752
|
+
settings2.push(native.args[i + 1]);
|
|
10753
|
+
}
|
|
10754
|
+
settings2.push('cli_auth_credentials_store="file"', 'forced_login_method="api"');
|
|
10755
|
+
if (!settings2.some((setting) => setting.startsWith("approval_policy=")))
|
|
10756
|
+
settings2.push('approval_policy="on-request"');
|
|
10757
|
+
if (!settings2.some((setting) => setting.startsWith("sandbox_mode=")))
|
|
10758
|
+
settings2.push('sandbox_mode="workspace-write"');
|
|
10759
|
+
const configPath = join13(home, "config.toml");
|
|
10760
|
+
const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
|
|
10761
|
+
if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
|
|
10762
|
+
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.");
|
|
10763
|
+
let existing = {};
|
|
10764
|
+
try {
|
|
10765
|
+
existing = Bun.TOML.parse(await safeDesktopRead(configPath) ?? "");
|
|
10766
|
+
} catch (error) {
|
|
10767
|
+
if (error.code !== "ENOENT")
|
|
10768
|
+
throw new Fault(422, "desktop_config_invalid", "The desktop profile config cannot be read safely.");
|
|
10769
|
+
}
|
|
10770
|
+
const config = merge2(existing, Bun.TOML.parse(settings2.join(`
|
|
10771
|
+
`)));
|
|
10772
|
+
await writeDesktopPrivate(configPath, renderCodexAgentToml(config));
|
|
10773
|
+
const key = native.env.SWITCHER_HARNESS_API_KEY;
|
|
10774
|
+
if (!key)
|
|
10775
|
+
throw new Fault(500, "desktop_auth_missing", "Desktop preparation did not receive a scoped gateway credential.");
|
|
10776
|
+
authText = JSON.stringify({ OPENAI_API_KEY: key }) + `
|
|
10777
|
+
`;
|
|
10778
|
+
await writeDesktopPrivate(receiptPath, digest(authText));
|
|
10779
|
+
await writeDesktopPrivate(authPath, authText);
|
|
10780
|
+
const wrapper = join13(stateDir, "chatgpt-codex");
|
|
10781
|
+
const overrides = settings2.flatMap((setting) => ["-c", setting]);
|
|
10782
|
+
await writeFile12(wrapper, `#!/bin/sh
|
|
10783
|
+
set -eu
|
|
10784
|
+
unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
|
|
10785
|
+
export CODEX_HOME=${quote2(home)}
|
|
10786
|
+
if [ "\${1-}" = sandbox ]; then
|
|
10787
|
+
exec ${quote2(app.codexExecutable)} "$@"
|
|
10788
|
+
fi
|
|
10789
|
+
exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
|
|
10790
|
+
`, { mode: 448, flag: "wx" });
|
|
10791
|
+
return {
|
|
10792
|
+
...native,
|
|
10793
|
+
executable: app.executable,
|
|
10794
|
+
args: [`--user-data-dir=${userData}`],
|
|
10795
|
+
env: { ...native.env, CODEX_HOME: home, CODEX_ELECTRON_USER_DATA_PATH: userData, CODEX_CLI_PATH: wrapper, CODEX_APP_SERVER_FORCE_CLI: "1", CODEX_APP_SERVER_USE_LOCAL_DAEMON: "0" },
|
|
10796
|
+
configPaths: [...native.configPaths, configPath, wrapper],
|
|
10797
|
+
warnings: [...native.warnings, `ChatGPT provider profile: ${sessionDir}. Local Codex conversations use this provider; ChatGPT cloud Chat/Work and account-only features are not redirected. Keep Switcher running until you quit this app instance.`],
|
|
10798
|
+
cleanup: async () => {
|
|
10799
|
+
try {
|
|
10800
|
+
await native.cleanup?.();
|
|
10801
|
+
} finally {
|
|
10802
|
+
await cleanup();
|
|
10803
|
+
}
|
|
10804
|
+
}
|
|
10805
|
+
};
|
|
10806
|
+
} catch (error) {
|
|
10807
|
+
await cleanup();
|
|
10808
|
+
throw error;
|
|
10809
|
+
}
|
|
10810
|
+
}
|
|
10811
|
+
|
|
10812
|
+
// src/claude-desktop-launch.ts
|
|
10813
|
+
import { createHash as createHash10 } from "crypto";
|
|
10814
|
+
import { execFile as execFile4 } from "child_process";
|
|
10815
|
+
import { access as access4, rm as rm5, writeFile as writeFile13 } from "fs/promises";
|
|
10816
|
+
import { homedir as homedir8, userInfo as userInfo2 } from "os";
|
|
10817
|
+
import { join as join14 } from "path";
|
|
10818
|
+
import { promisify as promisify4 } from "util";
|
|
10819
|
+
var execute3 = promisify4(execFile4);
|
|
10820
|
+
var hash2 = (text) => createHash10("sha256").update(text).digest("hex");
|
|
10821
|
+
var claudeDesktopDataDirectory = () => join14(homedir8(), "Library/Application Support/Claude-3p");
|
|
10822
|
+
async function assertAvailable(userData) {
|
|
10823
|
+
for (const path of [join14("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
|
|
10824
|
+
if (await access4(path).then(() => true, () => false))
|
|
10825
|
+
throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
|
|
10826
|
+
let openFiles;
|
|
10827
|
+
try {
|
|
10828
|
+
openFiles = (await execute3("/usr/sbin/lsof", ["-n", "-P", "-Fpn", "-a", "-u", String(process.getuid?.()), "-c", "Claude"], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, timeout: 8000 })).stdout;
|
|
10829
|
+
} catch (error) {
|
|
10830
|
+
if (error.code === 1)
|
|
10831
|
+
return;
|
|
10832
|
+
throw new Fault(409, "desktop_process_check", "Could not check whether Claude's third-party profile is already running.");
|
|
10833
|
+
}
|
|
10834
|
+
if (openFiles.split(`
|
|
10835
|
+
`).some((line) => line.startsWith("n" + userData + "/")))
|
|
10836
|
+
throw new Fault(409, "desktop_busy", "Claude's third-party instance is already running. Quit that instance before changing its provider; the normal Claude instance can stay open.");
|
|
10837
|
+
}
|
|
10838
|
+
function metadata(text) {
|
|
10839
|
+
const value = text === undefined ? { entries: [] } : JSON.parse(text);
|
|
10840
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((item) => !item || typeof item !== "object" || Array.isArray(item)))
|
|
10841
|
+
throw new Fault(422, "desktop_config_invalid", "Claude's configuration library metadata is invalid.");
|
|
10842
|
+
return value;
|
|
10843
|
+
}
|
|
10844
|
+
async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
|
|
10845
|
+
if (input.harness !== "claude")
|
|
10846
|
+
throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
|
|
10847
|
+
validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
|
|
10848
|
+
if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
|
|
10849
|
+
throw new Fault(400, "desktop_arguments", "Claude desktop uses its own effort and permission controls; native CLI arguments and Codex-only launch controls are not accepted.");
|
|
10850
|
+
const version = app.version.split(".").map(Number);
|
|
10851
|
+
if (version.length < 3 || version.some((n) => !Number.isSafeInteger(n)) || version[0] < 1 || version[0] === 1 && version[1] < 52386)
|
|
10852
|
+
throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
|
|
10853
|
+
const userData = system?.userData ?? claudeDesktopDataDirectory();
|
|
10854
|
+
const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
|
|
10855
|
+
await check2();
|
|
10856
|
+
await privateDirectory(userData);
|
|
10857
|
+
const library = join14(userData, "configLibrary");
|
|
10858
|
+
await privateDirectory(library);
|
|
10859
|
+
const release = await desktopLease(join14(library, ".switcher-lease.sqlite"));
|
|
10860
|
+
const metaPath = join14(library, "_meta.json"), receiptPath = join14(library, ".switcher-selection.json");
|
|
10861
|
+
let receipt, gateway, closed = false;
|
|
10862
|
+
const restore = async (record3) => {
|
|
10863
|
+
if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
|
|
10864
|
+
throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
|
|
10865
|
+
const configPath = join14(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
|
|
10866
|
+
if (current !== undefined && hash2(current) !== record3.configHash)
|
|
10867
|
+
throw new Fault(409, "desktop_config_changed", "The Switcher Claude configuration was edited outside this launch. Switcher will preserve it; review the configuration library before relaunching.");
|
|
10868
|
+
const currentMeta = await safeDesktopRead(metaPath);
|
|
10869
|
+
if (currentMeta !== record3.appliedMeta && currentMeta !== (record3.previousMeta ?? undefined))
|
|
10870
|
+
throw new Fault(409, "desktop_config_changed", "Claude's selected configuration changed during this launch. Switcher will preserve the changed selection; review its configuration library before relaunching.");
|
|
10871
|
+
if (record3.previousMeta === null)
|
|
10872
|
+
await rm5(metaPath, { force: true });
|
|
10873
|
+
else
|
|
10874
|
+
await writeDesktopPrivate(metaPath, record3.previousMeta);
|
|
10875
|
+
await rm5(configPath, { force: true });
|
|
10876
|
+
await rm5(receiptPath, { force: true });
|
|
10877
|
+
};
|
|
10878
|
+
const cleanup = async () => {
|
|
10879
|
+
if (closed)
|
|
10880
|
+
return;
|
|
10881
|
+
closed = true;
|
|
10882
|
+
try {
|
|
10883
|
+
await gateway?.cleanup();
|
|
10884
|
+
if (receipt)
|
|
10885
|
+
await restore(receipt);
|
|
10886
|
+
} finally {
|
|
10887
|
+
release();
|
|
10888
|
+
}
|
|
10889
|
+
};
|
|
10890
|
+
try {
|
|
10891
|
+
const recovery = await safeDesktopRead(receiptPath);
|
|
10892
|
+
if (recovery)
|
|
10893
|
+
await restore(JSON.parse(recovery));
|
|
10894
|
+
const localConfig = await safeDesktopRead(join14(userData, "claude_desktop_config.json"));
|
|
10895
|
+
if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
|
|
10896
|
+
throw new Fault(409, "desktop_mode", "Claude's third-party profile is set to standard account mode. Select third-party mode in Claude before launching this gateway.");
|
|
10897
|
+
await privateDirectory(sessionDir);
|
|
10898
|
+
const roles2 = input.modelPolicy?.roles;
|
|
10899
|
+
const targets = { sonnet: input.model, opus: roles2?.planning ?? input.model, haiku: roles2?.fast ?? input.model };
|
|
10900
|
+
const aliases = Object.fromEntries(Object.entries(targets).map(([tier, model3]) => ["switcher/" + tier, model3]));
|
|
10901
|
+
for (const [alias, target] of Object.entries(aliases))
|
|
10902
|
+
if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
|
|
10903
|
+
throw new Fault(409, "desktop_alias_conflict", "The model policy conflicts with Claude desktop's reserved switcher/sonnet, switcher/opus or switcher/haiku routing aliases.");
|
|
10904
|
+
const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
|
|
10905
|
+
const catalogPath = join14(input.stateDir, "claude-desktop-policy.json");
|
|
10906
|
+
await writeFile13(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
|
|
10907
|
+
gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
|
|
10908
|
+
const id2 = crypto.randomUUID(), configPath = join14(library, id2 + ".json");
|
|
10909
|
+
const config = JSON.stringify({
|
|
10910
|
+
inferenceProvider: "gateway",
|
|
10911
|
+
inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
|
|
10912
|
+
inferenceGatewayApiKey: gateway.token,
|
|
10913
|
+
inferenceGatewayAuthScheme: "bearer",
|
|
10914
|
+
modelDiscoveryEnabled: false,
|
|
10915
|
+
inferenceModels: Object.entries(targets).map(([tier, model3]) => ({ name: "switcher/" + tier, labelOverride: model3, anthropicFamilyTier: tier, isFamilyDefault: true }))
|
|
10916
|
+
});
|
|
10917
|
+
const previousMeta = await safeDesktopRead(metaPath);
|
|
10918
|
+
const meta = metadata(previousMeta);
|
|
10919
|
+
const appliedMeta = JSON.stringify({ ...meta, appliedId: id2, entries: [...meta.entries, { id: id2, name: `Switcher: ${input.providerId ?? "provider"} / ${input.model}` }] });
|
|
10920
|
+
receipt = { id: id2, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
|
|
10921
|
+
await writeDesktopPrivate(configPath, config);
|
|
10922
|
+
await writeDesktopPrivate(receiptPath, JSON.stringify(receipt));
|
|
10923
|
+
await writeDesktopPrivate(metaPath, appliedMeta);
|
|
10924
|
+
return {
|
|
10925
|
+
executable: app.executable,
|
|
10926
|
+
args: [],
|
|
10927
|
+
env: { CLAUDE_CONFIG_DIR: sessionDir },
|
|
10928
|
+
configPaths: [catalogPath, configPath],
|
|
10929
|
+
beforeLaunch: check2,
|
|
10930
|
+
cleanup,
|
|
10931
|
+
warnings: [`Claude desktop gateway: ${input.providerId ?? "provider"} / ${input.model}. Uses the shared Claude-3p profile, separate from the normal Claude account. Quit this instance before switching providers; keep Switcher running until then. The previous configuration selection is restored on exit. Managed settings and native permissions remain authoritative.`]
|
|
10932
|
+
};
|
|
10933
|
+
} catch (error) {
|
|
10934
|
+
try {
|
|
10935
|
+
await cleanup();
|
|
10936
|
+
} catch {}
|
|
10937
|
+
throw error;
|
|
10938
|
+
}
|
|
10939
|
+
}
|
|
10940
|
+
|
|
10182
10941
|
// src/launcher.ts
|
|
10183
10942
|
var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
|
|
10184
10943
|
async function writeOriCodexCatalog(stateDir, models) {
|
|
10185
|
-
const path =
|
|
10186
|
-
const nativeModels2 = models.filter(codingEligible).map(codexModel);
|
|
10187
|
-
await
|
|
10944
|
+
const path = join15(stateDir, "ori-codex-models.json");
|
|
10945
|
+
const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
|
|
10946
|
+
await writeFile14(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
|
|
10188
10947
|
`, { mode: 384, flag: "wx" });
|
|
10189
10948
|
return path;
|
|
10190
10949
|
}
|
|
@@ -10273,9 +11032,9 @@ async function prepareOriForPlan(plan, options) {
|
|
|
10273
11032
|
});
|
|
10274
11033
|
try {
|
|
10275
11034
|
const shim = prepareOriModelPolicy(request.target, native);
|
|
10276
|
-
const dir =
|
|
11035
|
+
const dir = join15(options.stateDir, "ori-bin"), path = join15(dir, shim.name);
|
|
10277
11036
|
await mkdir11(dir, { mode: 448 });
|
|
10278
|
-
await
|
|
11037
|
+
await writeFile14(path, shim.script, { mode: 448, flag: "wx" });
|
|
10279
11038
|
return { contract, prepared: {
|
|
10280
11039
|
...ori,
|
|
10281
11040
|
env: { ...ori.env, ...shim.env, PATH: `${dir}:${ori.env.PATH ?? process.env.PATH ?? ""}` },
|
|
@@ -10292,6 +11051,8 @@ async function prepareOriForPlan(plan, options) {
|
|
|
10292
11051
|
async function launch(client, profileId, options = {}) {
|
|
10293
11052
|
const launchDeadline = options.timeoutMs === undefined ? undefined : Date.now() + options.timeoutMs;
|
|
10294
11053
|
const profile = await client.getProfile(profileId);
|
|
11054
|
+
if ((options.reasoning || options.dangerouslyBypassApprovalsAndSandbox) && (profile.harness !== "codex" || (options.backend ?? "direct") !== "direct"))
|
|
11055
|
+
throw new Error("Reasoning and full-access launch options require direct Codex or ChatGPT.");
|
|
10295
11056
|
assertHarnessArguments(profile.harness, options.args ?? []);
|
|
10296
11057
|
if (profile.harness === "gemini")
|
|
10297
11058
|
validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
|
|
@@ -10312,16 +11073,21 @@ async function launch(client, profileId, options = {}) {
|
|
|
10312
11073
|
throw new Error("--executable is ambiguous with --backend ori; use --ori-executable PATH.");
|
|
10313
11074
|
if (backend === "direct" && options.oriExecutable)
|
|
10314
11075
|
throw new Error("--ori-executable requires --backend ori.");
|
|
10315
|
-
|
|
10316
|
-
|
|
11076
|
+
if (options.desktop && (plan.profile.harness !== "codex" || backend !== "direct"))
|
|
11077
|
+
throw new Error("ChatGPT requires the direct Codex provider adapter.");
|
|
11078
|
+
if (options.claudeDesktop && (options.desktop || plan.profile.harness !== "claude" || backend !== "direct" || options.executable || options.args?.length))
|
|
11079
|
+
throw new Error("Claude desktop requires its direct Messages gateway adapter without native CLI overrides.");
|
|
11080
|
+
const nativeExecutable = options.desktop?.codexExecutable ?? options.executable;
|
|
11081
|
+
const detection = backend === "direct" && !options.claudeDesktop ? await detectHarness(plan.profile.harness, nativeExecutable) : undefined;
|
|
11082
|
+
if (backend === "direct" && !options.claudeDesktop && !detection?.available)
|
|
10317
11083
|
throw new Error(harnessInstallationMessage(plan.profile.harness, detection?.executable ?? plan.profile.harness, Boolean(options.executable)));
|
|
10318
11084
|
if (backend === "direct" && plan.profile.harness === "gemini")
|
|
10319
11085
|
validateHarnessVersion("gemini", detection?.version);
|
|
10320
11086
|
if (backend === "direct" && plan.profile.harness === "aider")
|
|
10321
11087
|
validateHarnessVersion(plan.profile.harness, detection?.version);
|
|
10322
|
-
const root = resolve9(options.stateDir ??
|
|
11088
|
+
const root = resolve9(options.stateDir ?? join15(switcherHome(), "state"));
|
|
10323
11089
|
await privateDirectory(root);
|
|
10324
|
-
const stateDir = await mkdtemp(
|
|
11090
|
+
const stateDir = await mkdtemp(join15(root, "launch-"));
|
|
10325
11091
|
let credential;
|
|
10326
11092
|
if (backend === "direct") {
|
|
10327
11093
|
try {
|
|
@@ -10329,7 +11095,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
10329
11095
|
if (plan.provider.credentialEnv && !credential)
|
|
10330
11096
|
throw new Error("Provider credential environment reference is not available in this local launcher process.");
|
|
10331
11097
|
} catch (error) {
|
|
10332
|
-
await
|
|
11098
|
+
await rm6(stateDir, { recursive: true, force: true });
|
|
10333
11099
|
throw error;
|
|
10334
11100
|
}
|
|
10335
11101
|
}
|
|
@@ -10365,25 +11131,45 @@ async function launch(client, profileId, options = {}) {
|
|
|
10365
11131
|
return;
|
|
10366
11132
|
});
|
|
10367
11133
|
try {
|
|
10368
|
-
const
|
|
11134
|
+
const input = {
|
|
10369
11135
|
harness: plan.profile.harness,
|
|
10370
11136
|
baseUrl: plan.provider.baseUrl,
|
|
10371
11137
|
protocol: plan.provider.protocol,
|
|
11138
|
+
authStyle: plan.provider.authStyle,
|
|
10372
11139
|
model: plan.profile.model,
|
|
10373
11140
|
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
10374
11141
|
modelPolicy: plan.profile.modelPolicy,
|
|
10375
11142
|
providerId: plan.provider.id,
|
|
10376
11143
|
onRoutingEvent,
|
|
10377
11144
|
credential,
|
|
11145
|
+
stateDir,
|
|
11146
|
+
cwd: resolve9(options.cwd ?? process.cwd())
|
|
11147
|
+
};
|
|
11148
|
+
let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join15(root, "desktop-claude", profileId)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent })).prepared : await prepareHarnessLaunch({
|
|
11149
|
+
harness: plan.profile.harness,
|
|
11150
|
+
baseUrl: plan.provider.baseUrl,
|
|
11151
|
+
protocol: plan.provider.protocol,
|
|
11152
|
+
model: plan.profile.model,
|
|
11153
|
+
models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
|
|
11154
|
+
modelPolicy: plan.profile.modelPolicy,
|
|
11155
|
+
providerId: plan.provider.id,
|
|
11156
|
+
onRoutingEvent,
|
|
11157
|
+
reasoning: options.reasoning,
|
|
11158
|
+
dangerouslyBypassApprovalsAndSandbox: options.dangerouslyBypassApprovalsAndSandbox,
|
|
11159
|
+
credential,
|
|
10378
11160
|
authStyle: plan.provider.authStyle,
|
|
10379
|
-
executable:
|
|
11161
|
+
executable: nativeExecutable ?? detection?.executable,
|
|
10380
11162
|
args: options.args ?? [],
|
|
10381
11163
|
stateDir,
|
|
10382
11164
|
cwd: resolve9(options.cwd ?? process.cwd()),
|
|
10383
11165
|
version: detection?.version,
|
|
10384
|
-
...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo"].includes(plan.profile.harness) ? { sessionDir:
|
|
11166
|
+
...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo"].includes(plan.profile.harness) ? { sessionDir: join15(root, "sessions", plan.profile.harness, profileId) } : {}
|
|
10385
11167
|
});
|
|
10386
11168
|
cleanup = prepared.cleanup;
|
|
11169
|
+
if (options.desktop) {
|
|
11170
|
+
prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join15(root, "desktop", profileId));
|
|
11171
|
+
cleanup = prepared.cleanup;
|
|
11172
|
+
}
|
|
10387
11173
|
for (const warning of [...plan.warnings, ...prepared.warnings])
|
|
10388
11174
|
console.error(`switcher: ${warning}`);
|
|
10389
11175
|
const interruptPreparation = (error, cancel = true) => {
|
|
@@ -10458,7 +11244,7 @@ async function launch(client, profileId, options = {}) {
|
|
|
10458
11244
|
interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
|
|
10459
11245
|
throw preparationSignal;
|
|
10460
11246
|
}
|
|
10461
|
-
const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve9(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, timeoutMs: remainingRuntime });
|
|
11247
|
+
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 });
|
|
10462
11248
|
await cleanup?.();
|
|
10463
11249
|
cleanup = undefined;
|
|
10464
11250
|
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}.`);
|
|
@@ -10489,13 +11275,13 @@ async function launch(client, profileId, options = {}) {
|
|
|
10489
11275
|
try {
|
|
10490
11276
|
await cleanup?.();
|
|
10491
11277
|
} finally {
|
|
10492
|
-
await
|
|
11278
|
+
await rm6(stateDir, { recursive: true, force: true });
|
|
10493
11279
|
}
|
|
10494
11280
|
}
|
|
10495
11281
|
}
|
|
10496
11282
|
|
|
10497
11283
|
// src/direct-launch.ts
|
|
10498
|
-
import { createHash as
|
|
11284
|
+
import { createHash as createHash11 } from "crypto";
|
|
10499
11285
|
import { createInterface } from "readline/promises";
|
|
10500
11286
|
var absent = (error) => error instanceof SwitcherError && error.status === 404;
|
|
10501
11287
|
async function resolveLaunchProvider(client, selector, options = {}) {
|
|
@@ -10575,8 +11361,8 @@ async function selectModel(models, query = "", harness) {
|
|
|
10575
11361
|
async function ensureLaunchProfile(client, provider, harness, model3, modelPolicy) {
|
|
10576
11362
|
const normalizedPolicy = modelPolicy === undefined ? undefined : parse2(modelPolicySchema, modelPolicy);
|
|
10577
11363
|
const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
|
|
10578
|
-
const
|
|
10579
|
-
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${
|
|
11364
|
+
const hash3 = createHash11("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
|
|
11365
|
+
const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
|
|
10580
11366
|
let existing;
|
|
10581
11367
|
try {
|
|
10582
11368
|
existing = await client.getProfile(desired.id);
|
|
@@ -10599,57 +11385,57 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
|
|
|
10599
11385
|
}
|
|
10600
11386
|
|
|
10601
11387
|
// src/credentials.ts
|
|
10602
|
-
import { z as
|
|
10603
|
-
import { constants as
|
|
10604
|
-
import { open as open3, readdir as readdir5, unlink, link, lstat as
|
|
10605
|
-
import { join as
|
|
10606
|
-
import { createHash as
|
|
10607
|
-
import { execFile as
|
|
10608
|
-
import { promisify as
|
|
10609
|
-
import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as
|
|
10610
|
-
var
|
|
10611
|
-
var reference =
|
|
10612
|
-
var item =
|
|
10613
|
-
var vaultKey =
|
|
10614
|
-
var keychain =
|
|
10615
|
-
var operator =
|
|
10616
|
-
|
|
10617
|
-
|
|
10618
|
-
|
|
11388
|
+
import { z as z7 } from "zod";
|
|
11389
|
+
import { constants as constants6 } from "fs";
|
|
11390
|
+
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";
|
|
11391
|
+
import { join as join16, isAbsolute as isAbsolute13, dirname as dirname8, parse as pathParts, resolve as resolvePath, sep as sep2 } from "path";
|
|
11392
|
+
import { createHash as createHash12, randomUUID as randomUUID5 } from "crypto";
|
|
11393
|
+
import { execFile as execFile5, spawn as spawn2 } from "child_process";
|
|
11394
|
+
import { promisify as promisify5 } from "util";
|
|
11395
|
+
import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
|
|
11396
|
+
var execute4 = promisify5(execFile5);
|
|
11397
|
+
var reference = z7.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
|
|
11398
|
+
var item = z7.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
|
|
11399
|
+
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");
|
|
11400
|
+
var keychain = z7.object({ kind: z7.literal("keychain"), service: item, account: item }).strict();
|
|
11401
|
+
var operator = z7.discriminatedUnion("kind", [
|
|
11402
|
+
z7.object({ kind: z7.literal("contracts") }).strict(),
|
|
11403
|
+
z7.object({ kind: z7.literal("env") }).strict(),
|
|
11404
|
+
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()
|
|
10619
11405
|
]);
|
|
10620
|
-
var origin =
|
|
10621
|
-
var credentialBindingSchema =
|
|
10622
|
-
schema:
|
|
11406
|
+
var origin = z7.string().transform((value) => new URL(endpoint(value)).origin);
|
|
11407
|
+
var credentialBindingSchema = z7.object({
|
|
11408
|
+
schema: z7.literal(1),
|
|
10623
11409
|
credentialEnv: reference,
|
|
10624
|
-
origins:
|
|
10625
|
-
source:
|
|
10626
|
-
kind:
|
|
11410
|
+
origins: z7.array(origin).min(1).max(30),
|
|
11411
|
+
source: z7.discriminatedUnion("kind", [keychain, z7.object({
|
|
11412
|
+
kind: z7.literal("vault"),
|
|
10627
11413
|
key: vaultKey,
|
|
10628
|
-
url:
|
|
10629
|
-
executable:
|
|
11414
|
+
url: z7.string().max(2000).transform(endpoint).optional(),
|
|
11415
|
+
executable: z7.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute13, "Secrets executable must be an absolute path"),
|
|
10630
11416
|
operator
|
|
10631
11417
|
}).strict()])
|
|
10632
11418
|
}).strict().superRefine((binding, ctx) => {
|
|
10633
11419
|
if (binding.source.kind === "vault" && binding.source.operator.kind !== "contracts" && !binding.source.url)
|
|
10634
11420
|
ctx.addIssue({ code: "custom", path: ["source", "url"], message: "An explicit env or Keychain operator binding requires a vault URL." });
|
|
10635
11421
|
});
|
|
10636
|
-
var fingerprint = (binding) =>
|
|
11422
|
+
var fingerprint = (binding) => createHash12("sha256").update(JSON.stringify(binding)).digest("hex");
|
|
10637
11423
|
|
|
10638
11424
|
class CredentialBindings {
|
|
10639
11425
|
env;
|
|
10640
11426
|
directory;
|
|
10641
11427
|
constructor(env = process.env) {
|
|
10642
11428
|
this.env = env;
|
|
10643
|
-
this.directory =
|
|
11429
|
+
this.directory = join16(switcherHome(env), "config", "credential-bindings");
|
|
10644
11430
|
}
|
|
10645
11431
|
path(name) {
|
|
10646
|
-
return
|
|
11432
|
+
return join16(this.directory, parse2(reference, name) + ".json");
|
|
10647
11433
|
}
|
|
10648
11434
|
async readableDirectory() {
|
|
10649
|
-
for (const path of [switcherHome(this.env),
|
|
11435
|
+
for (const path of [switcherHome(this.env), join16(switcherHome(this.env), "config"), this.directory]) {
|
|
10650
11436
|
let info;
|
|
10651
11437
|
try {
|
|
10652
|
-
info = await
|
|
11438
|
+
info = await lstat5(path);
|
|
10653
11439
|
} catch (error) {
|
|
10654
11440
|
if (error.code === "ENOENT")
|
|
10655
11441
|
return false;
|
|
@@ -10666,7 +11452,7 @@ class CredentialBindings {
|
|
|
10666
11452
|
return;
|
|
10667
11453
|
let file;
|
|
10668
11454
|
try {
|
|
10669
|
-
file = await open3(path,
|
|
11455
|
+
file = await open3(path, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
10670
11456
|
} catch (error) {
|
|
10671
11457
|
if (error.code === "ENOENT")
|
|
10672
11458
|
return;
|
|
@@ -10715,9 +11501,9 @@ class CredentialBindings {
|
|
|
10715
11501
|
if (binding.source.kind === "vault")
|
|
10716
11502
|
await validateVaultExecutable(binding.source.executable);
|
|
10717
11503
|
await privateDirectory(switcherHome(this.env));
|
|
10718
|
-
await privateDirectory(
|
|
11504
|
+
await privateDirectory(join16(switcherHome(this.env), "config"));
|
|
10719
11505
|
await privateDirectory(this.directory);
|
|
10720
|
-
const temporary =
|
|
11506
|
+
const temporary = join16(this.directory, `.binding-${randomUUID5()}`);
|
|
10721
11507
|
const file = await open3(temporary, "wx", 384);
|
|
10722
11508
|
try {
|
|
10723
11509
|
await file.writeFile(JSON.stringify(binding, null, 2) + `
|
|
@@ -10757,8 +11543,8 @@ async function inspectVaultExecutable(path, permitWritableFile = false) {
|
|
|
10757
11543
|
let info, resolved;
|
|
10758
11544
|
try {
|
|
10759
11545
|
resolved = await realpath6(path);
|
|
10760
|
-
await
|
|
10761
|
-
info = await
|
|
11546
|
+
await access5(resolved, constants6.X_OK);
|
|
11547
|
+
info = await stat6(resolved);
|
|
10762
11548
|
if (!info.isFile())
|
|
10763
11549
|
throw new Error;
|
|
10764
11550
|
} catch {
|
|
@@ -10773,13 +11559,13 @@ async function inspectVaultExecutable(path, permitWritableFile = false) {
|
|
|
10773
11559
|
for (const part of candidate.slice(prefix.length).split(sep2)) {
|
|
10774
11560
|
if (!part)
|
|
10775
11561
|
continue;
|
|
10776
|
-
prefix =
|
|
11562
|
+
prefix = join16(prefix, part);
|
|
10777
11563
|
if (seen.has(prefix))
|
|
10778
11564
|
continue;
|
|
10779
11565
|
seen.add(prefix);
|
|
10780
11566
|
if (seen.size > 256)
|
|
10781
11567
|
throw new Fault(422, "vault_exec_permissions", "The secrets executable path has too many symlink components.");
|
|
10782
|
-
const entry = await
|
|
11568
|
+
const entry = await lstat5(prefix);
|
|
10783
11569
|
const permittedFile = permitWritableFile && prefix === resolved && entry.isFile();
|
|
10784
11570
|
if (entry.uid !== 0 && entry.uid !== process.getuid?.() || !entry.isSymbolicLink() && !permittedFile && entry.mode & 18)
|
|
10785
11571
|
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.");
|
|
@@ -10804,12 +11590,12 @@ async function validateVaultExecutable(path) {
|
|
|
10804
11590
|
async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
10805
11591
|
if (!/^[a-f0-9]{64}$/.test(expectedSha256))
|
|
10806
11592
|
throw new Fault(400, "invalid_request", "--sha256 requires the SHA256 of the executable member from a verified package artifact.");
|
|
10807
|
-
if (!
|
|
11593
|
+
if (!isAbsolute13(path) || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path))
|
|
10808
11594
|
throw new Fault(400, "invalid_request", "Secrets executable must be an absolute path without control characters.");
|
|
10809
11595
|
if (process.platform === "win32")
|
|
10810
11596
|
throw new Fault(422, "vault_exec_repair_unsafe", "Executable permission repair requires POSIX file permissions.");
|
|
10811
11597
|
const resolved = await inspectVaultExecutable(path, true);
|
|
10812
|
-
const file = await open3(resolved,
|
|
11598
|
+
const file = await open3(resolved, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
|
|
10813
11599
|
const unsafe = () => new Fault(422, "vault_exec_repair_unsafe", "Executable ownership, type, links or contents changed; no trusted repair can be confirmed.");
|
|
10814
11600
|
let temporary;
|
|
10815
11601
|
try {
|
|
@@ -10818,8 +11604,8 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
10818
11604
|
if (!before.isFile() || before.uid !== process.getuid?.() || before.size > limit || before.mode & 3584)
|
|
10819
11605
|
throw unsafe();
|
|
10820
11606
|
const sameFile = (info) => info.dev === before.dev && info.ino === before.ino && info.size === before.size && info.uid === before.uid && info.nlink === before.nlink && info.mode === before.mode && info.mtimeMs === before.mtimeMs && info.ctimeMs === before.ctimeMs;
|
|
10821
|
-
const
|
|
10822
|
-
const
|
|
11607
|
+
const hash3 = async (target) => {
|
|
11608
|
+
const digest2 = createHash12("sha256");
|
|
10823
11609
|
const buffer = Buffer.alloc(1024 * 1024);
|
|
10824
11610
|
let position = 0;
|
|
10825
11611
|
while (true) {
|
|
@@ -10830,41 +11616,41 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
|
|
|
10830
11616
|
if (position > limit)
|
|
10831
11617
|
throw unsafe();
|
|
10832
11618
|
const bytes = buffer.subarray(0, bytesRead);
|
|
10833
|
-
|
|
11619
|
+
digest2.update(bytes);
|
|
10834
11620
|
if (target)
|
|
10835
11621
|
await target.writeFile(bytes);
|
|
10836
11622
|
}
|
|
10837
11623
|
if (position !== before.size || !sameFile(await file.stat()))
|
|
10838
11624
|
throw unsafe();
|
|
10839
|
-
if (
|
|
11625
|
+
if (digest2.digest("hex") !== expectedSha256)
|
|
10840
11626
|
throw new Fault(422, "vault_exec_digest_mismatch", "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed.");
|
|
10841
11627
|
};
|
|
10842
|
-
await
|
|
11628
|
+
await hash3();
|
|
10843
11629
|
const mode = before.mode & 511 & ~18;
|
|
10844
11630
|
const changed = mode !== (before.mode & 511);
|
|
10845
|
-
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await
|
|
11631
|
+
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat5(resolved)))
|
|
10846
11632
|
throw unsafe();
|
|
10847
11633
|
if (!changed) {
|
|
10848
11634
|
await validateVaultExecutable(path);
|
|
10849
11635
|
return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
|
|
10850
11636
|
}
|
|
10851
|
-
temporary =
|
|
11637
|
+
temporary = join16(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
|
|
10852
11638
|
const replacement = await open3(temporary, "wx", 384);
|
|
10853
11639
|
try {
|
|
10854
|
-
await
|
|
11640
|
+
await hash3(replacement);
|
|
10855
11641
|
await replacement.chmod(mode);
|
|
10856
11642
|
await replacement.sync();
|
|
10857
11643
|
const ready = await replacement.stat();
|
|
10858
11644
|
if (!ready.isFile() || ready.nlink !== 1 || ready.uid !== before.uid || ready.size !== before.size)
|
|
10859
11645
|
throw unsafe();
|
|
10860
|
-
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await
|
|
11646
|
+
if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat5(resolved)))
|
|
10861
11647
|
throw unsafe();
|
|
10862
|
-
await
|
|
11648
|
+
await rename3(temporary, resolved);
|
|
10863
11649
|
temporary = undefined;
|
|
10864
|
-
const installed = await
|
|
11650
|
+
const installed = await lstat5(resolved);
|
|
10865
11651
|
if (installed.dev !== ready.dev || installed.ino !== ready.ino || await validateVaultExecutable(path) !== resolved)
|
|
10866
11652
|
throw unsafe();
|
|
10867
|
-
const directory = await open3(dirname8(resolved),
|
|
11653
|
+
const directory = await open3(dirname8(resolved), constants6.O_RDONLY | constants6.O_DIRECTORY | constants6.O_NOFOLLOW);
|
|
10868
11654
|
try {
|
|
10869
11655
|
await directory.sync();
|
|
10870
11656
|
} finally {
|
|
@@ -10900,15 +11686,19 @@ function bindingTarget(selector, override, allowedOrigins) {
|
|
|
10900
11686
|
async function readKeychain(source) {
|
|
10901
11687
|
if (process.platform !== "darwin")
|
|
10902
11688
|
throw new Fault(422, "keychain_unavailable", "This binding requires macOS Keychain. Use a supported vault binding or runtime environment on this station.");
|
|
11689
|
+
let stdout;
|
|
10903
11690
|
try {
|
|
10904
|
-
|
|
10905
|
-
|
|
10906
|
-
|
|
10907
|
-
|
|
10908
|
-
|
|
10909
|
-
|
|
10910
|
-
|
|
10911
|
-
|
|
11691
|
+
({ stdout } = await execute4("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 }));
|
|
11692
|
+
} catch (error) {
|
|
11693
|
+
const status = error.code;
|
|
11694
|
+
if (status === 44)
|
|
11695
|
+
throw new Fault(422, "keychain_item_missing", "The configured Keychain item does not exist for that service and account; no alternate credential was selected.");
|
|
11696
|
+
throw new Fault(422, "keychain_unavailable", `The configured Keychain item could not be read (security exited ${typeof status === "number" ? status : "without a status"}); it is locked or inaccessible. No alternate credential was selected.`);
|
|
11697
|
+
}
|
|
11698
|
+
const value = stdout.replace(/\r?\n$/, "");
|
|
11699
|
+
if (!value || /[\x00-\x1f\x7f]/.test(value))
|
|
11700
|
+
throw new Fault(422, "keychain_item_invalid", "The configured Keychain item holds an unusable value; no alternate credential was selected.");
|
|
11701
|
+
return value;
|
|
10912
11702
|
}
|
|
10913
11703
|
|
|
10914
11704
|
class CredentialResolver {
|
|
@@ -10944,7 +11734,7 @@ class CredentialResolver {
|
|
|
10944
11734
|
return { credentialEnv: name, source: "vault", available: true, length: Number(match[1]), sha256: match[2], providerAuthentication: "not tested" };
|
|
10945
11735
|
}
|
|
10946
11736
|
const value = await this.keychainRead(binding.source);
|
|
10947
|
-
return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256:
|
|
11737
|
+
return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash12("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
|
|
10948
11738
|
}
|
|
10949
11739
|
}
|
|
10950
11740
|
var DELIVERY_URL = "SWITCHER_CREDENTIAL_DELIVERY_URL";
|
|
@@ -10964,7 +11754,7 @@ async function vaultEnvironment(binding, env, options = {}) {
|
|
|
10964
11754
|
try {
|
|
10965
11755
|
if (source.operator.kind === "contracts") {
|
|
10966
11756
|
const pair = () => {
|
|
10967
|
-
const keys =
|
|
11757
|
+
const keys = clientTransportEnvKeys3("secrets");
|
|
10968
11758
|
const configuredUrl = keys.apiUrlKeys.map((name) => env[name]).find((value) => value !== undefined) ?? keychainConfigValue2("secrets", env, options.keychain)?.value ?? appConfigDiskValue2("secrets", env, keys.apiUrlKeys)?.value;
|
|
10969
11759
|
const resolution = resolveClientTransport("secrets", env, { credentials: options });
|
|
10970
11760
|
const key = resolveCredential("secrets", env, options);
|
|
@@ -11123,8 +11913,13 @@ async function deliverVaultCredential() {
|
|
|
11123
11913
|
}
|
|
11124
11914
|
|
|
11125
11915
|
// src/cli.ts
|
|
11126
|
-
var HELP = `switcher \u2014 launch
|
|
11916
|
+
var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your provider and model
|
|
11127
11917
|
|
|
11918
|
+
switcher launch chatgpt --provider PROVIDER --model MODEL [--reasoning EFFORT]
|
|
11919
|
+
[--dangerously-bypass-approvals-and-sandbox] [--app-path /absolute/ChatGPT.app]
|
|
11920
|
+
[--dry-run] [--cwd DIR] [--timeout SECONDS]
|
|
11921
|
+
switcher launch claude-desktop --provider PROVIDER --model MODEL
|
|
11922
|
+
[--app-path /absolute/Claude.app] [--dry-run]
|
|
11128
11923
|
switcher providers presets [ID]
|
|
11129
11924
|
switcher providers list [--search TEXT] [--limit N] [--offset N]
|
|
11130
11925
|
switcher providers add ID --url URL --protocol PROTOCOL [--credential-env NAME]
|
|
@@ -11156,12 +11951,22 @@ var HELP = `switcher \u2014 launch a coding harness with a provider and its mode
|
|
|
11156
11951
|
switcher doctor
|
|
11157
11952
|
|
|
11158
11953
|
HARNESS: claude, codex, grok, opencode, opencode2, pi, omp, dsh, cline, hermes, prime-agent, gemini, aider, kilo
|
|
11954
|
+
chatgpt launches the installed macOS desktop app in an isolated provider profile.
|
|
11955
|
+
Its local Codex conversations use the selected Responses-compatible provider.
|
|
11956
|
+
claude-desktop launches Claude in its separate Claude-3p gateway profile with a
|
|
11957
|
+
Messages-compatible provider. Quit that instance before switching providers.
|
|
11958
|
+
Keep Switcher running while using the app; quit that app instance to end the launch.
|
|
11959
|
+
--reasoning: none, minimal, low, medium, high, xhigh, max, ultra (provider support required).
|
|
11960
|
+
--dangerously-bypass-approvals-and-sandbox: full access without prompts or command sandboxing.
|
|
11159
11961
|
PROTOCOL: anthropic-messages, openai-responses, openai-chat, gemini-generate-content
|
|
11160
|
-
|
|
11161
|
-
|
|
11162
|
-
|
|
11163
|
-
|
|
11164
|
-
|
|
11962
|
+
Data access is HTTP against the configured Switcher API. Its URL/key resolve
|
|
11963
|
+
through @hasna/contracts: overrides, Keychain (hasna.credentials.switcher.api-key),
|
|
11964
|
+
~/.hasna/switcher/config/credentials, then environment (HASNA_SWITCHER_API_KEY).
|
|
11965
|
+
A key alone uses the gateway. With nothing configured the command exits 1 and
|
|
11966
|
+
names those sources; it never falls back to local data.
|
|
11967
|
+
HASNA_SWITCHER_LOCAL=1 (alias SWITCHER_LOCAL=1) deliberately selects the on-box
|
|
11968
|
+
store in ~/.hasna/switcher (override HASNA_SWITCHER_HOME) behind an owned
|
|
11969
|
+
per-command loopback API; a configured remote API outranks the flag.
|
|
11165
11970
|
Provider credential references must start SWITCHER_PROVIDER_.
|
|
11166
11971
|
--models-file accepts a JSON array of model metadata; --model adds one starter.
|
|
11167
11972
|
Use --catalog-format none for a manual catalog; otherwise discovery stays active.
|
|
@@ -11219,6 +12024,9 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11219
12024
|
json: { type: "boolean" },
|
|
11220
12025
|
url: { type: "string" },
|
|
11221
12026
|
sha256: { type: "string" },
|
|
12027
|
+
"app-path": { type: "string" },
|
|
12028
|
+
reasoning: { type: "string" },
|
|
12029
|
+
"dangerously-bypass-approvals-and-sandbox": { type: "boolean" },
|
|
11222
12030
|
protocol: { type: "string" },
|
|
11223
12031
|
preset: { type: "string" },
|
|
11224
12032
|
name: { type: "string" },
|
|
@@ -11264,6 +12072,18 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11264
12072
|
}
|
|
11265
12073
|
const [command, action2, id2] = positionals;
|
|
11266
12074
|
const output = (value) => console.log(JSON.stringify(value, null, 2));
|
|
12075
|
+
const reasoning = values2.reasoning === undefined ? undefined : parse2(reasoningEffortSchema, values2.reasoning);
|
|
12076
|
+
const dangerouslyBypassApprovalsAndSandbox = values2["dangerously-bypass-approvals-and-sandbox"];
|
|
12077
|
+
if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" || values2.provider && !["chatgpt", "codex"].includes(action2) || values2.backend && values2.backend !== "direct"))
|
|
12078
|
+
throw new Fault(400, "conflicting_options", "--reasoning and --dangerously-bypass-approvals-and-sandbox require a direct Codex or ChatGPT launch.");
|
|
12079
|
+
const chatgpt = command === "launch" && action2 === "chatgpt" && values2.provider !== undefined;
|
|
12080
|
+
const claudeDesktop = command === "launch" && action2 === "claude-desktop" && values2.provider !== undefined;
|
|
12081
|
+
if (values2["app-path"] !== undefined && !chatgpt && !claudeDesktop)
|
|
12082
|
+
throw new Fault(400, "conflicting_options", "--app-path belongs to launch chatgpt or claude-desktop --provider PROVIDER --model MODEL.");
|
|
12083
|
+
if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 || values2.executable !== undefined || values2.backend !== undefined || values2["ori-executable"] !== undefined))
|
|
12084
|
+
throw new Fault(400, "conflicting_options", "Desktop apps use their own runtime; native CLI arguments, --executable and --backend are not accepted.");
|
|
12085
|
+
const desktop = chatgpt ? await detectChatGPTApp(values2["app-path"]) : undefined;
|
|
12086
|
+
const claudeApp = claudeDesktop ? await detectClaudeDesktopApp(values2["app-path"]) : undefined;
|
|
11267
12087
|
if (!["doctor", "launch", "models", "runs", "providers", "profiles", "credentials"].includes(command))
|
|
11268
12088
|
throw new Error("Unknown command. Run switcher --help.");
|
|
11269
12089
|
const providerFlags = ["url", "protocol", "preset", "credential-env", "auth-style", "catalog-url", "catalog-format", "catalog-auth-style", "catalog-credential-env", "catalog-account-id", "models-path"];
|
|
@@ -11380,7 +12200,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11380
12200
|
if (command === "launch" && provided(["name", "harness", "file"]))
|
|
11381
12201
|
throw new Fault(400, "conflicting_options", "Launch takes its harness from the positional argument or saved profile; edit named records through providers/profiles.");
|
|
11382
12202
|
if (command === "launch" && values2.provider) {
|
|
11383
|
-
const harness = parse2(harnessSchema, action2);
|
|
12203
|
+
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action2);
|
|
11384
12204
|
assertHarnessArguments(harness, nativeArgs);
|
|
11385
12205
|
await validateHarnessConfiguration(harness, values2.cwd ?? process.cwd(), nativeArgs);
|
|
11386
12206
|
}
|
|
@@ -11426,7 +12246,7 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11426
12246
|
throw new Error("--timeout must be positive seconds.");
|
|
11427
12247
|
let profileId = action2;
|
|
11428
12248
|
if (values2.provider) {
|
|
11429
|
-
const harness = parse2(harnessSchema, action2);
|
|
12249
|
+
const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action2);
|
|
11430
12250
|
const modelPolicy = await readModelPolicy(values2["model-policy-file"], values2["role-model"]);
|
|
11431
12251
|
const provider = await resolveLaunchProvider(client, values2.provider, { ...presetOptions(), harness });
|
|
11432
12252
|
validateHarnessProvider(harness, provider);
|
|
@@ -11439,6 +12259,8 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11439
12259
|
throw new Fault(422, "model_expired", "Selected model has passed its configured expiry date. Select an unexpired model.");
|
|
11440
12260
|
if (!harnessEligible(selected, harness))
|
|
11441
12261
|
throw new Fault(422, "model_ineligible", "Selected model explicitly lacks text output or tool support.");
|
|
12262
|
+
if (harness === "codex")
|
|
12263
|
+
codexReasoning(selected, provider.baseUrl, reasoning);
|
|
11442
12264
|
profileId = (await ensureLaunchProfile(client, provider, harness, model3, modelPolicy)).id;
|
|
11443
12265
|
} else {
|
|
11444
12266
|
if (values2.model || values2.protocol || values2.url || values2["credential-env"] || values2["model-policy-file"] || values2["role-model"])
|
|
@@ -11452,15 +12274,22 @@ async function main(args = process.argv.slice(2)) {
|
|
|
11452
12274
|
}
|
|
11453
12275
|
if (values2["dry-run"]) {
|
|
11454
12276
|
const plan = await client.launchPlan(profileId);
|
|
12277
|
+
if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && plan.profile.harness !== "codex")
|
|
12278
|
+
throw new Fault(400, "conflicting_options", "Reasoning and full-access options require Codex or ChatGPT.");
|
|
12279
|
+
if (reasoning) {
|
|
12280
|
+
const model3 = plan.catalog.models.find((model4) => model4.id === plan.profile.model);
|
|
12281
|
+
if (model3)
|
|
12282
|
+
codexReasoning(model3, plan.provider.baseUrl, reasoning);
|
|
12283
|
+
}
|
|
11455
12284
|
assertHarnessArguments(plan.profile.harness, nativeArgs);
|
|
11456
12285
|
if (backend === "ori") {
|
|
11457
12286
|
const { contract, warnings } = await validateOriForPlan(plan, { oriExecutable: values2["ori-executable"], args: nativeArgs, cwd: values2.cwd });
|
|
11458
12287
|
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] } });
|
|
11459
12288
|
} else
|
|
11460
|
-
output(plan);
|
|
12289
|
+
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" } } : {} });
|
|
11461
12290
|
return;
|
|
11462
12291
|
}
|
|
11463
|
-
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) });
|
|
12292
|
+
process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, resolveCredential: (provider) => credentials.resolve(provider) });
|
|
11464
12293
|
return;
|
|
11465
12294
|
}
|
|
11466
12295
|
if (editingModel) {
|