# How to Mimic Sea.site — Build a Sea-Like Engine

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

This chapter is a buildable specification for recreating `sea.telegram365books.stream` (the Knowledge Sea advisor) as a standalone engine. It covers:

1. The reference engine's retrieval tools, tool loop, quote gate, session policy, and corpus.
2. How an external AI assistant can consume the public Knowledge Sea API.
3. How the public API provides the static and dynamic contract needed for a Sea-like retrieval client.

The current host mapping is Google `ebstudy-vm` → Cloudflare tunnel → `sea.service` on `127.0.0.1:8091`. Oracle Hermes is a separate owner-only service and is not part of this engine.

---

## 1. What Sea.site is (the reference implementation)

`sea.telegram365books.stream` runs on Google `ebstudy-vm`, bound to `127.0.0.1:8091`, and is exposed through Cloudflare. The maintained implementation is a single-process, stdlib-only HTTP service (`sea_app.py`) that answers clause-level questions about the current EB2026 corpus in English, Sinhala, Tamil, and Arabic.

It is **not** a chatbot wrapper. It is an agentic advisor with four properties:

| Property | What it means |
|----------|---------------|
| **Tool loop** | The model must call tools to locate clauses before answering. It never answers from memory alone. |
| **Quote gate** | Every quotation is re-verified verbatim against the canonical clause text before release. |
| **SSE streaming** | Tool rounds, evidence, gate result, and final answer stream to the browser as server-sent events. |
| **18-turn session** | Hard cap of 18 turns; turns 15–17 wind down with a case state; turn 18 emits a `CASE HANDOFF` block. |

### Corpus

The current KB is published at `https://eb2026.telegram365books.stream/kb/`. The full corpus is loaded lazily, not at startup: `_load_docs()` fetches `kb/all.ndjson` only when the managed `data/all.ndjson` cache is missing and full-text search, non-English translation verification, or a failed-quote corpus scan first needs it. The file is then indexed in memory; topic and map resources are fetched on first use and cached in memory. Each clause has:

- `clause_id` (e.g. `fr-0003`, `ec1-c15`, `pog-gp-0169`, `psf-0001`)
- `heading`, `content`
- `canonical_lang` (en / si / ta)
- `cites` / `cited_by` relations
- `source_url` pointing to the human-readable source on EB2026

Use the [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) as the current manifests. Do not hardcode book, clause, record, or tool counts in a mimic.

The EB2026 maps index headings only. Full-text search covers the complete English text with deterministic keyword ranking (no embeddings).

---

## 2. Retrieval tools (specification)

The reference engine exposes the following retrieval tools. Their maintained source of truth is `sea/sea_app.py` in the Knowledge Sea source tree, especially `SCHEMA`, `IMPL`, and the `t_*` functions. The public HTTP `/v1/tools/{name}` adapter is a separate contract; do not assume its responses are identical to these internal tool results.

Every `t_*` function returns a string. All results except `read_map` are JSON text representing the array or object shown below; errors are JSON objects with an `error` field and, for some tools, `topics` or `books`.

| Tool | Purpose | Input | Output |
|------|---------|-------|--------|
| `topic_index` | List topics with exam weight and keyword tags | `{}` | JSON array `[{id, label, exam_weight, keywords, clause_count}]`; there is no wrapper object. |
| `topic` | Get one topic's clause IDs | `{topic_id}` (required) | JSON object `{id, label, keywords, clause_ids}`. This internal tool differs from the public API's metadata-only topic response. |
| `find_in_map` | Locate headings in a route map | `{book, query, limit?}` (`book`, `query` required) | JSON object `{book, hits, matches, hint}`; `matches` contains numbered strings such as `L12: F.R.12 ...`, not clause objects. If no line contains every query word: `{book, hits: 0, note, closest, hint}`. |
| `read_map` | Read a numbered route-map range | `{book, start, end?}` (`book`, `start` required by `SCHEMA`) | Plain text: `book map entries start-end of total` followed by `L<n>: <text>` lines. It does not return JSON. |
| `get_clause` | Retrieve an exact clause by ID | `{clause_id}` | JSON object `{clause_id, book, canonical_lang, authoritative, part_title, heading, content, source_url, cites, cited_by}`. |
| `quote_check` | Verify a quotation verbatim | `{clause_id, quote}` | JSON object containing `verified` and `note`; successful results also carry `language`, and translation matches can carry `canonical_lang`, `caveat`, and `label`. |
| `related_clauses` | Get clauses cited by or citing a clause | `{clause_id}` | JSON object `{clause_id, cites, cited_by}`. |
| `search_text` | Full-text search across the corpus | `{query, limit?}` (`query` required) | JSON object `{query, hits, clauses: [{clause_id, book, part_title, heading, snippet}]}`. `hits` is the number of returned rows, not the total number of matching clauses. |

