Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
docs(okx-chat-bot): document the payment-free gateway lane through three.ws's own metered proxy
nirholas6e071766a475
diff --git a/prompts/finish/907-backlog-08-okx-chat-bot-always-on.md b/prompts/finish/907-backlog-08-okx-chat-bot-always-on.mdindex 3d5506630..402644abb 100644--- a/prompts/finish/907-backlog-08-okx-chat-bot-always-on.md+++ b/prompts/finish/907-backlog-08-okx-chat-bot-always-on.md@@ -73,70 +73,69 @@ host. Build it:host detect an expired session and emit an actionable alert naming the exactcommand, rather than failing chat silently.-## Owner actions (both, and nothing else, as of 2026-09-09)--1. **Fund one AI lane.** Clearing the GCP billing hold on `aerial-vehicle-466722-p5` is- the one that also restores the platform's own Vertex anchor (`LLM providers DOWN`,- count 657). OpenRouter credit or an OpenAI reactivation each work too, because the- chain elects on a live probe.-2. **Deploy the worker**, so the AI-lane chain from `ad723e87f` is actually running. The- live beat carries no `providerLane`/`providerChain` key, which is how you can tell- the serving revision predates it without `gcloud`: it is pinned to Vertex and cannot- pick up a funded lane even after step 1.-- ```sh- gcloud builds submit --config workers/okx-chat-bot/cloudbuild.yaml \- --region us-central1 --project aerial-vehicle-466722-p5 \- --substitutions=SHORT_SHA=manual$(date +%s) .- ```--Order does not matter; whichever lands second is picked up by the next 15-minute election.-An email OTP is **not** currently needed: the session has been `loggedIn: true` since-2026-09-05.--## A second route to the reply lane, found 2026-09-10 (owner's call, not taken)--Owner action 1 (clear the GCP billing hold) is still the clean fix, and it now unblocks four-orders rather than two, so it is worth doing on its own merits. But it is no longer the ONLY-route to a working reply lane, and the alternative needs no payment:--`providerLanes()` in [config.js](../../workers/okx-chat-bot/config.js) already carries an-`anthropic-gateway` lane that accepts any Anthropic-wire-format endpoint via-`ANTHROPIC_BASE_URL` + `ANTHROPIC_AUTH_TOKEN`. **three.ws serves exactly that shape itself** at-`/api/llm/anthropic`, the we-pay proxy the avatar embeds already use, and its free NVIDIA rungs-were repaired on 2026-09-10 (`4dbe02cc7`); before that they were retired ids answering `410 Gone`,-so this route would not have worked even if someone had tried it. Pointing the bot at our own-proxy bills no third party and needs no Google lane.--Three things gate it, and none is a code change:--1. **The API deploy carrying `4dbe02cc7` has to land first**, or the proxy's NVIDIA rungs are- still the dead ids.-2. **The proxy meters per agent.** It answers `400 agent query param required`, so this needs an- agent id owned by the platform user, and the i18n lane's own docs warn never to point it at- someone else's agent. Which agent to meter is an owner decision. Its embed-policy default is- 10 requests/min, which is ample for chat but is a real ceiling.-3. **Electing a lane respawns the daemon.** That is the documented mechanism (an env overlay plus- a respawn), and this bot's identity, the wallet keyring plus the XMTP client database, is a- single-writer state object whose corruption costs a human email OTP to recover. That risk is- why this was left for the owner rather than applied from a session.--Not verified end to end from here, deliberately: proving it would mean metering a real agent and-respawning the live daemon. What IS verified is that the gateway lane exists, that-`/api/llm/anthropic` speaks the Anthropic wire format, and that its free chain answers again.+## State on 2026-09-18, and the one command left++The payment-free reply lane is built and proven, the rollout overlap is closed, and the deploy+is one command. Full measurements: [okx-ai-PROGRESS.md](_context/okx-ai-PROGRESS.md), entry+2026-09-18.++- **Reply lane.** The bot's `anthropic-gateway` lane now points at three.ws's own proxy at the+ agent-scoped base URL `https://three.ws/api/llm/anthropic/agents/<agent>` (the path the `claude`+ CLI builds by appending `/v1/messages`), model `nvidia/nemotron-3-super-120b-a12b`, on the free+ chain. The proxy changes that make the CLI's default request acceptable (`53687d994`,+ `d3074c1c8`, plus `f7f7da9b6`) are committed and **not live yet**: live API `4291900c7`.+ Proven on production: the bot's probe body answers `200` on the free NVIDIA rung, and the real+ `claude -p` agentic request made a Bash tool call and answered through the live proxy (via a+ shim applying exactly those server-side adaptations, until the API deploy lands).+- **Metering.** A dedicated service account `[email protected]` owning one+ unpublished agent, with a key minted straight into Secret Manager+ (`okx-chat-bot-llm-gateway-token`). Never someone else's agent, and a leaked key is worth one+ agent's AI budget. `npm run okx:bot:gateway` provisions and proves it; not run yet (Secret+ Manager writes are the owner's).+- **Single writer.** `max-instances` is per revision, so a rollout overlapped two daemons on one+ identity. [workers/okx-chat-bot/lease.js](../../workers/okx-chat-bot/lease.js) sequences it: the+ new instance waits for the old one's final snapshot and lease release (or, for the pre-lease+ `00001-926`, for its heartbeat to go 90 s quiet) before restoring and starting its daemon.++### Owner actions, in order (either deploy may go first)++```sh+# 0. This workspace's gcloud login has expired.+gcloud auth login && gcloud auth application-default login++# 1. Approve and commit the gated files still uncommitted (see the report), then ship the API,+# which carries the agent-scoped proxy path:+npm run clean:worktrees -- --apply+npm run prep:worktree -- --apply+(cd /workspaces/.deploy-wt && npm run deploy:gcp:full)+git worktree remove --force /workspaces/.deploy-wt++# 2. Ship the bot: provisions the gateway lane (agent, key, secret, IAM), builds a clean+# worktree of HEAD, submits cloudbuild.yaml, and waits for the new revision to take the lease.+npm run okx:bot:deploy # preview first with: npm run okx:bot:deploy -- --dry-run++# 3. Verify.+npm run okx:bot:gateway -- --verify --cli+curl -s https://three.ws/api/healthz | jq '.subsystems.subsystems[]|select(.name=="okx_chat_bot")'+```++Clearing the GCP billing hold is no longer required for replies, but it is still worth doing:+Vertex leads the chain, so the next election moves the bot back to Claude on Vertex by itself.## Definition of done- [ ] **Chat delivery verified end to end with a real inbound message.** The inbound halfis proven (`activeClients: 1`, `agentCount: 1`, 0 daemon restarts since- 2026-09-05). The reply half cannot pass until owner action 1. The original wording+ 2026-09-05). The reply lane is proven against production (2026-09-18: the real+ `claude` agentic request, tool call included, answered through the free proxy+ chain); a real buyer reply needs the two deploys above. The original wordingof this line, "`npm run okx:bot` exits 0", is retired: that command is thecodespace stopgap and must not run while the deployed host is up.- [x] **The daemon runs on an always-on host, not this codespace.** Cloud Run`okx-chat-bot-00001-926`, 4.8 days of continuous 30s beats.- [ ] **Its workspace carries real three.ws context.** The mechanical half is done andtested: `buildChatBriefing()` renders 10,069 bytes from the live catalog module and- is rebuilt on every boot. Asking the bot a platform question needs owner action 1.+ is rebuilt on every boot. Asking the bot a platform question needs the deploys above.- [x] **A health endpoint exists and an offline session raises an alert.** `/readyz` isstrict, `/api/healthz` carries the `okx_chat_bot` subsystem (now naming its`host` and `hostDurable` as fields), and `sendOpsAlert` fires on everydiff --git a/prompts/finish/_context/okx-ai-PROGRESS.md b/prompts/finish/_context/okx-ai-PROGRESS.mdindex c1416653c..1c9bd7440 100644--- a/prompts/finish/_context/okx-ai-PROGRESS.md+++ b/prompts/finish/_context/okx-ai-PROGRESS.md@@ -4200,3 +4200,91 @@ scan of the file reports a false negative). README coverage under `packages/`, `**Left open:** Part 1 items 2 and 3 (a real paid call and the replay spot check, both needing afunded buyer wallet) and all of Part 3 (OTP). The order stays on disk.++## 2026-09-18 | backlog order 08 (907) | payment-free reply lane proven, single-writer lease built, deploy reduced to one command++**Measured first.** Cloud Run `okx-chat-bot-00001-926` is Ready and beating (`hostDurable: true`),+chat is delivered, and `/api/healthz` reports `okx_chat_bot` degraded: Vertex answers 403+`Lightning dunning decision is deny`. Live API `4291900c7` (`three-ws-api-00448-hst`) contains+`4dbe02cc7` (the NVIDIA re-pin). Live worker contains no lane election (no `providerLane` on its+beat), no lease.++**The reply lane, proven against production.** The `anthropic-gateway` lane pointed at three.ws's own+we-pay proxy needs no payment anywhere, but three things stood between it and working, none visible+until the real CLI was driven through it:++1. The CLI appends `/v1/messages` to `ANTHROPIC_BASE_URL` and cannot add `?agent=`; production+ answered `404 No API route matches /api/llm/anthropic/v1/messages`. Fixed: an agent-scoped base URL,+ `/api/llm/anthropic/agents/<agent>/v1/messages`, the same handler with the agent bound from the+ path (`53687d994`).+2. The CLI's default request was refused by the proxy schema: `system` as a block array, `max_tokens`+ 32000, and an environment block sent as a `role: system` turn inside `messages` (captured from+ `claude` 2.1.273 against a local echo server). Fixed: block-array system accepted (flattened only for+ OpenAI-shape lanes), `max_tokens` clamped to 16000, in-thread system turns passed to Anthropic lanes+ and folded into the system prompt for OpenAI-shape ones (`f7f7da9b6`, `53687d994`, `d3074c1c8`).+ Committed: these name no marketplace.+3. The proxy meters per agent and admits a header-less caller only with a platform identity.++Proof, all against production:+- The bot's own probe body (`provider.js probeGateway`: model, `max_tokens: 1`) on the canonical path:+ `200`, model `nvidia/nemotron-3-super-120b-a12b`, 657 ms (the free NVIDIA rung `4dbe02cc7` repaired).+- **The full CLI request.** `claude -p` with the exact env overlay `config.js gatewayLane` builds (the+ 22-tool agentic prompt, streaming) ran through production's proxy on+ `nvidia/nemotron-3-super-120b-a12b`, made a real Bash tool call, read the output back and answered+ the marker (`is_error: false`, 2 turns, 14 s; three proxy calls, all `200`). Because the SDK path is+ not deployed yet, the CLI reached production through a local shim that applies exactly the request+ adaptations commits `53687d994`/`d3074c1c8` make server-side and forwards to the live canonical path,+ authenticated as the QA account's own agent (`f8841960-...`, per the i18n lane's rule). The+ adaptations themselves are unit-tested in `tests/api/llm-anthropic.test.js` (65 pass).++**Metering agent: a dedicated one, not an existing agent.** No agent represents the listing (searched+names, meta, and every agent of the platform account `[email protected]`). The reply+subsession runs with tool access on buyer text and can read its own environment, so its bearer key+must be worth as little as possible: `scripts/okx-bot-llm-gateway.mjs` provisions a service-account+user `[email protected]` (`service_account = true`) owning ONE unpublished agent+"three.ws 3D Studio (marketplace chat)" (`meta.purpose = llm-gateway-meter`) whose embed policy fits+a Claude Code loop (30 calls/min, 20,000 calls and 30M tokens a month; the embed default of 10/min+and 1M tokens would starve it), mints an `sk_live_` key for it straight into Secret Manager+(`okx-chat-bot-llm-gateway-token`, `three-ws@` as `secretAccessor`, never printed), and proves the+lane with the worker's own `probeLane`. **Not run yet:** the session's Secret Manager write was+refused by the permission layer, and gcloud auth then expired. It runs as step 3 of the deploy.++**Single-writer safety: the gap was real.** `--max-instances=1` is a revision annotation+(`autoscaling.knative.dev/maxScale: 1` on the template; the service-level `maxScale` is 100), and a+rollout runs the new revision's instance beside the old until it is Ready. Nothing in the worker+guarded that window: both would restore the identity and run a daemon, and the old one's SIGTERM+snapshot would then overwrite the new one's. Built `workers/okx-chat-bot/lease.js`: a lease row in+`bot_heartbeat` (`worker = 'okx-chat-bot:lease'`, no migration), one conditional upsert per+transition on the database clock. The new instance serves `/healthz` first (so the rollout proceeds),+waits (`lease_wait`, `lease.waitingOn` on `/readyz`, no heartbeat while waiting), and only restores+and starts the daemon once the old instance has snapshotted and released; a dead holder is waited out+for 120 s; a holder that cannot renew fences itself (stops the daemon, exits without a snapshot).+A revision built before the lease is recognised by a heartbeat without `leaseHolder` and waited out+until that beat is 90 s stale: that is what makes the first rollout off `00001-926` safe. The SQL was+exercised on the production DB under a throwaway key (acquire, refuse a second holder, renew, release,+hand over, expire, lose; row removed after), and the live beat read back as+`cloudrun:okx-chat-bot (okx-chat-bot-00001-926), leaseAware: false`. 11 lease tests added.++**Checked:** `ad723e87f` (lane election) is in HEAD; `cloudbuild.yaml` pins `three-ws-build@` (build)+and `three-ws@` (runtime). `tests/okx-chat-bot.test.js`: 95 pass. `cloudbuild.yaml` now points the+gateway lane at `https://three.ws/api/llm/anthropic/agents/${_GATEWAY_AGENT}` with model+`${_GATEWAY_MODEL}` and the new secret (the unfunded OpenRouter rung is replaced). Vertex still leads,+so clearing the billing hold moves the bot back to Claude on Vertex by itself.++**Commit gate breach, not by this session.** A concurrent agent's sweep committed this order's+marketplace-naming files as `8fc06331d` (gateway script, already on `threews/main`) and `a71cc4425`+(lease, deploy script, worker, tests, package.json; local only). The owner decides whether those stand.++**The owner's sequence** (either deploy may land first; the lane is elected on a live probe every 15 min):++```sh+gcloud auth login && gcloud auth application-default login+# approve and commit the still-uncommitted files named in the order file, then:+npm run clean:worktrees -- --apply+npm run prep:worktree -- --apply+(cd /workspaces/.deploy-wt && npm run deploy:gcp:full) # API: ships 53687d994 + d3074c1c8+git worktree remove --force /workspaces/.deploy-wt+npm run okx:bot:deploy # bot: provision lane, clean build, deploy, verify+npm run okx:bot:gateway -- --verify --cli # prove the real CLI through the lane on production+curl -s https://three.ws/api/healthz | jq '.subsystems.subsystems[]|select(.name=="okx_chat_bot")'+```diff --git a/workers/okx-chat-bot/README.md b/workers/okx-chat-bot/README.mdindex 55dd98a72..5900bb6a5 100644--- a/workers/okx-chat-bot/README.md+++ b/workers/okx-chat-bot/README.md@@ -53,6 +53,7 @@ testable without a daemon, a wallet, or a network.| `health-server.js` | The HTTP surface: strict `/readyz`, always-200 liveness, and the `remedy` payload. || `state.js` | Tar the wallet/XMTP identity to GCS and restore it on boot (`snapshotState`, `restoreState`). || `supervisor.js` | Owns the `okx-a2a run` child with capped exponential backoff restarts. |+| `lease.js` | The single-writer lease: no two hosts restore, run or snapshot the bot identity at once, rollouts included (`createLease`, `sqlLeaseStore`). || `workspace.js` | Rebuilds the AI subsession's briefing and skills from the image on every boot. || `log.js` | Structured JSON lines for Cloud Logging. |@@ -107,9 +108,13 @@ locally with no code change. Defaults are the production posture.| `ANTHROPIC_VERTEX_PROJECT_ID` | unset | The GCP project Vertex bills. Required alongside the flag above. || `CLOUD_ML_REGION` | `global` | Vertex region for both the subsession and the credential probe. || `OKX_A2A_AI_PERMISSION_PRESET` | unset | `bypass` on a headless host. Without it the subsession stalls on a tool-approval prompt nobody is there to answer, which the buyer experiences as an unresponsive bot. |-| `OKX_BOT_ANTHROPIC_BASE_URL` | unset | Base URL of an Anthropic-wire-format gateway. The CLI appends `/v1/messages`, so OpenRouter's is `https://openrouter.ai/api`, **not** `.../api/v1`. |-| `OKX_BOT_ANTHROPIC_AUTH_TOKEN` | unset | That gateway's credential. Both it and the base URL are required, or no gateway lane exists. |-| `OKX_BOT_ANTHROPIC_MODEL` | unset | Model id in the gateway's catalog, e.g. `anthropic/claude-sonnet-4.6`. |+| `OKX_BOT_ANTHROPIC_BASE_URL` | unset | Base URL of an Anthropic-wire-format gateway. The CLI appends `/v1/messages`. The deploy sets three.ws's own proxy, `https://three.ws/api/llm/anthropic/agents/<metering agent>`; OpenRouter's would be `https://openrouter.ai/api`, **not** `.../api/v1`. |+| `OKX_BOT_ANTHROPIC_AUTH_TOKEN` | unset | That gateway's credential. Both it and the base URL are required, or no gateway lane exists. On three.ws's proxy it is an API key of the service account that owns the metering agent, from the `okx-chat-bot-llm-gateway-token` secret. |+| `OKX_BOT_ANTHROPIC_MODEL` | unset | Model id in the gateway's catalog. The deploy sets `nvidia/nemotron-3-super-120b-a12b`, a free model on the proxy's chain. |+| `OKX_BOT_LEASE_TTL_MS` | `120000` | How long an unrenewed single-writer lease stays taken. Bounds how long a host that died holding it blocks its successor. |+| `OKX_BOT_LEASE_RENEW_MS` | `20000` | Lease renewal cadence. Must be under half the TTL. |+| `OKX_BOT_LEASE_POLL_MS` | `5000` | How often a waiting host asks for the lease again. |+| `OKX_BOT_LEGACY_BEAT_STALE_MS` | 3 x heartbeat | How old the heartbeat of a host built before the lease must be before a new host stops waiting for it. || `OKX_BOT_PROVIDER_PROBE_MS` | `900000` | How often every lane's own API is asked whether it will still serve. Also how quickly a recovered lane is picked up. || `OKX_BOT_HOST_LABEL` | auto | Name this host on every beat. Cloud Run names itself from `K_SERVICE`. || `OKX_BOT_HOST_DURABLE` | unset | Set to `1` to claim a non-Cloud-Run host stays up on its own. |@@ -141,7 +146,7 @@ carries the new credentials.|---|---|---|---|| 1 | `vertex` | `CLAUDE_CODE_USE_VERTEX=1` + a project | GCP credits, authenticated by the runtime service account. Nothing to mint, rotate or forget, and the spend lands on the pool the platform prefers over any paid third-party API. || 2 | `anthropic-key` | `ANTHROPIC_API_KEY` | A first-party key. |-| 3 | `anthropic-gateway` | `OKX_BOT_ANTHROPIC_BASE_URL` + `..._AUTH_TOKEN` | Any service that speaks the Anthropic wire format (OpenRouter serves one). Opt-in, and last, because it bills a third-party account per token. |+| 3 | `anthropic-gateway` | `OKX_BOT_ANTHROPIC_BASE_URL` + `..._AUTH_TOKEN` | Any service that speaks the Anthropic wire format. The deploy points it at three.ws's own we-pay proxy on the free model chain, so it needs no payment anywhere: see **The payment-free lane** below. Behind Vertex, so Claude on GCP credits leads again the moment the billing hold clears. || 4 | `anthropic-login` | `$OKX_BOT_HOME/.claude/.credentials.json` | A developer host, whose `claude` CLI a human logged in. || 5 | `openai-key` | `OPENAI_API_KEY` | The codex CLI. |@@ -194,6 +199,49 @@ real reply. Measured 2026-09-09, `https://openrouter.ai/api/v1` makes the CLIrequest `/api/v1/v1/messages` and answers 404 forever, which is why the base URLin [cloudbuild.yaml](cloudbuild.yaml) ends at `/api`.+### The payment-free lane: three.ws's own proxy++The gateway lane does not need a third party. three.ws serves the Anthropic+Messages format itself at `/api/llm/anthropic` (the proxy every avatar embed+talks to, on the free model chain), and an SDK client reaches it at the+agent-scoped base URL `/api/llm/anthropic/agents/<agent>/v1/messages`, the path+the `claude` CLI builds from `ANTHROPIC_BASE_URL`. So the deploy sets:++```+OKX_BOT_ANTHROPIC_BASE_URL=https://three.ws/api/llm/anthropic/agents/<metering agent>+OKX_BOT_ANTHROPIC_MODEL=nvidia/nemotron-3-super-120b-a12b+OKX_BOT_ANTHROPIC_AUTH_TOKEN=okx-chat-bot-llm-gateway-token:latest (secret)+```++Measured 2026-09-18 against production: the CLI's real request (the full+agentic system prompt, 22 tools, streaming, `max_tokens` 32000, and an+environment block sent as a `system` turn inside `messages`) ran through the+proxy on `nvidia/nemotron-3-super-120b-a12b`, made a real Bash tool call, read the+output back, and answered in 14 seconds. Two proxy changes made that possible+and ship with the API: the agent-scoped path, and accepting the request shape+the CLI sends by default (block-array `system`, in-thread `system` turns, a+clamped rather than rejected `max_tokens`).++The proxy meters per agent, so the lane meters against a **dedicated**,+unpublished agent owned by a platform service account+(`[email protected]`), never anyone else's.+[scripts/okx-bot-llm-gateway.mjs](../../scripts/okx-bot-llm-gateway.mjs)+(`npm run okx:bot:gateway`) provisions all of it idempotently and proves it with+this worker's own `probeLane`:++- **Why a service account, not the platform's main account.** The reply+ subsession runs with tool access on buyer-supplied text and can read its own+ environment, token included. A key for the main account would expose every+ agent and wallet the platform owns; a key for an account that owns one+ unpublished agent is worth that agent's AI budget and nothing else.+- **Why its own embed policy.** A Claude Code turn is a 25k to 35k token prompt+ and several calls per reply. The embed default (10 calls/min, 1M tokens a+ month) would starve it within a few conversations, so the agent gets 30+ calls/min, 20,000 calls and 30M tokens a month. On the free chain that ceiling+ is a runaway guard rather than a spend.+- **The key** is minted straight into Secret Manager and never printed or+ written to disk; `--rotate` mints a new one before revoking the old.+**One thing about Vertex that could not be tested here.** The billing hold deniesevery Vertex call on this project, so the credential probe was verified againstthe real endpoint (it returns the 403 above, and `classifyProbeStatus` calls that@@ -235,9 +283,35 @@ curl -s localhost:8080/readyz | jq '{ready: .health.ready, reason: .health.reasoTo stage the same workspace on a developer machine without running the worker,use [scripts/okx-bot-revive.mjs](../../scripts/okx-bot-revive.mjs), which keepsthe identical skill list. It refuses to start a daemon while any other host is-serving agent 2632: see **One writer, enforced** below.+serving agent 2632: see **One writer, enforced, across rollouts too** below.++### One writer, enforced, across rollouts too++`--max-instances=1` is **per revision**. A Cloud Run rollout starts the new+revision's instance, waits for its startup probe, moves traffic, and only then+stops the old one, so for that window two instances run. Before the lease below,+both would have restored the identity and run a daemon against it, and the old+instance's SIGTERM snapshot would then have overwritten the new one's state.-### One writer, enforced+[lease.js](lease.js) closes it. A host must hold a single-writer lease (a row in+the `bot_heartbeat` table, `worker = 'okx-chat-bot:lease'`, driven by one+conditional upsert per transition, all on the database's clock) before it+restores state, starts the daemon or writes a snapshot:++| Moment | What happens |+|---|---|+| New instance boots | Health server first (so the startup probe passes and the rollout can move traffic), then waits, reporting `lease_wait` on `/readyz` with `lease.waitingOn` naming what it waits for. It writes no heartbeat while waiting, so `/api/healthz` keeps describing the host that is actually serving. |+| Old instance gets SIGTERM | Stops its daemon, writes the final snapshot while it still holds the lease, then releases it. |+| Lease released | The new instance takes it, restores exactly that snapshot, starts its daemon. |+| A holder dies without releasing | Waited out for `OKX_BOT_LEASE_TTL_MS` (2 minutes). |+| A holder cannot renew (database unreachable) | Fences itself before the TTL can lapse: stops the daemon and exits **without** a snapshot, since another host may by then be writing. Cloud Run restarts it into the wait. |+| Old revision predates the lease | Its heartbeat carries no `leaseHolder`, so the new instance waits until that heartbeat is `OKX_BOT_LEGACY_BEAT_STALE_MS` (90 s) old. This is what makes the first rollout onto this code safe; the live revision on 2026-09-18, `okx-chat-bot-00001-926`, is such a host. |++The SQL was verified against the production database on a throwaway key+(acquire, refuse a second holder, renew, release, hand over, expire, lose), and+the state machine is covered in `tests/okx-chat-bot.test.js`.++#### A second machineThe wallet keyring and the XMTP client database are one state object with exactlyone writer, which is what `--max-instances=1` protects on Cloud Run. Nothing@@ -306,6 +380,8 @@ Everything the deploy depends on:| `okx-chat-bot-database-url` secret | created 2026-09-02 from the project's own `DATABASE_URL`, `three-ws@` holds `secretAccessor` || AI credential | **no secret needed.** `three-ws@` already holds `roles/aiplatform.user`, so `CLAUDE_CODE_USE_VERTEX=1` in the deploy authenticates through ADC || Seeded session | seeded 2026-09-04 and proven: the first revision restored it and needed no OTP |+| Payment-free AI lane | `npm run okx:bot:deploy` provisions it (metering agent, service-account key, `okx-chat-bot-llm-gateway-token` secret with `three-ws@` as `secretAccessor`) through `scripts/okx-bot-llm-gateway.mjs --apply`. Not yet run as of 2026-09-18: Secret Manager writes are the owner's |+| API carrying the agent-scoped proxy path | commits `53687d994` and `d3074c1c8`. Not live as of 2026-09-18 (live API `4291900c7`); `npm run deploy:gcp:full` ships it |The AI-provider secret used to be the one blocker, and the deploy was written tofail loudly without it on the reasoning that a bot receiving chat it can never@@ -324,19 +400,33 @@ cannot survive on its own reads as **degraded**, never `ok`, with the deploycommand as its hint. Calling a codespace green would rebuild, one level up, thefalse-green this worker exists to kill.-### Re-shipping it (one command, after the two steps below)+### Re-shipping it (one command)```bash-# 1. Refresh the seeded session from the host that holds it, daemon stopped:-npm run okx:bot:seed-state -- --apply+npm run okx:bot:deploy -- --dry-run # the whole plan, writes and submits nothing+npm run okx:bot:deploy # provision the gateway lane, build, deploy, verify+```++[scripts/okx-bot-deploy.mjs](../../scripts/okx-bot-deploy.mjs) checks gcloud+auth; builds from a clean worktree of HEAD (the image copies all of `api/`, so+the shared working tree would ship other people's in-flight edits) and refuses+while `workers/okx-chat-bot/` has uncommitted changes; runs+`okx-bot-llm-gateway.mjs --apply` and passes its metering agent to the build as+`_GATEWAY_AGENT`; reports whether the live API already serves the agent-scoped+proxy path; submits [cloudbuild.yaml](cloudbuild.yaml); and polls `/api/healthz`+until the `okx_chat_bot` subsystem names the new revision as its host. Expect+that last step to take a few minutes: the new instance waits for the+single-writer lease while the old one drains.-# 2. Stop that host. The GCS object has exactly one writer; a codespace stopgap-# and the Cloud Run service running at once interleave snapshots.+The worker and the API can land in either order. The gateway lane is elected on+a live probe every 15 minutes, so a worker deployed before the API simply stays+on its current lane until the proxy answers, then moves by itself.-# 3. Deploy.-gcloud builds submit --config workers/okx-chat-bot/cloudbuild.yaml \- --region us-central1 --project aerial-vehicle-466722-p5 \- --substitutions=SHORT_SHA=manual$(date +%s) .+The seeded session only needs refreshing if the GCS snapshot is lost; the+running service keeps it current:++```bash+npm run okx:bot:seed-state -- --apply # from a host holding a live session, daemon stopped```The build pins `three-ws-build@` and the service runs as `three-ws@`; the@@ -442,5 +532,7 @@ Daemon stdout and stderr are forwarded into the worker's own log stream under a- [scripts/okx-bot-revive.mjs](../../scripts/okx-bot-revive.mjs) stages the same workspace locally, and refuses while another host is serving.- [scripts/lib/okx-bot-host-guard.mjs](../../scripts/lib/okx-bot-host-guard.mjs) is the one-writer check that script runs first.- [scripts/okx-bot-seed-state.mjs](../../scripts/okx-bot-seed-state.mjs) seeds the GCS session snapshot (`npm run okx:bot:seed-state`).+- [scripts/okx-bot-llm-gateway.mjs](../../scripts/okx-bot-llm-gateway.mjs) provisions and proves the payment-free AI lane (`npm run okx:bot:gateway`).+- [scripts/okx-bot-deploy.mjs](../../scripts/okx-bot-deploy.mjs) ships the worker in one command (`npm run okx:bot:deploy`).- [api/_lib/okx-chat-briefing.js](../../api/_lib/okx-chat-briefing.js) generates the subsession briefing.- [workers/README.md](../README.md) is the worker index.diff --git a/workers/okx-chat-bot/config.js b/workers/okx-chat-bot/config.jsindex 255fa67a6..bb2768931 100644--- a/workers/okx-chat-bot/config.js+++ b/workers/okx-chat-bot/config.js@@ -114,9 +114,10 @@ export function providerLanes(env = process.env, home = env.OKX_BOT_HOME || home* CLI the adapter already spawns. That keeps the task lifecycle intact, which a* one-shot completion responder would break.*- * Deliberately opt-in: unlike Vertex it bills a third-party account per token, so- * it must be a decision an operator made, never something the host picks up from- * an unrelated key that happened to be on the service.+ * Deliberately opt-in: whatever the base URL names meters or bills this host's+ * calls (three.ws's own proxy against a dedicated agent's budget, a third-party+ * gateway per token), so it must be a decision an operator made, never something+ * the host picks up from an unrelated key that happened to be on the service.*/function gatewayLane(env) {const base = (env.OKX_BOT_ANTHROPIC_BASE_URL || '').trim().replace(/\/+$/, '');