Skip to content

Ship a host-only artifact for enrolled machines - #2969

Merged
ymichael merged 1 commit into
mainfrom
bb/ship-host-only-machine-artifact-thr_9dvdk3y5xc
Sep 2, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/ship-host-only-machine-artifact-thr_9dvdk3y5xc

Conversation

@ymichael

@ymichael ymichael commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

The enrolled-machine installer and protocol updater consumed the same complete bb-app tarball as local and desktop installations. That artifact included the server, web application, SDK output, and dependencies a remote execution machine never launches, while the route exposed no content identity that could distinguish an identical unpublished build and safely avoid another download and npm install.

What changed

  • Add a dedicated Turbo bb-app#build:host package containing the host daemon, provider/plugin workers, reachable bundled CLI chunks, the bb, bb-app, and bb-host-daemon bins, and only host runtime dependencies. The source-tree route builds it directly; a packaged server materializes the equivalent host package from its full distribution for release compatibility.
  • Content-address generated tarballs by SHA-256 and publish the digest through a strong ETag and x-bb-artifact-sha256 while retaining /install/version and /install/bb-app.tgz. Conditional requests return 304 with no artifact bytes.
  • Make install.sh and protocol self-update verify the advertised digest, persist it only after a valid install, and skip downloading/running npm when the identical artifact is already installed. Legacy responses without the digest and the existing PATH/npm-registry fallbacks remain supported.
  • Split launcher artifact validation so daemon and CLI entrypoints do not require server/web assets. Keep the existing exact package version, bin names, enrollment flags, launchd/systemd paths, and update prefix.
  • Document the host-only distribution and update behavior. No public command or configuration changed, so no CLI guide surface changed.
  • HOST_DAEMON_PROTOCOL_VERSION remains 177 because the session, WebSocket, and host-RPC contracts are unchanged. The HTTP metadata is additive; new clients accept legacy servers without it and older clients ignore it.

Measured on macOS with Node 22.23.1 and warm npm dependencies:

Metric Full artifact Host artifact Reduction
Compressed tarball 39,602,419 B 1,236,936 B 96.9%
Unpacked tarball 177,646,835 B 5,877,691 B 96.7%
Files 2,063 43 97.9%
Forced Turbo build 53.83 s 13.09 s 75.7%
npm pack 16.20 s 0.28 s 98.3%
Fresh installed footprint 267,087,872 B 65,912,832 B 75.3%
Fresh install 5.20 s 0.77 s 85.2%

The old route transferred 39,602,419 bytes on every request. The new route transferred 1,236,936 bytes once and returned 304/zero bytes for the identical repeat. Two independent packs produced SHA-256 26e365744761a80d434052151181f311caa1d67ca2d24ef6724df814db6fb033.

How you verified

The new artifact, installer, route, and updater assertions fail against the previous full-package/no-digest behavior and pass with this change.

  • pnpm exec turbo run test --filter=@bb/server --force -- test/app/bb-app-artifact.test.ts test/app/install-machine-script.test.ts test/app/skeleton.test.ts — 43 tests passed.
  • pnpm exec turbo run test --filter=@bb/host-daemon --force -- src/protocol-self-update.test.ts — 15 tests passed.
  • pnpm exec turbo run test --filter=bb-app --force — 73 tests passed.
  • pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/host-daemon --filter=bb-app --force — 7 Turbo tasks passed.
  • pnpm exec turbo run build --filter=bb-app — 12 Turbo tasks passed.
  • pnpm exec turbo run build:host --filter=bb-app --force — 6 Turbo tasks passed.
  • Installed the exact 0.41.0 host tarball into a clean prefix and exercised all three bins.
  • Enrolled the packaged daemon against a fresh local server, observed connected status, and used its bundled bb machine list --json successfully.
  • Ran the real updater with npm: first install completed in 771 ms and persisted the verified digest; the identical second request returned 304 and completed in 5 ms without npm.
  • Upgraded an existing full private-prefix install in place: 267,087,872 B to 65,851,392 B in 1.15 s, with server/web payloads removed and all host bins working.
  • Verified shell syntax, Prettier, deterministic packing, artifact contents, response digest, and git diff --check.

Fixes #2968

AGENT GENERATED

@ymichael

ymichael commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

@slopcop

@ymichael

ymichael commented Sep 2, 2026

Copy link
Copy Markdown
Collaborator Author