Implementation details that affect callers:

- `find_in_map` defaults `limit` to 20 and clamps it to 1–40. Exact all-word matches are returned first; otherwise up to eight closest lines by word overlap are returned.
- `read_map` defaults an omitted `start` to 1 in the implementation, defaults `end` to `start + 20`, and caps a range at 40 lines.
- `search_text` defaults `limit` to 8 and clamps it to 1–15. Its argument is `query`, not `q`.
- Map book slugs come from `BOOKS` (`fr`, `ec1`, `ec2`, `pog`, `psf`, `dh`). The `dh` book and `dh-*` clauses/topics are hidden unless `_hadmin_ok()` is true.

### Tool loop flow

1. User asks a question.
2. Model calls one or more tools (topic → get_clause → search_text, etc.).
3. Model assembles an answer with `[clause-id]` citations and verbatim quotes.
4. `gate_answer()` re-verifies every citation and every quote span (≥25 chars).
5. Failed quotes are flagged (`elsewhere`, `label_missing`) and streamed to the UI.
6. Final answer is released only after the gate passes.

---

## 3. How an external AI assistant consumes the tools

To let an external assistant use the Sea retrieval tools, expose the public API as an **Actions/OpenAPI schema** at `https://api.telegram365books.stream/openapi.json`.

### 3.1 What the client needs

The client needs:

- The OpenAPI document at a public URL.
- One operation per documented retrieval capability, including `GET /v1/topics`, `GET /v1/topics/{id}`, `GET /v1/clause/{id}`, `POST /v1/quote-check`, and `POST /v1/tools/{name}`.
- Clear parameter descriptions and response schemas.
- Authentication documented in `securitySchemes` if the deployment adds it; the current public API requires no API key.

### 3.2 Wiring it into a custom GPT

1. In the GPT builder, go to **Actions → Create action**.
2. Import the OpenAPI schema from `https://api.telegram365books.stream/openapi.json`.
3. Use **None** for authentication when calling the current public API.
4. Add instructions: "Before answering an EB exam question, call at least one retrieval tool. Cite clauses as `[fr-0003]`. Verify quotes verbatim."
5. Publish and test against live responses. The schema documents intended behavior; if it differs from an observed response, record the mismatch and handle the observed behavior explicitly rather than assuming both are authoritative.

### 3.3 Example system prompt

```text
You are an EB exam research assistant. Use the available retrieval tools.
Never answer corpus questions from memory. Locate clauses with tools first.
Cite clauses as [clause-id], for example [fr-0003].
Quote verbatim from clause content; quotes ≥25 chars must match exactly.
If a quote fails verification, say so and do not present it as authoritative.
Answer in the user's language (en / si / ta / arb).
```

---

## 4. How the public API supports a Sea-like engine

The API at `https://api.telegram365books.stream` is a hybrid retrieval layer. Read-heavy corpus data is served as static files; endpoints that need user input or live computation remain dynamic. An external model supplies reasoning and conversation behavior.

