@hasna/switcher 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 z3 } from "zod";
451
+ import { z as z4 } from "zod";
452
452
 
453
- // src/model-policy-schema.ts
453
+ // src/reasoning.ts
454
454
  import { z as z2 } from "zod";
455
- var policyModelIdSchema = z2.string().min(1).max(300).regex(/^[^\u0000-\u001f\u007f]+$/);
456
- var modelPolicyRoleSchema = z2.enum(["subagent", "fast", "planning", "review", "summary", "compaction", "weak", "editor"]);
457
- var boundedModelList = z2.array(policyModelIdSchema).max(500);
458
- var aliasSchema = z2.string().regex(/^[A-Za-z0-9._/-]{1,120}$/).refine((v) => !["__proto__", "prototype", "constructor"].includes(v));
459
- var boundedModelMap = z2.record(aliasSchema, policyModelIdSchema).superRefine((value, ctx) => {
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 = z2.record(policyModelIdSchema, z2.array(policyModelIdSchema).max(20)).superRefine((value, ctx) => {
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 = z2.object({
468
- version: z2.literal(1).default(1),
469
- roles: z2.object({
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 = z2.enum(["allow", "alias", "reject", "fallback"]);
484
- var routingEventRoleSchema = z2.enum(["main", ...modelPolicyRoleSchema.options]);
485
- var routingEventSchema = z2.object({
486
- at: z2.string().datetime({ offset: true }),
487
- requestId: z2.string().regex(/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/),
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: z2.string().regex(/^[a-z][a-z0-9_]{0,63}$/).optional(),
494
- upstreamStatus: z2.number().int().min(100).max(599).optional()
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 = z2.array(routingEventSchema).max(1000);
511
+ var routingEventsSchema = z3.array(routingEventSchema).max(1000);
497
512
  function canonicalPolicyJSON(value) {
498
513
  return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
499
514
  }
500
515
 
501
516
  // src/domain.ts
502
- var VERSION = "0.1.8";
503
- var harnessSchema = z3.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
504
- var protocolSchema = z3.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
505
- var idSchema = z3.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
506
- var label = z3.string().min(1).max(200);
507
- var envRef = z3.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/);
517
+ var VERSION = "0.1.9";
518
+ var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
519
+ var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
520
+ var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
521
+ var label = z4.string().min(1).max(200);
522
+ var envRef = z4.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/);
508
523
  function endpoint(value) {
509
524
  let url;
510
525
  try {
@@ -517,85 +532,86 @@ function endpoint(value) {
517
532
  throw new Fault(400, "invalid_url", "URL must use HTTPS, contain no credentials/query/fragment, or use HTTP on loopback.");
518
533
  return url.href.replace(/\/+$/, "");
519
534
  }
520
- var urlSchema = z3.string().max(2000).superRefine((v, ctx) => {
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 = z3.string().regex(/^\d{4}-\d{2}-\d{2}$/).refine((value) => {
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 = z3.object({
532
- id: z3.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."),
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: z3.string().max(8000).optional(),
535
- available: z3.boolean().optional(),
549
+ description: z4.string().max(8000).optional(),
550
+ available: z4.boolean().optional(),
536
551
  expiresOn: expiresOnSchema.optional(),
537
- contextWindow: z3.number().int().positive().optional(),
538
- maxOutputTokens: z3.number().int().positive().optional(),
539
- inputModalities: z3.array(z3.string().max(50)).max(20).optional(),
540
- outputModalities: z3.array(z3.string().max(50)).max(20).optional(),
541
- supportedParameters: z3.array(z3.string().max(100)).max(100).optional(),
542
- supportedGenerationMethods: z3.array(z3.string().min(1).max(100)).max(100).optional()
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 = z3.object({
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: z3.enum(["bearer", "x-api-key", "api-key"]).default("bearer"),
566
+ authStyle: z4.enum(["bearer", "x-api-key", "api-key"]).default("bearer"),
551
567
  catalogBaseUrl: urlSchema.optional(),
552
- catalogFormat: z3.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]).optional(),
553
- catalogAuthStyle: z3.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
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: z3.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/).optional(),
556
- modelsPath: z3.string().regex(/^[a-zA-Z0-9_/-]+$/).max(200).default("models"),
557
- manualModels: z3.array(modelSchema).max(1e4).default([]),
558
- additionalModels: z3.array(modelSchema).max(1e4).optional()
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 = z3.object({
576
+ var providerPresetSchema = z4.object({
561
577
  id: idSchema,
562
578
  name: label,
563
579
  credentialEnv: envRef.optional(),
564
- credentialAliases: z3.array(z3.string().regex(/^[A-Z][A-Z0-9_]+$/)),
565
- protocols: z3.array(z3.object({
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: z3.enum(["bearer", "x-api-key", "api-key"]),
584
+ authStyle: z4.enum(["bearer", "x-api-key", "api-key"]),
569
585
  catalogBaseUrl: urlSchema.optional(),
570
- catalogFormat: z3.enum(["openai", "ollama", "mistral", "together", "fireworks", "dashscope", "gemini", "none"]),
571
- catalogAuthStyle: z3.enum(["bearer", "x-api-key", "api-key", "none"]).optional(),
572
- modelsPath: z3.string(),
573
- notes: z3.array(z3.string())
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: z3.array(z3.string().url()),
576
- verification: z3.literal("documented")
591
+ sources: z4.array(z4.string().url()),
592
+ verification: z4.literal("documented")
577
593
  }).strict();
578
- var profileInputSchema = z3.object({
594
+ var profileInputSchema = z4.object({
579
595
  id: idSchema,
580
596
  name: label,
581
597
  providerId: idSchema,
582
598
  harness: harnessSchema,
583
- model: z3.string().min(1).max(300),
599
+ model: z4.string().min(1).max(300),
584
600
  modelPolicy: modelPolicySchema.optional()
585
601
  }).strict();
586
- var runInputSchema = z3.object({
587
- modelPolicyVersion: z3.literal(1),
602
+ var runInputSchema = z4.object({
603
+ modelPolicyVersion: z4.literal(1),
588
604
  profileId: idSchema,
589
605
  harness: harnessSchema,
590
- model: z3.string().min(1).max(300),
606
+ model: z4.string().min(1).max(300),
591
607
  modelPolicy: modelPolicySchema.optional(),
592
- planToken: z3.string().regex(/^[a-f0-9]{64}$/)
608
+ planToken: z4.string().regex(/^[a-f0-9]{64}$/)
593
609
  }).strict();
594
- var runUpdateSchema = z3.object({
595
- status: z3.enum(["exited", "failed", "interrupted"]),
596
- exitCode: z3.number().int().min(0).max(255),
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: z3.number().int().min(0).max(1e6).optional()
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 {
@@ -1598,15 +1706,15 @@ function openCodeInvocationModel(args, policy, defaultAgent) {
1598
1706
 
1599
1707
  // src/gemini-config.ts
1600
1708
  import { readFile, writeFile as writeFile3, lstat as lstat2, readdir as readdir2, symlink, realpath as realpath2 } from "fs/promises";
1601
- import { join as join4, dirname as dirname3, resolve as resolve4, isAbsolute as isAbsolute4, relative as relative2, sep } from "path";
1602
- import { homedir as homedir3 } from "os";
1709
+ import { join as join5, dirname as dirname3, resolve as resolve4, isAbsolute as isAbsolute5, relative as relative2, sep } from "path";
1710
+ import { homedir as homedir4 } from "os";
1603
1711
  import { parseTree as parseTree2, getNodeValue } from "jsonc-parser";
1604
1712
 
1605
1713
  // src/runtime.ts
1606
1714
  import { randomBytes } from "crypto";
1607
1715
  import { mkdir as mkdir4, lstat } from "fs/promises";
1608
- import { homedir as homedir2 } from "os";
1609
- import { isAbsolute as isAbsolute3, join as join3, resolve as resolve3 } from "path";
1716
+ import { homedir as homedir3 } from "os";
1717
+ import { isAbsolute as isAbsolute4, join as join4, resolve as resolve3 } from "path";
1610
1718
 
1611
1719
  // src/store.ts
1612
1720
  var {SQL } = globalThis.Bun;
@@ -1771,7 +1879,7 @@ class Store {
1771
1879
 
1772
1880
  // src/service.ts
1773
1881
  import { createHash as createHash3, timingSafeEqual } from "crypto";
1774
- import { z as z4 } from "zod";
1882
+ import { z as z5 } from "zod";
1775
1883
 
1776
1884
  // src/auth.ts
1777
1885
  function authHeader(style, credential) {
@@ -2208,7 +2316,7 @@ var openapi_default = {
2208
2316
  openapi: "3.0.3",
2209
2317
  info: {
2210
2318
  title: "Switcher API",
2211
- version: "0.1.8",
2319
+ version: "0.1.9",
2212
2320
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2213
2321
  },
2214
2322
  security: [
@@ -3647,6 +3755,23 @@ var openapi_default = {
3647
3755
  },
3648
3756
  maxItems: 100
3649
3757
  },
3758
+ reasoningEfforts: {
3759
+ type: "array",
3760
+ items: {
3761
+ type: "string",
3762
+ enum: [
3763
+ "none",
3764
+ "minimal",
3765
+ "low",
3766
+ "medium",
3767
+ "high",
3768
+ "xhigh",
3769
+ "max",
3770
+ "ultra"
3771
+ ]
3772
+ },
3773
+ maxItems: 8
3774
+ },
3650
3775
  supportedGenerationMethods: {
3651
3776
  type: "array",
3652
3777
  items: {
@@ -3726,6 +3851,23 @@ var openapi_default = {
3726
3851
  },
3727
3852
  maxItems: 100
3728
3853
  },
3854
+ reasoningEfforts: {
3855
+ type: "array",
3856
+ items: {
3857
+ type: "string",
3858
+ enum: [
3859
+ "none",
3860
+ "minimal",
3861
+ "low",
3862
+ "medium",
3863
+ "high",
3864
+ "xhigh",
3865
+ "max",
3866
+ "ultra"
3867
+ ]
3868
+ },
3869
+ maxItems: 8
3870
+ },
3729
3871
  supportedGenerationMethods: {
3730
3872
  type: "array",
3731
3873
  items: {
@@ -3891,6 +4033,23 @@ var openapi_default = {
3891
4033
  },
3892
4034
  maxItems: 100
3893
4035
  },
4036
+ reasoningEfforts: {
4037
+ type: "array",
4038
+ items: {
4039
+ type: "string",
4040
+ enum: [
4041
+ "none",
4042
+ "minimal",
4043
+ "low",
4044
+ "medium",
4045
+ "high",
4046
+ "xhigh",
4047
+ "max",
4048
+ "ultra"
4049
+ ]
4050
+ },
4051
+ maxItems: 8
4052
+ },
3894
4053
  supportedGenerationMethods: {
3895
4054
  type: "array",
3896
4055
  items: {
@@ -3970,6 +4129,23 @@ var openapi_default = {
3970
4129
  },
3971
4130
  maxItems: 100
3972
4131
  },
4132
+ reasoningEfforts: {
4133
+ type: "array",
4134
+ items: {
4135
+ type: "string",
4136
+ enum: [
4137
+ "none",
4138
+ "minimal",
4139
+ "low",
4140
+ "medium",
4141
+ "high",
4142
+ "xhigh",
4143
+ "max",
4144
+ "ultra"
4145
+ ]
4146
+ },
4147
+ maxItems: 8
4148
+ },
3973
4149
  supportedGenerationMethods: {
3974
4150
  type: "array",
3975
4151
  items: {
@@ -4373,6 +4549,23 @@ var openapi_default = {
4373
4549
  },
4374
4550
  maxItems: 100
4375
4551
  },
4552
+ reasoningEfforts: {
4553
+ type: "array",
4554
+ items: {
4555
+ type: "string",
4556
+ enum: [
4557
+ "none",
4558
+ "minimal",
4559
+ "low",
4560
+ "medium",
4561
+ "high",
4562
+ "xhigh",
4563
+ "max",
4564
+ "ultra"
4565
+ ]
4566
+ },
4567
+ maxItems: 8
4568
+ },
4376
4569
  supportedGenerationMethods: {
4377
4570
  type: "array",
4378
4571
  items: {
@@ -4517,6 +4710,19 @@ var openapi_default = {
4517
4710
  maxLength: 300,
4518
4711
  pattern: "^[^\\u0000-\\u001f\\u007f]+$"
4519
4712
  },
4713
+ reasoningEffort: {
4714
+ type: "string",
4715
+ enum: [
4716
+ "none",
4717
+ "minimal",
4718
+ "low",
4719
+ "medium",
4720
+ "high",
4721
+ "xhigh",
4722
+ "max",
4723
+ "ultra"
4724
+ ]
4725
+ },
4520
4726
  decision: {
4521
4727
  type: "string",
4522
4728
  enum: [
@@ -4621,6 +4827,23 @@ var openapi_default = {
4621
4827
  },
4622
4828
  maxItems: 100
4623
4829
  },
4830
+ reasoningEfforts: {
4831
+ type: "array",
4832
+ items: {
4833
+ type: "string",
4834
+ enum: [
4835
+ "none",
4836
+ "minimal",
4837
+ "low",
4838
+ "medium",
4839
+ "high",
4840
+ "xhigh",
4841
+ "max",
4842
+ "ultra"
4843
+ ]
4844
+ },
4845
+ maxItems: 8
4846
+ },
4624
4847
  supportedGenerationMethods: {
4625
4848
  type: "array",
4626
4849
  items: {
@@ -4739,6 +4962,23 @@ var openapi_default = {
4739
4962
  },
4740
4963
  maxItems: 100
4741
4964
  },
4965
+ reasoningEfforts: {
4966
+ type: "array",
4967
+ items: {
4968
+ type: "string",
4969
+ enum: [
4970
+ "none",
4971
+ "minimal",
4972
+ "low",
4973
+ "medium",
4974
+ "high",
4975
+ "xhigh",
4976
+ "max",
4977
+ "ultra"
4978
+ ]
4979
+ },
4980
+ maxItems: 8
4981
+ },
4742
4982
  supportedGenerationMethods: {
4743
4983
  type: "array",
4744
4984
  items: {
@@ -4915,6 +5155,23 @@ var openapi_default = {
4915
5155
  },
4916
5156
  maxItems: 100
4917
5157
  },
5158
+ reasoningEfforts: {
5159
+ type: "array",
5160
+ items: {
5161
+ type: "string",
5162
+ enum: [
5163
+ "none",
5164
+ "minimal",
5165
+ "low",
5166
+ "medium",
5167
+ "high",
5168
+ "xhigh",
5169
+ "max",
5170
+ "ultra"
5171
+ ]
5172
+ },
5173
+ maxItems: 8
5174
+ },
4918
5175
  supportedGenerationMethods: {
4919
5176
  type: "array",
4920
5177
  items: {
@@ -4994,6 +5251,23 @@ var openapi_default = {
4994
5251
  },
4995
5252
  maxItems: 100
4996
5253
  },
5254
+ reasoningEfforts: {
5255
+ type: "array",
5256
+ items: {
5257
+ type: "string",
5258
+ enum: [
5259
+ "none",
5260
+ "minimal",
5261
+ "low",
5262
+ "medium",
5263
+ "high",
5264
+ "xhigh",
5265
+ "max",
5266
+ "ultra"
5267
+ ]
5268
+ },
5269
+ maxItems: 8
5270
+ },
4997
5271
  supportedGenerationMethods: {
4998
5272
  type: "array",
4999
5273
  items: {
@@ -5253,6 +5527,23 @@ var openapi_default = {
5253
5527
  },
5254
5528
  maxItems: 100
5255
5529
  },
5530
+ reasoningEfforts: {
5531
+ type: "array",
5532
+ items: {
5533
+ type: "string",
5534
+ enum: [
5535
+ "none",
5536
+ "minimal",
5537
+ "low",
5538
+ "medium",
5539
+ "high",
5540
+ "xhigh",
5541
+ "max",
5542
+ "ultra"
5543
+ ]
5544
+ },
5545
+ maxItems: 8
5546
+ },
5256
5547
  supportedGenerationMethods: {
5257
5548
  type: "array",
5258
5549
  items: {
@@ -5504,6 +5795,19 @@ var openapi_default = {
5504
5795
  maxLength: 300,
5505
5796
  pattern: "^[^\\u0000-\\u001f\\u007f]+$"
5506
5797
  },
5798
+ reasoningEffort: {
5799
+ type: "string",
5800
+ enum: [
5801
+ "none",
5802
+ "minimal",
5803
+ "low",
5804
+ "medium",
5805
+ "high",
5806
+ "xhigh",
5807
+ "max",
5808
+ "ultra"
5809
+ ]
5810
+ },
5507
5811
  decision: {
5508
5812
  type: "string",
5509
5813
  enum: [
@@ -5774,6 +6078,19 @@ var openapi_default = {
5774
6078
  maxLength: 300,
5775
6079
  pattern: "^[^\\u0000-\\u001f\\u007f]+$"
5776
6080
  },
6081
+ reasoningEffort: {
6082
+ type: "string",
6083
+ enum: [
6084
+ "none",
6085
+ "minimal",
6086
+ "low",
6087
+ "medium",
6088
+ "high",
6089
+ "xhigh",
6090
+ "max",
6091
+ "ultra"
6092
+ ]
6093
+ },
5777
6094
  decision: {
5778
6095
  type: "string",
5779
6096
  enum: [
@@ -5982,10 +6299,10 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
5982
6299
  const id2 = parts[2];
5983
6300
  if (id2)
5984
6301
  parse2(idSchema, id2);
5985
- const page = () => parse2(z4.object({
5986
- limit: z4.coerce.number().int().min(1).max(1000).default(100),
5987
- offset: z4.coerce.number().int().min(0).max(1e6).default(0),
5988
- search: z4.string().max(200).default("")
6302
+ const page = () => parse2(z5.object({
6303
+ limit: z5.coerce.number().int().min(1).max(1000).default(100),
6304
+ offset: z5.coerce.number().int().min(0).max(1e6).default(0),
6305
+ search: z5.string().max(200).default("")
5989
6306
  }).strict(), Object.fromEntries(url.searchParams));
5990
6307
  if (request.method === "GET") {
5991
6308
  if (resource === "provider-presets" && parts.length <= 3)
@@ -6029,7 +6346,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
6029
6346
  return json(replay.value, request.method === "POST" && ["providers", "profiles", "runs"].includes(resource) && !id2 ? 201 : 200);
6030
6347
  let refreshed;
6031
6348
  if (resource === "providers" && id2 && parts[3] === "refresh" && parts.length === 4 && request.method === "POST") {
6032
- parse2(z4.object({}).strict(), body);
6349
+ parse2(z5.object({}).strict(), body);
6033
6350
  const provider = await store.get("providers", id2);
6034
6351
  refreshed = { provider, catalog: await discover(provider, providerEnv, resolveCredential) };
6035
6352
  }
@@ -6069,7 +6386,7 @@ function createHandler(store, apiKey, providerEnv = process.env, resolveCredenti
6069
6386
  return store.put("catalogs", { id: id2, ...catalog }, old?.version, db);
6070
6387
  }
6071
6388
  if (resource === "launch-plans" && !id2 && request.method === "POST") {
6072
- const { profileId } = parse2(z4.object({ profileId: idSchema }).strict(), body);
6389
+ const { profileId } = parse2(z5.object({ profileId: idSchema }).strict(), body);
6073
6390
  const profile = await store.get("profiles", profileId, db);
6074
6391
  const provider = await store.get("providers", profile.providerId, db);
6075
6392
  validateHarnessProvider(profile.harness, provider);
@@ -6184,8 +6501,8 @@ async function startServer(options) {
6184
6501
  import { resolveCredential as resolveClientCredential, clientTransportEnvKeys, appConfigDiskValue, keychainConfigValue } from "@hasna/contracts/client";
6185
6502
  function switcherHome(env = process.env) {
6186
6503
  const override = env.HASNA_HOME?.trim();
6187
- const root = override && isAbsolute3(override) ? override : join3(env.HOME?.trim() || homedir2(), ".hasna");
6188
- return resolve3(env.HASNA_SWITCHER_HOME ?? join3(root, "switcher"));
6504
+ const root = override && isAbsolute4(override) ? override : join4(env.HOME?.trim() || homedir3(), ".hasna");
6505
+ return resolve3(env.HASNA_SWITCHER_HOME ?? join4(root, "switcher"));
6189
6506
  }
6190
6507
  async function privateDirectory(path) {
6191
6508
  await mkdir4(path, { recursive: true, mode: 448 });
@@ -6210,7 +6527,7 @@ async function openCliRuntime(env = process.env, resolveCredential) {
6210
6527
  const service = await startServer({
6211
6528
  apiKey,
6212
6529
  databaseUrl: env.HASNA_SWITCHER_DATABASE_URL,
6213
- sqlitePath: env.HASNA_SWITCHER_SQLITE_PATH ?? (env.HASNA_SWITCHER_DATABASE_URL ? undefined : join3(home, "switcher.db")),
6530
+ sqlitePath: env.HASNA_SWITCHER_SQLITE_PATH ?? (env.HASNA_SWITCHER_DATABASE_URL ? undefined : join4(home, "switcher.db")),
6214
6531
  providerEnv,
6215
6532
  resolveCredential
6216
6533
  });
@@ -6303,8 +6620,8 @@ var nativeModels = ["gemini-3.1-flash-lite", "gemini-3.1-pro-preview", "gemini-3
6303
6620
  var object2 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
6304
6621
  async function regular(path, limit = 2 * 1024 * 1024) {
6305
6622
  try {
6306
- const stat3 = await lstat2(path);
6307
- if (!stat3.isFile() || stat3.size > limit)
6623
+ const stat4 = await lstat2(path);
6624
+ if (!stat4.isFile() || stat4.size > limit)
6308
6625
  throw new Error("unsupported");
6309
6626
  return true;
6310
6627
  } catch (error) {
@@ -6357,12 +6674,12 @@ function originalPaths(value, home) {
6357
6674
  return result;
6358
6675
  }
6359
6676
  async function validateGeminiConfiguration(cwd, env = process.env) {
6360
- const home = env.GEMINI_CLI_HOME ?? env.HOME ?? homedir3();
6361
- if (!isAbsolute4(home))
6677
+ const home = env.GEMINI_CLI_HOME ?? env.HOME ?? homedir4();
6678
+ if (!isAbsolute5(home))
6362
6679
  throw new Error("Gemini requires an absolute native home.");
6363
6680
  const systemPath = env.GEMINI_CLI_SYSTEM_SETTINGS_PATH ?? (process.platform === "darwin" ? "/Library/Application Support/GeminiCli/settings.json" : process.platform === "win32" ? "C:\\ProgramData\\gemini-cli\\settings.json" : "/etc/gemini-cli/settings.json");
6364
- const defaultsPath = env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ?? join4(dirname3(systemPath), "system-defaults.json");
6365
- const paths = [defaultsPath, join4(home, ".gemini", "settings.json"), join4(resolve4(cwd), ".gemini", "settings.json"), systemPath];
6681
+ const defaultsPath = env.GEMINI_CLI_SYSTEM_DEFAULTS_PATH ?? join5(dirname3(systemPath), "system-defaults.json");
6682
+ const paths = [defaultsPath, join5(home, ".gemini", "settings.json"), join5(resolve4(cwd), ".gemini", "settings.json"), systemPath];
6366
6683
  const values2 = [];
6367
6684
  for (const path of paths) {
6368
6685
  const value = await settings(path);
@@ -6373,7 +6690,7 @@ async function validateGeminiConfiguration(cwd, env = process.env) {
6373
6690
  if (values2[2][key]?.some?.((path) => typeof path === "string" && (path === "~" || path.startsWith("~/"))))
6374
6691
  throw new Error("Gemini project policy paths using ~ must use an absolute path so workspace trust remains authoritative under an isolated native home.");
6375
6692
  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 ?? join4(home, ".gemini", "trustedFolders.json") };
6693
+ return { home, defaults: originalPaths(values2[0], home), user: originalPaths(values2[1], home), system: originalPaths(values2[3], home), contextNames, trustPath: env.GEMINI_CLI_TRUSTED_FOLDERS_PATH ?? join5(home, ".gemini", "trustedFolders.json") };
6377
6694
  }
6378
6695
  async function snapshotFile(source, destination) {
6379
6696
  if (await regular(source))
@@ -6382,8 +6699,8 @@ async function snapshotFile(source, destination) {
6382
6699
  async function snapshotPolicies(source, destination) {
6383
6700
  let entries;
6384
6701
  try {
6385
- const stat3 = await lstat2(source);
6386
- if (!stat3.isDirectory() || stat3.isSymbolicLink())
6702
+ const stat4 = await lstat2(source);
6703
+ if (!stat4.isDirectory() || stat4.isSymbolicLink())
6387
6704
  throw new Error("Unsupported Gemini policy directory");
6388
6705
  entries = await readdir2(source, { withFileTypes: true });
6389
6706
  } catch (error) {
@@ -6396,12 +6713,12 @@ async function snapshotPolicies(source, destination) {
6396
6713
  throw new Error("Gemini user policy directory exceeds the snapshot limit.");
6397
6714
  for (const entry of entries) {
6398
6715
  if (entry.name.endsWith(".toml"))
6399
- await snapshotFile(join4(source, entry.name), join4(destination, entry.name));
6716
+ await snapshotFile(join5(source, entry.name), join5(destination, entry.name));
6400
6717
  }
6401
6718
  }
6402
6719
  async function snapshotContext(sourceDir, destinationDir, names) {
6403
6720
  const root = await realpath2(sourceDir), files = new Map;
6404
- const importsDir = join4(destinationDir, ".switcher-context");
6721
+ const importsDir = join5(destinationDir, ".switcher-context");
6405
6722
  let bytes = 0;
6406
6723
  const copy = async (source, destination) => {
6407
6724
  if (files.has(source))
@@ -6422,9 +6739,9 @@ async function snapshotContext(sourceDir, destinationDir, names) {
6422
6739
  if (code.some(([a, b]) => start >= a && start < b))
6423
6740
  continue;
6424
6741
  const imported = resolve4(dirname3(source), match[2]), actual = await realpath2(imported).catch(() => imported), within = relative2(root, actual);
6425
- if (within === ".." || within.startsWith(".." + sep) || isAbsolute4(within))
6742
+ if (within === ".." || within.startsWith(".." + sep) || isAbsolute5(within))
6426
6743
  throw new Error("Gemini global context imports outside the original context directory require a supported explicit context location.");
6427
- const target = files.get(imported) ?? join4(importsDir, `${files.size}.md`);
6744
+ const target = files.get(imported) ?? join5(importsDir, `${files.size}.md`);
6428
6745
  await privateDirectory(importsDir);
6429
6746
  await copy(imported, target);
6430
6747
  output += text.slice(last, start) + "@./" + relative2(dirname3(destination), target).split(sep).join("/");
@@ -6433,30 +6750,30 @@ async function snapshotContext(sourceDir, destinationDir, names) {
6433
6750
  await writeFile3(destination, output + text.slice(last), { mode: 384, flag: "wx" });
6434
6751
  };
6435
6752
  for (const name of names)
6436
- if (await regular(join4(sourceDir, name)))
6437
- await copy(join4(sourceDir, name), join4(destinationDir, name));
6753
+ if (await regular(join5(sourceDir, name)))
6754
+ await copy(join5(sourceDir, name), join5(destinationDir, name));
6438
6755
  }
6439
6756
  async function prepareGemini(input) {
6440
6757
  const original = await validateGeminiConfiguration(input.cwd);
6441
- const home = join4(input.stateDir, "gemini-home"), dir = join4(home, ".gemini");
6758
+ const home = join5(input.stateDir, "gemini-home"), dir = join5(home, ".gemini");
6442
6759
  await privateDirectory(home);
6443
6760
  await privateDirectory(dir);
6444
- const durable = join4(input.sessionDir ?? join4(input.stateDir, "sessions"), "gemini-home", ".gemini");
6761
+ const durable = join5(input.sessionDir ?? join5(input.stateDir, "sessions"), "gemini-home", ".gemini");
6445
6762
  await privateDirectory(durable);
6446
6763
  for (const name of ["tmp", "history"]) {
6447
- const target = join4(durable, name);
6764
+ const target = join5(durable, name);
6448
6765
  await privateDirectory(target);
6449
- await symlink(target, join4(dir, name), "dir");
6766
+ await symlink(target, join5(dir, name), "dir");
6450
6767
  }
6451
- await snapshotFile(original.trustPath, join4(dir, "trustedFolders.json"));
6452
- await snapshotPolicies(join4(original.home, ".gemini", "policies"), join4(dir, "policies"));
6768
+ await snapshotFile(original.trustPath, join5(dir, "trustedFolders.json"));
6769
+ await snapshotPolicies(join5(original.home, ".gemini", "policies"), join5(dir, "policies"));
6453
6770
  try {
6454
- await snapshotContext(join4(original.home, ".gemini"), dir, original.contextNames);
6771
+ await snapshotContext(join5(original.home, ".gemini"), dir, original.contextNames);
6455
6772
  } catch (error) {
6456
6773
  if (error.code !== "ENOENT")
6457
6774
  throw error;
6458
6775
  }
6459
- const defaults = join4(input.stateDir, "gemini-system-defaults.json"), system = join4(input.stateDir, "gemini-system.json"), user = join4(dir, "settings.json");
6776
+ const defaults = join5(input.stateDir, "gemini-system-defaults.json"), system = join5(input.stateDir, "gemini-system.json"), user = join5(dir, "settings.json");
6460
6777
  const modelPolicy = compileGeminiModelPolicy(input.model, input.models, input.compiledPolicy ?? compileModelPolicy(input.model, input.models, input.modelPolicy));
6461
6778
  const modelDefinitions = { ...Object.fromEntries(nativeModels.map((id2) => [id2, { isVisible: false }])), ...modelPolicy.modelConfigs.modelDefinitions };
6462
6779
  const enforced = { ...original.system, security: { ...original.system.security, auth: { ...original.system.security?.auth, selectedType: "gemini-api-key" } }, model: { ...original.system.model, name: input.model }, modelConfigs: { ...modelPolicy.modelConfigs, modelDefinitions }, agents: { ...original.system.agents, overrides: { ...original.system.agents?.overrides, ...modelPolicy.agents?.overrides } }, experimental: { ...original.system.experimental, dynamicModelConfiguration: true } };
@@ -6471,7 +6788,7 @@ async function prepareGemini(input) {
6471
6788
  GEMINI_CLI_HOME: home,
6472
6789
  GEMINI_CLI_SYSTEM_SETTINGS_PATH: system,
6473
6790
  GEMINI_CLI_SYSTEM_DEFAULTS_PATH: defaults,
6474
- GEMINI_CLI_TRUSTED_FOLDERS_PATH: join4(dir, "trustedFolders.json"),
6791
+ GEMINI_CLI_TRUSTED_FOLDERS_PATH: join5(dir, "trustedFolders.json"),
6475
6792
  GEMINI_API_KEY: input.credential,
6476
6793
  GOOGLE_API_KEY: "",
6477
6794
  GOOGLE_GEMINI_BASE_URL: input.baseUrl.replace(/\/v1beta\/?$/i, ""),
@@ -6709,6 +7026,20 @@ async function isContextOverflow(response) {
6709
7026
  }
6710
7027
  }
6711
7028
 
7029
+ // src/codex-delegation.ts
7030
+ function normalizeCodexDelegation(body) {
7031
+ if (!Array.isArray(body.input))
7032
+ return body;
7033
+ return { ...body, input: body.input.map((item) => {
7034
+ if (item?.type !== "function_call_output" || item.namespace !== "codex_app" || item.call_id != null)
7035
+ return item;
7036
+ const content = typeof item.output === "string" ? [{ type: "input_text", text: item.output }] : item.output;
7037
+ if (!Array.isArray(content) || !content.length || !content.every((part) => part && (part.type === "input_text" && typeof part.text === "string" || part.type === "input_image" && (typeof part.image_url === "string" || typeof part.file_id === "string"))))
7038
+ throw new Fault(400, "unsupported_task_message_content", "The task message contains content this provider route cannot represent.");
7039
+ return { type: "message", role: "user", content };
7040
+ }) };
7041
+ }
7042
+
6712
7043
  // src/inference-gateway.ts
6713
7044
  import { createHash as createHash5, timingSafeEqual as timingSafeEqual3 } from "crypto";
6714
7045
  var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
@@ -6757,6 +7088,9 @@ function createInferenceGateway(input) {
6757
7088
  }
6758
7089
  const requestId = crypto.randomUUID();
6759
7090
  const event = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), decision: "reject" };
7091
+ const effort = reasoningEffortSchema.safeParse(body.reasoning?.effort);
7092
+ if (effort.success)
7093
+ event.reasoningEffort = effort.data;
6760
7094
  const emit = () => input.onRoutingEvent?.(event);
6761
7095
  let resolved;
6762
7096
  try {
@@ -6820,7 +7154,7 @@ function createInferenceGateway(input) {
6820
7154
  throw new Fault(422, "model_expired", "Selected model has expired.");
6821
7155
  if (attempt) {
6822
7156
  flush();
6823
- current = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), resolvedModel: model, decision: "fallback", reason: "explicit_transient_fallback" };
7157
+ current = { at: new Date().toISOString(), requestId, requestedModel: safeModel(requested), resolvedModel: model, decision: "fallback", reason: "explicit_transient_fallback", ...effort.success ? { reasoningEffort: effort.data } : {} };
6824
7158
  }
6825
7159
  const payload = structuredClone(body);
6826
7160
  if (gemini) {
@@ -6831,7 +7165,8 @@ function createInferenceGateway(input) {
6831
7165
  } else
6832
7166
  payload.model = model;
6833
7167
  const guidance = renderModelGuidance({ harness: input.harness, providerId: input.providerId, baseUrl: input.baseUrl, model, compiled: policy, catalogPath: input.catalogPath });
6834
- const outgoing = injectModelGuidance(input.protocol, payload, guidance, match?.[2]);
7168
+ const compatible2 = input.harness === "codex" && input.protocol === "openai-responses" && new URL(input.baseUrl).hostname !== "api.openai.com" ? normalizeCodexDelegation(payload) : payload;
7169
+ const outgoing = injectModelGuidance(input.protocol, compatible2, guidance, match?.[2]);
6835
7170
  const path = gemini ? `/models/${encodeURIComponent(model)}:${match[2]}${url.search}` : suffix + (betaQuery ? "?beta=true" : "");
6836
7171
  try {
6837
7172
  response = await fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(outgoing), redirect: "manual", signal });
@@ -6924,8 +7259,8 @@ function createInferenceGateway(input) {
6924
7259
  }
6925
7260
 
6926
7261
  // src/codex-model-policy.ts
6927
- import { mkdir as mkdir5, readFile as readFile2, realpath as realpath3, stat as stat3, writeFile as writeFile4 } from "fs/promises";
6928
- import { dirname as dirname4, isAbsolute as isAbsolute5, join as join5, resolve as resolve5 } from "path";
7262
+ import { mkdir as mkdir5, readFile as readFile2, realpath as realpath3, stat as stat4, writeFile as writeFile4 } from "fs/promises";
7263
+ import { dirname as dirname4, isAbsolute as isAbsolute6, join as join6, resolve as resolve5 } from "path";
6929
7264
  import { execFileSync as execFileSync2 } from "child_process";
6930
7265
  import { createHash as createHash6 } from "crypto";
6931
7266
  var dict = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
@@ -6945,7 +7280,7 @@ function codexAgentsFromEffectiveConfig(config, trustedProject = true, baseDir)
6945
7280
  const rawConfigFile = value.config_file;
6946
7281
  if (rawConfigFile !== undefined && typeof rawConfigFile !== "string")
6947
7282
  throw new Error(`Codex agents.${name}.config_file must be a string.`);
6948
- const configFile = rawConfigFile === undefined ? undefined : isAbsolute5(rawConfigFile) ? rawConfigFile : baseDir ? resolve5(baseDir, rawConfigFile) : undefined;
7283
+ const configFile = rawConfigFile === undefined ? undefined : isAbsolute6(rawConfigFile) ? rawConfigFile : baseDir ? resolve5(baseDir, rawConfigFile) : undefined;
6949
7284
  if (rawConfigFile !== undefined && !configFile)
6950
7285
  throw new Error(`Codex agents.${name}.config_file must be absolute after precedence resolution.`);
6951
7286
  const definition = { trusted: trustedProject, config_file: configFile };
@@ -7074,20 +7409,20 @@ async function writeCodexAgentOverrides(result, stateDir) {
7074
7409
  const paths = {};
7075
7410
  for (const agent of result.agents) {
7076
7411
  const digest = createHash6("sha256").update(agent.name).digest("hex").slice(0, 16);
7077
- const path = join5(root, `agent-${digest}.toml`);
7412
+ const path = join6(root, `agent-${digest}.toml`);
7078
7413
  await writeFile4(path, renderCodexAgentToml(agent.config), { encoding: "utf8", mode: 384, flag: "wx" });
7079
7414
  paths[agent.name] = path;
7080
7415
  }
7081
7416
  return paths;
7082
7417
  }
7083
7418
  async function prepareCodexModelPolicy(input) {
7084
- const home = resolve5(input.home ?? process.env.CODEX_HOME ?? join5(process.env.HOME ?? "/", ".codex"));
7419
+ const home = resolve5(input.home ?? process.env.CODEX_HOME ?? join6(process.env.HOME ?? "/", ".codex"));
7085
7420
  const cwd = resolve5(input.cwd);
7086
- const globalPath = join5(home, "config.toml");
7421
+ const globalPath = join6(home, "config.toml");
7087
7422
  const readConfig = async (path) => {
7088
7423
  let info;
7089
7424
  try {
7090
- info = await stat3(path);
7425
+ info = await stat4(path);
7091
7426
  } catch (error) {
7092
7427
  if (error.code === "ENOENT")
7093
7428
  return;
@@ -7107,7 +7442,7 @@ async function prepareCodexModelPolicy(input) {
7107
7442
  const global = await readConfig(globalPath) ?? {};
7108
7443
  const projects = dict(global.projects) ? global.projects : {};
7109
7444
  const markers = global.project_root_markers ?? [".git"];
7110
- if (!Array.isArray(markers) || markers.some((m) => typeof m !== "string" || isAbsolute5(m) || m.includes("..")))
7445
+ if (!Array.isArray(markers) || markers.some((m) => typeof m !== "string" || isAbsolute6(m) || m.includes("..")))
7111
7446
  throw new Error("Unsupported Codex project root markers.");
7112
7447
  const ancestorDirs = [];
7113
7448
  for (let dir = cwd;; dir = dirname4(dir)) {
@@ -7120,9 +7455,9 @@ async function prepareCodexModelPolicy(input) {
7120
7455
  for (const dir of ancestorDirs)
7121
7456
  for (const marker of markers) {
7122
7457
  try {
7123
- const info = await stat3(join5(dir, marker));
7458
+ const info = await stat4(join6(dir, marker));
7124
7459
  if (marker === ".git" && info.isDirectory())
7125
- await stat3(join5(dir, marker, "HEAD"));
7460
+ await stat4(join6(dir, marker, "HEAD"));
7126
7461
  projectRoot = dir;
7127
7462
  break findRoot;
7128
7463
  } catch {}
@@ -7147,7 +7482,7 @@ async function prepareCodexModelPolicy(input) {
7147
7482
  const layers = [{ path: globalPath, config: global }];
7148
7483
  const projectDirs = ancestorDirs.slice(0, ancestorDirs.indexOf(projectRoot) + 1).reverse();
7149
7484
  for (const dir of projectDirs) {
7150
- const path = join5(dir, ".codex", "config.toml");
7485
+ const path = join6(dir, ".codex", "config.toml");
7151
7486
  if (path === globalPath)
7152
7487
  continue;
7153
7488
  const decision = await trust(dir) ?? projectTrust ?? repoTrust;
@@ -7176,10 +7511,10 @@ async function prepareCodexModelPolicy(input) {
7176
7511
  return { ...result, agentConfigPaths: await writeCodexAgentOverrides(result, input.stateDir), configPaths: loaded };
7177
7512
  }
7178
7513
  async function readCodexAgentConfig(path) {
7179
- if (!isAbsolute5(path))
7514
+ if (!isAbsolute6(path))
7180
7515
  throw new Error("Codex agent config_file must be absolute before launch.");
7181
7516
  const canonical = await realpath3(path);
7182
- const info = await stat3(canonical);
7517
+ const info = await stat4(canonical);
7183
7518
  if (!info.isFile() || info.size > 1024 * 1024)
7184
7519
  throw new Error(`Codex agent config must be a regular file no larger than 1 MiB: ${path}`);
7185
7520
  const text = await readFile2(canonical, "utf8");
@@ -7191,27 +7526,27 @@ async function readCodexAgentConfig(path) {
7191
7526
  }
7192
7527
 
7193
7528
  // src/harnesses.ts
7194
- import { access as access2, mkdir as mkdir10, readFile as readFile4, readdir as readdir4, writeFile as writeFile10, rm as rm2 } from "fs/promises";
7195
- import { basename as basename2, dirname as dirname7, join as join11, isAbsolute as isAbsolute10, resolve as resolve8 } from "path";
7196
- import { homedir as homedir6, tmpdir } from "os";
7529
+ import { access as access3, mkdir as mkdir10, readFile as readFile4, readdir as readdir4, writeFile as writeFile10, rm as rm2 } from "fs/promises";
7530
+ import { basename as basename2, dirname as dirname7, join as join12, isAbsolute as isAbsolute11, resolve as resolve8 } from "path";
7531
+ import { homedir as homedir7, tmpdir } from "os";
7197
7532
  import { createHash as createHash8, randomUUID as randomUUID4, timingSafeEqual as timingSafeEqual5 } from "crypto";
7198
- import { execFile } from "child_process";
7199
- import { promisify } from "util";
7533
+ import { execFile as execFile2 } from "child_process";
7534
+ import { promisify as promisify2 } from "util";
7200
7535
  import { createConnection } from "net";
7201
7536
 
7202
7537
  // 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 constants2 } from "fs";
7205
- import { dirname as dirname5, basename, join as join6, resolve as resolve6, isAbsolute as isAbsolute6 } from "path";
7206
- import { homedir as homedir4 } from "os";
7538
+ import { readFile as readFile3, writeFile as writeFile5, lstat as lstat3, copyFile, rename, realpath as realpath4, access as access2 } from "fs/promises";
7539
+ import { constants as constants3 } from "fs";
7540
+ import { dirname as dirname5, basename, join as join7, resolve as resolve6, isAbsolute as isAbsolute7 } from "path";
7541
+ import { homedir as homedir5 } from "os";
7207
7542
  import { parseDocument as parseDocument2 } from "yaml";
7208
7543
  var KEY2 = "SWITCHER_HARNESS_API_KEY";
7209
7544
  var object3 = (v) => !!v && typeof v === "object" && !Array.isArray(v);
7210
7545
  async function data(path) {
7211
7546
  let text;
7212
7547
  try {
7213
- const stat4 = await lstat3(path);
7214
- if (!stat4.isFile() || stat4.size > 1024 * 1024)
7548
+ const stat5 = await lstat3(path);
7549
+ if (!stat5.isFile() || stat5.size > 1024 * 1024)
7215
7550
  throw new Error("unsupported");
7216
7551
  text = await readFile3(path, "utf8");
7217
7552
  } catch (error) {
@@ -7244,9 +7579,9 @@ async function gitRoot(path) {
7244
7579
  parent = dirname5(parent);
7245
7580
  }
7246
7581
  }
7247
- for (let dir = join6(parent, ...missing);; dir = dirname5(dir)) {
7582
+ for (let dir = join7(parent, ...missing);; dir = dirname5(dir)) {
7248
7583
  try {
7249
- await lstat3(join6(dir, ".git"));
7584
+ await lstat3(join7(dir, ".git"));
7250
7585
  return dir;
7251
7586
  } catch (error) {
7252
7587
  if (!["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
@@ -7259,9 +7594,9 @@ async function gitRoot(path) {
7259
7594
  var falseValue = (v) => v === undefined || v === null || v === false || v === 0 || typeof v === "string" && ["", "false", "no", "off", "0"].includes(v.toLowerCase());
7260
7595
  var startup = `yes-always gui browser upgrade install-main-branch just-check-update apply-clipboard-edits test lint commit`.split(" ");
7261
7596
  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("~/") ? join6(home, path.slice(2)) : path;
7263
- async function validateAiderConfiguration(cwd, args = [], home = process.env.HOME ?? homedir4()) {
7264
- if (!isAbsolute6(home))
7597
+ var expandHome = (path, home) => path === "~" ? home : path.startsWith("~/") ? join7(home, path.slice(2)) : path;
7598
+ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOME ?? homedir5()) {
7599
+ if (!isAbsolute7(home))
7265
7600
  throw new Error("Aider requires an absolute HOME to preserve native instruction paths.");
7266
7601
  const parsed = aiderArguments(args), cwdRoot = await gitRoot(cwd);
7267
7602
  const roots = new Set([resolve6(home), ...cwdRoot ? [cwdRoot] : [], resolve6(cwd)]);
@@ -7272,7 +7607,7 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
7272
7607
  }
7273
7608
  let effective = {};
7274
7609
  for (const root of roots) {
7275
- const path = join6(root, ".aider.conf.yml"), value = await data(path);
7610
+ const path = join7(root, ".aider.conf.yml"), value = await data(path);
7276
7611
  if (value !== undefined) {
7277
7612
  if (!object3(value))
7278
7613
  throw new Error(`Aider configuration must be a mapping: ${path}`);
@@ -7297,13 +7632,13 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
7297
7632
  }
7298
7633
  effective = { ...effective, ...normalized };
7299
7634
  }
7300
- const settings2 = await data(join6(root, ".aider.model.settings.yml"));
7635
+ const settings2 = await data(join7(root, ".aider.model.settings.yml"));
7301
7636
  if (settings2 !== undefined) {
7302
7637
  if (!Array.isArray(settings2))
7303
7638
  throw new Error("Aider model settings must be a list.");
7304
7639
  for (const entry of settings2)
7305
7640
  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: ${join6(root, ".aider.model.settings.yml")}`);
7641
+ throw new Error(`Aider custom transport or callback model settings cannot be preserved safely: ${join7(root, ".aider.model.settings.yml")}`);
7307
7642
  }
7308
7643
  }
7309
7644
  if (effective.read !== undefined && !(typeof effective.read === "string" || Array.isArray(effective.read) && effective.read.every((v) => typeof v === "string")))
@@ -7311,7 +7646,7 @@ async function validateAiderConfiguration(cwd, args = [], home = process.env.HOM
7311
7646
  const reads = parsed.reads.length ? parsed.reads : typeof effective.read === "string" ? [effective.read] : effective.read ?? [];
7312
7647
  for (const path of reads) {
7313
7648
  try {
7314
- await access(resolve6(cwd, expandHome(path, home)), constants2.R_OK);
7649
+ await access2(resolve6(cwd, expandHome(path, home)), constants3.R_OK);
7315
7650
  } catch {
7316
7651
  throw new Error(`Aider read-only instruction file is not readable: ${path}`);
7317
7652
  }
@@ -7324,8 +7659,8 @@ function aiderModelName(protocol, id2) {
7324
7659
  return `${protocol === "anthropic-messages" ? "anthropic" : protocol === "openai-responses" ? "openai/responses" : "openai"}/${id2}`;
7325
7660
  }
7326
7661
  async function historyFile(path) {
7327
- const stat4 = await lstat3(path);
7328
- if (!stat4.isFile() || stat4.isSymbolicLink() || stat4.size > 64 * 1024 * 1024 || process.platform !== "win32" && ((stat4.mode & 63) !== 0 || stat4.uid !== process.getuid?.()))
7662
+ const stat5 = await lstat3(path);
7663
+ if (!stat5.isFile() || stat5.isSymbolicLink() || stat5.size > 64 * 1024 * 1024 || process.platform !== "win32" && ((stat5.mode & 63) !== 0 || stat5.uid !== process.getuid?.()))
7329
7664
  throw new Error("Aider history must be an owner-only regular file smaller than 64 MiB.");
7330
7665
  }
7331
7666
  async function prepareAider(input) {
@@ -7339,7 +7674,7 @@ async function prepareAider(input) {
7339
7674
  const files = parsed.args.splice(literal2).slice(1);
7340
7675
  parsed.args.push(...files.map((path) => resolve6(input.cwd, path)));
7341
7676
  }
7342
- const sourceHome = process.env.HOME ?? homedir4();
7677
+ const sourceHome = process.env.HOME ?? homedir5();
7343
7678
  for (let i = 0;i < parsed.args.length; i++) {
7344
7679
  if (parsed.args[i] === "--read") {
7345
7680
  i++;
@@ -7347,26 +7682,26 @@ async function prepareAider(input) {
7347
7682
  } else if (parsed.args[i].startsWith("--read="))
7348
7683
  parsed.args[i] = "--read=" + expandHome(parsed.args[i].slice(7), sourceHome);
7349
7684
  }
7350
- const home = join6(input.stateDir, "aider-home");
7685
+ const home = join7(input.stateDir, "aider-home");
7351
7686
  await privateDirectory(home);
7352
- const originalHome = process.env.HOME ?? homedir4();
7353
- const gitSources = process.env.GIT_CONFIG_GLOBAL ? [resolve6(process.env.GIT_CONFIG_GLOBAL)] : [join6(process.env.XDG_CONFIG_HOME ?? join6(originalHome, ".config"), "git", "config"), join6(originalHome, ".gitconfig")];
7354
- const gitConfig = join6(home, ".gitconfig");
7687
+ const originalHome = process.env.HOME ?? homedir5();
7688
+ const gitSources = process.env.GIT_CONFIG_GLOBAL ? [resolve6(process.env.GIT_CONFIG_GLOBAL)] : [join7(process.env.XDG_CONFIG_HOME ?? join7(originalHome, ".config"), "git", "config"), join7(originalHome, ".gitconfig")];
7689
+ const gitConfig = join7(home, ".gitconfig");
7355
7690
  await writeFile5(gitConfig, gitSources.map((path) => `[include]
7356
7691
  path = ${JSON.stringify(path)}
7357
7692
  `).join(""), { mode: 384, flag: "wx" });
7358
- const sessions = input.sessionDir ?? join6(input.stateDir, "sessions");
7693
+ const sessions = input.sessionDir ?? join7(input.stateDir, "sessions");
7359
7694
  await privateDirectory(sessions);
7360
- const id2 = crypto.randomUUID(), history = join6(sessions, `${id2}.chat.md`), inputHistory = join6(sessions, `${id2}.input`);
7695
+ const id2 = crypto.randomUUID(), history = join7(sessions, `${id2}.chat.md`), inputHistory = join7(sessions, `${id2}.input`);
7361
7696
  if (parsed.restore) {
7362
- const latest = join6(sessions, "latest.json");
7697
+ const latest = join7(sessions, "latest.json");
7363
7698
  await historyFile(latest).catch(() => {
7364
7699
  throw new Error("No valid completed Aider history is available for this profile.");
7365
7700
  });
7366
7701
  const previous = JSON.parse(await readFile3(latest, "utf8"));
7367
7702
  if (!object3(previous) || typeof previous.id !== "string" || !/^[-a-f0-9]{36}$/.test(previous.id))
7368
7703
  throw new Error("Invalid Aider history reference.");
7369
- const source = join6(sessions, `${previous.id}.chat.md`);
7704
+ const source = join7(sessions, `${previous.id}.chat.md`);
7370
7705
  await historyFile(source);
7371
7706
  await copyFile(source, history, 1);
7372
7707
  } else
@@ -7376,7 +7711,7 @@ async function prepareAider(input) {
7376
7711
  const model2 = aiderModelName(input.protocol, input.model);
7377
7712
  const weakModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.weak ?? input.model), editorModel = aiderModelName(input.protocol, input.compiledPolicy?.roles.editor ?? input.model);
7378
7713
  const extra = { api_base: input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl, api_key: `os.environ/${KEY2}` };
7379
- const settings2 = join6(input.stateDir, "aider-model-settings.json"), metadata = join6(input.stateDir, "aider-model-metadata.json"), config = join6(input.stateDir, "aider-config.json"), empty = join6(input.stateDir, "aider-empty.env");
7714
+ const settings2 = join7(input.stateDir, "aider-model-settings.json"), metadata = join7(input.stateDir, "aider-model-metadata.json"), config = join7(input.stateDir, "aider-config.json"), empty = join7(input.stateDir, "aider-empty.env");
7380
7715
  const definitions = input.models.map((m) => ({ name: aiderModelName(input.protocol, m.id), edit_format: "whole", use_repo_map: true, weak_model_name: weakModel, editor_model_name: editorModel, extra_params: extra }));
7381
7716
  await writeFile5(settings2, JSON.stringify([...definitions, { name: "aider/extra_params", extra_params: extra }]), { mode: 384, flag: "wx" });
7382
7717
  await writeFile5(metadata, JSON.stringify(Object.fromEntries(input.models.map((m) => [aiderModelName(input.protocol, m.id), {
@@ -7395,7 +7730,7 @@ async function prepareAider(input) {
7395
7730
  return {
7396
7731
  executable: input.executable ?? "aider",
7397
7732
  args: ["--config", config, "--model", model2, "--weak-model", weakModel, "--editor-model", editorModel, "--set-env", "PYTHON_DOTENV_DISABLED=1", "--api-key", "SWITCHER_UNUSED=unused", ...aliases, ...parsed.args],
7398
- env: { HOME: home, XDG_CONFIG_HOME: join6(home, "config"), XDG_CACHE_HOME: join6(home, "cache"), XDG_DATA_HOME: join6(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 },
7733
+ env: { HOME: home, XDG_CONFIG_HOME: join7(home, "config"), XDG_CACHE_HOME: join7(home, "cache"), XDG_DATA_HOME: join7(home, "data"), PYTHON_DOTENV_DISABLED: "1", LITELLM_LOCAL_MODEL_COST_MAP: "True", [KEY2]: input.credential, [input.protocol === "anthropic-messages" ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY"]: input.credential },
7399
7734
  configPaths: [config, settings2, metadata, empty, gitConfig],
7400
7735
  warnings: [
7401
7736
  ...input.protocol === "openai-responses" ? ["Aider 0.86.2 with LiteLLM 1.81.10 uses buffered Responses requests even when native streaming is requested; incremental upstream Responses output is unavailable through this adapter."] : [],
@@ -7411,9 +7746,9 @@ async function prepareAider(input) {
7411
7746
  await historyFile(history);
7412
7747
  if (!/^#### /m.test((await readFile3(history, "utf8")).slice(originalHistoryLength)))
7413
7748
  return;
7414
- const pending = join6(sessions, `${id2}.latest.json`);
7749
+ const pending = join7(sessions, `${id2}.latest.json`);
7415
7750
  await writeFile5(pending, JSON.stringify({ id: id2 }), { mode: 384, flag: "wx" });
7416
- await rename(pending, join6(sessions, "latest.json"));
7751
+ await rename(pending, join7(sessions, "latest.json"));
7417
7752
  }
7418
7753
  };
7419
7754
  }
@@ -7497,7 +7832,7 @@ function validateGrokResume(args) {
7497
7832
  // src/cline-backend.ts
7498
7833
  import { mkdir as mkdir6, writeFile as writeFile6 } from "fs/promises";
7499
7834
  import { randomUUID as randomUUID2 } from "crypto";
7500
- import { isAbsolute as isAbsolute7, join as join7 } from "path";
7835
+ import { isAbsolute as isAbsolute8, join as join8 } from "path";
7501
7836
  var ENV_BY_PROTOCOL = {
7502
7837
  "anthropic-messages": "ANTHROPIC_API_KEY",
7503
7838
  "openai-responses": "OPENAI_API_KEY",
@@ -7543,18 +7878,18 @@ async function prepareClineLaunch(input) {
7543
7878
  throw new Error(`Cline ${input.protocol} uses ${mapping.authStyle} authentication; use a provider with the native Cline auth contract.`);
7544
7879
  if (input.credential && /[\r\n]/.test(input.credential))
7545
7880
  throw new Error("Provider credential contains invalid header characters.");
7546
- if (!isAbsolute7(input.stateDir) || !isAbsolute7(input.cwd))
7881
+ if (!isAbsolute8(input.stateDir) || !isAbsolute8(input.cwd))
7547
7882
  throw new Error("Launch state and working directories must be absolute.");
7548
- const dataDir = join7(input.stateDir, "cline-data");
7549
- const sessionDir = input.sessionDir ?? join7(dataDir, "sessions");
7550
- const launchDir = join7(input.stateDir, `cline-launch-${randomUUID2()}`);
7551
- const settingsDir = join7(launchDir, "settings");
7552
- const configDir = join7(launchDir, "config");
7883
+ const dataDir = join8(input.stateDir, "cline-data");
7884
+ const sessionDir = input.sessionDir ?? join8(dataDir, "sessions");
7885
+ const launchDir = join8(input.stateDir, `cline-launch-${randomUUID2()}`);
7886
+ const settingsDir = join8(launchDir, "settings");
7887
+ const configDir = join8(launchDir, "config");
7553
7888
  await mkdir6(settingsDir, { recursive: true, mode: 448 });
7554
7889
  await mkdir6(configDir, { recursive: true, mode: 448 });
7555
7890
  const baseUrl = endpoint(input.baseUrl);
7556
7891
  const providerId = mapping.providerId;
7557
- const providersPath = await writeJson(join7(settingsDir, "providers.json"), {
7892
+ const providersPath = await writeJson(join8(settingsDir, "providers.json"), {
7558
7893
  version: 1,
7559
7894
  lastUsedProvider: providerId,
7560
7895
  modes: {},
@@ -7574,7 +7909,7 @@ async function prepareClineLaunch(input) {
7574
7909
  }
7575
7910
  }
7576
7911
  });
7577
- const modelsPath = await writeJson(join7(settingsDir, "models.json"), {
7912
+ const modelsPath = await writeJson(join8(settingsDir, "models.json"), {
7578
7913
  version: 1,
7579
7914
  providers: {
7580
7915
  [providerId]: {
@@ -7623,17 +7958,17 @@ async function prepareClineLaunch(input) {
7623
7958
  }
7624
7959
 
7625
7960
  // src/opencode2-config.ts
7626
- import { mkdir as mkdir7, open as open2, realpath as realpath5, readdir as readdir3, stat as stat4, writeFile as writeFile7 } from "fs/promises";
7627
- import { constants as constants3 } from "fs";
7628
- import { dirname as dirname6, isAbsolute as isAbsolute8, join as join8, relative as relative4, resolve as resolve7 } from "path";
7629
- import { homedir as homedir5 } from "os";
7961
+ import { mkdir as mkdir7, open as open2, realpath as realpath5, readdir as readdir3, stat as stat5, writeFile as writeFile7 } from "fs/promises";
7962
+ import { constants as constants4 } from "fs";
7963
+ import { dirname as dirname6, isAbsolute as isAbsolute9, join as join9, relative as relative4, resolve as resolve7 } from "path";
7964
+ import { homedir as homedir6 } from "os";
7630
7965
  import { randomUUID as randomUUID3 } from "crypto";
7631
7966
  import { Database as Database2 } from "bun:sqlite";
7632
7967
  import { parse as parse3, parseTree as parseTree3 } from "jsonc-parser";
7633
7968
  import { parseDocument as parseDocument3 } from "yaml";
7634
- import { z as z5 } from "zod";
7635
- var effect = z5.enum(["allow", "deny", "ask"]);
7636
- var rule = z5.object({ action: z5.string(), resource: z5.string(), effect }).strict();
7969
+ import { z as z6 } from "zod";
7970
+ var effect = z6.enum(["allow", "deny", "ask"]);
7971
+ var rule = z6.object({ action: z6.string(), resource: z6.string(), effect }).strict();
7637
7972
  var object4 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
7638
7973
  var own2 = (value, key) => Object.hasOwn(value, key);
7639
7974
  var maxFileBytes2 = 1024 * 1024;
@@ -7641,7 +7976,7 @@ var maxTotalBytes2 = 8 * 1024 * 1024;
7641
7976
  var maxFiles2 = 256;
7642
7977
  var inside2 = (root, path) => {
7643
7978
  const rel = relative4(root, path);
7644
- return rel === "" || !isAbsolute8(rel) && rel !== ".." && !rel.startsWith("../");
7979
+ return rel === "" || !isAbsolute9(rel) && rel !== ".." && !rel.startsWith("../");
7645
7980
  };
7646
7981
  var action = (value) => ({ bash: "shell", task: "subagent", write: "edit", patch: "edit" })[value] ?? value;
7647
7982
  function invalid2(path, field) {
@@ -7683,7 +8018,7 @@ function permissions(value, path, home) {
7683
8018
  }
7684
8019
  }
7685
8020
  if (own2(value, "permissions")) {
7686
- const parsed = z5.array(rule).safeParse(value.permissions);
8021
+ const parsed = z6.array(rule).safeParse(value.permissions);
7687
8022
  if (!parsed.success)
7688
8023
  invalid2(path, "permissions");
7689
8024
  result.push(...parsed.data);
@@ -7693,7 +8028,7 @@ function permissions(value, path, home) {
7693
8028
  literal2(item.resource, path, "permission resource");
7694
8029
  if (!["read", "edit", "external_directory"].includes(item.action))
7695
8030
  return item;
7696
- const resource = item.resource === "~" || item.resource === "$HOME" ? home : item.resource.startsWith("~/") ? join8(home, item.resource.slice(2)) : item.resource.startsWith("$HOME/") || item.resource.startsWith("$HOME\\") ? join8(home, item.resource.slice(6)) : item.resource;
8031
+ const resource = item.resource === "~" || item.resource === "$HOME" ? home : item.resource.startsWith("~/") ? join9(home, item.resource.slice(2)) : item.resource.startsWith("$HOME/") || item.resource.startsWith("$HOME\\") ? join9(home, item.resource.slice(6)) : item.resource;
7697
8032
  return { ...item, resource };
7698
8033
  });
7699
8034
  }
@@ -7721,14 +8056,14 @@ function jsonc2(text, path) {
7721
8056
  return record2(value, path, "configuration object");
7722
8057
  }
7723
8058
  async function checkRemoteConfiguration(dataHome) {
7724
- const path = join8(dataHome, "opencode", "opencode.db");
7725
- const legacyAuth = await stat4(join8(dataHome, "opencode", "auth.json")).then(() => true, (error) => {
8059
+ const path = join9(dataHome, "opencode", "opencode.db");
8060
+ const legacyAuth = await stat5(join9(dataHome, "opencode", "auth.json")).then(() => true, (error) => {
7726
8061
  if (error.code === "ENOENT")
7727
8062
  return false;
7728
8063
  throw error;
7729
8064
  });
7730
8065
  try {
7731
- await stat4(path);
8066
+ await stat5(path);
7732
8067
  } catch (error) {
7733
8068
  if (error.code === "ENOENT") {
7734
8069
  if (legacyAuth)
@@ -7762,23 +8097,23 @@ async function checkRemoteConfiguration(dataHome) {
7762
8097
  }
7763
8098
  async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
7764
8099
  for (const name of ["HOME", "XDG_CONFIG_HOME", "XDG_DATA_HOME", "OPENCODE_CONFIG_DIR"])
7765
- if (env[name] && !isAbsolute8(env[name]))
8100
+ if (env[name] && !isAbsolute9(env[name]))
7766
8101
  throw new Error(`OpenCode 2 requires an absolute ${name} to preserve native configuration authority.`);
7767
- const home = resolve7(env.HOME || homedir5());
7768
- const configRoot = resolve7(env.OPENCODE_CONFIG_DIR || join8(env.XDG_CONFIG_HOME || join8(home, ".config"), "opencode"));
8102
+ const home = resolve7(env.HOME || homedir6());
8103
+ const configRoot = resolve7(env.OPENCODE_CONFIG_DIR || join9(env.XDG_CONFIG_HOME || join9(home, ".config"), "opencode"));
7769
8104
  const canonicalConfigRoot = await realpath5(configRoot).catch((error) => {
7770
8105
  if (error.code === "ENOENT")
7771
8106
  return configRoot;
7772
8107
  throw error;
7773
8108
  });
7774
- const dataHome = resolve7(env.XDG_DATA_HOME || join8(home, ".local", "share"));
8109
+ const dataHome = resolve7(env.XDG_DATA_HOME || join9(home, ".local", "share"));
7775
8110
  await checkRemoteConfiguration(dataHome);
7776
8111
  let files = 0, total = 0;
7777
8112
  const paths = [];
7778
8113
  async function read(path, optional = true) {
7779
8114
  let handle;
7780
8115
  try {
7781
- handle = await open2(path, constants3.O_RDONLY | constants3.O_NONBLOCK);
8116
+ handle = await open2(path, constants4.O_RDONLY | constants4.O_NONBLOCK);
7782
8117
  } catch (error) {
7783
8118
  if (optional && error.code === "ENOENT")
7784
8119
  return;
@@ -7811,7 +8146,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
7811
8146
  invalid2(path, "agent prompt environment reference");
7812
8147
  let result = "", cursor = 0;
7813
8148
  for (const match of text.matchAll(/\{file:([^}]+)\}/g)) {
7814
- const requested = match[1].startsWith("~/") ? join8(home, match[1].slice(2)) : resolve7(dirname6(path), match[1]);
8149
+ const requested = match[1].startsWith("~/") ? join9(home, match[1].slice(2)) : resolve7(dirname6(path), match[1]);
7815
8150
  const content = (await read(requested, false)).trim();
7816
8151
  literal2(content, requested, "nested prompt variable reference");
7817
8152
  result += text.slice(cursor, match.index) + content;
@@ -7833,7 +8168,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
7833
8168
  }
7834
8169
  async function agentsDirectory(directory2) {
7835
8170
  for (const source of ["agent", "agents", "mode", "modes"]) {
7836
- const base = join8(directory2, source), entries = [];
8171
+ const base = join9(directory2, source), entries = [];
7837
8172
  const visited = new Set;
7838
8173
  let examined = 0;
7839
8174
  async function walk(dir, depth) {
@@ -7852,8 +8187,8 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
7852
8187
  if (depth > 16 || (examined += names.length) > maxFiles2)
7853
8188
  throw new Error("OpenCode 2 agent policy exceeds its bounded directory limit.");
7854
8189
  for (const name of names) {
7855
- const path = join8(dir, name);
7856
- const info = await stat4(path);
8190
+ const path = join9(dir, name);
8191
+ const info = await stat5(path);
7857
8192
  if (info.isDirectory()) {
7858
8193
  if (source === "agent" || source === "agents")
7859
8194
  await walk(path, depth + 1);
@@ -7886,8 +8221,8 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
7886
8221
  }
7887
8222
  }
7888
8223
  async function directory(path) {
7889
- await document(join8(path, "opencode.json"));
7890
- await document(join8(path, "opencode.jsonc"));
8224
+ await document(join9(path, "opencode.json"));
8225
+ await document(join9(path, "opencode.jsonc"));
7891
8226
  await agentsDirectory(path);
7892
8227
  }
7893
8228
  await directory(configRoot);
@@ -7902,11 +8237,11 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
7902
8237
  const projectEnabled = !["1", "true"].includes((env.OPENCODE_CONFIG_PROJECT_DISABLE ?? env.OPENCODE_DISABLE_PROJECT_CONFIG ?? "").toLowerCase());
7903
8238
  if (projectEnabled) {
7904
8239
  for (const path of [...ancestors].reverse()) {
7905
- await document(join8(path, "opencode.json"));
7906
- await document(join8(path, "opencode.jsonc"));
8240
+ await document(join9(path, "opencode.json"));
8241
+ await document(join9(path, "opencode.jsonc"));
7907
8242
  }
7908
8243
  for (const path of [...ancestors].reverse()) {
7909
- const candidate = join8(path, ".opencode");
8244
+ const candidate = join9(path, ".opencode");
7910
8245
  const canonical = await realpath5(candidate).catch((error) => {
7911
8246
  if (error.code === "ENOENT")
7912
8247
  return candidate;
@@ -7917,7 +8252,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
7917
8252
  }
7918
8253
  }
7919
8254
  if (env.OPENCODE_CONFIG_CONTENT)
7920
- documents.push({ path: join8(cwd, "OPENCODE_CONFIG_CONTENT"), value: jsonc2(env.OPENCODE_CONFIG_CONTENT, "OPENCODE_CONFIG_CONTENT") });
8255
+ documents.push({ path: join9(cwd, "OPENCODE_CONFIG_CONTENT"), value: jsonc2(env.OPENCODE_CONFIG_CONTENT, "OPENCODE_CONFIG_CONTENT") });
7921
8256
  const policy = [];
7922
8257
  const agents = Object.create(null);
7923
8258
  let defaultAgent;
@@ -7928,19 +8263,19 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
7928
8263
  defaultAgent = literal2(string2(value.default_agent, path, "default_agent"), path, "default_agent");
7929
8264
  const policies = [];
7930
8265
  if (own2(value, "enabled_providers")) {
7931
- const names = z5.array(z5.string()).safeParse(value.enabled_providers);
8266
+ const names = z6.array(z6.string()).safeParse(value.enabled_providers);
7932
8267
  if (!names.success)
7933
8268
  invalid2(path, "provider policy");
7934
8269
  policies.push({ action: "provider.use", resource: "*", effect: "deny" }, ...names.data.map((resource) => ({ action: "provider.use", resource, effect: "allow" })));
7935
8270
  }
7936
8271
  if (own2(value, "disabled_providers")) {
7937
- const names = z5.array(z5.string()).safeParse(value.disabled_providers);
8272
+ const names = z6.array(z6.string()).safeParse(value.disabled_providers);
7938
8273
  if (!names.success)
7939
8274
  invalid2(path, "provider policy");
7940
8275
  policies.push(...names.data.map((resource) => ({ action: "provider.use", resource, effect: "deny" })));
7941
8276
  }
7942
8277
  if (object4(value.experimental) && own2(value.experimental, "policies")) {
7943
- const parsed = z5.array(z5.object({ action: z5.literal("provider.use"), resource: z5.string(), effect: z5.enum(["allow", "deny"]) }).strict()).safeParse(value.experimental.policies);
8278
+ const parsed = z6.array(z6.object({ action: z6.literal("provider.use"), resource: z6.string(), effect: z6.enum(["allow", "deny"]) }).strict()).safeParse(value.experimental.policies);
7944
8279
  if (!parsed.success)
7945
8280
  invalid2(path, "provider policy");
7946
8281
  policies.push(...parsed.data);
@@ -7964,7 +8299,7 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
7964
8299
  if (own2(item, "description"))
7965
8300
  target.description = string2(item.description, path, "agent description");
7966
8301
  if (own2(item, "mode")) {
7967
- const parsed = z5.enum(["primary", "subagent", "all"]).safeParse(item.mode);
8302
+ const parsed = z6.enum(["primary", "subagent", "all"]).safeParse(item.mode);
7968
8303
  if (!parsed.success)
7969
8304
  invalid2(path, "agent mode");
7970
8305
  target.mode = parsed.data;
@@ -8010,26 +8345,26 @@ async function isolateOpenCode2(cwd, stateDir, providerID, env = process.env) {
8010
8345
  instructions.push(`Instructions from: ${path}
8011
8346
  ${content}`);
8012
8347
  }
8013
- await instruction(join8(configRoot, "AGENTS.md"));
8348
+ await instruction(join9(configRoot, "AGENTS.md"));
8014
8349
  if (projectEnabled) {
8015
8350
  let stop = resolve7(cwd);
8016
8351
  if (inside2(home, resolve7(cwd)))
8017
8352
  stop = home;
8018
8353
  else
8019
8354
  for (const path of ancestors) {
8020
- if (await stat4(join8(path, ".git")).then(() => true, () => false)) {
8355
+ if (await stat5(join9(path, ".git")).then(() => true, () => false)) {
8021
8356
  stop = path;
8022
8357
  break;
8023
8358
  }
8024
8359
  }
8025
8360
  for (const path of ancestors) {
8026
- await instruction(join8(path, "AGENTS.md"));
8361
+ await instruction(join9(path, "AGENTS.md"));
8027
8362
  if (path === stop)
8028
8363
  break;
8029
8364
  }
8030
8365
  }
8031
- const privateHome = join8(stateDir, "opencode-home"), privateConfig = join8(stateDir, "opencode-config");
8032
- const instructionFile = join8(privateConfig, "opencode", "AGENTS.md");
8366
+ const privateHome = join9(stateDir, "opencode-home"), privateConfig = join9(stateDir, "opencode-config");
8367
+ const instructionFile = join9(privateConfig, "opencode", "AGENTS.md");
8033
8368
  await mkdir7(dirname6(instructionFile), { recursive: true, mode: 448 });
8034
8369
  await mkdir7(privateHome, { recursive: true, mode: 448 });
8035
8370
  await writeFile7(instructionFile, instructions.join(`
@@ -8037,7 +8372,7 @@ ${content}`);
8037
8372
  `), { flag: "wx", mode: 384 });
8038
8373
  return {
8039
8374
  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: join8(privateConfig, "opencode"), XDG_CACHE_HOME: join8(stateDir, "opencode-cache"), XDG_STATE_HOME: join8(stateDir, "opencode-state"), XDG_DATA_HOME: dataHome, OPENCODE_DISABLE_PROJECT_CONFIG: "true", OPENCODE_CONFIG_PROJECT_DISABLE: "true", OPENCODE_DISABLE_MODELS_FETCH: "true" },
8375
+ env: { HOME: privateHome, XDG_CONFIG_HOME: privateConfig, OPENCODE_CONFIG_DIR: join9(privateConfig, "opencode"), XDG_CACHE_HOME: join9(stateDir, "opencode-cache"), XDG_STATE_HOME: join9(stateDir, "opencode-state"), XDG_DATA_HOME: dataHome, OPENCODE_DISABLE_PROJECT_CONFIG: "true", OPENCODE_CONFIG_PROJECT_DISABLE: "true", OPENCODE_DISABLE_MODELS_FETCH: "true" },
8041
8376
  instructionFile,
8042
8377
  sourcePaths: paths
8043
8378
  };
@@ -8053,7 +8388,7 @@ function openCode2ConfigText(config, providerID, keyEnv) {
8053
8388
 
8054
8389
  // src/omp-backend.ts
8055
8390
  import { mkdir as mkdir8, rm, writeFile as writeFile8 } from "fs/promises";
8056
- import { join as join9 } from "path";
8391
+ import { join as join10 } from "path";
8057
8392
  var KEY3 = "SWITCHER_HARNESS_API_KEY";
8058
8393
  var API = {
8059
8394
  "anthropic-messages": "anthropic-messages",
@@ -8078,8 +8413,8 @@ async function prepareOmpLaunch(input) {
8078
8413
  const baseUrl = endpoint(input.baseUrl);
8079
8414
  if (input.credential && /[\r\n]/.test(input.credential))
8080
8415
  throw new Error("Provider credential contains invalid header characters.");
8081
- const agentDir = join9(input.stateDir, "omp-agent");
8082
- const sessionDir = input.sessionDir ?? join9(input.stateDir, "sessions");
8416
+ const agentDir = join10(input.stateDir, "omp-agent");
8417
+ const sessionDir = input.sessionDir ?? join10(input.stateDir, "sessions");
8083
8418
  await mkdir8(agentDir, { recursive: true, mode: 448 });
8084
8419
  await mkdir8(sessionDir, { recursive: true, mode: 448 });
8085
8420
  const api = API[input.protocol];
@@ -8105,8 +8440,8 @@ async function prepareOmpLaunch(input) {
8105
8440
  provider.apiKey = KEY3;
8106
8441
  provider.authHeader = true;
8107
8442
  }
8108
- const modelsPath = join9(agentDir, "models.yml");
8109
- const configPath = join9(agentDir, "config.yml");
8443
+ const modelsPath = join10(agentDir, "models.yml");
8444
+ const configPath = join10(agentDir, "config.yml");
8110
8445
  const selector = `switcher/${input.model}`;
8111
8446
  await writeFile8(modelsPath, JSON.stringify({ providers: { switcher: provider } }, null, 2) + `
8112
8447
  `, { mode: 384, flag: "wx" });
@@ -8184,7 +8519,7 @@ function compileHermesModelPolicy(currentModel, roles2, baseUrl, apiMode = "chat
8184
8519
  // src/hermes-backend.ts
8185
8520
  import { createHash as createHash7, timingSafeEqual as timingSafeEqual4 } from "crypto";
8186
8521
  import { mkdir as mkdir9, symlink as symlink2, writeFile as writeFile9 } from "fs/promises";
8187
- import { isAbsolute as isAbsolute9, join as join10 } from "path";
8522
+ import { isAbsolute as isAbsolute10, join as join11 } from "path";
8188
8523
  var hermesApiMode = {
8189
8524
  "anthropic-messages": "anthropic_messages",
8190
8525
  "openai-responses": "codex_responses",
@@ -8323,7 +8658,7 @@ function createHermesBridge(input) {
8323
8658
  };
8324
8659
  }
8325
8660
  async function prepareHermesLaunch(input) {
8326
- if (!isAbsolute9(input.stateDir) || !isAbsolute9(input.cwd))
8661
+ if (!isAbsolute10(input.stateDir) || !isAbsolute10(input.cwd))
8327
8662
  throw new Error("Launch state and working directories must be absolute.");
8328
8663
  if (input.protocol !== "anthropic-messages" && input.protocol !== "openai-responses" && input.protocol !== "openai-chat")
8329
8664
  throw new Error("Hermes does not support this provider protocol.");
@@ -8333,12 +8668,12 @@ async function prepareHermesLaunch(input) {
8333
8668
  throw new Error("Hermes cannot safely select model IDs that differ only by letter case; update the provider catalog.");
8334
8669
  if (input.credential && /[\r\n]/.test(input.credential))
8335
8670
  throw new Error("Provider credential contains invalid header characters.");
8336
- const sessionDir = input.sessionDir ?? join10(input.stateDir, "hermes-session");
8337
- const sessionsDir = join10(sessionDir, "sessions");
8671
+ const sessionDir = input.sessionDir ?? join11(input.stateDir, "hermes-session");
8672
+ const sessionsDir = join11(sessionDir, "sessions");
8338
8673
  await mkdir9(input.stateDir, { recursive: true, mode: 448 });
8339
8674
  await mkdir9(sessionsDir, { recursive: true, mode: 448 });
8340
- await symlink2(join10(sessionDir, "state.db"), join10(input.stateDir, "state.db"));
8341
- await symlink2(sessionsDir, join10(input.stateDir, "sessions"));
8675
+ await symlink2(join11(sessionDir, "state.db"), join11(input.stateDir, "state.db"));
8676
+ await symlink2(sessionsDir, join11(input.stateDir, "sessions"));
8342
8677
  const bridge = createHermesBridge(input);
8343
8678
  let policy;
8344
8679
  try {
@@ -8366,7 +8701,7 @@ async function prepareHermesLaunch(input) {
8366
8701
  }
8367
8702
  }
8368
8703
  };
8369
- const configPath = join10(input.stateDir, "config.yaml");
8704
+ const configPath = join11(input.stateDir, "config.yaml");
8370
8705
  try {
8371
8706
  await writeFile9(configPath, JSON.stringify(config, null, 2) + `
8372
8707
  `, { mode: 384, flag: "wx" });
@@ -8383,7 +8718,7 @@ async function prepareHermesLaunch(input) {
8383
8718
  SWITCHER_HERMES_AUX_API_KEY: bridge.token,
8384
8719
  OPENAI_API_KEY: bridge.token,
8385
8720
  OPENAI_BASE_URL: bridge.baseUrl,
8386
- CODEX_HOME: join10(input.stateDir, "codex-home")
8721
+ CODEX_HOME: join11(input.stateDir, "codex-home")
8387
8722
  },
8388
8723
  configPaths: [configPath],
8389
8724
  warnings: [
@@ -8521,14 +8856,14 @@ function harnessInstallationMessage(harness, executable, explicitOverride) {
8521
8856
  }
8522
8857
 
8523
8858
  // src/harnesses.ts
8524
- var execute = promisify(execFile);
8859
+ var execute2 = promisify2(execFile2);
8525
8860
  var KEY4 = "SWITCHER_HARNESS_API_KEY";
8526
8861
  var quote = (value) => JSON.stringify(value);
8527
8862
  async function detectHarness(harness, override) {
8528
8863
  const executable = override ?? Bun.which(harness) ?? harness;
8529
8864
  const installation = harnessInstallation(harness);
8530
8865
  try {
8531
- const { stdout, stderr } = await execute(executable, ["--version"], { timeout: 8000, maxBuffer: 65536, env: childEnvironment() });
8866
+ const { stdout, stderr } = await execute2(executable, ["--version"], { timeout: 8000, maxBuffer: 65536, env: childEnvironment() });
8532
8867
  return { harness, executable, available: true, version: (stdout.trim() || stderr.trim()).slice(0, 200), installation };
8533
8868
  } catch {
8534
8869
  return { harness, executable, available: false, version: undefined, installation };
@@ -8589,7 +8924,7 @@ function validateHarnessVersion(harness, version) {
8589
8924
  throw new Error("Gemini CLI 0.58.0 is required by the verified native settings and argument contract.");
8590
8925
  }
8591
8926
  async function jsonFile(dir, name, value) {
8592
- const path = join11(dir, name);
8927
+ const path = join12(dir, name);
8593
8928
  await writeFile10(path, JSON.stringify(value, null, 2) + `
8594
8929
  `, { mode: 384, flag: "wx" });
8595
8930
  return path;
@@ -8598,8 +8933,8 @@ async function projectInstructionPaths(cwd) {
8598
8933
  let dir = resolve8(cwd);
8599
8934
  while (true) {
8600
8935
  for (const name of ["AGENTS.md", "CLAUDE.md", "CONTEXT.md"]) {
8601
- const path = join11(dir, name);
8602
- if (await access2(path).then(() => true, () => false))
8936
+ const path = join12(dir, name);
8937
+ if (await access3(path).then(() => true, () => false))
8603
8938
  return [path];
8604
8939
  }
8605
8940
  const parent = dirname7(dir);
@@ -8675,7 +9010,7 @@ function expandHomePattern(value) {
8675
9010
  const record3 = value;
8676
9011
  const output = {};
8677
9012
  for (const [key, item] of Object.entries(record3)) {
8678
- const expanded = key === "~" ? homedir6() : key.startsWith("~/") ? join11(homedir6(), key.slice(2)) : key;
9013
+ const expanded = key === "~" ? homedir7() : key.startsWith("~/") ? join12(homedir7(), key.slice(2)) : key;
8679
9014
  output[expanded] = expandHomePattern(item);
8680
9015
  }
8681
9016
  return output;
@@ -8751,7 +9086,7 @@ async function agentPolicyFiles(dir, kind) {
8751
9086
  throw error;
8752
9087
  }
8753
9088
  for (const entry of entries) {
8754
- const file = join11(current, entry.name);
9089
+ const file = join12(current, entry.name);
8755
9090
  if (entry.isDirectory())
8756
9091
  await visit(file, root);
8757
9092
  else if (entry.isFile() && entry.name.endsWith(".md"))
@@ -8759,7 +9094,7 @@ async function agentPolicyFiles(dir, kind) {
8759
9094
  }
8760
9095
  };
8761
9096
  for (const rootName of [kind, `${kind}s`])
8762
- await visit(join11(dir, rootName), join11(dir, rootName));
9097
+ await visit(join12(dir, rootName), join12(dir, rootName));
8763
9098
  return result.sort((a, b) => a.file.localeCompare(b.file));
8764
9099
  }
8765
9100
  async function readAgentPolicyFile(file, kind, root) {
@@ -8815,9 +9150,9 @@ async function preservedOpenCodePolicy(cwd) {
8815
9150
  result.mode = { ...result.mode ?? {}, [policy.name]: { permission: merged } };
8816
9151
  }
8817
9152
  };
8818
- const originalConfig = join11(process.env.XDG_CONFIG_HOME ?? join11(homedir6(), ".config"), "opencode");
9153
+ const originalConfig = join12(process.env.XDG_CONFIG_HOME ?? join12(homedir7(), ".config"), "opencode");
8819
9154
  for (const name of ["config.json", "opencode.json", "opencode.jsonc"])
8820
- await apply(join11(originalConfig, name));
9155
+ await apply(join12(originalConfig, name));
8821
9156
  await applyMarkdown(originalConfig, "agent");
8822
9157
  await applyMarkdown(originalConfig, "mode");
8823
9158
  if (process.env.OPENCODE_CONFIG)
@@ -8833,22 +9168,22 @@ async function preservedOpenCodePolicy(cwd) {
8833
9168
  }
8834
9169
  for (const current of [...dirs].reverse())
8835
9170
  for (const name of ["opencode.jsonc", "opencode.json"])
8836
- await apply(join11(current, name));
9171
+ await apply(join12(current, name));
8837
9172
  for (const current of dirs) {
8838
- const configDir = join11(current, ".opencode");
9173
+ const configDir = join12(current, ".opencode");
8839
9174
  for (const name of ["opencode.json", "opencode.jsonc"])
8840
- await apply(join11(configDir, name));
9175
+ await apply(join12(configDir, name));
8841
9176
  await applyMarkdown(configDir, "agent");
8842
9177
  await applyMarkdown(configDir, "mode");
8843
9178
  }
8844
- const homeConfig = join11(homedir6(), ".opencode");
9179
+ const homeConfig = join12(homedir7(), ".opencode");
8845
9180
  for (const name of ["opencode.json", "opencode.jsonc"])
8846
- await apply(join11(homeConfig, name));
9181
+ await apply(join12(homeConfig, name));
8847
9182
  await applyMarkdown(homeConfig, "agent");
8848
9183
  await applyMarkdown(homeConfig, "mode");
8849
9184
  if (process.env.OPENCODE_CONFIG_DIR) {
8850
9185
  for (const name of ["opencode.json", "opencode.jsonc"])
8851
- await apply(join11(process.env.OPENCODE_CONFIG_DIR, name));
9186
+ await apply(join12(process.env.OPENCODE_CONFIG_DIR, name));
8852
9187
  await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "agent");
8853
9188
  await applyMarkdown(process.env.OPENCODE_CONFIG_DIR, "mode");
8854
9189
  }
@@ -8868,7 +9203,8 @@ async function preservedOpenCodePolicy(cwd) {
8868
9203
  result.permission = mergePolicyValue(toolsPermission(result.tools, "OpenCode tools policy"), result.permission);
8869
9204
  return result;
8870
9205
  }
8871
- function codexModel(model3, priority) {
9206
+ function codexModel(model3, priority, baseUrl = "https://provider.invalid", selectedReasoning) {
9207
+ const reasoning = codexReasoning(model3, baseUrl, selectedReasoning);
8872
9208
  return {
8873
9209
  slug: model3.id,
8874
9210
  display_name: model3.name,
@@ -8877,8 +9213,8 @@ function codexModel(model3, priority) {
8877
9213
  visibility: "list",
8878
9214
  supported_in_api: true,
8879
9215
  priority,
8880
- supported_reasoning_levels: [],
8881
- default_reasoning_level: null,
9216
+ supported_reasoning_levels: reasoning.levels.map((effort) => ({ effort, description: effort === "none" ? "Disable reasoning" : `${effort} reasoning effort` })),
9217
+ default_reasoning_level: reasoning.defaultEffort,
8882
9218
  support_verbosity: false,
8883
9219
  supports_reasoning_summary_parameter: false,
8884
9220
  default_verbosity: null,
@@ -9013,20 +9349,20 @@ var PRIME_DAEMON_STARTUP_TIMEOUT_MS = 30000;
9013
9349
  var PRIME_DAEMON_SHUTDOWN_TIMEOUT_MS = 5000;
9014
9350
  function primeSocketPaths(runtimeDir) {
9015
9351
  const basename3 = `p-${randomUUID4().replaceAll("-", "").slice(0, 8)}.sock`;
9016
- const daemonSocket = join11(runtimeDir, basename3);
9352
+ const daemonSocket = join12(runtimeDir, basename3);
9017
9353
  const uid = typeof process.getuid === "function" ? String(process.getuid()) : "user";
9018
- const workerDir = join11(runtimeDir, `prime-agent-${uid}`);
9354
+ const workerDir = join12(runtimeDir, `prime-agent-${uid}`);
9019
9355
  const workerKey = createHash8("sha256").update(daemonSocket).digest("hex").slice(0, 12);
9020
- const workerSocket = join11(workerDir, `worker-${workerKey}-${"x".repeat(12)}.sock`);
9356
+ const workerSocket = join12(workerDir, `worker-${workerKey}-${"x".repeat(12)}.sock`);
9021
9357
  const overlong = [daemonSocket, workerSocket].find((path) => Buffer.byteLength(path, "utf8") > PRIME_UNIX_SOCKET_LIMIT);
9022
- return { daemonSocket, runtimeDir, workerDir, workerPrefix: join11(workerDir, `worker-${workerKey}-`), overlong };
9358
+ return { daemonSocket, runtimeDir, workerDir, workerPrefix: join12(workerDir, `worker-${workerKey}-`), overlong };
9023
9359
  }
9024
9360
  async function primeSocketInfo() {
9025
9361
  const requested = tmpdir();
9026
9362
  const direct = primeSocketPaths(requested);
9027
9363
  if (!direct.overlong)
9028
9364
  return direct;
9029
- const fallback = join11(switcherHome(), "r");
9365
+ const fallback = join12(switcherHome(), "r");
9030
9366
  await privateDirectory(switcherHome());
9031
9367
  await privateDirectory(fallback);
9032
9368
  const scoped = primeSocketPaths(fallback);
@@ -9123,7 +9459,7 @@ async function primeStartSupervisor(input, executable, socketPath, env, onSpawn)
9123
9459
  }
9124
9460
  }
9125
9461
  async function primeOwnedShutdown(socketPath, workerPrefix) {
9126
- const exists = () => access2(socketPath).then(() => true, () => false);
9462
+ const exists = () => access3(socketPath).then(() => true, () => false);
9127
9463
  const workerEntries = () => readdir4(workerPrefix.slice(0, workerPrefix.lastIndexOf("/"))).then((entries) => entries.filter((entry) => entry.startsWith(workerPrefix.slice(workerPrefix.lastIndexOf("/") + 1))), () => []);
9128
9464
  if (!await exists())
9129
9465
  throw new Error(`Prime Agent owned daemon socket disappeared before cleanup (${socketPath}).`);
@@ -9203,11 +9539,11 @@ async function primeWaitExit(supervisor, timeout) {
9203
9539
  return await Promise.race([supervisor.exited.then(() => true), new Promise((resolve9) => setTimeout(() => resolve9(false), timeout))]);
9204
9540
  }
9205
9541
  async function primeRemainingSockets(socketPath, workerPrefix) {
9206
- const daemon = await access2(socketPath).then(() => true, () => false);
9542
+ const daemon = await access3(socketPath).then(() => true, () => false);
9207
9543
  const workerDir = workerPrefix.slice(0, workerPrefix.lastIndexOf("/"));
9208
9544
  const prefix = workerPrefix.slice(workerPrefix.lastIndexOf("/") + 1);
9209
9545
  const workers = await readdir4(workerDir).then((entries) => entries.filter((entry) => entry.startsWith(prefix)), () => []);
9210
- return [...daemon ? [socketPath] : [], ...workers.map((entry) => join11(workerDir, entry))];
9546
+ return [...daemon ? [socketPath] : [], ...workers.map((entry) => join12(workerDir, entry))];
9211
9547
  }
9212
9548
  function primeModel(input, api) {
9213
9549
  return input.models.map((model3) => ({
@@ -9225,7 +9561,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
9225
9561
  if (!compatible(input.harness, input.protocol))
9226
9562
  throw new Error("Harness and provider protocol are incompatible.");
9227
9563
  validateHarnessVersion(input.harness, input.version);
9228
- if (!isAbsolute10(input.stateDir) || !isAbsolute10(input.cwd))
9564
+ if (!isAbsolute11(input.stateDir) || !isAbsolute11(input.cwd))
9229
9565
  throw new Error("Launch state and working directories must be absolute.");
9230
9566
  if (!input.models.length || !input.models.some((m) => m.id === input.model))
9231
9567
  throw new Error("Selected model is missing from the launch catalog.");
@@ -9263,7 +9599,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
9263
9599
  }
9264
9600
  if (input.harness === "codex") {
9265
9601
  const rolePolicy2 = await prepareCodexModelPolicy({ cwd: input.cwd, stateDir: input.stateDir, model: input.model, policy: input.modelPolicy ? { version: 1, ...input.modelPolicy } : undefined, switcherProvider: "switcher", switcherBaseUrl: input.baseUrl });
9266
- const file2 = await jsonFile(input.stateDir, "codex-models.json", { models: input.models.map(codexModel) });
9602
+ const file2 = await jsonFile(input.stateDir, "codex-models.json", { models: input.models.map((model3, index) => codexModel(model3, index, providerBaseUrl, model3.id === input.model ? input.reasoning : undefined)) });
9267
9603
  configPaths.push(file2);
9268
9604
  configPaths.push(...Object.values(rolePolicy2.agentConfigPaths));
9269
9605
  env[KEY4] = input.credential ?? "switcher-local-no-auth";
@@ -9282,7 +9618,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
9282
9618
  overrides.push("-c", `agents.${name}.config_file=${quote(path)}`);
9283
9619
  }
9284
9620
  overrides.push("-c", `memories.extract_model=${quote(input.model)}`, "-c", `memories.consolidation_model=${quote(input.model)}`);
9285
- warnings.push("Codex catalog uses conservative generic tool metadata and a model-neutral coding prompt; provider-specific reasoning is not advertised.");
9621
+ if (input.reasoning)
9622
+ overrides.push("-c", `model_reasoning_effort=${quote(input.reasoning)}`);
9623
+ if (input.dangerouslyBypassApprovalsAndSandbox)
9624
+ overrides.push("-c", 'approval_policy="never"', "-c", 'sandbox_mode="danger-full-access"');
9625
+ warnings.push("Codex catalog uses conservative generic tool metadata and a model-neutral coding prompt; reasoning controls come from declared capabilities, documented provider support or an explicit --reasoning selection.");
9626
+ if (input.dangerouslyBypassApprovalsAndSandbox)
9627
+ warnings.push("Full access: approval prompts and command sandboxing are disabled for this launch.");
9286
9628
  return { executable, args: [...overrides, ...args], env, configPaths, warnings };
9287
9629
  }
9288
9630
  if (input.harness === "grok") {
@@ -9306,8 +9648,8 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
9306
9648
  throw new Error("Pi cannot safely select model IDs that differ only by letter case; update the provider catalog.");
9307
9649
  const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions", "gemini-generate-content": "gemini" }[input.protocol];
9308
9650
  const providerId = piProviderId(input, providerBaseUrl);
9309
- const agentDir = join11(input.stateDir, "pi-agent");
9310
- const sessionDir = input.sessionDir ?? join11(input.stateDir, "sessions");
9651
+ const agentDir = join12(input.stateDir, "pi-agent");
9652
+ const sessionDir = input.sessionDir ?? join12(input.stateDir, "sessions");
9311
9653
  const piBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
9312
9654
  await mkdir10(agentDir, { recursive: true, mode: 448 });
9313
9655
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
@@ -9332,9 +9674,9 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
9332
9674
  const selected = dshArguments(args);
9333
9675
  const providerId = piProviderId(input, providerBaseUrl);
9334
9676
  const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
9335
- const home = join11(input.stateDir, "dsh-home");
9336
- const sessionDir = input.sessionDir ?? join11(input.stateDir, "dsh-state");
9337
- if (!isAbsolute10(sessionDir))
9677
+ const home = join12(input.stateDir, "dsh-home");
9678
+ const sessionDir = input.sessionDir ?? join12(input.stateDir, "dsh-state");
9679
+ if (!isAbsolute11(sessionDir))
9338
9680
  throw new Error("DSH session directory must be absolute.");
9339
9681
  await mkdir10(home, { recursive: true, mode: 448 });
9340
9682
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
@@ -9355,7 +9697,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
9355
9697
  }))
9356
9698
  } } } },
9357
9699
  { id: "agent-default-model", config: route2 },
9358
- { id: "session-persistence-jsonl", config: { root: join11(sessionDir, "sessions") } },
9700
+ { id: "session-persistence-jsonl", config: { root: join12(sessionDir, "sessions") } },
9359
9701
  { id: "attachment-local", config: { dshHome: sessionDir } },
9360
9702
  ...selected.profile === "acp" ? [{ id: "acp", config: route2 }] : []
9361
9703
  ];
@@ -9381,14 +9723,14 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
9381
9723
  throw new Error("Prime Agent cannot safely select model IDs that differ only by letter case; update the provider catalog.");
9382
9724
  const api = { "anthropic-messages": "anthropic-messages", "openai-responses": "openai-responses", "openai-chat": "openai-completions" }[input.protocol];
9383
9725
  const providerId = primeProviderId(input, providerBaseUrl);
9384
- const sessionDir = input.sessionDir ?? join11(input.stateDir, "sessions");
9385
- const agentDir = join11(input.stateDir, "prime-agent");
9726
+ const sessionDir = input.sessionDir ?? join12(input.stateDir, "sessions");
9727
+ const agentDir = join12(input.stateDir, "prime-agent");
9386
9728
  const socketInfo = await primeSocketInfo();
9387
9729
  const { daemonSocket, runtimeDir, workerPrefix } = socketInfo;
9388
9730
  const primeBaseUrl = input.protocol === "anthropic-messages" ? input.baseUrl.replace(/\/v1$/i, "") : input.baseUrl;
9389
9731
  await mkdir10(agentDir, { recursive: true, mode: 448 });
9390
9732
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
9391
- const file2 = join11(agentDir, "models.json");
9733
+ const file2 = join12(agentDir, "models.json");
9392
9734
  await writeFile10(file2, JSON.stringify({ providers: { [providerId]: {
9393
9735
  name: "Switcher",
9394
9736
  baseUrl: primeBaseUrl,
@@ -9480,13 +9822,13 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
9480
9822
  const file2 = await jsonFile(input.stateDir, "opencode-legacy.json", config2);
9481
9823
  configPaths.push(file2);
9482
9824
  env.OPENCODE_CONFIG = file2;
9483
- const sessionDir = input.sessionDir ?? join11(input.stateDir, "sessions");
9825
+ const sessionDir = input.sessionDir ?? join12(input.stateDir, "sessions");
9484
9826
  await mkdir10(sessionDir, { recursive: true, mode: 448 });
9485
- env.XDG_DATA_HOME = join11(sessionDir, "data");
9486
- env.XDG_CONFIG_HOME = join11(input.stateDir, "config");
9487
- env.XDG_CACHE_HOME = join11(input.stateDir, "cache");
9488
- env.XDG_STATE_HOME = join11(input.stateDir, "state");
9489
- env.HOME = join11(input.stateDir, "home");
9827
+ env.XDG_DATA_HOME = join12(sessionDir, "data");
9828
+ env.XDG_CONFIG_HOME = join12(input.stateDir, "config");
9829
+ env.XDG_CACHE_HOME = join12(input.stateDir, "cache");
9830
+ env.XDG_STATE_HOME = join12(input.stateDir, "state");
9831
+ env.HOME = join12(input.stateDir, "home");
9490
9832
  env.OPENCODE_DISABLE_PROJECT_CONFIG = "true";
9491
9833
  env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config2);
9492
9834
  env[KEY4] = input.credential ?? "switcher-local-no-auth";
@@ -9510,7 +9852,7 @@ async function prepareNativeLaunch(input, providerBaseUrl = input.providerBaseUr
9510
9852
  const rolePolicy = compileOpenCodeModelPolicy({ providerId: providerID, mainModel: input.model, roles: input.compiledPolicy?.roles, preservedAgents: Object.entries(isolated.config.agents ?? {}).map(([name, agent]) => ({ ...agent, name })) });
9511
9853
  const modelRef = openCodeInvocationModel(args, rolePolicy, isolated.config.default_agent);
9512
9854
  const config = { ...isolated.config, ...rolePolicy.config, providers: { [providerID]: { name: "Switcher", env: [KEY4], package: `@opencode-ai/ai/providers/${packageName}`, settings: settings2, models } } };
9513
- const file = join11(input.stateDir, "opencode.json");
9855
+ const file = join12(input.stateDir, "opencode.json");
9514
9856
  await writeFile10(file, openCode2ConfigText(config, providerID, KEY4), { mode: 384, flag: "wx" });
9515
9857
  configPaths.push(file, isolated.instructionFile);
9516
9858
  Object.assign(env, isolated.env);
@@ -9595,7 +9937,7 @@ async function prepareHarnessLaunch(input) {
9595
9937
  validateHarnessVersion(input.harness, input.version);
9596
9938
  if (!compatible(input.harness, input.protocol))
9597
9939
  throw new Error("Harness and provider protocol are incompatible.");
9598
- if (!isAbsolute10(input.stateDir) || !isAbsolute10(input.cwd))
9940
+ if (!isAbsolute11(input.stateDir) || !isAbsolute11(input.cwd))
9599
9941
  throw new Error("Launch state and working directories must be absolute.");
9600
9942
  const compiledPolicy = compileModelPolicy(input.model, input.models, input.modelPolicy);
9601
9943
  input = { ...input, models: input.models.filter((model3) => !modelExpired(model3)) };
@@ -9626,9 +9968,9 @@ async function prepareHarnessLaunch(input) {
9626
9968
  }
9627
9969
 
9628
9970
  // src/ori-model-policy.ts
9629
- import { isAbsolute as isAbsolute11 } from "path";
9971
+ import { isAbsolute as isAbsolute12 } from "path";
9630
9972
  function prepareOriModelPolicy(target, prepared) {
9631
- if (!isAbsolute11(prepared.executable) || /[\0\r\n]/.test(prepared.executable))
9973
+ if (!isAbsolute12(prepared.executable) || /[\0\r\n]/.test(prepared.executable))
9632
9974
  throw new Error("Ori requires an absolute verified native executable.");
9633
9975
  const entries = Object.entries(prepared.env);
9634
9976
  if (entries.some(([key]) => !/^[A-Z_][A-Z0-9_]*$/.test(key)))
@@ -9652,13 +9994,13 @@ exec "$SWITCHER_ORI_NATIVE_EXECUTABLE" ${prepared.args.map(quote2).join(" ")}
9652
9994
  }
9653
9995
 
9654
9996
  // src/launcher.ts
9655
- import { mkdir as mkdir11, mkdtemp, rm as rm3, writeFile as writeFile11 } from "fs/promises";
9656
- import { join as join12, resolve as resolve9 } from "path";
9997
+ import { mkdir as mkdir11, mkdtemp, rm as rm6, writeFile as writeFile14 } from "fs/promises";
9998
+ import { join as join15, resolve as resolve9 } from "path";
9657
9999
 
9658
10000
  // src/harness-process.ts
9659
10001
  import { spawn, spawnSync } from "child_process";
9660
10002
  import { EventEmitter } from "events";
9661
- import { existsSync, openSync, closeSync, writeSync, readSync, constants as constants4 } from "fs";
10003
+ import { existsSync, openSync, closeSync, writeSync, readSync, constants as constants5 } from "fs";
9662
10004
 
9663
10005
  // src/terminal-descriptors.ts
9664
10006
  async function terminalDescriptorDuplicator() {
@@ -9681,7 +10023,7 @@ async function terminalDescriptorDuplicator() {
9681
10023
  // src/harness-process.ts
9682
10024
  async function runHarnessProcess(options) {
9683
10025
  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);
10026
+ const grouped = process.platform !== "win32", interactive = !options.silent && grouped && tty.some(Boolean);
9685
10027
  const redirects = interactive ? tty.flatMap((value, index) => value ? [] : [index]) : [];
9686
10028
  const duplicator = redirects.length ? await terminalDescriptorDuplicator() : undefined;
9687
10029
  return new Promise((resolveResult, reject2) => {
@@ -9708,7 +10050,7 @@ async function runHarnessProcess(options) {
9708
10050
  let resize;
9709
10051
  const child = (() => {
9710
10052
  if (!interactive)
9711
- return spawn(options.executable, options.args, { cwd: options.cwd, env: options.env, stdio: "inherit", shell: false, detached: grouped });
10053
+ return spawn(options.executable, options.args, { cwd: options.cwd, env: options.env, stdio: options.silent ? "ignore" : "inherit", shell: false, detached: grouped });
9712
10054
  const duplicates = [];
9713
10055
  let native;
9714
10056
  try {
@@ -9914,7 +10256,7 @@ async function runHarnessProcess(options) {
9914
10256
  process.stdin.on("data", relay);
9915
10257
  process.stdin.resume();
9916
10258
  } else {
9917
- controllingInput = openSync("/dev/tty", constants4.O_RDONLY | constants4.O_NONBLOCK);
10259
+ controllingInput = openSync("/dev/tty", constants5.O_RDONLY | constants5.O_NONBLOCK);
9918
10260
  stty(["raw", "-echo"]);
9919
10261
  const buffer = Buffer.alloc(4096);
9920
10262
  inputTimer = setInterval(() => {
@@ -9945,9 +10287,9 @@ async function runHarnessProcess(options) {
9945
10287
  }
9946
10288
 
9947
10289
  // src/ori-backend.ts
9948
- import { execFile as execFile2 } from "child_process";
9949
- import { promisify as promisify2 } from "util";
9950
- var exec = promisify2(execFile2);
10290
+ import { execFile as execFile3 } from "child_process";
10291
+ import { promisify as promisify3 } from "util";
10292
+ var exec = promisify3(execFile3);
9951
10293
  var oriProviderCatalog = Object.freeze([{
9952
10294
  id: "openrouter",
9953
10295
  displayName: "OpenRouter",
@@ -10179,12 +10521,289 @@ function oriLaunchWarnings(target) {
10179
10521
  return target === "grok" ? ["Ori supplies Grok's account-entitled OpenRouter catalog; it is not the Switcher-filtered catalog snapshot."] : [];
10180
10522
  }
10181
10523
 
10524
+ // src/chatgpt-launch.ts
10525
+ import { createHash as createHash9 } from "crypto";
10526
+ import { writeFile as writeFile12, rm as rm4 } from "fs/promises";
10527
+ import { join as join13 } from "path";
10528
+
10529
+ // src/desktop-state.ts
10530
+ import { Database as Database3 } from "bun:sqlite";
10531
+ import { readFile as readFile5, writeFile as writeFile11, rm as rm3, lstat as lstat4, rename as rename2, chmod as chmod2 } from "fs/promises";
10532
+ async function safeDesktopRead(path) {
10533
+ try {
10534
+ const info = await lstat4(path);
10535
+ if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
10536
+ throw new Fault(422, "desktop_state_permissions", "Desktop settings must be regular files owned by this user.");
10537
+ return await readFile5(path, "utf8");
10538
+ } catch (error) {
10539
+ if (error.code === "ENOENT")
10540
+ return;
10541
+ throw error;
10542
+ }
10543
+ }
10544
+ async function writeDesktopPrivate(path, text) {
10545
+ const temporary = path + "." + crypto.randomUUID() + ".tmp";
10546
+ try {
10547
+ await writeFile11(temporary, text, { mode: 384, flag: "wx" });
10548
+ await rename2(temporary, path);
10549
+ } finally {
10550
+ await rm3(temporary, { force: true });
10551
+ }
10552
+ }
10553
+ async function desktopLease(path) {
10554
+ try {
10555
+ const info = await lstat4(path);
10556
+ if (!info.isFile() || info.isSymbolicLink() || info.uid !== process.getuid?.())
10557
+ throw new Fault(422, "desktop_state_permissions", "Desktop lease must be a regular file owned by this user.");
10558
+ } catch (error) {
10559
+ if (error.code !== "ENOENT")
10560
+ throw error;
10561
+ }
10562
+ const lease = new Database3(path);
10563
+ try {
10564
+ await chmod2(path, 384);
10565
+ lease.exec("PRAGMA busy_timeout=0; CREATE TABLE IF NOT EXISTS lease (id INTEGER PRIMARY KEY); BEGIN EXCLUSIVE;");
10566
+ } catch {
10567
+ lease.close();
10568
+ throw new Fault(409, "desktop_busy", "This desktop provider profile is already running. Quit that instance before launching it again.");
10569
+ }
10570
+ let closed = false;
10571
+ return () => {
10572
+ if (!closed) {
10573
+ closed = true;
10574
+ lease.close();
10575
+ }
10576
+ };
10577
+ }
10578
+
10579
+ // src/chatgpt-launch.ts
10580
+ var object5 = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
10581
+ function merge2(base, overlay) {
10582
+ const result = { ...base };
10583
+ for (const [key, value] of Object.entries(overlay))
10584
+ result[key] = object5(value) && object5(result[key]) ? merge2(result[key], value) : value;
10585
+ return result;
10586
+ }
10587
+ var digest = (value) => createHash9("sha256").update(value).digest("hex");
10588
+ var quote2 = (value) => `'${value.replaceAll("'", `'"'"'`)}'`;
10589
+ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
10590
+ await privateDirectory(sessionDir);
10591
+ const home = join13(sessionDir, "codex"), userData = join13(sessionDir, "electron");
10592
+ await privateDirectory(home);
10593
+ await privateDirectory(userData);
10594
+ const release = await desktopLease(join13(sessionDir, "launch.sqlite"));
10595
+ let released = false, authText;
10596
+ const authPath = join13(home, "auth.json"), receiptPath = join13(home, ".switcher-auth.sha256");
10597
+ const cleanup = async () => {
10598
+ if (released)
10599
+ return;
10600
+ released = true;
10601
+ try {
10602
+ if (authText !== undefined && await safeDesktopRead(authPath) === authText) {
10603
+ await rm4(authPath, { force: true });
10604
+ await rm4(receiptPath, { force: true });
10605
+ }
10606
+ } finally {
10607
+ release();
10608
+ }
10609
+ };
10610
+ try {
10611
+ const settings2 = [];
10612
+ for (let i = 0;i < native.args.length; i += 2) {
10613
+ if (native.args[i] !== "-c" || typeof native.args[i + 1] !== "string")
10614
+ throw new Fault(400, "desktop_arguments", "Desktop launches accept provider/model settings, not native CLI commands.");
10615
+ settings2.push(native.args[i + 1]);
10616
+ }
10617
+ settings2.push('cli_auth_credentials_store="file"', 'forced_login_method="api"');
10618
+ if (!settings2.some((setting) => setting.startsWith("approval_policy=")))
10619
+ settings2.push('approval_policy="on-request"');
10620
+ if (!settings2.some((setting) => setting.startsWith("sandbox_mode=")))
10621
+ settings2.push('sandbox_mode="workspace-write"');
10622
+ const configPath = join13(home, "config.toml");
10623
+ const previousAuth = await safeDesktopRead(authPath), previousReceipt = await safeDesktopRead(receiptPath);
10624
+ if (previousAuth !== undefined && previousReceipt !== digest(previousAuth))
10625
+ throw new Fault(409, "desktop_auth_changed", "This isolated desktop profile contains authentication that Switcher did not create. Sign out of that provider profile before launching it again; Switcher will not overwrite it.");
10626
+ let existing = {};
10627
+ try {
10628
+ existing = Bun.TOML.parse(await safeDesktopRead(configPath) ?? "");
10629
+ } catch (error) {
10630
+ if (error.code !== "ENOENT")
10631
+ throw new Fault(422, "desktop_config_invalid", "The desktop profile config cannot be read safely.");
10632
+ }
10633
+ const config = merge2(existing, Bun.TOML.parse(settings2.join(`
10634
+ `)));
10635
+ await writeDesktopPrivate(configPath, renderCodexAgentToml(config));
10636
+ const key = native.env.SWITCHER_HARNESS_API_KEY;
10637
+ if (!key)
10638
+ throw new Fault(500, "desktop_auth_missing", "Desktop preparation did not receive a scoped gateway credential.");
10639
+ authText = JSON.stringify({ OPENAI_API_KEY: key }) + `
10640
+ `;
10641
+ await writeDesktopPrivate(receiptPath, digest(authText));
10642
+ await writeDesktopPrivate(authPath, authText);
10643
+ const wrapper = join13(stateDir, "chatgpt-codex");
10644
+ const overrides = settings2.flatMap((setting) => ["-c", setting]);
10645
+ await writeFile12(wrapper, `#!/bin/sh
10646
+ set -eu
10647
+ unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
10648
+ export CODEX_HOME=${quote2(home)}
10649
+ exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
10650
+ `, { mode: 448, flag: "wx" });
10651
+ return {
10652
+ ...native,
10653
+ executable: app.executable,
10654
+ args: [`--user-data-dir=${userData}`],
10655
+ env: { ...native.env, CODEX_HOME: home, CODEX_ELECTRON_USER_DATA_PATH: userData, CODEX_CLI_PATH: wrapper, CODEX_APP_SERVER_FORCE_CLI: "1", CODEX_APP_SERVER_USE_LOCAL_DAEMON: "0" },
10656
+ configPaths: [...native.configPaths, configPath, wrapper],
10657
+ warnings: [...native.warnings, `ChatGPT provider profile: ${sessionDir}. Local Codex conversations use this provider; ChatGPT cloud Chat/Work and account-only features are not redirected. Keep Switcher running until you quit this app instance.`],
10658
+ cleanup: async () => {
10659
+ try {
10660
+ await native.cleanup?.();
10661
+ } finally {
10662
+ await cleanup();
10663
+ }
10664
+ }
10665
+ };
10666
+ } catch (error) {
10667
+ await cleanup();
10668
+ throw error;
10669
+ }
10670
+ }
10671
+
10672
+ // src/claude-desktop-launch.ts
10673
+ import { createHash as createHash10 } from "crypto";
10674
+ import { execFile as execFile4 } from "child_process";
10675
+ import { access as access4, rm as rm5, writeFile as writeFile13 } from "fs/promises";
10676
+ import { homedir as homedir8, userInfo as userInfo2 } from "os";
10677
+ import { join as join14 } from "path";
10678
+ import { promisify as promisify4 } from "util";
10679
+ var execute3 = promisify4(execFile4);
10680
+ var hash2 = (text) => createHash10("sha256").update(text).digest("hex");
10681
+ var claudeDesktopDataDirectory = () => join14(homedir8(), "Library/Application Support/Claude-3p");
10682
+ async function assertAvailable(userData) {
10683
+ for (const path of [join14("/Library/Managed Preferences", userInfo2().username, "com.anthropic.claudefordesktop.plist"), "/Library/Managed Preferences/com.anthropic.claudefordesktop.plist"])
10684
+ if (await access4(path).then(() => true, () => false))
10685
+ throw new Fault(409, "desktop_managed", "Claude has managed preferences. Configure its gateway through the administrator's policy; Switcher will not override it.");
10686
+ let openFiles;
10687
+ try {
10688
+ openFiles = (await execute3("/usr/sbin/lsof", ["-n", "-P", "-Fpn", "-a", "-u", String(process.getuid?.()), "-c", "Claude"], { encoding: "utf8", maxBuffer: 8 * 1024 * 1024, timeout: 8000 })).stdout;
10689
+ } catch (error) {
10690
+ if (error.code === 1)
10691
+ return;
10692
+ throw new Fault(409, "desktop_process_check", "Could not check whether Claude's third-party profile is already running.");
10693
+ }
10694
+ if (openFiles.split(`
10695
+ `).some((line) => line.startsWith("n" + userData + "/")))
10696
+ throw new Fault(409, "desktop_busy", "Claude's third-party instance is already running. Quit that instance before changing its provider; the normal Claude instance can stay open.");
10697
+ }
10698
+ function metadata(text) {
10699
+ const value = text === undefined ? { entries: [] } : JSON.parse(text);
10700
+ if (!value || typeof value !== "object" || Array.isArray(value) || !Array.isArray(value.entries) || value.entries.some((item) => !item || typeof item !== "object" || Array.isArray(item)))
10701
+ throw new Fault(422, "desktop_config_invalid", "Claude's configuration library metadata is invalid.");
10702
+ return value;
10703
+ }
10704
+ async function prepareClaudeDesktopLaunch(input, app, sessionDir, system) {
10705
+ if (input.harness !== "claude")
10706
+ throw new Fault(422, "desktop_harness", "Claude desktop requires the Claude Messages adapter.");
10707
+ validateHarnessProvider("claude", { protocol: input.protocol, authStyle: input.authStyle ?? "bearer" });
10708
+ if (input.args?.length || input.reasoning || input.dangerouslyBypassApprovalsAndSandbox)
10709
+ throw new Fault(400, "desktop_arguments", "Claude desktop uses its own effort and permission controls; native CLI arguments and Codex-only launch controls are not accepted.");
10710
+ const version = app.version.split(".").map(Number);
10711
+ if (version.length < 3 || version.some((n) => !Number.isSafeInteger(n)) || version[0] < 1 || version[0] === 1 && version[1] < 52386)
10712
+ throw new Fault(422, "desktop_version", "Claude desktop 1.52386.0 or newer is required for this verified gateway adapter.");
10713
+ const userData = system?.userData ?? claudeDesktopDataDirectory();
10714
+ const check2 = system?.assertAvailable ?? (() => assertAvailable(userData));
10715
+ await check2();
10716
+ await privateDirectory(userData);
10717
+ const library = join14(userData, "configLibrary");
10718
+ await privateDirectory(library);
10719
+ const release = await desktopLease(join14(library, ".switcher-lease.sqlite"));
10720
+ const metaPath = join14(library, "_meta.json"), receiptPath = join14(library, ".switcher-selection.json");
10721
+ let receipt, gateway, closed = false;
10722
+ const restore = async (record3) => {
10723
+ if (!/^[a-f0-9-]{36}$/.test(record3.id) || typeof record3.configHash !== "string" || typeof record3.appliedMeta !== "string" || record3.previousMeta !== null && typeof record3.previousMeta !== "string")
10724
+ throw new Fault(422, "desktop_config_invalid", "Claude's Switcher recovery record is invalid.");
10725
+ const configPath = join14(library, record3.id + ".json"), current = await safeDesktopRead(configPath);
10726
+ if (current !== undefined && hash2(current) !== record3.configHash)
10727
+ throw new Fault(409, "desktop_config_changed", "The Switcher Claude configuration was edited outside this launch. Switcher will preserve it; review the configuration library before relaunching.");
10728
+ const currentMeta = await safeDesktopRead(metaPath);
10729
+ if (currentMeta !== record3.appliedMeta && currentMeta !== (record3.previousMeta ?? undefined))
10730
+ throw new Fault(409, "desktop_config_changed", "Claude's selected configuration changed during this launch. Switcher will preserve the changed selection; review its configuration library before relaunching.");
10731
+ if (record3.previousMeta === null)
10732
+ await rm5(metaPath, { force: true });
10733
+ else
10734
+ await writeDesktopPrivate(metaPath, record3.previousMeta);
10735
+ await rm5(configPath, { force: true });
10736
+ await rm5(receiptPath, { force: true });
10737
+ };
10738
+ const cleanup = async () => {
10739
+ if (closed)
10740
+ return;
10741
+ closed = true;
10742
+ try {
10743
+ await gateway?.cleanup();
10744
+ if (receipt)
10745
+ await restore(receipt);
10746
+ } finally {
10747
+ release();
10748
+ }
10749
+ };
10750
+ try {
10751
+ const recovery = await safeDesktopRead(receiptPath);
10752
+ if (recovery)
10753
+ await restore(JSON.parse(recovery));
10754
+ const localConfig = await safeDesktopRead(join14(userData, "claude_desktop_config.json"));
10755
+ if (localConfig && JSON.parse(localConfig).deploymentMode === "1p")
10756
+ throw new Fault(409, "desktop_mode", "Claude's third-party profile is set to standard account mode. Select third-party mode in Claude before launching this gateway.");
10757
+ await privateDirectory(sessionDir);
10758
+ const roles2 = input.modelPolicy?.roles;
10759
+ const targets = { sonnet: input.model, opus: roles2?.planning ?? input.model, haiku: roles2?.fast ?? input.model };
10760
+ const aliases = Object.fromEntries(Object.entries(targets).map(([tier, model3]) => ["switcher/" + tier, model3]));
10761
+ for (const [alias, target] of Object.entries(aliases))
10762
+ if (input.modelPolicy?.aliases?.[alias] && input.modelPolicy.aliases[alias] !== target)
10763
+ throw new Fault(409, "desktop_alias_conflict", "The model policy conflicts with Claude desktop's reserved switcher/sonnet, switcher/opus or switcher/haiku routing aliases.");
10764
+ const compiledPolicy = compileModelPolicy(input.model, input.models, { ...input.modelPolicy, version: 1, aliases: { ...input.modelPolicy?.aliases, ...aliases } });
10765
+ const catalogPath = join14(input.stateDir, "claude-desktop-policy.json");
10766
+ await writeFile13(catalogPath, JSON.stringify({ policy: compiledPolicy, models: input.models }), { mode: 384, flag: "wx" });
10767
+ gateway = createInferenceGateway({ ...input, compiledPolicy, catalogPath });
10768
+ const id2 = crypto.randomUUID(), configPath = join14(library, id2 + ".json");
10769
+ const config = JSON.stringify({
10770
+ inferenceProvider: "gateway",
10771
+ inferenceGatewayBaseUrl: gateway.baseUrl.replace(/\/v1$/, ""),
10772
+ inferenceGatewayApiKey: gateway.token,
10773
+ inferenceGatewayAuthScheme: "bearer",
10774
+ modelDiscoveryEnabled: false,
10775
+ inferenceModels: Object.entries(targets).map(([tier, model3]) => ({ name: "switcher/" + tier, labelOverride: model3, anthropicFamilyTier: tier, isFamilyDefault: true }))
10776
+ });
10777
+ const previousMeta = await safeDesktopRead(metaPath);
10778
+ const meta = metadata(previousMeta);
10779
+ const appliedMeta = JSON.stringify({ ...meta, appliedId: id2, entries: [...meta.entries, { id: id2, name: `Switcher: ${input.providerId ?? "provider"} / ${input.model}` }] });
10780
+ receipt = { id: id2, configHash: hash2(config), previousMeta: previousMeta ?? null, appliedMeta };
10781
+ await writeDesktopPrivate(configPath, config);
10782
+ await writeDesktopPrivate(receiptPath, JSON.stringify(receipt));
10783
+ await writeDesktopPrivate(metaPath, appliedMeta);
10784
+ return {
10785
+ executable: app.executable,
10786
+ args: [],
10787
+ env: { CLAUDE_CONFIG_DIR: sessionDir },
10788
+ configPaths: [catalogPath, configPath],
10789
+ beforeLaunch: check2,
10790
+ cleanup,
10791
+ warnings: [`Claude desktop gateway: ${input.providerId ?? "provider"} / ${input.model}. Uses the shared Claude-3p profile, separate from the normal Claude account. Quit this instance before switching providers; keep Switcher running until then. The previous configuration selection is restored on exit. Managed settings and native permissions remain authoritative.`]
10792
+ };
10793
+ } catch (error) {
10794
+ try {
10795
+ await cleanup();
10796
+ } catch {}
10797
+ throw error;
10798
+ }
10799
+ }
10800
+
10182
10801
  // src/launcher.ts
10183
10802
  var LATE_RUN_FINALIZATION_TIMEOUT_MS = 5000;
10184
10803
  async function writeOriCodexCatalog(stateDir, models) {
10185
- const path = join12(stateDir, "ori-codex-models.json");
10186
- const nativeModels2 = models.filter(codingEligible).map(codexModel);
10187
- await writeFile11(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
10804
+ const path = join15(stateDir, "ori-codex-models.json");
10805
+ const nativeModels2 = models.filter(codingEligible).map((model3, index) => codexModel(model3, index));
10806
+ await writeFile14(path, JSON.stringify({ models: nativeModels2 }, null, 2) + `
10188
10807
  `, { mode: 384, flag: "wx" });
10189
10808
  return path;
10190
10809
  }
@@ -10273,9 +10892,9 @@ async function prepareOriForPlan(plan, options) {
10273
10892
  });
10274
10893
  try {
10275
10894
  const shim = prepareOriModelPolicy(request.target, native);
10276
- const dir = join12(options.stateDir, "ori-bin"), path = join12(dir, shim.name);
10895
+ const dir = join15(options.stateDir, "ori-bin"), path = join15(dir, shim.name);
10277
10896
  await mkdir11(dir, { mode: 448 });
10278
- await writeFile11(path, shim.script, { mode: 448, flag: "wx" });
10897
+ await writeFile14(path, shim.script, { mode: 448, flag: "wx" });
10279
10898
  return { contract, prepared: {
10280
10899
  ...ori,
10281
10900
  env: { ...ori.env, ...shim.env, PATH: `${dir}:${ori.env.PATH ?? process.env.PATH ?? ""}` },
@@ -10292,6 +10911,8 @@ async function prepareOriForPlan(plan, options) {
10292
10911
  async function launch(client, profileId, options = {}) {
10293
10912
  const launchDeadline = options.timeoutMs === undefined ? undefined : Date.now() + options.timeoutMs;
10294
10913
  const profile = await client.getProfile(profileId);
10914
+ if ((options.reasoning || options.dangerouslyBypassApprovalsAndSandbox) && (profile.harness !== "codex" || (options.backend ?? "direct") !== "direct"))
10915
+ throw new Error("Reasoning and full-access launch options require direct Codex or ChatGPT.");
10295
10916
  assertHarnessArguments(profile.harness, options.args ?? []);
10296
10917
  if (profile.harness === "gemini")
10297
10918
  validateHarnessProvider(profile.harness, await client.getProvider(profile.providerId));
@@ -10312,16 +10933,21 @@ async function launch(client, profileId, options = {}) {
10312
10933
  throw new Error("--executable is ambiguous with --backend ori; use --ori-executable PATH.");
10313
10934
  if (backend === "direct" && options.oriExecutable)
10314
10935
  throw new Error("--ori-executable requires --backend ori.");
10315
- const detection = backend === "direct" ? await detectHarness(plan.profile.harness, options.executable) : undefined;
10316
- if (backend === "direct" && !detection?.available)
10936
+ if (options.desktop && (plan.profile.harness !== "codex" || backend !== "direct"))
10937
+ throw new Error("ChatGPT requires the direct Codex provider adapter.");
10938
+ if (options.claudeDesktop && (options.desktop || plan.profile.harness !== "claude" || backend !== "direct" || options.executable || options.args?.length))
10939
+ throw new Error("Claude desktop requires its direct Messages gateway adapter without native CLI overrides.");
10940
+ const nativeExecutable = options.desktop?.codexExecutable ?? options.executable;
10941
+ const detection = backend === "direct" && !options.claudeDesktop ? await detectHarness(plan.profile.harness, nativeExecutable) : undefined;
10942
+ if (backend === "direct" && !options.claudeDesktop && !detection?.available)
10317
10943
  throw new Error(harnessInstallationMessage(plan.profile.harness, detection?.executable ?? plan.profile.harness, Boolean(options.executable)));
10318
10944
  if (backend === "direct" && plan.profile.harness === "gemini")
10319
10945
  validateHarnessVersion("gemini", detection?.version);
10320
10946
  if (backend === "direct" && plan.profile.harness === "aider")
10321
10947
  validateHarnessVersion(plan.profile.harness, detection?.version);
10322
- const root = resolve9(options.stateDir ?? join12(switcherHome(), "state"));
10948
+ const root = resolve9(options.stateDir ?? join15(switcherHome(), "state"));
10323
10949
  await privateDirectory(root);
10324
- const stateDir = await mkdtemp(join12(root, "launch-"));
10950
+ const stateDir = await mkdtemp(join15(root, "launch-"));
10325
10951
  let credential;
10326
10952
  if (backend === "direct") {
10327
10953
  try {
@@ -10329,7 +10955,7 @@ async function launch(client, profileId, options = {}) {
10329
10955
  if (plan.provider.credentialEnv && !credential)
10330
10956
  throw new Error("Provider credential environment reference is not available in this local launcher process.");
10331
10957
  } catch (error) {
10332
- await rm3(stateDir, { recursive: true, force: true });
10958
+ await rm6(stateDir, { recursive: true, force: true });
10333
10959
  throw error;
10334
10960
  }
10335
10961
  }
@@ -10365,25 +10991,45 @@ async function launch(client, profileId, options = {}) {
10365
10991
  return;
10366
10992
  });
10367
10993
  try {
10368
- const prepared = backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent })).prepared : await prepareHarnessLaunch({
10994
+ const input = {
10369
10995
  harness: plan.profile.harness,
10370
10996
  baseUrl: plan.provider.baseUrl,
10371
10997
  protocol: plan.provider.protocol,
10998
+ authStyle: plan.provider.authStyle,
10372
10999
  model: plan.profile.model,
10373
11000
  models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
10374
11001
  modelPolicy: plan.profile.modelPolicy,
10375
11002
  providerId: plan.provider.id,
10376
11003
  onRoutingEvent,
10377
11004
  credential,
11005
+ stateDir,
11006
+ cwd: resolve9(options.cwd ?? process.cwd())
11007
+ };
11008
+ let prepared = options.claudeDesktop ? await prepareClaudeDesktopLaunch(input, options.claudeDesktop, join15(root, "desktop-claude", profileId)) : backend === "ori" ? (await prepareOriForPlan(plan, { ...options, stateDir, onRoutingEvent })).prepared : await prepareHarnessLaunch({
11009
+ harness: plan.profile.harness,
11010
+ baseUrl: plan.provider.baseUrl,
11011
+ protocol: plan.provider.protocol,
11012
+ model: plan.profile.model,
11013
+ models: plan.catalog.models.filter((m) => modelExpired(m) || harnessEligible(m, plan.profile.harness)),
11014
+ modelPolicy: plan.profile.modelPolicy,
11015
+ providerId: plan.provider.id,
11016
+ onRoutingEvent,
11017
+ reasoning: options.reasoning,
11018
+ dangerouslyBypassApprovalsAndSandbox: options.dangerouslyBypassApprovalsAndSandbox,
11019
+ credential,
10378
11020
  authStyle: plan.provider.authStyle,
10379
- executable: options.executable ?? detection?.executable,
11021
+ executable: nativeExecutable ?? detection?.executable,
10380
11022
  args: options.args ?? [],
10381
11023
  stateDir,
10382
11024
  cwd: resolve9(options.cwd ?? process.cwd()),
10383
11025
  version: detection?.version,
10384
- ...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo"].includes(plan.profile.harness) ? { sessionDir: join12(root, "sessions", plan.profile.harness, profileId) } : {}
11026
+ ...["pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "opencode", "kilo"].includes(plan.profile.harness) ? { sessionDir: join15(root, "sessions", plan.profile.harness, profileId) } : {}
10385
11027
  });
10386
11028
  cleanup = prepared.cleanup;
11029
+ if (options.desktop) {
11030
+ prepared = await prepareChatGPTLaunch(prepared, options.desktop, stateDir, join15(root, "desktop", profileId));
11031
+ cleanup = prepared.cleanup;
11032
+ }
10387
11033
  for (const warning of [...plan.warnings, ...prepared.warnings])
10388
11034
  console.error(`switcher: ${warning}`);
10389
11035
  const interruptPreparation = (error, cancel = true) => {
@@ -10458,7 +11104,7 @@ async function launch(client, profileId, options = {}) {
10458
11104
  interruptPreparation(new CommandInterrupted(143, "Launch timed out before the native harness started."), false);
10459
11105
  throw preparationSignal;
10460
11106
  }
10461
- const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve9(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, timeoutMs: remainingRuntime });
11107
+ const { code, interrupted } = await runHarnessProcess({ executable: prepared.executable, args: prepared.args, cwd: resolve9(options.cwd ?? process.cwd()), env: { ...childEnvironment(), ...prepared.env }, silent: Boolean(options.desktop || options.claudeDesktop), timeoutMs: remainingRuntime });
10462
11108
  await cleanup?.();
10463
11109
  cleanup = undefined;
10464
11110
  await finishRunOnce(run, { status: interrupted ? "interrupted" : code === 0 ? "exited" : "failed", exitCode: code }, `switcher: Harness exited ${code}; final metadata could not be saved for run ${run.id}.`);
@@ -10489,13 +11135,13 @@ async function launch(client, profileId, options = {}) {
10489
11135
  try {
10490
11136
  await cleanup?.();
10491
11137
  } finally {
10492
- await rm3(stateDir, { recursive: true, force: true });
11138
+ await rm6(stateDir, { recursive: true, force: true });
10493
11139
  }
10494
11140
  }
10495
11141
  }
10496
11142
 
10497
11143
  // src/direct-launch.ts
10498
- import { createHash as createHash9 } from "crypto";
11144
+ import { createHash as createHash11 } from "crypto";
10499
11145
  import { createInterface } from "readline/promises";
10500
11146
  var absent = (error) => error instanceof SwitcherError && error.status === 404;
10501
11147
  async function resolveLaunchProvider(client, selector, options = {}) {
@@ -10575,8 +11221,8 @@ async function selectModel(models, query = "", harness) {
10575
11221
  async function ensureLaunchProfile(client, provider, harness, model3, modelPolicy) {
10576
11222
  const normalizedPolicy = modelPolicy === undefined ? undefined : parse2(modelPolicySchema, modelPolicy);
10577
11223
  const identity = normalizedPolicy === undefined ? [provider.id, harness, model3] : [provider.id, harness, model3, normalizedPolicy];
10578
- const hash2 = createHash9("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
10579
- const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash2}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
11224
+ const hash3 = createHash11("sha256").update(canonicalPolicyJSON(identity)).digest("hex").slice(0, 24);
11225
+ const desired = parse2(profileInputSchema, { id: `launch-${harness}-${hash3}`, name: `${harness}: ${model3}`.slice(0, 200), providerId: provider.id, harness, model: model3, ...normalizedPolicy ? { modelPolicy: normalizedPolicy } : {} });
10580
11226
  let existing;
10581
11227
  try {
10582
11228
  existing = await client.getProfile(desired.id);
@@ -10599,57 +11245,57 @@ async function ensureLaunchProfile(client, provider, harness, model3, modelPolic
10599
11245
  }
10600
11246
 
10601
11247
  // src/credentials.ts
10602
- import { z as z6 } from "zod";
10603
- import { constants as constants5 } from "fs";
10604
- import { open as open3, readdir as readdir5, unlink, link, lstat as lstat4, access as access3, stat as stat5, realpath as realpath6, readlink, rename as rename2 } from "fs/promises";
10605
- import { join as join13, isAbsolute as isAbsolute12, dirname as dirname8, parse as pathParts, resolve as resolvePath, sep as sep2 } from "path";
10606
- import { createHash as createHash10, randomUUID as randomUUID5 } from "crypto";
10607
- import { execFile as execFile3, spawn as spawn2 } from "child_process";
10608
- import { promisify as promisify3 } from "util";
11248
+ import { z as z7 } from "zod";
11249
+ import { constants as constants6 } from "fs";
11250
+ import { open as open3, readdir as readdir5, unlink, link, lstat as lstat5, access as access5, stat as stat6, realpath as realpath6, readlink, rename as rename3 } from "fs/promises";
11251
+ import { join as join16, isAbsolute as isAbsolute13, dirname as dirname8, parse as pathParts, resolve as resolvePath, sep as sep2 } from "path";
11252
+ import { createHash as createHash12, randomUUID as randomUUID5 } from "crypto";
11253
+ import { execFile as execFile5, spawn as spawn2 } from "child_process";
11254
+ import { promisify as promisify5 } from "util";
10609
11255
  import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys2, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
10610
- var execute2 = promisify3(execFile3);
10611
- var reference = z6.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
10612
- var item = z6.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
10613
- var vaultKey = z6.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");
10614
- var keychain = z6.object({ kind: z6.literal("keychain"), service: item, account: item }).strict();
10615
- var operator = z6.discriminatedUnion("kind", [
10616
- z6.object({ kind: z6.literal("contracts") }).strict(),
10617
- z6.object({ kind: z6.literal("env") }).strict(),
10618
- z6.object({ kind: z6.literal("keychain"), account: item.refine((value) => value.trim().length > 0 && value === value.trim(), "Vault account must be nonblank without surrounding whitespace") }).strict()
11256
+ var execute4 = promisify5(execFile5);
11257
+ var reference = z7.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
11258
+ var item = z7.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
11259
+ var vaultKey = z7.string().max(500).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*(?:\/[A-Za-z0-9][A-Za-z0-9_.-]*)*$/, "Use a vault key path, not an option or secret value");
11260
+ var keychain = z7.object({ kind: z7.literal("keychain"), service: item, account: item }).strict();
11261
+ var operator = z7.discriminatedUnion("kind", [
11262
+ z7.object({ kind: z7.literal("contracts") }).strict(),
11263
+ z7.object({ kind: z7.literal("env") }).strict(),
11264
+ z7.object({ kind: z7.literal("keychain"), account: item.refine((value) => value.trim().length > 0 && value === value.trim(), "Vault account must be nonblank without surrounding whitespace") }).strict()
10619
11265
  ]);
10620
- var origin = z6.string().transform((value) => new URL(endpoint(value)).origin);
10621
- var credentialBindingSchema = z6.object({
10622
- schema: z6.literal(1),
11266
+ var origin = z7.string().transform((value) => new URL(endpoint(value)).origin);
11267
+ var credentialBindingSchema = z7.object({
11268
+ schema: z7.literal(1),
10623
11269
  credentialEnv: reference,
10624
- origins: z6.array(origin).min(1).max(30),
10625
- source: z6.discriminatedUnion("kind", [keychain, z6.object({
10626
- kind: z6.literal("vault"),
11270
+ origins: z7.array(origin).min(1).max(30),
11271
+ source: z7.discriminatedUnion("kind", [keychain, z7.object({
11272
+ kind: z7.literal("vault"),
10627
11273
  key: vaultKey,
10628
- url: z6.string().max(2000).transform(endpoint).optional(),
10629
- executable: z6.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute12, "Secrets executable must be an absolute path"),
11274
+ url: z7.string().max(2000).transform(endpoint).optional(),
11275
+ executable: z7.string().max(4096).regex(/^[^\x00-\x1f\x7f]+$/).refine(isAbsolute13, "Secrets executable must be an absolute path"),
10630
11276
  operator
10631
11277
  }).strict()])
10632
11278
  }).strict().superRefine((binding, ctx) => {
10633
11279
  if (binding.source.kind === "vault" && binding.source.operator.kind !== "contracts" && !binding.source.url)
10634
11280
  ctx.addIssue({ code: "custom", path: ["source", "url"], message: "An explicit env or Keychain operator binding requires a vault URL." });
10635
11281
  });
10636
- var fingerprint = (binding) => createHash10("sha256").update(JSON.stringify(binding)).digest("hex");
11282
+ var fingerprint = (binding) => createHash12("sha256").update(JSON.stringify(binding)).digest("hex");
10637
11283
 
10638
11284
  class CredentialBindings {
10639
11285
  env;
10640
11286
  directory;
10641
11287
  constructor(env = process.env) {
10642
11288
  this.env = env;
10643
- this.directory = join13(switcherHome(env), "config", "credential-bindings");
11289
+ this.directory = join16(switcherHome(env), "config", "credential-bindings");
10644
11290
  }
10645
11291
  path(name) {
10646
- return join13(this.directory, parse2(reference, name) + ".json");
11292
+ return join16(this.directory, parse2(reference, name) + ".json");
10647
11293
  }
10648
11294
  async readableDirectory() {
10649
- for (const path of [switcherHome(this.env), join13(switcherHome(this.env), "config"), this.directory]) {
11295
+ for (const path of [switcherHome(this.env), join16(switcherHome(this.env), "config"), this.directory]) {
10650
11296
  let info;
10651
11297
  try {
10652
- info = await lstat4(path);
11298
+ info = await lstat5(path);
10653
11299
  } catch (error) {
10654
11300
  if (error.code === "ENOENT")
10655
11301
  return false;
@@ -10666,7 +11312,7 @@ class CredentialBindings {
10666
11312
  return;
10667
11313
  let file;
10668
11314
  try {
10669
- file = await open3(path, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
11315
+ file = await open3(path, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
10670
11316
  } catch (error) {
10671
11317
  if (error.code === "ENOENT")
10672
11318
  return;
@@ -10715,9 +11361,9 @@ class CredentialBindings {
10715
11361
  if (binding.source.kind === "vault")
10716
11362
  await validateVaultExecutable(binding.source.executable);
10717
11363
  await privateDirectory(switcherHome(this.env));
10718
- await privateDirectory(join13(switcherHome(this.env), "config"));
11364
+ await privateDirectory(join16(switcherHome(this.env), "config"));
10719
11365
  await privateDirectory(this.directory);
10720
- const temporary = join13(this.directory, `.binding-${randomUUID5()}`);
11366
+ const temporary = join16(this.directory, `.binding-${randomUUID5()}`);
10721
11367
  const file = await open3(temporary, "wx", 384);
10722
11368
  try {
10723
11369
  await file.writeFile(JSON.stringify(binding, null, 2) + `
@@ -10757,8 +11403,8 @@ async function inspectVaultExecutable(path, permitWritableFile = false) {
10757
11403
  let info, resolved;
10758
11404
  try {
10759
11405
  resolved = await realpath6(path);
10760
- await access3(resolved, constants5.X_OK);
10761
- info = await stat5(resolved);
11406
+ await access5(resolved, constants6.X_OK);
11407
+ info = await stat6(resolved);
10762
11408
  if (!info.isFile())
10763
11409
  throw new Error;
10764
11410
  } catch {
@@ -10773,13 +11419,13 @@ async function inspectVaultExecutable(path, permitWritableFile = false) {
10773
11419
  for (const part of candidate.slice(prefix.length).split(sep2)) {
10774
11420
  if (!part)
10775
11421
  continue;
10776
- prefix = join13(prefix, part);
11422
+ prefix = join16(prefix, part);
10777
11423
  if (seen.has(prefix))
10778
11424
  continue;
10779
11425
  seen.add(prefix);
10780
11426
  if (seen.size > 256)
10781
11427
  throw new Fault(422, "vault_exec_permissions", "The secrets executable path has too many symlink components.");
10782
- const entry = await lstat4(prefix);
11428
+ const entry = await lstat5(prefix);
10783
11429
  const permittedFile = permitWritableFile && prefix === resolved && entry.isFile();
10784
11430
  if (entry.uid !== 0 && entry.uid !== process.getuid?.() || !entry.isSymbolicLink() && !permittedFile && entry.mode & 18)
10785
11431
  throw new Fault(422, "vault_exec_permissions", "The secrets executable and its ancestor directories must not be replaceable by other users. Choose an installation owned by this user or root without group/public write permissions.");
@@ -10804,12 +11450,12 @@ async function validateVaultExecutable(path) {
10804
11450
  async function repairVaultExecutablePermissions(path, expectedSha256) {
10805
11451
  if (!/^[a-f0-9]{64}$/.test(expectedSha256))
10806
11452
  throw new Fault(400, "invalid_request", "--sha256 requires the SHA256 of the executable member from a verified package artifact.");
10807
- if (!isAbsolute12(path) || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path))
11453
+ if (!isAbsolute13(path) || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path))
10808
11454
  throw new Fault(400, "invalid_request", "Secrets executable must be an absolute path without control characters.");
10809
11455
  if (process.platform === "win32")
10810
11456
  throw new Fault(422, "vault_exec_repair_unsafe", "Executable permission repair requires POSIX file permissions.");
10811
11457
  const resolved = await inspectVaultExecutable(path, true);
10812
- const file = await open3(resolved, constants5.O_RDONLY | constants5.O_NOFOLLOW | constants5.O_NONBLOCK);
11458
+ const file = await open3(resolved, constants6.O_RDONLY | constants6.O_NOFOLLOW | constants6.O_NONBLOCK);
10813
11459
  const unsafe = () => new Fault(422, "vault_exec_repair_unsafe", "Executable ownership, type, links or contents changed; no trusted repair can be confirmed.");
10814
11460
  let temporary;
10815
11461
  try {
@@ -10818,8 +11464,8 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
10818
11464
  if (!before.isFile() || before.uid !== process.getuid?.() || before.size > limit || before.mode & 3584)
10819
11465
  throw unsafe();
10820
11466
  const sameFile = (info) => info.dev === before.dev && info.ino === before.ino && info.size === before.size && info.uid === before.uid && info.nlink === before.nlink && info.mode === before.mode && info.mtimeMs === before.mtimeMs && info.ctimeMs === before.ctimeMs;
10821
- const hash2 = async (target) => {
10822
- const digest = createHash10("sha256");
11467
+ const hash3 = async (target) => {
11468
+ const digest2 = createHash12("sha256");
10823
11469
  const buffer = Buffer.alloc(1024 * 1024);
10824
11470
  let position = 0;
10825
11471
  while (true) {
@@ -10830,41 +11476,41 @@ async function repairVaultExecutablePermissions(path, expectedSha256) {
10830
11476
  if (position > limit)
10831
11477
  throw unsafe();
10832
11478
  const bytes = buffer.subarray(0, bytesRead);
10833
- digest.update(bytes);
11479
+ digest2.update(bytes);
10834
11480
  if (target)
10835
11481
  await target.writeFile(bytes);
10836
11482
  }
10837
11483
  if (position !== before.size || !sameFile(await file.stat()))
10838
11484
  throw unsafe();
10839
- if (digest.digest("hex") !== expectedSha256)
11485
+ if (digest2.digest("hex") !== expectedSha256)
10840
11486
  throw new Fault(422, "vault_exec_digest_mismatch", "Installed executable differs from the trusted artifact digest. Reinstall the verified package; no credential was accessed.");
10841
11487
  };
10842
- await hash2();
11488
+ await hash3();
10843
11489
  const mode = before.mode & 511 & ~18;
10844
11490
  const changed = mode !== (before.mode & 511);
10845
- if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat4(resolved)))
11491
+ if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat5(resolved)))
10846
11492
  throw unsafe();
10847
11493
  if (!changed) {
10848
11494
  await validateVaultExecutable(path);
10849
11495
  return { changed, mode: mode.toString(8).padStart(4, "0"), sha256: expectedSha256 };
10850
11496
  }
10851
- temporary = join13(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
11497
+ temporary = join16(dirname8(resolved), `.switcher-repair-${randomUUID5()}`);
10852
11498
  const replacement = await open3(temporary, "wx", 384);
10853
11499
  try {
10854
- await hash2(replacement);
11500
+ await hash3(replacement);
10855
11501
  await replacement.chmod(mode);
10856
11502
  await replacement.sync();
10857
11503
  const ready = await replacement.stat();
10858
11504
  if (!ready.isFile() || ready.nlink !== 1 || ready.uid !== before.uid || ready.size !== before.size)
10859
11505
  throw unsafe();
10860
- if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat4(resolved)))
11506
+ if (await inspectVaultExecutable(path, true) !== resolved || !sameFile(await lstat5(resolved)))
10861
11507
  throw unsafe();
10862
- await rename2(temporary, resolved);
11508
+ await rename3(temporary, resolved);
10863
11509
  temporary = undefined;
10864
- const installed = await lstat4(resolved);
11510
+ const installed = await lstat5(resolved);
10865
11511
  if (installed.dev !== ready.dev || installed.ino !== ready.ino || await validateVaultExecutable(path) !== resolved)
10866
11512
  throw unsafe();
10867
- const directory = await open3(dirname8(resolved), constants5.O_RDONLY | constants5.O_DIRECTORY | constants5.O_NOFOLLOW);
11513
+ const directory = await open3(dirname8(resolved), constants6.O_RDONLY | constants6.O_DIRECTORY | constants6.O_NOFOLLOW);
10868
11514
  try {
10869
11515
  await directory.sync();
10870
11516
  } finally {
@@ -10901,7 +11547,7 @@ async function readKeychain(source) {
10901
11547
  if (process.platform !== "darwin")
10902
11548
  throw new Fault(422, "keychain_unavailable", "This binding requires macOS Keychain. Use a supported vault binding or runtime environment on this station.");
10903
11549
  try {
10904
- const { stdout } = await execute2("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 });
11550
+ const { stdout } = await execute4("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 });
10905
11551
  const value = stdout.replace(/\r?\n$/, "");
10906
11552
  if (!value || /[\x00-\x1f\x7f]/.test(value))
10907
11553
  throw new Error("Invalid credential");
@@ -10944,7 +11590,7 @@ class CredentialResolver {
10944
11590
  return { credentialEnv: name, source: "vault", available: true, length: Number(match[1]), sha256: match[2], providerAuthentication: "not tested" };
10945
11591
  }
10946
11592
  const value = await this.keychainRead(binding.source);
10947
- return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash10("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
11593
+ return { credentialEnv: name, source: "keychain", available: true, length: Buffer.byteLength(value), sha256: createHash12("sha256").update(value).digest("hex"), providerAuthentication: "not tested" };
10948
11594
  }
10949
11595
  }
10950
11596
  var DELIVERY_URL = "SWITCHER_CREDENTIAL_DELIVERY_URL";
@@ -11123,8 +11769,13 @@ async function deliverVaultCredential() {
11123
11769
  }
11124
11770
 
11125
11771
  // src/cli.ts
11126
- var HELP = `switcher \u2014 launch a coding harness with a provider and its model catalog
11772
+ var HELP = `switcher \u2014 launch coding harnesses and desktop apps with your provider and model
11127
11773
 
11774
+ switcher launch chatgpt --provider PROVIDER --model MODEL [--reasoning EFFORT]
11775
+ [--dangerously-bypass-approvals-and-sandbox] [--app-path /absolute/ChatGPT.app]
11776
+ [--dry-run] [--cwd DIR] [--timeout SECONDS]
11777
+ switcher launch claude-desktop --provider PROVIDER --model MODEL
11778
+ [--app-path /absolute/Claude.app] [--dry-run]
11128
11779
  switcher providers presets [ID]
11129
11780
  switcher providers list [--search TEXT] [--limit N] [--offset N]
11130
11781
  switcher providers add ID --url URL --protocol PROTOCOL [--credential-env NAME]
@@ -11156,6 +11807,13 @@ var HELP = `switcher \u2014 launch a coding harness with a provider and its mode
11156
11807
  switcher doctor
11157
11808
 
11158
11809
  HARNESS: claude, codex, grok, opencode, opencode2, pi, omp, dsh, cline, hermes, prime-agent, gemini, aider, kilo
11810
+ chatgpt launches the installed macOS desktop app in an isolated provider profile.
11811
+ Its local Codex conversations use the selected Responses-compatible provider.
11812
+ claude-desktop launches Claude in its separate Claude-3p gateway profile with a
11813
+ Messages-compatible provider. Quit that instance before switching providers.
11814
+ Keep Switcher running while using the app; quit that app instance to end the launch.
11815
+ --reasoning: none, minimal, low, medium, high, xhigh, max, ultra (provider support required).
11816
+ --dangerously-bypass-approvals-and-sandbox: full access without prompts or command sandboxing.
11159
11817
  PROTOCOL: anthropic-messages, openai-responses, openai-chat, gemini-generate-content
11160
11818
  Without remote API configuration, the CLI owns a local authenticated API and
11161
11819
  stores data in ~/.hasna/switcher (override HASNA_SWITCHER_HOME).
@@ -11219,6 +11877,9 @@ async function main(args = process.argv.slice(2)) {
11219
11877
  json: { type: "boolean" },
11220
11878
  url: { type: "string" },
11221
11879
  sha256: { type: "string" },
11880
+ "app-path": { type: "string" },
11881
+ reasoning: { type: "string" },
11882
+ "dangerously-bypass-approvals-and-sandbox": { type: "boolean" },
11222
11883
  protocol: { type: "string" },
11223
11884
  preset: { type: "string" },
11224
11885
  name: { type: "string" },
@@ -11264,6 +11925,18 @@ async function main(args = process.argv.slice(2)) {
11264
11925
  }
11265
11926
  const [command, action2, id2] = positionals;
11266
11927
  const output = (value) => console.log(JSON.stringify(value, null, 2));
11928
+ const reasoning = values2.reasoning === undefined ? undefined : parse2(reasoningEffortSchema, values2.reasoning);
11929
+ const dangerouslyBypassApprovalsAndSandbox = values2["dangerously-bypass-approvals-and-sandbox"];
11930
+ if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && (command !== "launch" || values2.provider && !["chatgpt", "codex"].includes(action2) || values2.backend && values2.backend !== "direct"))
11931
+ throw new Fault(400, "conflicting_options", "--reasoning and --dangerously-bypass-approvals-and-sandbox require a direct Codex or ChatGPT launch.");
11932
+ const chatgpt = command === "launch" && action2 === "chatgpt" && values2.provider !== undefined;
11933
+ const claudeDesktop = command === "launch" && action2 === "claude-desktop" && values2.provider !== undefined;
11934
+ if (values2["app-path"] !== undefined && !chatgpt && !claudeDesktop)
11935
+ throw new Fault(400, "conflicting_options", "--app-path belongs to launch chatgpt or claude-desktop --provider PROVIDER --model MODEL.");
11936
+ if ((chatgpt || claudeDesktop) && (nativeArgs.length || positionals.length !== 2 || values2.executable !== undefined || values2.backend !== undefined || values2["ori-executable"] !== undefined))
11937
+ throw new Fault(400, "conflicting_options", "Desktop apps use their own runtime; native CLI arguments, --executable and --backend are not accepted.");
11938
+ const desktop = chatgpt ? await detectChatGPTApp(values2["app-path"]) : undefined;
11939
+ const claudeApp = claudeDesktop ? await detectClaudeDesktopApp(values2["app-path"]) : undefined;
11267
11940
  if (!["doctor", "launch", "models", "runs", "providers", "profiles", "credentials"].includes(command))
11268
11941
  throw new Error("Unknown command. Run switcher --help.");
11269
11942
  const providerFlags = ["url", "protocol", "preset", "credential-env", "auth-style", "catalog-url", "catalog-format", "catalog-auth-style", "catalog-credential-env", "catalog-account-id", "models-path"];
@@ -11380,7 +12053,7 @@ async function main(args = process.argv.slice(2)) {
11380
12053
  if (command === "launch" && provided(["name", "harness", "file"]))
11381
12054
  throw new Fault(400, "conflicting_options", "Launch takes its harness from the positional argument or saved profile; edit named records through providers/profiles.");
11382
12055
  if (command === "launch" && values2.provider) {
11383
- const harness = parse2(harnessSchema, action2);
12056
+ const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action2);
11384
12057
  assertHarnessArguments(harness, nativeArgs);
11385
12058
  await validateHarnessConfiguration(harness, values2.cwd ?? process.cwd(), nativeArgs);
11386
12059
  }
@@ -11426,7 +12099,7 @@ async function main(args = process.argv.slice(2)) {
11426
12099
  throw new Error("--timeout must be positive seconds.");
11427
12100
  let profileId = action2;
11428
12101
  if (values2.provider) {
11429
- const harness = parse2(harnessSchema, action2);
12102
+ const harness = parse2(harnessSchema, chatgpt ? "codex" : claudeDesktop ? "claude" : action2);
11430
12103
  const modelPolicy = await readModelPolicy(values2["model-policy-file"], values2["role-model"]);
11431
12104
  const provider = await resolveLaunchProvider(client, values2.provider, { ...presetOptions(), harness });
11432
12105
  validateHarnessProvider(harness, provider);
@@ -11439,6 +12112,8 @@ async function main(args = process.argv.slice(2)) {
11439
12112
  throw new Fault(422, "model_expired", "Selected model has passed its configured expiry date. Select an unexpired model.");
11440
12113
  if (!harnessEligible(selected, harness))
11441
12114
  throw new Fault(422, "model_ineligible", "Selected model explicitly lacks text output or tool support.");
12115
+ if (harness === "codex")
12116
+ codexReasoning(selected, provider.baseUrl, reasoning);
11442
12117
  profileId = (await ensureLaunchProfile(client, provider, harness, model3, modelPolicy)).id;
11443
12118
  } else {
11444
12119
  if (values2.model || values2.protocol || values2.url || values2["credential-env"] || values2["model-policy-file"] || values2["role-model"])
@@ -11452,15 +12127,22 @@ async function main(args = process.argv.slice(2)) {
11452
12127
  }
11453
12128
  if (values2["dry-run"]) {
11454
12129
  const plan = await client.launchPlan(profileId);
12130
+ if ((reasoning || dangerouslyBypassApprovalsAndSandbox) && plan.profile.harness !== "codex")
12131
+ throw new Fault(400, "conflicting_options", "Reasoning and full-access options require Codex or ChatGPT.");
12132
+ if (reasoning) {
12133
+ const model3 = plan.catalog.models.find((model4) => model4.id === plan.profile.model);
12134
+ if (model3)
12135
+ codexReasoning(model3, plan.provider.baseUrl, reasoning);
12136
+ }
11455
12137
  assertHarnessArguments(plan.profile.harness, nativeArgs);
11456
12138
  if (backend === "ori") {
11457
12139
  const { contract, warnings } = await validateOriForPlan(plan, { oriExecutable: values2["ori-executable"], args: nativeArgs, cwd: values2.cwd });
11458
12140
  output({ ...plan, backend: { kind: "ori", executable: contract.executable, version: contract.version, target: plan.profile.harness, provider: "openrouter", model: plan.profile.model, warnings: [...plan.warnings, ...warnings] } });
11459
12141
  } else
11460
- output(plan);
12142
+ output({ ...plan, ...desktop ? { desktop: { ...desktop, mode: "isolated-provider", sessionProfile: profileId } } : {}, ...claudeApp ? { desktop: { ...claudeApp, mode: "claude-3p-gateway", sessionProfile: profileId } } : {}, ...reasoning ? { reasoning } : {}, ...dangerouslyBypassApprovalsAndSandbox ? { permissions: { approvalPolicy: "never", sandboxMode: "danger-full-access" } } : {} });
11461
12143
  return;
11462
12144
  }
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) });
12145
+ process.exitCode = await launch(client, profileId, { desktop, claudeDesktop: claudeApp, reasoning, dangerouslyBypassApprovalsAndSandbox, backend, oriExecutable: values2["ori-executable"], cwd: values2.cwd, executable: values2.executable, stateDir: values2["state-dir"], args: nativeArgs, timeoutMs, refresh: false, resolveCredential: (provider) => credentials.resolve(provider) });
11464
12146
  return;
11465
12147
  }
11466
12148
  if (editingModel) {