# Knowledge Sea — sea.telegram365books.stream

> **Status:** CURRENT
> **Last verified:** 2026-11-28

The knowledge-sea advisor runs `sea_app.py` on Google `ebstudy-vm`, bound to `127.0.0.1:8091`, and is exposed through Cloudflare at `https://sea.telegram365books.stream/`. The maintained implementation is a single-process, stdlib-only HTTP service that answers clause-level questions about the current EB2026 corpus in English, Sinhala, Tamil, and Arabic. See `architecture.md` and `sites.md` for the verified host and route mapping.

It is not a wrapper around a chatbot. It is an agentic advisor with a tool loop, a quote-verification gate, SSE streaming, and an 18-turn session policy.

## What it does, in four steps

1. **Runs a tool loop over the published KB.** The model is given the engine's retrieval tools (`topic_index`, `topic`, `find_in_map`, `read_map`, `get_clause`, `quote_check`, `related_clauses`, `search_text`) and must call them to locate clauses before answering. It never answers from memory alone. Use maintained `sea/sea_app.py` for the internal tool contract and the [API OpenAPI contract](https://api.telegram365books.stream/openapi.json) for public HTTP operations; observed responses take precedence when a published schema lags behavior.
2. **Carries a compact session.** Each chat stores only question + final answer (never tool payloads), with a hard cap of 18 turns. Older answers are replayed as short digests so a long chat stays inside the model's context budget.
3. **Re-verifies every quotation.** Before an answer is released, every quoted span is checked verbatim against the canonical clause text. A quote that fails is flagged; a translation from a Sinhala-canonical clause must carry the label `[English translation - not authoritative]`.
4. **Streams as SSE.** The whole turn — tool rounds, evidence, gate result, final answer — streams to the browser as server-sent events so the visitor can watch the work.

## Corpus

The current KB is published at `https://eb2026.telegram365books.stream/kb/`. The full corpus is loaded lazily, not at startup: when `_load_docs()` is first needed by full-text search, non-English translation verification, or a failed-quote corpus scan, the service fetches `kb/all.ndjson` only if `data/all.ndjson` is missing, then caches and indexes it in memory. Topic and map resources are fetched on first use and cached in memory. Each clause has an id (`fr-0003`, `ec1-c15`, `pog-gp-0169`, `psf-0001`, etc.), heading, content, canonical language, and `cites` / `cited_by` relations.