| Endpoint | Method | Purpose | Static or dynamic? |
|----------|--------|---------|-------------------|
| `/` | GET | Index / discovery page | Static HTML |
| `/openapi.json` | GET | Machine-readable tool contract | Static JSON |
| `/sitemap.xml` | GET | Discoverable URLs | Static XML |
| `/robots.txt` | GET | Crawler directives | Static text |
| `/v1/topics` | GET | List topics | Static JSON |
| `/v1/topics/{id}` | GET | One topic's metadata; the observed response has no clause IDs | Static JSON |
| `/v1/clause/{id}` | GET | Exact clause text | Static JSON |
| `/v1/related/{id}` | GET | Cites / cited-by | Static JSON |
| `/v1/map/{book}` | GET | Route map | Static JSON |
| `/kb/clause/{id}.html` | GET | Human-readable clause page | Static HTML |
| `/kb/all.ndjson` | GET | Full corpus dump | Static NDJSON |
| `/v1/search?q=...` | GET | Full-text search | **Dynamic** |
| `/v1/quote-check` | POST | Verify a quotation | **Dynamic** |
| `/v1/tools/{name}` | POST | Generic tool execution | **Dynamic** |
| `/health` | GET | Service health | **Dynamic** |

### 4.1 Contract requirements

A Sea-like retrieval client needs:

1. **Stable URLs** — for example `https://api.telegram365books.stream/v1/clause/fr-0003`.
2. **CORS enabled** — so a client on another origin can fetch the public API.
3. **No account cookie for corpus retrieval** — the public API is independent of registration and model-provider credentials.
4. **Deterministic retrieval** — the same clause or query should produce stable retrieval results.
5. **Complete published corpus** — the client must not silently substitute a partial local copy.

### 4.2 Current service layout

The API service runs on Google `ebstudy-vm` as `sea-api.service`, listening on `127.0.0.1:8092`. Its working directory is `/home/zxc-funnel/sea-api/`. The conceptual layout is:

```text
/home/zxc-funnel/sea-api/
├── api_app.py              # dynamic Python server (loopback port 8092)
├── api_config.py           # host, port, rate limits, CORS
├── sea_app.py              # retrieval engine imported by the adapter
├── api_static/             # pre-built static files
│   ├── index.html
│   ├── openapi.json
│   ├── sitemap.xml
│   ├── robots.txt
│   ├── v1/                 # topics, clauses, related records, maps
│   └── kb/                 # clause pages and all.ndjson
├── build_api_static.py     # corpus → static files
└── sea-api.service         # systemd unit
```

File names and generated-file counts are service-maintained details. Inspect the live service rather than treating this conceptual tree as a manifest.

---

## 5. Current topology checklist

This is a read-only reference, not an execution runbook. Deployment, DNS, ingress changes, and restarts are outside this guide.

- `api.telegram365books.stream` is present in Google `/etc/cloudflared/config.yml` and maps to `http://localhost:8092`.
- `sea-api.service` is active/running and enabled at the verified snapshot.
- The API is not hosted on Oracle and is not the Eddy service on `:8093`.
- `mcp.telegram365books.stream` is retired and absent from current ingress.
- Build static artifacts from the current published corpus; do not embed stale counts in generated documentation.

Read-only verification:

```bash
curl -fsS https://api.telegram365books.stream/health
curl -fsS https://api.telegram365books.stream/openapi.json
curl -fsS https://api.telegram365books.stream/v1/topics
curl -fsS https://api.telegram365books.stream/v1/clause/fr-0003
curl -fsS https://api.telegram365books.stream/v1/map/fr
```

---

## 6. What to build first

1. **OpenAPI contract** — keep it aligned with live routes and response schemas.
2. **Static retrieval artifacts** — generate topics, clauses, related records, maps, and HTML from the current corpus.
3. **Dynamic adapter** — serve search, quote-check, tool dispatch, and health on the API service.
4. **Google tunnel mapping** — keep `api.` → `localhost:8092` under change control.
5. **Retired-surface guard** — do not reactivate `mcp.` or map the API to Eddy's port.
6. **Documentation** — link to live manifests instead of duplicating corpus/tool counts.

---

## Related

- `/sea.md` — the Sea engine implementation (tool loop, quote gate, session policy, model lanes).
- `/architecture.md` — Google/Oracle/Cloudflare topology and ingress.
- `/sites.md` — current domain-to-service catalog.
- `/endpoints.md` — public service URLs.
- `/api-examples.md` — example request/response pairs for the Knowledge Sea API.
- Live Sea: https://sea.telegram365books.stream/
- Live API: https://api.telegram365books.stream/