End-to-end canary completed on the real mbp-intel SSH target.

  • Started an isolated protocol-177 server from this PR behind an SSH reverse tunnel; used unique remote data, daemon port 49932, and launch agent app.getbb.host-daemon.127-0-0-1-49931, leaving the existing enrollment untouched.
  • Ran the actual /install.sh without mocks. It downloaded the host artifact, installed 39 packages with npm, enrolled, replaced the temporary daemon with launchd, and reported the machine ready.
  • Confirmed remote /status was connected at protocol 177, the installed digest matched the PR artifact, and the packaged bb machine list --json worked.
  • Rebuilt the same temporary server and host artifact at protocol 178. The real protocol-177 daemon received the mismatch, downloaded and installed the new artifact through /install/bb-app.tgz, recorded a new digest, exited, and was restarted by launchd. The launchd PID changed from 73454 to 73894; the replacement reconnected with connected: true, protocolVersion: 178. Total observed mismatch-to-reconnect time was 35 seconds.
  • Reran the actual installer against the identical protocol-178 artifact. It reported The identical server host artifact is already installed, skipped download/npm, retained enrollment, and restarted the launch agent successfully.
  • The updater needed its existing 15-second forced-exit fallback because a PipeWrap remained active, then launchd recovered normally. This behavior predates the artifact change and did not prevent the update.
  • Removed the temporary launch agent, remote data, reverse tunnel, and local server data. Restored source and build outputs to protocol 177. The worktree is clean and bb machine show Intel --json remains connected with the original ymichael.getbb.app service.

