Skip to content

[codex] Bundle Claude Code SDK CLI support file - #4

Closed
SawyerHood wants to merge 1 commit into
mainfrom
bb/investigate-claude-code-provider-bundling-thr_kdztsapzec
Closed

SawyerHood wants to merge 1 commit into
mainfrom
bb/investigate-claude-code-provider-bundling-thr_kdztsapzec

Conversation

@SawyerHood

Copy link
Copy Markdown
Collaborator

Summary

  • Copy the @anthropic-ai/claude-agent-sdk cli.js fallback support file beside the host-daemon Claude bridge bundle.
  • Extend bundle checking so the copied Claude Code CLI support file is syntax-checked and reported.
  • Add Turbo wiring for bundle:check so the package check can be run through the repo-standard Turbo path.

Root Cause

The bundled Claude Code bridge relocates SDK code into apps/host-daemon/dist, but the SDK fallback executable cli.js was not copied into that directory. When the SDK could not resolve a native platform package, its fallback lookup also failed, producing the reported native-binary error before review execution started.

Validation

  • pnpm exec prettier --check apps/host-daemon/scripts/bundle-manifest.mjs apps/host-daemon/scripts/build-bundles.mjs apps/host-daemon/scripts/check-bundles.mjs turbo.json
  • pnpm exec turbo run bundle:check --filter=@bb/host-daemon
  • pnpm exec turbo run typecheck --filter=@bb/host-daemon
  • pnpm exec turbo run test --filter=@bb/host-daemon
  • Direct bundled bridge thread/start repro returned a providerThreadId instead of the native-binary error.

@SawyerHood SawyerHood closed this May 15, 2026
SawyerHood pushed a commit that referenced this pull request Jul 30, 2026
## The problem

When you open a thread through bb connect, your browser has to talk to
your laptop through a long pipe that runs out to Cloudflare and back.
Every single question your browser asks down that pipe takes about **95
milliseconds** to get an answer, no matter how small the answer is.
That's just how long the trip takes.

So if you ask two questions one after the other, you wait ~190 ms. If
you ask them at the same time, you wait ~95 ms. The number of questions
matters way more than how big the answers are.

Opening a thread used to ask more questions than it needed to, and it
asked some of them in a line when they could have been asked all at
once.

## What this changes

**1. Stop waiting in line.** Loading a thread needs two things: the
thread itself, and its timeline. Neither one needs the other. But the
code asked for the thread, waited for the whole answer to come back, and
only then asked for the timeline. Now both go out at the same time.

**2. Stop asking twice.** Right after loading the thread, the app
immediately asked for the same thread again. Now it skips the second ask
if the first one just answered (within 5 seconds).

**3. Stop asking for things nobody looked at.** There's a "Parent"
dropdown in the thread sidebar. The app fetched the list of possible
parent threads on every thread open — even though most people never open
that dropdown. Now it only fetches when you actually click it. You'll
see a brief "Loading threads…" the first time, and a retry option if it
fails.

**4. Let answers be zipped.** The pipe had a rule that said "don't send
me compressed data." That rule made your laptop unzip everything before
pushing it through the pipe, so we shipped big uncompressed answers when
small zipped ones would do. That rule is gone.

## Did it actually work?

Yes for #1, barely for #4. I tested this against the real production
Connect — real Cloudflare, real tunnel, not a simulation.

