Skip to content

Add bb account endpoints, tunnel tickets, and the AI gateway - #4227

Merged
SawyerHood merged 11 commits into
mainfrom
bb/account-stack-1-hosted
Sep 24, 2026
Merged

SawyerHood merged 11 commits into
mainfrom
bb/account-stack-1-hosted

Conversation

@SawyerHood

@SawyerHood SawyerHood commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

A bb server had no general identity on getbb.app. bb connect paired with its own dashboard code and sent a long-lived raw credential to the tunnel gate on every dial, and nothing else could use that sign-in. There was also no hosted service a server could call for bb's small helper-model tasks (thread titles, branch names, commit messages), so those depended on each user's own Codex login.

This is the bottom of a four-PR stack. It ships only the hosted side, and every change is additive for servers already in the field.

What changed

  • connect-db migration 0006. connect_code.user_id becomes nullable, and new columns hold the server-link device-code flow (device_code_hash, client_name, polled_at, approved_at, denied_at). Two new tables: ai_usage_day and ai_request_log. Existing pairing codes keep their owner. migrations/README.md gives the deployment order.
  • Server credentials. resolveServerCredential and serverCredentialFromHeaders are the one place a server credential is checked.
  • bb-web.
    • Device-code sign-in: /api/account/link/start, /api/account/link/poll, and the /link approval page. It shows the requesting server's name and claims a handle when the account has none.
    • /api/account/me returns the signed-in account and server.
    • /api/connect/tunnel-ticket mints a five-minute HMAC ticket (bbtkt_…, keyed by HKDF of BETTER_AUTH_SECRET).
    • /api/connect/machine-code-lookup looks up a machine code with the server credential.
    • The dashboard copy points at Settings → bb account.
  • Connect gate. It accepts a tunnel ticket in place of the raw credential. Raw credentials from older servers still work.
  • New bb-ai-gateway worker (apps/ai-gateway) on /api/ai/*.
    • POST /api/ai/v1/complete takes a prompt and returns text. GET /api/ai/v1/usage reports the day's spend.
    • Calls go to OpenRouter with zero data retention, data collection denied, latency sort, and no reasoning. AI_MODELS is a primary model plus fallbacks.
    • Each account gets 50¢ of model spend per UTC day. Spend is reserved and then settled in D1 with conditional updates, and requests are rate-limited. There is no worker-wide cap; total spend is bounded by the OpenRouter key's credit limit.
    • A nightly cron prunes request logs and usage rows older than 30 days.
  • deploy-ai-gateway.yml deploys the gateway on merges to main that touch apps/ai-gateway or connect-db. It mirrors deploy-connect.yml: same concurrency group, and it applies pending migrations first. It uploads OPENROUTER_API_KEY from the repository's Actions secrets with wrangler deploy --secrets-file, which also works for the first deploy.
  • pnpm cloud:dev runs the gateway next to the dashboard and gate. BB_CLOUD_DEV_AI_UPSTREAM_BASE_URL points it at a local fake model.

How you verified

  • turbo run typecheck lint test for @bb/connect-db, @bb/web, @bb/connect, @bb/ai-gateway: all pass. The new tests cover the migration against the 0005 schema, ticket mint and verify (expiry, tampering, wrong secret), device-code start, poll and approve, the ticket dial in the gate, and gateway metering (budget exhaustion, concurrent reservations at the limit, settle after an upstream failure, a single-model config).
  • wrangler deploy --dry-run --secrets-file with a JSON secrets file resolves the production gateway config and its secret binding.
  • Deployed to staging (vibecodethis.site) in order: migration 0006 on bb-connect-staging, then bb-web-staging, bb-connect-staging, and bb-ai-gateway-staging.
    • /api/account/me, /api/connect/tunnel-ticket, and /api/ai/v1/* answer 401 without a credential.
    • /link renders, and /api/account/link/start returns a device code.
  • Local end to end with pnpm cloud:dev: a server from main before this stack paired with the old dashboard code, dialed the gate with its raw credential (101), redeemed and used machine codes, and shared a port, all against the new hosted code.

Rollout: add the OPENROUTER_API_KEY Actions secret before merging. On merge, the three deploy workflows apply migration 0006 once and ship bb-web, the gate, and the gateway. All of this must happen before any bb release that includes the PRs above. The gateway's zone route (getbb.app/api/ai/*) needs a CI Cloudflare token that can edit Workers routes.

AGENT GENERATED

🤖 Generated with Claude Code

SawyerHood and others added 2 commits September 23, 2026 16:04
Hosted half of a single bb account sign-in for servers and a hosted
helper-model service.

- connect-db migration 0006: server-link device codes on connect_code
  (user_id nullable), ai_usage_day, ai_global_usage_day, ai_request_log.
- bb-web: /link approval page, /api/account/link/start|poll,
  /api/account/me, /api/connect/tunnel-ticket, and
  /api/connect/machine-code-lookup. Server credentials resolve through
  one shared helper.
- Connect gate: tunnels dial with a five-minute HMAC ticket; raw
  credentials from older servers keep working.
- New bb-ai-gateway worker on /api/ai/*: OpenRouter with ZDR and a
  model fallback list, $2/day per account and $50/day global, metered by
  reserve and settle in D1.
- pnpm cloud:dev runs the gateway locally, with an upstream override for
  fake-model testing.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
deploy-ai-gateway.yml mirrors deploy-connect.yml: it runs on pushes to
main that touch apps/ai-gateway or connect-db, shares the connect-db
concurrency group, applies pending D1 migrations, and deploys with
OPENROUTER_API_KEY from the repository's Actions secrets through
--secrets-file, which also works for the first deploy.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@SawyerHood
SawyerHood force-pushed the bb/account-stack-1-hosted branch from 6389efe to 047ec8f Compare September 23, 2026 23:04
SawyerHood and others added 9 commits September 23, 2026 16:09
AI_DAILY_BUDGET_MICROS drops to 500000 in both environments. The worker's
global daily cap, its AI_GLOBAL_DAILY_BUDGET_MICROS setting, and the
ai_global_usage_day table are removed; total spend is bounded by the
OpenRouter key's own credit limit. Migration 0006 is regenerated without
the table (it has not reached production).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The hosted side deploys before any bb release has bb account, so the
dashboard's bb account login command and Settings path would fail for
every existing bb. Restore the published bb connect --code command with
--server so staging dashboards still pair against staging.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
A ticket carried only the server id and expiry, so after Approve and
replace rotated the credential the old bb could keep redialing the tunnel
with saved tickets for five minutes. Tickets now carry a credential-hash
prefix, and the gate rejects any ticket whose prefix no longer matches the
server's current credential.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
GitHub keeps one pending run per concurrency group, so a connect-db merge
that queued web, connect, and the gateway in one group cancelled one of
the three deploys. The gateway now has its own group and no migration
step; web and connect already apply migrations, and no client calls the
gateway until a bb release ships. The workflow also redeploys when its
own file changes.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The /link page needs to show where a sign-in request came from, and a
poll whose response was lost needs to know which credential it delivered
so it can rotate it again safely. Migration 0007 adds both as nullable
columns; 0006 is already applied on staging, so this is a new generated
migration rather than an edit.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
link/start was the first unauthenticated endpoint that writes rows, with
no throttle and nothing deleting expired requests. It now goes through a
per-IP Workers Rate Limiting binding (429 rate-limited) and prunes a
bounded batch of unapproved requests that expired over an hour ago.

A pre-filled /link URL with an attacker-chosen client name could phish an
approval. Client names lose control and bidi-control characters, the page
shows when and from which city and country the request started, and
replacing a server that already has a bb requires typing the code the bb
shows, enforced on the server.

Polling checked expiry before approval, re-minted onto a server the user
had disconnected, and a lost response ended in 409 forever. Approved codes
now deliver even after expiry, delivery is refused once the server was
disconnected after approval, and a later poll inside the code's window
rotates a fresh credential while the server still holds the one last
delivered.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
An upstream timeout charged nothing and refunded the reserve even though
OpenRouter still bills a cancelled non-streaming call, and settlement ran
only if the request lived long enough, so a client disconnect or a thrown
error stranded the 5,000-micro hold until midnight. A call without a
reported cost is now charged the reserve whenever OpenRouter may bill it
(success, timeout, dropped connection, unreadable reply) and nothing only
for an error response. Settlement runs in a finally, and the worker keeps
the whole completion alive with ctx.waitUntil.

The upstream timeout drops to 4 s so replies land inside bb-ai's 5 s
fetch timeout instead of being billed and discarded. The body is read
with a byte counter so a chunked body cannot exceed 512 KiB,
whitespace-only prompts are rejected, and 429s are logged with the
rate_limited outcome.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@SawyerHood
SawyerHood marked this pull request as ready for review September 24, 2026 00:55
@SawyerHood
SawyerHood merged commit 900070d into main Sep 24, 2026
18 checks passed
@SawyerHood
SawyerHood deleted the bb/account-stack-1-hosted branch September 24, 2026 01:06
SawyerHood added a commit that referenced this pull request Sep 24, 2026
…#4228)

## Human comments

## What was wrong

bb's helper tasks (thread titles and the branch names built from them,
commit messages, voice transcripts) went through one model string per
task. `BB_INFERENCE`, `BB_INFERENCE_FALLBACK`, and `BB_TRANSCRIPTION`
held `<service>/<model>`, and the only way to set them was `bb-app
config`.

A plugin that wanted to serve these tasks had to implement a host RPC
contract on the primary machine and return structured error codes for
core's retry policy. Users had no UI to see or change which service did
what, and no way to pick their own plugin (an OpenRouter plugin, say)
for one task only.

Stacked on #4227 (hosted side). It does not depend on anything in that
PR.

## What changed

- **Plugin API (SDK 0.5.23).** `bb.experimental_aiServices.register({
id, displayName, complete?, transcribe?, status? })` takes plain
server-side functions.
  - `complete(prompt, { signal })` resolves to a string.
  - `transcribe(audio, { signal, hint })` resolves to a string.
  - `status()` reports `{ ready: true }` or `{ ready: false, message }`.
- bb owns the prompts and the reply cleanup; the plugin owns the model,
the API, and any retries.
- `@get-bb/plugin-sdk/ai-services` and its host contract are removed.
`docs/api_to_audit.md` is rewritten for the new shape.
- **Per-task choice.** Each of `thread-title`, `commit-message`, and
`voice` stores `automatic`, `off`, or `{ pluginId, serviceId }` in app
settings.
- Automatic walks the built-in services in order: `provider-codex`, then
`bb-ai`, which the top PR adds.
- A picked service is used alone, with no fallthrough to another. When
it fails, bb falls back as before: titles use the start of the prompt,
and commits say `bb: automated commit`.
- Status is cached for 10 s behind a 2 s timeout, so a slow plugin never
blocks config reads.
  - Calls time out at 5 s for text and 10 s for voice.
- **Surfaces.**
- Settings → AI services: one picker per task, like the sidebar pickers,
with a status line and a Test button.
- `GET /system/ai-services`, `PUT /system/ai-services/selection`, `POST
/system/ai-services/test`.
  - SDK: `system.aiServices`, `setAiServiceSelection`, `testAiService`.
- CLI: `bb settings ai-services show | set <task>
<automatic|off|service> | test <task>`.
- The guide, CLI skill, configuration docs, and plugin authoring
references are updated to match.
- **Codex.** The Codex plugin registers `codex` from its server entry.
It calls its own `bb.host` entry for the Codex CLI login on the primary
machine, trying `gpt-5.6-luna` then `gpt-5.4-mini` for text and
`gpt-transcribe` for voice.
- **Prompts.** The title and commit-message templates ask for plain
text. `cleanGeneratedLine` strips think blocks, code fences, labels,
quotes, and the `result(...)` and `<title>` wrappers some models add.
- **Removed settings.** `BB_INFERENCE`, `BB_INFERENCE_FALLBACK`,
`BB_TRANSCRIPTION`, and the `OPENAI_API_KEY` route are gone.
  - `bb-app config set` for one of them fails and names the replacement.
  - Existing managed config drops them with a warning.
  - `pi-ai` leaves `@bb/server`.

No server/daemon wire change, so `HOST_DAEMON_PROTOCOL_VERSION` is
unchanged.

## How you verified

- Repo-wide `turbo run typecheck lint`.
- `turbo run test` for every touched package: server, CLI, config, db,
domain, SDK, server-contract, plugin SDK, templates, bb-app, the Codex
plugin, the guide plugin, and demo-server. Also the app suite and the
integration harness test.
- New tests cover:
  - Automatic order and strictness (`ai-tasks.test.ts`);
- the status cache and throwing or invalid `status()` results
(`ai-service-registry.test.ts`);
  - reply cleanup (`ai-reply.test.ts`);
  - the picker (`AiServicesSettingsSection.test.tsx`);
  - declaration validation in the SDK;
  - the removed-setting paths in config and bb-app.
- `pnpm check:plugin-forks plugins/provider-codex` passes.
- Real model replies: bb cloud (the top PR) answered a title in 428 ms
and a commit message in 498 ms. A managed worktree got the branch
`bb/add-user-preference-dark-mode-toggle-…`, and the environment commit
was "feat: read theme from localStorage and support dark mode".

> AGENT GENERATED

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 24, 2026
## Human comments

## What was wrong

getbb.app sign-in lived inside the Connect plugin. The pairing code, the
stored credential, and the tunnel dial were all Connect's, so no other
plugin could use the bb account. A hosted service such as bb cloud AI
(the top PR) would have had to duplicate or reach into Connect's
credential.

Stacked on #4228 (AI services). It needs the hosted endpoints from
#4227.

## What changed

- **New built-in `bb-account` plugin.** It owns the server's getbb.app
credential and never returns it to callers.
  - Its discoverable RPC contract, `bb-account.v1`, has four methods:
    - `status`;
    - `waitForStatusChange`, a long poll keyed by a revision;
- `fetch`, which sends the credential to the fixed getbb.app origin,
only for `/api/` paths, with 1 MB caps and no redirects;
    - `adoptConnectCredential`.
  - Sign-in:
    - a browser device-code link through `/link`;
    - a pasted dashboard pairing code;
    - an upstream 401 signs the server out everywhere.
- CLI: `bb account status | login [--wait] [--code <code>] [--base-url
<url>] | logout`.
- A Settings page with the account, sign-in dialog, "Have a pairing
code?", and sign-out.
- **Connect moves onto bb account.**
- It dials the gate with a fresh five-minute ticket from
`/api/connect/tunnel-ticket` for every connection.
  - It tears the tunnel down on sign-out.
- It adopts an existing Connect credential on upgrade and deletes
Connect's copy, so paired servers stay paired.
- `bb connect off` and `bb connect on` stop and restart the tunnel while
the server stays signed in.
- `bb connect --code` still works, as an alias of `bb account login
--code`.
- Signed out, the Remote access page shows an inline "Sign in to your bb
account" card and the pairing-code form.
- Machine access and shares use bb account's `fetch`. The machine-code
lookup moves to `/api/connect/machine-code-lookup`.
- **Server import hold.** The hold after `bb server import` now covers
bb account as well as Connect, so a copied server can't use the
original's account or tunnel. `bb server allow-connect` lifts both.
- **`pnpm dev --staging`.** A source bb can sign in, open tunnels, and
call the gateway on the staging Cloud (`https://vibecodethis.site`). bb
account and Connect accept that exact origin, or a `bb.localhost` one,
only in development builds. As with local Cloud, the tunnel serves the
Vite dev app.
- Docs, the guide, the CLI skill, and verify-bb feature maps are
updated.

## How you verified

- `turbo run typecheck lint test` for `bb-plugin-bb-account`,
`bb-plugin-connect`, `@bb/server`, `@bb/cli`, and `@bb/scripts`.
- The new bb-account tests cover code and link sign-in, denial, expiry,
slow-down, cancellation, the fetch allowlist and caps, sign-out on
upstream 401, revision waits, legacy adoption, and the CLI and settings
UI.
- The Connect integration tests cover ticket dials, a fresh ticket per
reconnect, legacy adoption, sign-out teardown, `connect off` and `on`,
and `connect --code`.
- Trunk's "reacquires fresh access for the same host after release" test
is ported to the new harness.
- Old-client compatibility, end to end against the new hosted code:
- **An unmodified server from `main`:** it paired with the old redeem,
tunneled with its raw credential (101), listed servers, issued and
redeemed machine codes, dialed a machine credential, shared a port, and
loaded its app through the tunnel.
- **Upgrade:** copying that server's data to this build adopted the
credential, removed Connect's copy, kept the shares, and reconnected the
tunnel with tickets.
- New-client flow against local Cloud: link sign-in with a handle claim,
the tunnel, sign-out, and code sign-in.

> AGENT GENERATED

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 24, 2026
…unts (#4230)

## Human comments

## What was wrong

Thread titles, branch names, and commit messages only came from a model
when the user had the Codex CLI signed in. Everyone else got the start
of the prompt as a title and `bb: automated commit` as the commit
message.

Stacked on #4229 (bb account). It uses the gateway from #4227 and the AI
services API from #4228.

## What changed

- **New built-in `bb-ai` plugin ("bb cloud AI").**
- It registers the AI service `{ id: "bb", displayName: "bb cloud",
complete, status }`.
- `complete` posts to `/api/ai/v1/complete` through bb account's
`fetch`, so the plugin never holds a credential.
- `status` is ready while the server is signed in and the day's budget
remains. A 402 `budget_exhausted` marks it not ready until the next UTC
midnight, and Automatic moves on.
- **Automatic.** bb cloud joins the Automatic chain after Codex, so a
signed-in bb gets generated titles and commit messages with nothing else
set up.
- **Surfaces.**
  - CLI: `bb ai status` and `bb ai usage`.
- A settings section with readiness and today's usage against the 50¢
daily allowance.
- A skill, and the Plugin Guide's AI services card lists it as a
first-party example.
  - Voice stays with Codex for now.

## How you verified

- `turbo run typecheck lint test` for `bb-plugin-bb-ai` (10 tests),
`@bb/server` (builtin reconciliation and icons), and `@bb/scripts` (the
Plugin Guide first-party table).
- End to end against local Cloud with a real OpenRouter key and
`inception/mercury-2.5`: a thread title in 428 ms and a commit message
in 498 ms. A managed worktree got the branch
`bb/add-user-preference-dark-mode-toggle-…` from its generated title.
- Budget exhaustion: with the day's spend set to the limit in local D1,
an explicit bb cloud pick failed with "daily limit reached" and did not
fall through. `bb ai status` reported not ready, and `bb ai usage`
showed the day's spend at the limit.

> AGENT GENERATED

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 24, 2026
## Human comments

## What was wrong

The bb-connect gate deployed from #4227 (version `985dc695`, 2026-09-24
01:07 UTC) broke tunnels for every server, old releases included.
Tunnels opened, but the gate never answered their heartbeats: servers
logged `tunnel heartbeat missed` 60–80 s after every dial and redialed
forever. Across `*.getbb.app`, 503s went from a steady 9–10%
(00:00–01:05) to 25–32% (01:10–01:25) and peaked at 55–56%
(01:41–01:42); WebSocket upgrades roughly tripled from constant redials.
Rolling the gate back to `6f79c289` at 01:43 brought 503s back to 12–14%
within a minute. The root cause is not identified yet: the gate diff
only adds the ticket check before the tunnel is handed to the Durable
Object and does not touch heartbeats or routing.

`main` still carries that gate, so the next merge touching
`apps/connect/**`, `packages/connect-db/**`, or
`packages/tunnel-contract/**` would redeploy it. `main`'s bb clients
also dial with tunnel tickets that the rolled-back gate refuses, so
`main` can't be released as is.

## What changed

- Reverts #4230 (bb cloud AI), #4229 (bb account plugin, Connect on bb
account), and #4227 (account endpoints, tunnel tickets, AI gateway).
- **Keeps** `packages/connect-db` migrations 0006/0007, their snapshots
and journal entries, and `schema.ts`. Production D1 already has them,
and dropping them from the schema would make the next `db:generate` emit
a destructive migration.
- Keeps #4227's null-owner guards in `apps/web/src/server/api.ts`:
`connect_code.user_id` stays nullable, and production already has
ownerless `server-link` rows. Redeeming one as a pairing code or machine
code returns `invalid-code`.
- Keeps #4228 (AI services). `main` returns to its state right after
#4228 merged.

Rollout notes:
- Merging redeploys the web worker without `/api/account/*`, `/link`,
and `/api/connect/tunnel-ticket`. No released bb uses them.
- If `Deploy Connect` is enabled, merging redeploys a gate equivalent to
the live `6f79c289`.
- The deployed `bb-ai-gateway` worker is not removed by this PR; delete
it in Cloudflare if wanted.
- Any bb that ran `main` after #4229 had its Connect credential moved
into the bb-account plugin. On this code it starts signed out; pair it
again with `bb connect --code <code>`.

## How you verified

- `pnpm install --frozen-lockfile` passes with the reverted lockfile.
- `turbo run typecheck lint test` for `@bb/connect-db`, `@bb/web`,
`@bb/connect`, `bb-plugin-connect`, `@bb/bundled-plugins`,
`bb-plugin-plugin-api-docs`: pass.
- `turbo run typecheck lint --filter=@bb/server`: pass. Server
`test/services/plugins/builtin-plugins.test.ts` and `test/ai/*`: 95
tests pass.
- Production evidence for the incident and the recovery: Cloudflare zone
analytics (per-minute `edgeResponseStatus` for `*.getbb.app`), `wrangler
tail bb-connect`, and bee's server log. The bee log shows the pre-stack
build dropping every minute from 01:08:24.

> AGENT GENERATED

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

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 24, 2026
…rsions instead of deploying them

Re-lands the web half of #4227: /api/account/* (me, link start and
poll), the /link approval page, /api/connect/tunnel-ticket,
/api/connect/machine-code-lookup, and the connect-db helpers they use
(resolveServerCredential, tunnel ticket mint and verify). Everything is
additive; released bbs don't call any of it.

An approved link code can no longer replace a newer sign-in. Delivering
a link credential, re-pairing from the dashboard, and disconnecting a
server deny every other approved, undelivered link for that server, and
an approved code is delivered at most two minutes past its expiry.

This is also the first change in the stack that touches
packages/connect-db, which triggers Deploy Connect. That workflow
deployed every gate straight to 100% on merge, which is how the
2026-09-24 outage shipped. It now applies migrations and runs
`wrangler versions upload`, so a merge never moves gate traffic.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 24, 2026
… and roll the gate out gradually

The 2026-09-24 outage was not caused by the new gate's code. On
staging, redeploying the unchanged previous gate while tunnels were
connected reproduced it every time: any new deployment of bb-connect,
even a 0% split, orphans the hibernated tunnel WebSockets. The bb keeps
a socket nothing answers, visitors get 503, and while the object keeps
receiving requests every new dial into it is orphaned too. Only about 45
seconds without requests brings an object back, and busy servers never
get that.

- TunnelDO records when its tunnel opens and closes. When a visitor
  request, a tunnel dial, or the presence alarm finds no live tunnel
  socket although the last one never closed, it durably records a close
  and calls ctx.abort(). The restarted object closes the orphaned
  socket, the bb redials, and the tunnel is back in seconds. Objects
  from before this change are restarted once from their presence keys.
- The gate accepts a `bbtkt_` tunnel ticket in place of the raw
  credential when TUNNEL_TICKETS is "on" (the gate half of #4227).
  Production ships "off"; a refused ticket gets 401, which bb answers by
  dialing with its raw credential. Staging and local cloud dev run "on".
- Roll out Connect gate (workflow_dispatch) connects a canary, deploys
  an uploaded version at 0%, 5%, 25% or 100% with `wrangler versions
  deploy`, and requires the canary's tunnel to be back within 120 s and
  then hold. It rolls back if the canary fails, and reads each
  environment's canary settings without falling back to production's.
  @bb/connect-rollout holds the canary and the step planner.
- docs/connect-gate-rollout.md covers how Cloudflare assigns versions
  for a Worker with Durable Objects, why the first version with the
  restart must go straight to 100%, what to watch, and rollback.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 24, 2026
Re-lands the AI gateway from #4227: `POST /api/ai/v1/complete` and
`GET /api/ai/v1/usage` on bb-ai-gateway, metered at 50 cents per account
per UTC day against the connect-db usage tables, with `pnpm cloud:dev`
running it next to the dashboard and gate. Nothing in a released bb
calls it.

Deploy AI Gateway now runs when apps/ai-gateway, the connect-db source
it bundles (credential checks, schema), or its workflow changes. It no
longer runs on migration-only connect-db changes, which put it in the
same merge as web and gate deploys.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 24, 2026
… and roll the gate out gradually

The 2026-09-24 outage was not caused by the new gate's code. On
staging, redeploying the unchanged previous gate while tunnels were
connected reproduced it every time: any new deployment of bb-connect,
even a 0% split, orphans the hibernated tunnel WebSockets. The bb keeps
a socket nothing answers, visitors get 503, and while the object keeps
receiving requests every new dial into it is orphaned too. Only about 45
seconds without requests brings an object back, and busy servers never
get that.

- TunnelDO records when its tunnel opens and closes. When a visitor
  request, a tunnel dial, or the presence alarm finds no live tunnel
  socket although the last one never closed, it durably records a close
  and calls ctx.abort(). The restarted object closes the orphaned
  socket, the bb redials, and the tunnel is back in seconds. Objects
  from before this change are restarted once from their presence keys.
- The gate accepts a `bbtkt_` tunnel ticket in place of the raw
  credential when TUNNEL_TICKETS is "on" (the gate half of #4227).
  Production ships "off"; a refused ticket gets 401, which bb answers by
  dialing with its raw credential. Staging and local cloud dev run "on".
- Roll out Connect gate (workflow_dispatch) connects a canary, deploys
  an uploaded version at 0%, 5%, 25% or 100% with `wrangler versions
  deploy`, and requires the canary's tunnel to be back within 120 s and
  then hold. It rolls back if the canary fails, and reads each
  environment's canary settings without falling back to production's.
  @bb/connect-rollout holds the canary and the step planner.
- docs/connect-gate-rollout.md covers how Cloudflare assigns versions
  for a Worker with Durable Objects, why the first version with the
  restart must go straight to 100%, what to watch, and rollback.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 24, 2026
Re-lands the AI gateway from #4227: `POST /api/ai/v1/complete` and
`GET /api/ai/v1/usage` on bb-ai-gateway, metered at 50 cents per account
per UTC day against the connect-db usage tables, with `pnpm cloud:dev`
running it next to the dashboard and gate. Nothing in a released bb
calls it.

Deploy AI Gateway now runs when apps/ai-gateway, the connect-db source
it bundles (credential checks, schema), or its workflow changes. It no
longer runs on migration-only connect-db changes, which put it in the
same merge as web and gate deploys.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 24, 2026
…rsions instead of deploying them

Re-lands the web half of #4227: /api/account/* (me, link start and
poll), the /link approval page, /api/connect/tunnel-ticket,
/api/connect/machine-code-lookup, and the connect-db helpers they use
(resolveServerCredential, tunnel ticket mint and verify). Everything is
additive; released bbs don't call any of it.

An approved link code can no longer replace a newer sign-in. Delivering
a link credential, re-pairing from the dashboard, and disconnecting a
server deny every other approved, undelivered link for that server, and
an approved code is delivered at most two minutes past its expiry.

This is also the first change in the stack that touches
packages/connect-db, which triggers Deploy Connect. That workflow
deployed every gate straight to 100% on merge, which is how the
2026-09-24 outage shipped. It now applies migrations and runs
`wrangler versions upload`, so a merge never moves gate traffic.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 24, 2026
…with a canary

The gate half of #4227, plus the rollout tooling the 2026-09-24 outage
called for. The tunnel self-restart that fixed the outage itself landed
separately in #4268.

- The gate accepts a `bbtkt_` tunnel ticket in place of the raw
  credential when TUNNEL_TICKETS is "on". Production ships "off"; a
  refused ticket gets 401, which bb answers by dialing with its raw
  credential. Staging and local cloud dev run "on".
- Roll out Connect gate (workflow_dispatch) connects a canary, deploys
  an uploaded version at 0%, 5%, 25% or 100% with `wrangler versions
  deploy`, and requires the canary's tunnel to be back within 120 s and
  then hold. It rolls back with `wrangler rollback` if the canary fails,
  and reads each environment's canary settings without falling back to
  production's. It refuses to start while another split is deployed.
- @bb/connect-rollout holds the canary and the step planner. The canary
  holds a tunnel as a dedicated server, answers its own hostname
  through that tunnel, and with --recover-within redials after a drop
  and fails unless it is back in time.
- Deploy Connect's summary points at the workflow.
- docs/connect-gate-rollout.md covers why every deployment disconnects
  tunnels, how Cloudflare assigns versions for a Worker with Durable
  Objects (entrypoint per request, each object pinned per deployment),
  the steps, what to watch, and rollback (`wrangler rollback`, never
  `versions deploy <old>@100%`).

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 24, 2026
Re-lands the AI gateway from #4227: `POST /api/ai/v1/complete` and
`GET /api/ai/v1/usage` on bb-ai-gateway, metered at 50 cents per account
per UTC day against the connect-db usage tables, with `pnpm cloud:dev`
running it next to the dashboard and gate. Nothing in a released bb
calls it.

Deploy AI Gateway now runs when apps/ai-gateway, the connect-db source
it bundles (credential checks, schema), or its workflow changes. It no
longer runs on migration-only connect-db changes, which put it in the
same merge as web and gate deploys.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 29, 2026
## Human comments

## What was wrong

#4232 reverted the bb account stack after the 2026-09-24 connect gate
outage. This PR brings back the web half of #4227: the endpoints a bb
account client needs. It is the first layer of a four-PR stack that
re-lands #4227, #4229 and #4230 so each part can be deployed and rolled
back on its own. The re-land drops #4227's tunnel tickets, so the gate
itself doesn't change.

## What changed

- **bb-web** (from #4227, without the tunnel ticket endpoint):
- `/api/account/me`, `/api/account/link/start`, `/api/account/link/poll`
and the `/link` approval page;
  - `POST /api/connect/machine-code-lookup`;
- the dashboard's connect UI moved into `components/connect-ui.tsx`. The
pairing command it shows (`bb connect --code … --server …`) works for
released bbs and new ones.
- **Link approvals can't replace a newer sign-in** (SlopCop P1).
Delivering a link credential, re-pairing from the dashboard, and
disconnecting a server now deny every other approved, undelivered link
for that server. An approved code is delivered at most two minutes past
its expiry; before, it could be delivered at any time.
- **connect-db:** `resolveServerCredential`,
`serverCredentialFromHeaders`, `write-result`, and a `./testing` export.
Migrations 0006/0007 are already on `main`; this adds none.
- Nothing changes under `apps/connect`, the tunnel packages, or the
deploy workflows.

## How you verified

- `pnpm exec turbo run typecheck --filter="...[HEAD^1]"` and `test
--filter="[HEAD^1]"` on this layer alone: pass (connect-db, web,
connect).
- New `account.test.ts` cases, all four failing on the previous code:
- an approved, unpolled code is denied after a disconnect plus a newer
link;
  - it is denied after another link replaces the server;
  - it is denied after a dashboard re-pair;
  - it isn't delivered past the grace.
- Not changed, answered on the review: atomic delivery writes and an
index for the expired-link prune. Both are follow-ups.
- Staging (`vibecodethis.site`), last run 2026-09-25 02:40–03:07 UTC on
`main` with #4313: this web (`630823a5`) with `main`'s gate. A
released-style bb paired through it with a dashboard-style pairing code
(`Paired as sawyer — reachable at https://sawyer.vibecodethis.site`),
then upgraded, downgraded and signed in again on the new client (#4253).
`POST /api/connect/tunnel-ticket` answers 404. Rolling this web back to
the pre-stack version under the new client kept its tunnel and sign-in
(details in #4253). No `wrangler tail` was used.

## Rollout

1. Merge. **Deploy Web** ships bb-web to 100%. It only adds routes. This
PR touches `packages/connect-db`, so **Deploy Connect** also runs: it
applies no migrations (none are pending, checked against production D1
on 2026-09-25) and `wrangler deploy`s the gate. The gate's own code is
unchanged from production's (#4313, `000248de`); the connect-db
additions it bundles are unused by it. So connected bbs just reconnect
once; with #4313's visitor hold that is a short delay for visitors
(staging: 75/75 one-second probes returned 200, one held 3.1 s).
2. Watch for 10 minutes:
- bb-web 5xx on `getbb.app`, especially `/api/account/*` and
`/api/connect/*`;
- a dashboard pairing code still pairs a released bb (`npx -p
bb-app@latest bb connect --code <code> --server
https://<handle>.getbb.app`).

## Rollback

- Web: `pnpm --filter @bb/web exec wrangler rollback <previous> --name
bb-web -m "<reason>"`, where `<previous>` is the version `wrangler
deployments status --name bb-web` shows before the merge deploys
(`d929bb65-81be-4090-ad8e-70a6e9d46fd7` on 2026-09-29 16:54 UTC, `main`
at #4454). Once #4253 has shipped, a web rollback keeps those bbs
connected and signed in; only new sign-ins stop working until it rolls
forward.
- Gate: `pnpm --filter @bb/connect exec wrangler rollback
000248de-6a8b-4ca0-94f9-a7a27fe80b8f -m "<reason>"` (production's gate
before the merge).

Stack: 1 of 4. Base: `main`. Next: #4252.

> AGENT GENERATED

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

Co-authored-by: Claude Opus 5.5 <[email protected]>
SawyerHood added a commit that referenced this pull request Sep 29, 2026
## Human comments

## What was wrong

#4232 reverted the bb-ai-gateway worker with the rest of the bb account
stack. The deployed worker was left in place, but its source and deploy
workflow left `main`. It also used to deploy on every
`packages/connect-db` change, which put it in the same merge as the web
and gate deploys. Three workers shipping on one merge made the
2026-09-24 outage harder to read.

## What changed

- `apps/ai-gateway` is back unchanged from #4227:
- `POST /api/ai/v1/complete` and `GET /api/ai/v1/usage` on
`bb-ai-gateway`;
  - calls go to OpenRouter;
- metered at 50 cents per account per UTC day against the connect-db
usage tables;
  - a nightly cron prunes request logs.
- `pnpm cloud:dev` runs it next to the dashboard and the gate again.
- **Deploy AI Gateway** now runs when `apps/ai-gateway/**`,
`packages/connect-db/src/**` (the credential checks and schema it
bundles) or the workflow itself changes. It no longer runs on
migration-only connect-db changes, which put it in the same merge as the
web and gate deploys.

## How you verified

- `pnpm exec turbo run typecheck test --filter=@bb/ai-gateway` on this
layer: pass.
- Staging: this gateway deployed to `bb-ai-gateway-staging` (`c0cb8b9a`,
last on 2026-09-25) and served the bb-ai e2e in #4254: titles and commit
messages from bb cloud in about 0.6 s, metered against the daily budget.
- No bb calls the gateway until a release includes #4254.

## Rollout

1. The `OPENROUTER_API_KEY` Actions secret must exist. It already does
from #4227.
2. Merge after #4250. **Deploy AI Gateway** runs `wrangler deploy` for
`bb-ai-gateway` alone. The worker already exists in production from the
01:07 UTC deploy on 2026-09-24, so this replaces it with the same code.
3. Watch: `GET https://getbb.app/api/ai/v1/usage` answers 401 without a
credential; the worker shows no exceptions; OpenRouter spend stays flat
until the bb-ai release.

## Rollback

`pnpm --filter @bb/ai-gateway exec wrangler rollback
9cbac579-3396-4fb7-bc89-abac544419e4 -m "<reason>"` (production's
gateway on 2026-09-24), or delete the `getbb.app/api/ai/*` route.
Nothing released depends on it.

Stack: 2 of 4. Base: #4250.

> AGENT GENERATED

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

Co-authored-by: Claude Opus 5.5 (1M context) <[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