pi-bro 0.36.0 → 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/CHANGELOG.md +16 -0
- package/docs/piG-agent-shell-qualification.md +79 -0
- package/docs/pig-compatibility.md +2 -0
- package/docs/reference/settings.md +72 -0
- package/package.json +4 -2
- package/src/backend.ts +250 -59
- package/src/cli-auth.ts +85 -0
- package/src/doctor.ts +58 -16
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,22 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to pi-bro are documented here.
|
|
4
4
|
|
|
5
|
+
## [0.36.1] - 2026-11-09
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- Make the Pi child use the same host-effective registry for model metadata, provider authentication, endpoint and streaming. Do not pair a stale host endpoint with a credential reread from an edited models.json. A same-host edit keeps A+key A; a new host uses B+key B.
|
|
10
|
+
- Give host-supplied model scopes priority over disk patterns in the picker; keep an empty resolved host scope empty, reject unavailable scoped models and avoid diagnostics calculated from a different source. An SDK empty scope with no file patterns cannot reveal an unmatched CLI flag until the host exposes scope provenance.
|
|
11
|
+
- Allow PiG-Agent to select each official Claude Code or Codex CLI subscription through existing `CLAUDE_CONFIG_DIR`/`CODEX_HOME`; filter conflicting API credentials in that child alone, check the reported login method before execution, and keep the normal parent account untouched. No new account store.
|
|
12
|
+
- Add profile-routing, no-API-fallback, host-model, and two-home memory fixtures while retaining the newer real-host cleanup and session-restore behavior from 0.32–0.36.
|
|
13
|
+
|
|
14
|
+
- For explicit Codex subscription access, inspect the official effective provider config. Accept Codex 0.165.0's implicit OpenAI default (`model_provider: null`), preserve its profile/project precedence, and reject custom API-key providers or endpoint redirects. The inspection app-server gets a temporary local model catalog to avoid startup network discovery; the actual Codex request does not. Doctor runs the same checks and cannot certify a rejected setup.
|
|
15
|
+
- Publish the PiG shell qualification report in the npm package; CI checks `npm pack --dry-run` contents. Replace obsolete development docs about rebuilding host model/auth catalogs.
|
|
16
|
+
|
|
17
|
+
### Qualification
|
|
18
|
+
|
|
19
|
+
- Reconciled against pi-bro 0.36.0. Fixture success is not proof of PiG-Agent 0.5.3 interactive TUI or live account use. See `docs/piG-agent-shell-qualification.md`.
|
|
20
|
+
|
|
5
21
|
## [0.36.0] - 2026-11-09
|
|
6
22
|
|
|
7
23
|
### Added
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# PiG-Agent shell qualification — issue #177
|
|
2
|
+
|
|
3
|
+
**Status:** Bro 0.36.1 candidate. Direct **PiG 0.5.3 TUI and RPC** checks passed with synthetic CLI input; the *installed PiG-Agent package*, a genuine model-provider answer, and live subscription accounts are **not yet qualified**.
|
|
4
|
+
|
|
5
|
+
## Exact inputs and responsibility
|
|
6
|
+
|
|
7
|
+
| Part | Initial PiG-Agent PR #2 pin | Bro qualification work |
|
|
8
|
+
| --- | --- | --- |
|
|
9
|
+
| PiG binary | 0.5.3 | Unchanged |
|
|
10
|
+
| Node | 24.15.0 | Unchanged |
|
|
11
|
+
| PiG-Agent PR #2 | Initially `3f121638feaf9c8a551a2d7001481cd7d936a8c9`; later `eef7162241a8a65c1774043e172f90fe2d082110` | Rebuild with reconciled Bro 0.36.1 |
|
|
12
|
+
| Bro | 0.29.0 at `ff6b260b10be8889809d4ea02108aceb826e4668` | Reconciled with main 0.36.0 at `55f050343ec9e48afc5b6768596326b5714c5278`; PR stages 0.36.1 |
|
|
13
|
+
| Other extensions | Follow `shell/source-lock.json` in PiG-Agent PR #2 | Not changed by this PR |
|
|
14
|
+
|
|
15
|
+
Do **not** label the newer Bro commit as a test of the old Bro 0.29.0 artifact. Pin this PR's eventual full commit and its actual `package.json` version in the shell lock; rebuild the full native shell and record the resulting artifact digest. Reviewer/Engineering prompts are not involved in the gate.
|
|
16
|
+
|
|
17
|
+
## Bro → shell contracts
|
|
18
|
+
|
|
19
|
+
**Storage:** Bro's settings, preferences, approved memories and Pi model runtime resolve through the host's `getAgentDir()`, rather than the main Pi home. The shell sets `PIG_CODING_AGENT_DIR` and `PI_CODING_AGENT_DIR` to `<agent-home>/.pi`. The installed application and sessions remain distinct from that directory. `models.json` lives at `<agent-home>/.pi/models.json`; Bro does not search the main Pi directory or import another model format.
|
|
20
|
+
|
|
21
|
+
**Pi model selection:** The selected full `<provider>/<model-id>` is exact (split on the first slash). At execution Bro requires the model from the **host registry** and passes that physical model object (API, endpoint, limits and overrides) to the inner Pi session. A model not found in the host fails; it is never replaced with a similarly named default. The Pi SDK child uses a minimal session runtime with an inert in-memory credential store, **without reading the agent's models.json or auth.json**. It delegates model lookup, provider auth and model streaming to the **same host registry**. The child cannot copy, refresh, or rewrite host credentials. PiG-Agent owns optional source selection and any import/link of a shared `models.json`; changes to that source require a supported host reload or a new PiG session. No claim that the external CLI catalogs use `models.json`.
|
|
22
|
+
|
|
23
|
+
**Official CLI profiles:** PiG-Agent uses the reusable [launcher contract for CLI authentication](reference/settings.md#launcher-contract-for-cli-authentication), not a PiG-specific account mechanism. It chooses an existing `CLAUDE_CONFIG_DIR` or `CODEX_HOME` and, for an explicit subscription choice, passes the matching `PI_BRO_CLAUDE_AUTH_SOURCE=subscription` or `PI_BRO_CODEX_AUTH_SOURCE=subscription` in that installed shell's launch environment. Supply the same choice to TUI, print and RPC. The official CLI owns login and refresh; Bro owns the child-only policy and Doctor parity. The canonical values, filtering and failure behavior are in the linked reference; the versioned Codex/local-server evidence is [below](#codex-provider-route-regression-and-diagnostic-parity).
|
|
24
|
+
|
|
25
|
+
**Model scope:** If `ctx.scopedModels` contains host-selected models (for example from launch-time `--models`), the picker uses only those models and does not read independently changed file patterns to explain them. If the host reports an empty scope and there are configured `enabledModels`, Bro keeps the list empty and tells the user to check/reload the host. If the host does not supply `scopedModels` (older test hosts), Bro can resolve file patterns against the **host** catalog. Models removed from the host registry or lacking current host auth are not offered. **Host API limit:** A real `ctx.scopedModels=[]` with *no* `enabledModels` is documented by Pi as unscoped; the same empty array cannot reveal whether an unmatched launch-time `--models` pattern was attempted. To distinguish those cases, the Pi/PiG context API would need to expose whether an effective scope was configured and its resolution diagnostics. Bro cannot infer that history from the array; until the host exposes it, do not claim this particular case is fully distinguishable.
|
|
26
|
+
|
|
27
|
+
**Lifecycle:** Cancellation uses existing bounded process-group termination. Bro retains main's tracked, awaited backend shutdown on session lifecycle. The real PiG 0.5.3 RPC host test now confirms awaited reload cancellation and clean EOF with a synthetic child. Installed-shell hard exit and desktop exit are still **NOT RUN**; PiG-Agent owns its worker lifetime.
|
|
28
|
+
|
|
29
|
+
## Verified direct PiG 0.5.3 host checks (not packaged shell)
|
|
30
|
+
|
|
31
|
+
[GitHub Actions run 42629350520](https://github.com/tranhoangnguyen03/pi-bro/actions/runs/42629350520) ran on Linux x64 using PiG `0.5.3+1.4.0.74f46864`, Node `24.15.0`, and a downloaded PiG archive with SHA-256 `1e45e5e591a06d087587d5f09d2b6d61673a1e262cb2609e6189defffd5ae7ec`.
|
|
32
|
+
|
|
33
|
+
- **PASS:** Real host RPC reload cancels an active fake CLI child, awaits teardown and accepts a fresh command. EOF terminates its child without a late result (2/2 host tests).
|
|
34
|
+
- **PASS:** Real PiG 0.5.3 loaded `<agent-home>/.pi/models.json` containing only `study/probe`; Bro issued a real HTTP request to a local OpenAI-compatible endpoint with the selected model and bearer key. After changing endpoint/key A to B **while the original host stayed running**, the next request still went to **A using key A**; B received no request. A **new PiG host/session** then used **B with key B**. This is the mixed-state regression, not just a new-host test (1/1 custom-model test). No external provider was called.
|
|
35
|
+
- **PASS:** In an actual pseudo-terminal, `/bro config` shows Global/Features; `/bro text` opens Simplify and displays a completed fake Agy answer; Simplify `/copy` writes the exact answer via a **stubbed Linux clipboard command**; `/bro remember-me` shows its private memory view; `/bro preferences` opens its editor; `/bro btw` opens its side-question composer and returns a **fresh** backend answer; `/bro help` opens and PageDown moves its scroll position. Keyboard input, resize and Esc work, and Bro remains usable after closing Help.
|
|
36
|
+
- **PASS:** Full Bro CI at the updated source head: **578/578** tests, Node 22/Linux, Node 24/macOS, and the historical PiG 0.3.0 lane. The updated suites also check host-auth preflight deadlines, launch-time scope without `enabledModels`, host/file scope disagreement, scoped-empty behavior, and removed host-scoped models. The real-host lifecycle fixture uses a synchronous SIGTERM handler so an external shell-trap race cannot hide whether cleanup happened.
|
|
37
|
+
- **NOT RUN:** Packaged PiG-Agent application with Bro 0.36.1 pinned; a genuine **remote provider** answer and actual billing method; two authorized accounts; macOS/native clipboard delivery; all remaining advanced terminal journeys and hard-exit behavior. The custom endpoint test uses a local server and does not qualify a paid provider.
|
|
38
|
+
|
|
39
|
+
These tests load the extension from its source checkout in the **real PiG host**, not from a PiG-Agent installed release. A fake Agy CLI is not a subscription or provider request. The custom-model test makes real HTTP requests but only to a local test server; it is not evidence of an external provider's auth or billing.
|
|
40
|
+
|
|
41
|
+
## Codex provider-route regression and diagnostic parity
|
|
42
|
+
|
|
43
|
+
[Codex 0.165.0 offline regression](../test/codex-subscription-real.test.mjs) is a separate source CI lane. It creates an isolated temporary `CODEX_HOME` with **synthetic ChatGPT login tokens**, selects a custom `model_provider` with an API-key `env_key`, and starts a local HTTP listener. A deliberate subscription selection must fail in both Bro execution and `/bro doctor`; the local server must see **zero** requests. This verifies a real CLI configuration path, not a live account or subscription billing. The fallback guarantee is limited to the effective provider configuration that Codex exposes through `config/read`; if Codex cannot report its effective route, Bro stops before execution. Doctor uses the same effective environment and checks.
|
|
44
|
+
|
|
45
|
+
**Codex 0.165.0 default + network-discovery regression:** The [real CLI test](../test/codex-subscription-real.test.mjs) now covers a normal `CODEX_HOME/config.toml` with **no `model_provider` field** and checks that both the subscription preflight and Doctor accept it. It also checks explicit `openai`, custom `env_key` providers, trusted-project `model_provider` keys that Codex deliberately ignores, and a redirected `openai_base_url`. The test's local HTTP server must receive **zero requests of any method**, including discovery `GET /v1/models`, during these preflight probes. This verifies the selected model endpoint on Codex 0.165.0; it is not a blanket guarantee against unrelated Codex startup network traffic. The static catalog is an **inspection-only input**: it is not a model source or auth override for real inference. A passing preflight still does not verify a live subscription call or billing.
|
|
46
|
+
|
|
47
|
+
## Reproducible acceptance on the *packaged* shell
|
|
48
|
+
|
|
49
|
+
Build the exact PiG-Agent PR #2 source with the Bro PR head pinned. Install it into **two fresh independent homes** `A` and `B` using `shell-reference install --home DIR`. Run `doctor` for each and record actual PiG/Node/Bro/CLI versions, commit SHA, installed archive SHA256, platform and where `getAgentDir()` resolves.
|
|
50
|
+
|
|
51
|
+
1. **TUI, not RPC:** Run `shell-reference new --home A` in a real terminal. Use a real authorized backend and try `/bro`, `/bro simplify` (inside it `/text`, `/url`, `/file`, `/copy`, `/clear`, `/help`), `/bro config`, `/bro preferences`, `/bro btw`, and `/bro remember-me`. Exercise text input, selection, scrolling, resize, Esc/cancel and clipboard. Verify a real final backend answer. Check `/bro guided-review`, `/bro advisor`, `/bro elevate`, `/bro grill-me`, `/bro show`, `/bro overthink`, `/bro architecture`, and `/bro doctor`; mark unexercised paths **NOT RUN**, not PASS.
|
|
52
|
+
2. **Cleanup:** During a long real Claude/Codex/Pi request, use cancel, `/reload` and exit, then inspect child PIDs/grandchildren. A terminal exit must not leave an active backend. Test the same with a fast failure, slow backend and missing executable.
|
|
53
|
+
3. **Models:** Start with no `A/.pi/models.json`, check built-ins. Add an agent-local custom provider with a harmless locally controlled test endpoint; confirm picker listing, unchanged provider/model ID, request URL, configured credentials and metadata overrides in a real result. Break its key and definition and confirm useful failure with no fallback. Edit model file; check the host's supported reload/new session. Test enabled-model scopes and default settings separately.
|
|
54
|
+
4. **Accounts:** With an already-authorized host Claude login, run with `CLAUDE_CONFIG_DIR` inherited and then with the shell-selected profile and `PI_BRO_CLAUDE_AUTH_SOURCE=subscription`. Confirm non-secret CLI account/method and actual answer. Repeat Codex with `CODEX_HOME` and `PI_BRO_CODEX_AUTH_SOURCE=subscription`. Test inherited API key collisions, missing/expired login, forced method and parent API env retention. For two distinct authorized accounts, test concurrent A/B routing; otherwise mark the second live account **NOT RUN**.
|
|
55
|
+
5. **Isolation:** New sessions must not inherit another task's transcripts/side questions; an approved general Remember Me lesson stays available in A but not B. Inspect A and B settings, memory, session roots and model sources after concurrent use, reinstall and compatible rollback.
|
|
56
|
+
|
|
57
|
+
**Fixtures:** `npm test` includes deterministic fake CLI source-routing, conflicting auth, no-fallback and process-stop tests plus host registry model identity. The additional PiG 0.5.3 CI lane runs the real host/terminal with a synthetic Agy backend **and** runs Bro's Pi SDK against two real local HTTP model endpoints, confirming model ID, URL, credentials unchanged on the live host after a disk edit and refreshed on the next host. Both remain distinct from an installed PiG-Agent release and live subscription evidence.
|
|
58
|
+
|
|
59
|
+
## Specific PiG-Agent PR #2 work remaining
|
|
60
|
+
|
|
61
|
+
1. Add a shell-side account/model-source chooser (or clear documented setup) which picks each installed agent's existing CLI profile and optional shared `models.json` source, installs/seeds local models before launch, and supplies the **same resolved inputs** to TUI, print and RPC. It must not blindly share the main Pi home.
|
|
62
|
+
2. For a deliberate subscription choice, export the matching `PI_BRO_*_AUTH_SOURCE=subscription` flag **only in that installed shell's launch env**. Keep the normal process login untouched. Bro handles backend-child auth filtering.
|
|
63
|
+
3. Update `shell/source-lock.json` to this PR's exact Bro commit and matching version; rebuild a native release with PiG 0.5.3/Node 24.15.0, then execute the matrix above. Do not treat the existing smoke command registration as TUI qualification.
|
|
64
|
+
4. Verify that PiG reload and hard exit tear down the Node extension worker and its backends; if not, fix the PiG host lifetime owner rather than adding a second shell worker manager.
|
|
65
|
+
|
|
66
|
+
## Qualification matrix — actual observations
|
|
67
|
+
|
|
68
|
+
| Journey | Fixture / CI | Direct PiG 0.5.3 host | Installed PiG-Agent shell | Authorized account |
|
|
69
|
+
| --- | --- | --- | --- | --- |
|
|
70
|
+
| Simplify/config/preferences/BTW/Remember Me/Help, resize/scroll/Esc | **PASS** | **PASS** (synthetic Agy TUI) | **NOT RUN** | **NOT RUN** |
|
|
71
|
+
| Simplify clipboard write through fake Linux `xclip` | **PASS** | **PASS** — copied actual answer | **NOT RUN** | **NOT RUN** |
|
|
72
|
+
| Native macOS clipboard, Guided Review, Advisor, Elevate, Grill Me, Show, Overthink, Architecture | Unit coverage varies | **NOT RUN** | **NOT RUN** | **NOT RUN** |
|
|
73
|
+
| Reload cancellation and EOF process cleanup | **PASS** | **PASS** (RPC, 2/2) | **NOT RUN** | **NOT RUN** |
|
|
74
|
+
| Host-selected Pi model, auth and same-host file edit | **PASS** | **PASS** — A+A after disk edit; B+B after new host | **NOT RUN** | **NOT RUN** |
|
|
75
|
+
| Scope from host, conflict with file, explicit empty scope | **PASS** — host-context fixtures | **NOT RUN** — CLI-origin empty scope | **NOT RUN** | **NOT RUN** |
|
|
76
|
+
| Claude/Codex profile routing and explicit subscription policy | **PASS** — fake CLI and Doctor policy fixtures | **NOT RUN** — live account | **NOT RUN** | **NOT RUN** |
|
|
77
|
+
| Two isolated homes, fresh task and approved lesson | **PASS** — memory-root fixture | **NOT RUN** | **NOT RUN** | **NOT RUN** |
|
|
78
|
+
|
|
79
|
+
A fixture PASS does not establish the installed shell, real account identity, or paid request. To close #177, pin Bro 0.36.1 in PiG-Agent PR #2, rebuild, complete the missing installed-shell and live checks and record their exact source/artifact versions.
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# PiG compatibility
|
|
2
2
|
|
|
3
|
+
> PiG-Agent **0.5.3 shell qualification** is separate from the historical 0.3.0 lane here. See [shell acceptance, exact pins and remaining real-host checks](piG-agent-shell-qualification.md). Bro 0.36.1 reuses the host model registry and honors explicit official CLI subscription selection; it does not create its own model-source/account store.
|
|
4
|
+
|
|
3
5
|
Bro uses one TypeScript package on Pi and Pi-in-Go (PiG). PiG runs Bro in a Node subprocess; it is not a Go port or a fused native extension.
|
|
4
6
|
|
|
5
7
|
## Target and installation
|
|
@@ -93,6 +93,78 @@ Bro reads the file again before each request, so manual edits apply next time.
|
|
|
93
93
|
settings file, for example `PI_BRO_MODEL=gemini-3.7-flash-low pi`.
|
|
94
94
|
- Older flat settings files (root `model`/`effort`) still load and mean Agy.
|
|
95
95
|
|
|
96
|
+
## Launcher contract for CLI authentication
|
|
97
|
+
|
|
98
|
+
This contract is available to any launcher of Bro's Pi-compatible extension,
|
|
99
|
+
not only PiG-Agent. It selects authentication intent for the **Claude Code and
|
|
100
|
+
Codex backends**; it does not make either CLI a host for Bro's UI or tools.
|
|
101
|
+
|
|
102
|
+
### Ownership and launch inputs
|
|
103
|
+
|
|
104
|
+
- The launcher chooses an existing CLI profile and passes its location through
|
|
105
|
+
`CLAUDE_CONFIG_DIR` (Claude Code) or `CODEX_HOME` (Codex). If unset, the official
|
|
106
|
+
CLI uses its normal profile lookup. Bro does not find, create or switch accounts.
|
|
107
|
+
- The official CLI owns login, credential storage and refresh. Authenticate the
|
|
108
|
+
selected profile through that CLI; Bro does not copy tokens or manage logins.
|
|
109
|
+
- Bro owns its independent sessions and backend execution. It reads the intent
|
|
110
|
+
below when preparing backend children; these flags do not select a backend or
|
|
111
|
+
model. Choose those separately with `/bro config`.
|
|
112
|
+
- A launcher that offers this choice passes the same selected profile and intent
|
|
113
|
+
to interactive, print and RPC launches. The flags belong in that launch's
|
|
114
|
+
environment, not in `bro-settings.json` or a shared global account setting.
|
|
115
|
+
|
|
116
|
+
| Backend | Existing profile selector | Bro authentication intent |
|
|
117
|
+
| --- | --- | --- |
|
|
118
|
+
| Claude Code | `CLAUDE_CONFIG_DIR` | `PI_BRO_CLAUDE_AUTH_SOURCE` |
|
|
119
|
+
| Codex | `CODEX_HOME` | `PI_BRO_CODEX_AUTH_SOURCE` |
|
|
120
|
+
|
|
121
|
+
Each intent flag accepts exactly `inherit` or `subscription`. Unset means
|
|
122
|
+
`inherit`; any other value, including an empty string, fails for that backend.
|
|
123
|
+
|
|
124
|
+
- **`inherit`:** Bro preserves the CLI's ordinary authentication environment and
|
|
125
|
+
behavior. It does not require a subscription login or reject custom API routes.
|
|
126
|
+
- **`subscription`:** Bro checks the official CLI's login method and applies the
|
|
127
|
+
backend-specific policy below. A failed check stops the request; Bro does not
|
|
128
|
+
fall back to API-key authentication or silently select another provider.
|
|
129
|
+
|
|
130
|
+
For example, launch native Pi with an **already authenticated** Codex profile:
|
|
131
|
+
|
|
132
|
+
```sh
|
|
133
|
+
CODEX_HOME="$HOME/.codex" PI_BRO_CODEX_AUTH_SOURCE=subscription pi
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Bro must already be installed and its selected backend must be Codex. A different
|
|
137
|
+
launcher passes these same environment variables to its host process; it does not
|
|
138
|
+
need a separate Bro authentication implementation. To return to ordinary CLI
|
|
139
|
+
behavior, omit the intent flag or set it to `inherit` on the next launch.
|
|
140
|
+
|
|
141
|
+
### Backend-child policy
|
|
142
|
+
|
|
143
|
+
Bro copies the parent environment, removes both Bro intent flags from the child,
|
|
144
|
+
and leaves the parent's environment unchanged. Subscription filtering applies to
|
|
145
|
+
that backend child only; it does not change the host's model credentials or
|
|
146
|
+
another backend's authentication.
|
|
147
|
+
|
|
148
|
+
- **Claude Code:** Remove `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`,
|
|
149
|
+
`ANTHROPIC_BASE_URL`, `ANTHROPIC_CUSTOM_HEADERS`, `CLAUDE_CODE_OAUTH_TOKEN`,
|
|
150
|
+
`CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX` and
|
|
151
|
+
`CLAUDE_CODE_USE_FOUNDRY`. Require `claude auth status` to report
|
|
152
|
+
`loggedIn=true` and `authMethod=claude.ai` before model execution.
|
|
153
|
+
- **Codex:** Remove `CODEX_API_KEY`, `OPENAI_API_KEY`, `OPENAI_BASE_URL` and
|
|
154
|
+
`CHATGPT_BASE_URL`. Require ChatGPT login and inspect the selected profile's
|
|
155
|
+
effective provider configuration through the official app-server `config/read`.
|
|
156
|
+
Accept the implicit or explicit built-in OpenAI route; reject custom providers,
|
|
157
|
+
overrides of the built-in provider and endpoint redirects. Unreadable configuration
|
|
158
|
+
also stops execution. Bro uses Codex's effective configuration, not its own TOML
|
|
159
|
+
parser. After validation, execution pins that route and the ChatGPT login method.
|
|
160
|
+
|
|
161
|
+
`/bro doctor` applies the same explicit subscription checks as execution. A passing
|
|
162
|
+
check establishes the tested login method and route, **not** a successful live
|
|
163
|
+
answer, human account identity or subscription billing. See the
|
|
164
|
+
[implementation notes](../DEVELOPMENT.md#official-cli-subscription-policy) for
|
|
165
|
+
Codex's inspection-only catalog and the [PiG qualification guide](../piG-agent-shell-qualification.md#codex-provider-route-regression-and-diagnostic-parity)
|
|
166
|
+
for the versioned real-CLI/local-server evidence.
|
|
167
|
+
|
|
96
168
|
## Preferences
|
|
97
169
|
|
|
98
170
|
Tell Bro about yourself and how you like answers. Bro adds what you write to
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-bro",
|
|
3
|
-
"version": "0.36.
|
|
3
|
+
"version": "0.36.1",
|
|
4
4
|
"description": "A sidekick for you and your Pi agent: plain-language explanations, side questions, diagrams, PR review and second opinions, without cluttering the agent's context.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -79,6 +79,7 @@
|
|
|
79
79
|
"src/ui-capabilities.ts",
|
|
80
80
|
"src/modal-kit.ts",
|
|
81
81
|
"src/backend.ts",
|
|
82
|
+
"src/cli-auth.ts",
|
|
82
83
|
"src/prompt.ts",
|
|
83
84
|
"src/vendor/mermaid.min.js",
|
|
84
85
|
"README.md",
|
|
@@ -89,6 +90,7 @@
|
|
|
89
90
|
"docs/getting-started.md",
|
|
90
91
|
"docs/user-guide.md",
|
|
91
92
|
"docs/pig-compatibility.md",
|
|
93
|
+
"docs/piG-agent-shell-qualification.md",
|
|
92
94
|
"docs/guided-review.md",
|
|
93
95
|
"docs/elevate.md",
|
|
94
96
|
"docs/grill-me.md",
|
|
@@ -108,7 +110,7 @@
|
|
|
108
110
|
"scripts": {
|
|
109
111
|
"docs:check": "node scripts/check-docs.mjs && node --test test/docs-quality.test.mjs",
|
|
110
112
|
"typecheck": "tsc --noEmit",
|
|
111
|
-
"test": "npm run typecheck && npm run docs:check && node .github/scripts/release-utils.mjs selftest && node --experimental-transform-types --test --test-concurrency=2 test/architecture.test.mjs test/architecture-review.test.mjs test/architecture-controller.test.mjs test/elevate.test.ts test/overthink.test.ts test/copy-modal.test.mjs test/simplify.test.ts test/simplify-modal.test.mjs test/session-state.test.ts test/session-lifecycle.test.mjs test/host-lifecycle.test.mjs test/grill.test.ts test/config-navigation.test.ts test/config-navigation-modal.test.mjs test/remember.test.ts test/remember-modal.test.mjs test/review-ux.test.mjs test/review-doctor.test.mjs test/review-versions.test.mjs test/review-regeneration.test.mjs test/review-modal.test.mjs test/review.test.ts test/review-session.test.mjs test/helpers.test.mjs test/prompt.test.ts test/backend.test.ts test/claude.test.ts test/grok.test.ts test/codex.test.ts test/muse.test.ts test/settings.test.ts test/sources.test.ts test/release.test.ts test/show-html.test.ts test/smoke-rpc.test.ts test/ui-capabilities.test.ts test/modal-contract.test.mjs benchmark/*.test.ts && sh ./test/smoke-test.sh",
|
|
113
|
+
"test": "npm run typecheck && npm run docs:check && node .github/scripts/release-utils.mjs selftest && node --experimental-transform-types --test --test-concurrency=2 test/architecture.test.mjs test/architecture-review.test.mjs test/architecture-controller.test.mjs test/elevate.test.ts test/overthink.test.ts test/copy-modal.test.mjs test/simplify.test.ts test/simplify-modal.test.mjs test/session-state.test.ts test/session-lifecycle.test.mjs test/host-lifecycle.test.mjs test/grill.test.ts test/config-navigation.test.ts test/config-navigation-modal.test.mjs test/remember.test.ts test/remember-modal.test.mjs test/review-ux.test.mjs test/review-doctor.test.mjs test/review-versions.test.mjs test/review-regeneration.test.mjs test/review-modal.test.mjs test/review.test.ts test/review-session.test.mjs test/helpers.test.mjs test/prompt.test.ts test/backend.test.ts test/cli-auth.test.ts test/claude.test.ts test/grok.test.ts test/codex.test.ts test/muse.test.ts test/settings.test.ts test/sources.test.ts test/release.test.ts test/package-files.test.mjs test/show-html.test.ts test/smoke-rpc.test.ts test/ui-capabilities.test.ts test/modal-contract.test.mjs benchmark/*.test.ts && sh ./test/smoke-test.sh",
|
|
112
114
|
"benchmark:dry-run": "node benchmark/run.ts dry-run",
|
|
113
115
|
"benchmark:run": "node benchmark/run.ts run",
|
|
114
116
|
"benchmark:report": "node benchmark/run.ts report",
|
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
|
-
/**
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
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)
|
|
1462
|
-
|
|
1463
|
-
//
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
}
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
const
|
|
1477
|
-
|
|
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
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
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
|
-
//
|
|
1561
|
-
|
|
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/cli-auth.ts
ADDED
|
@@ -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
|
+
}
|
package/src/doctor.ts
CHANGED
|
@@ -16,7 +16,8 @@ import {
|
|
|
16
16
|
readAdvisorSteering,
|
|
17
17
|
resolveAdvisorState,
|
|
18
18
|
} from "./advisor.ts";
|
|
19
|
-
import { agyFailureMessage, bridgePiRuntimeForCatalog, piEffectiveEffort, reviewBackendNotice, splitPiModel } from "./backend.ts";
|
|
19
|
+
import { agyFailureMessage, bridgePiRuntimeForCatalog, piEffectiveEffort, reviewBackendNotice, splitPiModel, verifyCliSubscription } from "./backend.ts";
|
|
20
|
+
import { resolveCliChildAuth } from "./cli-auth.ts";
|
|
20
21
|
import { createConfigModal } from "./config-ui.ts";
|
|
21
22
|
import { createConfigNavigationModal } from "./config-navigation-ui.ts";
|
|
22
23
|
import { type ConfigNavAction, type ConfigNavState } from "./config-navigation.ts";
|
|
@@ -124,16 +125,47 @@ export async function listPiModels(
|
|
|
124
125
|
if (signal?.aborted) throw new Error("Canceled.");
|
|
125
126
|
|
|
126
127
|
const patterns = settingsManager.getEnabledModels() ?? [];
|
|
128
|
+
const hostScoped = ctx.scopedModels;
|
|
129
|
+
// The host has already resolved --models / enabledModels. A nonempty host
|
|
130
|
+
// scope wins even if the on-disk patterns disagree or do not exist.
|
|
131
|
+
if (hostScoped?.length) {
|
|
132
|
+
const effective = hostScoped.flatMap(({ model, thinkingLevel }) => {
|
|
133
|
+
const selected = ctx.modelRegistry.find(model.provider, model.id);
|
|
134
|
+
return selected && ctx.modelRegistry.hasConfiguredAuth(selected)
|
|
135
|
+
? [{ model: selected, thinkingLevel }] : [];
|
|
136
|
+
});
|
|
137
|
+
return {
|
|
138
|
+
models: toPiModelChoices(effective),
|
|
139
|
+
scope: "scoped",
|
|
140
|
+
diagnostics: effective.length < hostScoped.length
|
|
141
|
+
? ["A model in the active host scope is no longer available or authenticated. Refresh the host selection."] : [],
|
|
142
|
+
modelRuntime,
|
|
143
|
+
};
|
|
144
|
+
}
|
|
127
145
|
if (patterns.length) {
|
|
146
|
+
if (hostScoped !== undefined) {
|
|
147
|
+
// The host explicitly reports an empty resolved scope. Never turn it
|
|
148
|
+
// into an unscoped picker, or recompute options from newer disk files.
|
|
149
|
+
return {
|
|
150
|
+
models: [], scope: "scoped",
|
|
151
|
+
diagnostics: ["The active host has no scoped models. Check its --models / enabledModels selection; reload the host after editing settings."],
|
|
152
|
+
modelRuntime,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
// Old test hosts without scopedModels can still resolve file patterns;
|
|
156
|
+
// use only the host-backed catalog for both choices and diagnostics.
|
|
128
157
|
const resolved = await resolveModelScopeWithDiagnostics(patterns, modelRuntime);
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
158
|
+
return {
|
|
159
|
+
models: toPiModelChoices(resolved.scopedModels),
|
|
160
|
+
scope: "scoped",
|
|
161
|
+
diagnostics: resolved.diagnostics.map((entry) => entry.message),
|
|
162
|
+
modelRuntime,
|
|
163
|
+
};
|
|
134
164
|
}
|
|
135
|
-
|
|
136
|
-
|
|
165
|
+
// SDK documents [] as "no scope" when there are no enabledModels.
|
|
166
|
+
// The API cannot distinguish this from a failed CLI --models scope that
|
|
167
|
+
// resolved to [], since it does not expose the CLI source patterns.
|
|
168
|
+
const available = ctx.modelRegistry.getAvailable().map((model) => ({ model }));
|
|
137
169
|
return { models: toPiModelChoices(available), scope: "available", diagnostics: [], modelRuntime };
|
|
138
170
|
}
|
|
139
171
|
|
|
@@ -195,6 +227,12 @@ async function checkCliVersion(pi: ExtensionAPI, binary: string, displayName: st
|
|
|
195
227
|
// Auth status only: a version/auth answer without a model request. A passing answer here
|
|
196
228
|
// says the CLI starts and reports signed-in state -- it does not imply connectivity.
|
|
197
229
|
async function checkClaudeAuth(pi: ExtensionAPI, signal: AbortSignal): Promise<string> {
|
|
230
|
+
const auth = resolveCliChildAuth("claude");
|
|
231
|
+
if (auth.subscription) {
|
|
232
|
+
const outcome = await verifyCliSubscription("claude", auth.env, signal, 5_000, 15_000);
|
|
233
|
+
if (outcome) throw new Error("message" in outcome ? outcome.message : "Unexpected subscription preflight outcome");
|
|
234
|
+
return "subscription login verified (not a model request or account identity check)";
|
|
235
|
+
}
|
|
198
236
|
const result = await probeCli(pi, "claude", ["auth", "status"], signal, 15_000);
|
|
199
237
|
if (result.killed || result.code !== 0) {
|
|
200
238
|
const detail = result.stderr.trim() || result.stdout.trim();
|
|
@@ -208,7 +246,13 @@ async function checkClaudeAuth(pi: ExtensionAPI, signal: AbortSignal): Promise<s
|
|
|
208
246
|
|
|
209
247
|
// Auth status only: a version/auth answer without a model request. A passing answer here
|
|
210
248
|
// says the CLI starts and reports signed-in state -- it does not imply connectivity.
|
|
211
|
-
async function checkCodexAuth(pi: ExtensionAPI, signal: AbortSignal): Promise<string> {
|
|
249
|
+
async function checkCodexAuth(pi: ExtensionAPI, signal: AbortSignal, cwd: string): Promise<string> {
|
|
250
|
+
const auth = resolveCliChildAuth("codex");
|
|
251
|
+
if (auth.subscription) {
|
|
252
|
+
const outcome = await verifyCliSubscription("codex", auth.env, signal, 5_000, 15_000, cwd);
|
|
253
|
+
if (outcome) throw new Error("message" in outcome ? outcome.message : "Unexpected subscription preflight outcome");
|
|
254
|
+
return "ChatGPT login and built-in OpenAI provider route verified (not a model request or billing proof)";
|
|
255
|
+
}
|
|
212
256
|
const result = await probeCli(pi, "codex", ["login", "status"], signal, 15_000);
|
|
213
257
|
if (result.killed || result.code !== 0) {
|
|
214
258
|
const detail = result.stderr.trim() || result.stdout.trim();
|
|
@@ -235,13 +279,12 @@ export async function doctorReport(pi: ExtensionAPI, ctx: ExtensionCommandContex
|
|
|
235
279
|
let settings: BroSettings | undefined;
|
|
236
280
|
let models: AgyModelFamily[] | undefined;
|
|
237
281
|
let agyVersion: string | undefined;
|
|
238
|
-
let piRuntime: Awaited<ReturnType<typeof bridgePiRuntimeForCatalog>> | undefined;
|
|
239
282
|
const findPiModel = (provider: string, id: string) => {
|
|
240
|
-
const model =
|
|
283
|
+
const model = ctx.modelRegistry.find(provider, id);
|
|
241
284
|
return model?.api === "pi-virtual" ? undefined : model;
|
|
242
285
|
};
|
|
243
286
|
const hasPiAuth = (model: NonNullable<ReturnType<typeof findPiModel>>) =>
|
|
244
|
-
|
|
287
|
+
ctx.modelRegistry.hasConfiguredAuth(model);
|
|
245
288
|
const pass = (name: string, detail: string) => lines.push(`- ✓ **${name}:** ${detail}`);
|
|
246
289
|
const fail = (name: string, error: unknown) => {
|
|
247
290
|
failed = true;
|
|
@@ -318,7 +361,7 @@ export async function doctorReport(pi: ExtensionAPI, ctx: ExtensionCommandContex
|
|
|
318
361
|
}
|
|
319
362
|
if (backend === "claude" || backend === "codex") {
|
|
320
363
|
try {
|
|
321
|
-
pass(`${label} auth`, await (backend === "claude" ? checkClaudeAuth(pi, signal) : checkCodexAuth(pi, signal)));
|
|
364
|
+
pass(`${label} auth`, await (backend === "claude" ? checkClaudeAuth(pi, signal) : checkCodexAuth(pi, signal, ctx.cwd)));
|
|
322
365
|
} catch (error) {
|
|
323
366
|
if (signal.aborted) throw error;
|
|
324
367
|
fail(`${label} auth`, error);
|
|
@@ -328,13 +371,12 @@ export async function doctorReport(pi: ExtensionAPI, ctx: ExtensionCommandContex
|
|
|
328
371
|
}
|
|
329
372
|
}
|
|
330
373
|
|
|
331
|
-
// Pi is in-process: validate the selected physical model
|
|
374
|
+
// Pi is in-process: validate the host-selected physical model without a
|
|
332
375
|
// CLI spawn or a live model turn. A passing answer means the model resolves and has configured
|
|
333
376
|
// auth; it is not a connectivity test.
|
|
334
377
|
if (piInUse) {
|
|
335
378
|
try {
|
|
336
|
-
const { models: piModels, scope, diagnostics
|
|
337
|
-
piRuntime = modelRuntime;
|
|
379
|
+
const { models: piModels, scope, diagnostics } = await listPiModels(ctx, signal);
|
|
338
380
|
pass("Pi model catalog", `${piModels.length} physical model${piModels.length === 1 ? "" : "s"} selectable · ${scope === "scoped" ? "from enabledModels (scoped)" : "all models with configured auth"}`);
|
|
339
381
|
for (const diagnostic of diagnostics) lines.push(`- ℹ **Pi scoped models:** ${diagnostic}`);
|
|
340
382
|
} catch (error) {
|