An AI assistant for websites that answers only from what a business has published, hands everything else to a person, and logs every question it could not answer so the gap can be filled.
Working name. The packages and Workers still use the earlier internal name
cf-chat (@cf-chat/*, cf-chat-app, cf-chat-widget).
A small chat window on a website answers visitors from the site's own pages and uploaded documents, with a link to the source of each answer. When it is not confident, it says so and hands the conversation to a person instead of guessing.
It is not built to be smarter than other assistants. It is built to be wrong less often: a wrong answer about a price or an opening time costs a customer, and an unnecessary handoff costs a minute. So the reply loop leans towards handing off, on three independent signals:
- No good match. Nothing was retrieved, or the best passage's reranker score is below the tenant's threshold.
- Low confidence. The model's own confidence report is below the tenant's threshold.
- Rules. Plain triggers, such as the visitor asking for a human.
Every turn is logged with its inputs (scores, confidence, which rule fired, model id), escalated or not, because the thresholds are tuned against both rates.
Built and tested:
- Multi-tenant accounts, sessions and tenant switching. Tenant isolation is enforced in every query and backed by row level security, with an isolation suite that runs against Postgres 18 in CI.
- Knowledge ingestion: upload to R2, conversion, indexing into a per-tenant AI Search instance, retries, a dead-letter queue and clean deletes.
- The reply loop: retrieval, generation, citations, the three escalation signals and the per-turn log.
- The embeddable widget: site key, origin allowlist, Turnstile, signed visitor tokens and a WebSocket to the conversation's agent. The loader is 1.9 KB gzipped; the chat panel loads when the visitor opens it. Run end to end against the live services from a third-party page.
In progress: handing an escalated conversation to a person.
Roughly in order, each step gated on the one before proving useful:
- Handoff by email with the transcript, where the reply can be saved as a new answer.
- Answers you can check: quotes verified against the source text, and an explicit "not found" rather than a paraphrase.
- Onboarding from a site's URL, not only file uploads.
- A regular digest of the questions the content does not answer, built from the per-turn log.
- Usage limits and per-visitor rate limiting, then a public demo.
- An evaluation set from real transcripts, and measured cost per conversation.
- Dashboard views for conversations, gaps and answer edits.
visitor's page
│ embed.js
▼
widget Worker site key, origin allowlist, Turnstile, signed visitor token
│ service binding, WebSocket upgrade
▼
app Worker TanStack Start dashboard, Hono API, queue consumers
│ checks the token names this tenant and conversation
▼
Conversation Durable Object (Agents SDK), one per tenant and conversation
│ runTurn (packages/reply-loop): retrieve, generate, decide whether to escalate
├──▶ AI Search, one instance per tenant
└──▶ Workers AI through AI Gateway
Neon Postgres behind Hyperdrive is the system of record. Uploads land in R2. Queues carry ingestion and the conversation archive, each with a dead-letter queue.
The decisions that shape the code:
- Tenant isolation under Hyperdrive. Every tenant-scoped repository
function takes a branded
TenantIdand emitstenant_id = $1, so calling one without a tenant is a compile error, and the tenant is part of Hyperdrive's cache key. Row level security is the backstop: writes run in a transaction that setsapp.tenant_id, and the policies reject any write that does not match it. - Reads fail open at the RLS layer, deliberately. Plain reads do not open a transaction, so the read policies let them through and the predicate is the guard. Failing closed would put every read in a transaction and pin a pooled Hyperdrive connection for each one. The isolation suite tests both layers, and that the tenant setting never outlives its transaction on a reused connection.
- The reply loop is binding-free.
runTurntakesRetrieverandGeneratorinterfaces. Production passes AI Search and Workers AI; tests passFixtureRetrieverandFixtureGenerator. No test touches a live binding, so the suite is fast, free and deterministic. - The model is config.
REPLY_MODEL_IDinapps/app/wrangler.jsonc, currently@cf/zai-org/glm-4.7-flash, called through AI Gateway.
This repo is built with an AI coding agent (Claude Code). The rules it works
under are in CLAUDE.md, so every session starts from them. Where
a rule can be checked mechanically it is; the rest are conventions, listed as
such.
Enforced:
- Tenant scoping. Repository functions and
Retriever.searchtake a brandedTenantId, so a bare string does not typecheck. The isolation suite checks against Postgres 18 in CI that the id reaches the SQL and that row level security rejects mismatched writes. It covers the sources and messages tables so far. - Retrieved content is data. Chunks and the host page are wrapped in delimiters the content cannot close, with a standing instruction that they are data; tests try to break out.
- No live bindings in tests. The test pools declare no Workers AI, AI
Search or Hyperdrive, so a test that reaches for one fails.
RetrieverandGeneratorhave fixture implementations, so reply-loop changes are tested deterministically and for free. - Boundaries. Strict TypeScript (
noUncheckedIndexedAccess,exactOptionalPropertyTypes), zod on external input, and Biome rejectinganyand non-null assertions. - The tests are tested. The isolation suite was checked by breaking the
code on purpose: a session-wide tenant setting, a read without the tenant
predicate, and running as the superuser instead of
app_user. Each break turns the run red, and the top of the suite lists what catches it.
Conventions, held by review:
- Secrets only in Worker secrets; KV never read straight after a write.
- Plan and agree the decision before code; one decision record per settled choice (private, cited by number in code comments); changes reviewed a file at a time; the agent does not commit.
| Path | What |
|---|---|
apps/app |
TanStack Start dashboard + Hono API. The main Worker. |
apps/widget |
Embed Worker: site key, origin and Turnstile gates, visitor tokens, WebSocket upgrade forwarded to app. |
packages/shared |
Branded ids, zod boundary schemas, AppError, Result, session, password and visitor-token primitives. |
packages/db |
Drizzle schema, migrations, Hyperdrive client, tenant-scoped repositories, Postgres isolation tests. |
packages/retrieval |
Retriever and Indexer interfaces, AISearchRetriever, FixtureRetriever. |
packages/reply-loop |
runTurn, escalation signals, Generator interface and FixtureGenerator. |
packages/widget-ui |
React 19 embed UI: a small loader, and the chat panel it loads on open. |
pnpm install
pnpm dev # vite dev on :3000, widget runs as an auxiliary Worker
pnpm typecheck # wrangler types, then tsc across the workspace
pnpm lint # biome check
pnpm format # biome check --write
pnpm test # vitest: workerd for the Workers and shared, node for the restThe tenant isolation tests in packages/db need a Postgres and skip without
one:
docker run --rm -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:18
TEST_DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres pnpm testPoint TEST_DATABASE_URL only at a disposable Postgres, as a superuser. Each
run creates its own database and drops it afterwards.
Per package: pnpm --filter @cf-chat/db generate (new migration from schema
changes), pnpm --filter @cf-chat/db migrate (apply to Neon),
pnpm --filter @cf-chat/app deploy.
-
Create the account resources. The ids committed in
apps/*/wrangler.jsoncbelong to this deployment. They are not secrets, but they only work on its Cloudflare account. To run your own, create the resources, then replace the KV namespace id in bothwrangler.jsoncfiles and the Hyperdrive id inapps/app/wrangler.jsonc. The Hyperdrive one needs your Neon credentials, so it is not something to paste into a shared shell.pnpm exec wrangler kv namespace create KV pnpm exec wrangler hyperdrive create cf-chat-neon --connection-string="postgres://app_user:[email protected]/..."
-
Environment. In
.envat the repo root:DATABASE_URL=postgres://<owner>@<host>/<db> # direct Neon, drizzle-kit only CLOUDFLARE_HYPERDRIVE_LOCAL_CONNECTION_STRING_HYPERDRIVE=postgres://app_user@<host>/<db>DATABASE_URLuses the owner role because migrations create objects. Everything else connects asapp_user, which is what makes row level security meaningful.In
apps/appandapps/widget, copy.dev.vars.exampleto.dev.vars. The examples work as they are for local development. They are also where the generatedEnvtype gets its secret names, so a new secret goes in the example first. In production, runpnpm exec wrangler secret put <NAME>for each, with the sameWIDGET_TOKEN_SECRETon both Workers. -
Migrate, then set the app role's password. The password is deliberately not in the migration:
pnpm --filter @cf-chat/db migrate psql "$DATABASE_URL" -c "ALTER ROLE app_user WITH LOGIN PASSWORD '<secret>';"
GitHub Actions (ci.yml) runs typecheck, lint and
the full test suite, including the isolation tests against a Postgres 18
service, on every push to main and every pull request. It holds no Cloudflare
credentials.
Deploys run on Workers Builds, configured in the Cloudflare dashboard against this repository. A failing CI run does not block a deploy.
cf-chat-app |
cf-chat-widget |
|
|---|---|---|
| Root directory | apps/app |
apps/widget |
| Build command | pnpm install && pnpm build |
pnpm install |
| Deploy command | pnpm exec wrangler deploy |
pnpm exec wrangler deploy |
- Design decision records (ADRs) and planning docs live in a private
docs/folder. Code comments cite ADRs by number; the decisions under Architecture summarise the ones that shape the code. maininapps/app/wrangler.jsoncpoints at./src/server.ts, deliberately, not at@tanstack/react-start/server-entryas the Cloudflare framework guide shows. That package export is a self-contained default entry that never imports our server file, so pointingmainat it silently drops the Hono API and every named export while the build still succeeds.compatibility_dateis pinned to2026-08-22across dev, test and deploy. That is the newest date the test pool's bundled runtime accepts; letting the three drift is not worth the twelve days.- Tests never touch live bindings. AI Search and Workers AI have no local
emulation, and hitting them would burn allowance and make results
nondeterministic, so
FixtureRetrieverandFixtureGeneratorexist.