pi-bro 0.36.0 → 0.36.2
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 +24 -0
- package/docs/features/btw.md +6 -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 +269 -69
- package/src/btw.ts +59 -16
- package/src/cli-auth.ts +85 -0
- package/src/doctor.ts +58 -16
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,30 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to pi-bro are documented here.
|
|
4
4
|
|
|
5
|
+
## [0.36.2] - 2026-11-10
|
|
6
|
+
|
|
7
|
+
### Improved
|
|
8
|
+
|
|
9
|
+
- `/bro btw` shows a live phase and elapsed time in its modal while a side question is running, including before the backend begins streaming text.
|
|
10
|
+
- When a backend reports tool use, BTW shows the last tool name/type without exposing commands, tool output or hidden reasoning. A quiet backend still updates the elapsed time every second.
|
|
11
|
+
- Progress hints stay out of saved threads and copies and clear on completion, errors and cancellation. Added offline UI/protocol checks.
|
|
12
|
+
|
|
13
|
+
## [0.36.1] - 2026-11-09
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- 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.
|
|
18
|
+
- 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.
|
|
19
|
+
- 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.
|
|
20
|
+
- 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.
|
|
21
|
+
|
|
22
|
+
- 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.
|
|
23
|
+
- 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.
|
|
24
|
+
|
|
25
|
+
### Qualification
|
|
26
|
+
|
|
27
|
+
- 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`.
|
|
28
|
+
|
|
5
29
|
## [0.36.0] - 2026-11-09
|
|
6
30
|
|
|
7
31
|
### Added
|
package/docs/features/btw.md
CHANGED
|
@@ -43,6 +43,12 @@ asked in.
|
|
|
43
43
|
are at the bottom; scroll up to read earlier turns. The header shows the model and reasoning effort the latest
|
|
44
44
|
turn used (`default` when the model's own effort applies) and the current
|
|
45
45
|
mode.
|
|
46
|
+
- While a turn runs, the bottom hint shows its current phase and elapsed time, even
|
|
47
|
+
when a backend has not started streaming the answer. When a backend reports tool
|
|
48
|
+
activity, the hint shows the latest tool name/type, not commands or private
|
|
49
|
+
output. Elapsed time means the request is still active, not that a specific
|
|
50
|
+
step is complete. These status hints are temporary: they are not copied or
|
|
51
|
+
stored with the conversation and disappear on completion or cancellation.
|
|
46
52
|
- A turn is capped at 2 minutes in conversation-only mode and 10 minutes in
|
|
47
53
|
full permission mode.
|
|
48
54
|
- Bro saves its completed thread, mode and draft as private Pi session entries.
|
|
@@ -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.2",
|
|
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,
|
|
@@ -220,7 +221,7 @@ export function beginAttempt(child: ChildProcess, signal: AbortSignal, deadlineM
|
|
|
220
221
|
type AgyEvent = {
|
|
221
222
|
event?: string;
|
|
222
223
|
conversation_id?: string;
|
|
223
|
-
step_update?: { step_type?: string; text_delta?: unknown };
|
|
224
|
+
step_update?: { step_type?: string; text_delta?: unknown; tool_name?: unknown };
|
|
224
225
|
result?: { status?: string; response?: unknown; error?: unknown; conversation_id?: string };
|
|
225
226
|
};
|
|
226
227
|
|
|
@@ -243,7 +244,7 @@ function parseExplainLine(line: string): { delta?: string; result?: string } {
|
|
|
243
244
|
return {};
|
|
244
245
|
}
|
|
245
246
|
|
|
246
|
-
export function parseBtwAgyLine(line: string): { delta?: string; result?: string; conversationId?: string; error?: string } {
|
|
247
|
+
export function parseBtwAgyLine(line: string): { delta?: string; result?: string; conversationId?: string; error?: string; activity?: string } {
|
|
247
248
|
let event: AgyEvent;
|
|
248
249
|
try {
|
|
249
250
|
event = JSON.parse(line) as AgyEvent;
|
|
@@ -251,6 +252,9 @@ export function parseBtwAgyLine(line: string): { delta?: string; result?: string
|
|
|
251
252
|
throw new Error("Agy returned invalid streaming data.");
|
|
252
253
|
}
|
|
253
254
|
const conversationId = event.conversation_id ?? event.result?.conversation_id;
|
|
255
|
+
if (event.event === "step_update" && typeof event.step_update?.tool_name === "string" && event.step_update.tool_name.trim()) {
|
|
256
|
+
return { activity: event.step_update.tool_name.trim(), conversationId };
|
|
257
|
+
}
|
|
254
258
|
if (event.event === "step_update" && event.step_update?.step_type === "agent_response" && typeof event.step_update.text_delta === "string") {
|
|
255
259
|
return { delta: event.step_update.text_delta, conversationId };
|
|
256
260
|
}
|
|
@@ -389,6 +393,7 @@ async function executeArgvPrint(
|
|
|
389
393
|
if (isBtw) {
|
|
390
394
|
const parsed = parseBtwAgyLine(line);
|
|
391
395
|
if (parsed.conversationId) conversationId = parsed.conversationId;
|
|
396
|
+
if (parsed.activity) onProgress?.({ kind: "activity", label: parsed.activity, timestamp: Date.now() });
|
|
392
397
|
if (parsed.error) throw new Error(parsed.error);
|
|
393
398
|
if (parsed.delta) {
|
|
394
399
|
partial += parsed.delta;
|
|
@@ -595,6 +600,176 @@ async function executeAdvisorStdin(
|
|
|
595
600
|
return { status: "success", text };
|
|
596
601
|
}
|
|
597
602
|
|
|
603
|
+
/**
|
|
604
|
+
* Ask the official Codex app-server for the effective provider configuration.
|
|
605
|
+
* This is the same Codex CLI, CODEX_HOME, and working directory used for exec.
|
|
606
|
+
* A login status alone cannot detect custom provider env_key API billing.
|
|
607
|
+
*
|
|
608
|
+
* Inspection never makes a model request. Missing, unreadable or unsupported
|
|
609
|
+
* app-server/config/read support fails closed when subscription is explicit.
|
|
610
|
+
*/
|
|
611
|
+
// Codex 0.165.0 app-server starts an online catalog refresh on boot,
|
|
612
|
+
// even if the only client method is config/read. Supply a disposable static
|
|
613
|
+
// catalog for this *inspection process only* so the refresh worker cannot
|
|
614
|
+
// contact a configured provider. The override does NOT select a provider,
|
|
615
|
+
// change account credentials, or go into the real codex exec arguments.
|
|
616
|
+
// The provider is still read from Codex's effective config for the same cwd.
|
|
617
|
+
const CODEX_INSPECTION_CATALOG = {
|
|
618
|
+
models: [{
|
|
619
|
+
slug: "bro-config-inspection-only",
|
|
620
|
+
display_name: "Bro configuration inspection only",
|
|
621
|
+
description: "Local offline catalog; never used for inference",
|
|
622
|
+
base_instructions: "Local configuration inspection only; never used for inference.",
|
|
623
|
+
default_reasoning_level: "medium",
|
|
624
|
+
supported_reasoning_levels: [{ effort: "medium", description: "medium" }],
|
|
625
|
+
shell_type: "shell_command",
|
|
626
|
+
visibility: "none",
|
|
627
|
+
supported_in_api: true,
|
|
628
|
+
priority: 0,
|
|
629
|
+
support_verbosity: false,
|
|
630
|
+
default_verbosity: null,
|
|
631
|
+
apply_patch_tool_type: null,
|
|
632
|
+
truncation_policy: { mode: "bytes", limit: 10_000 },
|
|
633
|
+
experimental_supported_tools: [],
|
|
634
|
+
}],
|
|
635
|
+
};
|
|
636
|
+
|
|
637
|
+
async function inspectCodexSubscriptionRoute(
|
|
638
|
+
env: NodeJS.ProcessEnv, cwd: string | undefined, signal: AbortSignal,
|
|
639
|
+
deadlineMs: number, killEscalationMs: number,
|
|
640
|
+
): Promise<BackendOutcome | undefined> {
|
|
641
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
642
|
+
const probeDir = await mkdtemp(join(tmpdir(), "pi-bro-codex-inspect-"));
|
|
643
|
+
try {
|
|
644
|
+
const catalogPath = join(probeDir, "catalog.json");
|
|
645
|
+
await writeFile(catalogPath, JSON.stringify(CODEX_INSPECTION_CATALOG), { mode: 0o600 });
|
|
646
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
647
|
+
const { child, attempt, diagnostics } = startCliAttempt(
|
|
648
|
+
"codex", ["-c", `model_catalog_json=${JSON.stringify(catalogPath)}`, "app-server"],
|
|
649
|
+
{ env, cwd, stdio: ["pipe", "pipe", "pipe"] },
|
|
650
|
+
signal, Math.min(deadlineMs, 15_000), killEscalationMs,
|
|
651
|
+
);
|
|
652
|
+
let buffer = "";
|
|
653
|
+
let decided = false;
|
|
654
|
+
let finish: (problem: string | undefined) => void = () => {};
|
|
655
|
+
const decision = new Promise<string | undefined>(resolve => { finish = resolve; });
|
|
656
|
+
const settle = (problem: string | undefined) => {
|
|
657
|
+
if (decided) return;
|
|
658
|
+
decided = true;
|
|
659
|
+
finish(problem);
|
|
660
|
+
};
|
|
661
|
+
const send = (value: object) => {
|
|
662
|
+
if (decided || attempt.causeOf()) return;
|
|
663
|
+
try { child.stdin?.write(JSON.stringify(value) + "\n"); }
|
|
664
|
+
catch { settle("Codex app-server could not accept the configuration query"); }
|
|
665
|
+
};
|
|
666
|
+
// An app-server may close its input pipe while its buffered response is
|
|
667
|
+
// still readable. The close race below decides whether the query succeeded.
|
|
668
|
+
child.stdin?.on("error", () => {});
|
|
669
|
+
child.stdout?.setEncoding("utf8");
|
|
670
|
+
child.stdout?.on("data", (chunk: string) => {
|
|
671
|
+
if (decided || attempt.causeOf()) return;
|
|
672
|
+
buffer += chunk;
|
|
673
|
+
if (buffer.length > 2_000_000) { settle("Codex returned an oversized configuration response"); return; }
|
|
674
|
+
for (;;) {
|
|
675
|
+
const index = buffer.indexOf("\n");
|
|
676
|
+
if (index < 0) break;
|
|
677
|
+
const line = buffer.slice(0, index);
|
|
678
|
+
buffer = buffer.slice(index + 1);
|
|
679
|
+
if (!line.trim()) continue;
|
|
680
|
+
let message: Record<string, unknown>;
|
|
681
|
+
try {
|
|
682
|
+
message = JSON.parse(line) as Record<string, unknown>;
|
|
683
|
+
} catch {
|
|
684
|
+
settle("Codex app-server returned invalid JSON");
|
|
685
|
+
return;
|
|
686
|
+
}
|
|
687
|
+
if (message.id === 0) {
|
|
688
|
+
if (!message.result || message.error) {
|
|
689
|
+
settle("Codex app-server initialization failed");
|
|
690
|
+
return;
|
|
691
|
+
}
|
|
692
|
+
send({ method: "initialized", params: {} });
|
|
693
|
+
send({ method: "config/read", id: 1, params: { includeLayers: false, ...(cwd ? { cwd } : {}) } });
|
|
694
|
+
} else if (message.id === 1) {
|
|
695
|
+
if (message.error || !message.result || typeof message.result !== "object") {
|
|
696
|
+
settle("Codex app-server did not support config/read for this account/profile");
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
const config = (message.result as { config?: unknown }).config;
|
|
700
|
+
settle(codexSubscriptionRouteProblem(config));
|
|
701
|
+
return;
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
});
|
|
705
|
+
send({ method: "initialize", id: 0,
|
|
706
|
+
params: { clientInfo: { name: "pi_bro", title: "Pi Bro", version: "0.36.1" } } });
|
|
707
|
+
const result = await Promise.race([
|
|
708
|
+
decision.then(problem => ({ kind: "decision" as const, problem })),
|
|
709
|
+
attempt.closed.then(() => ({ kind: "closed" as const })),
|
|
710
|
+
]);
|
|
711
|
+
// The probe is not a long-running provider connection.
|
|
712
|
+
if (!attempt.causeOf()) attempt.stop("protocol");
|
|
713
|
+
await attempt.closed;
|
|
714
|
+
attempt.dispose();
|
|
715
|
+
if (signal.aborted || attempt.causeOf() === "cancelled")
|
|
716
|
+
return { status: "cancelled", message: "Canceled." };
|
|
717
|
+
if (attempt.causeOf() === "timeout")
|
|
718
|
+
return { status: "timeout", message: "Codex effective subscription configuration check timed out." };
|
|
719
|
+
const problem = result.kind === "decision"
|
|
720
|
+
? result.problem
|
|
721
|
+
: diagnostics.processError
|
|
722
|
+
? "Codex app-server could not start"
|
|
723
|
+
: "Codex app-server closed without returning the effective configuration" +
|
|
724
|
+
(diagnostics.stderr.trim() ? ": " + diagnostics.stderr.trim().slice(0, 700) : "");
|
|
725
|
+
return problem
|
|
726
|
+
? { status: "failure", message: "Codex subscription selection is not safe: " + problem +
|
|
727
|
+
". 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." }
|
|
728
|
+
: undefined;
|
|
729
|
+
} finally {
|
|
730
|
+
await rm(probeDir, { recursive: true, force: true });
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// Only a deliberate subscription choice gets an auth-method preflight.
|
|
735
|
+
// CLI status is not proof of account identity or a paid model call.
|
|
736
|
+
export async function verifyCliSubscription(
|
|
737
|
+
backend: CliAuthBackend,
|
|
738
|
+
env: NodeJS.ProcessEnv,
|
|
739
|
+
signal: AbortSignal,
|
|
740
|
+
killEscalationMs: number,
|
|
741
|
+
deadlineMs: number,
|
|
742
|
+
cwd?: string,
|
|
743
|
+
): Promise<BackendOutcome | undefined> {
|
|
744
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
745
|
+
const label = backend === "claude" ? "Claude Code" : "Codex";
|
|
746
|
+
const args = backend === "claude" ? ["auth", "status"] : ["login", "status"];
|
|
747
|
+
const { child, attempt, diagnostics } = startCliAttempt(backend, args,
|
|
748
|
+
{ env, stdio: ["ignore", "pipe", "pipe"] },
|
|
749
|
+
signal, Math.min(deadlineMs, 15_000), killEscalationMs);
|
|
750
|
+
let stdout = "";
|
|
751
|
+
child.stdout?.on("data", (chunk: Buffer) => {
|
|
752
|
+
stdout = (stdout + chunk.toString()).slice(0, 32_768);
|
|
753
|
+
});
|
|
754
|
+
const { code, exitSignal } = await attempt.closed;
|
|
755
|
+
attempt.dispose();
|
|
756
|
+
if (attempt.causeOf() === "cancelled") return { status: "cancelled", message: "Canceled." };
|
|
757
|
+
if (attempt.causeOf() === "timeout") return { status: "timeout", message: label + " subscription login check timed out." };
|
|
758
|
+
if (diagnostics.processError)
|
|
759
|
+
return { status: "failure", message: processStartMessage(diagnostics.processError as NodeJS.ErrnoException, label) };
|
|
760
|
+
const status = backend === "codex" ? stdout + "\n" + diagnostics.stderr : stdout;
|
|
761
|
+
if (code !== 0 || exitSignal || !isSubscriptionStatus(backend, status)) {
|
|
762
|
+
const command = backend === "claude" ? "claude auth status" : "codex login status";
|
|
763
|
+
const profile = backend === "claude" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME";
|
|
764
|
+
return { status: "failure", message: label +
|
|
765
|
+
" did not confirm subscription login in the selected profile. Run `" + command +
|
|
766
|
+
"` with that " + profile + " and sign in to the intended subscription; Bro will not switch to API billing." };
|
|
767
|
+
}
|
|
768
|
+
return backend === "codex"
|
|
769
|
+
? inspectCodexSubscriptionRoute(env, cwd, signal, deadlineMs, killEscalationMs)
|
|
770
|
+
: undefined;
|
|
771
|
+
}
|
|
772
|
+
|
|
598
773
|
type ClaudeEvent = {
|
|
599
774
|
type?: unknown;
|
|
600
775
|
subtype?: unknown;
|
|
@@ -638,6 +813,14 @@ async function executeClaude(
|
|
|
638
813
|
}
|
|
639
814
|
|
|
640
815
|
try {
|
|
816
|
+
let auth: ReturnType<typeof resolveCliChildAuth>;
|
|
817
|
+
try { auth = resolveCliChildAuth("claude"); }
|
|
818
|
+
catch (error) { return { status: "failure", message: errorMessage(error) }; }
|
|
819
|
+
if (auth.subscription) {
|
|
820
|
+
const check = await verifyCliSubscription("claude", auth.env, signal, killEscalationMs, deadlineMs);
|
|
821
|
+
if (check) return check;
|
|
822
|
+
}
|
|
823
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
641
824
|
const { child, attempt, diagnostics } = startCliAttempt("claude",
|
|
642
825
|
[
|
|
643
826
|
"-p",
|
|
@@ -660,7 +843,7 @@ async function executeClaude(
|
|
|
660
843
|
],
|
|
661
844
|
{
|
|
662
845
|
cwd: runDirectory ?? request.cwd,
|
|
663
|
-
stdio: ["pipe", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
|
|
846
|
+
stdio: ["pipe", "pipe", "pipe"], env: auth.env }, signal, deadlineMs, killEscalationMs);
|
|
664
847
|
|
|
665
848
|
let partial = "";
|
|
666
849
|
let final: string | undefined;
|
|
@@ -690,9 +873,10 @@ async function executeClaude(
|
|
|
690
873
|
onProgress?.({ kind: "text", text: partial });
|
|
691
874
|
}
|
|
692
875
|
}
|
|
693
|
-
if (isAdvisor && topLevel && event.type === "assistant" && Array.isArray(event.message?.content)) {
|
|
876
|
+
if ((isAdvisor || isBtw) && topLevel && event.type === "assistant" && Array.isArray(event.message?.content)) {
|
|
694
877
|
for (const block of event.message.content as Array<{ type?: unknown; name?: unknown; text?: unknown }>) {
|
|
695
878
|
if (attempt.causeOf()) break;
|
|
879
|
+
if (isBtw && block?.type !== "tool_use") continue;
|
|
696
880
|
const label =
|
|
697
881
|
block?.type === "tool_use" && typeof block.name === "string"
|
|
698
882
|
? block.name.trim()
|
|
@@ -880,9 +1064,10 @@ async function executeGrok(
|
|
|
880
1064
|
}
|
|
881
1065
|
streamedSinceAssistant = false;
|
|
882
1066
|
}
|
|
883
|
-
if (isAdvisor && event.type === "assistant" && Array.isArray(message?.content)) {
|
|
1067
|
+
if ((isAdvisor || isBtw) && event.type === "assistant" && Array.isArray(message?.content)) {
|
|
884
1068
|
for (const block of message.content as Array<{ type?: unknown; name?: unknown; text?: unknown }>) {
|
|
885
1069
|
if (attempt.causeOf()) break;
|
|
1070
|
+
if (isBtw && block?.type !== "tool_use") continue;
|
|
886
1071
|
const label =
|
|
887
1072
|
block?.type === "tool_use" && typeof block.name === "string"
|
|
888
1073
|
? block.name.trim()
|
|
@@ -1013,10 +1198,19 @@ async function executeCodex(
|
|
|
1013
1198
|
}
|
|
1014
1199
|
|
|
1015
1200
|
try {
|
|
1201
|
+
let auth: ReturnType<typeof resolveCliChildAuth>;
|
|
1202
|
+
try { auth = resolveCliChildAuth("codex"); }
|
|
1203
|
+
catch (error) { return { status: "failure", message: errorMessage(error) }; }
|
|
1204
|
+
if (auth.subscription) {
|
|
1205
|
+
const check = await verifyCliSubscription("codex", auth.env, signal, killEscalationMs, deadlineMs, runDirectory ?? request.cwd);
|
|
1206
|
+
if (check) return check;
|
|
1207
|
+
}
|
|
1208
|
+
if (signal.aborted) return { status: "cancelled", message: "Canceled." };
|
|
1016
1209
|
const permissionArgs = full ? ["--dangerously-bypass-approvals-and-sandbox"] : ["--sandbox", "read-only"];
|
|
1017
1210
|
const resume = isBtw && request.continuation;
|
|
1018
1211
|
const args = [
|
|
1019
1212
|
"exec",
|
|
1213
|
+
...(auth.subscription ? ["-c", 'forced_login_method="chatgpt"', "-c", 'model_provider="openai"'] : []),
|
|
1020
1214
|
...permissionArgs,
|
|
1021
1215
|
...(resume ? ["resume"] : []),
|
|
1022
1216
|
"--json",
|
|
@@ -1030,7 +1224,7 @@ async function executeCodex(
|
|
|
1030
1224
|
|
|
1031
1225
|
const { child, attempt, diagnostics } = startCliAttempt("codex", args, {
|
|
1032
1226
|
cwd: runDirectory ?? request.cwd,
|
|
1033
|
-
stdio: ["pipe", "pipe", "pipe"] }, signal, deadlineMs, killEscalationMs);
|
|
1227
|
+
stdio: ["pipe", "pipe", "pipe"], env: auth.env }, signal, deadlineMs, killEscalationMs);
|
|
1034
1228
|
|
|
1035
1229
|
let partial = "";
|
|
1036
1230
|
let threadId: string | undefined;
|
|
@@ -1069,8 +1263,10 @@ async function executeCodex(
|
|
|
1069
1263
|
return;
|
|
1070
1264
|
}
|
|
1071
1265
|
const item = event.item;
|
|
1072
|
-
if (isAdvisor && (event.type === "item.started" || event.type === "item.completed")) {
|
|
1073
|
-
const activity =
|
|
1266
|
+
if ((isAdvisor || isBtw) && (event.type === "item.started" || event.type === "item.completed")) {
|
|
1267
|
+
const activity = isBtw
|
|
1268
|
+
? (typeof item?.type === "string" && item.type !== "agent_message" && item.type !== "reasoning" ? item.type : undefined)
|
|
1269
|
+
: codexActivityFromEvent(event);
|
|
1074
1270
|
if (activity) onProgress?.({ kind: "activity", label: activity, timestamp: Date.now() });
|
|
1075
1271
|
}
|
|
1076
1272
|
if (event.type === "item.completed" && item?.type === "agent_message") {
|
|
@@ -1214,22 +1410,23 @@ async function executeMuse(
|
|
|
1214
1410
|
const runStream = payload?.run_stream;
|
|
1215
1411
|
const isRoot = rootRunId !== undefined && runStream?.kind === "run" && runStream.id === rootRunId;
|
|
1216
1412
|
|
|
1217
|
-
if (isAdvisor) {
|
|
1413
|
+
if (isAdvisor || isBtw) {
|
|
1218
1414
|
if (envelope.payload_type === "tool.result") {
|
|
1219
1415
|
const facts = payload?.correlation_facts as { tool_name?: unknown } | undefined;
|
|
1220
1416
|
const toolName = typeof facts?.tool_name === "string" && facts.tool_name ? facts.tool_name : "tool";
|
|
1221
1417
|
const candidate = [payload?.text, payload?.command, payload?.path, payload?.file_path, payload?.query]
|
|
1222
1418
|
.find((v) => typeof v === "string" && v.trim());
|
|
1223
1419
|
const preview = typeof candidate === "string" ? candidate.replace(/\s+/g, " ").trim() : "";
|
|
1224
|
-
const label = `${toolName}${preview ? ` ${preview}` : ""}`;
|
|
1420
|
+
const label = isBtw ? toolName : `${toolName}${preview ? ` ${preview}` : ""}`;
|
|
1225
1421
|
onProgress?.({ kind: "activity", label, timestamp: Date.now() });
|
|
1226
|
-
} else if (envelope.payload_type === "task.lifecycle.status") {
|
|
1422
|
+
} else if (isAdvisor && envelope.payload_type === "task.lifecycle.status") {
|
|
1227
1423
|
const event = payload?.event as { message?: unknown } | undefined;
|
|
1228
1424
|
if (typeof event?.message === "string" && event.message.trim()) {
|
|
1229
1425
|
onProgress?.({ kind: "activity", label: event.message.trim(), timestamp: Date.now() });
|
|
1230
1426
|
}
|
|
1231
1427
|
}
|
|
1232
|
-
}
|
|
1428
|
+
}
|
|
1429
|
+
if (!isAdvisor && isRoot && envelope.payload_type === "run.output.delta") {
|
|
1233
1430
|
if (typeof payload?.text === "string" && payload.text) {
|
|
1234
1431
|
partial += payload.text;
|
|
1235
1432
|
onProgress?.({ kind: "text", text: partial });
|
|
@@ -1431,63 +1628,67 @@ function piAssistantText(message: { content?: unknown }): string {
|
|
|
1431
1628
|
.trim();
|
|
1432
1629
|
}
|
|
1433
1630
|
|
|
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> {
|
|
1631
|
+
/**
|
|
1632
|
+
* The Pi SDK asks for a ModelRuntime even when its physical model is explicit.
|
|
1633
|
+
* Bind every auth/model/stream read to the host's existing registry instead of
|
|
1634
|
+
* rebuilding a second provider from models.json. In particular, an on-disk edit
|
|
1635
|
+
* must never combine a host-old endpoint with a freshly read API key.
|
|
1636
|
+
*
|
|
1637
|
+
* The SDK runtime here only supplies agent/session mechanics; it does not own
|
|
1638
|
+
* credentials, source selection or refresh. No models.json is read by this child.
|
|
1639
|
+
*/
|
|
1640
|
+
async function bridgePiModelRuntime(host: PiHostContext | undefined, _agentDir: string): Promise<ModelRuntime> {
|
|
1460
1641
|
const registry = host?.modelRegistry;
|
|
1461
|
-
if (!registry)
|
|
1462
|
-
|
|
1463
|
-
//
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
}
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
const
|
|
1477
|
-
|
|
1642
|
+
if (!registry) throw new Error("The Pi host model registry is unavailable; reopen Bro from a live Pi session.");
|
|
1643
|
+
// The SDK requires a ModelRuntime, but it must not read an independent auth.json
|
|
1644
|
+
// or models.json. All real auth and model calls below delegate to the host.
|
|
1645
|
+
const credentials = {
|
|
1646
|
+
read: async () => undefined,
|
|
1647
|
+
list: async () => [],
|
|
1648
|
+
modify: async (): Promise<never> => { throw new Error("The Pi host owns credential writes."); },
|
|
1649
|
+
delete: async (): Promise<never> => { throw new Error("The Pi host owns credential deletion."); },
|
|
1650
|
+
};
|
|
1651
|
+
const runtime = await ModelRuntime.create({
|
|
1652
|
+
credentials,
|
|
1653
|
+
modelsPath: null,
|
|
1654
|
+
refreshOnCreate: false,
|
|
1655
|
+
});
|
|
1656
|
+
const models = (provider?: string) => registry.getAll().filter((m) => !provider || m.provider === provider);
|
|
1657
|
+
const available = (provider?: string) => registry.getAvailable().filter((m) => !provider || m.provider === provider);
|
|
1658
|
+
// Use the same registry for the SDK's preflight, model lookup and final stream.
|
|
1659
|
+
// Resolving auth from provider alone is intentional: ModelRegistry.getProviderAuth()
|
|
1660
|
+
// is the public host API, and its underlying runtime still applies model-specific
|
|
1661
|
+
// headers and request overrides inside streamSimple().
|
|
1662
|
+
Object.assign(runtime, {
|
|
1663
|
+
getModel: (provider: string, id: string) => registry.find(provider, id),
|
|
1664
|
+
getModels: models,
|
|
1665
|
+
getAllModels: models,
|
|
1666
|
+
getAvailableSnapshot: () => available(),
|
|
1667
|
+
getAvailable: async (provider?: string) => available(provider),
|
|
1668
|
+
getProvider: (provider: string) => registry.getProvider(provider),
|
|
1669
|
+
getProviderAuthStatus: (provider: string) => registry.getProviderAuthStatus(provider),
|
|
1670
|
+
getAuth: async (modelOrProvider: string | { provider: string }) =>
|
|
1671
|
+
registry.getProviderAuth(typeof modelOrProvider === "string" ? modelOrProvider : modelOrProvider.provider),
|
|
1672
|
+
hasConfiguredAuth: (provider: string) => models(provider).some((model) => registry.hasConfiguredAuth(model)),
|
|
1673
|
+
checkAuth: async (provider: string) =>
|
|
1674
|
+
(await registry.getProviderAuth(provider)) ? { type: "api_key", source: "host registry" } : undefined,
|
|
1675
|
+
isUsingOAuth: (provider: string) => models(provider).some((model) => registry.isUsingOAuth(model)),
|
|
1676
|
+
streamSimple: (
|
|
1677
|
+
model: Parameters<ModelRuntime["streamSimple"]>[0],
|
|
1678
|
+
context: Parameters<ModelRuntime["streamSimple"]>[1],
|
|
1679
|
+
options: Parameters<ModelRuntime["streamSimple"]>[2],
|
|
1680
|
+
) => {
|
|
1681
|
+
// Neither another runtime nor child options may override the host's auth.
|
|
1682
|
+
const { apiKey: _key, env: _env, ...rest } = options ?? {};
|
|
1683
|
+
return registry.streamSimple(model, context, rest);
|
|
1684
|
+
},
|
|
1685
|
+
});
|
|
1478
1686
|
return runtime;
|
|
1479
1687
|
}
|
|
1480
1688
|
|
|
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);
|
|
1689
|
+
/** The picker and the executor use this same host-backed model/auth view. */
|
|
1690
|
+
export async function bridgePiRuntimeForCatalog(host: PiHostContext | undefined, agentDir: string): Promise<ModelRuntime> {
|
|
1691
|
+
return bridgePiModelRuntime(host, agentDir);
|
|
1491
1692
|
}
|
|
1492
1693
|
|
|
1493
1694
|
async function executePi(
|
|
@@ -1557,16 +1758,15 @@ async function executePi(
|
|
|
1557
1758
|
// or throwing host credential lookup becomes an ordinary outcome rather than a rejection.
|
|
1558
1759
|
const modelRuntime = await Promise.race([bridgePiModelRuntime(host, agentDir), stopped.then(() => undefined)]);
|
|
1559
1760
|
if (!modelRuntime) return latchedOutcome();
|
|
1560
|
-
//
|
|
1561
|
-
|
|
1761
|
+
// Use the effective host model for its exact identity, endpoint and metadata.
|
|
1762
|
+
// The SDK child uses the same host model, auth resolver and streaming transport.
|
|
1763
|
+
const model = host?.modelRegistry?.find(parts.providerId, parts.modelId);
|
|
1562
1764
|
if (!model) {
|
|
1563
1765
|
return { status: "failure", message: piErrorMessage(request.feature, `model \`${selection.model}\` is not in your Pi model catalog. Run \`/bro doctor\`.`) };
|
|
1564
1766
|
}
|
|
1565
1767
|
if ((model as { api?: string }).api === "pi-virtual") {
|
|
1566
1768
|
return { status: "failure", message: piErrorMessage(request.feature, `\`${selection.model}\` is a virtual model; choose a physical model in \`/bro config\`.`) };
|
|
1567
1769
|
}
|
|
1568
|
-
await Promise.race([copyRuntimeCredentials(host, modelRuntime, parts.providerId), stopped]);
|
|
1569
|
-
if (stopCause) return latchedOutcome();
|
|
1570
1770
|
|
|
1571
1771
|
// Guided Review runs on an untrusted PR checkout, so its `.pi/settings.json` must never be merged.
|
|
1572
1772
|
// Elsewhere the host's own trust decision decides: a repo the user declined to trust must not get
|
package/src/btw.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
2
|
import { copyToClipboard, getMarkdownTheme } from "@earendil-works/pi-coding-agent";
|
|
3
3
|
import { Input, Markdown, matchesKey, wrapTextWithAnsi, type Focusable } from "@earendil-works/pi-tui";
|
|
4
|
-
import { execute as executeBackend, textProgressThrottle, type BackendSelection } from "./backend.ts";
|
|
4
|
+
import { execute as executeBackend, textProgressThrottle, type BackendProgress, type BackendSelection } from "./backend.ts";
|
|
5
5
|
import { buildBtwPrompt } from "./prompt.ts";
|
|
6
6
|
import {
|
|
7
7
|
type BackendName,
|
|
@@ -138,9 +138,14 @@ export async function runBtwTurn(
|
|
|
138
138
|
selection: BackendSelection,
|
|
139
139
|
options: { full: boolean; cwd: string; conversationId?: string },
|
|
140
140
|
signal: AbortSignal,
|
|
141
|
-
onProgress?: (
|
|
141
|
+
onProgress?: (event: BackendProgress) => void,
|
|
142
142
|
): Promise<{ text: string; conversationId?: string; expiredContinuation?: true }> {
|
|
143
|
-
const
|
|
143
|
+
const textProgress = textProgressThrottle(signal, (text) => onProgress?.({ kind: "text", text }));
|
|
144
|
+
const receive = (event: BackendProgress) => {
|
|
145
|
+
if (signal.aborted) return;
|
|
146
|
+
if (event.kind === "activity") onProgress?.(event);
|
|
147
|
+
else textProgress.receive?.(event);
|
|
148
|
+
};
|
|
144
149
|
|
|
145
150
|
try {
|
|
146
151
|
const outcome = await executeBackend(
|
|
@@ -153,13 +158,13 @@ export async function runBtwTurn(
|
|
|
153
158
|
},
|
|
154
159
|
selection,
|
|
155
160
|
signal,
|
|
156
|
-
|
|
161
|
+
receive,
|
|
157
162
|
);
|
|
158
163
|
if (outcome.status === "success") return { text: outcome.text, conversationId: outcome.continuation?.id };
|
|
159
164
|
if (outcome.continuationExpired) return { text: "", expiredContinuation: true };
|
|
160
165
|
throw new Error(outcome.message);
|
|
161
166
|
} finally {
|
|
162
|
-
|
|
167
|
+
textProgress.dispose();
|
|
163
168
|
}
|
|
164
169
|
}
|
|
165
170
|
|
|
@@ -179,6 +184,7 @@ export class BtwModal implements Focusable {
|
|
|
179
184
|
{ followEnd: true },
|
|
180
185
|
);
|
|
181
186
|
private running = false;
|
|
187
|
+
private progressText = "";
|
|
182
188
|
private full = false;
|
|
183
189
|
private model = "";
|
|
184
190
|
private customMode = "";
|
|
@@ -243,6 +249,14 @@ export class BtwModal implements Focusable {
|
|
|
243
249
|
|
|
244
250
|
setRunning(running: boolean): void {
|
|
245
251
|
this.running = running;
|
|
252
|
+
if (!running) this.progressText = "";
|
|
253
|
+
this.tui.requestRender();
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Ephemeral in-flight status; never enters the thread or clipboard. */
|
|
257
|
+
setProgress(text: string): void {
|
|
258
|
+
if (this.disposed || !this.running) return;
|
|
259
|
+
this.progressText = text;
|
|
246
260
|
this.tui.requestRender();
|
|
247
261
|
}
|
|
248
262
|
|
|
@@ -323,7 +337,7 @@ export class BtwModal implements Focusable {
|
|
|
323
337
|
this.input.render(inner)[0] ?? "",
|
|
324
338
|
],
|
|
325
339
|
notice: this.noticeText ? formatNotice(this.theme, this.noticeText, this.noticeTone) : undefined,
|
|
326
|
-
hints: this.running ? "Bro is thinking… · Esc close (stops reply)
|
|
340
|
+
hints: this.running ? `${this.progressText || "Bro is thinking…"} · Esc close (stops reply)` : (this.appearance.idleHint ?? "Enter send · Esc close"),
|
|
327
341
|
});
|
|
328
342
|
}
|
|
329
343
|
|
|
@@ -345,6 +359,7 @@ export async function openBtwModal(
|
|
|
345
359
|
(tui, theme, _keybindings, done) => {
|
|
346
360
|
let closed = false;
|
|
347
361
|
let controller: AbortController | undefined;
|
|
362
|
+
let stopActiveProgress: (() => void) | undefined;
|
|
348
363
|
let activeTurn: { pending?: BtwTurn; original?: BtwTurn } | undefined;
|
|
349
364
|
// Discard an unfinished reply immediately on close, before another modal can
|
|
350
365
|
// reuse the same thread. A cancelled retry restores the completed old turn.
|
|
@@ -381,6 +396,7 @@ export async function openBtwModal(
|
|
|
381
396
|
if (closed) return;
|
|
382
397
|
closed = true;
|
|
383
398
|
saveDraft();
|
|
399
|
+
stopActiveProgress?.();
|
|
384
400
|
controller?.abort();
|
|
385
401
|
discardUnfinished();
|
|
386
402
|
options.onChange?.();
|
|
@@ -391,6 +407,7 @@ export async function openBtwModal(
|
|
|
391
407
|
if (closed) return; // Close already saved and cleaned this thread.
|
|
392
408
|
closed = true;
|
|
393
409
|
saveDraft();
|
|
410
|
+
stopActiveProgress?.();
|
|
394
411
|
controller?.abort();
|
|
395
412
|
discardUnfinished();
|
|
396
413
|
options.onChange?.();
|
|
@@ -407,7 +424,21 @@ export async function openBtwModal(
|
|
|
407
424
|
const work: { pending?: BtwTurn; original?: BtwTurn } = { original: replaced };
|
|
408
425
|
activeTurn = work;
|
|
409
426
|
controller = turnController;
|
|
427
|
+
const startedAt = Date.now();
|
|
428
|
+
let stage = "Preparing request";
|
|
429
|
+
const updateProgress = () => {
|
|
430
|
+
if (!closed && controller === turnController && !turnController.signal.aborted)
|
|
431
|
+
modal.setProgress(`${stage} · ${Math.floor((Date.now() - startedAt) / 1000)}s`);
|
|
432
|
+
};
|
|
433
|
+
const timer = setInterval(updateProgress, 1000);
|
|
434
|
+
timer.unref?.();
|
|
435
|
+
const stopProgress = () => {
|
|
436
|
+
clearInterval(timer);
|
|
437
|
+
if (stopActiveProgress === stopProgress) stopActiveProgress = undefined;
|
|
438
|
+
};
|
|
439
|
+
stopActiveProgress = stopProgress;
|
|
410
440
|
modal.setRunning(true);
|
|
441
|
+
updateProgress();
|
|
411
442
|
|
|
412
443
|
let settings: BroSettings;
|
|
413
444
|
let preferences: string;
|
|
@@ -415,6 +446,7 @@ export async function openBtwModal(
|
|
|
415
446
|
settings = await readSettings();
|
|
416
447
|
preferences = await readPreferences();
|
|
417
448
|
} catch (error) {
|
|
449
|
+
stopProgress();
|
|
418
450
|
if (activeTurn === work) discardUnfinished();
|
|
419
451
|
if (!closed && !replaced && !options.initialQuestion) modal.setComposerText(question);
|
|
420
452
|
if (controller === turnController) controller = undefined;
|
|
@@ -423,6 +455,7 @@ export async function openBtwModal(
|
|
|
423
455
|
}
|
|
424
456
|
// Do not restore a cancelled retry twice after close/dispose.
|
|
425
457
|
if (closed || turnController.signal.aborted) {
|
|
458
|
+
stopProgress();
|
|
426
459
|
if (activeTurn === work) discardUnfinished();
|
|
427
460
|
if (controller === turnController) controller = undefined;
|
|
428
461
|
return;
|
|
@@ -454,16 +487,27 @@ export async function openBtwModal(
|
|
|
454
487
|
thread.model = selectionLabel(selection);
|
|
455
488
|
thread.preferences = Boolean(preferences);
|
|
456
489
|
modal.setModel(btwHeaderLabel(thread));
|
|
490
|
+
stage = "Waiting for backend";
|
|
491
|
+
updateProgress();
|
|
492
|
+
const showBackendProgress = (event: BackendProgress) => {
|
|
493
|
+
if (closed || turnController.signal.aborted) return;
|
|
494
|
+
if (event.kind === "activity") {
|
|
495
|
+
// Tool names/types only, never commands, tool results, or hidden reasoning.
|
|
496
|
+
const label = event.label.trim().split(/\s+/)[0]?.slice(0, 30);
|
|
497
|
+
if (label) stage = `Last tool: ${label}`;
|
|
498
|
+
} else {
|
|
499
|
+
stage = "Receiving answer";
|
|
500
|
+
pending.answer = event.text;
|
|
501
|
+
modal.setText(transcript());
|
|
502
|
+
}
|
|
503
|
+
updateProgress();
|
|
504
|
+
};
|
|
457
505
|
let result = await runBtwTurn(
|
|
458
506
|
buildBtwPrompt(context, question, { full, history, preferences }),
|
|
459
507
|
selection,
|
|
460
508
|
{ full, cwd: ctx.cwd, conversationId },
|
|
461
509
|
turnController.signal,
|
|
462
|
-
|
|
463
|
-
if (closed || turnController.signal.aborted) return;
|
|
464
|
-
pending.answer = partial;
|
|
465
|
-
modal.setText(transcript());
|
|
466
|
-
},
|
|
510
|
+
showBackendProgress,
|
|
467
511
|
);
|
|
468
512
|
if (closed || turnController.signal.aborted) return;
|
|
469
513
|
if (result.expiredContinuation) {
|
|
@@ -471,17 +515,15 @@ export async function openBtwModal(
|
|
|
471
515
|
// transcript AND its captured main-session context (the local `context` is undefined
|
|
472
516
|
// whenever a continuation existed), and run once more so nothing is silently lost.
|
|
473
517
|
thread.conversationId = undefined;
|
|
518
|
+
stage = "Restoring side thread";
|
|
519
|
+
updateProgress();
|
|
474
520
|
modal.setNotice("Side thread expired — reseeded from the transcript and session context.", "warning");
|
|
475
521
|
const reseeded = await runBtwTurn(
|
|
476
522
|
buildBtwPrompt(thread.context, question, { full, history: formatBtwTranscript(thread.turns.slice(0, -1)), preferences }),
|
|
477
523
|
selection,
|
|
478
524
|
{ full, cwd: ctx.cwd },
|
|
479
525
|
turnController.signal,
|
|
480
|
-
|
|
481
|
-
if (closed || turnController.signal.aborted) return;
|
|
482
|
-
pending.answer = partial;
|
|
483
|
-
modal.setText(transcript());
|
|
484
|
-
},
|
|
526
|
+
showBackendProgress,
|
|
485
527
|
);
|
|
486
528
|
result = reseeded;
|
|
487
529
|
}
|
|
@@ -496,6 +538,7 @@ export async function openBtwModal(
|
|
|
496
538
|
pending.answer = `_${errorMessage(error)}_`;
|
|
497
539
|
modal.setNotice(errorMessage(error), "error");
|
|
498
540
|
} finally {
|
|
541
|
+
stopProgress();
|
|
499
542
|
if (controller === turnController) controller = undefined;
|
|
500
543
|
if (activeTurn === work) {
|
|
501
544
|
if (closed || turnController.signal.aborted) discardUnfinished();
|
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) {
|