pi-bro 0.35.1 → 0.36.1

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/src/backend.ts CHANGED
@@ -2,6 +2,7 @@ import { type ChildProcess, type SpawnOptions, spawn } from "node:child_process"
2
2
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
3
3
  import { tmpdir } from "node:os";
4
4
  import { join } from "node:path";
5
+ import { codexSubscriptionRouteProblem, isSubscriptionStatus, resolveCliChildAuth, type CliAuthBackend } from "./cli-auth.ts";
5
6
  import {
6
7
  createAgentSession,
7
8
  DefaultResourceLoader,
@@ -595,6 +596,176 @@ async function executeAdvisorStdin(
595
596
  return { status: "success", text };
596
597
  }
597
598
 
599
+ /**
600
+ * Ask the official Codex app-server for the effective provider configuration.
601
+ * This is the same Codex CLI, CODEX_HOME, and working directory used for exec.
602
+ * A login status alone cannot detect custom provider env_key API billing.
603
+ *
604
+ * Inspection never makes a model request. Missing, unreadable or unsupported
605
+ * app-server/config/read support fails closed when subscription is explicit.
606
+ */
607
+ // Codex 0.165.0 app-server starts an online catalog refresh on boot,
608
+ // even if the only client method is config/read. Supply a disposable static
609
+ // catalog for this *inspection process only* so the refresh worker cannot
610
+ // contact a configured provider. The override does NOT select a provider,
611
+ // change account credentials, or go into the real codex exec arguments.
612
+ // The provider is still read from Codex's effective config for the same cwd.
613
+ const CODEX_INSPECTION_CATALOG = {
614
+ models: [{
615
+ slug: "bro-config-inspection-only",
616
+ display_name: "Bro configuration inspection only",
617
+ description: "Local offline catalog; never used for inference",
618
+ base_instructions: "Local configuration inspection only; never used for inference.",
619
+ default_reasoning_level: "medium",
620
+ supported_reasoning_levels: [{ effort: "medium", description: "medium" }],
621
+ shell_type: "shell_command",
622
+ visibility: "none",
623
+ supported_in_api: true,
624
+ priority: 0,
625
+ support_verbosity: false,
626
+ default_verbosity: null,
627
+ apply_patch_tool_type: null,
628
+ truncation_policy: { mode: "bytes", limit: 10_000 },
629
+ experimental_supported_tools: [],
630
+ }],
631
+ };
632
+
633
+ async function inspectCodexSubscriptionRoute(
634
+ env: NodeJS.ProcessEnv, cwd: string | undefined, signal: AbortSignal,
635
+ deadlineMs: number, killEscalationMs: number,
636
+ ): Promise<BackendOutcome | undefined> {
637
+ if (signal.aborted) return { status: "cancelled", message: "Canceled." };
638
+ const probeDir = await mkdtemp(join(tmpdir(), "pi-bro-codex-inspect-"));
639
+ try {
640
+ const catalogPath = join(probeDir, "catalog.json");
641
+ await writeFile(catalogPath, JSON.stringify(CODEX_INSPECTION_CATALOG), { mode: 0o600 });
642
+ if (signal.aborted) return { status: "cancelled", message: "Canceled." };
643
+ const { child, attempt, diagnostics } = startCliAttempt(
644
+ "codex", ["-c", `model_catalog_json=${JSON.stringify(catalogPath)}`, "app-server"],
645
+ { env, cwd, stdio: ["pipe", "pipe", "pipe"] },
646
+ signal, Math.min(deadlineMs, 15_000), killEscalationMs,
647
+ );
648
+ let buffer = "";
649
+ let decided = false;
650
+ let finish: (problem: string | undefined) => void = () => {};
651
+ const decision = new Promise<string | undefined>(resolve => { finish = resolve; });
652
+ const settle = (problem: string | undefined) => {
653
+ if (decided) return;
654
+ decided = true;
655
+ finish(problem);
656
+ };
657
+ const send = (value: object) => {
658
+ if (decided || attempt.causeOf()) return;
659
+ try { child.stdin?.write(JSON.stringify(value) + "\n"); }
660
+ catch { settle("Codex app-server could not accept the configuration query"); }
661
+ };
662
+ // An app-server may close its input pipe while its buffered response is
663
+ // still readable. The close race below decides whether the query succeeded.
664
+ child.stdin?.on("error", () => {});
665
+ child.stdout?.setEncoding("utf8");
666
+ child.stdout?.on("data", (chunk: string) => {
667
+ if (decided || attempt.causeOf()) return;
668
+ buffer += chunk;
669
+ if (buffer.length > 2_000_000) { settle("Codex returned an oversized configuration response"); return; }
670
+ for (;;) {
671
+ const index = buffer.indexOf("\n");
672
+ if (index < 0) break;
673
+ const line = buffer.slice(0, index);
674
+ buffer = buffer.slice(index + 1);
675
+ if (!line.trim()) continue;
676
+ let message: Record<string, unknown>;
677
+ try {
678
+ message = JSON.parse(line) as Record<string, unknown>;
679
+ } catch {
680
+ settle("Codex app-server returned invalid JSON");
681
+ return;
682
+ }
683
+ if (message.id === 0) {
684
+ if (!message.result || message.error) {
685
+ settle("Codex app-server initialization failed");
686
+ return;
687
+ }
688
+ send({ method: "initialized", params: {} });
689
+ send({ method: "config/read", id: 1, params: { includeLayers: false, ...(cwd ? { cwd } : {}) } });
690
+ } else if (message.id === 1) {
691
+ if (message.error || !message.result || typeof message.result !== "object") {
692
+ settle("Codex app-server did not support config/read for this account/profile");
693
+ return;
694
+ }
695
+ const config = (message.result as { config?: unknown }).config;
696
+ settle(codexSubscriptionRouteProblem(config));
697
+ return;
698
+ }
699
+ }
700
+ });
701
+ send({ method: "initialize", id: 0,
702
+ params: { clientInfo: { name: "pi_bro", title: "Pi Bro", version: "0.36.1" } } });
703
+ const result = await Promise.race([
704
+ decision.then(problem => ({ kind: "decision" as const, problem })),
705
+ attempt.closed.then(() => ({ kind: "closed" as const })),
706
+ ]);
707
+ // The probe is not a long-running provider connection.
708
+ if (!attempt.causeOf()) attempt.stop("protocol");
709
+ await attempt.closed;
710
+ attempt.dispose();
711
+ if (signal.aborted || attempt.causeOf() === "cancelled")
712
+ return { status: "cancelled", message: "Canceled." };
713
+ if (attempt.causeOf() === "timeout")
714
+ return { status: "timeout", message: "Codex effective subscription configuration check timed out." };
715
+ const problem = result.kind === "decision"
716
+ ? result.problem
717
+ : diagnostics.processError
718
+ ? "Codex app-server could not start"
719
+ : "Codex app-server closed without returning the effective configuration" +
720
+ (diagnostics.stderr.trim() ? ": " + diagnostics.stderr.trim().slice(0, 700) : "");
721
+ return problem
722
+ ? { status: "failure", message: "Codex subscription selection is not safe: " + problem +
723
+ ". No Codex model execution was started; the inspection uses a temporary local catalog to suppress ordinary model discovery. Use a subscription-compatible CODEX_HOME profile or select inherited/API authentication explicitly." }
724
+ : undefined;
725
+ } finally {
726
+ await rm(probeDir, { recursive: true, force: true });
727
+ }
728
+ }
729
+
730
+ // Only a deliberate subscription choice gets an auth-method preflight.
731
+ // CLI status is not proof of account identity or a paid model call.
732
+ export async function verifyCliSubscription(
733
+ backend: CliAuthBackend,
734
+ env: NodeJS.ProcessEnv,
735
+ signal: AbortSignal,
736
+ killEscalationMs: number,
737
+ deadlineMs: number,
738
+ cwd?: string,
739
+ ): Promise<BackendOutcome | undefined> {
740
+ if (signal.aborted) return { status: "cancelled", message: "Canceled." };
741
+ const label = backend === "claude" ? "Claude Code" : "Codex";
742
+ const args = backend === "claude" ? ["auth", "status"] : ["login", "status"];
743
+ const { child, attempt, diagnostics } = startCliAttempt(backend, args,
744
+ { env, stdio: ["ignore", "pipe", "pipe"] },
745
+ signal, Math.min(deadlineMs, 15_000), killEscalationMs);
746
+ let stdout = "";
747
+ child.stdout?.on("data", (chunk: Buffer) => {
748
+ stdout = (stdout + chunk.toString()).slice(0, 32_768);
749
+ });
750
+ const { code, exitSignal } = await attempt.closed;
751
+ attempt.dispose();
752
+ if (attempt.causeOf() === "cancelled") return { status: "cancelled", message: "Canceled." };
753
+ if (attempt.causeOf() === "timeout") return { status: "timeout", message: label + " subscription login check timed out." };
754
+ if (diagnostics.processError)
755
+ return { status: "failure", message: processStartMessage(diagnostics.processError as NodeJS.ErrnoException, label) };
756
+ const status = backend === "codex" ? stdout + "\n" + diagnostics.stderr : stdout;
757
+ if (code !== 0 || exitSignal || !isSubscriptionStatus(backend, status)) {
758
+ const command = backend === "claude" ? "claude auth status" : "codex login status";
759
+ const profile = backend === "claude" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME";
760
+ return { status: "failure", message: label +
761
+ " did not confirm subscription login in the selected profile. Run `" + command +
762
+ "` with that " + profile + " and sign in to the intended subscription; Bro will not switch to API billing." };
763
+ }
764
+ return backend === "codex"
765
+ ? inspectCodexSubscriptionRoute(env, cwd, signal, deadlineMs, killEscalationMs)
766
+ : undefined;
767
+ }
768
+
598
769
  type ClaudeEvent = {
599
770
  type?: unknown;
600
771
  subtype?: unknown;
@@ -638,6 +809,14 @@ async function executeClaude(
638
809
  }
639
810
 
640
811
  try {
812
+ let auth: ReturnType<typeof resolveCliChildAuth>;
813
+ try { auth = resolveCliChildAuth("claude"); }
814
+ catch (error) { return { status: "failure", message: errorMessage(error) }; }
815
+ if (auth.subscription) {
816
+ const check = await verifyCliSubscription("claude", auth.env, signal, killEscalationMs, deadlineMs);
817
+ if (check) return check;
818
+ }
819
+ if (signal.aborted) return { status: "cancelled", message: "Canceled." };
641
820
  const { child, attempt, diagnostics } = startCliAttempt("claude",
642
821
  [
643
822
  "-p",
@@ -660,7 +839,7 @@ async function executeClaude(
660
839
  ],
661
840
  {
662
841
  cwd: runDirectory ?? request.cwd,
663
- stdio: ["pipe", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
842
+ stdio: ["pipe", "pipe", "pipe"], env: auth.env }, signal, deadlineMs, killEscalationMs);
664
843
 
665
844
  let partial = "";
666
845
  let final: string | undefined;
@@ -1013,10 +1192,19 @@ async function executeCodex(
1013
1192
  }
1014
1193
 
1015
1194
  try {
1195
+ let auth: ReturnType<typeof resolveCliChildAuth>;
1196
+ try { auth = resolveCliChildAuth("codex"); }
1197
+ catch (error) { return { status: "failure", message: errorMessage(error) }; }
1198
+ if (auth.subscription) {
1199
+ const check = await verifyCliSubscription("codex", auth.env, signal, killEscalationMs, deadlineMs, runDirectory ?? request.cwd);
1200
+ if (check) return check;
1201
+ }
1202
+ if (signal.aborted) return { status: "cancelled", message: "Canceled." };
1016
1203
  const permissionArgs = full ? ["--dangerously-bypass-approvals-and-sandbox"] : ["--sandbox", "read-only"];
1017
1204
  const resume = isBtw && request.continuation;
1018
1205
  const args = [
1019
1206
  "exec",
1207
+ ...(auth.subscription ? ["-c", 'forced_login_method="chatgpt"', "-c", 'model_provider="openai"'] : []),
1020
1208
  ...permissionArgs,
1021
1209
  ...(resume ? ["resume"] : []),
1022
1210
  "--json",
@@ -1030,7 +1218,7 @@ async function executeCodex(
1030
1218
 
1031
1219
  const { child, attempt, diagnostics } = startCliAttempt("codex", args, {
1032
1220
  cwd: runDirectory ?? request.cwd,
1033
- stdio: ["pipe", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
1221
+ stdio: ["pipe", "pipe", "pipe"], env: auth.env }, signal, deadlineMs, killEscalationMs);
1034
1222
 
1035
1223
  let partial = "";
1036
1224
  let threadId: string | undefined;
@@ -1431,63 +1619,67 @@ function piAssistantText(message: { content?: unknown }): string {
1431
1619
  .trim();
1432
1620
  }
1433
1621
 
1434
- /** Copies every host-registered provider and runtime key into a fresh runtime. */
1435
- async function bridgePiModelRuntime(host: PiHostContext | undefined, agentDir: string): Promise<ModelRuntime> {
1436
- const modelRuntime = await ModelRuntime.create({
1437
- authPath: join(agentDir, "auth.json"),
1438
- modelsPath: join(agentDir, "models.json"),
1439
- });
1440
- const registry = host?.modelRegistry;
1441
- if (registry) {
1442
- for (const id of registry.getRegisteredProviderIds()) {
1443
- const native = registry.getRegisteredNativeProvider(id);
1444
- if (native) modelRuntime.registerNativeProvider(native);
1445
- const config = registry.getRegisteredProviderConfig(id);
1446
- if (config) modelRuntime.registerProvider(id, config);
1447
- }
1448
- }
1449
- return modelRuntime;
1450
- }
1451
-
1452
- // Copying only the key for the selected provider is enough for a run, but not for listing what the
1453
- // host can authenticate: a catalog built without runtime keys offers the user fewer models than
1454
- // execution can actually use. Copy every runtime key the host holds.
1455
- //
1456
- // The provider list must come from the host's model catalog, not getRegisteredProviderIds(): that
1457
- // method lists only extension-registered providers, so a runtime key set on a built-in provider
1458
- // (for example Pi's own `--api-key`) would be missed and its models would vanish from `/bro config`.
1459
- async function copyAllRuntimeCredentials(host: PiHostContext | undefined, runtime: ModelRuntime): Promise<void> {
1622
+ /**
1623
+ * The Pi SDK asks for a ModelRuntime even when its physical model is explicit.
1624
+ * Bind every auth/model/stream read to the host's existing registry instead of
1625
+ * rebuilding a second provider from models.json. In particular, an on-disk edit
1626
+ * must never combine a host-old endpoint with a freshly read API key.
1627
+ *
1628
+ * The SDK runtime here only supplies agent/session mechanics; it does not own
1629
+ * credentials, source selection or refresh. No models.json is read by this child.
1630
+ */
1631
+ async function bridgePiModelRuntime(host: PiHostContext | undefined, _agentDir: string): Promise<ModelRuntime> {
1460
1632
  const registry = host?.modelRegistry;
1461
- if (!registry) return;
1462
- const providerIds = new Set(registry.getRegisteredProviderIds());
1463
- // getAll() may be absent on a partial host stub; the extension list above still applies.
1464
- for (const model of registry.getAll?.() ?? []) providerIds.add(model.provider);
1465
- for (const providerId of providerIds) {
1466
- if (registry.getProviderAuthStatus(providerId).source !== "runtime") continue;
1467
- const key = await registry.getApiKeyForProvider(providerId);
1468
- if (key) await runtime.setRuntimeApiKey(providerId, key);
1469
- }
1470
- }
1471
-
1472
- // The runtime a Pi request or catalog read runs against: the host's registrations plus its runtime
1473
- // credentials. Both the executor and `/bro doctor`/`/bro config` go through here so they can never
1474
- // disagree about which models exist.
1475
- export async function bridgePiRuntimeForCatalog(host: PiHostContext | undefined, agentDir: string): Promise<ModelRuntime> {
1476
- const runtime = await bridgePiModelRuntime(host, agentDir);
1477
- await copyAllRuntimeCredentials(host, runtime);
1633
+ if (!registry) throw new Error("The Pi host model registry is unavailable; reopen Bro from a live Pi session.");
1634
+ // The SDK requires a ModelRuntime, but it must not read an independent auth.json
1635
+ // or models.json. All real auth and model calls below delegate to the host.
1636
+ const credentials = {
1637
+ read: async () => undefined,
1638
+ list: async () => [],
1639
+ modify: async (): Promise<never> => { throw new Error("The Pi host owns credential writes."); },
1640
+ delete: async (): Promise<never> => { throw new Error("The Pi host owns credential deletion."); },
1641
+ };
1642
+ const runtime = await ModelRuntime.create({
1643
+ credentials,
1644
+ modelsPath: null,
1645
+ refreshOnCreate: false,
1646
+ });
1647
+ const models = (provider?: string) => registry.getAll().filter((m) => !provider || m.provider === provider);
1648
+ const available = (provider?: string) => registry.getAvailable().filter((m) => !provider || m.provider === provider);
1649
+ // Use the same registry for the SDK's preflight, model lookup and final stream.
1650
+ // Resolving auth from provider alone is intentional: ModelRegistry.getProviderAuth()
1651
+ // is the public host API, and its underlying runtime still applies model-specific
1652
+ // headers and request overrides inside streamSimple().
1653
+ Object.assign(runtime, {
1654
+ getModel: (provider: string, id: string) => registry.find(provider, id),
1655
+ getModels: models,
1656
+ getAllModels: models,
1657
+ getAvailableSnapshot: () => available(),
1658
+ getAvailable: async (provider?: string) => available(provider),
1659
+ getProvider: (provider: string) => registry.getProvider(provider),
1660
+ getProviderAuthStatus: (provider: string) => registry.getProviderAuthStatus(provider),
1661
+ getAuth: async (modelOrProvider: string | { provider: string }) =>
1662
+ registry.getProviderAuth(typeof modelOrProvider === "string" ? modelOrProvider : modelOrProvider.provider),
1663
+ hasConfiguredAuth: (provider: string) => models(provider).some((model) => registry.hasConfiguredAuth(model)),
1664
+ checkAuth: async (provider: string) =>
1665
+ (await registry.getProviderAuth(provider)) ? { type: "api_key", source: "host registry" } : undefined,
1666
+ isUsingOAuth: (provider: string) => models(provider).some((model) => registry.isUsingOAuth(model)),
1667
+ streamSimple: (
1668
+ model: Parameters<ModelRuntime["streamSimple"]>[0],
1669
+ context: Parameters<ModelRuntime["streamSimple"]>[1],
1670
+ options: Parameters<ModelRuntime["streamSimple"]>[2],
1671
+ ) => {
1672
+ // Neither another runtime nor child options may override the host's auth.
1673
+ const { apiKey: _key, env: _env, ...rest } = options ?? {};
1674
+ return registry.streamSimple(model, context, rest);
1675
+ },
1676
+ });
1478
1677
  return runtime;
1479
1678
  }
1480
1679
 
1481
- async function copyRuntimeCredentials(
1482
- host: PiHostContext | undefined,
1483
- runtime: ModelRuntime,
1484
- providerId: string,
1485
- ): Promise<void> {
1486
- const registry = host?.modelRegistry;
1487
- if (!registry) return;
1488
- if (registry.getProviderAuthStatus(providerId).source !== "runtime") return;
1489
- const key = await registry.getApiKeyForProvider(providerId);
1490
- if (key) await runtime.setRuntimeApiKey(providerId, key);
1680
+ /** The picker and the executor use this same host-backed model/auth view. */
1681
+ export async function bridgePiRuntimeForCatalog(host: PiHostContext | undefined, agentDir: string): Promise<ModelRuntime> {
1682
+ return bridgePiModelRuntime(host, agentDir);
1491
1683
  }
1492
1684
 
1493
1685
  async function executePi(
@@ -1557,16 +1749,15 @@ async function executePi(
1557
1749
  // or throwing host credential lookup becomes an ordinary outcome rather than a rejection.
1558
1750
  const modelRuntime = await Promise.race([bridgePiModelRuntime(host, agentDir), stopped.then(() => undefined)]);
1559
1751
  if (!modelRuntime) return latchedOutcome();
1560
- // Fall back to the host registry, which may know a model the rebuilt runtime does not.
1561
- const model = modelRuntime.getModel(parts.providerId, parts.modelId) ?? host?.modelRegistry?.find(parts.providerId, parts.modelId);
1752
+ // Use the effective host model for its exact identity, endpoint and metadata.
1753
+ // The SDK child uses the same host model, auth resolver and streaming transport.
1754
+ const model = host?.modelRegistry?.find(parts.providerId, parts.modelId);
1562
1755
  if (!model) {
1563
1756
  return { status: "failure", message: piErrorMessage(request.feature, `model \`${selection.model}\` is not in your Pi model catalog. Run \`/bro doctor\`.`) };
1564
1757
  }
1565
1758
  if ((model as { api?: string }).api === "pi-virtual") {
1566
1759
  return { status: "failure", message: piErrorMessage(request.feature, `\`${selection.model}\` is a virtual model; choose a physical model in \`/bro config\`.`) };
1567
1760
  }
1568
- await Promise.race([copyRuntimeCredentials(host, modelRuntime, parts.providerId), stopped]);
1569
- if (stopCause) return latchedOutcome();
1570
1761
 
1571
1762
  // Guided Review runs on an untrusted PR checkout, so its `.pi/settings.json` must never be merged.
1572
1763
  // Elsewhere the host's own trust decision decides: a repo the user declined to trust must not get
package/src/bro.ts CHANGED
@@ -12,6 +12,7 @@ import { setPiHostContext, stopActiveBackendExecutions } from "./backend.ts";
12
12
  import { openElevateModal } from "./elevate.ts";
13
13
  import { openArchitectureDocs } from "./architecture.ts";
14
14
  import { openGrillModal } from "./grill.ts";
15
+ import { openCopyModal } from "./copy.ts";
15
16
  import { registerOverthink } from "./overthink.ts";
16
17
  import { openRememberModal } from "./remember.ts";
17
18
  import { openSimplifyWorkflow, type SimplifyState } from "./simplify-ui.ts";
@@ -73,10 +74,12 @@ export * from "./simplify-ui.ts";
73
74
  export * from "./overthink-state.ts";
74
75
  export * from "./overthink.ts";
75
76
  export * from "./session-state.ts";
77
+ export * from "./copy.ts";
76
78
 
77
79
  const COMMANDS = [
78
80
  { value: "architecture", label: "architecture", description: "Document this repository in docs/architecture/ with diagrams and an offline map" },
79
81
  { value: "simplify", label: "simplify", description: "Reopen the last Simplify screen without a new model call" },
82
+ { value: "copy", label: "copy", description: "Edit, preview and copy the last assistant reply as Markdown — no model call" },
80
83
  { value: "text", label: "text", description: "Explain pasted text, or the latest reply when text is omitted" },
81
84
  { value: "file", label: "file", description: "Explain a local document" },
82
85
  { value: "url", label: "url", description: "Explain a public webpage" },
@@ -231,6 +234,13 @@ export default async function bro(pi: ExtensionAPI) {
231
234
  return;
232
235
  }
233
236
 
237
+ if (action === "copy") {
238
+ if (value) { ctx.ui.notify("Use /bro copy without arguments to edit the last reply.", "warning"); return; }
239
+ try { await openCopyModal(ctx); }
240
+ catch (error) { ctx.ui.notify("Bro Copy: " + errorMessage(error), "error"); }
241
+ return;
242
+ }
243
+
234
244
  if (action === "show") {
235
245
  const { requested, steering, invalid } = parseShowArguments(value);
236
246
  if (invalid) {
@@ -0,0 +1,85 @@
1
+ /** The shell chooses CLI account profiles. Bro only enforces the choice in each child. */
2
+ export type CliAuthBackend = "claude" | "codex";
3
+ export type CliChildAuth = { env: NodeJS.ProcessEnv; subscription: boolean };
4
+
5
+ // Launchers select an existing CLI profile via CLAUDE_CONFIG_DIR or CODEX_HOME.
6
+ // These source flags carry intent; Bro does not persist accounts or copy tokens.
7
+ export function resolveCliChildAuth(backend: CliAuthBackend, parent: NodeJS.ProcessEnv = process.env): CliChildAuth {
8
+ const selector = backend === "claude" ? "PI_BRO_CLAUDE_AUTH_SOURCE" : "PI_BRO_CODEX_AUTH_SOURCE";
9
+ const choice = parent[selector] ?? "inherit";
10
+ if (choice !== "inherit" && choice !== "subscription")
11
+ throw new Error("Invalid " + selector + "=" + JSON.stringify(choice) + "; use inherit or subscription.");
12
+ const env = { ...parent };
13
+ delete env.PI_BRO_CLAUDE_AUTH_SOURCE;
14
+ delete env.PI_BRO_CODEX_AUTH_SOURCE;
15
+ if (choice === "subscription") {
16
+ if (backend === "claude") {
17
+ // Claude -p gives API keys precedence over an authenticated subscription.
18
+ for (const key of [
19
+ "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL",
20
+ "ANTHROPIC_CUSTOM_HEADERS", "CLAUDE_CODE_OAUTH_TOKEN",
21
+ "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY",
22
+ ]) delete env[key];
23
+ } else {
24
+ // Codex exec has independent, documented API-key overrides.
25
+ delete env.CODEX_API_KEY;
26
+ delete env.OPENAI_API_KEY;
27
+ // A subscription request must not inherit a provider URL redirect.
28
+ delete env.OPENAI_BASE_URL;
29
+ delete env.CHATGPT_BASE_URL;
30
+ }
31
+ }
32
+ return { env, subscription: choice === "subscription" };
33
+ }
34
+
35
+ /** Method-only status check. Does not prove a specific account or successful model request. */
36
+ export function isSubscriptionStatus(backend: CliAuthBackend, stdout: string): boolean {
37
+ if (backend === "codex") return /^Logged in using ChatGPT\s*$/im.test(stdout.trim());
38
+ try {
39
+ const status = JSON.parse(stdout) as Record<string, unknown>;
40
+ return status?.loggedIn === true && status.authMethod === "claude.ai";
41
+ } catch { return false; }
42
+ }
43
+
44
+
45
+ /**
46
+ * Codex login status describes the account, not the effective request provider.
47
+ * Read Codex's own resolved config via app-server config/read rather than
48
+ * interpreting individual TOML layers in Bro.
49
+ *
50
+ * Only the built-in OpenAI provider with no endpoint override is admitted for
51
+ * explicit ChatGPT subscription intent. Never silently switch the user's
52
+ * configured custom provider to OpenAI. Other providers remain available in
53
+ * ordinary (inherit) mode.
54
+ */
55
+ export function codexSubscriptionRouteProblem(config: unknown): string | undefined {
56
+ if (!config || typeof config !== "object" || Array.isArray(config))
57
+ return "Codex did not provide a usable effective configuration";
58
+ const effective = config as Record<string, unknown>;
59
+ // Codex 0.165.0 config/read reports null for an omitted provider.
60
+ // Its own Config::load resolves that implicit default to "openai" *after*
61
+ // managed, CLI and merged file/profile overrides. The app-server query
62
+ // already uses those effective layers for the requested working directory.
63
+ const configured = effective.model_provider;
64
+ const provider = configured === null || configured === undefined ? "openai" : configured;
65
+ if (provider !== "openai")
66
+ return `Codex selected model_provider=${JSON.stringify(provider)}; choose the built-in OpenAI provider in the selected CODEX_HOME profile`;
67
+ if (effective.openai_base_url !== undefined &&
68
+ effective.openai_base_url !== null && effective.openai_base_url !== "")
69
+ return "Codex has a custom openai_base_url; remove this redirect from the selected subscription profile";
70
+ // Codex config/read includes its built-in ChatGPT URL even in an untouched
71
+ // profile. Only an alternate target is a redirect.
72
+ const chatgptUrl = effective.chatgpt_base_url;
73
+ if (chatgptUrl !== undefined && chatgptUrl !== null && chatgptUrl !== "" &&
74
+ (typeof chatgptUrl !== "string" ||
75
+ chatgptUrl.replace(/[/]+$/, "") !== "https://chatgpt.com/backend-api"))
76
+ return "Codex has a custom chatgpt_base_url; remove this redirect from the selected subscription profile";
77
+ const providers = effective.model_providers;
78
+ if (providers !== null && providers !== undefined) {
79
+ if (typeof providers !== "object" || Array.isArray(providers))
80
+ return "Codex returned an unreadable provider table";
81
+ if (Object.prototype.hasOwnProperty.call(providers, "openai"))
82
+ return "Codex overrides the built-in OpenAI provider; use an unmodified subscription provider";
83
+ }
84
+ return undefined;
85
+ }