**Asking both questions at once (change #1):**

| | how long |
|---|---:|
| Before (one after the other) | **255 ms** |
| After (both at once) | **141 ms** |

That's **114 ms faster, about 45%**. This is the change that matters.

**Zipping the answers (change #4):** barely moves the needle, ~0–10 ms.

The reason is boring: the answers are already small. Earlier work capped
how much timeline gets sent at once, so even the biggest threads on my
machine only produce 15–61 KB. Zipping shrinks that by 3–4×, which
sounds great, but the pipe moves data fast enough (~18 MB/s) that 40 KB
was never the problem. The 95 ms trip was.

Zipping still earns its place in two spots, though:
- On a slow connection (say hotel wifi at 10 Mbps), that same 40 KB *is*
worth ~35 ms per request.
- It turns the app's precompressed asset files back on. Those had been
silently disabled over Connect this whole time by the "don't send me
compressed data" rule, and they're much bigger than any API response.

**Bottom line: don't expect to feel the zipping on fast internet. Do
expect thread opens to feel snappier.**

## Things that will look different

- **A new "Parent: None" row.** If you have a project with only one
thread, the Parent row used to be hidden — the app knew there was
nothing to pick. Now it can't know that without asking, and asking is
the thing we're trying to avoid. So the row is always there for root
threads.
- **The Parent dropdown can be tabbed to** in a couple of cases where it
previously couldn't.
- **Re-opening a thread you've seen before** now asks "what's new since
X?" instead of "give me everything," and falls back to asking for
everything if the server can't answer that.

## The part to be careful about

To let zipped data through the pipe, I rewrote the piece of code that
forwards requests, swapping `fetch` for Node's lower-level HTTP client.
This touches **every** thing that goes through the tunnel — including
any dev server you've shared with `bb connect expose <port>`, not just
BB itself. It's the riskiest part of this PR.

Things that could have broken, and why they didn't:

- **Garbled responses.** Raw headers now get forwarded as-is, which is
dangerous if a "this data is chunked" header rides along with data
that's already been un-chunked. The relay already throws those headers
away (`apps/connect/src/tunnel-do.ts:44`), so it can't happen.
- **Wrong length.** A "this is 500 bytes" header on a body that isn't
500 bytes would break things. Checked both places that set it — they
always match what actually gets sent.
- **Redirects.** The old code told `fetch` not to follow them. Node's
client doesn't follow them anyway. Same behavior.
- **Reused memory.** The new code hands out views into Node's internal
buffer. Safe here, because it's copied out synchronously before Node can
reuse it.

No daemon protocol version bump needed — the wire format didn't change,
no worker code changed, and the already-deployed relay handles these
headers fine.

**One thing tests can't cover:** whether Cloudflare's runtime passes a
zipped response through untouched. I confirmed it by hand (step 2
below). Running it locally uses the same runtime but skips Cloudflare's
CDN layer, so local testing isn't a full substitute.

## How to check it yourself

Node 22, pnpm 9, clean checkout:

```bash
pnpm install --offline --frozen-lockfile
pnpm run ensure-native-modules
pnpm exec turbo run test typecheck --filter=@bb/tunnel-client --filter=bb-plugin-connect --force
pnpm exec turbo run test --filter=@bb/app --force -- src/hooks/cache-owners/cache-owner-registry.test.ts src/hooks/queries/thread-queries.test.tsx src/components/secondary-panel/ThreadMetadataContent.test.tsx src/views/thread-detail/ThreadDetailSecondaryContent.test.tsx
pnpm exec turbo run typecheck --filter=@bb/app --force
```

Then open DevTools → Network and load a thread through bb connect:

1. The thread and timeline requests start together, and the thread isn't
requested twice.
2. The timeline response has `content-encoding: gzip` and a
`server-timing: bb_connect_origin` header.
3. The Connect host log prints timing (`originTtfbMs`, `originBodyMs`,
`responseBytes`, `contentEncoding`).
4. Nothing requests parent candidates until you click **Parent**. First
click shows "Loading threads…", then the list.
5. A root thread in a project with no other threads shows the **Parent:
None** row.

## Tests

All green. Tunnel client 6/6, connect plugin 65/65, four focused app
suites 28/28, plus typechecks. The full GitHub matrix passes — app,
server, integration, packages, checks, and macOS/Linux smoke.

The new tests are the interesting ones. They check that the timeline
request really does leave before the thread request comes back, that a
warm cache asks for a delta and merges the answer correctly, that the
duplicate thread request is skipped when fresh but still happens when
stale, and that zipped bytes cross the tunnel byte-for-byte identical.
amadad pushed a commit to amadad/bb that referenced this pull request Aug 14, 2026
## The problem

When you open a thread through bb connect, your browser has to talk to
your laptop through a long pipe that runs out to Cloudflare and back.
Every single question your browser asks down that pipe takes about **95
milliseconds** to get an answer, no matter how small the answer is.
That's just how long the trip takes.

So if you ask two questions one after the other, you wait ~190 ms. If
you ask them at the same time, you wait ~95 ms. The number of questions
matters way more than how big the answers are.

Opening a thread used to ask more questions than it needed to, and it
asked some of them in a line when they could have been asked all at
once.

## What this changes

**1. Stop waiting in line.** Loading a thread needs two things: the
thread itself, and its timeline. Neither one needs the other. But the
code asked for the thread, waited for the whole answer to come back, and
only then asked for the timeline. Now both go out at the same time.

**2. Stop asking twice.** Right after loading the thread, the app
immediately asked for the same thread again. Now it skips the second ask
if the first one just answered (within 5 seconds).

**3. Stop asking for things nobody looked at.** There's a "Parent"
dropdown in the thread sidebar. The app fetched the list of possible
parent threads on every thread open — even though most people never open
that dropdown. Now it only fetches when you actually click it. You'll
see a brief "Loading threads…" the first time, and a retry option if it
fails.

**4. Let answers be zipped.** The pipe had a rule that said "don't send
me compressed data." That rule made your laptop unzip everything before
pushing it through the pipe, so we shipped big uncompressed answers when
small zipped ones would do. That rule is gone.

## Did it actually work?

Yes for get-bb#1, barely for get-bb#4. I tested this against the real production
Connect — real Cloudflare, real tunnel, not a simulation.

**Asking both questions at once (change get-bb#1):**

| | how long |
|---|---:|
| Before (one after the other) | **255 ms** |
| After (both at once) | **141 ms** |

That's **114 ms faster, about 45%**. This is the change that matters.

**Zipping the answers (change get-bb#4):** barely moves the needle, ~0–10 ms.

The reason is boring: the answers are already small. Earlier work capped
how much timeline gets sent at once, so even the biggest threads on my
machine only produce 15–61 KB. Zipping shrinks that by 3–4×, which
sounds great, but the pipe moves data fast enough (~18 MB/s) that 40 KB
was never the problem. The 95 ms trip was.

Zipping still earns its place in two spots, though:
- On a slow connection (say hotel wifi at 10 Mbps), that same 40 KB *is*
worth ~35 ms per request.
- It turns the app's precompressed asset files back on. Those had been
silently disabled over Connect this whole time by the "don't send me
compressed data" rule, and they're much bigger than any API response.

**Bottom line: don't expect to feel the zipping on fast internet. Do
expect thread opens to feel snappier.**

## Things that will look different

- **A new "Parent: None" row.** If you have a project with only one
thread, the Parent row used to be hidden — the app knew there was
nothing to pick. Now it can't know that without asking, and asking is
the thing we're trying to avoid. So the row is always there for root
threads.
- **The Parent dropdown can be tabbed to** in a couple of cases where it
previously couldn't.
- **Re-opening a thread you've seen before** now asks "what's new since
X?" instead of "give me everything," and falls back to asking for
everything if the server can't answer that.

## The part to be careful about

To let zipped data through the pipe, I rewrote the piece of code that
forwards requests, swapping `fetch` for Node's lower-level HTTP client.
This touches **every** thing that goes through the tunnel — including
any dev server you've shared with `bb connect expose <port>`, not just
BB itself. It's the riskiest part of this PR.

Things that could have broken, and why they didn't:

- **Garbled responses.** Raw headers now get forwarded as-is, which is
dangerous if a "this data is chunked" header rides along with data
that's already been un-chunked. The relay already throws those headers
away (`apps/connect/src/tunnel-do.ts:44`), so it can't happen.
- **Wrong length.** A "this is 500 bytes" header on a body that isn't
500 bytes would break things. Checked both places that set it — they
always match what actually gets sent.
- **Redirects.** The old code told `fetch` not to follow them. Node's
client doesn't follow them anyway. Same behavior.
- **Reused memory.** The new code hands out views into Node's internal
buffer. Safe here, because it's copied out synchronously before Node can
reuse it.

No daemon protocol version bump needed — the wire format didn't change,
no worker code changed, and the already-deployed relay handles these
headers fine.

**One thing tests can't cover:** whether Cloudflare's runtime passes a
zipped response through untouched. I confirmed it by hand (step 2
below). Running it locally uses the same runtime but skips Cloudflare's
CDN layer, so local testing isn't a full substitute.

## How to check it yourself

Node 22, pnpm 9, clean checkout:

```bash
pnpm install --offline --frozen-lockfile
pnpm run ensure-native-modules
pnpm exec turbo run test typecheck --filter=@bb/tunnel-client --filter=bb-plugin-connect --force
pnpm exec turbo run test --filter=@bb/app --force -- src/hooks/cache-owners/cache-owner-registry.test.ts src/hooks/queries/thread-queries.test.tsx src/components/secondary-panel/ThreadMetadataContent.test.tsx src/views/thread-detail/ThreadDetailSecondaryContent.test.tsx
pnpm exec turbo run typecheck --filter=@bb/app --force
```

Then open DevTools → Network and load a thread through bb connect:

1. The thread and timeline requests start together, and the thread isn't
requested twice.
2. The timeline response has `content-encoding: gzip` and a
`server-timing: bb_connect_origin` header.
3. The Connect host log prints timing (`originTtfbMs`, `originBodyMs`,
`responseBytes`, `contentEncoding`).
4. Nothing requests parent candidates until you click **Parent**. First
click shows "Loading threads…", then the list.
5. A root thread in a project with no other threads shows the **Parent:
None** row.

## Tests

All green. Tunnel client 6/6, connect plugin 65/65, four focused app
suites 28/28, plus typechecks. The full GitHub matrix passes — app,
server, integration, packages, checks, and macOS/Linux smoke.

The new tests are the interesting ones. They check that the timeline
request really does leave before the thread request comes back, that a
warm cache asks for a delta and merges the answer correctly, that the
duplicate thread request is skipped when fresh but still happens when
stale, and that zipped bytes cross the tunnel byte-for-byte identical.
albrand referenced this pull request in alb-hold/bb Sep 13, 2026
A thread keeps the PR of its branch forever, so a closed or merged one sat
in the banner indefinitely. On an unmanaged workspace that is worse than
untidy: 17 threads share ~/projects/meu-psi on branch dev, so every one of
them showed PR #4 - closed since - as if it were live work, and the thread
goes on to open more.

The banner now carries only an open or draft pull request. The uncommitted
section is untouched: the workspace's current state is what the banner is
for. A finished PR stays visible in the thread metadata panel, which is
where history belongs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
albrand referenced this pull request in alb-hold/bb Sep 14, 2026
A thread keeps the PR of its branch forever, so a closed or merged one sat
in the banner indefinitely. On an unmanaged workspace that is worse than
untidy: 17 threads share ~/projects/meu-psi on branch dev, so every one of
them showed PR #4 - closed since - as if it were live work, and the thread
goes on to open more.

The banner now carries only an open or draft pull request. The uncommitted
section is untouched: the workspace's current state is what the banner is
for. A finished PR stays visible in the thread metadata panel, which is
where history belongs.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
(cherry picked from commit 478bbe1)
ymichael added a commit that referenced this pull request Oct 7, 2026
## Human comments

## What was wrong

Prompt Library searches kept the browse layout: a **Starred** section
ranked by fuzzy score, then a **Recent** section ranked by fuzzy score.
A starred prompt therefore beat a better match, prompts that start with
the query could be buried under weaker substring matches (`Deploy
later…` and `deploy the preview…` were 6th and 7th of 8 for `deploy`),
and starred prompts appeared twice (once per section). Separately, each
search inserted a "Searching prompts…" row above the list, so the list
jumped down and back on every keystroke.

## What changed

- `plugins/prompt-library/ranking.ts`: `rankByQuery` marks prefix
matches (case-insensitive, whitespace-collapsed) and sorts prefix
matches first, then fuzzy score, keeping input order (recency) for ties.
`compareRank` is exported for merging.
- `plugins/prompt-library/server.ts`: with a query, starred and history
matches are merged into one list ranked by prefix, then score, then
starred, then recency; history rows whose text is starred are dropped so
each prompt appears once. Browsing (empty query) is unchanged: starred,
then recent.
- `plugins/prompt-library/contract.ts`: **`search` output changed** from
`{ starred, recent }` to `{ prompts }`, each row with `kind: "starred" |
"recent"`. This also changes `bb prompts search --json`. Text output
follows the same order.
- `plugins/prompt-library/app.tsx`: while searching, section headers are
hidden and rows are keyed by prompt text, so the selection follows a
prompt when starring/unstarring moves it. The status row is gone:
results stay in place during a search, the search icon becomes a spinner
only for searches slower than 300 ms, and the first "Loading prompts…"
message renders inside the empty list.
- CLI help, the skill (`SKILL.md`) and `PLUGIN_OVERVIEW.md` describe the
ranking and the new output shape.

## How you verified

- `pnpm exec turbo run test typecheck lint --filter='...[origin/main]'`
(prompt library and bundled plugins), plus `turbo run test
--filter=@bb/web -- src/marketplace`.
- New tests:
- `server.test.ts`: one test checks the full order (prefix + starred,
prefix + newer, prefix + older, fuzzy + starred, fuzzy + newer, weak
fuzzy match), including a capitalised prefix and removal of the
duplicate starred row.
- `app.test.tsx`: no section headers while searching, and the selection
follows an unstarred prompt. This test fails without the text-keyed
rows.
- `app.test.tsx`: results stay in place with no status row while a
search is pending, and the spinner appears only after 300 ms. This test
fails against the old status row.
- Manual QA on a `pnpm start:worktree` instance with seeded history:
- Source CLI: `bb prompts search` checks ranking, project and thread
scopes, multi-word queries, extra whitespace, no-match queries, the flag
constraint, and star/unstar round trips. Unstarring moves a prompt from
#4 to #6 and re-starring moves it back.
- Headless Chrome: the popup shows one list without headers. With
Ctrl+S, the selection follows the moved row; Tab switches scope; Enter
inserts the prompt.
- A per-frame sampler ran over 166 frames of typing and deleting: the
list's top never moved, and the old status text never appeared.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: qa <qa@x>
Co-authored-by: Claude Opus 5.5 <[email protected]>
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 24, 2026
…t read (#8119)

## Human comments

## What was wrong

Before every turn, and on every slash-menu open, the server makes one
`host.read_workspace_agent_context` RPC. That RPC returned the full text
of every project `.bb/skills/*/SKILL.md`, with a 32 MiB budget. The
server only runs `parseSkillMetadata` on each file to get `name` and
`description`. It then sends the skill to `turn.submit` as a
`workspace-path` source, so the provider reads the file from disk
itself. Every SKILL.md body made a daemon → server trip and was never
used. On the bb repo (9 project skills) that comes to 73 KB per turn.
This is finding #4 of the server → daemon RPC audit. I confirmed the
call pattern in
`apps/server/src/services/threads/workspace-agent-context.ts` and
`thread-runtime-config.ts` before changing anything.

## What changed

**Wire change: `HOST_DAEMON_PROTOCOL_VERSION` 281 → 282.**

- `host.read_workspace_agent_context`:
- The `kind: "file"` project skill entry now carries `frontmatter`
instead of `content`.
- `projectSkillRead.maxContentBytes` is renamed to
`maxFrontmatterBytes`.
- `skillFrontmatterBlock(content)` is new in `@bb/skill-index/metadata`,
next to `parseSkillMetadata`. It returns the file only through its
closing `---` delimiter. Parsing that block gives the same result as
parsing the whole file, because gray-matter's data and the
opening-delimiter check depend only on text before the first `\n---`
after the opener. A file with no `---` returns `""` and gets the same
"must start with a plain --- delimiter" error. An unterminated block
returns the whole file, as before.
- Daemon (`command-handlers/workspace-agent-context.ts`):
- It still reads each SKILL.md under the same 10 MiB per-file limit and
still reports `oversized`.
  - It returns only the frontmatter block.
- The total budget now counts JSON-encoded frontmatter, not file bodies.
- The daemon does no validation. That stays on the server, so the
AGENTS.md boundary holds: the daemon returns raw host data and the
server parses it.
- Server: sends `maxFrontmatterBytes: 4 MiB`, which is about 1,000
skills × 4 KiB, instead of 32 MiB. It parses `skill.frontmatter` with
the same `resolveProjectSkillSourceFromContent`. The budget-exceeded
warning now names the frontmatter budget.
- `docs/debugging-and-qa.md` ("Workspace Context Read Limits") describes
the new policy.

Not done (from the report's optional steps): the per-(host, workspace)
digest cache and daemon-pushed invalidation. The serial round trip
before `turn.submit` remains; only its payload shrinks.

## How you verified

**Tests**
- `packages/skill-index/test/metadata.test.ts` (new): for 16 SKILL.md
shapes, the block is a prefix of the file and
`parseSkillMetadata(block)` deep-equals `parseSkillMetadata(content)`.
The shapes are plain, CRLF, BOM, `---yaml`, an empty block, a `-----`
closer, a multiline description, unterminated, leading whitespace
(closed and unclosed), no opener, no delimiter at all, a `----` opener,
invalid YAML, `---` only, and empty.
- `apps/host-daemon/.../workspace-agent-context.test.ts`: asserts only
frontmatter is returned. A new budget case gives each file a 5 KB body
to show the body never counts against the budget.
- Updated the contract fixture and version assertions, plus the server
test fakes.
- `pnpm exec turbo run typecheck lint --filter=@bb/host-daemon
--filter=@bb/server --filter=@bb/host-daemon-contract
--filter=@bb/skill-index`
- `turbo run test` for `@bb/skill-index`, `@bb/host-daemon`
(workspace-agent-context), `@bb/host-daemon-contract`, and `@bb/server`
(thread-runtime-config, public-project-commands, skills/,
public-project-workspace-routing).

**Real servers, main (`af25b0b5a6`) vs this branch, same input**

Setup:
- Each build ran as `pnpm start --perf-diagnostics` on its own fresh
data dir under thread storage, never `~/.bb`.
- Each had its local daemon plus a second enrolled daemon
(`daemon-bundle.mjs`, separate data dir) behind a TCP proxy that adds
100 ms each way (200 ms RTT).
- The proxy decodes WebSocket frames to count `host-rpc.request`s and
response sizes per action.
- Every project points at the same detached checkout of `af25b0b5a6` (9
project skills, 70.6 KB of SKILL.md).
- Actions: 20× `GET
/projects/:id/commands?provider=claude-code&hostId=…` (slash menu), 1.5
s apart, and 8 real Claude Code (haiku) turns per host via `POST
/threads/:id/send`. Turn timings come from the server's `Turn trace`
log.

| action | host | host RPCs per action (main → branch) | agent-context
response (main → branch) | wall time median / p90 (main → branch) |
|---|---|---|---|---|
| turn send | local | 2 → 2 (`read_workspace_agent_context`,
`turn.submit`) | — | agent-context RPC 6.7 / 10.4 → 5.5 / 7.4 ms; send →
`turn.submit` sent 35.3 / 45.2 → 34.5 / 49.5 ms |
| turn send | 200 ms RTT | 2 → 2 | **73,022 → 3,331 B** (−95%) |
agent-context RPC 212.9 / 238.9 → 214.9 / 218.1 ms; send → `turn.submit`
sent 251.5 / 272.5 → 253.1 / 279.3 ms |
| slash menu | local | same as remote | — | 32.5 / 69.7 → 20.3 / 27.8 ms
|
| slash menu | 200 ms RTT | 2 in 16/20 → 15/20 (`list_commands`,
`read_workspace_agent_context`); `plugin.host.call` and
`provider.list_commands` join on cache expiry, same on both | **73,022 →
3,331 B** | 220.8 / 423.4 → 225.5 / 427.6 ms |

- Compressed sizes: the proxy connects over loopback, so the server
declines WebSocket compression and the byte counts above are
uncompressed. With the server's deflate level 1, the captured payloads
are 29,078 B (main) and 1,404 B (branch).
- Output parity:
- The slash-menu response for the remote host is identical: 87 entries,
deep-equal, including every project skill's description.
- The `turn.submit` request is 19,755 B on both builds, so the agent
gets the same skill sources.
- Wall time doesn't change: the proxy adds latency, not a bandwidth
limit, and the round trip is still serial. What this saves is ~70 KB of
tunnel transfer (~28 KB compressed) per turn and per slash-menu open on
this repo. It also caps skill-heavy repos at 4 MiB of frontmatter
instead of 32 MiB of bodies, and the server no longer JSON-parses the
bodies.

> 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
## Human comments

## What was wrong

Opening the slash-command menu, listing skills, and opening one skill
each cost several serial host round trips. Before every native-root scan
the server made a separate `plugin.host.call resolveNativeRoots`, cached
for 10 s, and only then sent `host.list_commands` / `host.list_skills`.
The skills index also sent one `host.list_skills` per visible provider
plus one for shared roots. Opening a skill rebuilt that whole index
twice, once for content and once for files, just to map a skill id to a
path. On a Connect-tunnelled host each serial wave costs ~200 ms (audit
findings #2 and #3, `thr_ejgucea7p3/report.md`). Finding #4,
frontmatter-only project skill reads, is handled in a separate thread.

## What changed

- **Daemon wire change, `HOST_DAEMON_PROTOCOL_VERSION` 281 → 282.**
- `host.list_commands` now takes `{ cwd, provider: { providerId,
declaredRoots, resolver }, resolution: { contributedEnv, timeoutMs } }`.
- `host.list_skills` takes `{ cwd, providers: [...], sharedRoots,
resolution }` and returns `{ workspaceSkills, sharedSkills, providers:
[{ providerId, skills }] }`.
- `resolver` is `{ pluginId, generation, artifact }` or null. The daemon
calls the plugin's `resolveNativeRoots` in-process through its
`PluginHostManager`, inside the same request as the scan. It cancels
that call if the listing is cancelled. A failed, malformed, or
unavailable answer falls back to the declared roots with a warning, as
the server did before.
- **Server policy stays on the server**
(`services/providers/native-roots.ts`): which providers are scanned,
which plugin resolves, the host env, and a 10 s resolver cap that leaves
the scan time inside the first retry attempt. The server-side
resolved-roots cache (`ProviderNativeRootsCache`) is deleted because
resolving is no longer a separate round trip.
- **Skills index** (`services/skills/skill-listing.ts`):
- One batched `host.list_skills` replaces the per-provider calls and the
separate shared-roots call.
- `.bb/skills` is scanned once instead of once per provider. It is now
also listed when no provider has native roots.
  - Server-owned skills load in parallel with the host call.
- A per-(host, cwd) index memo (`@bb/async-cache`, 5 min) is refreshed
by every listing. Content and file reads resolve the id from it and
rebuild once only for an id the last listing didn't have. Writes and
deletes always rebuild first. Plugin settings changes clear it.
- **Docs:** `docs/api_to_audit.md` and the
`experimental_nativeRootsHostContract` JSDoc now say the daemon resolves
per listing, uncached. Plugin SDK bumped to 0.6.197 for the JSDoc
change.

## How you verified

Measured on two real servers, main at merge base `af25b0b5a60` vs this
branch, each with a fresh data dir (no `~/.bb`). Each server had a
second enrolled daemon behind a TCP latency proxy adding 100 ms each way
(~200 ms RTT). The proxy strips `permessage-deflate` from the daemon's
upgrade, reads server→daemon frames, and counts `host-rpc.request`s.
Input was the same bb checkout (9 `.bb/skills`, real `~/.claude` etc.)
and `provider=claude-code`, with 8 samples per action after warm-up.

Remote host (~200 ms RTT): median wall time / host RPCs per action

| action | main | branch |
|---|---|---|
| slash menu, cold (>10 s since last) | 437 ms / 3 (resolver →
`list_commands`, ‖ `read_workspace_agent_context`) | 233 ms / 2 |
| slash menu, warm | 222 ms / 2 | 233 ms / 2 |
| skills list, cold (>10 s since last) | ~527 ms / 13 (6 resolvers → 7
`list_skills`) | ~310 ms / 1 |
| skills list, warm (resolver cache hit on main) | 364 ms / 7 | 404 ms /
1 (steady-state resample: ~300–320 ms on both) |
| open one skill (content + files in parallel) | 584 ms / 16–22 (two
index rebuilds + read + list) | 219 ms / 2 (`read_file` ‖ `list_files`)
|

Local host (primary daemon, no proxy), median:

| action | main | branch |
|---|---|---|
| slash menu, cold / warm | 22 / 19 ms | 21 / 19 ms |
| skills list | 119 ms | 115 ms |
| open one skill | 167 ms | 17 ms |

The warm slash menu still makes 2 RPCs in one parallel wave:
`host.list_commands` and `host.read_workspace_agent_context`. Folding
the second one in overlaps finding #4's change to that command, so it is
left for that thread. Every action is now a single wave. The remaining
~100 ms over RTT on the skills list is server-side index work
(`listServerSkills` hashing), not host traffic.

Tests:
- `apps/server/test/public/public-project-skills.test.ts` adds "opens a
listed skill with one host read…". It asserts that a listing is one
`host.list_skills`, that content + files after it are exactly
`host.read_file` + `host.list_files`, and that an unknown id re-lists
once. It fails on main, where every open re-lists.
- `apps/host-daemon/src/command-handlers/list-skills.test.ts` covers the
batched handler with a fake plugin host: the `.bb/skills` root is listed
once, shared roots and resolved roots are scanned, a throwing /
malformed / missing runtime falls back to declared roots with a warning,
and cancelling the listing cancels the resolver call.
- `native-roots.test.ts`, the commands, workspace-routing and contract
tests are updated to the new wire shape.
- `pnpm exec turbo run typecheck lint --filter=@bb/server
--filter=@bb/host-daemon --filter=@bb/host-daemon-contract
--filter=@get-bb/plugin-sdk --filter=@bb/integration-tests` passes. So
do the targeted vitest runs above, plus `tests/integration`
`native-roots-golden`. 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 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant