Repository navigation
fix(agent-runtime): expose user/global ~/.claude settings to Claude SDK - #8
Merged
SawyerHood merged 1 commit intoMay 14, 2026
Merged
Conversation
Restricting the Claude Agent SDK's settingSources to ["project"] hid the user's global ~/.claude configuration (settings.json, CLAUDE.md) from bb-managed sessions. Mirror the CLI cascade by loading user, project, and local sources so global home configuration is respected alongside workspace settings, while HOME still flows through the bridge so the SDK can locate ~/.claude on disk. Co-Authored-By: Claude Opus 4.7 <[email protected]>
SawyerHood
marked this pull request as ready for review
May 14, 2026 22:10
ymichael
added a commit
that referenced
this pull request
Oct 30, 2026
## Human comments ## What was wrong Several cache owners wrote a server reply or the thread-detail bootstrap straight into the React Query cache with `setQueryData` while a fetch of the same key could still be in flight. React Query writes fetch results without checking whether they're older than what's cached (query-core `query.ts`), so the older fetch landed last and put stale data back. Effects included: an environment or host status that stayed stale after opening a thread, a plugin settings form resetting its draft to the old value, a cancelled plugin install flipping back to running, new plugin update jobs dropping out of the list, an `idle` app update phase switching off the progress poll, and the AI service selection flickering back. These are items #2–#10 from the direct cache write audit (@thread:thr_fjr5x8dzaz). #1 (thread tabs) is fixed separately in #6611. ## What changed Two fixes, depending on whether the data has a version field: - **Environment and Host keep the newer copy by `updatedAt`** (#2, #3, #10). The bootstrap ingest (`thread-detail-cache-owner.ts`), the rename reply (`applyEnvironmentUpdateResult`), and the `useEnvironment`/`useHosts` fetches all compare `updatedAt`. The fetch-side check is what catches a fetch that started before the write and lands after it. To make it testable, those fetches now live in `environmentQueryOptions` and `hostsQueryOptions`. Host `status` comes from live daemon sessions and a disconnect doesn't change `updatedAt`, so on a tie the cached copy wins over the bootstrap. The bootstrap only fills an empty cache or replaces strictly older data. Rename replies and fetch results still win ties. - **`setQueryDataOverInFlightFetch`** (`cache-effect-utils.ts`) for data with no version (#4–#9): it writes the value, and if a fetch of the key is in flight it cancels that fetch (the cache keeps the written value) and refetches. With nothing in flight it's a plain write. Used by `applyPluginSettingsView`, `applyPluginInstallJob`, `applyPluginUpdateJob`, `hydrateAppUpdateStatus`, `hydrateSystemVersionCache` and `writeCachedAiServices`, so every caller gets the fix. Where the audit suggested an unconditional cancel-write-invalidate (#7) or a cancel before the write (#8, #9), this helper refetches only when a fetch was actually in flight. That avoids an extra request on every write. Forced version and app-update checks update the server's cache, so the trailing unforced refetch returns the forced result. No wire, CLI or plugin API changes. Not covered here: audit items #11 (plugin safe mode) and #12 (prompt history), both low risk. Also not covered: a lint rule restricting direct `setQueryData` calls to the helper, which would stop new call sites from bringing the race back. ## How you verified - New tests use real `QueryClient`/`QueryObserver` instances: start a fetch that resolves late with older data, do the write, let the fetch land, then check that the newer value survives (and, for the helper, that the trailing refetch runs). - `thread-detail-cache-owner.test.ts` (new): late environment and host-list fetches after a bootstrap, an older bootstrap over a newer cache, and the equal-`updatedAt` host status case. - `environment-workspace-cache-owner.test.ts`: a late environment fetch after a rename, and an older rename reply over a newer cache. - `in-flight-fetch-writes.test.ts` (new): one row per cache-owner write for #4–#9, plus helper tests for the no-fetch case (no extra request) and a fetch of an unobserved query. - With each source change reverted, every race test failed on the stale data and passed once the fix was restored. - `pnpm exec turbo run typecheck lint test --filter=@bb/app`: passed (647 files, 6515 tests; 0 lint errors, no new warnings). After rebasing onto `0472409243` I re-ran the three changed test files (21 tests passed). 🤖 Generated with [Claude Code](https://claude.com/claude-code) > AGENT GENERATED --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 5, 2026
… exists (#7067) ## Human comments ## What was wrong `getWorkspaceGitOperation` ran `git --no-optional-locks status --porcelain=v1 --untracked-files=all` on every call, even though it only uses that output for `hasConflicts`, and it returns `hasConflicts` only when a rebase/merge/cherry-pick/revert marker exists in the git dir. All three callers also run the same status themselves to get `hasUncommittedChanges`, so every call did two full status walks in parallel: - `host.inspect_git_source` (`apps/host-daemon/src/command-handlers/host-branches.ts`), used by the branch picker and project routes - `inspectCheckout`, and the `attachCheckout` readiness check, in `plugins/environment-project-checkout/host/checkout.ts` This is finding #8 in the Nov 4 hot-path audit, which looked for hot paths doing more work than their caller needs (after 1a8de2d). The duplicate is still present on origin/main 7775a0f. ## What changed `packages/environment-provider-host/src/workspace-git.ts`: `getWorkspaceGitOperation` checks the marker files first and reads status only when it finds one. In the usual case, with no operation in progress, each caller now runs one status instead of two. During an operation the result is computed exactly as before. The return values don't change, so the wire format is the same: no `HOST_DAEMON_PROTOCOL_VERSION` bump and no plugin SDK change. ## How you verified Benchmark on the real `~/Projects/bb` checkout (4,477 local branches, 123 worktrees, clean tree, git 2.50.1). The script calls the real `inspectHostGitSource` handler and the plugin's `inspectCheckout`, counting git processes through a logging `git` shim on `PATH`. It ran main then branch, alternating for 6 rounds of 20 calls each, after one warm-up call and an 8 s wait so the background remote refresh wasn't included. The host was loaded (load average 15–28), so the absolute times are noisy, but the branch was faster than main in every round. | | main | branch | |---|---|---| | `inspectHostGitSource` git spawns/call | 17 (2 × status) | 16 (1 × status) | | `inspectHostGitSource` p50, median of 6 rounds | 305 ms | 216 ms | | `inspectHostGitSource` per-round p50 | 381 / 259 / 219 / 237 / 381 / 352 | 279 / 188 / 203 / 228 / 303 / 205 | | `inspectCheckout` git spawns/call | 7 (2 × status) | 6 (1 × status) | | `inspectCheckout` p50, median of 6 rounds | 131 ms | 93 ms | | `inspectCheckout` per-round p50 | 167 / 96 / 135 / 142 / 128 / 110 | 99 / 83 / 93 / 92 / 127 / 81 | On its own, a single status on this checkout takes about 80 ms. The two calls ran concurrently and competed for the same index and worktree scan, so the saving is larger than one call running alone would suggest. Targeted tests: `pnpm exec turbo run typecheck test --filter=bb-environment-provider-host --filter=@bb/host-workspace --filter=bb-plugin-environment-project-checkout` passed: 12/12 tasks, and the existing `getWorkspaceGitOperation` tests (no operation, merge conflicts, rebase conflicts) pass. CI runs the full suites. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 5, 2026
…h -unormal (#7100) ## Human comments ## What was wrong This is the rest of finding #8 in the Nov 4 hot-path audit; #7067 did the first part. Two problems remained: - **Dirty check lists every untracked file.** `hasUncommittedChanges` (`packages/environment-provider-host/src/workspace-git.ts`) ran `git status --untracked-files=all`, which lists every file inside untracked folders. Every caller only needs yes/no: - `host.inspect_git_source` → `hasUncommittedChanges: boolean` → the branch picker's `dirty` flag - project-checkout `inspectCheckout` → `server.ts` `if (inspection.hasUncommittedChanges)` - the `assertSwitchable` guard in `attachCheckout` - **The same repo questions are asked several times per call.** `host.inspect_git_source` (`apps/host-daemon/src/command-handlers/host-branches.ts`) asked: - "is this a repo" 4 times (`detectGitRepoKind`, then again inside `getCheckoutRef`, `readDefaultBranchRefs` and `hasRef`) - `--git-common-dir`, `--absolute-git-dir` and `--git-dir` once each, as separate processes - "does `origin/main` exist", then rev-parsed `main` and `origin/main` again for the relation check The project-checkout inspect and attach paths (`plugins/environment-project-checkout/host/checkout.ts`) had the same pattern. On `~/Projects/bb` each git process costs about 15 ms. ## What changed - **`--untracked-files=normal` for the status read** (`readPorcelainStatus`). It gives the same yes/no: an untracked folder shows as one `dir/` entry, and empty or ignored-only folders are still hidden. The same read checks for conflicts during a rebase, merge, cherry-pick or revert. Conflicts only involve tracked files, so the untracked mode doesn't change that answer. - **New `readGitRepo(cwd)` → `GitRepo | null`.** It runs one `rev-parse --is-inside-work-tree --is-bare-repository --git-dir --absolute-git-dir --git-common-dir` and returns `{ path, kind, gitDir, commonDir, isLinkedWorktree }`: - `gitDir` and `commonDir` are resolved exactly as `getAbsoluteGitDir` and `getGitCommonDir` resolve them. - `isLinkedWorktree` uses the same `--git-dir` "/worktrees/" test as the old `detectLinkedWorktree`, which this deletes along with its `@bb/host-workspace` export. - `detectGitRepoKind` and `ensureGitRepo` now use it; `ensureGitRepo` returns the `GitRepo`. - **These functions now take the `GitRepo` instead of re-detecting:** - `readCheckoutRef(repo)` (`getCheckoutRef(cwd)` keeps its detect-then-read behaviour) - `getWorkspaceGitOperation(repo)` (uses `repo.gitDir`) - `refreshRemoteBranches(repo, …)` (uses `repo.commonDir`) - `readDefaultBranchRefs(repo)` - **`readDefaultBranchRefs` makes one `for-each-ref` call** for `refs/remotes/origin/HEAD` plus `refs/heads|refs/remotes/origin` × `main|master`, with their oids and symref. It replaces `symbolic-ref` + `for-each-ref` + `hasRef` (detect + `show-ref`) + 2 × `rev-parse`. It queries more refs only when needed: - origin/HEAD names some other branch - neither main nor master exists locally - origin/HEAD is missing or dangling: it falls back to `symbolic-ref`, so a dangling origin/HEAD still picks the same local branch as before (new test) - **Callers updated:** - the `inspect_git_source` and `inspect_git_checkout` handlers - `listBranchOptions` - project-checkout `inspectCheckout` and `attachCheckout`: they read the repo once; `locateBranch` is one `for-each-ref`, and its result is passed from `planSwitch` to `assertSwitchable` instead of being looked up again - worktree `resolveWorktreeBaseBranch`: `ensureGitRepo` then `readDefaultBranchRefs`, the same process count as before - **No wire change.** Results are identical, so there is no `HOST_DAEMON_PROTOCOL_VERSION` bump. `bb-environment-provider-host` is internal, so there is no plugin SDK change. ## How you verified **Benchmark on the real `~/Projects/bb`** (4,490 local branches, clean tree, git 2.50.1, on `main` = `origin/main`): - The script calls the real `inspectHostGitSource` handler and the project-checkout plugin's `inspectCheckout` and `attachCheckout`. The `attachCheckout` call targets the branch already checked out, so it runs plan + assert and exits as already-current without switching. - Git processes are counted with a logging `git` shim on `PATH`. - main (a detached `origin/main` worktree outside this checkout) and the branch alternated for 6 rounds of 20 calls each. Each round started with a warm-up call and an 8 s wait so the background remote fetch wasn't counted. - Every call returned the same result on main and on the branch. - Load average ranged from 4 to 22, and rounds 3–4 ran during a spike, so the table uses the median of the six per-round p50s. | | main | branch | |---|---|---| | `inspectHostGitSource` git spawns/call | 15 | 5 | | `inspectHostGitSource` p50 (median of rounds) | 182 ms | 92 ms | | per-round p50 | 177 / 174 / 661 / 295 / 187 / 177 | 95 / 186 / 403 / 89 / 88 / 89 | | `inspectCheckout` git spawns/call | 6 | 4 | | `inspectCheckout` p50 (median of rounds) | 87 ms | 90 ms | | per-round p50 | 86 / 84 / 570 / 100 / 87 / 87 | 86 / 516 / 365 / 87 / 87 / 94 | | `attachCheckout` (no-op) git spawns/call | 10 | 7 | | `attachCheckout` p50 (median of rounds) | 169 ms | 104 ms | | per-round p50 | 152 / 159 / 592 / 197 / 166 / 172 | 92 / 315 / 423 / 100 / 100 / 108 | Git processes per `inspectHostGitSource` call on the branch: 1. `rev-parse` (repo facts) 2. `symbolic-ref HEAD` 3. `rev-parse --verify HEAD` 4. one `for-each-ref` 5. `status -unormal` `inspectCheckout` time doesn't change. Its two dropped `rev-parse` calls ran in parallel with `status` (~80 ms), which still sets its wall time; the change saves process CPU there, not latency. **`-uall` vs `-unormal`:** the bb checkout was clean, so its numbers don't show the untracked-files saving. I measured it separately on a throwaway `origin/main` copy with 5,000 untracked files in 20 untracked folders, taking the median of 15 runs each: - `-uall`: 72 ms, 5,000 output lines - `-unormal`: 62 ms, 1 line Same yes/no answer. The gap grows with untracked tree size. **Tests:** - New: `hasUncommittedChanges` with nested untracked folders vs empty or ignored-only folders. - New: `readDefaultBranchRefs` with a dangling origin/HEAD. - The `detectLinkedWorktree` test became a `readGitRepo` test covering a linked worktree, an ordinary checkout, a bare root and a plain folder. - The existing `readDefaultBranchRefs`, `getCheckoutRef`, `getWorkspaceGitOperation` and project-checkout attach tests pass. - `pnpm exec turbo run lint typecheck test --filter=bb-environment-provider-host --filter=@bb/host-workspace --filter=bb-plugin-environment-project-checkout --filter=bb-plugin-environment-git-worktree --filter=@bb/host-daemon --only`: 12/12 tasks pass. CI runs the full suites. **Left out:** - **`tryWithCheckoutMutationLock` still runs its own `rev-parse --absolute-git-dir`**, so `attachCheckout` makes 7 git calls rather than 6. The lock reads the git dir inside its admission lock, and the worktree plugin's teardown also uses it. Passing a known git dir in would change the shared lock API for one process. - **`readCheckoutRef` stays 2 processes** (`symbolic-ref` + `rev-parse --verify HEAD`, run in parallel). Folding `HEAD` into the repo `rev-parse` makes the whole command fail in an unborn repo, so it would need a fallback path. - **Finding #8's "~4 repeated rev-parse checks" in other `hasRef` callers** (worktree `base-branch.ts`, `worktree.ts`) are not on the inspect/attach paths, so they're unchanged. - **The background remote refresh's `fetchRemoteBranches`** still calls `ensureGitRepo` once per 30 s throttle window. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 24, 2026
…n one host call (#8121) ## Human comments ## What was wrong Finding #8 of the server→daemon RPC audit. Two separate problems made creating a project-default worktree thread slow on a remote machine. First, the create request inspected the project checkout twice, one after the other. `resolveProjectDefaultThreadEnvironment` called `host.inspect_git_checkout` to choose the worktree provider. Provider placement then called `resolveGitCheckoutAvailability`, which sent the same RPC for the same path again. Its dedupe only covers calls that are in flight at the same moment, and these two run in sequence. Second, the worktree plugin's warm-pool handoff made separate plugin host calls in a row: `readRemoteBase`, then `checkPoolMember`, then `fastForward` when the member was behind the remote base, then `nameHandedOffBranch`. ## What changed - **Server: one checkout inspection per create request.** `createGitCheckoutInspector(deps)` (`services/environments/provider-availability.ts`) memoizes `host.inspect_git_checkout` per (host, path) for one request. - `thread-create.ts` creates one and passes it to both `resolveCreateThreadEnvironment` and `resolveThreadEnvironmentPlacement`. Placement's `validateProviderSelection` reuses the result through `gitCheckoutAvailability()`. - Every other `completeProviderSelection` caller gets a fresh inspector, so its behavior is unchanged. - The TTL-cached machine-availability path keeps its in-flight dedupe. - **Worktree plugin: one `claimPoolMember` host call** replaces `readRemoteBase`, `checkPoolMember` and `fastForward` (`host/handoff.ts`, `contract.ts`, `warm-pools.ts`, `server.ts`). - The claim reads the remote base. When the server passes the base from an earlier claim, the claim of the next candidate reuses it instead. - It then runs the same check under the ref lock, and fast-forwards the member when it is behind the base. - The server still owns reservation, discard and adopt policy. It still reserves one member at a time, so two creates running at once still get different members. - Failure handling, because the claim can now move the checkout: - A member whose fast-forward fails is refused and discarded. Before, the create failed after adopt. - If adopt fails after the claim moved the member, the member is discarded. Its setup ran against the old commit, so it must not go back into the pool. - A claim call that throws (disconnect, abort, or still running after 15 minutes) discards the member, because it may have moved. - Folder worktrees (from #8065, merged in): once the main worktree's claim succeeds, each folder worktree is claimed with `claimPoolMember` too, all at once, reusing each folder's remote base for the next member. This replaces the separate `readRemoteBase`, `checkPoolMember` and `fastForward` calls per folder. A member whose folder claim is busy, timed out or has no readable base is kept only when none of its worktrees moved; otherwise it is deleted. - Time limits: reading the base and checking the member get 15 s together, as before. The server passes that budget as `checkTimeoutMs` and the host applies it to those steps only. When it runs out the claim returns `timed-out`, the member is kept and a fresh worktree is built. The fast-forward is not under that budget: the call gets the create's 15-minute timeout, the limit the fast-forward had before. - A remote base that can't be read returns `base-unavailable`. The member is kept and a fresh worktree is built, as before. - `nameHandedOffBranch` stays a separate call. It needs `branchName()`, which waits for the thread title to settle. - **Docs:** `plugins/environment-git-worktree/README.md`, `docs/worktrees.md`, and the `experimental_` adopt entry in `docs/api_to_audit.md` now describe the new order. - **No daemon wire change.** `claimPoolMember` is a plugin host method, and its code ships to the daemon in the plugin artifact. Core protocol commands are untouched, so `HOST_DAEMON_PROTOCOL_VERSION` is not bumped. ## How you verified **Real servers, main vs this branch, same input.** - Setup: `pnpm start` for main (`40b8939`) and for this branch, each on its own `/tmp` data dir. Each server had a second enrolled daemon behind a TCP proxy that adds 100 ms each way (200 ms RTT). The proxy decodes the daemon WebSocket frames and logs each `host-rpc.request`/`response`. - The project's only checkout was on that remote machine, with a warm pool of size 1. - Each round waited for a ready member, then `POST /api/v1/threads` with `environment: {type: "project-default"}`, and polled until the environment was `ready`. - 8 rounds per case, with main and branch interleaved. - "Behind base" means a new commit was pushed to the remote just before the create, so the member had to fast-forward and run setup again. | 200 ms RTT remote machine | main | branch | |---|---|---| | `POST /threads` response, median (min–max) | 470 ms (458–477) | **240 ms** (236–252) | | host RPCs awaited in the create request | 2 (`inspect_git_checkout` ×2) | **1** | | environment ready, member at base | 1458 ms (1425–1585) | **1056 ms** (1018–1170) | | environment ready, member behind base | 2044 ms (2002–2225) | **1396 ms** (1378–1653) | | warm-claim host calls before adopt (at base / behind) | 2 / 3 | **1 / 1** | | all host RPCs from create to ready (at base / behind) | 8 / 9 | **6 / 6** | Sequences seen in the proxy log. A background `provider.list_models` refresh is left out because the request doesn't await it. - main, at base: `inspect_git_checkout > inspect_git_checkout > readRemoteBase > checkPoolMember > nameHandedOffBranch > …` - branch, at base: `inspect_git_checkout > claimPoolMember > nameHandedOffBranch > …` - main, behind: `… readRemoteBase > checkPoolMember > fastForward > nameHandedOffBranch > environment.hook.run …` - branch, behind: `… claimPoolMember > nameHandedOffBranch > environment.hook.run …` On the local primary daemon (no proxy, 6 interleaved rounds), the create response went from a 56 ms to a 38 ms median. Time to ready was unchanged within noise: 206 vs 206 ms at base, 386 vs 374 ms behind base. **Tests** - `public-threads.project-default.test.ts` now asserts that a branch checkout is inspected exactly once. It fails on main, which inspects twice, and passes here. - `warm-pools.test.ts`: - covers the new call order; - checks that a refused member's claim passes its base on to the next candidate, so the remote is read once; - checks that a member the claim moved is discarded when adopt is refused, and that a member whose claim timed out is discarded. - `host.test.ts` runs `claimPoolMember` against real git repos: usable, fetch then fast-forward, refused after a rewritten base, offline fallback, used placeholder, and busy lock. - It also checks that a check that runs out of time returns `timed-out` and leaves the member alone, and that a fast-forward slower than the check's budget still finishes. That second test fails when the fast-forward is put back under the check's budget. - **Folder worktree, real server.** A project with one extra repository and a warm pool that branches it. After a new commit landed only in that repository, the thread got the warm worktree, the folder claim moved the folder from 1b44b75 to 0d4e22c, setup ran again, and both worktrees were renamed to the thread's branch. The steps shown match main's wording. - **Slow fast-forward, real server.** A `post-merge` hook that sleeps 20 s stands in for a slow fast-forward in a large repository. Before the timeout fix, the create waited 15 s, the claim hit its deadline, the member was discarded and a fresh worktree was built. With it, the thread got the warm worktree after the 20 s fast-forward ("Moved the warm worktree from 3eb71f2 to 22a1ba1; setup runs again"), and no member was discarded. - Commands: - `pnpm exec turbo run typecheck lint lint:type-aware --filter=@bb/server --filter=bb-plugin-environment-git-worktree` - `vitest run` for the 5 affected server test files (204 tests) - the full worktree plugin suite (222 tests) > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
pushed a commit
that referenced
this pull request
Nov 25, 2026
…lability read (#8187) ## Human comments ## What was wrong A nested bb whose Account Pooler proxies to a parent pool decides per turn whether it can route through the parent, using `ParentAvailability` in `plugins/account-pool/src/parent-pool.ts`. `load()` gives the parent's `/availability` 2 s, and on any error or non-OK status returns `UNAVAILABLE_POOL`. `get()` caches that result for the full 30 s TTL, the same as a good answer. So one slow read from a busy parent takes the child off the pool for 30 s, and every turn that starts in that window runs with no pool credentials. On a child with no Claude login of its own, Claude Code answers `Not logged in · Please run /login` and Provider Retry skips the turn as not retryable. On one child this happened three times in a day, each time the parent's host was under heavy load. ## What changed - `plugins/account-pool/src/parent-pool.ts`: `ParentAvailability` remembers the last good availability. - A failed read keeps serving it, and the next read is tried after 5 s instead of 30 s. - Once reads have failed for 60 s in a row, the parent is reported unavailable and that answer is cached for the normal TTL, as before. A parent that has never answered is reported unavailable, and the read is retried after 5 s. - The read timeout goes from 2 s to 5 s. - `plugins/account-pool/src/parent-pool.test.ts`: three cases, all of which fail on `main`: - one failed read keeps the last good value and retries after 5 s; - a parent that stays down is reported unavailable after 60 s, then cached for the TTL; - a failed first read is retried after 5 s. - No wire, CLI or doc changes. ## How you verified - New tests on `main`'s `parent-pool.ts`: the 3 new tests fail with `expected { claude: false, codex: false } to deeply equal { claude: true, codex: false }`, and the other 13 pass. With the change: 16/16. - After the final commit: `pnpm exec turbo run typecheck lint test --filter=bb-plugin-account-pool --force` passed 10/10 tasks, with 14 test files and 402 tests passing. Lint reported 3 warnings, all in `app.tsx`, which this PR does not touch. `pnpm exec turbo run lint:type-aware --filter=bb-plugin-account-pool --force` passed 7/7 tasks with 0 warnings. `pnpm exec turbo run prepare:bundled --filter=bb-plugin-account-pool` passed 7/7 tasks. `oxfmt --check` passes on both files. - Standalone reproduction with real HTTP and the real clock. `ParentAvailability` uses the real `fetch` and the shipped TTL and timeouts against a local HTTP parent, and one `get()` per second stands in for a turn start. `main` and this branch ran side by side. One slow answer (request #2 answers in 8 s, then normal), on `main`: ``` [ 0.0s] parent: request #1 -> 200 {claude:true} [ 0.1s] child: turn start -> ROUTED (claude via parent pool) [ 30.2s] parent: request #2 answering in 8s [ 32.2s] child: warn could not read parent availability: The operation was aborted due to timeout [ 32.2s] child: turn start -> NOT ROUTED (turn runs with no login) after waiting 2003ms [ 62.3s] parent: request #3 -> 200 {claude:true} [ 62.3s] child: turn start -> ROUTED (claude via parent pool) summary: 43 turn starts routed, 30 not routed, 3 parent requests ``` With the change: ``` [ 0.0s] parent: request #1 -> 200 {claude:true} [ 0.1s] child: turn start -> ROUTED (claude via parent pool) [ 30.2s] parent: request #2 answering in 8s [ 35.2s] child: warn could not read parent availability: The operation was aborted due to timeout [ 35.2s] child: turn start -> ROUTED (claude via parent pool) after waiting 5003ms [ 40.2s] parent: request #3 -> 200 {claude:true} [ 70.4s] parent: request #4 -> 200 {claude:true} summary: 70 turn starts routed, 0 not routed, 4 parent requests ``` A parent that stays down (503 from 25 s on), on `main`: ``` [ 0.0s] parent: request #1 -> 200 {claude:true} [ 0.1s] child: turn start -> ROUTED (claude via parent pool) [ 30.2s] parent: request #2 -> 503 (down) [ 30.2s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 30.2s] child: turn start -> NOT ROUTED (turn runs with no login) [ 60.4s] parent: request #3 -> 503 (down) [ 60.4s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 90.5s] parent: request #4 -> 503 (down) [ 90.5s] child: warn could not read parent availability: parent availability returned HTTP 503 [120.7s] parent: request #5 -> 503 (down) [120.7s] child: warn could not read parent availability: parent availability returned HTTP 503 summary: 30 turn starts routed, 100 not routed, 5 parent requests ``` With the change, the child keeps routing for 60 s after the first failure, then reports the parent unavailable and goes back to reading every 30 s: ``` [ 0.0s] parent: request #1 -> 200 {claude:true} [ 0.1s] child: turn start -> ROUTED (claude via parent pool) [ 30.2s] parent: request #2 -> 503 (down) [ 30.2s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 35.2s] parent: request #3 -> 503 (down) [ 35.2s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 40.2s] parent: request #4 -> 503 (down) [ 40.2s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 45.3s] parent: request #5 -> 503 (down) [ 45.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 50.3s] parent: request #6 -> 503 (down) [ 50.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 55.3s] parent: request #7 -> 503 (down) [ 55.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 60.3s] parent: request #8 -> 503 (down) [ 60.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 65.3s] parent: request #9 -> 503 (down) [ 65.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 70.3s] parent: request #10 -> 503 (down) [ 70.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 75.3s] parent: request #11 -> 503 (down) [ 75.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 80.3s] parent: request #12 -> 503 (down) [ 80.3s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 85.4s] parent: request #13 -> 503 (down) [ 85.4s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 90.4s] parent: request #14 -> 503 (down) [ 90.4s] child: warn could not read parent availability: parent availability returned HTTP 503 [ 90.4s] child: turn start -> NOT ROUTED (turn runs with no login) [120.5s] parent: request #15 -> 503 (down) [120.5s] child: warn could not read parent availability: parent availability returned HTTP 503 summary: 90 turn starts routed, 40 not routed, 15 parent requests ``` <details><summary>repro.mts (run from the repo root as <code>node_modules/.bin/tsx repro.mts $PWD/plugins/account-pool/src/parent-pool.ts slow-once|down</code>)</summary> ```ts import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; const [modulePath, scenario] = process.argv.slice(2) as [string, "slow-once" | "down"]; const { ParentAvailability } = await import(modulePath); const TOKEN = "vqMIj4xUiI3PyvKS2SllSKHsOfxLF_sAZwzNAAvV9TQ"; const started = Date.now(); const t = () => ((Date.now() - started) / 1000).toFixed(1).padStart(5); let request = 0; const server = createServer((req, res) => { request += 1; const n = request; const elapsed = (Date.now() - started) / 1000; if (req.headers["x-bb-account-pool-token"] !== TOKEN) { res.writeHead(401).end(); return; } const answer = () => { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ claude: true, codex: false })); }; if (scenario === "slow-once" && n === 2) { console.log(`[${t()}s] parent: request #${n} answering in 8s`); setTimeout(() => { if (!res.destroyed) answer(); }, 8_000); return; } if (scenario === "down" && elapsed > 25) { console.log(`[${t()}s] parent: request #${n} -> 503 (down)`); res.writeHead(503).end(); return; } console.log(`[${t()}s] parent: request #${n} -> 200 {claude:true}`); answer(); }); await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)); const { port } = server.address() as AddressInfo; const availability = new ParentAvailability({ parent: { baseUrl: `http://127.0.0.1:${port}/api/v1/plugins/account-pool/http`, token: TOKEN }, fetch, now: Date.now, onError: (error: unknown) => console.log(`[${t()}s] child: warn could not read parent availability: ${error instanceof Error ? error.message : String(error)}`), }); const durationS = scenario === "slow-once" ? 75 : 130; let last: string | null = null; let routed = 0; let unrouted = 0; while ((Date.now() - started) / 1000 < durationS) { const before = Date.now(); const value = await availability.get(); const waited = Date.now() - before; if (value.claude) routed += 1; else unrouted += 1; const state = value.claude ? "ROUTED (claude via parent pool)" : "NOT ROUTED (turn runs with no login)"; if (state !== last || waited > 500) { console.log(`[${t()}s] child: turn start -> ${state}${waited > 500 ? ` after waiting ${waited}ms` : ""}`); last = state; } await new Promise((r) => setTimeout(r, 1_000)); } console.log(`summary: ${routed} turn starts routed, ${unrouted} not routed, ${request} parent requests`); server.close(); process.exit(0); ``` </details> - **Not checked:** an isolated nested bb against a slow parent bb end to end. The reproduction drives the same class the server constructs, with the same options except `onError`. Fixes #8188 > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
settingSources: [\"project\"], so the SDK silently dropped the user's global~/.claude/settings.jsonand~/.claude/CLAUDE.mdwhen loading settings for bb-managed sessions. Permission allowlists, model defaults, hooks, and global instructions defined per-user never reached the agent.[\"user\", \"project\", \"local\"]) so global home configuration layers in alongside the workspace's project/local settings.HOME(and the rest ofprocess.env) was already forwarded through the bridge to the SDK process, so no env wiring change is needed — only the explicit allowlist had to widen.Root cause
packages/agent-runtime/src/claude-code/bridge/sdk-session.tssetsettingSources: [\"project\"]when invokingquery(). The SDK treats this as an allowlist; the\"user\"source (~/.claude/...) is therefore skipped even thoughHOMEis available.Test plan
pnpm exec turbo run typecheck --filter=@bb/agent-runtimepnpm exec turbo run typecheck --filter=@bb/host-daemonpnpm exec turbo run test --filter=@bb/agent-runtime --force(465 passing)pnpm exec turbo run test --filter=@bb/host-daemon --force(255 passing)SdkSessionasserts the SDK is launched withsettingSources: [\"user\", \"project\", \"local\"].process.env.HOMEand the cascade reach the SDK viaquery()options onthread/start.🤖 Generated with Claude Code