@ymichael
ymichael force-pushed the bb/ship-host-only-machine-artifact-thr_9dvdk3y5xc branch from 1de8e61 to c8c70c3 Compare September 2, 2026 23:15
@ymichael
ymichael merged commit d352c56 into main Sep 2, 2026
15 checks passed
@ymichael
ymichael deleted the bb/ship-host-only-machine-artifact-thr_9dvdk3y5xc branch September 2, 2026 23:58
ymichael added a commit that referenced this pull request Oct 27, 2026
…d file transfer (#6331)

## Human comments

## What was wrong

Two server-to-daemon downloads still held the whole payload in memory,
and they skipped the verification that #6330 added for skills and
attachments.

- **Daemon self-update** read the host package with
`response.arrayBuffer()`. It checked the sha256 only if the server sent
`x-bb-artifact-sha256`. It then wrote `bb-app-update-<pid>.tgz` with
`writeFile`, which is not atomic and leaves a partial file behind if the
daemon crashes mid-write.
- **The install route.** `GET /install/bb-app.tgz` called `readFile` on
the whole tarball for every request.
- **Plugin host artifacts.** `fetchPluginHostArtifact` collected chunks
into one buffer of up to `HOST_ARTIFACT_MAX_BYTES` (256 MiB), so the
cache held two copies during a write. Every worker start or bridge
launch also read the whole cached `host.mjs` back and re-hashed it with
`readFile`.

## What changed

Both downloads now go through `writeVerifiedFile` from
`@bb/file-transfer` (added in #6330, moved into the package by #6335);
no parallel download code is added.

**Self-update** (`apps/host-daemon/src/protocol-self-update.ts`)
- Streams into `<dataDir>/host-package-download/bb-app.tgz.partial`
through `writeVerifiedFile` with a sha256 and an expected size. On
success it renames the file to `bb-app.tgz` and runs `npm install -g` on
it. The rename also gives npm the `.tgz` name it uses to recognize a
tarball.
- The download directory is cleared before each attempt and after it, so
a crash mid-download can't leave tarballs behind.
- **The digest is now required.** A 200 response without a valid
`x-bb-artifact-sha256` fails the attempt and nothing is installed.
- `content-length` becomes the expected size when present. There is also
a 1 GiB cap that rejects an oversized `content-length` before any bytes
are read.

**Install route** (`apps/server/src/server.ts`,
`apps/server/src/internal/host-artifact-response.ts`)
- `GET /install/bb-app.tgz` streams the file through the existing
`hostArtifactFileResponse`, which now takes the response headers as a
parameter. The plugin artifact route passes its own headers.
- Status codes, headers (`etag`, `x-bb-artifact-sha256`,
`content-length`, `content-type`, `cache-control`), the 304 path and the
response bytes are all unchanged.
- If the cached tarball is missing or has a different size than
recorded, the route returns the existing `host_package_unavailable` 500.

**Plugin host artifacts** (`server-client.ts`, `node-artifact-cache.ts`,
`plugin-host-artifact-cache.ts`, `plugin-host-manager.ts`)
- `fetchPluginHostArtifact` returns the response body as a stream after
the status and `content-length` checks. `readHostArtifactBytes` is
deleted.
- The cache writes `.staged-<uuid>.tmp` through `writeVerifiedFile` with
the digest, the byte length and the 256 MiB cap, then renames it into
place.
- It still retries a verification failure once. Network errors still
propagate. Partial files are always removed.
- **No re-hash of unchanged cache files.** A verified cache file is
remembered by `(dev, ino, size, mtimeNs, ctimeNs)`, mirroring #6330's
`SkillTreeRegistry`. The same racy-timestamp guard applies: a file whose
mtime or ctime is within 2 s of now is not remembered. A changed stat
key triggers a full re-hash; if that fails, the file is deleted and
downloaded again.
- Memo entries are dropped when stale digests are pruned, so there is at
most one per plugin.

### Compatibility (no `HOST_DAEMON_PROTOCOL_VERSION` bump)

The wire format is unchanged: same routes, request headers, response
headers and bytes.

- **Self-update across versions.** The download only starts when
`server.protocolVersion > HOST_DAEMON_PROTOCOL_VERSION`; an older or
equal server is refused before any download. So this daemon only ever
downloads from servers built after this change. Every server since #2969
(2026-09-02) sends `x-bb-artifact-sha256` and `content-length` on the
200, so requiring the digest cannot strand a daemon that is updating
from a newer server.
- **Older daemons against the new server.** They get byte-identical
responses with the same headers. Daemons from before #2969 ignore the
digest. Later ones verify it when present and send `if-none-match`,
which still gets a 304. `install.sh` and the Windows installer download
the same URL.
- **Plugin artifacts.** The server route is unchanged. The server's
`compress()` middleware gzips `text/javascript` and removes
`content-length`. The daemon already tolerated a missing
`content-length`, and it still verifies the exact byte length and digest
from the session payload.
- **Forward-compatibility limit.** The 1 GiB self-update cap is now
built into shipped daemons. The host package is about 1.4 MB today, but
a package over 1 GiB would need a manual install on older daemons.

## How you verified

**Tests**
- New `apps/host-daemon/src/node-artifact-cache.test.ts`:
  - streamed multi-chunk download
  - corrupt download: retried once, then fails with no files left
  - corrupt download followed by an intact retry
- oversized endless stream: reading stops at the expected length and the
generator is closed
- interrupted stream: the error propagates without a retry and no files
are left
- stat-key memo: hashes inside the racy window, stops hashing after it,
and a same-size tamper is re-hashed and re-downloaded
- `apps/host-daemon/src/protocol-self-update.test.ts` now uses
server-shaped responses and adds:
- one table of failure cases (digest mismatch, missing digest header,
body longer or shorter than `content-length`, connection reset
mid-body). Each asserts no install and no files left in the data dir.
  - an over-cap `content-length` that cancels the body before it is read
  - leftovers from an interrupted earlier attempt are cleared
- the installed file is the verified `bb-app.tgz`, never the `.partial`
- `apps/server/test/app/skeleton.test.ts` asserts the streamed
`content-length`, and that a cached tarball whose size changed returns
`host_package_unavailable`.

**Commands**
- `pnpm exec turbo run typecheck test --filter=@bb/host-daemon
--filter=@bb/server`:
  - typecheck passes for both packages
  - host-daemon: 849 passed, 12 skipped
- server: 3692 passed, 1 failed, in `builtin-plugins.test.ts` (builtin
plugin hot-reload, which this PR doesn't touch). It failed under load
average ~23. Run alone, a different test in that file failed once, then
the whole file passed twice.
- `oxfmt --check` and `oxlint` are clean on the changed daemon and test
files.

**Memory, measured on the real code paths**
- **Server side:** the real `createApp` install route (test harness) and
the real `registerInternalPluginHostArtifactRoutes` behind `compress()`,
served over HTTP with `@hono/node-server`.
- **Daemon side:** a separate Node process running the real
`createProtocolSelfUpdater` (stub `installTarball`; `/install/version`
rewritten to protocol+1) and the real
`createServerClient().fetchPluginHostArtifact` with
`ensureCachedPluginHostArtifact`.
- **Payloads:** the real files are this machine's cached host tarball
(1.4 MB) and the provider-claude-code `host.mjs` (2.1 MB). The 64 and
256 MiB payloads are those same files repeated.
- **Method:** "before" swaps in this PR's base versions of the 8 changed
source files. Each figure is the median of 3 fresh processes. Daemon
figures are `process.resourceUsage().maxRSS` growth during one download.
Server figures are peak `arrayBuffers` growth.

| payload | | self-update daemon peak RSS | install route server
arrayBuffers | plugin download daemon peak RSS | cached artifact reuse,
per call |
|---|---|---|---|---|---|
| real | before | +13.2 MiB | +2.7 MiB | +24.1 MiB | 1.77 ms (re-reads
and re-hashes 2.1 MB) |
| real | after | +11.9 MiB | +2.9 MiB | +23.0 MiB | 0.29 ms (stat only)
|
| 64 MiB | before | +225.2 MiB | +112.5 MiB | +166.9 MiB | 31 ms |
| 64 MiB | after | +64.7 MiB | +23.0 MiB | +62.6 MiB | 0.28 ms |
| 256 MiB | before | +809.8 MiB | +485.2 MiB | +572.6 MiB | 105 ms |
| 256 MiB | after | +76.0 MiB | +30.9 MiB | +63.4 MiB | 0.23 ms |

- **At today's sizes** the memory difference is within noise. The
visible gain is cached artifact reuse, which no longer reads and hashes
the file on every worker start.
- **At larger sizes** the old paths grow with the payload and the new
ones stay flat. The remaining ~64–76 MiB at 64 and 256 MiB is
fetch/undici buffering on loopback, not file contents.
- The first reuse call after a download still hashes once, because the
racy guard keeps a freshly written file out of the memo.

**Not changed**
- `apps/host-daemon/src/server-move/download.ts` has its own streamed,
verified download for server moves. It overlaps with `writeVerifiedFile`
and could be folded in separately.
- `bb-app-artifact.ts` still reads the packed tarball once per server
process to compute its digest. That happens at build time, not per
request.

> AGENT GENERATED

Co-authored-by: review <review@local>
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.

Ship a host-only artifact for enrolled machines

1 participant