AnyBot/docs/en/protocol.md

70 lines
6.6 KiB
Markdown
Raw Permalink Normal View History

# Protocol (English summary)
Canonical document: [docs/protocol.md](../protocol.md) (Chinese). For anyone modifying the relay or writing another client. All replies are JSON; errors are `{"error": "plain sentence"}` with an HTTP status.
## Identity
| Who | Proves itself with | From |
|---|---|---|
| Person (phone) | `Authorization: Bearer <session>` | `POST /relay/login` |
| An AnyBot (host) | `Authorization: Bearer <host token>` | `POST /relay/hosts` (after login) or `POST /relay/pair/claim` (pairing code) |
The server stores only hashes. Passwords are argon2id (legacy PBKDF2 hashes still sign in; upgraded on next password change).
## Relay endpoints
### Account
| Method | Path | Notes |
|---|---|---|
| POST | `/relay/signup` | `{user, password, invite}`. First account needs no invite; later ones need `ANYBOT_RELAY_INVITE` |
| POST | `/relay/login` | `{user, password, device}` → `{token}`; with 2FA on → `{need_2fa, challenge}` (valid 5 min). Lockout 8 tries / 5 min per IP+account |
| POST | `/relay/2fa/verify` | Second step. Sign-in: `{challenge, code}` → `{token}` (TOTP code, or a one-time recovery code → adds `used_recovery`). Enrollment (with session): `{code}` activates the new secret |
| POST | `/relay/2fa/enroll` | (session) → `{secret, uri, recovery_codes}` — codes shown once; 2FA is on only after a verified code |
| POST | `/relay/2fa/disable` | (session) `{code}` turns 2FA off |
| POST | `/relay/sessions/logout` | (session) kicks **every** device of the account, including this one |
| POST | `/relay/logout` | ends this session |
| GET | `/relay/me` | account, `two_factor`, usable AnyBots (`online`, `uses`, `hands`), signed-in devices, backup presence |
### Hosts and proxying
| Method | Path | Notes |
|---|---|---|
| POST | `/relay/hosts` | (person) `{name}` → `{id, token}`; re-registering a name rotates the token |
| POST | `/relay/hosts/<id>/remove` | (person) remove a host |
| GET | `/relay/host/ws` | (host) the long connection — see wire format below |
| GET | `/relay/host/next` · POST `/relay/host/reply/<id>` | legacy long-polling for hosts without WebSocket |
| GET | `/relay/host/peers` · GET/POST `/relay/host/members` | other hosts; team roles (admin/member) |
| POST | `/relay/host/notify` | push notification to the account's phones |
| POST | `/relay/host/sites/<name>` | publish a bot-made website at `/s/<name>/` |
| PUT/GET | `/relay/backup` | encrypted backup; the server cannot open it |
Proxying: `/h/<host>/api/...` (phone → that AnyBot, role owner/admin/member); `/relay/hosts/<host>/api/sync[/...]` (host → brain's `/api/sync…`, role `mirror`); `/relay/hosts/<host>/api/device/run` (host → hands, role `device`). The relay injects `user`, `role`, `from`. Offline → 503 immediately; no answer in 35 s → 504. VNC streaming: `POST /relay/screen-ticket {host}` → 10-minute ticket; `WebSocket /relay/vnc/<host>?t=|?ticket=` carries binary VNC bytes and typed text.
## AnyBot's own API (`remote::handle`)
記憶: a page to see it, a few lines picked while typing, a local model The memory had grown into a list carried whole, a top-14 recalled by a trigram index and pasted into the system prompt with the clock, and a page that broke its own layout. Nobody could see what went to the model, the prompt cache missed every message, and 「記住」 kept saying the same thing twice. Rebuilt per the spec (docs/memory.md): - Three kinds in memory.db: 記得的事 (fact), 做過的事 (event, a line per finished turn), 整理過的 (rollup). Each keeps pinned, uses, last_used, deleted, superseded_by, span. state.json keeps the facts as the copy that syncs; the page reads SQLite. - Search: jieba words ∪ CJK bigrams in an FTS5 unicode61 table (Traditional text goes through Simplified first), weighted share of query terms hit; plus local vectors, vec = clamp((cos−0.35)/0.35). score = max + 0.15×min, events ×0.9. ≥0.15 suggested, ≥0.5 ticked, ≥0.55 carried when nobody chose (3 at most). - What the model gets: the system prompt has the time zone and the pinned memories only, the same every turn. Each person message gets 〔送出時間〕 and 〔相關記憶〕 from Message.memories, built in group_history into a transient Message.context, so the beginning of a chat reads the same next turn (cache hits) and the event log, skills and audit see only what was typed. A memory already carried in view isn't carried again; each carry counts a use. - Picks travel with the message: Cmd::Send / POST send / sync act "memories" (empty = none; absent = the brain chooses, once, saved). - remember finds the like one (cos ≥ 0.85 or the same words) and asks for `replaces`; the old one is superseded, never carried. A fact forgotten and remembered again comes back. New search_memory (query, kind), with dates; read-only. - Nightly on the brain, no model: events past 30 days fold into a line per week (「11/3–11/9 做過的事(14 件):整理照片 ×3…」, ≤400 chars, like with like by words or vectors), weeks past 180 days into months; the folded go to 最近刪除 for 30 days. Facts are never removed. The page offers duplicates, facts unused for half a year, and what can fold now. - Local model: minishlab/potion-multilingual-128M through m2v.rs (same token ids as model2vec-rs on 13/13 sentences, cos ≥ 0.9999, without tokenizers' 1.1 GB). Converted while downloading: vocab.bin, table.i8 (int8 + row scales), dims.json, 137 MB kept of 530 MB; ANYBOT_HF_BASE picks a mirror (now passed into the server's brain container too). Loaded when first needed (34 ms), let go after 10 idle minutes. The brain loads it; a screen only with a document folder set; hands and phones never. 設定 › 一般 › 語意搜尋: 本機模型/Ollama/關閉; a new engine clears every vector. - Three files, three connections: memory.db (backed up nightly, 7 kept), docs.db (a cache), oplog/audit.db (30 days). An old audit.db hands its memories and documents over once and shrinks (a real one: 172 MB → 16 KB). docs_search scans every chunk now, vectors cached in RAM (it stopped at 8000); FTS optimize + VACUUM daily (260 MB of tombstones over 31 MB of text). - API: POST /api/memory (owner) and /api/sync/memory (mirror). Reads answer on the HTTP thread; writes go through phone_act("memory"). - Screens: a memory dialog (Bot menu 記憶…, Bot settings 打開記憶) with counts, live search, filters, suggestions, per-item kind/date/uses and pin/edit/forget/restore; chips above the composer 300 ms after typing stops, with a token estimate; 「帶了 N 條記憶」 under person messages. The phone has the same as a 記憶 tab, chips and tag. Checked: make test passes (app 297, relay 16), with new tests for the scores and thresholds, Traditional Chinese segmentation, remember's dedupe and replaces, two turns sending the same beginning, no double carry, weekly/monthly folding and the trash, and the audit.db move. Brain idle 37 MB as before, ~230 MB with the model loaded; search on the brain 0.2–0.5 ms, 7–44 ms from the phone page. A deadlock found on the way (stats re-taking the lock) is fixed and tested. Docs: docs/memory.md has the whole design; FEATURES.md, protocol, architecture (zh/en), multi-device and install say what changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Uirha3SYw9JJ9dXwaNvYh4
2026-11-10 23:46:50 +00:00
Reachable only through the relay (or on the LAN with the phone password). Highlights: `GET /api/state?since=` (bots, activity, pending approvals; long-poll ≤20 s), `GET /api/bots/<id>`, `POST /api/bots/<id>/<action>` (`send`, `stop`, `answer`, `read`, `new`, `upload`…; `send` may carry `"memories": [...]`, the memories ticked above the composer — empty means none, absent means the brain chooses), `POST /api/memory` (owner only) and `POST /api/sync/memory` (mirror) for the memory page and composer suggestions (`{op, bot, …}`; reads `suggest`/`search`/`list`/`stats`/`overview`, writes `add`/`pin`/`edit`/`forget`/`restore`/`merge`/`tidy`/`empty_trash`; see `docs/memory.md`), `GET/POST /api/screen/mac` (drive this Mac from the phone, if enabled), `/screen` + `/api/vnc` (view the bot's computer, noVNC), and the brain-sync family: `GET /api/sync?since=`, `POST /api/sync/edit` (`{ops, client, seq}`), `/api/sync/act`, `/api/sync/upload/<bot>`, `GET /api/sync/file`, `POST /api/sync/models`, `POST/GET /api/sync/screen` (thumbnails; `{kind:"hold"|"wake"}`).
Sending between devices (`src/drops.rs`; owner's phone at `/api/drop/<what>`, the owner's screens at `/api/sync/drop/<what>`): `GET targets` → `{targets: [{id, name, online, kind}], you}`; `GET list` → `{items}` (last 7 days); `POST new` `{name, bytes, to}` or `{text, to}` → `{id, chunk}`; `POST chunk?id=&at=` (raw bytes, 2 MB a piece) → `{have}` (a piece that isn't the next one is not written; the sender continues from `have`); `POST done` `{id}`; `GET file?id=&at=&len=` (phone only: a piece of a file waiting for the phone); `POST remove` / `retry` `{id}`. The brain pushes a parcel to a computer through `/api/device/run` with `tool: "drop_put"` and `args` `{id, name, bytes, from}` plus `{probe: true}` (how much do you have?), `{at, data}` (one base64 piece) or `{text}`; the answer is `{ok, have, done, text}`. A computer accepts `drop_put` only from its own brain, with or without 裝置連結.
## Wire format (`src/wire.rs`)
WebSocket binary frames, each message: `[4-byte big-endian header length][header JSON][raw body]` — bodies are not base64'd; `z: true` means the body is deflate-compressed, `z_ok: true` says the asker understands compressed replies.
| `t` | Direction | Header fields | Meaning |
|---|---|---|---|
| `hello` | AnyBot → relay | `brain`, `hands` | which brain this machine follows; is it hands |
| `job` | relay → AnyBot | `id, method, path, query, user, role, from, z, z_ok` | a request for this machine |
| `reply` | AnyBot → relay | `id, status, ctype, headers, z` | answer to a job |
| `call` | AnyBot → relay | `id, to, method, path, query, z` | ask another host (only `/api/sync…`, `/api/device/run`) |
| `ret` | relay → AnyBot | `id, status, ctype, z, headers` | answer to a call |
| `vopen` / `vdata` / `vtext` / `vclose` | both | `sid`, `why` | VNC session lifecycle: open, bytes, typed text, close |
Both loops poll every 2 ms while busy, 40 ms idle (`wire::Pace`), then flush queued messages; keepalive via WebSocket ping/pong. On disconnect the relay answers pending jobs 503, the AnyBot fails pending calls.
## Sync ops (`/api/sync/edit`)
`set` (one key; `next_*` counters only grow), `patch` (map/list item-level), `merge` (providers/skills/mcp_servers on move), `bot_add` (id collision → new id), `bot_del` (primary bot protected), `bot_set`, `bot_patch` (routines keep the brain's run times), `bot_read`, `bot_order`.
`patch` shapes: `{"value": …}` replaces; `{"map": {"put": {…}, "del": […]}}`; `{"list": {"put": […], "del": [keys], "order": [keys]}}` where keys are item `id`s (or `name`, raw values as-is). Items without id/name, or duplicate keys → send the whole value instead.