Use the [published corpus dump](https://eb2026.telegram365books.stream/kb/all.ndjson), [topic index](https://api.telegram365books.stream/v1/topics), and [OpenAPI contract](https://api.telegram365books.stream/openapi.json) for current content and schema. Book, clause, and record counts in prose are intentionally omitted because they change.

The EB2026 maps index headings only — scenario words often miss where the clause body matches, so `search_text` covers the full English text with deterministic keyword ranking (no embeddings). Discover current maps from the EB2026 site rather than maintaining a duplicate list here.

## Model lanes

The model is chosen per turn from `config.py`. The maintained lane families are:

- **NIM (server key)** — direct to `https://integrate.api.nvidia.com/v1` with the server-held NVIDIA key. Nemotron 120B (default, English), Nemotron Lightning (English/Tamil), Nano Omni (English/Tamil). The Google host holds the key; the visitor never does.
- **CF / Kilo (visitor's own key)** — relayed through `gm-worker` on the visitor's Cloudflare or Kilo token. The VM only forwards the `eb_acct` cookie; it holds no provider key of its own. Gemma 4 (en/si/ta) on CF; Kilo Gemma (si/en/ta/arb) on Kilo.
- **Gemini (owner free-tier key, server-held)** — `gemini-3.1-flash-lite` primary, `gemini-3.5-flash-lite` fallback on 429/503. The Google host holds `GEMINI_API_KEY`; the visitor never does. Language-locked options for en/si/ta/arb.

A model without a stored credential is refused before the stream opens (`TOKEN_REQUIRED` / `KILO_KEY_REQUIRED`). Rate limits are paced (up to 5 retries honoring the provider's `try again in Xs` hint); a 413 is terminal (context outgrew the key's tier — start a new chat).

## Account gate

Account state is represented by the `eb_acct` cookie (32-hex, HttpOnly, Domain=.telegram365books.stream). The engine calls the Worker's `/api/account/me` once per account per ten minutes (positives cached 10 min, negatives 1 min; a validator outage fails closed but clears within a minute). The result carries `has_token` / `has_kilo` / `has_gemini`, which decide which lanes the picker offers.

`/api/auth` is the current authority for the visitor's available models. No cookie → account-gated lanes return `SIGN_IN_REQUIRED` with a link to `reg.telegram365books.stream`; do not infer universal anonymous chat access from the public UI or an HTTP 200 auth-status response.

## Session policy (18 turns)

- Turns 1–14: normal tool-loop answers.
- Turns 15–17: the answer ends with a short case state (facts established, conclusions reached, open questions, clause ids).
- Turn 18 (final): the answer ends with a `CASE HANDOFF` block (at most six lines) so the next chat resumes without this history.
- A 19th question is refused with `SESSION_COMPLETE`; a chat too long for the model's cap is refused with `SESSION_CAP_REACHED`. The old session stays readable.

## Quote gate (the model does not get the last word)

`gate_answer()` re-verifies the finished answer:

- Every `[clause-id]` citation is checked for existence.
- Every quotation span (≥25 chars, no ellipsis/square brackets) is checked verbatim against the cited clause via `quote_check`.
- A quote that matches only elsewhere (not in a cited clause) is flagged `elsewhere`.
- A translation from a Sinhala-canonical clause without the required label is flagged `label_missing`.
- Unverified quotes and unknown citations are reported in the gate event streamed to the UI.

## Endpoints

| Path | Method | Purpose |
|------|--------|---------|
| `/` | GET | UI shell (static `index.html`) |
| `/api/health` | GET | Health: default model id and context cap |
| `/api/auth` | GET | Account status + model list for the picker (fresh check, skips cache) |
| `/api/sessions` | GET | List this browser's stored chats (sidebar) |
| `/api/session` | GET | Reopen one stored chat |
| `/api/session/delete` | POST | Delete one stored chat |
| `/api/session/handoff` | POST | Build a CASE HANDOFF from stored turns (no model call) |
| `/api/translate` | POST | Translate the last answer to si/ta via CF gemma-si-ta on the visitor's token |
| `/api/chat` | POST | SSE stream of one turn (tool loop → gate → answer) |
| `/mcq/generate` | POST | Write one MCQ paper in si/ta/arb (owner's Gemini key, account-gated, rate-limited) |
| `/mcq/auth` | GET | Account probe for the mcq practice engine / apex chooser |

## Files

- `sea_app.py` — engine: corpus loader, retrieval tools, model callers (NIM / relay / Gemini), tool loop, quote gate, session store, HTTP handler.
- `config.py` — frozen constants: model table, lanes, context caps, session policy (18 turns, wind-down from 15, 4 full turns kept), token budgets.
- `static/index.html` — the browser UI: sidebar chat list, model picker, language switch, meter, compose pane, SSE consumer.
- `sessions/` — per-browser chat store (one `.jsonl` per chat, capped at 9, oldest deleted on insert).
- `runs/` — console test traces and the mcq usage ledger.
- `data/all.ndjson` — cached KB corpus (fetched from EB2026 on first full-text, translation-verification, or failed-quote scan need; not at startup).

## What to change when developing sea

- Model table / lane / cap → `config.py` (never hardcode in `sea_app.py`).
- System prompt / tool directives → the `SYSTEM` constant in `sea_app.py`.
- Tool behaviour → the `t_*` functions and `IMPL` map in `sea_app.py`.
- Quote gate rules → `gate_answer()` / `extract_quotes()` / `_verify()`.
- Session policy → `SESSION_TURNS`, `WIND_DOWN_FROM`, `KEEP_FULL_TURNS` in `config.py`.
- UI copy / layout → `static/index.html`.
- Account / mcq relay → `gm-worker` (not in this repo).

The engine binds `127.0.0.1:8091` by default (`SEA_PORT` override allowed). Port 4000 is reserved for the local LLM router and must never be used by sea.

## Related

- Architecture: `/architecture.md` — Google/Oracle/Cloudflare topology and service map.
- Site catalog: `/sites.md` — domain-to-service mapping.
- Endpoints: `/endpoints.md` — public service URLs.
- Knowledge Sea (live): https://sea.telegram365books.stream/
